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