Ignore pending and running jobs when building standings
[gruntmaster-data.git] / lib / Gruntmaster / Data.pm
... / ...
CommitLineData
1package Gruntmaster::Data;
2use 5.014;
3use warnings;
4
5use parent qw/Exporter/;
6our $VERSION = '5999.000_016';
7our @EXPORT = qw/dbinit purge db user_list user_entry problem_list problem_entry contest_list contest_entry contest_has_problem job_list job_entry create_job standings update_status rerun_job rerun_problem take_job finish_job open_problem/;
8our @EXPORT_OK = @EXPORT;
9
10use JSON::MaybeXS qw/decode_json/;
11use HTTP::Tiny;
12use PerlX::Maybe qw/maybe/;
13
14use DBI;
15use DBIx::Simple;
16use List::Util qw/sum/;
17use SQL::Abstract;
18
19use constant PROBLEM_PUBLIC_COLUMNS => [qw/id author writer level name owner private timeout olimit value/];
20use constant JOBS_PER_PAGE => 50;
21
22my %statements = (
23 user_list_sth => 'SELECT * FROM user_list LIMIT 200',
24 user_entry_sth => 'SELECT * FROM user_data WHERE id = ?',
25
26 problem_status_sth => 'SELECT problem,solved FROM problem_status WHERE owner = ?',
27 contest_status_sth => 'SELECT contest,score,rank FROM contest_status WHERE owner = ?',
28
29 contest_list_sth => 'SELECT * FROM contest_entry',
30 contest_entry_sth => 'SELECT * FROM contest_entry WHERE id = ?',
31 contest_has_problem_sth => 'SELECT EXISTS(SELECT 1 FROM contest_problems WHERE contest = ? AND problem = ?)',
32 opens_sth => 'SELECT problem,owner,time FROM opens WHERE contest = ?',
33
34 problem_entry_sth => 'SELECT ' . (join ',', @{PROBLEM_PUBLIC_COLUMNS()}, 'statement', 'solution') . ' FROM problems WHERE id = ?',
35 limits_sth => 'SELECT format,timeout FROM limits WHERE problem = ?',
36
37 job_entry_sth => 'SELECT * FROM job_entry WHERE id = ?',
38
39 rerun_problem_sth => 'UPDATE jobs SET daemon=NULL,result=-2,result_text=NULL,results=NULL,errors=NULL WHERE problem = ?',
40 rerun_job_sth => 'UPDATE jobs SET daemon=NULL,result=-2,result_text=NULL,results=NULL,errors=NULL WHERE id = ?',
41 take_job_sth => 'UPDATE jobs SET daemon=? WHERE id = (SELECT id FROM jobs WHERE daemon IS NULL LIMIT 1 FOR UPDATE) RETURNING id',
42);
43
44our $db;
45sub db () { $db }
46
47sub dbinit {
48 $db = DBIx::Simple->new(@_);
49 $db->keep_statements = 100;
50};
51
52sub purge;
53
54sub _query {
55 my ($stat, @extra) = @_;
56 $db->query($statements{$stat}, @extra)
57}
58
59my (%name_cache, %name_cache_time);
60use constant NAME_CACHE_MAX_AGE => 5;
61
62sub _object_name {
63 my ($table, $id) = @_;
64 $name_cache_time{$table} //= 0;
65 if (time - $name_cache_time{$table} > NAME_CACHE_MAX_AGE) {
66 $name_cache_time{$table} = time;
67 $name_cache{$table} = {};
68 $name_cache{$table} = $db->select($table, 'id,name')->map;
69 }
70
71 $name_cache{$table}{$id}
72}
73
74
75sub _add_names ($) { ## no critic (ProhibitSubroutinePrototypes)
76 my ($el) = @_;
77 return unless defined $el;
78 if (ref $el eq 'ARRAY') {
79 &_add_names ($_) for @$el ## no critic (ProhibitAmpersandSigils)
80 } else {
81 for my $object (qw/contest owner problem/) {
82 my $table = $object eq 'owner' ? 'users' : "${object}s";
83 $el->{"${object}_name"} = _object_name $table, $el->{$object} if defined $el->{$object}
84 }
85 }
86
87 $el
88}
89
90sub user_list { scalar _query('user_list_sth')->hashes }
91
92sub user_entry {
93 my ($id) = @_;
94 my $ret = _query('user_entry_sth', $id)->hash;
95 $ret->{problems} = _add_names _query('problem_status_sth', $id)->hashes;
96 $ret->{contests} = _add_names _query('contest_status_sth', $id)->hashes;
97
98 $ret;
99}
100
101sub problem_list {
102 my (%args) = @_;
103 my @columns = @{PROBLEM_PUBLIC_COLUMNS()};
104 push @columns, 'solution' if $args{solution};
105 my %where;
106 $where{private} = 0 unless $args{contest} || $args{private};
107 $where{'cp.contest'} = $args{contest} if $args{contest};
108 $where{owner} = $args{owner} if $args{owner};
109
110 my $table = $args{contest} ? 'problems JOIN contest_problems cp ON cp.problem = id' : 'problems';
111 _add_names $db->select(\$table, \@columns, \%where, 'name')->hashes
112}
113
114sub problem_entry {
115 my ($id, $contest) = @_;
116 $contest = contest_entry ($contest) if $contest;
117 my $ret = _add_names _query(problem_entry_sth => $id)->hash;
118 my $limits = _query(limits_sth => $id)->hashes;
119 $ret->{limits} = $limits if @$limits;
120
121 if ($contest) {
122 $ret->{contest_start} = $contest->{start};
123 $ret->{contest_stop} = $contest->{stop};
124 delete $ret->{solution}
125 }
126
127 $ret
128}
129
130sub contest_list { _add_names _query('contest_list_sth')->hashes }
131
132sub contest_entry { _add_names _query(contest_entry_sth => $_[0])->hash }
133
134sub contest_has_problem { _query('contest_has_problem_sth', @_[0, 1])->flat }
135
136sub job_list {
137 my (%args) = @_;
138 $args{page} = int ($args{page} // 1);
139 my %where = (
140 maybe contest => $args{contest},
141 maybe owner => $args{owner},
142 maybe problem => $args{problem},
143 maybe result => $args{result},
144 );
145 $where{private} = 0 unless $args{private};
146
147 my $rows = $db->select('job_entry', 'COUNT(*)', \%where)->list;
148 my $pages = int (($rows + JOBS_PER_PAGE - 1) / JOBS_PER_PAGE);
149 my ($stmt, @bind) = $db->abstract->select('job_entry', '*', \%where, {-desc => 'id'});
150 my $jobs = _add_names $db->query("$stmt LIMIT " . JOBS_PER_PAGE . ' OFFSET ' . ($args{page} - 1) * JOBS_PER_PAGE, @bind)->hashes;
151 my $pageinfo = {
152 current_page => $args{page},
153 last_page => $pages,
154 ($args{page} - 1) ? (previous_page => $args{page} - 1) : (),
155 ($args{page} < $pages) ? (next_page => $args{page} + 1) : (),
156 };
157 wantarray ? ($jobs, $pageinfo) : $jobs;
158}
159
160sub job_entry {
161 my $ret = _add_names _query(job_entry_sth => $_[0])->hash;
162 $ret->{results} = decode_json $ret->{results} if $ret->{results};
163 $ret
164}
165
166sub create_job {
167 my (%args) = @_;
168 $db->update('users', {lastjob => time}, {id => $args{owner}});
169 purge '/log/';
170 scalar $db->insert('jobs', \%args, {returning => 'id'})->list
171}
172
173sub _calc_score {
174 my ($mxscore, $time, $tries, $totaltime) = @_;
175 my $score = $mxscore;
176 $time = 300 if $time > $totaltime; # uncoverable branch true does not happen anymore (only possible if opens are broken)
177 $score = ($totaltime - $time) / $totaltime * $score;
178 $score -= $tries / 10 * $mxscore;
179 $score = $mxscore * 3 / 10 if $score < $mxscore * 3 / 10;
180 int $score + 0.5
181}
182
183sub standings {
184 my ($ct) = @_;
185 my @problems = sort { $a->{value} <=> $b->{value} } @{problem_list contest => $ct};
186 my %values = map { $_->{id} => $_->{value} } @problems;
187 $ct = contest_entry $ct;
188
189 my (%scores, %tries, %opens);
190 my $opens = _query(opens_sth => $ct->{id});
191 while ($opens->into(my ($problem, $owner, $time))) {
192 $opens{$problem, $owner} = $time;
193 }
194
195 # result IS NULL if job was never run
196 # result = -2 if job is being rerun
197 my %where = (contest => $ct->{id}, result => {'>=', 0});
198 my $jobs = $db->select('job_entry', '*', \%where, 'id');
199
200 while (my $job = $jobs->hash) {
201 my $open = $opens{$job->{problem}, $job->{owner}} // $ct->{start};
202 my $time = $job->{date} - $open;
203 next if $time < 0; # uncoverable branch true job sent before contest is deprecated
204 my $value = $values{$job->{problem}};
205 my $factor = $job->{result} ? 0 : 1;
206 $factor = $1 / 100 if $job->{result_text} =~ /^(\d+ )/s;
207 $scores{$job->{owner}}{$job->{problem}} = int ($factor * _calc_score ($value, $time, $tries{$job->{owner}}{$job->{problem}}++, $ct->{stop} - $ct->{start}));
208 }
209
210 my @st = sort { $b->{score} <=> $a->{score} or $a->{user} cmp $b->{user} } map { ## no critic (ProhibitReverseSortBlock)
211 my $user = $_;
212 +{
213 user => $user,
214 user_name => _object_name(users => $user),
215 score => sum (values %{$scores{$user}}),
216 scores => [map { $scores{$user}{$_->{id}} // '-'} @problems],
217 }
218 } keys %scores;
219
220 $st[0]->{rank} = 1 if @st;
221 $st[$_]->{rank} = $st[$_ - 1]->{rank} + ($st[$_]->{score} < $st[$_ - 1]->{score}) for 1 .. $#st;
222
223 \@st
224}
225
226sub update_status {
227 my $jobs = $db->select('jobs', 'id,owner,problem,result', {-not_bool => 'private'}, 'id');
228
229 my %hash;
230 while ($jobs->into(my ($id, $owner, $problem, $result))) {
231 $hash{$problem, $owner} = [$id, $result ? 0 : 1];
232 }
233
234 my @problem_statuses = map { [split ($;), @{$hash{$_}} ] } keys %hash;
235
236 my @contest_statuses = map {
237 my $ct = $_;
238 map { [$ct, $_->{user}, $_->{score}, $_->{rank}] } @{standings $ct}
239 } $db->select('contests', 'id')->flat;
240
241 $db->begin;
242 $db->delete('problem_status');
243 $db->query('INSERT INTO problem_status (problem,owner,job,solved) VALUES (??)', @$_) for @problem_statuses;
244 $db->delete('contest_status');
245 $db->query('INSERT INTO contest_status (contest,owner,score,rank) VALUES (??)', @$_) for @contest_statuses;
246 $db->commit
247}
248
249sub rerun_problem {
250 my ($problem) = @_;
251 _query rerun_problem_sth => $problem;
252 purge '/log/';
253}
254
255sub rerun_job {
256 my ($id) = @_;
257 _query rerun_job_sth => $id;
258 purge '/log/';
259 purge "/log/$id";
260}
261
262sub take_job {
263 my ($daemon) = @_;
264 my $id = _query(take_job_sth => $daemon)->list;
265 return unless $id;
266 purge '/log/';
267 purge "/log/$id";
268 db->select(jobs => '*', {id => $id})->hash
269}
270
271sub finish_job {
272 my ($job, $private, %args) = @_;
273 db->update(jobs => \%args, {id => $job->{id}});
274 purge '/log/';
275 purge '/log/' . $job->{id};
276 purge '/st/' . $job->{contest} if $job->{contest};
277 return if $private;
278 my $status = {
279 problem => $job->{problem},
280 owner => $job->{owner},
281 job => $job->{id},
282 solved => ($args{result} ? 0 : 1),
283 };
284 eval {
285 db->insert(problem_status => $status)
286 } or db->update(problem_status => $status, {owner => $job->{owner}, problem => $job->{problem}});
287 purge '/us/' . $job->{owner};
288}
289
290sub open_problem {
291 my ($contest, $problem, $owner, $time) = @_;
292 my $ct = contest_entry($contest);
293 return unless $ct->{id} && $time >= $ct->{start} && $time < $ct->{stop}; ## no critic (ProhibitNegativeExpressionsInUnlessAndUntilConditions)
294 eval { db->insert(opens => { ## no critic (RequireCheckingReturnValueOfEval)
295 contest => $contest,
296 problem => $problem,
297 owner => $owner,
298 time => $time}) };
299}
300
301my @PURGE_HOSTS = exists $ENV{PURGE_HOSTS} ? split ' ', $ENV{PURGE_HOSTS} : ();
302my $ht = HTTP::Tiny->new;
303
304sub purge {
305 $ht->request(PURGE => "http://$_$_[0]") for @PURGE_HOSTS;
306}
307
3081;
309
310__END__
311
312=encoding utf-8
313
314=head1 NAME
315
316Gruntmaster::Data - Gruntmaster 6000 Online Judge -- database interface and tools
317
318=head1 SYNOPSIS
319
320
321=head1 DESCRIPTION
322
323Gruntmaster::Data is the interface to the Gruntmaster 6000 database.
324
325All functions are exported by default.
326
327=over
328
329=item B<dbinit>(I<@args>)
330
331This function connects to the database. I<@args> are the arguments
332passed to the L<DBIx::Simple> constructor.
333
334=item B<purge>(I<$url_path>)
335
336Purges a relative URL from the Varnish Cache by sending PURGE
337$url_path requests to all hosts in the PURGE_HOSTS environment
338variable.
339
340=item B<db>
341
342Returns a L<DBIx::Simple> object for interacting with the database
343directly. Use this when no other function in this module is suitable.
344
345=item B<user_list>
346
347Returns an arrayref of the top 200 users.
348
349=item B<user_entry>(I<$id>)
350
351Returns a hashref describing the user I<$id>.
352
353=item B<problem_list>([I<%args>])
354
355Returns an arrayref of problems.
356
357Takes the following named arguments:
358
359=over
360
361=item owner
362
363Only show problems owned by this user
364
365=item contest
366
367Only show problems in this contest
368
369=item private
370
371If true, include private problems. Always true if contest is present.
372
373=item solution
374
375If true, include problem solutions
376
377=back
378
379=item B<problem_entry>(i<$id>, [I<$contest>])
380
381Returns a hashref describing the problem I<$id>. If $contest is
382present, contest start and stop times are included, and the solution
383is deleted.
384
385=item B<contest_list>
386
387Returns an arrayref of contests.
388
389=item B<contest_entry>(I<$id>)
390
391Returns a hashref describing the contest I<$id>.
392
393=item B<contest_has_problem>(I<$contest>, I<$problem>)
394
395Returns true if the contest I<$contest> includes the problem
396I<$problem>, false otherwise.
397
398=item B<job_list>([I<%args>])
399
400In scalar context, returns an arrayref of jobs. In list context,
401returns an arrayref of jobs and a hashref of information about pages.
402
403Takes the following named arguments:
404
405=over
406
407=item page
408
409Show this page of the job log. Defaults to 1.
410
411=item owner
412
413Only show jobs submitted by this user.
414
415=item contest
416
417Only show jobs submitted in this contest.
418
419=item problem
420
421Only show jobs submitted for this problem.
422
423=item result
424
425Only show jobs with this result (see the constants in
426L<Gruntmaster::Daemon::Constants>).
427
428=item private
429
430If true, include private jobs. Defaults to false.
431
432=back
433
434=item B<job_entry>(I<$id>)
435
436Returns a hashref describing the job I<$id>.
437
438=item B<create_job>(I<%args>)
439
440Insert a new job into the database. This function also updates the
441lastjob field for the job's owner.
442
443=item B<standings>(I<$ct>)
444
445Returns an arrayref of the standings of contest I<$ct>.
446
447=item B<update_status>
448
449Rebuilds the problem_status and contest_status tables.
450
451=item B<rerun_job>(I<$id>)
452
453Marks the job $id as pending and clears its results, so that it will
454be run again by the daemon.
455
456=item B<take_job>(I<$daemon>)
457
458Marks a random job as being run by I<$daemon>. Returns a hashref
459describing the job, or undef if no job was available.
460
461=item B<finish_job>(I<$job>, I<$private>, I<%results>)
462
463Updates the job $job with the results in %results. If $private is
464false, also updates the problem_status table.
465
466=item B<open_problem>(I<$contest>, I<$problem>, I<$owner>, I<$time>)
467
468Notes that I<$owner> has opened the problem I<$problem> of contest
469I<$contest> at time I<$time>. If the C<opens> table already contains
470this (I<$contest>, I<$problem>, I<$owner>) triplet, this function does
471nothing.
472
473=back
474
475=head1 AUTHOR
476
477Marius Gavrilescu E<lt>marius@ieval.roE<gt>
478
479=head1 COPYRIGHT AND LICENSE
480
481Copyright (C) 2014-2016 by Marius Gavrilescu
482
483This library is free software; you can redistribute it and/or modify
484it under the same terms as Perl itself, either Perl version 5.20.1 or,
485at your option, any later version of Perl 5 you may have available.
486
487
488=cut
This page took 0.011066 seconds and 4 git commands to generate.