Remove _full methods
[gruntmaster-data.git] / lib / Gruntmaster / Data.pm
CommitLineData
bbf8209c 1package Gruntmaster::Data;
6c0423f4 2use 5.014;
bbf8209c 3use warnings;
014ee8a6 4
edfc5928 5use parent qw/Exporter/;
9e130d3b 6our $VERSION = '5999.000_013';
cab36bc4 7our @EXPORT = qw/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 take_job finish_job/; ## no critic (ProhibitAutomaticExportation)
4ed3f8e7 8
91203bd5 9use JSON::MaybeXS qw/decode_json/;
edfc5928 10use HTTP::Tiny;
3473324b 11use PerlX::Maybe qw/maybe/;
52172a1a
MG
12
13use DBI;
14use DBIx::Simple;
15use List::Util qw/sum/;
16use SQL::Abstract;
014ee8a6 17
e890b3ae 18use constant PROBLEM_PUBLIC_COLUMNS => [qw/id author writer level name owner private timeout olimit value/];
e1250e20 19use constant JOBS_PER_PAGE => 50;
de625c9b 20
52172a1a
MG
21my %statements = (
22 user_list_sth => 'SELECT * FROM user_list LIMIT 200',
23 user_entry_sth => 'SELECT * FROM user_data WHERE id = ?',
24
25 problem_status_sth => 'SELECT problem,solved FROM problem_status WHERE owner = ?',
26 contest_status_sth => 'SELECT contest,score,rank FROM contest_status WHERE owner = ?',
27
28 contest_list_sth => 'SELECT * FROM contest_entry',
29 contest_entry_sth => 'SELECT * FROM contest_entry WHERE id = ?',
52172a1a
MG
30 contest_problems_sth => 'SELECT problem FROM contest_problems JOIN problems pb ON problem=pb.id WHERE contest = ? ORDER BY pb.value',
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 problem_values_sth => 'SELECT id,value FROM problems',
37
38 job_entry_sth => 'SELECT * FROM job_entry WHERE id = ?',
341fb893
MG
39
40 rerun_job_sth => 'UPDATE jobs SET daemon=NULL,result=-2,result_text=NULL,results=NULL,errors=NULL WHERE id = ?',
9dc335bd 41 take_job_sth => 'UPDATE jobs SET daemon=? WHERE id = (SELECT id FROM jobs WHERE daemon IS NULL LIMIT 1 FOR UPDATE) RETURNING id',
52172a1a
MG
42);
43
50b165c3 44our $db;
341fb893 45sub db () { $db }
23aa7eca 46
62a58bf3
MG
47sub init {
48 $db = DBIx::Simple->new(@_);
49 $db->keep_statements = 100;
52172a1a
MG
50};
51
52sub purge;
53
54sub query {
62a58bf3 55 my ($stat, @extra) = @_;
4623c9f2 56 $db->query($statements{$stat}, @extra)
52172a1a
MG
57}
58
59my (%name_cache, %name_cache_time);
60use constant NAME_CACHE_MAX_AGE => 5;
61
62sub object_name {
62a58bf3 63 my ($table, $id) = @_;
52172a1a
MG
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} = {};
62a58bf3 68 $name_cache{$table} = $db->select($table, 'id,name')->map;
52172a1a
MG
69 }
70
71 $name_cache{$table}{$id}
72}
73
74
6c0423f4 75sub add_names ($) { ## no critic (ProhibitSubroutinePrototypes)
62a58bf3 76 my ($el) = @_;
ee00be0c 77 return unless defined $el;
52172a1a 78 if (ref $el eq 'ARRAY') {
6c0423f4 79 &add_names ($_) for @$el ## no critic (ProhibitAmpersandSigils)
52172a1a
MG
80 } else {
81 for my $object (qw/contest owner problem/) {
82 my $table = $object eq 'owner' ? 'users' : "${object}s";
62a58bf3 83 $el->{"${object}_name"} = object_name $table, $el->{$object} if defined $el->{$object}
52172a1a
MG
84 }
85 }
86
87 $el
88}
89
b69781c1 90sub user_list { scalar query('user_list_sth')->hashes }
52172a1a
MG
91
92sub user_entry {
62a58bf3
MG
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;
52172a1a 97
52172a1a
MG
98 $ret;
99}
100
52172a1a 101sub problem_list {
62a58bf3 102 my (%args) = @_;
52172a1a
MG
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';
b69781c1 111 add_names $db->select(\$table, \@columns, \%where, 'name')->hashes
52172a1a
MG
112}
113
52172a1a 114sub problem_entry {
a1a4325a 115 my ($id, $contest) = @_;
4623c9f2 116 $contest = contest_entry ($contest) if $contest;
62a58bf3
MG
117 my $ret = add_names query(problem_entry_sth => $id)->hash;
118 my $limits = query(limits_sth => $id)->hashes;
52172a1a
MG
119 $ret->{limits} = $limits if @$limits;
120
121 if ($contest) {
122 $ret->{contest_start} = $contest->{start};
123 $ret->{contest_stop} = $contest->{stop};
d33e87f2 124 delete $ret->{solution}
52172a1a
MG
125 }
126
127 $ret
128}
129
b69781c1 130sub contest_list { add_names query('contest_list_sth')->hashes }
52172a1a 131
b69781c1 132sub contest_entry { add_names query(contest_entry_sth => $_[0])->hash }
52172a1a 133
b69781c1 134sub contest_has_problem { query('contest_has_problem_sth', @_[0, 1])->flat }
52172a1a 135
52172a1a 136sub job_list {
62a58bf3 137 my (%args) = @_;
b69781c1 138 $args{page} = int ($args{page} // 1);
52172a1a
MG
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
62a58bf3 147 my $rows = $db->select('job_entry', 'COUNT(*)', \%where)->list;
52172a1a 148 my $pages = int (($rows + JOBS_PER_PAGE - 1) / JOBS_PER_PAGE);
62a58bf3 149 my ($stmt, @bind) = $db->abstract->select('job_entry', '*', \%where, {-desc => 'id'});
b69781c1
MG
150 my $jobs = add_names $db->query("$stmt LIMIT " . JOBS_PER_PAGE . ' OFFSET ' . ($args{page} - 1) * JOBS_PER_PAGE, @bind)->hashes;
151 my $pageinfo = {
52172a1a
MG
152 current_page => $args{page},
153 last_page => $pages,
b69781c1
MG
154 ($args{page} - 1) ? (previous_page => $args{page} - 1) : (),
155 ($args{page} < $pages) ? (next_page => $args{page} + 1) : (),
156 };
157 wantarray ? ($jobs, $pageinfo) : $jobs;
52172a1a
MG
158}
159
160sub job_entry {
b69781c1 161 my $ret = add_names query(job_entry_sth => $_[0])->hash;
4623c9f2 162 $ret->{results} = decode_json $ret->{results} if $ret->{results};
62a58bf3 163 $ret
52172a1a
MG
164}
165
52172a1a 166sub create_job {
62a58bf3 167 my (%args) = @_;
5e77eeae 168 $db->update('users', {lastjob => time}, {id => $args{owner}});
52172a1a 169 purge '/log/';
62a58bf3 170 scalar $db->insert('jobs', \%args, {returning => 'id'})->list
52172a1a
MG
171}
172
173sub calc_score {
174 my ($mxscore, $time, $tries, $totaltime) = @_;
175 my $score = $mxscore;
4623c9f2 176 $time = 300 if $time > $totaltime; # uncoverable branch true does not happen anymore (only possible if opens are broken)
52172a1a
MG
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 {
62a58bf3
MG
184 my ($ct) = @_;
185 $ct = contest_entry $ct;
52172a1a 186
62a58bf3
MG
187 my @problems = query(contest_problems_sth => $ct->{id})->flat;
188 my $pblist = problem_list;
189 my %values = query('problem_values_sth')->map;
52172a1a
MG
190
191 my (%scores, %tries, %opens);
62a58bf3 192 my $opens = query(opens_sth => $ct->{id});
52172a1a
MG
193 while ($opens->into(my ($problem, $owner, $time))) {
194 $opens{$problem, $owner} = $time;
195 }
196
62a58bf3 197 my $jobs = $db->select('job_entry', '*', {contest => $ct->{id}}, 'id');
52172a1a
MG
198
199 while (my $job = $jobs->hash) {
200 my $open = $opens{$job->{problem}, $job->{owner}} // $ct->{start};
201 my $time = $job->{date} - $open;
4623c9f2 202 next if $time < 0; # uncoverable branch true job sent before contest is deprecated
52172a1a
MG
203 my $value = $values{$job->{problem}};
204 my $factor = $job->{result} ? 0 : 1;
205 $factor = $1 / 100 if $job->{result_text} =~ /^(\d+ )/s;
206 $scores{$job->{owner}}{$job->{problem}} = int ($factor * calc_score ($value, $time, $tries{$job->{owner}}{$job->{problem}}++, $ct->{stop} - $ct->{start}));
207 }
208
209 my @st = sort { $b->{score} <=> $a->{score} or $a->{user} cmp $b->{user} } map { ## no critic (ProhibitReverseSortBlock)
210 my $user = $_;
211 +{
212 user => $user,
62a58bf3 213 user_name => object_name(users => $user),
52172a1a
MG
214 score => sum (values %{$scores{$user}}),
215 scores => [map { $scores{$user}{$_} // '-'} @problems],
216 }
217 } keys %scores;
218
219 $st[0]->{rank} = 1 if @st;
220 $st[$_]->{rank} = $st[$_ - 1]->{rank} + ($st[$_]->{score} < $st[$_ - 1]->{score}) for 1 .. $#st;
221 +{
222 st => \@st,
62a58bf3 223 problems => [map { [ $_, object_name(problems => $_)] } @problems],
52172a1a
MG
224 }
225}
226
52172a1a 227sub update_status {
1761e170 228 my $jobs = $db->select('jobs', 'id,owner,problem,result', {-not_bool => 'private'}, 'id');
52172a1a
MG
229
230 my %hash;
231 while ($jobs->into(my ($id, $owner, $problem, $result))) {
232 $hash{$problem, $owner} = [$id, $result ? 0 : 1];
233 }
234
235 my @problem_statuses = map { [split ($;), @{$hash{$_}} ] } keys %hash;
236
237 my @contest_statuses = map {
238 my $ct = $_;
62a58bf3
MG
239 map { [$ct, $_->{user}, $_->{score}, $_->{rank}] } @{standings($ct)->{st}}
240 } $db->select('contests', 'id')->flat;
241
242 $db->begin;
243 $db->delete('problem_status');
244 $db->query('INSERT INTO problem_status (problem,owner,job,solved) VALUES (??)', @$_) for @problem_statuses;
245 $db->delete('contest_status');
246 $db->query('INSERT INTO contest_status (contest,owner,score,rank) VALUES (??)', @$_) for @contest_statuses;
247 $db->commit
52172a1a
MG
248}
249
341fb893
MG
250sub rerun_job {
251 my ($id) = @_;
686bacca 252 query rerun_job_sth => $id;
341fb893
MG
253 purge '/log/';
254 purge "/log/$id";
255}
256
9dc335bd
MG
257sub take_job {
258 my ($daemon) = @_;
259 my $id = query(take_job_sth => $daemon)->list;
cab36bc4 260 return $id ? db->select(jobs => '*', {id => $id})->hash : undef;
9dc335bd
MG
261}
262
263sub finish_job {
264 my ($job, $private, %args) = @_;
265 db->update(jobs => \%args, {id => $job->{id}});
266 return if $private;
267 my $status = {
268 problem => $job->{problem},
269 owner => $job->{owner},
270 job => $job->{id},
271 solved => ($args{result} ? 0 : 1),
272 };
273 eval {
274 db->insert(problem_status => $status)
275 } or db->update(problem_status => $status, {owner => $job->{owner}, problem => $job->{problem}});
276}
277
edfc5928
MG
278my @PURGE_HOSTS = exists $ENV{PURGE_HOSTS} ? split ' ', $ENV{PURGE_HOSTS} : ();
279my $ht = HTTP::Tiny->new;
280
de7226ca
MG
281sub purge {
282 $ht->request(PURGE => "http://$_$_[0]") for @PURGE_HOSTS;
283}
edfc5928 284
f7386aab 2851;
4a8747ef
MG
286
287__END__
288
289=encoding utf-8
290
291=head1 NAME
292
293Gruntmaster::Data - Gruntmaster 6000 Online Judge -- database interface and tools
294
295=head1 SYNOPSIS
296
297 my $db = Gruntmaster::Data->connect('dbi:Pg:');
cbb36c78
MG
298
299 my $problem = $db->problem('my_problem');
300 $problem->update({timeout => 2.5}); # Set time limit to 2.5 seconds
301 $problem->rerun; # And rerun all jobs for this problem
302
303 # ...
304
305 my $contest = $db->contests->create({ # Create a new contest
306 id => 'my_contest',
307 name => 'My Awesome Contest',
308 start => time + 100,
309 end => time + 1900,
310 });
311 $db->contest_problems->create({ # Add a problem to the contest
312 contest => 'my_contest',
313 problem => 'my_problem',
314 });
315
316 say 'The contest has not started yet' if $contest->is_pending;
317
318 # ...
319
320 my @jobs = $db->jobs->search({contest => 'my_contest', owner => 'MGV'})->all;
321 $_->rerun for @jobs; # Rerun all jobs sent by MGV in my_contest
4a8747ef
MG
322
323=head1 DESCRIPTION
324
cbb36c78
MG
325Gruntmaster::Data is the interface to the Gruntmaster 6000 database. Read the L<DBIx::Class> documentation for usage information.
326
327In addition to the typical DBIx::Class::Schema methods, this module contains several convenience methods:
328
329=over
330
331=item contests
332
333Equivalent to C<< $schema->resultset('Contest') >>
334
335=item contest_problems
336
337Equivalent to C<< $schema->resultset('ContestProblem') >>
338
339=item jobs
340
341Equivalent to C<< $schema->resultset('Job') >>
342
343=item problems
344
345Equivalent to C<< $schema->resultset('Problem') >>
346
347=item users
348
349Equivalent to C<< $schema->resultset('User') >>
350
351=item contest($id)
352
353Equivalent to C<< $schema->resultset('Contest')->find($id) >>
354
355=item job($id)
356
357Equivalent to C<< $schema->resultset('Job')->find($id) >>
358
359=item problem($id)
360
361Equivalent to C<< $schema->resultset('Problem')->find($id) >>
362
363=item user($id)
364
365Equivalent to C<< $schema->resultset('User')->find($id) >>
366
de625c9b
MG
367=item user_list
368
369Returns a list of users as an arrayref containing hashrefs.
370
371=item user_entry($id)
372
373Returns a hashref with information about the user $id.
374
375=item problem_list([%args])
376
377Returns a list of problems grouped by level. A hashref with levels as keys.
378
379Takes the following arguments:
380
381=over
382
383=item owner
384
385Only show problems owned by this user
386
387=item contest
388
389Only show problems in this contest
390
391=back
392
393=item problem_entry($id, [$contest, $user])
394
395Returns a hashref with information about the problem $id. If $contest and $user are present, problem open data is updated.
396
397=item contest_list([%args])
398
399Returns a list of contests grouped by state. A hashref with the following keys:
400
401=over
402
403=item pending
404
405An arrayref of hashrefs representing pending contests
406
407=item running
408
409An arrayref of hashrefs representing running contests
410
411=item finished
412
413An arrayref of hashrefs representing finished contests
414
415=back
416
417Takes the following arguments:
418
419=over
420
421=item owner
422
423Only show contests owned by this user.
424
425=back
426
427=item contest_entry($id)
428
429Returns a hashref with information about the contest $id.
430
431=item job_list([%args])
432
433Returns a list of jobs as an arrayref containing hashrefs. Takes the following arguments:
434
435=over
436
437=item owner
438
439Only show jobs submitted by this user.
440
441=item contest
442
443Only show jobs submitted in this contest.
444
445=item problem
446
447Only show jobs submitted for this problem.
448
449=item page
450
451Show this page of results. Defaults to 1. Pages have 10 entries, and the first page has the most recent jobs.
452
453=back
454
455=item job_entry($id)
456
457Returns a hashref with information about the job $id.
458
cbb36c78 459=back
4a8747ef
MG
460
461=head1 AUTHOR
462
463Marius Gavrilescu E<lt>marius@ieval.roE<gt>
464
465=head1 COPYRIGHT AND LICENSE
466
467Copyright (C) 2014 by Marius Gavrilescu
468
9d2e740e
MG
469This library is free software; you can redistribute it and/or modify
470it under the same terms as Perl itself, either Perl version 5.18.1 or,
471at your option, any later version of Perl 5 you may have available.
4a8747ef
MG
472
473
474=cut
This page took 0.052108 seconds and 4 git commands to generate.