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