blib/lib/Minion/Backend/mysql.pm

filter: Statementstmt 9.2% 37 / 399 Branchbran 0.0% 0 / 142 Conditioncond 0.9% 1 / 110 MC/DCmcdc 0.0% 0 / 59 Subroutinesub 17.8% 10 / 56 Podpod 100% 27 / 27 totaltotal 9.4% 75 / 793 CC 125 SCAR 48.2
CC
125
Cov
6%
_enqueue
462.0
dequeue
420.0
list_jobs
72.0
CRAP 123.5
↑ Summary
1 package Minion::Backend::mysql;
2  
3 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 ▶use Mojo::Base 'Minion::Backend';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use constant DEBUG => $ENV{MINION_BACKEND_DEBUG} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'MINION_BACKEND_DEBUG'} || 0
l!l
01
MC/DC0%0/1
$ENV{'MINION_BACKEND_DEBUG'} || 0
$ENV{'MINION_BACKEND_DEBUG'}
Truth table50%1/2
A
A= $ENV{'MINION_BACKEND_DEBUG'}
Aresult
11
00
8 1 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Mojo::JSON qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Minion::Util qw(next_cron_time);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Mojo::mysql;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Sys::Hostname 'hostname';
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use Time::Piece ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 1 has 'mysql';
17 0 ▶has 'no_txn' => sub { 0 };
Subroutine __ANON__: not called CC=1 SCAR=1.2
18  
19 1 our $VERSION = '1.009';
20  
21 # The dequeue system has a couple limitations:
22 # 1. There is no way to directly notify a sleeping worker of an incoming
23 # job
24 # 2. There is a race condition between identifying a runnable job
25 # and claiming it for the current worker.
26 #
27 # The first is solved by Mojo::mysql::PubSub, which currently makes
28 # a new connection to MySQL, records the connection ID, and then sleeps.
29 # When a message is "published", the publisher writes the message to
30 # a table and then `KILL`s all the sleeping "subscribers". One of the
31 # subscribers reads the message from the table and continues.
32 #
33 # The second is solved by checking how many rows are `UPDATE`d when
34 # claiming the job. Since we prefetch a few jobs, we can try to claim
35 # a couple before needing to go to the database again.
36 #
37 # If it gives up, there may still be jobs available to be dequeued. In
38 # most cases, this is okay: The worker will start sleeping for an
39 # incoming job and when one comes in, it will wake up and start
40 # dequeuing again (even if the new job itself isn't ready to run).
41 1 my $DEQUEUE_RACE_ATTEMPTS = 10;
42  
43 1 our $PREFETCH = 20;
44 1 our $PREFETCH_EXPIRY = 30; # seconds
45  
46 0 ▶sub _claim_job {
Subroutine _claim_job: not called CC=3 SCAR=24.8
47 0 my ( $self, $db, $worker_id, $job ) = @_;
48 # Try to claim the job for this worker. There is a race condition
49 # between selecting the job and claiming it, so we need to make sure
50 # we were the one to claim it.
51 my $claimed = $db->query(
52 qq{ UPDATE minion_jobs SET started = NOW(), state = 'active', worker = ? WHERE id = ? AND state = 'inactive' },
53 $worker_id, $job->{id},
54 0 )->affected_rows;
55  
56 0 ▶ if ($claimed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($claimed) 0 0 0
57 # Won the race, so do the job
58 0 ▶ $job->{args} = $job->{args} ? decode_json($job->{args}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$job->{'args'} ? : 0 0 0
59 0 return $job;
60 }
61 0 return undef;
62 }
63  
64 0 ▶sub dequeue {
Subroutine dequeue: not called CC=20 SCAR=60.4
Pod documented
65 0 my ($self, $worker_id, $wait, $options) = @_;
66 0 state @cached_jobs = ();
67 0 state $last_fetch_at = 0;
68 0 state $last_min_priority = undef;
69 0 state $last_tasks = undef;
70 0 my $has_fetched = 0;
71 0 my $db = $self->mysql->db;
72  
73 0 my $tasks = [keys %{$self->minion->tasks}];
74 0 ▶ return unless @$tasks;
Branch: 1 branch
BranchTrueFalseTotal
unless @$tasks 0 0 0
75  
76 # If we're trying to dequeue a specific job ID, just do it
77 0 ▶ if ($options->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{'id'}) { } 0 0 0
78 0 my ($job) = $self->_fetch_jobs($worker_id, $options)->each;
79 0 $has_fetched = 1;
80 0 $job = $self->_claim_job( $db, $worker_id, $job );
81 0 ▶ return $job if $job;
Branch: 1 branch
BranchTrueFalseTotal
if $job 0 0 0
82 }
83 else {
84 # If either of our cache conditions changes, drop the cache
85 0 ▶ if (defined $options->{min_priority} && defined $last_min_priority && $options->{min_priority} != $last_min_priority) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"min_priority"} and defined $last_min_priority and $options->{"min_priority"} != $last_min_priority) 0 0 0
Condition0%0/6
defined $options->{"min_priority"} and defined $last_min_priority and $options->{"min_priority"} != $last_min_priority
!ll&&!rl&&r
000
defined $options->{"min_priority"} and defined $last_min_priority
!ll&&!rl&&r
000
MC/DC0%0/3
defined $options->{"min_priority"} and defined $last_min_priority and $options->{"min_priority"} != $last_min_priority
defined $options->{"min_priority"} defined $last_min_priority $options->{"min_priority"} != $last_min_priority
Truth table0%0/4
A and B and C
A= defined $options->{"min_priority"}B= defined $last_min_priorityC= $options->{"min_priority"} != $last_min_priority
ABCresult
0XX0
10X0
1100
1111
86 0 @cached_jobs = ();
87 }
88 0 ▶ if (defined $options->{tasks} && defined $last_tasks && join( "\0", sort @{$options->{tasks}} ) ne join( "\0", sort @{$last_tasks} )) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"tasks"} and defined $last_tasks and join("\0", sort(@{$options->{"tasks"};})) ne join("\0", sort(@{$last_tasks;}))) 0 0 0
Condition0%0/6
defined $options->{"tasks"} and defined $last_tasks and join("\0", sort(@{$options->{"tasks"};})) ne join("\0", sort(@{$last_tasks;}))
!ll&&!rl&&r
000
defined $options->{"tasks"} and defined $last_tasks
!ll&&!rl&&r
000
MC/DC0%0/3
defined $options->{"tasks"} and defined $last_tasks and join("\0", sort(@{$options->{"tasks"};})) ne join("\0", sort(@{$last_tasks;}))
defined $options->{"tasks"} defined $last_tasks join("\0", sort(@{$options->{"tasks"};})) ne join("\0", sort(@{$last_tasks;}))
Truth table0%0/4
A and B and C
A= defined $options->{"tasks"}B= defined $last_tasksC= join("\0", sort(@{$options->{"tasks"};})) ne join("\0", sort(@{$last_tasks;}))
ABCresult
0XX0
10X0
1100
1111
89 0 @cached_jobs = ();
90 }
91  
92 # Decide if we need some jobs
93 0 ▶ if (!@cached_jobs || $last_fetch_at + $PREFETCH_EXPIRY < time) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @cached_jobs or $last_fetch_at + $Minion::Backend::mysql::PREFETCH_EXPIRY < time) 0 0 0
Condition0%0/3
not @cached_jobs or $last_fetch_at + $Minion::Backend::mysql::PREFETCH_EXPIRY < time
l!l&&r!l&&!r
000
MC/DC0%0/2
not @cached_jobs or $last_fetch_at + $Minion::Backend::mysql::PREFETCH_EXPIRY < time
not @cached_jobs $last_fetch_at + $Minion::Backend::mysql::PREFETCH_EXPIRY < time
Truth table0%0/3
not(A) or B
A= not @cached_jobsB= $last_fetch_at + $Minion::Backend::mysql::PREFETCH_EXPIRY < time
ABresult
1X1
011
000
94 0 @cached_jobs = $self->_fetch_jobs($worker_id, $options)->each;
95 0 $last_fetch_at = time;
96 0 $has_fetched = 1;
97 }
98  
99 0 ▶ $last_min_priority = $options->{min_priority} if defined $options->{min_priority};
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"min_priority"} 0 0 0
100 0 ▶ $last_tasks = [ @{$options->{tasks}} ] if defined $options->{tasks};
Branch: 1 branch
BranchTrueFalseTotal
if defined $options->{"tasks"} 0 0 0
101  
102 # Now, go through the jobs we have and try to claim one
103 0 ▶ while (@cached_jobs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cached_jobs) 0 0 0
104 0 my $job = $self->_claim_job( $db, $worker_id, shift @cached_jobs );
105 0 ▶ return $job if $job;
Branch: 1 branch
BranchTrueFalseTotal
if $job 0 0 0
106 }
107 }
108  
109 # If we haven't made one trip to the database, we should just in case
110 0 ▶ return $self->dequeue($worker_id, $wait, $options) if !$has_fetched;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_fetched 0 0 0
111  
112 0 ▶ return undef if Mojo::IOLoop->is_running || !$wait;
Branch: 1 branch
BranchTrueFalseTotal
if "Mojo::IOLoop"->is_running or not $wait 0 0 0
Condition0%0/3
"Mojo::IOLoop"->is_running or not $wait
l!l&&r!l&&!r
000
MC/DC0%0/2
"Mojo::IOLoop"->is_running or not $wait
"Mojo::IOLoop"->is_running not $wait
Truth table0%0/3
A or not(B)
A= "Mojo::IOLoop"->is_runningB= not $wait
ABresult
1X1
011
000
113  
114 # Otherwise, wait for up to $wait for a job to come in. We know when a job comes
115 # in because enqueue will kill all the `sleep` jobs that the "pubsub" creates.
116 0 ▶ my $cb = $self->mysql->pubsub->listen("minion.job" => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
117 0 Mojo::IOLoop->stop;
118 0 });
119  
120 0 ▶ my $timer = Mojo::IOLoop->timer($wait => sub { Mojo::IOLoop->stop });
Subroutine __ANON__: not called CC=1 SCAR=6.9
121 0 Mojo::IOLoop->start;
122  
123 0 ▶ $self->mysql->pubsub->unlisten("minion.job" => $cb) and Mojo::IOLoop->remove($timer);
Branch: 1 branch
BranchTrueFalseTotal
$self->mysql->pubsub->unlisten("minion.job", $cb) and "Mojo::IOLoop"->remove($timer) 0 0 0
124  
125 0 return $self->dequeue($worker_id, 0, $options);
126 }
127  
128 0 ▶sub history {
Subroutine history: not called CC=4 SCAR=30.0
Pod documented
129 0 my $self = shift;
130  
131 0 my $sql = <<SQL;
132 SELECT
133 MIN(UNIX_TIMESTAMP(jobs.finished)) as `epoch`,
134 DAY(jobs.finished) as `day`,
135 HOUR(jobs.finished) as `hour`,
136 SUM(CASE jobs.state WHEN 'failed' THEN 1 ELSE 0 END) AS failed_jobs,
137 SUM(CASE jobs.state WHEN 'finished' THEN 1 ELSE 0 END) AS finished_jobs
138 FROM minion_jobs jobs
139 WHERE jobs.finished > SUBTIME(NOW(), '23:00:00')
140 GROUP BY `day`, `hour`
141 ORDER BY `day`, `hour`
142 SQL
143  
144 0 my $data = $self->mysql->db->query($sql)->hashes;
145  
146 # Fill in missing hours to create a full time series
147 0 my $now = Time::Piece->new();
148 0 my $current_hour = $now->hour;
149 0 for my $i ( 0..23 ) {
150 0 my $i_hour = ( $current_hour - ( 23 - $i ) ) % 24;
151 0 ▶ if ( exists $data->[$i] and $data->[ $i ]{ hour } != $i_hour ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->[$i] and $data->[$i]{'hour'} != $i_hour) { } 0 0 0
Condition0%0/3
exists $data->[$i] and $data->[$i]{"hour"} != $i_hour
!ll&&!rl&&r
000
MC/DC0%0/2
exists $data->[$i] and $data->[$i]{"hour"} != $i_hour
exists $data->[$i] $data->[$i]{"hour"} != $i_hour
Truth table0%0/3
A and B
A= exists $data->[$i]B= $data->[$i]{"hour"} != $i_hour
ABresult
0X0
100
111
152 0 my $epoch = $now->epoch - ( 3600 * ( 24 - $i ) );
153 0 splice @$data, $i, 0, {
154 epoch => $epoch - ( $epoch % 3600 ),
155 failed_jobs => 0,
156 finished_jobs => 0,
157 };
158 }
159 else {
160 0 delete $data->[ $i ]{hour};
161 0 delete $data->[ $i ]{day};
162 }
163 }
164  
165 0 return {daily => $data};
166 }
167  
168 0 ▶sub dispatch_schedules {
Subroutine dispatch_schedules: not called CC=4 SCAR=30.0
Pod documented
169 0 my $self = shift;
170  
171 0 my $db = $self->mysql->db;
172 0 my $tx = $db->begin;
173 0 ▶ return [] unless $db->query(q{SELECT GET_LOCK('minion.schedules',0)})->array->[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $db->query("SELECT GET_LOCK('minion.schedules',0)")->array->[0] 0 0 0
174 0 ▶ my $guard = Minion::Backend::mysql::_guard->new(sub { $db->query(q{SELECT RELEASE_LOCK('minion.schedules')}) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
175  
176 0 my $due = $db->query(
177 q{SELECT id, args, attempts, cron, expire, lax, name, UNIX_TIMESTAMP(next_run) AS next_run,
178 UNIX_TIMESTAMP() AS `now`, notes, priority, queue, task
179 FROM minion_schedules WHERE next_run <= NOW() AND NOT paused FOR UPDATE}
180 )->expand->hashes;
181  
182 0 my @dispatched;
183 0 for my $s (@$due) {
184 my $job_id = $self->_enqueue(
185 $db,
186 $tx,
187 $s->{task},
188 $s->{args},
189 {
190 attempts => $s->{attempts},
191 expire => $s->{expire},
192 lax => $s->{lax},
193 notes => $s->{notes},
194 priority => $s->{priority},
195 queue => $s->{queue}
196 }
197 0 );
198 0 ▶ my $basis = $s->{next_run} > $s->{now} ? $s->{next_run} : $s->{now};
Branch: 1 branch
BranchTrueFalseTotal
$s->{'next_run'} > $s->{'now'} ? : 0 0 0
199 0 my $next = next_cron_time $s->{cron}, $basis;
200 $db->query('UPDATE minion_schedules SET last_job = ?, last_run = NOW(), next_run = FROM_UNIXTIME(?) WHERE id = ?',
201 0 $job_id, $next, $s->{id});
202 0 push @dispatched, {id => $s->{id}, name => $s->{name}, job => $job_id};
203 }
204 0 $tx->commit;
205  
206 0 return \@dispatched;
207 }
208  
209 0 ▶sub enqueue {
Subroutine enqueue: not called CC=1 SCAR=6.9
Pod documented
210 0 my $self = shift;
211 0 return $self->_enqueue( $self->mysql->db, undef, @_ );
212 }
213  
214 0 ▶sub _enqueue {
Subroutine _enqueue: not called CC=21 SCAR=61.4
215 0 my ($self, $db, $tx, $task) = (shift, shift, shift, shift);
216 0 ▶ my $args = shift // [];
Condition0%0/2
shift() // []
l!l
00
MC/DC0%0/1
shift() // []
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
217 0 ▶ my $options = shift // {};
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
218  
219 # Pre-compute parameters to reduce time holding DB transaction
220 my @insert_params = (
221 encode_json( $args ),
222 $options->{attempts} // 1,
223 $options->{delay} // 0,
224 ($options->{expire})x2,
225 $options->{lax} ? 1 : 0,
226 $options->{priority} // 0,
227 0 ▶ $options->{queue} // 'default',
Branch: 1 branch
BranchTrueFalseTotal
$options->{'lax'} ? : 0 0 0
Condition0%0/8
$options->{"attempts"} // 1
l!l
00
$options->{"delay"} // 0
l!l
00
$options->{"priority"} // 0
l!l
00
$options->{"queue"} // "default"
l!l
00
MC/DC0%0/1
$options->{"attempts"} // 1
$options->{"attempts"}
MC/DC0%0/1
$options->{"delay"} // 0
$options->{"delay"}
MC/DC0%0/1
$options->{"priority"} // 0
$options->{"priority"}
MC/DC0%0/1
$options->{"queue"} // "default"
$options->{"queue"}
Truth table0%0/2
A
A= $options->{"attempts"}
Aresult
11
00
Truth table0%0/2
A
A= $options->{"delay"}
Aresult
11
00
Truth table0%0/2
A
A= $options->{"priority"}
Aresult
11
00
Truth table0%0/2
A
A= $options->{"queue"}
Aresult
11
00
228 $task,
229 );
230  
231 0 ▶ my @parents = @{ $options->{parents} // [] };
Condition0%0/2
$options->{"parents"} // []
l!l
00
MC/DC0%0/1
$options->{"parents"} // []
$options->{"parents"}
Truth table0%0/2
A
A= $options->{"parents"}
Aresult
11
00
232 0 ▶ my %notes = %{ $options->{notes} // {} };
Condition0%0/2
$options->{"notes"} // {}
l!l
00
MC/DC0%0/1
$options->{"notes"} // {}
$options->{"notes"}
Truth table0%0/2
A
A= $options->{"notes"}
Aresult
11
00
233  
234 0 my ( $insert_parents_sql, $insert_notes_sql );
235 0 ▶ if ( @parents ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parents) 0 0 0
236 0 $insert_parents_sql = "INSERT IGNORE INTO minion_jobs_depends (`parent_id`, `child_id`) VALUES "
237 . join( ", ", map "( ?, ? )", @parents );
238 }
239 0 ▶ if ( keys %notes ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %notes) 0 0 0
240 0 $insert_notes_sql = 'INSERT INTO minion_notes (`job_id`, `note_key`, `note_value`) VALUES '
241 . join( ', ', map '( ?, ?, ? )', keys %notes );
242 0 $notes{ $_ } = encode_json( $notes{ $_ } ) for keys %notes;
243 }
244  
245 # If we are adding data in related tables, use a transaction to commit
246 # the entire job at once. Without this, a job may be started before
247 # one of its parents, since the parent restriction is added after the
248 # job itself.
249 0 my $commit = 0;
250 0 ▶ if (!$tx) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tx) 0 0 0
251 0 ▶ $tx = (!$insert_notes_sql && !$insert_parents_sql) || $self->no_txn ? undef : $db->begin;
Branch: 1 branch
BranchTrueFalseTotal
!($insert_notes_sql || $insert_parents_sql) || $self->no_txn ? : 0 0 0
Condition0%0/6
not $insert_notes_sql || $insert_parents_sql or $self->no_txn
l!l&&r!l&&!r
000
$insert_notes_sql || $insert_parents_sql
l!l&&r!l&&!r
000
MC/DC0%0/3
not $insert_notes_sql || $insert_parents_sql or $self->no_txn
$insert_notes_sql $insert_parents_sql $self->no_txn
Truth table0%0/5
not(A || B) or C
A= $insert_notes_sqlB= $insert_parents_sqlC= $self->no_txn
ABCresult
00X1
1X11
0111
1X00
0100
252 0 $commit = 1;
253 }
254  
255 0 my $job_id = $db->query(
256 "insert into minion_jobs (`args`, `attempts`, `delayed`, `expires`, `lax`, `priority`, `queue`, `task`)
257 values (?, ?, (DATE_ADD(NOW(), INTERVAL ? SECOND)), case when ? is not null then date_add( now(), interval ? second ) end, ?, ?, ?, ?)",
258 @insert_params,
259 )->last_insert_id;
260  
261 0 ▶ if ( $insert_parents_sql ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($insert_parents_sql) 0 0 0
262 0 my @insert_parents_params = map { $_, $job_id } @parents;
263 0 $db->query( $insert_parents_sql, @insert_parents_params );
264 }
265  
266 0 ▶ if ( $insert_notes_sql ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($insert_notes_sql) 0 0 0
267 0 my @insert_notes_params = map { $job_id, $_, $notes{$_} } keys %notes;
268 0 $db->query( $insert_notes_sql, @insert_notes_params );
269 }
270  
271 0 ▶ $tx->commit if $commit && defined $tx;
Branch: 1 branch
BranchTrueFalseTotal
if $commit and defined $tx 0 0 0
Condition0%0/3
$commit and defined $tx
!ll&&!rl&&r
000
MC/DC0%0/2
$commit and defined $tx
$commit defined $tx
Truth table0%0/3
A and B
A= $commitB= defined $tx
ABresult
0X0
100
111
272 0 $self->mysql->pubsub->notify("minion.job" => $job_id);
273  
274 0 return $job_id;
275 }
276  
277 0 ▶sub note {
Subroutine note: not called CC=4 SCAR=30.0
Pod documented
278 0 my ($self, $id, $notes) = @_;
279  
280 0 my @replace_keys = grep defined $notes->{ $_ }, keys %$notes;
281 0 my @delete_keys = grep !defined $notes->{ $_ }, keys %$notes;
282  
283 0 my ( $replaced, $deleted );
284 0 my $db = $self->mysql->db;
285 0 ▶ if ( @replace_keys ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@replace_keys) 0 0 0
286 0 local $@; # Don't clobber global
287 0 $replaced = !!eval {
288 $db->query(
289 'REPLACE INTO minion_notes (`job_id`, `note_key`, `note_value`) VALUES '
290 . join( ', ', map '( ?, ?, ? )', @replace_keys ),
291 0 map { $id, $_, encode_json( $notes->{$_} ) } @replace_keys
292 )->rows;
293 };
294 }
295 0 ▶ if ( @delete_keys ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@delete_keys) 0 0 0
296 0 $deleted = !!$db->delete(
297 minion_notes => {
298 job_id => $id,
299 note_key => { -in => \@delete_keys },
300 }
301 )->rows;
302 }
303  
304 0 ▶ return $replaced || $deleted;
Condition0%0/3
$replaced || $deleted
l!l&&r!l&&!r
000
MC/DC0%0/2
$replaced || $deleted
$replaced $deleted
Truth table0%0/3
A || B
A= $replacedB= $deleted
ABresult
1X1
011
000
305 }
306  
307 0 ▶sub fail_job { shift->_update(1, @_) }
Subroutine fail_job: not called CC=1 SCAR=6.9
Pod documented
308 0 ▶sub finish_job { shift->_update(0, @_) }
Subroutine finish_job: not called CC=1 SCAR=6.9
Pod documented
309  
310 0 ▶sub list_jobs {
Subroutine list_jobs: not called CC=8 SCAR=42.8
Pod documented
311 0 my ($self, $offset, $limit, $options) = @_;
312  
313 0 my ( @where, @params );
314 0 ▶ if ( my $states = $options->{states} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $states = $options->{"states"}) 0 0 0
315 0 push @where, 'j.state in (' . join( ',', ('?') x @$states ) . ')';
316 0 push @params, @$states;
317 }
318 0 ▶ if ( my $queues = $options->{queues} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $queues = $options->{"queues"}) 0 0 0
319 0 push @where, 'j.queue in (' . join( ',', ('?') x @$queues ) . ')';
320 0 push @params, @$queues;
321 }
322 0 ▶ if ( my $tasks = $options->{tasks} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tasks = $options->{"tasks"}) 0 0 0
323 0 push @where, 'j.task in (' . join( ',', ('?') x @$tasks ) . ')';
324 0 push @params, @$tasks;
325 }
326 0 ▶ if ( my $ids = $options->{ids} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ids = $options->{"ids"}) 0 0 0
327 0 push @where, 'j.id in (' . join( ',', ('?') x @$ids ) . ')';
328 0 push @params, @$ids;
329 }
330 0 ▶ if ( my $id = $options->{before} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $options->{"before"}) 0 0 0
331 0 push @where, 'j.id < ?';
332 0 push @params, $id;
333 }
334 0 ▶ if ( my $notes = $options->{notes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $notes = $options->{"notes"}) 0 0 0
335 0 push @where, '( '
336 . join( ' or ', ('? in ( select minion_notes.note_key from minion_notes where minion_notes.job_id=j.id )')x@$notes )
337 . ' )';
338 0 push @params, @$notes;
339 }
340  
341 0 push @where, q{(j.state != 'inactive' or j.expires is null or j.expires > now())};
342 0 ▶ my $where = @where ? 'WHERE ' . join( ' AND ', @where ) : '';
Branch: 1 branch
BranchTrueFalseTotal
@where ? : 0 0 0
343  
344 0 my $db = $self->mysql->db;
345  
346 0 my $list_sql = qq{
347 SELECT
348 minion_jobs.id, minion_jobs.args, minion_jobs.attempts,
349 minion_jobs.state, minion_jobs.task, minion_jobs.worker,
350 minion_jobs.lax, minion_jobs.priority, minion_jobs.queue,
351 minion_jobs.result, minion_jobs.retries,
352 filtered.children, filtered.parents,
353 UNIX_TIMESTAMP(minion_jobs.created) AS created,
354 UNIX_TIMESTAMP(minion_jobs.`delayed`) AS `delayed`,
355 UNIX_TIMESTAMP(minion_jobs.finished) AS finished,
356 UNIX_TIMESTAMP(minion_jobs.retried) AS retried,
357 UNIX_TIMESTAMP(minion_jobs.started) AS started,
358 UNIX_TIMESTAMP(NOW()) AS time,
359 UNIX_TIMESTAMP(minion_jobs.expires) AS expires
360 FROM minion_jobs
361 JOIN (
362 SELECT j.id,
363 GROUP_CONCAT( child_jobs.child_id ORDER BY child_jobs.child_id SEPARATOR ':' ) AS children,
364 GROUP_CONCAT( parent_jobs.parent_id ORDER BY parent_jobs.parent_id SEPARATOR ':' ) AS parents
365 FROM minion_jobs j
366 LEFT JOIN minion_jobs_depends child_jobs ON j.id=child_jobs.parent_id
367 LEFT JOIN minion_jobs_depends parent_jobs ON j.id=parent_jobs.child_id
368 $where
369 GROUP BY j.id
370 ) filtered USING ( id )
371 ORDER BY minion_jobs.id DESC
372 LIMIT ? OFFSET ?
373 };
374  
375 0 my $jobs = $db->query( $list_sql, @params, $limit, $offset )->hashes;
376 $jobs->map( _decode_json_fields(qw{ args result }) )
377 0 ▶ ->each( sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
378 0 ▶ $_->{children} = [ split /:/, $_->{children} // '' ];
Condition0%0/2
$_->{"children"} // ""
l!l
00
MC/DC0%0/1
$_->{"children"} // ""
$_->{"children"}
Truth table0%0/2
A
A= $_->{"children"}
Aresult
11
00
379 0 ▶ $_->{parents} = [ split /:/, $_->{parents} // '' ];
Condition0%0/2
$_->{"parents"} // ""
l!l
00
MC/DC0%0/1
$_->{"parents"} // ""
$_->{"parents"}
Truth table0%0/2
A
A= $_->{"parents"}
Aresult
11
00
380 $_->{notes} = {
381 $db->select( minion_notes => [qw( note_key note_value )], { job_id => $_->{id} } )
382 0 ▶ ->arrays->map(sub{ $_->[0], decode_json( $_->[1] ) })->each
Subroutine __ANON__: not called CC=1 SCAR=6.9
383 };
384 0 } );
385  
386 # ; use Data::Dumper;
387 # ; say Dumper $jobs;
388  
389 my $total = $db->query(
390 qq{SELECT COUNT(*) AS count FROM minion_jobs j $where}, @params
391 0 )->hash->{count};
392  
393 return {
394 0 jobs => $jobs,
395 total => $total,
396 }
397 }
398  
399 0 ▶sub _decode_json_fields {
Subroutine _decode_json_fields: not called CC=1 SCAR=6.9
400 0 my @fields = @_;
401 0 ▶ return sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
402 0 my $hash = shift;
403 0 for my $field ( @fields ) {
404 0 ▶ next unless $hash->{ $field };
Branch: 1 branch
BranchTrueFalseTotal
unless $hash->{$field} 0 0 0
405 0 $hash->{ $field } = decode_json( $hash->{ $field } );
406 }
407 0 return $hash;
408 0 };
409 }
410  
411 0 ▶sub list_schedules {
Subroutine list_schedules: not called CC=7 SCAR=40.3
Pod documented
412 0 my ($self, $offset, $limit, $options) = @_;
413  
414 0 my @where = ();
415 0 my @args = ();
416 0 ▶ if ($options->{before}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"before"}) 0 0 0
417 0 push @where, 'id < ?';
418 0 push @args, $options->{before};
419 }
420 0 ▶ if (my @ids = @{$options->{ids} || []}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@ids) = @{$options->{"ids"} or [];}) 0 0 0
Condition0%0/2
$options->{'ids'} || []
l!l
00
MC/DC0%0/1
$options->{'ids'} || []
$options->{'ids'}
Truth table0%0/2
A
A= $options->{'ids'}
Aresult
11
00
421 0 push @where, 'id IN (' . join( ', ', ('?')x@ids ) . ')';
422 0 push @args, @ids;
423 }
424 0 ▶ if (my @names = @{$options->{names} || []}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@names) = @{$options->{"names"} or [];}) 0 0 0
Condition0%0/2
$options->{'names'} || []
l!l
00
MC/DC0%0/1
$options->{'names'} || []
$options->{'names'}
Truth table0%0/2
A
A= $options->{'names'}
Aresult
11
00
425 0 push @where, 'name IN (' . join( ', ', ('?')x@names ) . ')';
426 0 push @args, @names;
427 }
428  
429 0 ▶ my $query = q{SELECT id, args, attempts, UNIX_TIMESTAMP(created) AS created, cron, expire, last_job,
Branch: 1 branch
BranchTrueFalseTotal
@where ? : 0 0 0
430 UNIX_TIMESTAMP(last_run) AS last_run, lax, name, UNIX_TIMESTAMP(next_run) AS next_run, notes, paused,
431 priority, queue, task, COUNT(*) OVER() AS total
432 FROM minion_schedules } .
433 ( @where ? 'WHERE ' . join( ' AND ', @where ) : '' ) .
434 q{ ORDER BY id DESC LIMIT ? OFFSET ?};
435 0 warn "List Schedules SQL: $query" if DEBUG;
436 0 my $schedules = $self->mysql->db->query( $query, @args, $limit, $offset )->expand->hashes->to_array;
437  
438 0 return _total('schedules', $schedules);
439 }
440  
441 0 ▶sub list_workers {
Subroutine list_workers: not called CC=4 SCAR=30.0
Pod documented
442 0 my ($self, $offset, $limit, $options) = @_;
443  
444 0 my ( @where, @params );
445 0 ▶ if ( my $ids = $options->{ids} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ids = $options->{"ids"}) 0 0 0
446 0 push @where, 'id in (' . join( ',', ('?') x @{$options->{ids}} ) . ')';
447 0 push @params, @{ $options->{ids} };
448 }
449 0 ▶ if ( my $id = $options->{before} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $options->{"before"}) 0 0 0
450 0 push @where, 'id < ?';
451 0 push @params, $id;
452 }
453  
454 0 my $db = $self->mysql->db;
455  
456 0 ▶ my $where = @where ? 'WHERE ' . join ' AND ', @where : '';
Branch: 1 branch
BranchTrueFalseTotal
@where ? : 0 0 0
457 0 my $sql = "SELECT
458 id, UNIX_TIMESTAMP(notified) AS notified, host, pid,
459 UNIX_TIMESTAMP(started) AS started, status
460 FROM minion_workers $where ORDER BY id DESC LIMIT ? OFFSET ?";
461 0 my $workers = $db->query($sql, @params, $limit, $offset)
462 ->hashes;
463  
464 # Add jobs to each worker
465 0 my $jobs_sql = q{SELECT id FROM minion_jobs WHERE state='active' AND worker=?};
466 0 ▶ $workers->map( sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
467 0 $_->{status} = decode_json( $_->{status} );
468 0 $_->{jobs} = $db->query($jobs_sql, $_->{id})->arrays->flatten->to_array
469 0 } );
470  
471 my $total = $db->query(
472 qq{SELECT COUNT(*) AS count FROM minion_workers $where}, @params
473 0 )->hash->{count};
474  
475 return {
476 0 workers => $workers,
477 total => $total,
478 };
479 }
480  
481 0 ▶sub list_locks {
Subroutine list_locks: not called CC=7 SCAR=40.3
Pod documented
482 0 my ($self, $offset, $limit, $options) = @_;
483  
484 0 my ( @where, @params );
485 0 ▶ if ( my $name = $options->{names} // $options->{name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $name = $options->{"names"} // $options->{"name"}) 0 0 0
Condition0%0/3
$options->{"names"} // $options->{"name"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$options->{"names"} // $options->{"name"}
$options->{"names"} $options->{"name"}
Truth table0%0/3
A // B
A= $options->{"names"}B= $options->{"name"}
ABresult
1X1
011
000
486 0 ▶ my @names = ref $name eq 'ARRAY' ? @$name : ( $name );
Branch: 1 branch
BranchTrueFalseTotal
ref $name eq 'ARRAY' ? : 0 0 0
487 0 push @where, 'name in (' . join( ',', ('?') x @names ) . ')';
488 0 push @params, @names;
489 }
490  
491 0 push @where, 'expires > now()';
492  
493 0 ▶ my $where = @where ? 'WHERE ' . join ' AND ', @where : '';
Branch: 1 branch
BranchTrueFalseTotal
@where ? : 0 0 0
494 0 my $sql = "SELECT
495 id, name, UNIX_TIMESTAMP(expires) AS expires
496 FROM minion_locks
497 $where
498 ORDER BY id
499 DESC LIMIT ? OFFSET ?";
500  
501 0 my $db = $self->mysql->db;
502  
503 0 ▶ my $locks = $db->query($sql, @params, $limit || 0, $offset || 0)->hashes;
Condition0%0/4
$limit || 0
l!l
00
$offset || 0
l!l
00
MC/DC0%0/1
$limit || 0
$limit
MC/DC0%0/1
$offset || 0
$offset
Truth table0%0/2
A
A= $limit
Aresult
11
00
Truth table0%0/2
A
A= $offset
Aresult
11
00
504  
505 my $total = $db->query(
506 "SELECT COUNT(name) AS total FROM minion_locks $where", @params
507 0 )->hash->{total};
508  
509 return {
510 0 locks => $locks,
511 total => $total,
512 };
513 }
514  
515 0 ▶sub new {
Subroutine new: not called CC=7 SCAR=40.3
Pod documented
516 0 my ( $class, @args ) = @_;
517 0 state $skip_migration = 0;
518  
519 0 my $mysql;
520 0 my $force_migration = 0;
521 0 ▶ if ( @args == 1 && blessed($args[0]) && $args[0]->isa('Mojo::mysql') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args == 1 and builtin::blessed($args[0]) and $args[0]->isa('Mojo::mysql')) { } 0 0 0
Condition0%0/6
@args == 1 and builtin::blessed($args[0]) and $args[0]->isa("Mojo::mysql")
!ll&&!rl&&r
000
@args == 1 and builtin::blessed($args[0])
!ll&&!rl&&r
000
MC/DC0%0/3
@args == 1 and builtin::blessed($args[0]) and $args[0]->isa("Mojo::mysql")
@args == 1 builtin::blessed($args[0]) $args[0]->isa("Mojo::mysql")
Truth table0%0/4
A and B and C
A= @args == 1B= builtin::blessed($args[0])C= $args[0]->isa("Mojo::mysql")
ABCresult
0XX0
10X0
1100
1111
522 0 $mysql = $args[0];
523 # We need to force an immediate migration if given a Mojo::mysql
524 # object, because the user may decide to add another migration after
525 # adding the Minion plugin.
526 0 $force_migration = 1;
527 }
528 else {
529 0 ▶ if ( ref $args[0] eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args[0] eq "HASH") 0 0 0
530 0 @args = %{ $args[0] };
531 }
532 0 $mysql = Mojo::mysql->new(@args);
533 }
534  
535 0 my $self = $class->SUPER::new(mysql => $mysql);
536  
537 0 ▶ if ( !$skip_migration ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($skip_migration) 0 0 0
538 0 ▶ if ($force_migration) {
Branch: 1 branch
BranchTrueFalseTotal
if ($force_migration) { } 0 0 0
539  
540 # First make sure any impending migrations happen
541 # before we overwrite them:
542 0 $mysql->migrations->migrate;
543  
544 # Then load this module's migrations and run them:
545 0 $mysql->migrations->name('minion')->from_data;
546 0 $mysql->migrations->migrate;
547 }
548 else {
549 # Load this module's migrations and run them
550 # the first time a DB connection is attempted:
551 0 $mysql->migrations->name('minion')->from_data;
552 0 ▶ $mysql->once(connection => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
553 0 my ( $mysql ) = @_;
554 0 $mysql->migrations->migrate;
555 0 });
556 }
557 }
558  
559 0 return $self;
560 }
561  
562 0 ▶sub register_worker {
Subroutine register_worker: not called CC=3 SCAR=24.8
Pod documented
563 0 my ($self, $id, $options) = @_;
564  
565 0 my $db = $self->mysql->db;
566 0 my $sql = q{INSERT INTO minion_workers (id, host, pid, status)
567 VALUES (?, ?, ?, ?)
568 ON DUPLICATE KEY UPDATE notified=NOW(), host=VALUES(host), pid=VALUES(pid), status=VALUES(status)};
569 0 ▶ my $res = $db->query($sql, $id, hostname, $$, encode_json( $options->{status} // {} ) );
Condition0%0/2
$options->{"status"} // {}
l!l
00
MC/DC0%0/1
$options->{"status"} // {}
$options->{"status"}
Truth table0%0/2
A
A= $options->{"status"}
Aresult
11
00
570  
571 0 ▶ return $id // $res->last_insert_id;
Condition0%0/3
$id // $res->last_insert_id
l!l&&r!l&&!r
000
MC/DC0%0/2
$id // $res->last_insert_id
$id $res->last_insert_id
Truth table0%0/3
A // B
A= $idB= $res->last_insert_id
ABresult
1X1
011
000
572 }
573  
574 0 ▶sub remove_job {
Subroutine remove_job: not called CC=1 SCAR=6.9
Pod documented
575 !!shift->mysql->db->query(
576 "delete minion_jobs, minion_jobs_depends from minion_jobs
577 left join minion_jobs_depends
578 on minion_jobs.id = minion_jobs_depends.parent_id
579 where minion_jobs.id = ? and minion_jobs.state in ('inactive', 'failed', 'finished')",
580 shift
581 0 )->{affected_rows};
582 }
583  
584 0 ▶sub repair {
Subroutine repair: not called CC=1 SCAR=6.9
Pod documented
585 0 my $self = shift;
586  
587 # Workers without heartbeats
588 0 my $db = $self->mysql->db;
589 0 my $minion = $self->minion;
590 0 $db->query(
591 "delete from minion_workers
592 where notified < DATE_SUB(NOW(), INTERVAL ? SECOND)",
593 $minion->missing_after
594 );
595  
596 # Old jobs with no unresolved dependencies
597 0 $db->query(
598 q{
599 DELETE job
600 FROM minion_jobs job
601 LEFT JOIN minion_jobs_depends depends ON depends.parent_id = job.id
602 LEFT JOIN minion_jobs child ON child.id = depends.child_id AND child.state != 'finished'
603 WHERE job.state = 'finished'
604 AND job.`finished` <= DATE_SUB(NOW(), INTERVAL ? SECOND)
605 AND child.id IS NULL
606 },
607 $minion->remove_after,
608 );
609  
610 # Old expired jobs
611 0 $db->query(
612 q{
613 DELETE FROM minion_jobs
614 WHERE state = 'inactive' AND expires <= NOW()
615 },
616 );
617  
618 # Jobs with missing worker (can be retried)
619 $db->query(
620 "select job.id, job.retries from minion_jobs job
621 left join minion_workers worker on job.worker = worker.id
622 where job.state = 'active' and job.queue != 'minion_foreground'
623 and worker.id is null"
624 0 ▶ )->hashes->each(sub { $self->fail_job(@$_{qw(id retries)}, 'Worker went away') });
Subroutine __ANON__: not called CC=1 SCAR=6.9
625  
626 # Jobs in queue without workers or not enough workers (cannot be retried and requires admin attention)
627 0 $db->query(
628 q{update minion_jobs set state = 'failed', result = '"Job appears stuck in queue"'
629 where state = 'inactive' and DATE_ADD( `delayed`, interval ? second ) < now()}, $minion->stuck_after
630 );
631  
632 }
633  
634 0 ▶sub reset {
Subroutine reset: not called CC=4 SCAR=30.0
Pod documented
635 0 ▶ my ($self, $options) = (shift, shift // {});
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
636  
637 0 my $db = $self->mysql->db;
638 0 ▶ if ( $options->{all} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($options->{'all'}) { } 0 0 0
elsif ($options->{'locks'}) { } 0 0 0
639 0 $db->query("delete from minion_jobs");
640 0 $db->query("ALTER TABLE minion_jobs AUTO_INCREMENT = 1");
641 0 $db->query("truncate table minion_locks");
642 0 $db->query("ALTER TABLE minion_locks AUTO_INCREMENT = 1");
643 0 $db->query("truncate table minion_jobs_depends");
644 0 $db->query("truncate table minion_notes");
645 0 $db->query("DELETE FROM minion_workers");
646 0 $db->query("ALTER TABLE minion_workers AUTO_INCREMENT = 1");
647 0 $db->query("DELETE FROM minion_schedules");
648 0 $db->query("ALTER TABLE minion_schedules AUTO_INCREMENT = 1");
649 }
650 elsif ( $options->{locks} ) {
651 0 $db->query("truncate table minion_locks");
652 0 $db->query("ALTER TABLE minion_locks AUTO_INCREMENT = 1");
653 }
654 }
655  
656 0 ▶sub lock {
Subroutine lock: not called CC=3 SCAR=24.8
Pod documented
657 0 ▶ my ($self, $name, $duration, $options) = (shift, shift, shift, shift // {});
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
658 return !!$self->mysql->db->query('SELECT minion_lock(?, ?, ?)',
659 0 ▶ $name, $duration, $options->{limit} || 1)->array->[0];
Condition0%0/2
$options->{'limit'} || 1
l!l
00
MC/DC0%0/1
$options->{'limit'} || 1
$options->{'limit'}
Truth table0%0/2
A
A= $options->{'limit'}
Aresult
11
00
660 }
661  
662 0 ▶sub unlock {
Subroutine unlock: not called CC=1 SCAR=6.9
Pod documented
663 !!shift->mysql->db->query(
664 0 'DELETE FROM minion_locks
665 WHERE expires > NOW() AND name = ? ORDER BY EXPIRES
666 LIMIT 1', shift
667 )->rows;
668 }
669  
670 0 ▶sub retry_job {
Subroutine retry_job: not called CC=7 SCAR=40.3
Pod documented
671 0 my ($self, $id, $retries) = (shift, shift, shift);
672 0 my $db = $self->mysql->db;
673 0 ▶ my $options = shift // {};
Condition0%0/2
shift() // {}
l!l
00
MC/DC0%0/1
shift() // {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
674  
675 0 ▶ if ( my $parents = delete $options->{ parents } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $parents = delete $options->{"parents"}) 0 0 0
676 0 $db->query(
677 'DELETE FROM `minion_jobs_depends` WHERE child_id=?',
678 $id,
679 );
680 0 ▶ if ( @$parents ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$parents) 0 0 0
681 $db->query(
682 "INSERT INTO minion_jobs_depends (`parent_id`, `child_id`) VALUES "
683 . join( ", ", map "( ?, ? )", @$parents ),
684 0 map { $_, $id } @$parents
685 );
686 }
687 }
688  
689 return !!$db->query(
690 "UPDATE `minion_jobs`
691 SET attempts = COALESCE(?, attempts),
692 `delayed` = DATE_ADD(NOW(), INTERVAL ? SECOND),
693 expires = case when ? is not null then date_add( now(), interval ? second ) else expires end,
694 lax = coalesce(?, lax),
695 priority = COALESCE(?, priority), queue = COALESCE(?, queue),
696 retried = NOW(), retries = retries + 1, state = 'inactive'
697 WHERE id = ? AND retries = ?",
698 $options->{attempts}, $options->{delay} // 0, ($options->{expire})x2,
699 exists $options->{lax} ? $options->{lax} ? 1 : 0 : undef,
700 @$options{qw(priority queue)}, $id, $retries
701 0 ▶ )->{affected_rows};
Branch: 2 branches
BranchTrueFalseTotal
exists $options->{'lax'} ? : 0 0 0
$options->{'lax'} ? : 0 0 0
Condition0%0/2
$options->{"delay"} // 0
l!l
00
MC/DC0%0/1
$options->{"delay"} // 0
$options->{"delay"}
Truth table0%0/2
A
A= $options->{"delay"}
Aresult
11
00
702 }
703  
704 0 ▶sub stats {
Subroutine stats: not called CC=5 SCAR=34.0
Pod documented
705 0 my $self = shift;
706  
707 0 my %stats = map { $_ => 0 } qw(
708 active_workers inactive_workers workers active_jobs inactive_jobs failed_jobs finished_jobs
709 enqueued_jobs delayed_jobs active_locks uptime
710 );
711  
712 0 my $db = $self->mysql->db;
713  
714 # Worker statistics
715 0 my $worker_sql = q{
716 SELECT
717 SUM(job.id IS NOT NULL) AS is_active
718 FROM minion_workers worker
719 LEFT JOIN minion_jobs job
720 ON worker.id = job.worker
721 AND job.state = 'active'
722 GROUP BY worker.id
723 };
724 0 my $res = $db->query( $worker_sql );
725 0 ▶ while ( my $row = $res->hash ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $res->hash) 0 0 0
726 0 ▶ $stats{ $row->{is_active} ? 'active_workers' : 'inactive_workers' }++;
Branch: 1 branch
BranchTrueFalseTotal
$row->{'is_active'} ? : 0 0 0
727 }
728 0 $stats{workers} = $stats{active_workers} + $stats{inactive_workers};
729  
730 # Job statistics
731 0 my $job_sql = q{
732 SELECT
733 minion_jobs.state,
734 COUNT(minion_jobs.state) AS jobs,
735 SUM(minion_jobs.`delayed` > NOW()) AS `delayed`
736 FROM minion_jobs
737 GROUP BY minion_jobs.state
738 };
739 0 $res = $db->query( $job_sql );
740 0 ▶ while ( my $row = $res->hash ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $res->hash) 0 0 0
741 0 my $state = $row->{state};
742 0 $stats{ "${state}_jobs" } += $row->{jobs};
743 0 $stats{ enqueued_jobs } += $row->{jobs};
744 0 ▶ if ( $state eq 'inactive' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($state eq "inactive") 0 0 0
745 0 $stats{ delayed_jobs } += $row->{delayed};
746 }
747 }
748  
749 0 $stats{active_locks} = $db->query("SELECT COUNT(*) FROM minion_locks WHERE expires > now()")->array->[0];
750 0 $stats{uptime} = $db->query( "SHOW GLOBAL STATUS LIKE 'Uptime'" )->hash->{Value};
751  
752 0 my $new_stats = $db->query(q{
753 SELECT
754 (SELECT COUNT(*) FROM minion_schedules WHERE NOT paused) AS schedules,
755 (SELECT COUNT(*) FROM minion_schedules WHERE paused) AS inactive_schedules
756 },
757 )->hash;
758 0 %stats = (%stats, %$new_stats);
759  
760 0 return \%stats;
761 }
762  
763 0 ▶sub unregister_worker {
Subroutine unregister_worker: not called CC=1 SCAR=6.9
Pod documented
764 0 shift->mysql->db->query('delete from minion_workers where id = ?', shift);
765 }
766  
767 0 ▶sub _set_paused {
Subroutine _set_paused: not called CC=1 SCAR=6.9
768 0 my ($self, $name, $paused) = @_;
769 0 return $self->mysql->db->query('UPDATE minion_schedules SET paused = ? WHERE name = ?', $paused, $name)->rows;
770 }
771 0 ▶sub pause_schedule { shift->_set_paused(shift, 1) }
Subroutine pause_schedule: not called CC=1 SCAR=6.9
Pod documented
772 0 ▶sub resume_schedule { shift->_set_paused(shift, 0) }
Subroutine resume_schedule: not called CC=1 SCAR=6.9
Pod documented
773  
774 0 ▶sub _fetch_jobs {
Subroutine _fetch_jobs: not called CC=6 SCAR=37.4
775 0 my ($self, $worker_id, $options) = @_;
776  
777 # The tasks this worker can perform
778 0 ▶ my $tasks = $options->{tasks} // [keys %{$self->minion->tasks}];
Condition0%0/2
$options->{"tasks"} // [keys %{$self->minion->tasks;}]
l!l
00
MC/DC0%0/1
$options->{"tasks"} // [keys %{$self->minion->tasks;}]
$options->{"tasks"}
Truth table0%0/2
A
A= $options->{"tasks"}
Aresult
11
00
779 # The queues this worker is watching
780 0 ▶ my $queues = $options->{queues} // ['default'];
Condition0%0/2
$options->{"queues"} // ["default"]
l!l
00
MC/DC0%0/1
$options->{"queues"} // ["default"]
$options->{"queues"}
Truth table0%0/2
A
A= $options->{"queues"}
Aresult
11
00
781  
782 0 my $qq = join ", ", map({ "?" } @$queues);
783 0 my $qt = join ", ", map({ "?" } @$tasks );
784 0 my @bind_vars = ( @$queues, @$tasks );
785  
786 0 my @where = ();
787 0 ▶ if ( defined $options->{id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"id"}) 0 0 0
788 0 push @where, 'job.id = ?';
789 0 push @bind_vars, $options->{id};
790 }
791 0 ▶ if (defined $options->{min_priority}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"min_priority"}) 0 0 0
792 0 push @where, 'job.priority >= ?';
793 0 push @bind_vars, $options->{min_priority};
794 }
795 0 ▶ my $sql_where = @where ? join( ' AND ', '', @where ) : '';
Branch: 1 branch
BranchTrueFalseTotal
@where ? : 0 0 0
796  
797 # The dependencies table stores a copy of the parent job's state and
798 # expiration (updated automatically via triggers). We use this to roll
799 # up a count of pending and failed parent jobs for the current child
800 # job. If there are no pending jobs, or if the current child job is
801 # "lax" and there are only failed jobs, the child job is ready.
802 # An expired job is considered "failed" for this check.
803 0 my $sql = qq{
804 SELECT job.id, job.args, job.retries, job.task
805 FROM minion_jobs job
806 LEFT JOIN (
807 SELECT depends.child_id, COUNT(depends.child_id) AS pending,
808 COALESCE( SUM(depends.state = 'failed' OR (depends.expires IS NOT NULL AND depends.expires <= NOW())), 0 ) AS failed
809 FROM minion_jobs_depends depends
810 WHERE depends.state IS NOT NULL AND (
811 depends.state = 'active'
812 OR ( depends.state = 'failed' )
813 OR ( depends.state = 'inactive' AND (depends.expires IS NULL OR depends.expires > NOW()))
814 )
815 GROUP BY depends.child_id
816 ) depends ON depends.child_id = job.id
817 WHERE job.state = 'inactive'
818 AND job.`delayed` <= NOW()
819 AND job.queue IN ($qq) AND job.task IN ($qt)
820 $sql_where
821 AND (job.expires IS NULL OR job.expires > NOW())
822 AND (
823 depends.pending IS NULL
824 OR ( depends.pending = depends.failed AND job.lax )
825 )
826 ORDER BY job.priority DESC, job.created
827 LIMIT $PREFETCH
828 };
829  
830 0 warn "Dequeuing SQL: $sql" if DEBUG;
831 0 my $db = $self->mysql->db;
832 0 return $db->query($sql, @bind_vars)->hashes;
833 }
834  
835 0 ▶sub _update {
Subroutine _update: not called CC=5 SCAR=34.0
836 0 my ($self, $fail, $id, $retries, $result) = @_;
837 my $updated = $self->mysql->db->query(
838 "update minion_jobs
839 set finished = now(), result = ?, state = ?
840 where id = ? and retries = ? and state = 'active'",
841 encode_json($result), $fail ? 'failed' : 'finished', $id,
842 $retries
843 0 ▶ )->{affected_rows};
Branch: 1 branch
BranchTrueFalseTotal
$fail ? : 0 0 0
844 #; say "Updated $updated job rows (id: $id, fail: $fail, result: @{[encode_json( $result )]})";
845 0 ▶ return undef unless $updated;
Branch: 1 branch
BranchTrueFalseTotal
unless $updated 0 0 0
846  
847 0 ▶ return 1 if !$fail; # finished
Branch: 1 branch
BranchTrueFalseTotal
unless $fail 0 0 0
848  
849 0 my $job = $self->list_jobs( 0, 1, { ids => [$id] } )->{jobs}[0];
850 0 ▶ return $fail ? $self->auto_retry_job($id, $retries, $job->{attempts}) : 1;
Branch: 1 branch
BranchTrueFalseTotal
$fail ? : 0 0 0
851 }
852  
853 0 ▶sub broadcast {
Subroutine broadcast: not called CC=5 SCAR=34.0
Pod documented
854 0 ▶ my ($self, $command, $args, $ids) = (shift, shift, shift || [], shift || []);
Condition0%0/4
shift() || []
l!l
00
shift() || []
l!l
00
MC/DC0%0/1
shift() || []
shift()
MC/DC0%0/1
shift() || []
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
Truth table0%0/2
A
A= shift()
Aresult
11
00
855  
856 0 my $db = $self->mysql->db;
857  
858 0 my $message = encode_json( [ $command, @$args ] );
859 0 ▶ if ( !@$ids ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$ids) 0 0 0
860 0 @$ids = map { $_->{id} }
861 0 @{ $db->query( 'SELECT id FROM minion_workers' )->hashes },
862 }
863 0 my $rows = 0;
864 0 for my $id ( @$ids ) {
865 0 $rows += $db->query(
866 'INSERT INTO minion_workers_inbox ( worker_id, message ) VALUES ( ?, ? )',
867 $id, $message,
868 )->rows;
869 }
870 0 return $rows;
871 }
872  
873 0 ▶sub receive {
Subroutine receive: not called CC=3 SCAR=24.8
Pod documented
874 0 my ($self, $worker_id) = @_;
875 #; use Data::Dumper;
876 0 my $db = $self->mysql->db;
877 0 my $rows = $db->query(
878 'SELECT id, message FROM minion_workers_inbox WHERE worker_id=?', $worker_id,
879 )->hashes;
880 0 ▶ return [] unless $rows && @$rows;
Branch: 1 branch
BranchTrueFalseTotal
unless $rows and @$rows 0 0 0
Condition0%0/3
$rows and @$rows
!ll&&!rl&&r
000
MC/DC0%0/2
$rows and @$rows
$rows @$rows
Truth table0%0/3
A and B
A= $rowsB= @$rows
ABresult
0X0
100
111
881 #; say Dumper $rows;
882 0 my @ids = map { $_->{id} } @$rows;
883 #; say Dumper \@ids;
884 0 $db->query(
885 'DELETE FROM minion_workers_inbox WHERE id IN (' . ( join ", ", ( '?' ) x @ids ) . ')',
886 @ids,
887 );
888 0 return [ map { decode_json( $_->{message} ) } @$rows ];
889 }
890  
891 0 ▶sub schedule {
Subroutine schedule: not called CC=8 SCAR=42.8
Pod documented
892 0 ▶ my ($self, $name, $cron, $task, $args, $options) = (shift, shift, shift, shift, shift || [], shift || {});
Condition0%0/4
shift() || []
l!l
00
shift() || {}
l!l
00
MC/DC0%0/1
shift() || []
shift()
MC/DC0%0/1
shift() || {}
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
Truth table0%0/2
A
A= shift()
Aresult
11
00
893  
894 0 my $db = $self->mysql->db;
895 0 my $next = next_cron_time $cron, $db->query('SELECT UNIX_TIMESTAMP()')->array->[0];
896  
897 return $db->query(
898 q{INSERT INTO minion_schedules (args, attempts, cron, expire, lax, name, next_run, notes, priority, queue, task)
899 VALUES (?, ?, ?, ?, ?, ?, FROM_UNIXTIME(?), ?, ?, ?, ?)
900 ON DUPLICATE KEY UPDATE
901 -- next_run must be set before cron so we can tell the difference --
902 next_run = CASE WHEN cron = VALUES(cron) THEN next_run ELSE VALUES(next_run) END,
903 args = VALUES(args), attempts = VALUES(attempts), cron = VALUES(cron), expire = VALUES(expire),
904 lax = VALUES(lax), notes = VALUES(notes), priority = VALUES(priority), queue = VALUES(queue),
905 task = VALUES(task)
906 }, encode_json($args), $options->{attempts} // 1, $cron, $options->{expire}, $options->{lax} ? 1 : 0,
907 0 ▶ $name, $next, encode_json($options->{notes} || {}), $options->{priority} // 0, $options->{queue} // 'default', $task
Branch: 1 branch
BranchTrueFalseTotal
$options->{'lax'} ? : 0 0 0
Condition0%0/8
$options->{"attempts"} // 1
l!l
00
$options->{'notes'} || {}
l!l
00
$options->{"priority"} // 0
l!l
00
$options->{"queue"} // "default"
l!l
00
MC/DC0%0/1
$options->{"attempts"} // 1
$options->{"attempts"}
MC/DC0%0/1
$options->{'notes'} || {}
$options->{'notes'}
MC/DC0%0/1
$options->{"priority"} // 0
$options->{"priority"}
MC/DC0%0/1
$options->{"queue"} // "default"
$options->{"queue"}
Truth table0%0/2
A
A= $options->{"attempts"}
Aresult
11
00
Truth table0%0/2
A
A= $options->{'notes'}
Aresult
11
00
Truth table0%0/2
A
A= $options->{"priority"}
Aresult
11
00
Truth table0%0/2
A
A= $options->{"queue"}
Aresult
11
00
908 )->last_insert_id
909 }
910  
911 0 ▶sub unschedule {
Subroutine unschedule: not called CC=1 SCAR=6.9
Pod documented
912 0 return shift->mysql->db->query('DELETE FROM minion_schedules WHERE name = ?', shift)->rows > 0;
913 }
914  
915 0 ▶sub _total {
Subroutine _total: not called CC=3 SCAR=24.8
916 0 my ($name, $results) = @_;
917 0 ▶ my $total = @$results ? $results->[0]{total} : 0;
Branch: 1 branch
BranchTrueFalseTotal
@$results ? : 0 0 0
918 0 delete $_->{total} for @$results;
919 0 return {total => $total, $name => $results};
920 }
921  
922 {
923 package
924 Minion::Backend::mysql::_guard;
925 0 ▶ sub new { bless $_[1], $_[0] }
Subroutine new: not called CC=1 SCAR=6.9
926 0 ▶ sub DESTROY { shift->() }
Subroutine DESTROY: not called CC=1 SCAR=6.9
927 }
928  
929 1 1;
930  
931 #pod =encoding utf8
932 #pod
933 #pod =head1 NAME
934 #pod
935 #pod Minion::Backend::mysql - MySQL backend
936 #pod
937 #pod =head1 SYNOPSIS
938 #pod
939 #pod use Mojolicious::Lite;
940 #pod
941 #pod plugin Minion => {mysql => 'mysql://user@127.0.0.1/minion_jobs'};
942 #pod
943 #pod # Slow task
944 #pod app->minion->add_task(poke_mojo => sub {
945 #pod my $job = shift;
946 #pod $job->app->ua->get('mojolicio.us');
947 #pod $job->app->log->debug('We have poked mojolicio.us for a visitor');
948 #pod });
949 #pod
950 #pod # Perform job in a background worker process
951 #pod get '/' => sub {
952 #pod my $c = shift;
953 #pod $c->minion->enqueue('poke_mojo');
954 #pod $c->render(text => 'We will poke mojolicio.us for you soon.');
955 #pod };
956 #pod
957 #pod app->start;
958 #pod
959 #pod =head1 DESCRIPTION
960 #pod
961 #pod L<Minion::Backend::mysql> is a backend for L<Minion> based on L<Mojo::mysql>. All
962 #pod necessary tables will be created automatically with a set of migrations named
963 #pod C<minion>. This backend requires at least v5.6.5 of MySQL.
964 #pod
965 #pod =head1 ATTRIBUTES
966 #pod
967 #pod L<Minion::Backend::mysql> inherits all attributes from L<Minion::Backend> and
968 #pod implements the following new ones.
969 #pod
970 #pod =head2 mysql
971 #pod
972 #pod my $mysql = $backend->mysql;
973 #pod $backend = $backend->mysql(Mojo::mysql->new);
974 #pod
975 #pod L<Mojo::mysql> object used to store all data.
976 #pod
977 #pod =head2 no_txn
978 #pod
979 #pod If true, will not make a transaction around the L</enqueue> insertions
980 #pod when a job has parent jobs. Without a transaction, the job could be
981 #pod dequeued before its parent relationships are written to the database.
982 #pod However, since MySQL does not support nested transactions (despite
983 #pod supporting something almost exactly like them...), you can disable
984 #pod transactions for testing by setting this attribute (if you perform your
985 #pod tests in a transaction so they can be rolled back when the test is
986 #pod complete).
987 #pod
988 #pod =head1 METHODS
989 #pod
990 #pod L<Minion::Backend::mysql> inherits all methods from L<Minion::Backend> and
991 #pod implements the following new ones.
992 #pod
993 #pod =head2 dequeue
994 #pod
995 #pod my $job_info = $backend->dequeue($worker_id, 0.5);
996 #pod my $job_info = $backend->dequeue($worker_id, 0.5, {queues => ['important']});
997 #pod
998 #pod Wait for job, dequeue it and transition from C<inactive> to C<active> state or
999 #pod return C<undef> if queues were empty.
1000 #pod
1001 #pod These options are currently available:
1002 #pod
1003 #pod =over 2
1004 #pod
1005 #pod =item min_priority
1006 #pod
1007 #pod min_priority => 3
1008 #pod
1009 #pod Do not dequeue jobs with a lower priority.
1010 #pod
1011 #pod =item queues
1012 #pod
1013 #pod queues => ['important']
1014 #pod
1015 #pod One or more queues to dequeue jobs from, defaults to C<default>.
1016 #pod
1017 #pod =item tasks
1018 #pod
1019 #pod tasks => ['foo', 'bar']
1020 #pod
1021 #pod One or more tasks to dequeue jobs for, defaults to all tasks.
1022 #pod
1023 #pod =back
1024 #pod
1025 #pod These fields are currently available:
1026 #pod
1027 #pod =over 2
1028 #pod
1029 #pod =item args
1030 #pod
1031 #pod args => ['foo', 'bar']
1032 #pod
1033 #pod Job arguments.
1034 #pod
1035 #pod =item id
1036 #pod
1037 #pod id => '10023'
1038 #pod
1039 #pod Job ID.
1040 #pod
1041 #pod =item retries
1042 #pod
1043 #pod retries => 3
1044 #pod
1045 #pod Number of times job has been retried.
1046 #pod
1047 #pod =item task
1048 #pod
1049 #pod task => 'foo'
1050 #pod
1051 #pod Task name.
1052 #pod
1053 #pod =back
1054 #pod
1055 #pod =head2 dispatch_schedules
1056 #pod
1057 #pod my $dispatched = $backend->dispatch_schedules;
1058 #pod
1059 #pod Enqueue jobs for all schedules whose firing time has been reached, advance their firing times to the next match, and
1060 #pod return information about each dispatch as an array reference. A Postgres advisory lock is held for the duration of the
1061 #pod dispatch cycle so that multiple workers ticking at the same time will not produce duplicate enqueues.
1062 #pod
1063 #pod Each entry contains C<id>, C<job> and C<name>.
1064 #pod
1065 #pod =head2 enqueue
1066 #pod
1067 #pod my $job_id = $backend->enqueue('foo');
1068 #pod my $job_id = $backend->enqueue(foo => [@args]);
1069 #pod my $job_id = $backend->enqueue(foo => [@args] => {priority => 1});
1070 #pod
1071 #pod Enqueue a new job with C<inactive> state.
1072 #pod
1073 #pod These options are currently available:
1074 #pod
1075 #pod =over 2
1076 #pod
1077 #pod =item attempts
1078 #pod
1079 #pod attempts => 25
1080 #pod
1081 #pod Number of times performing this job will be attempted, with a delay based on L<Minion/"backoff"> after the first
1082 #pod attempt, defaults to C<1>.
1083 #pod
1084 #pod =item delay
1085 #pod
1086 #pod delay => 10
1087 #pod
1088 #pod Delay job for this many seconds (from now).
1089 #pod
1090 #pod =item expire
1091 #pod
1092 #pod expire => 300
1093 #pod
1094 #pod Job is valid for this many seconds (from now) before it expires.
1095 #pod
1096 #pod =item lax
1097 #pod
1098 #pod lax => 1
1099 #pod
1100 #pod Existing jobs this job depends on may also have transitioned to the C<failed> state to allow for it to be processed,
1101 #pod defaults to C<false>.
1102 #pod
1103 #pod =item notes
1104 #pod
1105 #pod notes => {foo => 'bar', baz => [1, 2, 3]}
1106 #pod
1107 #pod Hash reference with arbitrary metadata for this job.
1108 #pod
1109 #pod =item parents
1110 #pod
1111 #pod parents => [$id1, $id2, $id3]
1112 #pod
1113 #pod One or more existing jobs this job depends on, and that need to have transitioned to the state C<finished> before it
1114 #pod can be processed.
1115 #pod
1116 #pod =item priority
1117 #pod
1118 #pod priority => 5
1119 #pod
1120 #pod Job priority, defaults to C<0>.
1121 #pod
1122 #pod =item queue
1123 #pod
1124 #pod queue => 'important'
1125 #pod
1126 #pod Queue to put job in, defaults to C<default>.
1127 #pod
1128 #pod =back
1129 #pod
1130 #pod =head2 fail_job
1131 #pod
1132 #pod my $bool = $backend->fail_job($job_id, $retries);
1133 #pod my $bool = $backend->fail_job($job_id, $retries, 'Something went wrong!');
1134 #pod my $bool = $backend->fail_job(
1135 #pod $job_id, $retries, {msg => 'Something went wrong!'});
1136 #pod
1137 #pod Transition from C<active> to C<failed> state.
1138 #pod
1139 #pod =head2 finish_job
1140 #pod
1141 #pod my $bool = $backend->finish_job($job_id, $retries);
1142 #pod my $bool = $backend->finish_job($job_id, $retries, 'All went well!');
1143 #pod my $bool = $backend->finish_job($job_id, $retries, {msg => 'All went well!'});
1144 #pod
1145 #pod Transition from C<active> to C<finished> state.
1146 #pod
1147 #pod =head2 job_info
1148 #pod
1149 #pod my $job_info = $backend->job_info($job_id);
1150 #pod
1151 #pod Get information about a job or return C<undef> if job does not exist.
1152 #pod
1153 #pod # Check job state
1154 #pod my $state = $backend->job_info($job_id)->{state};
1155 #pod
1156 #pod # Get job result
1157 #pod my $result = $backend->job_info($job_id)->{result};
1158 #pod
1159 #pod These fields are currently available:
1160 #pod
1161 #pod =over 2
1162 #pod
1163 #pod =item args
1164 #pod
1165 #pod args => ['foo', 'bar']
1166 #pod
1167 #pod Job arguments.
1168 #pod
1169 #pod =item created
1170 #pod
1171 #pod created => 784111777
1172 #pod
1173 #pod Time job was created.
1174 #pod
1175 #pod =item delayed
1176 #pod
1177 #pod delayed => 784111777
1178 #pod
1179 #pod Time job was delayed to.
1180 #pod
1181 #pod =item finished
1182 #pod
1183 #pod finished => 784111777
1184 #pod
1185 #pod Time job was finished.
1186 #pod
1187 #pod =item priority
1188 #pod
1189 #pod priority => 3
1190 #pod
1191 #pod Job priority.
1192 #pod
1193 #pod =item queue
1194 #pod
1195 #pod queue => 'important'
1196 #pod
1197 #pod Queue name.
1198 #pod
1199 #pod =item result
1200 #pod
1201 #pod result => 'All went well!'
1202 #pod
1203 #pod Job result.
1204 #pod
1205 #pod =item retried
1206 #pod
1207 #pod retried => 784111777
1208 #pod
1209 #pod Time job has been retried.
1210 #pod
1211 #pod =item retries
1212 #pod
1213 #pod retries => 3
1214 #pod
1215 #pod Number of times job has been retried.
1216 #pod
1217 #pod =item started
1218 #pod
1219 #pod started => 784111777
1220 #pod
1221 #pod Time job was started.
1222 #pod
1223 #pod =item state
1224 #pod
1225 #pod state => 'inactive'
1226 #pod
1227 #pod Current job state, usually C<active>, C<failed>, C<finished> or C<inactive>.
1228 #pod
1229 #pod =item task
1230 #pod
1231 #pod task => 'foo'
1232 #pod
1233 #pod Task name.
1234 #pod
1235 #pod =item worker
1236 #pod
1237 #pod worker => '154'
1238 #pod
1239 #pod Id of worker that is processing the job.
1240 #pod
1241 #pod =back
1242 #pod
1243 #pod =head2 list_jobs
1244 #pod
1245 #pod my $batch = $backend->list_jobs($offset, $limit);
1246 #pod my $batch = $backend->list_jobs($offset, $limit, {states => 'inactive'});
1247 #pod
1248 #pod Returns the same information as L</"job_info"> but in batches.
1249 #pod
1250 #pod These options are currently available:
1251 #pod
1252 #pod =over 2
1253 #pod
1254 #pod =item state
1255 #pod
1256 #pod state => 'inactive'
1257 #pod
1258 #pod List only jobs in this state.
1259 #pod
1260 #pod =item task
1261 #pod
1262 #pod task => 'test'
1263 #pod
1264 #pod List only jobs for this task.
1265 #pod
1266 #pod =back
1267 #pod
1268 #pod =head2 list_schedules
1269 #pod
1270 #pod my $results = $backend->list_schedules($offset, $limit);
1271 #pod my $results = $backend->list_schedules($offset, $limit, {names => ['daily']});
1272 #pod
1273 #pod Returns information about schedules in batches.
1274 #pod
1275 #pod # Get the total number of results (without limit)
1276 #pod my $num = $backend->list_schedules(0, 100)->{total};
1277 #pod
1278 #pod # Check next firing time
1279 #pod my $results = $backend->list_schedules(0, 1, {names => ['daily']});
1280 #pod my $next = $results->{schedules}[0]{next_run};
1281 #pod
1282 #pod These options are currently available:
1283 #pod
1284 #pod =over 2
1285 #pod
1286 #pod =item before
1287 #pod
1288 #pod before => 23
1289 #pod
1290 #pod List only schedules before this id.
1291 #pod
1292 #pod =item ids
1293 #pod
1294 #pod ids => ['23', '24']
1295 #pod
1296 #pod List only schedules with these ids.
1297 #pod
1298 #pod =item names
1299 #pod
1300 #pod names => ['foo', 'bar']
1301 #pod
1302 #pod List only schedules with these names.
1303 #pod
1304 #pod =back
1305 #pod
1306 #pod These fields are currently available:
1307 #pod
1308 #pod =over 2
1309 #pod
1310 #pod =item args
1311 #pod
1312 #pod args => ['foo', 'bar']
1313 #pod
1314 #pod Job arguments used for each enqueued job.
1315 #pod
1316 #pod =item attempts
1317 #pod
1318 #pod attempts => 25
1319 #pod
1320 #pod Number of attempts each enqueued job will get.
1321 #pod
1322 #pod =item created
1323 #pod
1324 #pod created => 784111777
1325 #pod
1326 #pod Epoch time the schedule was created.
1327 #pod
1328 #pod =item cron
1329 #pod
1330 #pod cron => '0 9 * * 1-5'
1331 #pod
1332 #pod Cron expression.
1333 #pod
1334 #pod =item expire
1335 #pod
1336 #pod expire => 300
1337 #pod
1338 #pod Expiration in seconds for each enqueued job.
1339 #pod
1340 #pod =item id
1341 #pod
1342 #pod id => 23
1343 #pod
1344 #pod Schedule id.
1345 #pod
1346 #pod =item last_job
1347 #pod
1348 #pod last_job => '10025'
1349 #pod
1350 #pod Id of the most recently enqueued job, or C<undef> if the schedule has not fired yet.
1351 #pod
1352 #pod =item last_run
1353 #pod
1354 #pod last_run => 784111777
1355 #pod
1356 #pod Epoch time the schedule last fired, or C<undef> if it has not fired yet.
1357 #pod
1358 #pod =item lax
1359 #pod
1360 #pod lax => 0
1361 #pod
1362 #pod Lax dependency setting for each enqueued job.
1363 #pod
1364 #pod =item name
1365 #pod
1366 #pod name => 'daily'
1367 #pod
1368 #pod Schedule name.
1369 #pod
1370 #pod =item next_run
1371 #pod
1372 #pod next_run => 784111777
1373 #pod
1374 #pod Epoch time the schedule will fire next.
1375 #pod
1376 #pod =item notes
1377 #pod
1378 #pod notes => {foo => 'bar'}
1379 #pod
1380 #pod Hash reference with arbitrary metadata applied to each enqueued job.
1381 #pod
1382 #pod =item paused
1383 #pod
1384 #pod paused => 0
1385 #pod
1386 #pod True if the schedule is paused and will not fire.
1387 #pod
1388 #pod =item priority
1389 #pod
1390 #pod priority => 0
1391 #pod
1392 #pod Priority of each enqueued job.
1393 #pod
1394 #pod =item queue
1395 #pod
1396 #pod queue => 'default'
1397 #pod
1398 #pod Queue each enqueued job is placed in.
1399 #pod
1400 #pod =item task
1401 #pod
1402 #pod task => 'foo'
1403 #pod
1404 #pod Task name.
1405 #pod
1406 #pod =back
1407 #pod
1408 #pod =head2 list_workers
1409 #pod
1410 #pod my $results = $backend->list_workers($offset, $limit);
1411 #pod my $results = $backend->list_workers($offset, $limit, {ids => [23]});
1412 #pod
1413 #pod Returns information about workers in batches.
1414 #pod
1415 #pod # Get the total number of results (without limit)
1416 #pod my $num = $backend->list_workers(0, 100)->{total};
1417 #pod
1418 #pod # Check worker host
1419 #pod my $results = $backend->list_workers(0, 1, {ids => [$worker_id]});
1420 #pod my $host = $results->{workers}[0]{host};
1421 #pod
1422 #pod These options are currently available:
1423 #pod
1424 #pod =over 2
1425 #pod
1426 #pod =item before
1427 #pod
1428 #pod before => 23
1429 #pod
1430 #pod List only workers before this id.
1431 #pod
1432 #pod =item ids
1433 #pod
1434 #pod ids => ['23', '24']
1435 #pod
1436 #pod List only workers with these ids.
1437 #pod
1438 #pod =back
1439 #pod
1440 #pod These fields are currently available:
1441 #pod
1442 #pod =over 2
1443 #pod
1444 #pod =item id
1445 #pod
1446 #pod id => 22
1447 #pod
1448 #pod Worker id.
1449 #pod
1450 #pod =item host
1451 #pod
1452 #pod host => 'localhost'
1453 #pod
1454 #pod Worker host.
1455 #pod
1456 #pod =item jobs
1457 #pod
1458 #pod jobs => ['10023', '10024', '10025', '10029']
1459 #pod
1460 #pod Ids of jobs the worker is currently processing.
1461 #pod
1462 #pod =item notified
1463 #pod
1464 #pod notified => 784111777
1465 #pod
1466 #pod Epoch time worker sent the last heartbeat.
1467 #pod
1468 #pod =item pid
1469 #pod
1470 #pod pid => 12345
1471 #pod
1472 #pod Process id of worker.
1473 #pod
1474 #pod =item started
1475 #pod
1476 #pod started => 784111777
1477 #pod
1478 #pod Epoch time worker was started.
1479 #pod
1480 #pod =item status
1481 #pod
1482 #pod status => {queues => ['default', 'important']}
1483 #pod
1484 #pod Hash reference with whatever status information the worker would like to share.
1485 #pod
1486 #pod =back
1487 #pod
1488 #pod =head2 new
1489 #pod
1490 #pod my $backend = Minion::Backend::mysql->new('mysql://mysql@/test');
1491 #pod
1492 #pod Construct a new L<Minion::Backend::mysql> object.
1493 #pod
1494 #pod =head2 note
1495 #pod
1496 #pod my $bool = $backend->note($job_id, {mojo => 'rocks', minion => 'too'});
1497 #pod
1498 #pod Change one or more metadata fields for a job. Setting a value to C<undef> will remove the field.
1499 #pod
1500 #pod =head2 pause_schedule
1501 #pod
1502 #pod my $bool = $backend->pause_schedule('daily');
1503 #pod
1504 #pod Pause a schedule by name so it stops firing until resumed. Returns true on success, false if the schedule does not
1505 #pod exist.
1506 #pod
1507 #pod =head2 receive
1508 #pod
1509 #pod my $commands = $backend->receive($worker_id);
1510 #pod
1511 #pod Receive remote control commands for worker.
1512 #pod
1513 #pod =head2 register_worker
1514 #pod
1515 #pod my $worker_id = $backend->register_worker;
1516 #pod my $worker_id = $backend->register_worker($worker_id);
1517 #pod
1518 #pod Register worker or send heartbeat to show that this worker is still alive.
1519 #pod
1520 #pod =head2 remove_job
1521 #pod
1522 #pod my $bool = $backend->remove_job($job_id);
1523 #pod
1524 #pod Remove C<failed>, C<finished> or C<inactive> job from queue.
1525 #pod
1526 #pod =head2 repair
1527 #pod
1528 #pod $backend->repair;
1529 #pod
1530 #pod Repair worker registry and job queue if necessary.
1531 #pod
1532 #pod =head2 reset
1533 #pod
1534 #pod $backend->reset;
1535 #pod
1536 #pod Reset job queue.
1537 #pod
1538 #pod =head2 resume_schedule
1539 #pod
1540 #pod my $bool = $backend->resume_schedule('daily');
1541 #pod
1542 #pod Resume a previously paused schedule. Returns true on success, false if the schedule does not exist.
1543 #pod
1544 #pod =head2 retry_job
1545 #pod
1546 #pod my $bool = $backend->retry_job($job_id, $retries);
1547 #pod my $bool = $backend->retry_job($job_id, $retries, {delay => 10});
1548 #pod
1549 #pod Transition from C<failed> or C<finished> state back to C<inactive>.
1550 #pod
1551 #pod These options are currently available:
1552 #pod
1553 #pod =over 2
1554 #pod
1555 #pod =item delay
1556 #pod
1557 #pod delay => 10
1558 #pod
1559 #pod Delay job for this many seconds (from now).
1560 #pod
1561 #pod =item parents
1562 #pod
1563 #pod parents => [$id1, $id2, $id3]
1564 #pod
1565 #pod Jobs this job depends on.
1566 #pod
1567 #pod =item priority
1568 #pod
1569 #pod priority => 5
1570 #pod
1571 #pod Job priority.
1572 #pod
1573 #pod =item queue
1574 #pod
1575 #pod queue => 'important'
1576 #pod
1577 #pod Queue to put job in.
1578 #pod
1579 #pod =back
1580 #pod
1581 #pod =head2 schedule
1582 #pod
1583 #pod my $id = $backend->schedule('daily', '0 4 * * *', 'cleanup');
1584 #pod my $id = $backend->schedule('daily', '0 4 * * *', 'cleanup', [@args]);
1585 #pod my $id = $backend->schedule(
1586 #pod 'daily', '0 4 * * *', 'cleanup', [@args], {priority => 5});
1587 #pod
1588 #pod Create or replace a schedule by unique name. Updating a schedule with the same cron expression preserves its current
1589 #pod firing time; changing the expression recomputes it.
1590 #pod
1591 #pod These options are currently available:
1592 #pod
1593 #pod =over 2
1594 #pod
1595 #pod =item attempts
1596 #pod
1597 #pod attempts => 25
1598 #pod
1599 #pod Number of times performing each enqueued job will be attempted, defaults to C<1>.
1600 #pod
1601 #pod =item expire
1602 #pod
1603 #pod expire => 300
1604 #pod
1605 #pod Each enqueued job is valid for this many seconds before it expires.
1606 #pod
1607 #pod =item lax
1608 #pod
1609 #pod lax => 1
1610 #pod
1611 #pod Existing jobs each enqueued job depends on may also have transitioned to the C<failed> state, defaults to C<false>.
1612 #pod
1613 #pod =item notes
1614 #pod
1615 #pod notes => {foo => 'bar'}
1616 #pod
1617 #pod Hash reference with arbitrary metadata applied to each enqueued job.
1618 #pod
1619 #pod =item priority
1620 #pod
1621 #pod priority => 5
1622 #pod
1623 #pod Priority of each enqueued job, defaults to C<0>.
1624 #pod
1625 #pod =item queue
1626 #pod
1627 #pod queue => 'important'
1628 #pod
1629 #pod Queue to put each enqueued job in, defaults to C<default>.
1630 #pod
1631 #pod =back
1632 #pod
1633 #pod =head2 stats
1634 #pod
1635 #pod my $stats = $backend->stats;
1636 #pod
1637 #pod Get statistics for jobs and workers.
1638 #pod
1639 #pod =head2 unregister_worker
1640 #pod
1641 #pod $backend->unregister_worker($worker_id);
1642 #pod
1643 #pod Unregister worker.
1644 #pod
1645 #pod =head2 worker_info
1646 #pod
1647 #pod my $worker_info = $backend->worker_info($worker_id);
1648 #pod
1649 #pod Get information about a worker or return C<undef> if worker does not exist.
1650 #pod
1651 #pod # Check worker host
1652 #pod my $host = $backend->worker_info($worker_id)->{host};
1653 #pod
1654 #pod These fields are currently available:
1655 #pod
1656 #pod =over 2
1657 #pod
1658 #pod =item host
1659 #pod
1660 #pod host => 'localhost'
1661 #pod
1662 #pod Worker host.
1663 #pod
1664 #pod =item jobs
1665 #pod
1666 #pod jobs => ['10023', '10024', '10025', '10029']
1667 #pod
1668 #pod Ids of jobs the worker is currently processing.
1669 #pod
1670 #pod =item notified
1671 #pod
1672 #pod notified => 784111777
1673 #pod
1674 #pod Last time worker sent a heartbeat.
1675 #pod
1676 #pod =item pid
1677 #pod
1678 #pod pid => 12345
1679 #pod
1680 #pod Process id of worker.
1681 #pod
1682 #pod =item started
1683 #pod
1684 #pod started => 784111777
1685 #pod
1686 #pod Time worker was started.
1687 #pod
1688 #pod =back
1689 #pod
1690 #pod =head1 PREFETCH AND JOB VOLUME
1691 #pod
1692 #pod Currently, the query to look for the next job to run is slower than it
1693 #pod could be. Between all the features like dependencies, priorities, retries,
1694 #pod and expiration, the query is complicated and requires some expensive data
1695 #pod manipulation. It still generally runs in less than one second even for
1696 #pod hundreds of thousands of jobs, but if jobs take less than one second
1697 #pod to process, a worker will end up spending most of its time looking up
1698 #pod new jobs to run, and wasting all the effort it took to get those pending
1699 #pod jobs in the right order.
1700 #pod
1701 #pod With v1.007, this backend prefetches a number of jobs in one query. These
1702 #pod jobs are then fed to worker processes as they ask. If a job is already claimed,
1703 #pod the worker tries again to claim the next job.
1704 #pod
1705 #pod If you are not seeing the throughput you expect, and your jobs are shorter
1706 #pod than one second, you can change the C<$Minion::Backend::mysql::PREFETCH> value
1707 #pod to be higher. A good goal is for a worker to perform work for a few seconds before
1708 #pod going back to the database. The prefetch cache expires after 30 seconds (which
1709 #pod can be adjusted with C<$Minion::Backend::mysql::PREFETCH_EXPIRY>).
1710 #pod
1711 #pod =head1 ERRORS
1712 #pod
1713 #pod =head2 DBD::mysql::st execute failed: Table '*.minion_workers' doesn't exist
1714 #pod
1715 #pod This may happen when the SQL create/upgrade scripts fail to run
1716 #pod completely due to permission errors. Re-running with the environment
1717 #pod variable C<MOJO_MIGRATIONS_DEBUG=1> should produce the error message
1718 #pod returned by the database.
1719 #pod
1720 #pod A common reason for the database install to fail on MySQL >= 8 is that
1721 #pod the user installing the database does not have C<SUPER> privileges
1722 #pod needed to create functions when binlogs are enabled: (C<DBD::mysql::st
1723 #pod execute failed: You do not have the SUPER privilege and binary logging
1724 #pod is enabled>). See L<the MySQL documentation for Stored Program Binary
1725 #pod Logging|https://dev.mysql.com/doc/refman/8.0/en/stored-programs-logging.html>
1726 #pod for more information about this problem and how to correct it.
1727 #pod
1728 #pod =head1 SEE ALSO
1729 #pod
1730 #pod L<Minion>, L<Minion::Guide>, L<https://minion.pm>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
1731 #pod
1732 #pod =cut
1733  
1734 =pod
1735  
1736 =encoding UTF-8
1737  
1738 =head1 NAME
1739  
1740 Minion::Backend::mysql
1741  
1742 =head1 VERSION
1743  
1744 version 1.009
1745  
1746 =head1 SYNOPSIS
1747  
1748 use Mojolicious::Lite;
1749  
1750 plugin Minion => {mysql => 'mysql://user@127.0.0.1/minion_jobs'};
1751  
1752 # Slow task
1753 app->minion->add_task(poke_mojo => sub {
1754 my $job = shift;
1755 $job->app->ua->get('mojolicio.us');
1756 $job->app->log->debug('We have poked mojolicio.us for a visitor');
1757 });
1758  
1759 # Perform job in a background worker process
1760 get '/' => sub {
1761 my $c = shift;
1762 $c->minion->enqueue('poke_mojo');
1763 $c->render(text => 'We will poke mojolicio.us for you soon.');
1764 };
1765  
1766 app->start;
1767  
1768 =head1 DESCRIPTION
1769  
1770 L<Minion::Backend::mysql> is a backend for L<Minion> based on L<Mojo::mysql>. All
1771 necessary tables will be created automatically with a set of migrations named
1772 C<minion>. This backend requires at least v5.6.5 of MySQL.
1773  
1774 =head1 NAME
1775  
1776 Minion::Backend::mysql - MySQL backend
1777  
1778 =head1 ATTRIBUTES
1779  
1780 L<Minion::Backend::mysql> inherits all attributes from L<Minion::Backend> and
1781 implements the following new ones.
1782  
1783 =head2 mysql
1784  
1785 my $mysql = $backend->mysql;
1786 $backend = $backend->mysql(Mojo::mysql->new);
1787  
1788 L<Mojo::mysql> object used to store all data.
1789  
1790 =head2 no_txn
1791  
1792 If true, will not make a transaction around the L</enqueue> insertions
1793 when a job has parent jobs. Without a transaction, the job could be
1794 dequeued before its parent relationships are written to the database.
1795 However, since MySQL does not support nested transactions (despite
1796 supporting something almost exactly like them...), you can disable
1797 transactions for testing by setting this attribute (if you perform your
1798 tests in a transaction so they can be rolled back when the test is
1799 complete).
1800  
1801 =head1 METHODS
1802  
1803 L<Minion::Backend::mysql> inherits all methods from L<Minion::Backend> and
1804 implements the following new ones.
1805  
1806 =head2 dequeue
1807  
1808 my $job_info = $backend->dequeue($worker_id, 0.5);
1809 my $job_info = $backend->dequeue($worker_id, 0.5, {queues => ['important']});
1810  
1811 Wait for job, dequeue it and transition from C<inactive> to C<active> state or
1812 return C<undef> if queues were empty.
1813  
1814 These options are currently available:
1815  
1816 =over 2
1817  
1818 =item min_priority
1819  
1820 min_priority => 3
1821  
1822 Do not dequeue jobs with a lower priority.
1823  
1824 =item queues
1825  
1826 queues => ['important']
1827  
1828 One or more queues to dequeue jobs from, defaults to C<default>.
1829  
1830 =item tasks
1831  
1832 tasks => ['foo', 'bar']
1833  
1834 One or more tasks to dequeue jobs for, defaults to all tasks.
1835  
1836 =back
1837  
1838 These fields are currently available:
1839  
1840 =over 2
1841  
1842 =item args
1843  
1844 args => ['foo', 'bar']
1845  
1846 Job arguments.
1847  
1848 =item id
1849  
1850 id => '10023'
1851  
1852 Job ID.
1853  
1854 =item retries
1855  
1856 retries => 3
1857  
1858 Number of times job has been retried.
1859  
1860 =item task
1861  
1862 task => 'foo'
1863  
1864 Task name.
1865  
1866 =back
1867  
1868 =head2 dispatch_schedules
1869  
1870 my $dispatched = $backend->dispatch_schedules;
1871  
1872 Enqueue jobs for all schedules whose firing time has been reached, advance their firing times to the next match, and
1873 return information about each dispatch as an array reference. A Postgres advisory lock is held for the duration of the
1874 dispatch cycle so that multiple workers ticking at the same time will not produce duplicate enqueues.
1875  
1876 Each entry contains C<id>, C<job> and C<name>.
1877  
1878 =head2 enqueue
1879  
1880 my $job_id = $backend->enqueue('foo');
1881 my $job_id = $backend->enqueue(foo => [@args]);
1882 my $job_id = $backend->enqueue(foo => [@args] => {priority => 1});
1883  
1884 Enqueue a new job with C<inactive> state.
1885  
1886 These options are currently available:
1887  
1888 =over 2
1889  
1890 =item attempts
1891  
1892 attempts => 25
1893  
1894 Number of times performing this job will be attempted, with a delay based on L<Minion/"backoff"> after the first
1895 attempt, defaults to C<1>.
1896  
1897 =item delay
1898  
1899 delay => 10
1900  
1901 Delay job for this many seconds (from now).
1902  
1903 =item expire
1904  
1905 expire => 300
1906  
1907 Job is valid for this many seconds (from now) before it expires.
1908  
1909 =item lax
1910  
1911 lax => 1
1912  
1913 Existing jobs this job depends on may also have transitioned to the C<failed> state to allow for it to be processed,
1914 defaults to C<false>.
1915  
1916 =item notes
1917  
1918 notes => {foo => 'bar', baz => [1, 2, 3]}
1919  
1920 Hash reference with arbitrary metadata for this job.
1921  
1922 =item parents
1923  
1924 parents => [$id1, $id2, $id3]
1925  
1926 One or more existing jobs this job depends on, and that need to have transitioned to the state C<finished> before it
1927 can be processed.
1928  
1929 =item priority
1930  
1931 priority => 5
1932  
1933 Job priority, defaults to C<0>.
1934  
1935 =item queue
1936  
1937 queue => 'important'
1938  
1939 Queue to put job in, defaults to C<default>.
1940  
1941 =back
1942  
1943 =head2 fail_job
1944  
1945 my $bool = $backend->fail_job($job_id, $retries);
1946 my $bool = $backend->fail_job($job_id, $retries, 'Something went wrong!');
1947 my $bool = $backend->fail_job(
1948 $job_id, $retries, {msg => 'Something went wrong!'});
1949  
1950 Transition from C<active> to C<failed> state.
1951  
1952 =head2 finish_job
1953  
1954 my $bool = $backend->finish_job($job_id, $retries);
1955 my $bool = $backend->finish_job($job_id, $retries, 'All went well!');
1956 my $bool = $backend->finish_job($job_id, $retries, {msg => 'All went well!'});
1957  
1958 Transition from C<active> to C<finished> state.
1959  
1960 =head2 job_info
1961  
1962 my $job_info = $backend->job_info($job_id);
1963  
1964 Get information about a job or return C<undef> if job does not exist.
1965  
1966 # Check job state
1967 my $state = $backend->job_info($job_id)->{state};
1968  
1969 # Get job result
1970 my $result = $backend->job_info($job_id)->{result};
1971  
1972 These fields are currently available:
1973  
1974 =over 2
1975  
1976 =item args
1977  
1978 args => ['foo', 'bar']
1979  
1980 Job arguments.
1981  
1982 =item created
1983  
1984 created => 784111777
1985  
1986 Time job was created.
1987  
1988 =item delayed
1989  
1990 delayed => 784111777
1991  
1992 Time job was delayed to.
1993  
1994 =item finished
1995  
1996 finished => 784111777
1997  
1998 Time job was finished.
1999  
2000 =item priority
2001  
2002 priority => 3
2003  
2004 Job priority.
2005  
2006 =item queue
2007  
2008 queue => 'important'
2009  
2010 Queue name.
2011  
2012 =item result
2013  
2014 result => 'All went well!'
2015  
2016 Job result.
2017  
2018 =item retried
2019  
2020 retried => 784111777
2021  
2022 Time job has been retried.
2023  
2024 =item retries
2025  
2026 retries => 3
2027  
2028 Number of times job has been retried.
2029  
2030 =item started
2031  
2032 started => 784111777
2033  
2034 Time job was started.
2035  
2036 =item state
2037  
2038 state => 'inactive'
2039  
2040 Current job state, usually C<active>, C<failed>, C<finished> or C<inactive>.
2041  
2042 =item task
2043  
2044 task => 'foo'
2045  
2046 Task name.
2047  
2048 =item worker
2049  
2050 worker => '154'
2051  
2052 Id of worker that is processing the job.
2053  
2054 =back
2055  
2056 =head2 list_jobs
2057  
2058 my $batch = $backend->list_jobs($offset, $limit);
2059 my $batch = $backend->list_jobs($offset, $limit, {states => 'inactive'});
2060  
2061 Returns the same information as L</"job_info"> but in batches.
2062  
2063 These options are currently available:
2064  
2065 =over 2
2066  
2067 =item state
2068  
2069 state => 'inactive'
2070  
2071 List only jobs in this state.
2072  
2073 =item task
2074  
2075 task => 'test'
2076  
2077 List only jobs for this task.
2078  
2079 =back
2080  
2081 =head2 list_schedules
2082  
2083 my $results = $backend->list_schedules($offset, $limit);
2084 my $results = $backend->list_schedules($offset, $limit, {names => ['daily']});
2085  
2086 Returns information about schedules in batches.
2087  
2088 # Get the total number of results (without limit)
2089 my $num = $backend->list_schedules(0, 100)->{total};
2090  
2091 # Check next firing time
2092 my $results = $backend->list_schedules(0, 1, {names => ['daily']});
2093 my $next = $results->{schedules}[0]{next_run};
2094  
2095 These options are currently available:
2096  
2097 =over 2
2098  
2099 =item before
2100  
2101 before => 23
2102  
2103 List only schedules before this id.
2104  
2105 =item ids
2106  
2107 ids => ['23', '24']
2108  
2109 List only schedules with these ids.
2110  
2111 =item names
2112  
2113 names => ['foo', 'bar']
2114  
2115 List only schedules with these names.
2116  
2117 =back
2118  
2119 These fields are currently available:
2120  
2121 =over 2
2122  
2123 =item args
2124  
2125 args => ['foo', 'bar']
2126  
2127 Job arguments used for each enqueued job.
2128  
2129 =item attempts
2130  
2131 attempts => 25
2132  
2133 Number of attempts each enqueued job will get.
2134  
2135 =item created
2136  
2137 created => 784111777
2138  
2139 Epoch time the schedule was created.
2140  
2141 =item cron
2142  
2143 cron => '0 9 * * 1-5'
2144  
2145 Cron expression.
2146  
2147 =item expire
2148  
2149 expire => 300
2150  
2151 Expiration in seconds for each enqueued job.
2152  
2153 =item id
2154  
2155 id => 23
2156  
2157 Schedule id.
2158  
2159 =item last_job
2160  
2161 last_job => '10025'
2162  
2163 Id of the most recently enqueued job, or C<undef> if the schedule has not fired yet.
2164  
2165 =item last_run
2166  
2167 last_run => 784111777
2168  
2169 Epoch time the schedule last fired, or C<undef> if it has not fired yet.
2170  
2171 =item lax
2172  
2173 lax => 0
2174  
2175 Lax dependency setting for each enqueued job.
2176  
2177 =item name
2178  
2179 name => 'daily'
2180  
2181 Schedule name.
2182  
2183 =item next_run
2184  
2185 next_run => 784111777
2186  
2187 Epoch time the schedule will fire next.
2188  
2189 =item notes
2190  
2191 notes => {foo => 'bar'}
2192  
2193 Hash reference with arbitrary metadata applied to each enqueued job.
2194  
2195 =item paused
2196  
2197 paused => 0
2198  
2199 True if the schedule is paused and will not fire.
2200  
2201 =item priority
2202  
2203 priority => 0
2204  
2205 Priority of each enqueued job.
2206  
2207 =item queue
2208  
2209 queue => 'default'
2210  
2211 Queue each enqueued job is placed in.
2212  
2213 =item task
2214  
2215 task => 'foo'
2216  
2217 Task name.
2218  
2219 =back
2220  
2221 =head2 list_workers
2222  
2223 my $results = $backend->list_workers($offset, $limit);
2224 my $results = $backend->list_workers($offset, $limit, {ids => [23]});
2225  
2226 Returns information about workers in batches.
2227  
2228 # Get the total number of results (without limit)
2229 my $num = $backend->list_workers(0, 100)->{total};
2230  
2231 # Check worker host
2232 my $results = $backend->list_workers(0, 1, {ids => [$worker_id]});
2233 my $host = $results->{workers}[0]{host};
2234  
2235 These options are currently available:
2236  
2237 =over 2
2238  
2239 =item before
2240  
2241 before => 23
2242  
2243 List only workers before this id.
2244  
2245 =item ids
2246  
2247 ids => ['23', '24']
2248  
2249 List only workers with these ids.
2250  
2251 =back
2252  
2253 These fields are currently available:
2254  
2255 =over 2
2256  
2257 =item id
2258  
2259 id => 22
2260  
2261 Worker id.
2262  
2263 =item host
2264  
2265 host => 'localhost'
2266  
2267 Worker host.
2268  
2269 =item jobs
2270  
2271 jobs => ['10023', '10024', '10025', '10029']
2272  
2273 Ids of jobs the worker is currently processing.
2274  
2275 =item notified
2276  
2277 notified => 784111777
2278  
2279 Epoch time worker sent the last heartbeat.
2280  
2281 =item pid
2282  
2283 pid => 12345
2284  
2285 Process id of worker.
2286  
2287 =item started
2288  
2289 started => 784111777
2290  
2291 Epoch time worker was started.
2292  
2293 =item status
2294  
2295 status => {queues => ['default', 'important']}
2296  
2297 Hash reference with whatever status information the worker would like to share.
2298  
2299 =back
2300  
2301 =head2 new
2302  
2303 my $backend = Minion::Backend::mysql->new('mysql://mysql@/test');
2304  
2305 Construct a new L<Minion::Backend::mysql> object.
2306  
2307 =head2 note
2308  
2309 my $bool = $backend->note($job_id, {mojo => 'rocks', minion => 'too'});
2310  
2311 Change one or more metadata fields for a job. Setting a value to C<undef> will remove the field.
2312  
2313 =head2 pause_schedule
2314  
2315 my $bool = $backend->pause_schedule('daily');
2316  
2317 Pause a schedule by name so it stops firing until resumed. Returns true on success, false if the schedule does not
2318 exist.
2319  
2320 =head2 receive
2321  
2322 my $commands = $backend->receive($worker_id);
2323  
2324 Receive remote control commands for worker.
2325  
2326 =head2 register_worker
2327  
2328 my $worker_id = $backend->register_worker;
2329 my $worker_id = $backend->register_worker($worker_id);
2330  
2331 Register worker or send heartbeat to show that this worker is still alive.
2332  
2333 =head2 remove_job
2334  
2335 my $bool = $backend->remove_job($job_id);
2336  
2337 Remove C<failed>, C<finished> or C<inactive> job from queue.
2338  
2339 =head2 repair
2340  
2341 $backend->repair;
2342  
2343 Repair worker registry and job queue if necessary.
2344  
2345 =head2 reset
2346  
2347 $backend->reset;
2348  
2349 Reset job queue.
2350  
2351 =head2 resume_schedule
2352  
2353 my $bool = $backend->resume_schedule('daily');
2354  
2355 Resume a previously paused schedule. Returns true on success, false if the schedule does not exist.
2356  
2357 =head2 retry_job
2358  
2359 my $bool = $backend->retry_job($job_id, $retries);
2360 my $bool = $backend->retry_job($job_id, $retries, {delay => 10});
2361  
2362 Transition from C<failed> or C<finished> state back to C<inactive>.
2363  
2364 These options are currently available:
2365  
2366 =over 2
2367  
2368 =item delay
2369  
2370 delay => 10
2371  
2372 Delay job for this many seconds (from now).
2373  
2374 =item parents
2375  
2376 parents => [$id1, $id2, $id3]
2377  
2378 Jobs this job depends on.
2379  
2380 =item priority
2381  
2382 priority => 5
2383  
2384 Job priority.
2385  
2386 =item queue
2387  
2388 queue => 'important'
2389  
2390 Queue to put job in.
2391  
2392 =back
2393  
2394 =head2 schedule
2395  
2396 my $id = $backend->schedule('daily', '0 4 * * *', 'cleanup');
2397 my $id = $backend->schedule('daily', '0 4 * * *', 'cleanup', [@args]);
2398 my $id = $backend->schedule(
2399 'daily', '0 4 * * *', 'cleanup', [@args], {priority => 5});
2400  
2401 Create or replace a schedule by unique name. Updating a schedule with the same cron expression preserves its current
2402 firing time; changing the expression recomputes it.
2403  
2404 These options are currently available:
2405  
2406 =over 2
2407  
2408 =item attempts
2409  
2410 attempts => 25
2411  
2412 Number of times performing each enqueued job will be attempted, defaults to C<1>.
2413  
2414 =item expire
2415  
2416 expire => 300
2417  
2418 Each enqueued job is valid for this many seconds before it expires.
2419  
2420 =item lax
2421  
2422 lax => 1
2423  
2424 Existing jobs each enqueued job depends on may also have transitioned to the C<failed> state, defaults to C<false>.
2425  
2426 =item notes
2427  
2428 notes => {foo => 'bar'}
2429  
2430 Hash reference with arbitrary metadata applied to each enqueued job.
2431  
2432 =item priority
2433  
2434 priority => 5
2435  
2436 Priority of each enqueued job, defaults to C<0>.
2437  
2438 =item queue
2439  
2440 queue => 'important'
2441  
2442 Queue to put each enqueued job in, defaults to C<default>.
2443  
2444 =back
2445  
2446 =head2 stats
2447  
2448 my $stats = $backend->stats;
2449  
2450 Get statistics for jobs and workers.
2451  
2452 =head2 unregister_worker
2453  
2454 $backend->unregister_worker($worker_id);
2455  
2456 Unregister worker.
2457  
2458 =head2 worker_info
2459  
2460 my $worker_info = $backend->worker_info($worker_id);
2461  
2462 Get information about a worker or return C<undef> if worker does not exist.
2463  
2464 # Check worker host
2465 my $host = $backend->worker_info($worker_id)->{host};
2466  
2467 These fields are currently available:
2468  
2469 =over 2
2470  
2471 =item host
2472  
2473 host => 'localhost'
2474  
2475 Worker host.
2476  
2477 =item jobs
2478  
2479 jobs => ['10023', '10024', '10025', '10029']
2480  
2481 Ids of jobs the worker is currently processing.
2482  
2483 =item notified
2484  
2485 notified => 784111777
2486  
2487 Last time worker sent a heartbeat.
2488  
2489 =item pid
2490  
2491 pid => 12345
2492  
2493 Process id of worker.
2494  
2495 =item started
2496  
2497 started => 784111777
2498  
2499 Time worker was started.
2500  
2501 =back
2502  
2503 =head1 PREFETCH AND JOB VOLUME
2504  
2505 Currently, the query to look for the next job to run is slower than it
2506 could be. Between all the features like dependencies, priorities, retries,
2507 and expiration, the query is complicated and requires some expensive data
2508 manipulation. It still generally runs in less than one second even for
2509 hundreds of thousands of jobs, but if jobs take less than one second
2510 to process, a worker will end up spending most of its time looking up
2511 new jobs to run, and wasting all the effort it took to get those pending
2512 jobs in the right order.
2513  
2514 With v1.007, this backend prefetches a number of jobs in one query. These
2515 jobs are then fed to worker processes as they ask. If a job is already claimed,
2516 the worker tries again to claim the next job.
2517  
2518 If you are not seeing the throughput you expect, and your jobs are shorter
2519 than one second, you can change the C<$Minion::Backend::mysql::PREFETCH> value
2520 to be higher. A good goal is for a worker to perform work for a few seconds before
2521 going back to the database. The prefetch cache expires after 30 seconds (which
2522 can be adjusted with C<$Minion::Backend::mysql::PREFETCH_EXPIRY>).
2523  
2524 =head1 ERRORS
2525  
2526 =head2 DBD::mysql::st execute failed: Table '*.minion_workers' doesn't exist
2527  
2528 This may happen when the SQL create/upgrade scripts fail to run
2529 completely due to permission errors. Re-running with the environment
2530 variable C<MOJO_MIGRATIONS_DEBUG=1> should produce the error message
2531 returned by the database.
2532  
2533 A common reason for the database install to fail on MySQL >= 8 is that
2534 the user installing the database does not have C<SUPER> privileges
2535 needed to create functions when binlogs are enabled: (C<DBD::mysql::st
2536 execute failed: You do not have the SUPER privilege and binary logging
2537 is enabled>). See L<the MySQL documentation for Stored Program Binary
2538 Logging|https://dev.mysql.com/doc/refman/8.0/en/stored-programs-logging.html>
2539 for more information about this problem and how to correct it.
2540  
2541 =head1 SEE ALSO
2542  
2543 L<Minion>, L<Minion::Guide>, L<https://minion.pm>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
2544  
2545 =head1 AUTHORS
2546  
2547 =over 4
2548  
2549 =item *
2550  
2551 Brian Medley <bpmedley@cpan.org>
2552  
2553 =item *
2554  
2555 Doug Bell <preaction@cpan.org>
2556  
2557 =back
2558  
2559 =head1 CONTRIBUTORS
2560  
2561 =for stopwords a-leelan Alexander Nalobin Dmitry Krylov Hu Yin James Dooley Jason A. Crome Larry Leszczynski Olaf Alders Paul Cochrane Peter Joh Sergey Andreev Zoffix Znet
2562  
2563 =over 4
2564  
2565 =item *
2566  
2567 a-leelan <40534142+a-leelan@users.noreply.github.com>
2568  
2569 =item *
2570  
2571 Alexander Nalobin <nalobin@reg.ru>
2572  
2573 =item *
2574  
2575 Dmitry Krylov <pentabion@gmail.com>
2576  
2577 =item *
2578  
2579 Hu Yin <huyin8@gmail.com>
2580  
2581 =item *
2582  
2583 James Dooley <322168445+jdooley-lw@users.noreply.github.com>
2584  
2585 =item *
2586  
2587 Jason A. Crome <jcrome@empoweredbenefits.com>
2588  
2589 =item *
2590  
2591 Larry Leszczynski <larryl@cpan.org>
2592  
2593 =item *
2594  
2595 Olaf Alders <olaf@wundersolutions.com>
2596  
2597 =item *
2598  
2599 Paul Cochrane <paul@liekut.de>
2600  
2601 =item *
2602  
2603 Peter Joh <peter.joh@grantstreet.com>
2604  
2605 =item *
2606  
2607 Sergey Andreev <40195653+saintserge@users.noreply.github.com>
2608  
2609 =item *
2610  
2611 Zoffix Znet <cpan@zoffix.com>
2612  
2613 =back
2614  
2615 =head1 COPYRIGHT AND LICENSE
2616  
2617 This software is copyright (c) 2021 by Doug Bell and Brian Medley.
2618  
2619 This is free software; you can redistribute it and/or modify it under
2620 the same terms as the Perl 5 programming language system itself.
2621  
2622 =cut
2623  
2624 __DATA__
↑ Summary