Minion/Backend/Pg.pm untested

filter: Statementstmt 0.0% 0 / 136 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 56 MC/DCmcdc 0.0% 0 / 19 Subroutinesub 0.0% 0 / 39 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 314 CC 17 SCAR 18.3
CC
17
Cov
0%
_update
20.0
dequeue
12.0
dispatch_schedules
12.0
CRAP 6.2
1 package Minion::Backend::Pg;
2 use Mojo::Base 'Minion::Backend';
3  
4 use Carp qw(croak);
5 use Minion::Util qw(next_cron_time);
6 use Mojo::File qw(path);
7 use Mojo::IOLoop;
8 use Mojo::Pg 5.0;
9 use Sys::Hostname qw(hostname);
10  
11 has 'pg';
12  
13 sub broadcast {
14 my ($self, $command, $args, $ids) = (shift, shift, shift || [], shift || []);
15 return $self->pg->db->query(
16 q{UPDATE minion_workers SET inbox = inbox || $1::JSONB WHERE (id = ANY ($2) OR $2 = '{}')},
17 {json => [[$command, @$args]]}, $ids)->rv > 0;
18 }
19  
20 sub dequeue {
21 my ($self, $id, $wait, $options) = @_;
22  
23 if ((my $job = $self->_try($id, $options))) { return $job }
24 return undef if Mojo::IOLoop->is_running;
25  
26 my $db = $self->pg->db;
27 $db->listen('minion.job')->on(notification => sub { Mojo::IOLoop->stop });
28 my $timer = Mojo::IOLoop->timer($wait => sub { Mojo::IOLoop->stop });
29 Mojo::IOLoop->start;
30 $db->unlisten('*') and Mojo::IOLoop->remove($timer);
31 undef $db;
32  
33 return $self->_try($id, $options);
34 }
35  
36 sub dispatch_schedules {
37 my $self = shift;
38  
39 my $db = $self->pg->db;
40 my $tx = $db->begin;
41 return [] unless $db->query(q{SELECT pg_try_advisory_xact_lock(hashtext('minion.schedules'))})->array->[0];
42  
43 my $due = $db->query(
44 q{SELECT id, args, attempts, cron, expire, lax, name, EXTRACT(EPOCH FROM next_run) AS next_run,
45 EXTRACT(EPOCH FROM NOW()) AS now, notes, priority, queue, task
46 FROM minion_schedules WHERE next_run <= NOW() AND NOT paused FOR UPDATE}
47 )->expand->hashes;
48  
49 my @dispatched;
50 for my $s (@$due) {
51 my $job_id = $self->_enqueue(
52 $db,
53 $s->{task},
54 $s->{args},
55 {
56 attempts => $s->{attempts},
57 expire => $s->{expire},
58 lax => $s->{lax},
59 notes => $s->{notes},
60 priority => $s->{priority},
61 queue => $s->{queue}
62 }
63 );
64 my $basis = $s->{next_run} > $s->{now} ? $s->{next_run} : $s->{now};
65 my $next = next_cron_time $s->{cron}, $basis;
66 $db->query('UPDATE minion_schedules SET last_job = ?, last_run = NOW(), next_run = TO_TIMESTAMP(?) WHERE id = ?',
67 $job_id, $next, $s->{id});
68 push @dispatched, {id => $s->{id}, name => $s->{name}, job => $job_id};
69 }
70 $tx->commit;
71  
72 return \@dispatched;
73 }
74  
75 sub enqueue {
76 my $self = shift;
77 return $self->_enqueue($self->pg->db, @_);
78 }
79  
80 sub fail_job { shift->_update(1, @_) }
81 sub finish_job { shift->_update(0, @_) }
82  
83 sub history {
84 my $self = shift;
85  
86 my $daily = $self->pg->db->query(
87 "SELECT EXTRACT(EPOCH FROM ts) AS epoch, COALESCE(failed_jobs, 0) AS failed_jobs,
88 COALESCE(finished_jobs, 0) AS finished_jobs
89 FROM (
90 SELECT EXTRACT (DAY FROM finished) AS day, EXTRACT(HOUR FROM finished) AS hour,
91 COUNT(*) FILTER (WHERE state = 'failed') AS failed_jobs,
92 COUNT(*) FILTER (WHERE state = 'finished') AS finished_jobs
93 FROM minion_jobs
94 WHERE finished > NOW() - INTERVAL '23 hours'
95 GROUP BY day, hour
96 ) AS j RIGHT OUTER JOIN (
97 SELECT *
98 FROM GENERATE_SERIES(NOW() - INTERVAL '23 hour', NOW(), '1 hour') AS ts
99 ) AS s ON EXTRACT(HOUR FROM ts) = j.hour AND EXTRACT(DAY FROM ts) = j.day
100 ORDER BY epoch ASC"
101 )->hashes->to_array;
102  
103 return {daily => $daily};
104 }
105  
106 sub list_jobs {
107 my ($self, $offset, $limit, $options) = @_;
108  
109 my $jobs = $self->pg->db->query(
110 q{SELECT id, args, attempts,
111 ARRAY(SELECT id FROM minion_jobs WHERE parents @> ARRAY[j.id]) AS children,
112 EXTRACT(epoch FROM created) AS created, EXTRACT(EPOCH FROM delayed) AS delayed,
113 EXTRACT(EPOCH FROM expires) AS expires, EXTRACT(EPOCH FROM finished) AS finished, lax, notes, parents, priority,
114 queue, result, EXTRACT(EPOCH FROM retried) AS retried, retries, EXTRACT(EPOCH FROM started) AS started, state,
115 task, EXTRACT(EPOCH FROM now()) AS time, COUNT(*) OVER() AS total, worker
116 FROM minion_jobs AS j
117 WHERE (id < $1 OR $1 IS NULL) AND (id = ANY ($2) OR $2 IS NULL) AND (notes \? ANY ($3) OR $3 IS NULL)
118 AND (queue = ANY ($4) OR $4 IS null) AND (state = ANY ($5) OR $5 IS NULL) AND (task = ANY ($6) OR $6 IS NULL)
119 AND (state != 'inactive' OR expires IS null OR expires > NOW())
120 ORDER BY id DESC
121 LIMIT $7 OFFSET $8}, @$options{qw(before ids notes queues states tasks)}, $limit, $offset
122 )->expand->hashes->to_array;
123  
124 return _total('jobs', $jobs);
125 }
126  
127 sub list_locks {
128 my ($self, $offset, $limit, $options) = @_;
129  
130 my $locks = $self->pg->db->query(
131 'SELECT id, name, EXTRACT(EPOCH FROM expires) AS expires, COUNT(*) OVER() AS total FROM minion_locks
132 WHERE expires > NOW() AND (name = ANY ($1) OR $1 IS NULL)
133 ORDER BY id DESC LIMIT $2 OFFSET $3', $options->{names}, $limit, $offset
134 )->hashes->to_array;
135 return _total('locks', $locks);
136 }
137  
138 sub list_schedules {
139 my ($self, $offset, $limit, $options) = @_;
140  
141 my $schedules = $self->pg->db->query(
142 q{SELECT id, args, attempts, EXTRACT(EPOCH FROM created) AS created, cron, expire, last_job,
143 EXTRACT(EPOCH FROM last_run) AS last_run, lax, name, EXTRACT(EPOCH FROM next_run) AS next_run, notes, paused,
144 priority, queue, task, COUNT(*) OVER() AS total
145 FROM minion_schedules
146 WHERE (id < $1 OR $1 IS NULL) AND (id = ANY ($2) OR $2 IS NULL) AND (name = ANY ($3) OR $3 IS NULL)
147 ORDER BY id DESC LIMIT $4 OFFSET $5}, @$options{qw(before ids names)}, $limit, $offset
148 )->expand->hashes->to_array;
149  
150 return _total('schedules', $schedules);
151 }
152  
153 sub list_workers {
154 my ($self, $offset, $limit, $options) = @_;
155  
156 my $workers = $self->pg->db->query(
157 "SELECT id, EXTRACT(EPOCH FROM notified) AS notified, ARRAY(
158 SELECT id FROM minion_jobs WHERE state = 'active' AND worker = minion_workers.id
159 ) AS jobs, host, pid, status, EXTRACT(EPOCH FROM started) AS started,
160 COUNT(*) OVER() AS total
161 FROM minion_workers
162 WHERE (id < \$1 OR \$1 IS NULL) AND (id = ANY (\$2) OR \$2 IS NULL)
163 ORDER BY id DESC LIMIT \$3 OFFSET \$4", @$options{qw(before ids)}, $limit, $offset
164 )->expand->hashes->to_array;
165 return _total('workers', $workers);
166 }
167  
168 sub lock {
169 my ($self, $name, $duration, $options) = (shift, shift, shift, shift // {});
170 return !!$self->pg->db->query('SELECT * FROM minion_lock(?, ?, ?)', $name, $duration, $options->{limit} || 1)
171 ->array->[0];
172 }
173  
174 sub new {
175 my $self = shift->SUPER::new(pg => Mojo::Pg->new(@_));
176  
177 my $db = Mojo::Pg->new(@_)->db;
178 croak 'PostgreSQL 12 or later is required' if $db->dbh->{pg_server_version} < 130000;
179 $db->disconnect;
180  
181 my $schema = path(__FILE__)->dirname->child('resources', 'migrations', 'pg.sql');
182 $self->pg->auto_migrate(1)->migrations->name('minion')->from_file($schema);
183  
184 return $self;
185 }
186  
187 sub note {
188 my ($self, $id, $merge) = @_;
189 return $self->pg->db->query('UPDATE minion_jobs SET notes = JSONB_STRIP_NULLS(notes || ?) WHERE id = ?',
190 {json => $merge}, $id)->rv > 0;
191 }
192  
193 sub pause_schedule { shift->_set_paused(shift, 1) }
194  
195 sub receive {
196 my $array = shift->pg->db->query(
197 "UPDATE minion_workers AS new SET inbox = '[]'
198 FROM (SELECT id, inbox FROM minion_workers WHERE id = ? FOR UPDATE) AS old
199 WHERE new.id = old.id AND old.inbox != '[]'
200 RETURNING old.inbox", shift
201 )->expand->array;
202 return $array ? $array->[0] : [];
203 }
204  
205 sub register_worker {
206 my ($self, $id, $options) = (shift, shift, shift || {});
207  
208 return $self->pg->db->query(
209 q{INSERT INTO minion_workers (id, host, pid, status)
210 VALUES (COALESCE($1, NEXTVAL('minion_workers_id_seq')), $2, $3, $4)
211 ON CONFLICT(id) DO UPDATE SET notified = now(), status = $4
212 RETURNING id}, $id, $self->{host} //= hostname, $$, {json => $options->{status} // {}}
213 )->hash->{id};
214 }
215  
216 sub remove_job {
217 my ($self, $id) = @_;
218 return $self->pg->db->query(
219 "DELETE FROM minion_jobs WHERE id = ? AND state IN ('inactive', 'failed', 'finished') RETURNING 1", $id)->rv > 0;
220 }
221  
222 sub repair {
223 my $self = shift;
224  
225 # Workers without heartbeat
226 my $db = $self->pg->db;
227 my $minion = $self->minion;
228 $db->query("DELETE FROM minion_workers WHERE notified < NOW() - INTERVAL '1 second' * ?", $minion->missing_after);
229  
230 # Old jobs with no unresolved dependencies
231 $db->query(
232 "DELETE FROM minion_jobs
233 WHERE id IN (
234 SELECT id FROM minion_jobs WHERE state = 'finished' AND finished <= NOW() - INTERVAL '1 second' * ?
235 EXCEPT SELECT unnest(parents) AS id FROM minion_jobs WHERE state != 'finished'
236 )", $minion->remove_after
237 );
238  
239 # Expired jobs
240 $db->query("DELETE FROM minion_jobs WHERE state = 'inactive' AND expires <= NOW()");
241  
242 # Jobs with missing worker (can be retried)
243 $db->query(
244 "SELECT id, retries FROM minion_jobs AS j
245 WHERE state = 'active' AND queue != 'minion_foreground'
246 AND NOT EXISTS (SELECT 1 FROM minion_workers WHERE id = j.worker)"
247 )->hashes->each(sub { $self->fail_job(@$_{qw(id retries)}, 'Worker went away') });
248  
249 # Jobs in queue without workers or not enough workers (cannot be retried and requires admin attention)
250 $db->query(
251 q{UPDATE minion_jobs SET state = 'failed', result = '"Job appears stuck in queue"'
252 WHERE state = 'inactive' AND delayed + ? * INTERVAL '1 second' < NOW()}, $minion->stuck_after
253 );
254 }
255  
256 sub reset {
257 my ($self, $options) = (shift, shift // {});
258  
259 if ($options->{all}) {
260 $self->pg->db->query('TRUNCATE minion_jobs, minion_locks, minion_schedules, minion_workers RESTART IDENTITY');
261 }
262 elsif ($options->{locks}) { $self->pg->db->query('TRUNCATE minion_locks') }
263 }
264  
265 sub resume_schedule { shift->_set_paused(shift, 0) }
266  
267 sub retry_job {
268 my ($self, $id, $retries, $options) = (shift, shift, shift, shift || {});
269  
270 return $self->pg->db->query(
271 q{UPDATE minion_jobs SET attempts = COALESCE($1, attempts), delayed = (NOW() + (INTERVAL '1 second' * $2)),
272 expires = CASE WHEN $3::BIGINT IS NOT NULL THEN NOW() + (INTERVAL '1 second' * $3::BIGINT) ELSE expires END,
273 lax = COALESCE($4, lax), parents = COALESCE($5, parents), priority = COALESCE($6, priority),
274 queue = COALESCE($7, queue), retried = NOW(), retries = retries + 1, state = 'inactive'
275 WHERE id = $8 AND retries = $9
276 RETURNING 1}, $options->{attempts}, $options->{delay} // 0, $options->{expire},
277 exists $options->{lax} ? $options->{lax} ? 1 : 0 : undef, @$options{qw(parents priority queue)}, $id, $retries
278 )->rv > 0;
279 }
280  
281 sub schedule {
282 my ($self, $name, $cron, $task, $args, $options) = (shift, shift, shift, shift, shift || [], shift || {});
283  
284 my $db = $self->pg->db;
285 my $next = next_cron_time $cron, $db->query('SELECT EXTRACT(EPOCH FROM NOW())')->array->[0];
286  
287 return $db->query(
288 q{INSERT INTO minion_schedules (args, attempts, cron, expire, lax, name, next_run, notes, priority, queue, task)
289 VALUES ($1, $2, $3, $4, $5, $6, TO_TIMESTAMP($7), $8, $9, $10, $11)
290 ON CONFLICT (name) DO UPDATE SET
291 args = EXCLUDED.args, attempts = EXCLUDED.attempts, cron = EXCLUDED.cron, expire = EXCLUDED.expire,
292 lax = EXCLUDED.lax, notes = EXCLUDED.notes, priority = EXCLUDED.priority, queue = EXCLUDED.queue,
293 task = EXCLUDED.task,
294 next_run = CASE WHEN minion_schedules.cron = EXCLUDED.cron THEN minion_schedules.next_run ELSE EXCLUDED.next_run END
295 RETURNING id}, {json => $args}, $options->{attempts} // 1, $cron, $options->{expire}, $options->{lax} ? 1 : 0,
296 $name, $next, {json => $options->{notes} || {}}, $options->{priority} // 0, $options->{queue} // 'default', $task
297 )->hash->{id};
298 }
299  
300 sub stats {
301 my $self = shift;
302  
303 my $stats = $self->pg->db->query(
304 "SELECT
305 (SELECT COUNT(*) FROM minion_jobs WHERE state = 'inactive' AND (expires IS NULL OR expires > NOW())) AS inactive_jobs,
306 (SELECT COUNT(*) FROM minion_jobs WHERE state = 'active') AS active_jobs,
307 (SELECT COUNT(*) FROM minion_jobs WHERE state = 'failed') AS failed_jobs,
308 (SELECT COUNT(*) FROM minion_jobs WHERE state = 'finished') AS finished_jobs,
309 (SELECT COUNT(*) FROM minion_jobs WHERE state = 'inactive' AND delayed > NOW()) AS delayed_jobs,
310 (SELECT COUNT(*) FROM minion_locks WHERE expires > NOW()) AS active_locks,
311 (SELECT COUNT(*) FROM minion_schedules WHERE NOT paused) AS schedules,
312 (SELECT COUNT(*) FROM minion_schedules WHERE paused) AS inactive_schedules,
313 (SELECT COUNT(DISTINCT worker) FROM minion_jobs mj WHERE state = 'active') AS active_workers,
314 (SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM minion_jobs_id_seq) AS enqueued_jobs,
315 (SELECT COUNT(*) FROM minion_workers) AS workers,
316 EXTRACT(EPOCH FROM NOW() - PG_POSTMASTER_START_TIME()) AS uptime"
317 )->hash;
318 $stats->{inactive_workers} = $stats->{workers} - $stats->{active_workers};
319  
320 return $stats;
321 }
322  
323 sub unlock {
324 shift->pg->db->query(
325 'DELETE FROM minion_locks WHERE id = (
326 SELECT id FROM minion_locks WHERE expires > NOW() AND name = ? ORDER BY expires LIMIT 1 FOR UPDATE
327 ) RETURNING 1', shift
328 )->rv > 0;
329 }
330  
331 sub unregister_worker { shift->pg->db->query('DELETE FROM minion_workers WHERE id = ?', shift) }
332  
333 sub unschedule {
334 return shift->pg->db->query('DELETE FROM minion_schedules WHERE name = ? RETURNING 1', shift)->rv > 0;
335 }
336  
337 sub _enqueue {
338 my ($self, $db, $task, $args, $options) = (shift, shift, shift, shift || [], shift || {});
339  
340 return $db->query(
341 q{INSERT INTO minion_jobs (args, attempts, delayed, expires, lax, notes, parents, priority, queue, task)
342 VALUES ($1, $2, (NOW() + (INTERVAL '1 second' * $3)),
343 CASE WHEN $4::BIGINT IS NOT NULL THEN NOW() + (INTERVAL '1 second' * $4::BIGINT) END, $5, $6, $7, $8, $9, $10)
344 RETURNING id}, {json => $args}, $options->{attempts} // 1, $options->{delay} // 0, $options->{expire},
345 $options->{lax} ? 1 : 0, {json => $options->{notes} || {}}, $options->{parents} || [], $options->{priority} // 0,
346 $options->{queue} // 'default', $task
347 )->hash->{id};
348 }
349  
350 sub _set_paused {
351 my ($self, $name, $paused) = @_;
352 return $self->pg->db->query('UPDATE minion_schedules SET paused = ? WHERE name = ? RETURNING 1', $paused, $name)->rv
353 > 0;
354 }
355  
356 sub _total {
357 my ($name, $results) = @_;
358 my $total = @$results ? $results->[0]{total} : 0;
359 delete $_->{total} for @$results;
360 return {total => $total, $name => $results};
361 }
362  
363 sub _try {
364 my ($self, $id, $options) = @_;
365  
366 return $self->pg->db->query(
367 q{WITH cte AS (
368 SELECT id FROM minion_jobs AS j
369 WHERE delayed <= NOW() AND id = COALESCE(?, id) AND (parents = '{}' OR NOT EXISTS (
370 SELECT 1 FROM minion_jobs
371 WHERE id = ANY (j.parents) AND (
372 state = 'active' OR (state = 'failed' AND NOT j.lax)
373 OR (state = 'inactive' AND (expires IS NULL OR expires > NOW()))
374 )
375 )) AND priority >= COALESCE(?, priority) AND queue = ANY (?) AND state = 'inactive' AND task = ANY (?)
376 AND (expires IS NULL OR expires > NOW())
377 ORDER BY priority DESC, id
378 LIMIT 1
379 FOR UPDATE SKIP LOCKED
380 )
381 UPDATE minion_jobs
382 SET started = NOW(), state = 'active', worker = ?
383 WHERE id = (SELECT id FROM cte)
384 RETURNING id, args, retries, task}, $options->{id}, $options->{min_priority}, $options->{queues} || ['default'],
385 $options->{tasks} || [keys %{$self->minion->tasks}], $id
386 )->expand->hash;
387 }
388  
389 sub _update {
390 my ($self, $fail, $id, $retries, $result) = @_;
391  
392 return undef unless my $row = $self->pg->db->query(
393 "UPDATE minion_jobs SET finished = NOW(), result = ?, state = ?
394 WHERE id = ? AND retries = ? AND state = 'active'
395 RETURNING attempts", {json => $result}, $fail ? 'failed' : 'finished', $id, $retries
396 )->array;
397  
398 return $fail ? $self->auto_retry_job($id, $retries, $row->[0]) : 1;
399 }
400  
401 1;
402  
403 =encoding utf8
404  
405 =head1 NAME
406  
407 Minion::Backend::Pg - PostgreSQL backend
408  
409 =head1 SYNOPSIS
410  
411 use Minion::Backend::Pg;
412  
413 my $backend = Minion::Backend::Pg->new('postgresql://postgres@/test');
414  
415 =head1 DESCRIPTION
416  
417 L<Minion::Backend::Pg> is a backend for L<Minion> based on L<Mojo::Pg>. All necessary tables will be created
418 automatically with a set of migrations named C<minion>. Note that this backend uses many bleeding edge features, so
419 only the latest, stable version of PostgreSQL is fully supported.
420  
421 =head1 ATTRIBUTES
422  
423 L<Minion::Backend::Pg> inherits all attributes from L<Minion::Backend> and implements the following new ones.
424  
425 =head2 pg
426  
427 my $pg = $backend->pg;
428 $backend = $backend->pg(Mojo::Pg->new);
429  
430 L<Mojo::Pg> object used to store all data.
431  
432 =head1 METHODS
433  
434 L<Minion::Backend::Pg> inherits all methods from L<Minion::Backend> and implements the following new ones.
435  
436 =head2 broadcast
437  
438 my $bool = $backend->broadcast('some_command');
439 my $bool = $backend->broadcast('some_command', [@args]);
440 my $bool = $backend->broadcast('some_command', [@args], [$id1, $id2, $id3]);
441  
442 Broadcast remote control command to one or more workers.
443  
444 =head2 dequeue
445  
446 my $job_info = $backend->dequeue($worker_id, 0.5);
447 my $job_info = $backend->dequeue($worker_id, 0.5, {queues => ['important']});
448  
449 Wait a given amount of time in seconds for a job, dequeue it and transition from C<inactive> to C<active> state, or
450 return C<undef> if queues were empty.
451  
452 These options are currently available:
453  
454 =over 2
455  
456 =item id
457  
458 id => '10023'
459  
460 Dequeue a specific job.
461  
462 =item min_priority
463  
464 min_priority => 3
465  
466 Do not dequeue jobs with a lower priority.
467  
468 =item queues
469  
470 queues => ['important']
471  
472 One or more queues to dequeue jobs from, defaults to C<default>.
473  
474 =item tasks
475  
476 tasks => ['foo', 'bar']
477  
478 One or more tasks to dequeue jobs for, defaults to all tasks.
479  
480 =back
481  
482 These fields are currently available:
483  
484 =over 2
485  
486 =item args
487  
488 args => ['foo', 'bar']
489  
490 Job arguments.
491  
492 =item id
493  
494 id => '10023'
495  
496 Job ID.
497  
498 =item retries
499  
500 retries => 3
501  
502 Number of times job has been retried.
503  
504 =item task
505  
506 task => 'foo'
507  
508 Task name.
509  
510 =back
511  
512 =head2 dispatch_schedules
513  
514 my $dispatched = $backend->dispatch_schedules;
515  
516 Enqueue jobs for all schedules whose firing time has been reached, advance their firing times to the next match, and
517 return information about each dispatch as an array reference. A Postgres advisory lock is held for the duration of the
518 dispatch cycle so that multiple workers ticking at the same time will not produce duplicate enqueues.
519  
520 Each entry contains C<id>, C<job> and C<name>.
521  
522 =head2 enqueue
523  
524 my $job_id = $backend->enqueue('foo');
525 my $job_id = $backend->enqueue(foo => [@args]);
526 my $job_id = $backend->enqueue(foo => [@args] => {priority => 1});
527  
528 Enqueue a new job with C<inactive> state.
529  
530 These options are currently available:
531  
532 =over 2
533  
534 =item attempts
535  
536 attempts => 25
537  
538 Number of times performing this job will be attempted, with a delay based on L<Minion/"backoff"> after the first
539 attempt, defaults to C<1>.
540  
541 =item delay
542  
543 delay => 10
544  
545 Delay job for this many seconds (from now), defaults to C<0>.
546  
547 =item expire
548  
549 expire => 300
550  
551 Job is valid for this many seconds (from now) before it expires.
552  
553 =item lax
554  
555 lax => 1
556  
557 Existing jobs this job depends on may also have transitioned to the C<failed> state to allow for it to be processed,
558 defaults to C<false>.
559  
560 =item notes
561  
562 notes => {foo => 'bar', baz => [1, 2, 3]}
563  
564 Hash reference with arbitrary metadata for this job.
565  
566 =item parents
567  
568 parents => [$id1, $id2, $id3]
569  
570 One or more existing jobs this job depends on, and that need to have transitioned to the state C<finished> before it
571 can be processed.
572  
573 =item priority
574  
575 priority => 5
576  
577 Job priority, defaults to C<0>. Jobs with a higher priority get performed first. Priorities can be positive or negative,
578 but should be in the range between C<100> and C<-100>.
579  
580 =item queue
581  
582 queue => 'important'
583  
584 Queue to put job in, defaults to C<default>.
585  
586 =back
587  
588 =head2 fail_job
589  
590 my $bool = $backend->fail_job($job_id, $retries);
591 my $bool = $backend->fail_job($job_id, $retries, 'Something went wrong!');
592 my $bool = $backend->fail_job(
593 $job_id, $retries, {whatever => 'Something went wrong!'});
594  
595 Transition from C<active> to C<failed> state with or without a result, and if there are attempts remaining, transition
596 back to C<inactive> with a delay based on L<Minion/"backoff">.
597  
598 =head2 finish_job
599  
600 my $bool = $backend->finish_job($job_id, $retries);
601 my $bool = $backend->finish_job($job_id, $retries, 'All went well!');
602 my $bool = $backend->finish_job(
603 $job_id, $retries, {whatever => 'All went well!'});
604  
605 Transition from C<active> to C<finished> state with or without a result.
606  
607 =head2 history
608  
609 my $history = $backend->history;
610  
611 Get history information for job queue.
612  
613 These fields are currently available:
614  
615 =over 2
616  
617 =item daily
618  
619 daily => [{epoch => 12345, finished_jobs => 95, failed_jobs => 2}, ...]
620  
621 Hourly counts for processed jobs from the past day.
622  
623 =back
624  
625 =head2 list_jobs
626  
627 my $results = $backend->list_jobs($offset, $limit);
628 my $results = $backend->list_jobs($offset, $limit, {states => ['inactive']});
629  
630 Returns the information about jobs in batches.
631  
632 # Get the total number of results (without limit)
633 my $num = $backend->list_jobs(0, 100, {queues => ['important']})->{total};
634  
635 # Check job state
636 my $results = $backend->list_jobs(0, 1, {ids => [$job_id]});
637 my $state = $results->{jobs}[0]{state};
638  
639 # Get job result
640 my $results = $backend->list_jobs(0, 1, {ids => [$job_id]});
641 my $result = $results->{jobs}[0]{result};
642  
643 These options are currently available:
644  
645 =over 2
646  
647 =item before
648  
649 before => 23
650  
651 List only jobs before this id.
652  
653 =item ids
654  
655 ids => ['23', '24']
656  
657 List only jobs with these ids.
658  
659 =item notes
660  
661 notes => ['foo', 'bar']
662  
663 List only jobs with one of these notes.
664  
665 =item queues
666  
667 queues => ['important', 'unimportant']
668  
669 List only jobs in these queues.
670  
671 =item states
672  
673 states => ['inactive', 'active']
674  
675 List only jobs in these states.
676  
677 =item tasks
678  
679 tasks => ['foo', 'bar']
680  
681 List only jobs for these tasks.
682  
683 =back
684  
685 These fields are currently available:
686  
687 =over 2
688  
689 =item args
690  
691 args => ['foo', 'bar']
692  
693 Job arguments.
694  
695 =item attempts
696  
697 attempts => 25
698  
699 Number of times performing this job will be attempted.
700  
701 =item children
702  
703 children => ['10026', '10027', '10028']
704  
705 Jobs depending on this job.
706  
707 =item created
708  
709 created => 784111777
710  
711 Epoch time job was created.
712  
713 =item delayed
714  
715 delayed => 784111777
716  
717 Epoch time job was delayed to.
718  
719 =item expires
720  
721 expires => 784111777
722  
723 Epoch time job is valid until before it expires.
724  
725 =item finished
726  
727 finished => 784111777
728  
729 Epoch time job was finished.
730  
731 =item id
732  
733 id => 10025
734  
735 Job id.
736  
737 =item lax
738  
739 lax => 0
740  
741 Existing jobs this job depends on may also have failed to allow for it to be processed.
742  
743 =item notes
744  
745 notes => {foo => 'bar', baz => [1, 2, 3]}
746  
747 Hash reference with arbitrary metadata for this job.
748  
749 =item parents
750  
751 parents => ['10023', '10024', '10025']
752  
753 Jobs this job depends on.
754  
755 =item priority
756  
757 priority => 3
758  
759 Job priority.
760  
761 =item queue
762  
763 queue => 'important'
764  
765 Queue name.
766  
767 =item result
768  
769 result => 'All went well!'
770  
771 Job result.
772  
773 =item retried
774  
775 retried => 784111777
776  
777 Epoch time job has been retried.
778  
779 =item retries
780  
781 retries => 3
782  
783 Number of times job has been retried.
784  
785 =item started
786  
787 started => 784111777
788  
789 Epoch time job was started.
790  
791 =item state
792  
793 state => 'inactive'
794  
795 Current job state, usually C<active>, C<failed>, C<finished> or C<inactive>.
796  
797 =item task
798  
799 task => 'foo'
800  
801 Task name.
802  
803 =item time
804  
805 time => 78411177
806  
807 Server time.
808  
809 =item worker
810  
811 worker => '154'
812  
813 Id of worker that is processing the job.
814  
815 =back
816  
817 =head2 list_locks
818  
819 my $results = $backend->list_locks($offset, $limit);
820 my $results = $backend->list_locks($offset, $limit, {names => ['foo']});
821  
822 Returns information about locks in batches.
823  
824 # Get the total number of results (without limit)
825 my $num = $backend->list_locks(0, 100, {names => ['bar']})->{total};
826  
827 # Check expiration time
828 my $results = $backend->list_locks(0, 1, {names => ['foo']});
829 my $expires = $results->{locks}[0]{expires};
830  
831 These options are currently available:
832  
833 =over 2
834  
835 =item names
836  
837 names => ['foo', 'bar']
838  
839 List only locks with these names.
840  
841 =back
842  
843 These fields are currently available:
844  
845 =over 2
846  
847 =item expires
848  
849 expires => 784111777
850  
851 Epoch time this lock will expire.
852  
853 =item id
854  
855 id => 1
856  
857 Lock id.
858  
859 =item name
860  
861 name => 'foo'
862  
863 Lock name.
864  
865 =back
866  
867 =head2 list_schedules
868  
869 my $results = $backend->list_schedules($offset, $limit);
870 my $results = $backend->list_schedules($offset, $limit, {names => ['daily']});
871  
872 Returns information about schedules in batches.
873  
874 # Get the total number of results (without limit)
875 my $num = $backend->list_schedules(0, 100)->{total};
876  
877 # Check next firing time
878 my $results = $backend->list_schedules(0, 1, {names => ['daily']});
879 my $next = $results->{schedules}[0]{next_run};
880  
881 These options are currently available:
882  
883 =over 2
884  
885 =item before
886  
887 before => 23
888  
889 List only schedules before this id.
890  
891 =item ids
892  
893 ids => ['23', '24']
894  
895 List only schedules with these ids.
896  
897 =item names
898  
899 names => ['foo', 'bar']
900  
901 List only schedules with these names.
902  
903 =back
904  
905 These fields are currently available:
906  
907 =over 2
908  
909 =item args
910  
911 args => ['foo', 'bar']
912  
913 Job arguments used for each enqueued job.
914  
915 =item attempts
916  
917 attempts => 25
918  
919 Number of attempts each enqueued job will get.
920  
921 =item created
922  
923 created => 784111777
924  
925 Epoch time the schedule was created.
926  
927 =item cron
928  
929 cron => '0 9 * * 1-5'
930  
931 Cron expression.
932  
933 =item expire
934  
935 expire => 300
936  
937 Expiration in seconds for each enqueued job.
938  
939 =item id
940  
941 id => 23
942  
943 Schedule id.
944  
945 =item last_job
946  
947 last_job => '10025'
948  
949 Id of the most recently enqueued job, or C<undef> if the schedule has not fired yet.
950  
951 =item last_run
952  
953 last_run => 784111777
954  
955 Epoch time the schedule last fired, or C<undef> if it has not fired yet.
956  
957 =item lax
958  
959 lax => 0
960  
961 Lax dependency setting for each enqueued job.
962  
963 =item name
964  
965 name => 'daily'
966  
967 Schedule name.
968  
969 =item next_run
970  
971 next_run => 784111777
972  
973 Epoch time the schedule will fire next.
974  
975 =item notes
976  
977 notes => {foo => 'bar'}
978  
979 Hash reference with arbitrary metadata applied to each enqueued job.
980  
981 =item paused
982  
983 paused => 0
984  
985 True if the schedule is paused and will not fire.
986  
987 =item priority
988  
989 priority => 0
990  
991 Priority of each enqueued job.
992  
993 =item queue
994  
995 queue => 'default'
996  
997 Queue each enqueued job is placed in.
998  
999 =item task
1000  
1001 task => 'foo'
1002  
1003 Task name.
1004  
1005 =back
1006  
1007 =head2 list_workers
1008  
1009 my $results = $backend->list_workers($offset, $limit);
1010 my $results = $backend->list_workers($offset, $limit, {ids => [23]});
1011  
1012 Returns information about workers in batches.
1013  
1014 # Get the total number of results (without limit)
1015 my $num = $backend->list_workers(0, 100)->{total};
1016  
1017 # Check worker host
1018 my $results = $backend->list_workers(0, 1, {ids => [$worker_id]});
1019 my $host = $results->{workers}[0]{host};
1020  
1021 These options are currently available:
1022  
1023 =over 2
1024  
1025 =item before
1026  
1027 before => 23
1028  
1029 List only workers before this id.
1030  
1031 =item ids
1032  
1033 ids => ['23', '24']
1034  
1035 List only workers with these ids.
1036  
1037 =back
1038  
1039 These fields are currently available:
1040  
1041 =over 2
1042  
1043 =item id
1044  
1045 id => 22
1046  
1047 Worker id.
1048  
1049 =item host
1050  
1051 host => 'localhost'
1052  
1053 Worker host.
1054  
1055 =item jobs
1056  
1057 jobs => ['10023', '10024', '10025', '10029']
1058  
1059 Ids of jobs the worker is currently processing.
1060  
1061 =item notified
1062  
1063 notified => 784111777
1064  
1065 Epoch time worker sent the last heartbeat.
1066  
1067 =item pid
1068  
1069 pid => 12345
1070  
1071 Process id of worker.
1072  
1073 =item started
1074  
1075 started => 784111777
1076  
1077 Epoch time worker was started.
1078  
1079 =item status
1080  
1081 status => {queues => ['default', 'important']}
1082  
1083 Hash reference with whatever status information the worker would like to share.
1084  
1085 =back
1086  
1087 =head2 lock
1088  
1089 my $bool = $backend->lock('foo', 3600);
1090 my $bool = $backend->lock('foo', 3600, {limit => 20});
1091  
1092 Try to acquire a named lock that will expire automatically after the given amount of time in seconds. An expiration
1093 time of C<0> can be used to check if a named lock already exists without creating one.
1094  
1095 These options are currently available:
1096  
1097 =over 2
1098  
1099 =item limit
1100  
1101 limit => 20
1102  
1103 Number of shared locks with the same name that can be active at the same time, defaults to C<1>.
1104  
1105 =back
1106  
1107 =head2 new
1108  
1109 my $backend = Minion::Backend::Pg->new('postgresql://postgres@/test');
1110 my $backend = Minion::Backend::Pg->new(Mojo::Pg->new);
1111  
1112 Construct a new L<Minion::Backend::Pg> object.
1113  
1114 =head2 note
1115  
1116 my $bool = $backend->note($job_id, {mojo => 'rocks', minion => 'too'});
1117  
1118 Change one or more metadata fields for a job. Setting a value to C<undef> will remove the field.
1119  
1120 =head2 pause_schedule
1121  
1122 my $bool = $backend->pause_schedule('daily');
1123  
1124 Pause a schedule by name so it stops firing until resumed. Returns true on success, false if the schedule does not
1125 exist.
1126  
1127 =head2 receive
1128  
1129 my $commands = $backend->receive($worker_id);
1130  
1131 Receive remote control commands for worker.
1132  
1133 =head2 register_worker
1134  
1135 my $worker_id = $backend->register_worker;
1136 my $worker_id = $backend->register_worker($worker_id);
1137 my $worker_id = $backend->register_worker(
1138 $worker_id, {status => {queues => ['default', 'important']}});
1139  
1140 Register worker or send heartbeat to show that this worker is still alive.
1141  
1142 These options are currently available:
1143  
1144 =over 2
1145  
1146 =item status
1147  
1148 status => {queues => ['default', 'important']}
1149  
1150 Hash reference with whatever status information the worker would like to share.
1151  
1152 =back
1153  
1154 =head2 remove_job
1155  
1156 my $bool = $backend->remove_job($job_id);
1157  
1158 Remove C<failed>, C<finished> or C<inactive> job from queue.
1159  
1160 =head2 repair
1161  
1162 $backend->repair;
1163  
1164 Repair worker registry and job queue if necessary.
1165  
1166 =head2 reset
1167  
1168 $backend->reset({all => 1});
1169  
1170 Reset job queue.
1171  
1172 These options are currently available:
1173  
1174 =over 2
1175  
1176 =item all
1177  
1178 all => 1
1179  
1180 Reset everything.
1181  
1182 =item locks
1183  
1184 locks => 1
1185  
1186 Reset only locks.
1187  
1188 =back
1189  
1190 =head2 resume_schedule
1191  
1192 my $bool = $backend->resume_schedule('daily');
1193  
1194 Resume a previously paused schedule. Returns true on success, false if the schedule does not exist.
1195  
1196 =head2 retry_job
1197  
1198 my $bool = $backend->retry_job($job_id, $retries);
1199 my $bool = $backend->retry_job($job_id, $retries, {delay => 10});
1200  
1201 Transition job back to C<inactive> state, already C<inactive> jobs may also be retried to change options.
1202  
1203 These options are currently available:
1204  
1205 =over 2
1206  
1207 =item attempts
1208  
1209 attempts => 25
1210  
1211 Number of times performing this job will be attempted.
1212  
1213 =item delay
1214  
1215 delay => 10
1216  
1217 Delay job for this many seconds (from now), defaults to C<0>.
1218  
1219 =item expire
1220  
1221 expire => 300
1222  
1223 Job is valid for this many seconds (from now) before it expires.
1224  
1225 =item lax
1226  
1227 lax => 1
1228  
1229 Existing jobs this job depends on may also have transitioned to the C<failed> state to allow for it to be processed,
1230 defaults to C<false>.
1231  
1232 =item parents
1233  
1234 parents => [$id1, $id2, $id3]
1235  
1236 Jobs this job depends on.
1237  
1238 =item priority
1239  
1240 priority => 5
1241  
1242 Job priority.
1243  
1244 =item queue
1245  
1246 queue => 'important'
1247  
1248 Queue to put job in.
1249  
1250 =back
1251  
1252 =head2 schedule
1253  
1254 my $id = $backend->schedule('daily', '0 4 * * *', 'cleanup');
1255 my $id = $backend->schedule('daily', '0 4 * * *', 'cleanup', [@args]);
1256 my $id = $backend->schedule(
1257 'daily', '0 4 * * *', 'cleanup', [@args], {priority => 5});
1258  
1259 Create or replace a schedule by unique name. Updating a schedule with the same cron expression preserves its current
1260 firing time; changing the expression recomputes it.
1261  
1262 These options are currently available:
1263  
1264 =over 2
1265  
1266 =item attempts
1267  
1268 attempts => 25
1269  
1270 Number of times performing each enqueued job will be attempted, defaults to C<1>.
1271  
1272 =item expire
1273  
1274 expire => 300
1275  
1276 Each enqueued job is valid for this many seconds before it expires.
1277  
1278 =item lax
1279  
1280 lax => 1
1281  
1282 Existing jobs each enqueued job depends on may also have transitioned to the C<failed> state, defaults to C<false>.
1283  
1284 =item notes
1285  
1286 notes => {foo => 'bar'}
1287  
1288 Hash reference with arbitrary metadata applied to each enqueued job.
1289  
1290 =item priority
1291  
1292 priority => 5
1293  
1294 Priority of each enqueued job, defaults to C<0>.
1295  
1296 =item queue
1297  
1298 queue => 'important'
1299  
1300 Queue to put each enqueued job in, defaults to C<default>.
1301  
1302 =back
1303  
1304 =head2 stats
1305  
1306 my $stats = $backend->stats;
1307  
1308 Get statistics for the job queue.
1309  
1310 These fields are currently available:
1311  
1312 =over 2
1313  
1314 =item active_jobs
1315  
1316 active_jobs => 100
1317  
1318 Number of jobs in C<active> state.
1319  
1320 =item active_locks
1321  
1322 active_locks => 100
1323  
1324 Number of active named locks.
1325  
1326 =item active_workers
1327  
1328 active_workers => 100
1329  
1330 Number of workers that are currently processing a job.
1331  
1332 =item delayed_jobs
1333  
1334 delayed_jobs => 100
1335  
1336 Number of jobs in C<inactive> state that are scheduled to run at specific time in the future.
1337  
1338 =item enqueued_jobs
1339  
1340 enqueued_jobs => 100000
1341  
1342 Rough estimate of how many jobs have ever been enqueued.
1343  
1344 =item failed_jobs
1345  
1346 failed_jobs => 100
1347  
1348 Number of jobs in C<failed> state.
1349  
1350 =item finished_jobs
1351  
1352 finished_jobs => 100
1353  
1354 Number of jobs in C<finished> state.
1355  
1356 =item inactive_jobs
1357  
1358 inactive_jobs => 100
1359  
1360 Number of jobs in C<inactive> state.
1361  
1362 =item inactive_schedules
1363  
1364 inactive_schedules => 100
1365  
1366 Number of schedules that are currently paused.
1367  
1368 =item inactive_workers
1369  
1370 inactive_workers => 100
1371  
1372 Number of workers that are currently not processing a job.
1373  
1374 =item schedules
1375  
1376 schedules => 100
1377  
1378 Number of schedules that are currently active.
1379  
1380 =item uptime
1381  
1382 uptime => 1000
1383  
1384 Uptime in seconds.
1385  
1386 =item workers
1387  
1388 workers => 200;
1389  
1390 Number of registered workers.
1391  
1392 =back
1393  
1394 =head2 unlock
1395  
1396 my $bool = $backend->unlock('foo');
1397  
1398 Release a named lock.
1399  
1400 =head2 unregister_worker
1401  
1402 $backend->unregister_worker($worker_id);
1403  
1404 Unregister worker.
1405  
1406 =head2 unschedule
1407  
1408 my $bool = $backend->unschedule('daily');
1409  
1410 Remove a schedule by name. Returns true on success, false if the schedule does not exist.
1411  
1412 =head1 SEE ALSO
1413  
1414 L<Minion>, L<Minion::Guide>, L<https://minion.pm>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
1415  
1416 =cut