JobScheduler.pm

filter: Statementstmt 91.2% 188 / 206 Branchbran 75.0% 51 / 68 Conditioncond 61.1% 11 / 18 MC/DCmcdc 33.3% 3 / 9 Subroutinesub 95.6% 22 / 23 Podpod 100% 3 / 3 totaltotal 85.0% 278 / 327 CC 47 SCAR 21.1
CC
47
Cov
86%
list_jobs
15.6
insert
14.2
funcname_to_id
7.0
CRAP 8.3
↑ Summary JobScheduler/Job.pm »
1 package TheSchwartz::JobScheduler;
2 ## no critic (ControlStructures::ProhibitPostfixControls)
3 ## no critic (Subroutines::RequireArgUnpacking)
4 ## no critic (ControlStructures::ProhibitUnlessBlocks)
5  
6 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # ABSTRACT: Lightweight TheSchwartz job dispatcher with maintained database connections
10  
11 6 our $VERSION = '0.002'; # VERSION: generated by DZP::OurPkgVersion
12  
13 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 6 ▶use English '-no_match_vars';
Subroutine BEGIN: called CC=1 SCAR=0.0
15 6 ▶use Storable;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 6 ▶use Module::Load qw( load );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 6 ▶use Scalar::Util qw( refaddr );
Subroutine BEGIN: called CC=1 SCAR=0.0
18 6 ▶use Const::Fast;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 6 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 6 ▶use Log::Any qw( $log ), hooks => { build_context => [ \&_build_context, ], };
Subroutine BEGIN: called CC=1 SCAR=0.0
22 6 ▶use Log::Any::Adapter::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 0 ▶sub _build_context {
Subroutine _build_context: not called CC=1 SCAR=6.9
25  
26 # my ($level, $category, $data) = @_;
27 0 my %ctx;
28 0 my @caller = Log::Any::Adapter::Util::get_correct_caller();
29 0 $ctx{file} = $caller[1];
30 0 $ctx{line} = $caller[2];
31 0 return %ctx;
32 }
33 6 ▶use Carp::Assert;
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 6 ▶use TheSchwartz::JobScheduler::Job;
Subroutine BEGIN: called CC=1 SCAR=0.0
36  
37 6 const my $DEFAULT_OPTION_UNIQKEY => 'no_check';
38  
39 6 has databases => (
40 is => 'ro',
41 required => 1,
42 );
43  
44 6 has dbh_callback => (
45 is => 'ro',
46 required => 0,
47 );
48  
49 has _funcmap => (
50 is => 'ro',
51 5 ▶ default => sub { {}; },
Subroutine __ANON__: called CC=1 SCAR=0.0
52 6 );
53  
54 has opts => (
55 is => 'ro',
56 3 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
57 3 return { handle_uniqkey => $DEFAULT_OPTION_UNIQKEY, };
58 },
59 6 );
60  
61 14 ▶sub insert {
Subroutine insert: called CC=14 SCAR=26.5
Pod documented
62 14 my ( $self, %args ) = @_;
63  
64 # use Data::Dumper;
65 # warn Dumper \%args;
66  
67 14 ▶ croak q{No job} unless exists $args{'job'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{"job"} 0 14 14
68 14 my $job = $args{'job'};
69 14 ▶ croak q{Argument job not TheSchwartz::JobScheduler::Job} unless $job->isa('TheSchwartz::JobScheduler::Job');
Branch: 1 branch
BranchTrueFalseTotal
unless $job->isa("TheSchwartz::JobScheduler::Job") 0 14 14
70  
71 # my $databases = $args{'databases'};
72 14 my $databases = $self->databases;
73 14 ▶ $job->arg( Storable::nfreeze( $job->arg ) ) if ref $job->arg;
Branch: 1 branch
BranchTrueFalseTotal
if ref $job->arg 13 1 14
74  
75 # $log->debugf( 'TheSchwartz::JobScheduler::insert(): databases: %s', $databases );
76 14 foreach my $database_id ( keys %{$databases} ) {
77  
78 # $log->debugf( 'TheSchwartz::JobScheduler::insert(): db: %s', $db );
79  
80 14 ▶ my $dbh_callback = exists $args{'dbh_callback'} ? $args{'dbh_callback'} : $self->dbh_callback;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'dbh_callback'} ? : 3 11 14
81 14 my $dbh = _get_dbh( $database_id, $dbh_callback );
82  
83 # $log->debugf( 'TheSchwartz::JobScheduler::insert(): dbh: %s', $dbh );
84 14 ▶ my $prefix = $databases->{$database_id}->{'prefix'} // q{};
Condition50%1/2
$databases->{$database_id}{"prefix"} // ""
l!l
140
MC/DC0%0/1
$databases->{$database_id}{"prefix"} // ""
$databases->{$database_id}{"prefix"}
Truth table50%1/2
A
A= $databases->{$database_id}{"prefix"}
Aresult
11
00
85  
86 # $log->debugf( 'TheSchwartz::JobScheduler::insert(): prefix: %s', $prefix );
87  
88 14 my $jobid;
89  
90 # local $EVAL_ERROR = undef;
91 # my $r = eval {
92 # $job->funcid( $self->funcname_to_id( $database, $job->funcname ) );
93 14 $job->funcid( $self->funcname_to_id( $dbh, $prefix, $job->funcname ) );
94 14 $job->insert_time(time);
95  
96 14 ▶ if ( $job->uniqkey && $self->opts->{'handle_uniqkey'} eq 'acknowledge' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($job->uniqkey and $self->opts->{"handle_uniqkey"} eq "acknowledge") 2 12 14
Condition100%3/3
$job->uniqkey and $self->opts->{"handle_uniqkey"} eq "acknowledge"
!ll&&!rl&&r
1022
MC/DC100%2/2
$job->uniqkey and $self->opts->{"handle_uniqkey"} eq "acknowledge"
$job->uniqkey $self->opts->{"handle_uniqkey"} eq "acknowledge"
Truth table100%3/3
A and B
A= $job->uniqkeyB= $self->opts->{"handle_uniqkey"} eq "acknowledge"
ABresult
0X0
100
111
97 2 my $row = $job->as_hashref;
98 2 my @query_cols = qw( jobid );
99 2 my @where_cols = qw( funcid uniqkey );
100 2 my $sql = sprintf 'SELECT %s FROM %sjob WHERE funcid = ? AND uniqkey = ?', ( join q{, }, @query_cols ), $prefix;
101  
102 2 my $sth = $dbh->prepare_cached($sql);
103 2 my $i = 1;
104 2 for my $where_col (@where_cols) {
105 4 $sth->bind_param( $i++, $row->{$where_col}, _bind_param_attr( $dbh, $prefix, $where_col ), );
106 }
107 2 $sth->execute();
108  
109 # Strange if there would be more than one entry!
110 2 my @job_ids;
111 2 ▶ while ( my $ref = $sth->fetchrow_arrayref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ref = $sth->fetchrow_arrayref) 2 2 4
112 2 push @job_ids, $ref->[0];
113 }
114  
115 # $sth->finish;
116 # https://metacpan.org/pod/DBI#finish
117 # Indicate that no more data will be fetched from this statement
118 # handle before it is either executed again or destroyed.
119 # You almost certainly do not need to call this method.
120 # Adding calls to finish after loop that fetches all rows
121 # is a common mistake, don't do it, it can mask genuine
122 # problems like uncaught fetch errors.
123 2 ▶ return $job_ids[0] if (@job_ids);
Branch: 1 branch
BranchTrueFalseTotal
if @job_ids 2 0 2
124 }
125  
126 12 my $row = $job->as_hashref;
127 12 my @col = keys %{$row};
128 12 my $sql = sprintf 'INSERT INTO %sjob (%s) VALUES (%s)', $prefix, ( join q{, }, @col ), ( join q{, }, (q{?}) x @col );
129  
130 12 my $sth = $dbh->prepare_cached($sql);
131 12 my $i = 1;
132 12 for my $col (@col) {
133 67 $sth->bind_param( $i++, $row->{$col}, _bind_param_attr( $dbh, $prefix, $col ), );
134 }
135 12 $sth->execute();
136  
137 11 $jobid = _insert_id( $dbh, $prefix, $sth, "${prefix}job", 'jobid' );
138  
139 11 $log->debugf( 'TheSchwartz::JobScheduler::insert() jobid: %s', $jobid );
140 11 ▶ return $jobid if defined $jobid;
Branch: 1 branch
BranchTrueFalseTotal
if defined $jobid 11 0 11
141 }
142  
143 0 return;
144 }
145  
146 27 ▶sub funcname_to_id {
Subroutine funcname_to_id: called CC=7 SCAR=19.5
Pod documented
147 27 my ( $self, $dbh, $prefix, $funcname ) = @_;
148 27 $log->debugf( 'TheSchwartz::JobScheduler::funcname_to_id(%s, %s, %s)', $dbh, $prefix, $funcname );
149  
150 # my ( $dbh, $prefix ) = ($database->dbh, $database->prefix);
151  
152 27 my $dbid = refaddr $dbh;
153 27 ▶ unless ( exists $self->_funcmap->{$dbid} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->_funcmap->{$dbid}) 20 7 27
154 20 my $sth = $dbh->prepare_cached("SELECT funcid, funcname FROM ${prefix}funcmap");
155 20 $sth->execute;
156 20 ▶ while ( my $row = $sth->fetchrow_arrayref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_arrayref) 16 20 36
157 16 $self->_funcmap->{$dbid}{ $row->[1] } = $row->[0];
158 }
159  
160 # $sth->finish;
161 # See above
162 }
163  
164 27 ▶ unless ( exists $self->_funcmap->{$dbid}{$funcname} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->_funcmap->{$dbid}{$funcname}) 12 15 27
165 ## This might fail in a race condition since funcname is UNIQUE
166 12 my $sth = $dbh->prepare_cached("INSERT INTO ${prefix}funcmap (funcname) VALUES (?)");
167 12 local $EVAL_ERROR = undef;
168 12 my $r = eval { $sth->execute($funcname) };
169 12 ▶ if ( !$r ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($r) 1 11 12
170 1 my $error = $EVAL_ERROR;
171 1 $log->warn( ' Unable to insert the funcname \'%s\'. Error: %s', $funcname, $error );
172 }
173  
174 12 my $id = _insert_id( $dbh, $prefix, $sth, "${prefix}funcmap", 'funcid' );
175  
176 ## If we got an exception, try to load the record again
177 12 ▶ if ($EVAL_ERROR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($TheSchwartz::JobScheduler::EVAL_ERROR) 1 11 12
178 1 $sth = $dbh->prepare_cached("SELECT funcid FROM ${prefix}funcmap WHERE funcname = ?");
179 1 $sth->execute($funcname);
180 1 ▶ $id = $sth->fetchrow_arrayref->[0]
Branch: 1 branch
BranchTrueFalseTotal
$id = $sth->fetchrow_arrayref->[0] or croak("Can't find or create funcname ${funcname}: $TheSchwartz::JobScheduler::EVAL_ERROR") 1 0 1
181 or croak "Can't find or create funcname $funcname: $EVAL_ERROR";
182 }
183  
184 12 $self->_funcmap->{$dbid}{$funcname} = $id;
185 }
186  
187 27 $log->debugf( 'TheSchwartz::JobScheduler::funcname_to_id(): %s', $self->_funcmap->{$dbid}{$funcname} );
188 27 return $self->_funcmap->{$dbid}{$funcname};
189 }
190  
191 23 ▶sub _insert_id {
Subroutine _insert_id: called CC=4 SCAR=17.2
192 23 my ( $dbh, $prefix, $sth, $table, $col ) = @_;
193  
194 # my ( $dbh, $prefix ) = ($database->dbh, $database->prefix);
195  
196 23 my $driver = $dbh->{Driver}{Name};
197 23 ▶ if ( $driver eq 'mysql' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($driver eq 'mysql') { } 0 23 23
elsif ($driver eq 'Pg') { } 0 23 23
elsif ($driver eq 'SQLite') { } 23 0 23
198 0 return $dbh->{mysql_insertid};
199 }
200 elsif ( $driver eq 'Pg' ) {
201 0 return $dbh->last_insert_id( undef, undef, undef, undef, { sequence => ( join q{_}, $table, $col, 'seq' ) } );
202 }
203 elsif ( $driver eq 'SQLite' ) {
204 23 return $dbh->func('last_insert_rowid');
205 }
206 else {
207 0 croak "Don't know how to get last insert id for $driver";
208 }
209 }
210  
211 6 ▶sub list_jobs {
Subroutine list_jobs: called CC=13 SCAR=27.5
Pod documented
212 6 my ( $self, %args ) = @_;
213 6 $log->debugf( 'TheSchwartz::JobScheduler::list_jobs(%s)', \%args );
214 6 ▶ croak q{No search_params} unless exists $args{'search_params'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{"search_params"} 0 6 6
215 6 my $search_params = $args{'search_params'};
216  
217 6 ▶ croak q{No funcname} unless exists $search_params->{funcname};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $search_params->{"funcname"} 0 6 6
218  
219 6 my @options;
220 push @options,
221 {
222 key => 'run_after',
223 op => '<=',
224 value => $search_params->{run_after}
225 6 ▶ } if exists $search_params->{run_after};
Branch: 1 branch
BranchTrueFalseTotal
if exists $search_params->{"run_after"} 0 6 6
226 push @options,
227 {
228 key => 'grabbed_until',
229 op => '<=',
230 value => $search_params->{grabbed_until}
231 }
232 6 ▶ if exists $search_params->{grabbed_until};
Branch: 1 branch
BranchTrueFalseTotal
if exists $search_params->{"grabbed_until"} 0 6 6
233  
234 6 ▶ if ( $search_params->{coalesce} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($search_params->{"coalesce"}) 0 6 6
235 0 ▶ $search_params->{coalesce_op} ||= q{=};
Condition0%0/2
$search_params->{"coalesce_op"} ||= "="
l!l
00
MC/DC0%0/1
$search_params->{"coalesce_op"} ||= "="
$search_params->{"coalesce_op"}
Truth table0%0/2
A
A= $search_params->{"coalesce_op"}
Aresult
11
00
236 push @options,
237 {
238 key => 'coalesce',
239 op => $search_params->{coalesce_op},
240 value => $search_params->{coalesce}
241 0 };
242 }
243  
244 6 my @jobs;
245 6 my $databases = $self->databases;
246 6 foreach my $database_id ( keys %{$databases} ) {
247 10 ▶ my $dbh_callback = exists $args{'dbh_callback'} ? $args{'dbh_callback'} : $self->dbh_callback;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'dbh_callback'} ? : 4 6 10
248 10 my $dbh = _get_dbh( $database_id, $dbh_callback );
249 10 ▶ my $prefix = $databases->{$database_id}->{'prefix'} // q{};
Condition50%1/2
$databases->{$database_id}{"prefix"} // ""
l!l
100
MC/DC0%0/1
$databases->{$database_id}{"prefix"} // ""
$databases->{$database_id}{"prefix"}
Truth table50%1/2
A
A= $databases->{$database_id}{"prefix"}
Aresult
11
00
250  
251 10 local $EVAL_ERROR = undef;
252 10 my $r = eval {
253 10 my $funcid = $self->funcname_to_id( $dbh, $prefix, $search_params->{funcname} );
254  
255 10 my $sql = "SELECT * FROM ${prefix}job WHERE funcid = ?";
256 10 my @value = ($funcid);
257 10 for (@options) {
258 0 $sql .= " AND $_->{key} $_->{op} ?";
259 0 push @value, $_->{value};
260 }
261  
262 10 my $sth = $dbh->prepare_cached($sql);
263 10 $sth->execute(@value);
264 10 ▶ while ( my $ref = $sth->fetchrow_hashref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ref = $sth->fetchrow_hashref) 9 10 19
265 9 $log->debugf( 'TheSchwartz::JobScheduler::list_jobs(): fetch:ref: %s', $ref );
266  
267 # my $job_fields = Storable::dclone( $ref );
268 # $job->search_params( Storable::nfreeze( $job->search_params ) ) if ref $job->search_params;
269 9 my $arg_tmp = _cond_thaw( $ref->{'arg'} );
270 9 my $job = TheSchwartz::JobScheduler::Job->new($ref);
271 9 $job->arg($arg_tmp);
272 9 push @jobs, $job;
273 }
274 10 1;
275 };
276 10 ▶ if ( !$r ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($r) 0 10 10
277 0 my $error = $EVAL_ERROR;
278 0 $log->warn( ' Unable to fetch jobs for funcname \'%s\' (id: %s). Error: %s', $search_params->{funcname}, $error );
279 }
280 }
281  
282 6 $log->debugf( 'TheSchwartz::JobScheduler::list_jobs(): %s', \@jobs );
283 6 return @jobs;
284 }
285  
286 71 ▶sub _bind_param_attr {
Subroutine _bind_param_attr: called CC=4 SCAR=15.0
287 71 my ( $dbh, $prefix, $col ) = @_;
288  
289 # my ( $dbh, $prefix ) = ( $database->dbh, $database->prefix );
290  
291 71 ▶ return if $col ne 'arg';
Branch: 1 branch
BranchTrueFalseTotal
if $col ne "arg" 59 12 71
292  
293 12 my $driver = $dbh->{Driver}{Name};
294 12 ▶ if ( $driver eq 'Pg' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($driver eq 'Pg') { } 0 12 12
elsif ($driver eq 'SQLite') { } 12 0 12
295 0 return { pg_type => DBD::Pg::PG_BYTEA() };
296 }
297 elsif ( $driver eq 'SQLite' ) {
298 12 return DBI::SQL_BLOB();
299 }
300 0 return;
301 }
302  
303 # Shamelessly copied from TheSchwartz::Job
304 # Perl::Critic applied
305 9 ▶sub _cond_thaw {
Subroutine _cond_thaw: called CC=6 SCAR=18.5
306 9 my $data = shift;
307  
308 9 my $magic = eval { Storable::read_magic($data); };
309 9 ▶ if ( $magic
Branch: 1 branch
BranchTrueFalseTotal
if ($magic and $magic->{'major'} and $magic->{'major'} >= 2 and $magic->{'major'} <= 5) { } 8 1 9
Condition66%6/9
$magic and $magic->{"major"} and $magic->{"major"} >= 2 and $magic->{"major"} <= 5
!ll&&!rl&&r
108
$magic and $magic->{"major"} and $magic->{"major"} >= 2
!ll&&!rl&&r
108
$magic and $magic->{"major"}
!ll&&!rl&&r
108
MC/DC25%1/4
$magic and $magic->{"major"} and $magic->{"major"} >= 2 and $magic->{"major"} <= 5
$magic $magic->{"major"} $magic->{"major"} >= 2 $magic->{"major"} <= 5
Truth table40%2/5
A and B and C and D
A= $magicB= $magic->{"major"}C= $magic->{"major"} >= 2D= $magic->{"major"} <= 5
ABCDresult
0XXX0
10XX0
110X0
11100
11111
310 && $magic->{major}
311 && $magic->{major} >= 2
312 && $magic->{major} <= 5 ) ## no critic (ValuesAndExpressions::ProhibitMagicNumbers)
313 {
314 8 my $thawed = eval { Storable::thaw($data) };
315 8 ▶ if ($@) { ## no critic (Variables::ProhibitPunctuationVars)
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 8 8
316  
317 # false alarm... looked like a Storable, but wasn't.
318 0 return $data;
319 }
320 8 return $thawed;
321 }
322 else {
323 1 return $data;
324 }
325 }
326  
327 31 ▶sub _get_dbh {
Subroutine _get_dbh: called CC=5 SCAR=16.1
328 31 my ( $database_id, $dbh_callback ) = @_;
329  
330 # my $cb = $dbh_callback;
331 31 my $dbh;
332 31 ▶ if ( ref $dbh_callback eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $dbh_callback eq 'CODE') { } 19 12 31
333 19 $dbh = &{$dbh_callback}($database_id);
334 }
335 else {
336 12 my $dbh_callback_code = $dbh_callback;
337 12 my ( $module, $creator ) = split qr/\-\>/msx, $dbh_callback_code;
338 12 local $EVAL_ERROR = undef;
339 12 my $r = eval { load $module };
340 12 ▶ if ($EVAL_ERROR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($TheSchwartz::JobScheduler::EVAL_ERROR) 1 11 12
341 1 croak q{Cannot load dbh_callback module '}, $module, q{'};
342 }
343 11 my $callback;
344 11 local $EVAL_ERROR = undef;
345 11 $r = eval { $callback = $module->$creator() };
346 11 ▶ if ($EVAL_ERROR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($TheSchwartz::JobScheduler::EVAL_ERROR) 1 10 11
347 1 croak q{Cannot instantiate dbh_callback module '}, "$module->$creator", q{'};
348 }
349 10 local $EVAL_ERROR = undef;
350 10 $r = eval { $dbh = $callback->dbh($database_id) };
351 10 ▶ if ($EVAL_ERROR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($TheSchwartz::JobScheduler::EVAL_ERROR) 1 9 10
352 1 croak q{Cannot get dbh from callback '}, "$module->$creator->dbh( $database_id )", q{'};
353 }
354 }
355  
356 28 return $dbh;
357 }
358  
359 6 1;
360  
361 __END__
↑ Summary JobScheduler/Job.pm »