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