File Coverage

blib/lib/Gruntmaster/Data.pm
Criterion Covered Total %
statement 39 189 20.6
branch 0 64 3.1
condition 0 18 0.0
subroutine 14 37 37.8
pod 19 20 95.0
total 72 328 22.5


line stmt bran cond sub pod time code
1             package Gruntmaster::Data;
2 4     4   68592 use 5.014;
  4         23  
3 4     4   32 use warnings;
  4         17  
  4         135  
4              
5 4     4   915 use parent qw/Exporter/;
  4         965  
  4         21  
6             our $VERSION = '6000.001';
7             our @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/;
8             our @EXPORT_OK = @EXPORT;
9              
10 4     4   2199 use JSON::MaybeXS qw/decode_json/;
  4         29177  
  4         227  
11 4     4   2740 use HTTP::Tiny;
  4         198594  
  4         185  
12 4     4   1775 use PerlX::Maybe qw/maybe/;
  4         6079  
  4         210  
13              
14 4     4   6071 use DBI;
  4         70661  
  4         231  
15 4     4   2197 use DBIx::Simple;
  4         21874  
  4         149  
16 4     4   31 use List::Util qw/sum/;
  4         8  
  4         396  
17 4     4   3025 use SQL::Abstract;
  4         45819  
  4         245  
18              
19 4     4   32 use constant PROBLEM_PUBLIC_COLUMNS => [qw/id author writer level name owner private timeout olimit value/];
  4         9  
  4         289  
20 4     4   25 use constant JOBS_PER_PAGE => 50;
  4         9  
  4         954  
21              
22             my %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 = ?',
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 = ?',
36              
37             job_entry_sth => 'SELECT * FROM job_entry WHERE id = ?',
38              
39             rerun_problem_sth => 'UPDATE jobs SET daemon=NULL,result=-2,result_text=NULL,results=NULL,errors=NULL WHERE problem = ?',
40             rerun_job_sth => 'UPDATE jobs SET daemon=NULL,result=-2,result_text=NULL,results=NULL,errors=NULL WHERE id = ?',
41             take_job_sth => 'UPDATE jobs SET daemon=? WHERE id = (SELECT id FROM jobs WHERE daemon IS NULL LIMIT 1 FOR UPDATE) RETURNING id',
42             );
43              
44             our $db;
45 0     0 1 0 sub db () { $db }
46              
47             sub dbinit {
48 2     2 1 77144 $db = DBIx::Simple->new(@_);
49 0           $db->keep_statements = 100;
50 0           $db->dbh->do('SET search_path TO gruntmaster, public');
51             };
52              
53             sub purge;
54              
55             sub _query {
56 0     0     my ($stat, @extra) = @_;
57 0           $db->query($statements{$stat}, @extra)
58             }
59              
60             my (%name_cache, %name_cache_time);
61 4     4   33 use constant NAME_CACHE_MAX_AGE => 5;
  4         10  
  4         10024  
