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