File Coverage

blib/lib/Gruntmaster/Data.pm
Criterion Covered Total %
statement 39 183 21.3
branch 0 62 3.2
condition 0 18 0.0
subroutine 14 36 38.8
pod 19 19 100.0
total 72 318 23.2


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