62              
63             sub _object_name {
64 0     0     my ($table, $id) = @_;
65 0   0       $name_cache_time{$table} //= 0;
66 0 0         if (time - $name_cache_time{$table} > NAME_CACHE_MAX_AGE) {
67 0           $name_cache_time{$table} = time;
68 0           $name_cache{$table} = {};
69 0           $name_cache{$table} = $db->select($table, 'id,name')->map;
70             }
71              
72 0           $name_cache{$table}{$id}
73             }
74              
75              
76             sub _add_names ($) { ## no critic (ProhibitSubroutinePrototypes)
77 0     0     my ($el) = @_;
78 0 0         return unless defined $el;
79 0 0         if (ref $el eq 'ARRAY') {
80 0           &_add_names ($_) for @$el ## no critic (ProhibitAmpersandSigils)
81             } else {
82 0           for my $object (qw/contest owner problem/) {
83 0 0         my $table = $object eq 'owner' ? 'users' : "${object}s";
84 0 0         $el->{"${object}_name"} = _object_name $table, $el->{$object} if defined $el->{$object}
85             }
86             }
87              
88 0           $el
89             }
90              
91 0     0 1   sub user_list { scalar _query('user_list_sth')->hashes }
92              
93             sub user_entry {
94 0     0 1   my ($id) = @_;
95 0           my $ret = _query('user_entry_sth', $id)->hash;
96 0           $ret->{problems} = _add_names _query('problem_status_sth', $id)->hashes;
97 0           $ret->{contests} = _add_names _query('contest_status_sth', $id)->hashes;
98              
99 0           $ret;
100             }
101              
102             sub problem_list {
103 0     0 1   my (%args) = @_;
104 0           my @columns = @{PROBLEM_PUBLIC_COLUMNS()};
  0            
105 0 0         push @columns, 'solution' if $args{solution};
106 0           my %where;
107 0 0 0       $where{private} = 0 unless $args{contest} || $args{private};
108 0 0         $where{'cp.contest'} = $args{contest} if $args{contest};
109 0 0         $where{owner} = $args{owner} if $args{owner};
110              
111 0 0         my $table = $args{contest} ? 'problems JOIN contest_problems cp ON cp.problem = id' : 'problems';
112 0           _add_names $db->select(\$table, \@columns, \%where, 'name')->hashes
113             }
114              
115             sub problem_entry {
116 0     0 1   my ($id, $contest) = @_;
117 0 0         $contest = contest_entry ($contest) if $contest;
118 0           my $ret = _add_names _query(problem_entry_sth => $id)->hash;
119 0           my $limits = _query(limits_sth => $id)->hashes;
120 0 0         $ret->{limits} = $limits if @$limits;
121              
122 0 0         if ($contest) {
123 0           $ret->{contest_start} = $contest->{start};
124 0           $ret->{contest_stop} = $contest->{stop};
125             delete $ret->{solution}
126 0           }
127              
128             $ret
129 0           }
130              
131 0     0 1   sub contest_list { _add_names _query('contest_list_sth')->hashes }
132              
133 0     0 1   sub contest_entry { _add_names _query(contest_entry_sth => $_[0])->hash }
134              
135 0     0 1   sub contest_has_problem { _query('contest_has_problem_sth', @_[0, 1])->flat }
136              
137             sub job_list {
138 0     0 1   my (%args) = @_;
139 0   0       $args{page} = int ($args{page} // 1);
140             my %where = (
141             maybe contest => $args{contest},
142             maybe owner => $args{owner},
143             maybe problem => $args{problem},
144             maybe result => $args{result},
145 0           );
146 0 0         $where{private} = 0 unless $args{private};
147              
148 0           my $rows = $db->select('job_entry', 'COUNT(*)', \%where)->list;
149 0           my $pages = int (($rows + JOBS_PER_PAGE - 1) / JOBS_PER_PAGE);
150 0           my ($stmt, @bind) = $db->abstract->select('job_entry', '*', \%where, {-desc => 'id'});
151 0           my $jobs = _add_names $db->query("$stmt LIMIT " . JOBS_PER_PAGE . ' OFFSET ' . ($args{page} - 1) * JOBS_PER_PAGE, @bind)->hashes;
152             my $pageinfo = {
153             current_page => $args{page},
154             last_page => $pages,
155             ($args{page} - 1) ? (previous_page => $args{page} - 1) : (),
156 0 0         ($args{page} < $pages) ? (next_page => $args{page} + 1) : (),
    0          
157             };
158 0 0         wantarray ? ($jobs, $pageinfo) : $jobs;
159             }
160              
161             sub job_entry {
162 0     0 1   my $ret = _add_names _query(job_entry_sth => $_[0])->hash;
163 0 0         $ret->{results} = decode_json $ret->{results} if $ret->{results};
164 0           $ret
165             }
166              
167             sub create_job {
168 0     0 1   my (%args) = @_;
169 0           $db->update('users', {lastjob => time}, {id => $args{owner}});
170 0           purge '/log/';
171 0           scalar $db->insert('jobs', \%args, {returning => 'id'})->list
172             }
173              
174             sub _calc_score {
175 0     0     my ($mxscore, $time, $tries, $totaltime) = @_;
176 0           my $score = $mxscore;
177 0 0         $time = 300 if $time > $totaltime; # uncoverable branch true does not happen anymore (only possible if opens are broken)
178 0           $score = ($totaltime - $time) / $totaltime * $score;
179 0           $score -= $tries / 10 * $mxscore;
180 0 0         $score = $mxscore * 3 / 10 if $score < $mxscore * 3 / 10;
181 0           int $score + 0.5
182             }
183              
184             sub standings {
185 0     0 1   my ($ct) = @_;
186 0           my @problems = sort { $a->{value} <=> $b->{value} } @{problem_list contest => $ct};
  0            
  0            
187 0           my %values = map { $_->{id} => $_->{value} } @problems;
  0            
188 0           $ct = contest_entry $ct;
189              
190 0           my (%scores, %tries, %opens);
191 0           my $opens = _query(opens_sth => $ct->{id});
192 0           while ($opens->into(my ($problem, $owner, $time))) {
193 0           $opens{$problem, $owner} = $time;
194             }
195              
196             # result IS NULL if job was never run
197             # result = -2 if job is being rerun
198 0           my %where = (contest => $ct->{id}, result => {'>=', 0});
199 0           my $jobs = $db->select('job_entry', '*', \%where, 'id');
200              
201 0           while (my $job = $jobs->hash) {
202 0   0       my $open = $opens{$job->{problem}, $job->{owner}} // $ct->{start};
203 0           my $time = $job->{date} - $open;
204 0 0         next if $time < 0; # uncoverable branch true job sent before contest is deprecated
205 0           my $value = $values{$job->{problem}};
206 0 0         my $factor = $job->{result} ? 0 : 1;
207 0 0         $factor = $1 / 100 if $job->{result_text} =~ /^(\d+ )/s;
208 0           $scores{$job->{owner}}{$job->{problem}} = int ($factor * _calc_score ($value, $time, $tries{$job->{owner}}{$job->{problem}}++, $ct->{stop} - $ct->{start}));
209             }
210              
211 0 0         my @st = sort { $b->{score} <=> $a->{score} or $a->{user} cmp $b->{user} } map { ## no critic (ProhibitReverseSortBlock)
212 0           my $user = $_;
  0            
213             +{
214             user => $user,
215             user_name => _object_name(users => $user),
216 0           score => sum (values %{$scores{$user}}),
217 0   0       scores => [map { $scores{$user}{$_->{id}} // '-'} @problems],
  0            
218             }
219             } keys %scores;
220              
221 0 0         $st[0]->{rank} = 1 if @st;
222 0           $st[$_]->{rank} = $st[$_ - 1]->{rank} + ($st[$_]->{score} < $st[$_ - 1]->{score}) for 1 .. $#st;
223              
224             \@st
225 0           }
226              
227             sub update_status {
228 0     0 1   my $jobs = $db->select('jobs', 'id,owner,problem,result', {-not_bool => 'private'}, 'id');
229              
230 0           my %hash;
231 0           while ($jobs->into(my ($id, $owner, $problem, $result))) {
232 0 0         $hash{$problem, $owner} = [$id, $result ? 0 : 1];
233             }
234              
235 0           my @problem_statuses = map { [split ($;), @{$hash{$_}} ] } keys %hash;
  0            
  0            
236              
237             my @contest_statuses = map {
238 0           my $ct = $_;
  0            
239 0           map { [$ct, $_->{user}, $_->{score}, $_->{rank}] } @{standings $ct}
  0            
  0            
240             } $db->select('contests', 'id')->flat;
241              
242 0           $db->begin;
243 0           $db->delete('problem_status');
244 0           $db->query('INSERT INTO problem_status (problem,owner,job,solved) VALUES (??)', @$_) for @problem_statuses;
245 0           $db->delete('contest_status');
246 0           $db->query('INSERT INTO contest_status (contest,owner,score,rank) VALUES (??)', @$_) for @contest_statuses;
247 0           $db->commit
248             }
249              
250             sub rerun_problem {
251 0     0 0   my ($problem) = @_;
252 0           _query rerun_problem_sth => $problem;
253 0           purge '/log/';
254             }
255              
256             sub rerun_job {
257 0     0 1   my ($id) = @_;
258 0           _query rerun_job_sth => $id;
259 0           purge '/log/';
260 0           purge "/log/$id";
261             }
262              
263             sub take_job {
264 0     0 1   my ($daemon) = @_;
265 0           my $id = _query(take_job_sth => $daemon)->list;
266 0 0         return unless $id;
267 0           purge '/log/';
268 0           purge "/log/$id";
269 0           db->select(jobs => '*', {id => $id})->hash
270             }
271              
272             sub finish_job {
273 0     0 1   my ($job, $private, %args) = @_;
274 0           db->update(jobs => \%args, {id => $job->{id}});
275 0           purge '/log/';
276 0           purge '/log/' . $job->{id};
277 0 0         purge '/st/' . $job->{contest} if $job->{contest};
278 0 0         return if $private;
279             my $status = {
280             problem => $job->{problem},
281             owner => $job->{owner},
282             job => $job->{id},
283 0 0         solved => ($args{result} ? 0 : 1),
284             };
285             eval {
286 0           db->insert(problem_status => $status)
287 0 0         } or db->update(problem_status => $status, {owner => $job->{owner}, problem => $job->{problem}});
288 0           purge '/us/' . $job->{owner};
289             }
290              
291             sub open_problem {
292 0     0 1   my ($contest, $problem, $owner, $time) = @_;
293 0           my $ct = contest_entry($contest);
294 0 0 0       return unless $ct->{id} && $time >= $ct->{start} && $time < $ct->{stop}; ## no critic (ProhibitNegativeExpressionsInUnlessAndUntilConditions)
      0        
295 0           eval { db->insert(opens => { ## no critic (RequireCheckingReturnValueOfEval)
  0            
296             contest => $contest,
297             problem => $problem,
298             owner => $owner,
299             time => $time}) };
300             }
301              
302             my @PURGE_HOSTS = exists $ENV{PURGE_HOSTS} ? split ' ', $ENV{PURGE_HOSTS} : ();
303             my $ht = HTTP::Tiny->new;
304              
305             sub purge {
306 0     0 1   $ht->request(PURGE => "http://$_$_[0]") for @PURGE_HOSTS;
307             }
308              
309             1;
310              
311             __END__