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