include/pq_backend.h

filter: Statementstmt 97.1% 647 / 666 Branchbran 71.3% 321 / 450 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 86.7% 968 / 1116 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xs/cron.xs ↑ Summary include/pq_log.h »
1 #ifndef PQ_BACKEND_H
2 #define PQ_BACKEND_H
3  
4 /* pq_backend.h - the shared backend implementation, plus the per-driver
5 * dispatch.
6 *
7 * The split is the point of this file. Everything below the dispatch block
8 * is written once and behaves identically on every backend, and the
9 * conformance suite (t/lib/PQConform.pm) exists to prove that claim rather
10 * than assert it. What a backend genuinely has to do differently is exactly
11 * the seven entries dispatched here.
12 *
13 * If you are adding a third backend: the operations below are the ones you
14 * do NOT need to touch.
15 *
16 * Include after pq_sqlite.h and pq_pg.h. */
17  
18 #include <stdint.h>
19  
20 /* ---- per-driver dispatch ---------------------------------------------------
21 *
22 * Dispatch is on the DBI driver name rather than on the class, so a
23 * subclass of a shipped backend keeps working, and a hand-written backend
24 * that never reaches this file is unaffected. */
25  
26 2896 static int pq_is_pg(pTHX_ SV *self) {
27 2896 return pq_driver_is(aTHX_ pq_dbh(aTHX_ self), "Pg");
28 }
29  
30 201 static double pq_probe_clock(pTHX_ SV *dbh) {
31 201 ▶ if (pq_driver_is(aTHX_ dbh, "SQLite")) return pq_sqlite_probe_clock(aTHX_ dbh);
Branch: 1 branch
BranchTrueFalseTotal
if (pq_driver_is(aTHX_ dbh, "SQLite")) return pq_sqlite_probe_clock(aTHX_ dbh); 201 0 201
32 0 ▶ if (pq_driver_is(aTHX_ dbh, "Pg")) return pq_pg_probe_clock(aTHX_ dbh);
Branch: 1 branch
BranchTrueFalseTotal
if (pq_driver_is(aTHX_ dbh, "Pg")) return pq_pg_probe_clock(aTHX_ dbh); 0 0 0
33 /* An unknown driver is not fatal: a zero delta just means "trust the
34 * local clock", which is what a single-host deployment has anyway. */
35 0 return 0.0;
36 }
37  
38 138 static void pq_txn_begin_exclusive(pTHX_ SV *self) {
39 138 ▶ if (pq_is_pg(aTHX_ self)) pq_pg_begin_exclusive(aTHX_ self);
Branch: 1 branch
BranchTrueFalseTotal
if (pq_is_pg(aTHX_ self)) pq_pg_begin_exclusive(aTHX_ self); 0 138 138
40 138 else pq_sqlite_begin_exclusive(aTHX_ self);
41 138 }
42  
43 /* The plain transaction the state transitions use: no advisory lock - on
44 * Pg the migrate lock would serialise every finish across the fleet. */
45 180 static void pq_txn_begin(pTHX_ SV *self) {
46 180 ▶ if (pq_is_pg(aTHX_ self)) pq_pg_begin(aTHX_ self);
Branch: 1 branch
BranchTrueFalseTotal
if (pq_is_pg(aTHX_ self)) pq_pg_begin(aTHX_ self); 0 180 180
47 180 else pq_sqlite_begin_exclusive(aTHX_ self);
48 180 }
49  
50 318 static void pq_txn_commit(pTHX_ SV *self) {
51 318 ▶ if (pq_is_pg(aTHX_ self)) pq_pg_commit(aTHX_ self);
Branch: 1 branch
BranchTrueFalseTotal
if (pq_is_pg(aTHX_ self)) pq_pg_commit(aTHX_ self); 0 318 318
52 318 else pq_sqlite_commit(aTHX_ self);
53 318 }
54  
55 static void pq_txn_rollback(pTHX_ SV *self) PERL_UNUSED_DECL;
56 0 static void pq_txn_rollback(pTHX_ SV *self) {
57 0 ▶ if (pq_is_pg(aTHX_ self)) pq_pg_rollback(aTHX_ self);
Branch: 1 branch
BranchTrueFalseTotal
if (pq_is_pg(aTHX_ self)) pq_pg_rollback(aTHX_ self); 0 0 0
58 0 else pq_sqlite_rollback(aTHX_ self);
59 0 }
60  
61 668 static const char *const *pq_migration_steps(pTHX_ SV *self) {
62 668 ▶ return pq_is_pg(aTHX_ self) ? pq_pg_steps(aTHX) : pq_sqlite_steps(aTHX);
Branch: 1 branch
BranchTrueFalseTotal
return pq_is_pg(aTHX_ self) ? pq_pg_steps(aTHX) : pq_sqlite_steps(aTHX); 0 668 668
63 }
64  
65 332 static void pq_check_server_version(pTHX_ SV *self) {
66 332 ▶ if (pq_is_pg(aTHX_ self)) pq_pg_check_version(aTHX_ self);
Branch: 1 branch
BranchTrueFalseTotal
if (pq_is_pg(aTHX_ self)) pq_pg_check_version(aTHX_ self); 0 332 332
67 332 else pq_sqlite_check_version(aTHX_ self);
68 332 }
69  
70 237 static SV *pq_dequeue(pTHX_ SV *self, IV worker_id, AV *queues, AV *tasks) {
71 237 SV *job = pq_is_pg(aTHX_ self)
72 0 ? pq_pg_dequeue(aTHX_ self, worker_id, queues, tasks)
73 237 ▶ : pq_sqlite_dequeue(aTHX_ self, worker_id, queues, tasks);
Branch: 1 branch
BranchTrueFalseTotal
: pq_sqlite_dequeue(aTHX_ self, worker_id, queues, tasks); 0 237 237
74 237 ▶ if (job && SvROK(job)) {
Branch: 2 branches
BranchTrueFalseTotal
if (job && SvROK(job)) { 200 37 237
if (job && SvROK(job)) { 200 0 200
75 200 HV *row = (HV *)SvRV(job);
76 200 SV *id = pq_get(aTHX_ row, "id");
77 200 SV *rt = pq_get(aTHX_ row, "retries");
78 200 SV *at = pq_get(aTHX_ row, "attempts");
79 200 ▶ if (id && SvOK(id))
Branch: 2 branches
BranchTrueFalseTotal
if (id && SvOK(id)) 200 0 200
if (id && SvOK(id)) 200 0 200
80 600 ▶ pq_log_addf(aTHX_ self, SvIV(id), "info",
Branch: 2 branches
BranchTrueFalseTotal
pq_log_addf(aTHX_ self, SvIV(id), "info", 200 0 200
pq_log_addf(aTHX_ self, SvIV(id), "info", 200 0 200
81 "claimed by worker %ld (attempt %ld of %ld)",
82 (long)worker_id,
83 200 ▶ (long)((rt && SvOK(rt)) ? SvIV(rt) : 0) + 1,
Branch: 1 branch
BranchTrueFalseTotal
(long)((rt && SvOK(rt)) ? SvIV(rt) : 0) + 1, 200 0 200
84 200 ▶ (long)((at && SvOK(at)) ? SvIV(at) : 1));
Branch: 1 branch
BranchTrueFalseTotal
(long)((at && SvOK(at)) ? SvIV(at) : 1)); 200 0 200
85 }
86 237 return job;
87 }
88  
89 978 static void pq_notify(pTHX_ SV *self, SV *queue, IV id) {
90 978 ▶ if (pq_is_pg(aTHX_ self)) pq_pg_notify(aTHX_ self, queue, id);
Branch: 1 branch
BranchTrueFalseTotal
if (pq_is_pg(aTHX_ self)) pq_pg_notify(aTHX_ self, queue, id); 0 978 978
91 978 else pq_sqlite_notify(aTHX_ self, queue, id);
92 978 }
93  
94 /* ---- enqueue ---------------------------------------------------------------
95 *
96 * opts: queue, priority, delay, attempts, expire, notes, timeout, lax,
97 * unique, parents.
98 *
99 * With parents, the whole enqueue is one transaction and the parent rows
100 * are read under a lock (FOR UPDATE on Pg; BEGIN IMMEDIATE covers SQLite):
101 * without that, a parent finishing between our read and our commit would
102 * decrement children it cannot see yet, and this child would hang forever
103 * with parents_left = 1. That interleaving is exactly the drift the
104 * conformance battery hunts.
105 *
106 * A parent id that does not exist is treated as already gone - the same
107 * reading Minion takes - so a chain can be enqueued even after early
108 * members were removed by retention. */
109 1000 static IV pq_enqueue(pTHX_ SV *self, SV *task, SV *args, HV *opts) {
110 SV *sql, *queue, *notes_json, *args_json, *v;
111 1000 SV *unique = NULL;
112 1000 AV *bind, *parents = NULL;
113 1000 double now, delayed, expires = 0.0, timeout = 0.0;
114 1000 int has_expires = 0, has_timeout = 0, lax = 0, in_txn = 0;
115 1000 IV priority = 0, attempts = 1, id = 0;
116  
117 1000 pq_name_check(aTHX_ task, "task");
118  
119 987 ▶ queue = opts ? pq_get(aTHX_ opts, "queue") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
queue = opts ? pq_get(aTHX_ opts, "queue") : NULL; 987 0 987
120 987 ▶ if (queue && SvOK(queue)) pq_name_check(aTHX_ queue, "queue");
Branch: 2 branches
BranchTrueFalseTotal
if (queue && SvOK(queue)) pq_name_check(aTHX_ queue, "queue"); 45 942 987
if (queue && SvOK(queue)) pq_name_check(aTHX_ queue, "queue"); 45 0 45
121 942 else queue = sv_2mortal(newSVpvs("default"));
122  
123 985 ▶ if (opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts) { 985 0 985
124 985 ▶ if ((v = pq_get(aTHX_ opts, "priority")) && SvOK(v)) priority = SvIV(v);
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pq_get(aTHX_ opts, "priority")) && SvOK(v)) priority = SvIV(v); 29 956 985
if ((v = pq_get(aTHX_ opts, "priority")) && SvOK(v)) priority = SvIV(v); 29 0 29
125 985 ▶ if ((v = pq_get(aTHX_ opts, "attempts")) && SvOK(v)) attempts = SvIV(v);
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pq_get(aTHX_ opts, "attempts")) && SvOK(v)) attempts = SvIV(v); 31 954 985
if ((v = pq_get(aTHX_ opts, "attempts")) && SvOK(v)) attempts = SvIV(v); 31 0 31
126 985 ▶ if (attempts < 1)
Branch: 1 branch
BranchTrueFalseTotal
if (attempts < 1) 1 984 985
127 1 croak("Punk::Queue: attempts must be at least 1, not %ld",
128 (long)attempts);
129 984 ▶ if ((v = pq_get(aTHX_ opts, "lax")) && SvTRUE(v)) lax = 1;
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pq_get(aTHX_ opts, "lax")) && SvTRUE(v)) lax = 1; 3 981 984
if ((v = pq_get(aTHX_ opts, "lax")) && SvTRUE(v)) lax = 1; 3 0 3
130 984 ▶ if ((v = pq_get(aTHX_ opts, "unique")) && SvOK(v)) {
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pq_get(aTHX_ opts, "unique")) && SvOK(v)) { 15 969 984
if ((v = pq_get(aTHX_ opts, "unique")) && SvOK(v)) { 15 0 15
131 15 pq_name_check(aTHX_ v, "unique");
132 14 unique = v;
133 }
134 983 ▶ if ((v = pq_get(aTHX_ opts, "timeout")) && SvOK(v)) {
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pq_get(aTHX_ opts, "timeout")) && SvOK(v)) { 5 978 983
if ((v = pq_get(aTHX_ opts, "timeout")) && SvOK(v)) { 5 0 5
135 5 timeout = SvNV(v);
136 5 has_timeout = timeout > 0;
137 }
138 983 ▶ if ((v = pq_get(aTHX_ opts, "parents")) && SvOK(v)) {
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pq_get(aTHX_ opts, "parents")) && SvOK(v)) { 14 969 983
if ((v = pq_get(aTHX_ opts, "parents")) && SvOK(v)) { 14 0 14
139 14 ▶ if (!(SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVAV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVAV)) 13 1 14
if (!(SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVAV)) 0 13 13
140 1 croak("Punk::Queue: parents must be an array reference");
141 13 parents = (AV *)SvRV(v);
142 13 ▶ if (av_len(parents) < 0) parents = NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(parents) < 0) parents = NULL; 0 13 13
143 }
144 }
145  
146 982 now = pq_now(aTHX_ self);
147 982 delayed = now;
148 982 ▶ if (opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts) { 982 0 982
149 982 ▶ if ((v = pq_get(aTHX_ opts, "delay")) && SvOK(v))
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pq_get(aTHX_ opts, "delay")) && SvOK(v)) 8 974 982
if ((v = pq_get(aTHX_ opts, "delay")) && SvOK(v)) 8 0 8
150 8 delayed = now + SvNV(v);
151 982 ▶ if ((v = pq_get(aTHX_ opts, "expire")) && SvOK(v)) {
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pq_get(aTHX_ opts, "expire")) && SvOK(v)) { 5 977 982
if ((v = pq_get(aTHX_ opts, "expire")) && SvOK(v)) { 5 0 5
152 5 expires = now + SvNV(v);
153 5 has_expires = 1;
154 }
155 }
156  
157 982 args_json = sv_2mortal(pq_json_encode(aTHX_ args, "[]"));
158 982 ▶ notes_json = sv_2mortal(pq_json_encode(aTHX_
Branch: 1 branch
BranchTrueFalseTotal
notes_json = sv_2mortal(pq_json_encode(aTHX_ 982 0 982
159 opts ? pq_get(aTHX_ opts, "notes") : NULL, "{}"));
160  
161 982 ▶ if (parents) { pq_txn_begin(aTHX_ self); in_txn = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (parents) { pq_txn_begin(aTHX_ self); in_txn = 1; } 13 969 982
162  
163 982 sql = pq_sql_new(aTHX_
164 "INSERT INTO pq_jobs"
165 " (task, args, queue, state, priority, attempts, created, delayed,"
166 " expires, notes, timeout, lax, lock_key)"
167 " VALUES (?, ?, ?, 'inactive', ?, ?, ?, ?, ?, ?, ?, ?, ?)");
168  
169 982 bind = pq_binds(aTHX);
170 982 pq_bind_sv(aTHX_ bind, task);
171 982 pq_bind_sv(aTHX_ bind, args_json);
172 982 pq_bind_sv(aTHX_ bind, queue);
173 982 pq_bind_iv(aTHX_ bind, priority);
174 982 pq_bind_iv(aTHX_ bind, attempts);
175 982 pq_bind_nv(aTHX_ bind, now);
176 982 pq_bind_nv(aTHX_ bind, delayed);
177 982 ▶ if (has_expires) pq_bind_nv(aTHX_ bind, expires);
Branch: 1 branch
BranchTrueFalseTotal
if (has_expires) pq_bind_nv(aTHX_ bind, expires); 5 977 982
178 977 else pq_bind_undef(aTHX_ bind);
179 982 pq_bind_sv(aTHX_ bind, notes_json);
180 982 ▶ if (has_timeout) pq_bind_nv(aTHX_ bind, timeout);
Branch: 1 branch
BranchTrueFalseTotal
if (has_timeout) pq_bind_nv(aTHX_ bind, timeout); 5 977 982
181 977 else pq_bind_undef(aTHX_ bind);
182 982 pq_bind_iv(aTHX_ bind, lax);
183 982 ▶ if (unique) pq_bind_sv(aTHX_ bind, unique);
Branch: 1 branch
BranchTrueFalseTotal
if (unique) pq_bind_sv(aTHX_ bind, unique); 14 968 982
184 968 else pq_bind_undef(aTHX_ bind);
185  
186 /* The insert is trapped only when `unique` is set: the partial unique
187 * index rejecting a second live job with the same key is the expected
188 * path there, and the answer is the existing job's id, not an error. */
189 {
190 982 int died = 0;
191 982 SV *sth, *errmsg = NULL;
192 982 ▶ if (pq_has_returning(aTHX_ self)) pq_sql_cat(aTHX_ sql, " RETURNING id");
Branch: 1 branch
BranchTrueFalseTotal
if (pq_has_returning(aTHX_ self)) pq_sql_cat(aTHX_ sql, " RETURNING id"); 982 0 982
193  
194 982 sth = pq_sth(aTHX_ self, sql); /* mortal, borrowed for this scope */
195 {
196 981 SSize_t n = av_len(bind) + 1, i;
197 981 SV **ea = (SV **)pq_xmalloc(aTHX_ sizeof(SV *) * (size_t)n);
198 SV *r;
199 12753 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 11772 981 12753
200 11772 SV **e = av_fetch(bind, i, 0);
201 11772 ▶ ea[i] = (e && *e) ? *e : &PL_sv_undef;
Branch: 2 branches
BranchTrueFalseTotal
ea[i] = (e && *e) ? *e : &PL_sv_undef; 11772 0 11772
ea[i] = (e && *e) ? *e : &PL_sv_undef; 11772 0 11772
202 }
203 981 r = pq_call_meth_ev(aTHX_ sth, "execute", ea, (int)n, 1, &died);
204 981 safefree(ea);
205 981 ▶ if (r) SvREFCNT_dec(r);
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); 978 3 981
206 }
207 981 ▶ if (died) {
Branch: 1 branch
BranchTrueFalseTotal
if (died) { 3 978 981
208 3 ▶ errmsg = sv_2mortal(newSVsv(ERRSV));
Branch: 1 branch
BranchTrueFalseTotal
errmsg = sv_2mortal(newSVsv(ERRSV)); 3 0 3
209 3 ▶ if (in_txn) { pq_txn_rollback(aTHX_ self); in_txn = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (in_txn) { pq_txn_rollback(aTHX_ self); in_txn = 0; } 0 3 3
210 3 ▶ if (unique) {
Branch: 1 branch
BranchTrueFalseTotal
if (unique) { 3 0 3
211 3 AV *b2 = pq_binds(aTHX), *row;
212 3 pq_bind_sv(aTHX_ b2, unique);
213 3 row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
214 "SELECT id FROM pq_jobs WHERE lock_key = ?"
215 " AND state IN ('inactive', 'active')")), b2);
216 3 ▶ if (row) {
Branch: 1 branch
BranchTrueFalseTotal
if (row) { 3 0 3
217 3 id = pq_col_iv(aTHX_ row, 0);
218 3 SvREFCNT_dec((SV *)row);
219 3 return id; /* the existing live job */
220 }
221 }
222 0 croak_sv(errmsg);
223 }
224 978 ▶ if (pq_has_returning(aTHX_ self)) {
Branch: 1 branch
BranchTrueFalseTotal
if (pq_has_returning(aTHX_ self)) { 978 0 978
225 978 AV *row = pq_fetchrow(aTHX_ sth);
226 978 ▶ if (row) { id = pq_col_iv(aTHX_ row, 0); SvREFCNT_dec((SV *)row); }
Branch: 1 branch
BranchTrueFalseTotal
if (row) { id = pq_col_iv(aTHX_ row, 0); SvREFCNT_dec((SV *)row); } 978 0 978
227 978 { SV *r = pq_call_meth(aTHX_ sth, "finish", NULL, 0, 1);
228 978 ▶ if (r) SvREFCNT_dec(r); }
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); } 978 0 978
229 }
230 0 else id = pq_last_insert_id(aTHX_ self);
231 }
232  
233 978 ▶ if (!id) {
Branch: 1 branch
BranchTrueFalseTotal
if (!id) { 0 978 978
234 0 ▶ if (in_txn) pq_txn_rollback(aTHX_ self);
Branch: 1 branch
BranchTrueFalseTotal
if (in_txn) pq_txn_rollback(aTHX_ self); 0 0 0
235 0 croak("Punk::Queue: enqueue produced no job id");
236 }
237  
238 978 ▶ if (parents) {
Branch: 1 branch
BranchTrueFalseTotal
if (parents) { 13 965 978
239 13 SSize_t np = av_len(parents) + 1, i, nseen = 0;
240 13 IV blocking = 0;
241 13 IV *seen = (IV *)pq_xmalloc(aTHX_ sizeof(IV) * (size_t)np);
242  
243 29 ▶ for (i = 0; i < np; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < np; i++) { 16 13 29
244 16 SV **e = av_fetch(parents, i, 0);
245 IV pid_;
246 AV *b, *row;
247 SV *psql;
248 SSize_t k;
249 16 int dupe = 0;
250 16 ▶ if (!(e && *e && SvOK(*e))) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(e && *e && SvOK(*e))) continue; 16 0 16
if (!(e && *e && SvOK(*e))) continue; 16 0 16
if (!(e && *e && SvOK(*e))) continue; 0 16 16
251 16 pid_ = SvIV(*e);
252 16 ▶ if (pid_ == id) continue; /* self-dependency is nonsense */
Branch: 1 branch
BranchTrueFalseTotal
if (pid_ == id) continue; /* self-dependency is nonsense */ 0 16 16
253  
254 /* dedupe in C rather than letting the deps PK reject it: an
255 * error inside a Pg transaction aborts the whole transaction
256 * (the phase-2 lesson), so a trapped constraint violation is
257 * not a tool available in here */
258 17 ▶ for (k = 0; k < nseen; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nseen; k++) 3 14 17
259 3 ▶ if (seen[k] == pid_) { dupe = 1; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (seen[k] == pid_) { dupe = 1; break; } 2 1 3
260 16 ▶ if (dupe) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (dupe) continue; 2 14 16
261 14 seen[nseen++] = pid_;
262  
263 /* lock the parent row while we decide whether it blocks */
264 14 psql = pq_sql_new(aTHX_
265 "SELECT state FROM pq_jobs WHERE id = ?");
266 14 ▶ if (pq_is_pg(aTHX_ self)) pq_sql_cat(aTHX_ psql, " FOR UPDATE");
Branch: 1 branch
BranchTrueFalseTotal
if (pq_is_pg(aTHX_ self)) pq_sql_cat(aTHX_ psql, " FOR UPDATE"); 0 14 14
267 14 b = pq_binds(aTHX);
268 14 pq_bind_iv(aTHX_ b, pid_);
269 14 row = pq_selectrow(aTHX_ self, psql, b);
270 14 ▶ if (!row) continue; /* gone = already done */
Branch: 1 branch
BranchTrueFalseTotal
if (!row) continue; /* gone = already done */ 1 13 14
271  
272 {
273 13 SV *st = pq_col(aTHX_ row, 0);
274 26 ▶ const char *s = SvOK(st) ? SvPV_nolen(st) : "";
Branch: 1 branch
BranchTrueFalseTotal
const char *s = SvOK(st) ? SvPV_nolen(st) : ""; 13 0 13
275 3 ▶ int done = lax ? (strEQ(s, "finished") || strEQ(s, "failed"))
Branch: 2 branches
BranchTrueFalseTotal
int done = lax ? (strEQ(s, "finished") || strEQ(s, "failed")) 3 0 3
int done = lax ? (strEQ(s, "finished") || strEQ(s, "failed")) 0 3 3
276 16 ▶ : strEQ(s, "finished");
Branch: 1 branch
BranchTrueFalseTotal
: strEQ(s, "finished"); 3 10 13
277 13 SvREFCNT_dec((SV *)row);
278  
279 /* the dep row records lineage even when not blocking */
280 {
281 13 AV *b2 = pq_binds(aTHX);
282 13 pq_bind_iv(aTHX_ b2, id);
283 13 pq_bind_iv(aTHX_ b2, pid_);
284 13 (void)pq_do(aTHX_ self, sv_2mortal(newSVpvs(
285 "INSERT INTO pq_job_deps (job_id, parent_id)"
286 " VALUES (?, ?)")), b2);
287 }
288 13 ▶ if (!done) blocking++;
Branch: 1 branch
BranchTrueFalseTotal
if (!done) blocking++; 12 1 13
289 }
290 }
291 13 safefree(seen);
292  
293 13 ▶ if (blocking) {
Branch: 1 branch
BranchTrueFalseTotal
if (blocking) { 11 2 13
294 11 AV *b = pq_binds(aTHX);
295 11 pq_bind_iv(aTHX_ b, blocking);
296 11 pq_bind_iv(aTHX_ b, id);
297 11 (void)pq_do(aTHX_ self, sv_2mortal(newSVpvs(
298 "UPDATE pq_jobs SET parents_left = ? WHERE id = ?")), b);
299 }
300 13 pq_txn_commit(aTHX_ self);
301 }
302  
303 /* Wake a listening worker. After the commit, so on Pg the NOTIFY and
304 * the row arrive in the right order (pg_notify inside the transaction
305 * would also have worked - delivery is at commit - but emitting after
306 * keeps the no-parents autocommit path and the parents path
307 * identical). No-op on SQLite. */
308 978 pq_notify(aTHX_ self, queue, id);
309  
310 978 return id;
311 }
312  
313 /* ---- reads ----------------------------------------------------------------- */
314  
315 /* One job as a plain hashref (+1), or NULL when there is no such id.
316 * Includes `parents`, the surviving parent ids - the UI's lineage links
317 * and the CLI's `job <id>` view both want them, and a second indexed
318 * lookup is cheaper than teaching the row decode a join. */
319 228 static SV *pq_job_info(pTHX_ SV *self, IV id) {
320 228 AV *bind = pq_binds(aTHX), *row;
321 HV *h;
322 228 pq_bind_iv(aTHX_ bind, id);
323 228 row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
324 "SELECT " PQ_JOB_COLS " FROM pq_jobs WHERE id = ?")), bind);
325 228 ▶ if (!row) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!row) return NULL; 11 217 228
326 217 h = pq_job_row_hv(aTHX_ row);
327 217 SvREFCNT_dec((SV *)row);
328  
329 {
330 217 AV *parents = newAV();
331 SV *sth;
332 217 AV *b2 = pq_binds(aTHX), *prow;
333 217 pq_bind_iv(aTHX_ b2, id);
334 217 sth = pq_sth(aTHX_ self, sv_2mortal(newSVpvs(
335 "SELECT parent_id FROM pq_job_deps WHERE job_id = ?"
336 " ORDER BY parent_id")));
337 217 (void)pq_execute(aTHX_ sth, b2);
338 238 ▶ while ((prow = pq_fetchrow(aTHX_ sth))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((prow = pq_fetchrow(aTHX_ sth))) { 21 217 238
339 21 av_push(parents, newSViv(pq_col_iv(aTHX_ prow, 0)));
340 21 SvREFCNT_dec((SV *)prow);
341 }
342 217 { SV *r = pq_call_meth(aTHX_ sth, "finish", NULL, 0, 1);
343 217 ▶ if (r) SvREFCNT_dec(r); }
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); } 217 0 217
344 217 (void)hv_stores(h, "parents", newRV_noinc((SV *)parents));
345 }
346 217 return newRV_noinc((SV *)h);
347 }
348  
349 /* ---- backoff ---------------------------------------------------------------
350 *
351 * Full jitter: uniform(0, min(cap, base * 2^retries)). Full rather than
352 * equal or none, because a burst of jobs that all failed against the same
353 * downed dependency must not come back in lockstep. Seeded per process
354 * from pid ^ time - unseeded children of one supervisor would jitter
355 * identically, which is the lockstep again with extra steps.
356 *
357 * drand48's own generator, carried here because the Windows CRT has no
358 * drand48: one sequence on every platform. */
359 18 static double pq_rand01(pTHX) {
360 static int seeded = 0;
361 static uint64_t x;
362 18 ▶ if (!seeded) {
Branch: 1 branch
BranchTrueFalseTotal
if (!seeded) { 9 9 18
363 9 seeded = 1;
364 9 x = ((uint64_t)(U32)((long)PerlProc_getpid() ^ (long)time(NULL)) << 16)
365 9 | 0x330E;
366 }
367 18 x = (x * UINT64_C(0x5DEECE66D) + 0xB) & ((UINT64_C(1) << 48) - 1);
368 18 return (double)x / (double)(UINT64_C(1) << 48);
369 }
370  
371 #define PQ_BACKOFF_BASE_DEFAULT 5.0
372 #define PQ_BACKOFF_CAP_DEFAULT 3600.0
373  
374 /* pq_opt_num moved to pq_dbi.h so pq_log.h (included earlier) can gate
375 * the lifecycle rows on the `logging` option */
376  
377 3 static double pq_backoff_delay(pTHX_ SV *self, IV retries) {
378 3 double base = pq_opt_num(aTHX_ self, "attempts_delay",
379 PQ_BACKOFF_BASE_DEFAULT);
380 3 double cap = pq_opt_num(aTHX_ self, "max_backoff",
381 PQ_BACKOFF_CAP_DEFAULT);
382 3 double d = base;
383 IV i;
384 4 ▶ for (i = 0; i < retries && d < cap; i++) d *= 2.0;
Branch: 2 branches
BranchTrueFalseTotal
for (i = 0; i < retries && d < cap; i++) d *= 2.0; 1 3 4
for (i = 0; i < retries && d < cap; i++) d *= 2.0; 1 0 1
385 3 ▶ if (d > cap) d = cap;
Branch: 1 branch
BranchTrueFalseTotal
if (d > cap) d = cap; 0 3 3
386 3 return pq_rand01(aTHX) * d;
387 }
388  
389 /* ---- parents_left maintenance ----------------------------------------------
390 *
391 * THE correctness risk of the whole design, so the rules live in one place
392 * and every mutation goes through this function, inside the transition's
393 * transaction:
394 *
395 * parent finishes -> -1 every child
396 * parent fails terminally -> -1 lax children only (non-lax stay
397 * blocked until the parent is retried or
398 * removed)
399 * finished parent retried -> +1 every child (they had counted it done)
400 * failed parent retried -> +1 lax children only
401 * inactive parent removed -> -1 every child
402 * failed parent removed -> -1 non-lax children (lax already got
403 * theirs at the fail)
404 * finished parent removed -> nothing (everyone got theirs)
405 *
406 * The conformance battery recomputes the truth from pq_job_deps after
407 * every transition it performs, so a missed rule here fails loudly there. */
408  
409 enum { PQ_KIDS_ALL, PQ_KIDS_LAX, PQ_KIDS_NONLAX };
410  
411 82 static void pq_children_adjust(pTHX_ SV *self, IV parent_id, IV delta,
412 int which) {
413 82 AV *bind = pq_binds(aTHX);
414 82 SV *sql = pq_sql_new(aTHX_
415 "UPDATE pq_jobs SET parents_left = parents_left + ?"
416 " WHERE id IN (SELECT job_id FROM pq_job_deps WHERE parent_id = ?)");
417 82 pq_bind_iv(aTHX_ bind, delta);
418 82 pq_bind_iv(aTHX_ bind, parent_id);
419 82 ▶ if (which == PQ_KIDS_LAX) pq_sql_cat(aTHX_ sql, " AND lax = 1");
Branch: 1 branch
BranchTrueFalseTotal
if (which == PQ_KIDS_LAX) pq_sql_cat(aTHX_ sql, " AND lax = 1"); 33 49 82
420 82 ▶ if (which == PQ_KIDS_NONLAX) pq_sql_cat(aTHX_ sql, " AND lax = 0");
Branch: 1 branch
BranchTrueFalseTotal
if (which == PQ_KIDS_NONLAX) pq_sql_cat(aTHX_ sql, " AND lax = 0"); 1 81 82
421 82 (void)pq_do(aTHX_ self, sql, bind);
422 82 }
423  
424 /* The row's (state, attempts) under the retries guard, inside the caller's
425 * transaction. Returns 1 and fills the outputs, or 0 when the guard missed. */
426 40 static int pq_guarded_peek(pTHX_ SV *self, IV id, IV retries,
427 char *state, size_t statelen, IV *attempts) {
428 40 AV *bind = pq_binds(aTHX), *row;
429 40 pq_bind_iv(aTHX_ bind, id);
430 40 pq_bind_iv(aTHX_ bind, retries);
431 40 row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
432 "SELECT state, attempts FROM pq_jobs"
433 " WHERE id = ? AND retries = ?")), bind);
434 40 ▶ if (!row) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!row) return 0; 1 39 40
435 {
436 39 SV *st = pq_col(aTHX_ row, 0);
437 78 ▶ my_strlcpy(state, SvOK(st) ? SvPV_nolen(st) : "", statelen);
Branch: 1 branch
BranchTrueFalseTotal
my_strlcpy(state, SvOK(st) ? SvPV_nolen(st) : "", statelen); 39 0 39
438 39 *attempts = pq_col_iv(aTHX_ row, 1);
439 }
440 39 SvREFCNT_dec((SV *)row);
441 39 return 1;
442 }
443  
444 /* ---- the transitions -------------------------------------------------------
445 *
446 * All take the caller's idea of `retries` as an optimistic guard: repair
447 * requeues a vanished worker's job by bumping retries, and without the
448 * guard the original worker - possibly still alive and about to report -
449 * would clobber the new attempt. Minion's trick, and load-bearing.
450 *
451 * All return 1 when the transition applied, 0 when the guard rejected it.
452 * A 0 is information, not an error: the caller lost a race it is allowed
453 * to lose. All are transactions, because the job row and its children's
454 * counters must move together or the drift check catches us. */
455  
456 48 static IV pq_finish_job(pTHX_ SV *self, IV id, IV retries, SV *result) {
457 48 AV *bind = pq_binds(aTHX);
458 48 SV *json = sv_2mortal(pq_json_encode(aTHX_ result, "null"));
459 IV took;
460  
461 48 pq_txn_begin(aTHX_ self);
462 48 pq_bind_nv(aTHX_ bind, pq_now(aTHX_ self));
463 48 pq_bind_sv(aTHX_ bind, json);
464 48 pq_bind_iv(aTHX_ bind, id);
465 48 pq_bind_iv(aTHX_ bind, retries);
466 48 took = pq_do(aTHX_ self, sv_2mortal(newSVpvs(
467 "UPDATE pq_jobs SET state = 'finished', finished = ?, result = ?"
468 " WHERE id = ? AND retries = ? AND state = 'active'")), bind);
469 48 ▶ if (took > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (took > 0) { 41 7 48
470 41 pq_children_adjust(aTHX_ self, id, -1, PQ_KIDS_ALL);
471 41 pq_log_addf(aTHX_ self, id, "info", "finished");
472 }
473 48 pq_txn_commit(aTHX_ self);
474 48 return took > 0 ? 1 : 0;
475 }
476  
477 /* fail: backoff-retry when attempts remain, terminal failure when not.
478 * The error lands in result either way, so the last failure is visible
479 * while the job waits out its backoff. */
480 28 static IV pq_fail_job(pTHX_ SV *self, IV id, IV retries, SV *err) {
481 28 SV *json = sv_2mortal(pq_json_encode(aTHX_ err, "null"));
482 char state[16];
483 28 IV attempts = 0, took = 0;
484 double now;
485  
486 28 pq_txn_begin(aTHX_ self);
487 28 ▶ if (!pq_guarded_peek(aTHX_ self, id, retries, state, sizeof state,
Branch: 1 branch
BranchTrueFalseTotal
if (!pq_guarded_peek(aTHX_ self, id, retries, state, sizeof state, 28 0 28
488 &attempts)
489 28 ▶ || strNE(state, "active")) {
Branch: 1 branch
BranchTrueFalseTotal
|| strNE(state, "active")) { 1 27 28
490 1 pq_txn_commit(aTHX_ self);
491 1 return 0;
492 }
493 27 now = pq_now(aTHX_ self);
494  
495 27 ▶ if (retries + 1 < attempts) {
Branch: 1 branch
BranchTrueFalseTotal
if (retries + 1 < attempts) { 3 24 27
496 3 double delay = pq_backoff_delay(aTHX_ self, retries);
497 3 AV *bind = pq_binds(aTHX);
498 3 pq_bind_nv(aTHX_ bind, now);
499 3 pq_bind_nv(aTHX_ bind, now + delay);
500 3 pq_bind_sv(aTHX_ bind, json);
501 3 pq_bind_iv(aTHX_ bind, id);
502 3 pq_bind_iv(aTHX_ bind, retries);
503 3 took = pq_do(aTHX_ self, sv_2mortal(newSVpvs(
504 "UPDATE pq_jobs SET state = 'inactive',"
505 " retries = retries + 1, retried = ?, delayed = ?,"
506 " started = NULL, worker = NULL, result = ?"
507 " WHERE id = ? AND retries = ? AND state = 'active'")), bind);
508 /* still blocking its children exactly as before: no adjustment */
509 3 ▶ if (took > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (took > 0) { 3 0 3
510 char ebuf[PQ_LOG_ERRMAX];
511 3 pq_log_addf(aTHX_ self, id, "warn",
512 "attempt %ld of %ld failed: %s - retry due in %.1" NVff "s",
513 3 (long)(retries + 1), (long)attempts,
514 pq_log_errpv(aTHX_ err, ebuf, sizeof ebuf),
515 (NV)delay);
516 }
517 }
518 else {
519 24 AV *bind = pq_binds(aTHX);
520 24 pq_bind_nv(aTHX_ bind, now);
521 24 pq_bind_sv(aTHX_ bind, json);
522 24 pq_bind_iv(aTHX_ bind, id);
523 24 pq_bind_iv(aTHX_ bind, retries);
524 24 took = pq_do(aTHX_ self, sv_2mortal(newSVpvs(
525 "UPDATE pq_jobs SET state = 'failed', finished = ?, result = ?"
526 " WHERE id = ? AND retries = ? AND state = 'active'")), bind);
527 24 ▶ if (took > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (took > 0) { 24 0 24
528 char ebuf[PQ_LOG_ERRMAX];
529 24 pq_children_adjust(aTHX_ self, id, -1, PQ_KIDS_LAX);
530 24 pq_log_addf(aTHX_ self, id, "error",
531 "failed after %ld of %ld attempts: %s",
532 24 (long)(retries + 1), (long)attempts,
533 pq_log_errpv(aTHX_ err, ebuf, sizeof ebuf));
534 }
535 }
536 27 pq_txn_commit(aTHX_ self);
537 27 return took > 0 ? 1 : 0;
538 }
539  
540 /* retry_job requeues from ANY state, deliberately - retrying an `active`
541 * job is exactly how a stuck job is recovered from the outside: the bump
542 * invalidates the running attempt's guard, so whatever the stale worker
543 * eventually reports lands on a row that no longer matches. The same
544 * guard protects THIS call: two operators retrying at once apply exactly
545 * one bump.
546 *
547 * opts (each optional): delay, priority, queue, attempts. */
548 12 static IV pq_retry_job(pTHX_ SV *self, IV id, IV retries, HV *opts) {
549 12 AV *bind = pq_binds(aTHX);
550 12 double now, delay = 0.0;
551 char prestate[16];
552 12 IV attempts_col = 0, took;
553 SV *sql, *v;
554  
555 12 pq_txn_begin(aTHX_ self);
556 12 ▶ if (!pq_guarded_peek(aTHX_ self, id, retries, prestate, sizeof prestate,
Branch: 1 branch
BranchTrueFalseTotal
if (!pq_guarded_peek(aTHX_ self, id, retries, prestate, sizeof prestate, 1 11 12
557 &attempts_col)) {
558 1 pq_txn_commit(aTHX_ self);
559 1 return 0;
560 }
561 11 now = pq_now(aTHX_ self);
562  
563 11 sql = pq_sql_new(aTHX_
564 "UPDATE pq_jobs SET state = 'inactive', retries = retries + 1,"
565 " retried = ?, delayed = ?, started = NULL, finished = NULL,"
566 " worker = NULL, result = NULL");
567 11 ▶ if (opts && (v = pq_get(aTHX_ opts, "delay")) && SvOK(v))
Branch: 3 branches
BranchTrueFalseTotal
if (opts && (v = pq_get(aTHX_ opts, "delay")) && SvOK(v)) 5 6 11
if (opts && (v = pq_get(aTHX_ opts, "delay")) && SvOK(v)) 2 3 5
if (opts && (v = pq_get(aTHX_ opts, "delay")) && SvOK(v)) 2 0 2
568 2 delay = SvNV(v);
569 11 pq_bind_nv(aTHX_ bind, now);
570 11 pq_bind_nv(aTHX_ bind, now + delay);
571  
572 11 ▶ if (opts && (v = pq_get(aTHX_ opts, "priority")) && SvOK(v)) {
Branch: 3 branches
BranchTrueFalseTotal
if (opts && (v = pq_get(aTHX_ opts, "priority")) && SvOK(v)) { 5 6 11
if (opts && (v = pq_get(aTHX_ opts, "priority")) && SvOK(v)) { 2 3 5
if (opts && (v = pq_get(aTHX_ opts, "priority")) && SvOK(v)) { 2 0 2
573 2 pq_sql_cat(aTHX_ sql, ", priority = ?");
574 2 pq_bind_iv(aTHX_ bind, SvIV(v));
575 }
576 11 ▶ if (opts && (v = pq_get(aTHX_ opts, "queue")) && SvOK(v)) {
Branch: 3 branches
BranchTrueFalseTotal
if (opts && (v = pq_get(aTHX_ opts, "queue")) && SvOK(v)) { 5 6 11
if (opts && (v = pq_get(aTHX_ opts, "queue")) && SvOK(v)) { 1 4 5
if (opts && (v = pq_get(aTHX_ opts, "queue")) && SvOK(v)) { 1 0 1
577 1 pq_name_check(aTHX_ v, "queue");
578 1 pq_sql_cat(aTHX_ sql, ", queue = ?");
579 1 pq_bind_sv(aTHX_ bind, v);
580 }
581 11 ▶ if (opts && (v = pq_get(aTHX_ opts, "attempts")) && SvOK(v)) {
Branch: 3 branches
BranchTrueFalseTotal
if (opts && (v = pq_get(aTHX_ opts, "attempts")) && SvOK(v)) { 5 6 11
if (opts && (v = pq_get(aTHX_ opts, "attempts")) && SvOK(v)) { 1 4 5
if (opts && (v = pq_get(aTHX_ opts, "attempts")) && SvOK(v)) { 1 0 1
582 1 ▶ if (SvIV(v) < 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvIV(v) < 1) { 0 1 1
583 0 pq_txn_rollback(aTHX_ self);
584 0 croak("Punk::Queue: attempts must be at least 1, not %ld",
585 (long)SvIV(v));
586 }
587 1 pq_sql_cat(aTHX_ sql, ", attempts = ?");
588 1 pq_bind_iv(aTHX_ bind, SvIV(v));
589 }
590  
591 11 pq_sql_cat(aTHX_ sql, " WHERE id = ? AND retries = ?");
592 11 pq_bind_iv(aTHX_ bind, id);
593 11 pq_bind_iv(aTHX_ bind, retries);
594  
595 11 took = pq_do(aTHX_ self, sql, bind);
596 11 ▶ if (took > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (took > 0) { 11 0 11
597 /* the children had counted this parent done; block them again */
598 11 ▶ if (strEQ(prestate, "finished"))
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(prestate, "finished")) 1 10 11
599 1 pq_children_adjust(aTHX_ self, id, +1, PQ_KIDS_ALL);
600 10 ▶ else if (strEQ(prestate, "failed"))
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(prestate, "failed")) 8 2 10
601 8 pq_children_adjust(aTHX_ self, id, +1, PQ_KIDS_LAX);
602 11 ▶ pq_log_addf(aTHX_ self, id, "info",
Branch: 1 branch
BranchTrueFalseTotal
pq_log_addf(aTHX_ self, id, "info", 2 9 11
603 delay > 0 ? "retried from '%s' - due in %.1" NVff "s"
604 : "retried from '%s'",
605 prestate, (NV)delay);
606 }
607 11 pq_txn_commit(aTHX_ self);
608 11 return took > 0 ? 1 : 0;
609 }
610  
611 /* remove_job refuses an active job: the worker running it would finish
612 * into a void and the supervision bookkeeping would point at a ghost.
613 * Retry it first (which strands the running attempt), then remove. Dep
614 * rows cascade via the foreign keys - but only after the children's
615 * counters are adjusted, because the adjustment needs the dep rows to
616 * find them. */
617 14 static IV pq_remove_job(pTHX_ SV *self, IV id) {
618 char prestate[16];
619 14 IV attempts = 0, took = 0;
620  
621 14 pq_txn_begin(aTHX_ self);
622 {
623 14 AV *bind = pq_binds(aTHX), *row;
624 14 pq_bind_iv(aTHX_ bind, id);
625 14 row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
626 "SELECT state, attempts FROM pq_jobs WHERE id = ?")), bind);
627 14 ▶ if (!row) { pq_txn_commit(aTHX_ self); return 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (!row) { pq_txn_commit(aTHX_ self); return 0; } 2 12 14
628 {
629 12 SV *st = pq_col(aTHX_ row, 0);
630 24 ▶ my_strlcpy(prestate, SvOK(st) ? SvPV_nolen(st) : "",
Branch: 1 branch
BranchTrueFalseTotal
my_strlcpy(prestate, SvOK(st) ? SvPV_nolen(st) : "", 12 0 12
631 sizeof prestate);
632 12 attempts = pq_col_iv(aTHX_ row, 1);
633 }
634 12 SvREFCNT_dec((SV *)row);
635 PERL_UNUSED_VAR(attempts);
636 }
637 12 ▶ if (strEQ(prestate, "active")) {
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(prestate, "active")) { 3 9 12
638 3 pq_txn_commit(aTHX_ self);
639 3 return 0;
640 }
641  
642 9 ▶ if (strEQ(prestate, "inactive"))
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(prestate, "inactive")) 6 3 9
643 6 pq_children_adjust(aTHX_ self, id, -1, PQ_KIDS_ALL);
644 3 ▶ else if (strEQ(prestate, "failed"))
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(prestate, "failed")) 1 2 3
645 1 pq_children_adjust(aTHX_ self, id, -1, PQ_KIDS_NONLAX);
646 /* finished: every child already got its decrement */
647  
648 {
649 9 AV *bind = pq_binds(aTHX);
650 9 pq_bind_iv(aTHX_ bind, id);
651 9 took = pq_do(aTHX_ self, sv_2mortal(newSVpvs(
652 "DELETE FROM pq_jobs WHERE id = ?"
653 " AND state IN ('inactive', 'failed', 'finished')")), bind);
654 }
655 9 ▶ if (took > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (took > 0) { 9 0 9
656 9 AV *bind = pq_binds(aTHX);
657 9 pq_bind_iv(aTHX_ bind, id);
658 9 (void)pq_do(aTHX_ self, sv_2mortal(newSVpvs(
659 "DELETE FROM pq_job_logs WHERE job_id = ?")), bind);
660 }
661 9 pq_txn_commit(aTHX_ self);
662 9 return took > 0 ? 1 : 0;
663 }
664  
665 /* ---- notes -----------------------------------------------------------------
666 *
667 * Merge, not replace, and merged in C after an frj decode rather than in
668 * SQL - json_patch exists on neither backend in a portable form, and the
669 * conformance suite requires byte-identical behaviour. A key set to undef
670 * is deleted. Works in any state: progress notes on an active job are the
671 * whole point. */
672 4 static IV pq_note(pTHX_ SV *self, IV id, HV *merge) {
673 AV *bind, *row;
674 SV *decoded, *json;
675 HV *notes;
676 IV took;
677  
678 4 ▶ if (!merge) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!merge) return 0; 0 4 4
679  
680 4 pq_txn_begin(aTHX_ self);
681 4 bind = pq_binds(aTHX);
682 4 pq_bind_iv(aTHX_ bind, id);
683 4 row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
684 "SELECT notes FROM pq_jobs WHERE id = ?")), bind);
685 4 ▶ if (!row) { pq_txn_commit(aTHX_ self); return 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (!row) { pq_txn_commit(aTHX_ self); return 0; } 1 3 4
686  
687 3 decoded = sv_2mortal(pq_json_decode(aTHX_ pq_col(aTHX_ row, 0)));
688 3 SvREFCNT_dec((SV *)row);
689 3 ▶ notes = (SvROK(decoded) && SvTYPE(SvRV(decoded)) == SVt_PVHV)
Branch: 1 branch
BranchTrueFalseTotal
notes = (SvROK(decoded) && SvTYPE(SvRV(decoded)) == SVt_PVHV) 3 0 3
690 6 ▶ ? (HV *)SvRV(decoded) : (HV *)sv_2mortal((SV *)newHV());
Branch: 1 branch
BranchTrueFalseTotal
? (HV *)SvRV(decoded) : (HV *)sv_2mortal((SV *)newHV()); 3 0 3
691  
692 {
693 HE *he;
694 3 hv_iterinit(merge);
695 7 ▶ while ((he = hv_iternext(merge))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(merge))) { 4 3 7
696 4 SV *val = HeVAL(he);
697 4 ▶ if (val && SvOK(val))
Branch: 2 branches
BranchTrueFalseTotal
if (val && SvOK(val)) 4 0 4
if (val && SvOK(val)) 3 1 4
698 3 ▶ (void)hv_store_ent(notes, HeSVKEY_force(he),
Branch: 2 branches
BranchTrueFalseTotal
(void)hv_store_ent(notes, HeSVKEY_force(he), 3 0 3
(void)hv_store_ent(notes, HeSVKEY_force(he), 0 3 3
699 newSVsv(val), 0);
700 else
701 1 ▶ (void)hv_delete_ent(notes, HeSVKEY_force(he), G_DISCARD, 0);
Branch: 2 branches
BranchTrueFalseTotal
(void)hv_delete_ent(notes, HeSVKEY_force(he), G_DISCARD, 0); 1 0 1
(void)hv_delete_ent(notes, HeSVKEY_force(he), G_DISCARD, 0); 0 1 1
702 }
703 }
704  
705 3 json = sv_2mortal(pq_json_encode(aTHX_
706 sv_2mortal(newRV_inc((SV *)notes)), "{}"));
707 3 bind = pq_binds(aTHX);
708 3 pq_bind_sv(aTHX_ bind, json);
709 3 pq_bind_iv(aTHX_ bind, id);
710 3 took = pq_do(aTHX_ self, sv_2mortal(newSVpvs(
711 "UPDATE pq_jobs SET notes = ? WHERE id = ?")), bind);
712 3 pq_txn_commit(aTHX_ self);
713 3 return took > 0 ? 1 : 0;
714 }
715  
716 /* ---- the worker registry ---------------------------------------------------
717 *
718 * One row per process that claims jobs. `-j 4` is four child processes and
719 * four rows (the deliberate departure from Minion), because timeout
720 * enforcement and the admin UI want per-child granularity - a supervisor
721 * row with jobs=4 cannot tell you which child is stuck. */
722  
723 45 static void pq_hostname(pTHX_ char *buf, size_t len) {
724 #ifdef HAS_GETHOSTNAME
725 45 ▶ if (gethostname(buf, (int)len) == 0) { buf[len - 1] = 0; return; }
Branch: 1 branch
BranchTrueFalseTotal
if (gethostname(buf, (int)len) == 0) { buf[len - 1] = 0; return; } 45 0 45
726 #endif
727 0 my_strlcpy(buf, "localhost", len);
728 }
729  
730 /* Register (or refresh, when id is non-zero) a worker row. Refreshing keeps
731 * identity across a reconnect, which matters once the admin UI links jobs
732 * to the worker that ran them. opts: role, queues (arrayref), jobs. */
733 46 static IV pq_register_worker(pTHX_ SV *self, IV id, HV *opts) {
734 46 double now = pq_now(aTHX_ self);
735 46 ▶ SV *role = opts ? pq_get(aTHX_ opts, "role") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *role = opts ? pq_get(aTHX_ opts, "role") : NULL; 45 1 46
736 46 ▶ SV *queues = opts ? pq_get(aTHX_ opts, "queues") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *queues = opts ? pq_get(aTHX_ opts, "queues") : NULL; 45 1 46
737 46 ▶ SV *jobs = opts ? pq_get(aTHX_ opts, "jobs") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *jobs = opts ? pq_get(aTHX_ opts, "jobs") : NULL; 45 1 46
738 46 SV *qjson = sv_2mortal(pq_json_encode(aTHX_ queues, "[]"));
739  
740 46 ▶ if (id) {
Branch: 1 branch
BranchTrueFalseTotal
if (id) { 1 45 46
741 1 AV *b = pq_binds(aTHX);
742 1 pq_bind_nv(aTHX_ b, now);
743 1 pq_bind_sv(aTHX_ b, qjson);
744 1 pq_bind_iv(aTHX_ b, id);
745 1 ▶ if (pq_do(aTHX_ self, sv_2mortal(newSVpvs(
Branch: 1 branch
BranchTrueFalseTotal
if (pq_do(aTHX_ self, sv_2mortal(newSVpvs( 1 0 1
746 "UPDATE pq_workers SET notified = ?, queues = ?"
747 " WHERE id = ?")), b) > 0)
748 1 return id;
749 /* the row is gone (repair swept it); fall through and re-register */
750 }
751  
752 {
753 char host[256];
754 45 AV *b = pq_binds(aTHX);
755 45 SV *sql = pq_sql_new(aTHX_
756 "INSERT INTO pq_workers"
757 " (host, pid, role, queues, jobs, version, started, notified)"
758 " VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
759 45 pq_hostname(aTHX_ host, sizeof host);
760 45 pq_bind_pv(aTHX_ b, host);
761 45 pq_bind_iv(aTHX_ b, (IV)PerlProc_getpid());
762 45 ▶ if (role && SvOK(role)) pq_bind_sv(aTHX_ b, role);
Branch: 2 branches
BranchTrueFalseTotal
if (role && SvOK(role)) pq_bind_sv(aTHX_ b, role); 40 5 45
if (role && SvOK(role)) pq_bind_sv(aTHX_ b, role); 40 0 40
763 5 else pq_bind_pv(aTHX_ b, "child");
764 45 pq_bind_sv(aTHX_ b, qjson);
765 45 ▶ pq_bind_iv(aTHX_ b, (jobs && SvOK(jobs)) ? SvIV(jobs) : 1);
Branch: 2 branches
BranchTrueFalseTotal
pq_bind_iv(aTHX_ b, (jobs && SvOK(jobs)) ? SvIV(jobs) : 1); 15 30 45
pq_bind_iv(aTHX_ b, (jobs && SvOK(jobs)) ? SvIV(jobs) : 1); 15 0 15
766 45 pq_bind_pv(aTHX_ b, PQ_VERSION_STRING);
767 45 pq_bind_nv(aTHX_ b, now);
768 45 pq_bind_nv(aTHX_ b, now);
769  
770 45 ▶ if (pq_has_returning(aTHX_ self)) {
Branch: 1 branch
BranchTrueFalseTotal
if (pq_has_returning(aTHX_ self)) { 45 0 45
771 AV *row;
772 45 IV got = 0;
773 45 pq_sql_cat(aTHX_ sql, " RETURNING id");
774 45 row = pq_selectrow(aTHX_ self, sql, b);
775 45 ▶ if (row) { got = pq_col_iv(aTHX_ row, 0); SvREFCNT_dec((SV *)row); }
Branch: 1 branch
BranchTrueFalseTotal
if (row) { got = pq_col_iv(aTHX_ row, 0); SvREFCNT_dec((SV *)row); } 45 0 45
776 45 return got;
777 }
778 0 (void)pq_do(aTHX_ self, sql, b);
779 0 return pq_last_insert_id(aTHX_ self);
780 }
781 }
782  
783 35 static IV pq_unregister_worker(pTHX_ SV *self, IV id) {
784 35 AV *b = pq_binds(aTHX);
785 35 pq_bind_iv(aTHX_ b, id);
786 35 return pq_do(aTHX_ self, sv_2mortal(newSVpvs(
787 35 "DELETE FROM pq_workers WHERE id = ?")), b) > 0 ? 1 : 0;
788 }
789  
790 /* The heartbeat: proof of life, and (from phase 6) the inbox drain point.
791 * status is stored as JSON for the admin UI; NULL keeps what is there. */
792 29 static IV pq_worker_heartbeat(pTHX_ SV *self, IV id, SV *status) {
793 29 AV *b = pq_binds(aTHX);
794 29 SV *sql = pq_sql_new(aTHX_ "UPDATE pq_workers SET notified = ?");
795 29 pq_bind_nv(aTHX_ b, pq_now(aTHX_ self));
796 29 ▶ if (status && SvOK(status)) {
Branch: 2 branches
BranchTrueFalseTotal
if (status && SvOK(status)) { 9 20 29
if (status && SvOK(status)) { 1 8 9
797 1 SV *json = sv_2mortal(pq_json_encode(aTHX_ status, "{}"));
798 1 pq_sql_cat(aTHX_ sql, ", status = ?");
799 1 pq_bind_sv(aTHX_ b, json);
800 }
801 29 pq_sql_cat(aTHX_ sql, " WHERE id = ?");
802 29 pq_bind_iv(aTHX_ b, id);
803 29 return pq_do(aTHX_ self, sql, b) > 0 ? 1 : 0;
804 }
805  
806 /* ---- listing ---------------------------------------------------------------
807 *
808 * One filter vocabulary - id, state, queue, task, worker - shared verbatim
809 * by the CLI (`punk-queue jobs --state failed`), the phase-8 REST API and
810 * the admin UI, so an operator never learns three dialects. The WHERE is
811 * assembled from this whitelist and nothing else; caller input never
812 * reaches the SQL as text. */
813  
814 static const char *const PQ_JOB_FILTERS[] =
815 { "id", "state", "queue", "task", "worker", NULL };
816  
817 /* The table search: filter key `search` matches a substring against a
818 * per-lister whitelist of columns, OR'd. The term is LIKE-escaped and
819 * bound - caller input never reaches the SQL as text - and both sides
820 * are lower()ed because LIKE is case-insensitive on SQLite but
821 * case-sensitive on Pg, and the conformance battery requires one
822 * behaviour. Numeric columns join the whitelist as CAST(... AS TEXT). */
823 20 static void pq_search_where(pTHX_ SV *where, AV *fbind, int *first,
824 SV *term, const char *const cols[]) {
825 STRLEN len, i;
826 20 const char *p = SvPV(term, len);
827 20 SV *pat = sv_2mortal(newSVpvs("%"));
828 int j;
829 123 ▶ for (i = 0; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < len; i++) { 103 20 123
830 103 ▶ char ch = (char)toLOWER((U8)p[i]);
Branch: 1 branch
BranchTrueFalseTotal
char ch = (char)toLOWER((U8)p[i]); 14 89 103
831 103 ▶ if (ch == '%' || ch == '_' || ch == '\\')
Branch: 3 branches
BranchTrueFalseTotal
if (ch == '%' || ch == '_' || ch == '\\') 102 1 103
if (ch == '%' || ch == '_' || ch == '\\') 101 1 102
if (ch == '%' || ch == '_' || ch == '\\') 0 101 101
832 2 sv_catpvs(pat, "\\");
833 103 sv_catpvn(pat, &ch, 1);
834 }
835 20 sv_catpvs(pat, "%");
836 20 ▶ pq_sql_cat(aTHX_ where, *first ? " WHERE (" : " AND (");
Branch: 1 branch
BranchTrueFalseTotal
pq_sql_cat(aTHX_ where, *first ? " WHERE (" : " AND ("); 18 2 20
837 96 ▶ for (j = 0; cols[j]; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; cols[j]; j++) { 76 20 96
838 76 ▶ if (j) pq_sql_cat(aTHX_ where, " OR ");
Branch: 1 branch
BranchTrueFalseTotal
if (j) pq_sql_cat(aTHX_ where, " OR "); 56 20 76
839 76 pq_sql_cat(aTHX_ where, "lower(");
840 76 pq_sql_cat(aTHX_ where, cols[j]);
841 76 pq_sql_cat(aTHX_ where, ") LIKE ? ESCAPE '\\'");
842 76 pq_bind_sv(aTHX_ fbind, pat);
843 }
844 20 pq_sql_cat(aTHX_ where, ")");
845 20 *first = 0;
846 20 }
847  
848 189 static void pq_search_filter(pTHX_ SV *where, AV *fbind, int *first,
849 HV *filter, const char *const cols[]) {
850 189 ▶ SV *v = filter ? pq_get(aTHX_ filter, "search") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *v = filter ? pq_get(aTHX_ filter, "search") : NULL; 69 120 189
851 189 ▶ if (v && SvOK(v) && SvCUR(v))
Branch: 3 branches
BranchTrueFalseTotal
if (v && SvOK(v) && SvCUR(v)) 20 169 189
if (v && SvOK(v) && SvCUR(v)) 20 0 20
if (v && SvOK(v) && SvCUR(v)) 20 0 20
852 20 pq_search_where(aTHX_ where, fbind, first, v, cols);
853 189 }
854  
855 /* Sortable columns are whitelisted exactly as filterable ones are: the
856 * ORDER BY is assembled from this table and a fixed asc/desc pair, and
857 * caller input never reaches the SQL as text. An unknown column croaks
858 * (a typo'd sort is a caller bug), landing as a clean 4xx upstream. */
859 static const char *const PQ_JOB_SORTS[] =
860 { "id", "state", "queue", "task", "worker", "priority", "created",
861 NULL };
862  
863 55 static SV *pq_list_jobs(pTHX_ SV *self, IV offset, IV limit, HV *filter,
864 SV *sort_col, SV *sort_dir) {
865 55 SV *where = pq_sql_new(aTHX_ "");
866 55 AV *fbind = pq_binds(aTHX);
867 55 HV *out = newHV();
868 55 AV *jobs = newAV();
869 55 int i, first = 1;
870  
871 330 ▶ for (i = 0; PQ_JOB_FILTERS[i]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; PQ_JOB_FILTERS[i]; i++) { 275 55 330
872 275 ▶ SV *v = filter ? pq_get(aTHX_ filter, PQ_JOB_FILTERS[i]) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *v = filter ? pq_get(aTHX_ filter, PQ_JOB_FILTERS[i]) : NULL; 260 15 275
873 275 ▶ if (!(v && SvOK(v))) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!(v && SvOK(v))) continue; 36 239 275
if (!(v && SvOK(v))) continue; 0 36 36
874 36 ▶ pq_sql_cat(aTHX_ where, first ? " WHERE " : " AND ");
Branch: 1 branch
BranchTrueFalseTotal
pq_sql_cat(aTHX_ where, first ? " WHERE " : " AND "); 35 1 36
875 36 pq_sql_cat(aTHX_ where, PQ_JOB_FILTERS[i]);
876 36 pq_sql_cat(aTHX_ where, " = ?");
877 36 pq_bind_sv(aTHX_ fbind, v);
878 36 first = 0;
879 }
880 {
881 static const char *const cols[] =
882 { "task", "queue", "state", "CAST(id AS TEXT)", NULL };
883 55 pq_search_filter(aTHX_ where, fbind, &first, filter, cols);
884 }
885  
886 { /* total first, so paging can show "page 2 of 40" */
887 55 SV *sql = pq_sql_new(aTHX_ "SELECT count(*) FROM pq_jobs");
888 AV *row;
889 55 pq_sql_cat_all(aTHX_ sql, where);
890 55 row = pq_selectrow(aTHX_ self, sql, fbind);
891 55 ▶ (void)hv_stores(out, "total",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(out, "total", 55 0 55
892 newSViv(row ? pq_col_iv(aTHX_ row, 0) : 0));
893 55 ▶ if (row) SvREFCNT_dec((SV *)row);
Branch: 1 branch
BranchTrueFalseTotal
if (row) SvREFCNT_dec((SV *)row); 55 0 55
894 }
895  
896 {
897 55 SV *sql = pq_sql_new(aTHX_ "SELECT " PQ_JOB_COLS " FROM pq_jobs");
898 SV *sth;
899 55 AV *bind = pq_binds(aTHX), *row;
900 55 SSize_t n = av_len(fbind) + 1, k;
901 147 ▶ for (k = 0; k < n; k++) pq_bind_sv(aTHX_ bind, *av_fetch(fbind, k, 0));
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n; k++) pq_bind_sv(aTHX_ bind, *av_fetch(fbind, k, 0)); 92 55 147
902 55 pq_sql_cat_all(aTHX_ sql, where);
903 /* newest first by default: the question is nearly always "what
904 * just happened" */
905 56 ▶ if (sort_col && SvOK(sort_col)) {
Branch: 2 branches
BranchTrueFalseTotal
if (sort_col && SvOK(sort_col)) { 9 46 55
if (sort_col && SvOK(sort_col)) { 2 7 9
906 2 const char *want = SvPV_nolen(sort_col);
907 2 int i, ok = 0;
908 14 ▶ for (i = 0; PQ_JOB_SORTS[i]; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; PQ_JOB_SORTS[i]; i++) 13 1 14
909 13 ▶ if (strEQ(want, PQ_JOB_SORTS[i])) { ok = 1; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(want, PQ_JOB_SORTS[i])) { ok = 1; break; } 1 12 13
910 2 ▶ if (!ok)
Branch: 1 branch
BranchTrueFalseTotal
if (!ok) 1 1 2
911 1 croak("Punk::Queue: cannot sort jobs by '%s'", want);
912 1 pq_sql_cat(aTHX_ sql, " ORDER BY ");
913 1 pq_sql_cat(aTHX_ sql, want);
914 2 ▶ pq_sql_cat(aTHX_ sql,
Branch: 1 branch
BranchTrueFalseTotal
pq_sql_cat(aTHX_ sql, 1 0 1
915 1 ▶ (sort_dir && SvOK(sort_dir)
Branch: 1 branch
BranchTrueFalseTotal
(sort_dir && SvOK(sort_dir) 1 0 1
916 1 ▶ && strEQ(SvPV_nolen(sort_dir), "asc"))
Branch: 1 branch
BranchTrueFalseTotal
&& strEQ(SvPV_nolen(sort_dir), "asc")) 0 1 1
917 ? " ASC" : " DESC");
918 1 pq_sql_cat(aTHX_ sql, ", id DESC LIMIT ? OFFSET ?");
919 }
920 else
921 53 pq_sql_cat(aTHX_ sql, " ORDER BY id DESC LIMIT ? OFFSET ?");
922 54 ▶ pq_bind_iv(aTHX_ bind, limit > 0 ? limit : 50);
Branch: 1 branch
BranchTrueFalseTotal
pq_bind_iv(aTHX_ bind, limit > 0 ? limit : 50); 9 45 54
923 54 pq_bind_iv(aTHX_ bind, offset > 0 ? offset : 0);
924  
925 54 sth = pq_sth(aTHX_ self, sql);
926 54 (void)pq_execute(aTHX_ sth, bind);
927 116 ▶ while ((row = pq_fetchrow(aTHX_ sth))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((row = pq_fetchrow(aTHX_ sth))) { 62 54 116
928 62 av_push(jobs, newRV_noinc((SV *)pq_job_row_hv(aTHX_ row)));
929 62 SvREFCNT_dec((SV *)row);
930 }
931 54 { SV *r = pq_call_meth(aTHX_ sth, "finish", NULL, 0, 1);
932 54 ▶ if (r) SvREFCNT_dec(r); }
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); } 54 0 54
933 }
934  
935 54 (void)hv_stores(out, "jobs", newRV_noinc((SV *)jobs));
936 54 return newRV_noinc((SV *)out);
937 }
938  
939 /* A worker row -> plain hashref, JSON columns decoded. */
940 184 static HV *pq_worker_row_hv(pTHX_ AV *row) {
941 184 HV *h = newHV();
942 184 ▶ if (!row) return h;
Branch: 1 branch
BranchTrueFalseTotal
if (!row) return h; 0 184 184
943 184 pq_hv_set_iv(aTHX_ h, "id", pq_col_iv(aTHX_ row, 0));
944 184 pq_hv_set_sv(aTHX_ h, "host", pq_col(aTHX_ row, 1));
945 184 pq_hv_set_iv(aTHX_ h, "pid", pq_col_iv(aTHX_ row, 2));
946 184 pq_hv_set_sv(aTHX_ h, "role", pq_col(aTHX_ row, 3));
947 184 (void)hv_stores(h, "queues", pq_json_decode(aTHX_ pq_col(aTHX_ row, 4)));
948 184 pq_hv_set_iv(aTHX_ h, "jobs", pq_col_iv(aTHX_ row, 5));
949 184 (void)hv_stores(h, "status", pq_json_decode(aTHX_ pq_col(aTHX_ row, 6)));
950 184 pq_hv_set_sv(aTHX_ h, "version", pq_col(aTHX_ row, 8));
951 184 pq_hv_set_nv_or_undef(aTHX_ h, "started", pq_col(aTHX_ row, 9));
952 184 pq_hv_set_nv_or_undef(aTHX_ h, "notified", pq_col(aTHX_ row, 10));
953 184 return h;
954 }
955  
956 124 static SV *pq_list_workers(pTHX_ SV *self, IV offset, IV limit, HV *filter) {
957 124 SV *where = pq_sql_new(aTHX_ "");
958 124 AV *fbind = pq_binds(aTHX);
959 124 HV *out = newHV();
960 124 AV *ws = newAV();
961 SV *v;
962  
963 124 ▶ if (filter && (v = pq_get(aTHX_ filter, "role")) && SvOK(v)) {
Branch: 3 branches
BranchTrueFalseTotal
if (filter && (v = pq_get(aTHX_ filter, "role")) && SvOK(v)) { 7 117 124
if (filter && (v = pq_get(aTHX_ filter, "role")) && SvOK(v)) { 2 5 7
if (filter && (v = pq_get(aTHX_ filter, "role")) && SvOK(v)) { 2 0 2
964 2 pq_sql_cat(aTHX_ where, " WHERE role = ?");
965 2 pq_bind_sv(aTHX_ fbind, v);
966 }
967 {
968 static const char *const cols[] =
969 { "host", "role", "CAST(id AS TEXT)", "CAST(pid AS TEXT)",
970 NULL };
971 126 ▶ int first = !(filter && (v = pq_get(aTHX_ filter, "role"))
Branch: 2 branches
BranchTrueFalseTotal
int first = !(filter && (v = pq_get(aTHX_ filter, "role")) 7 117 124
int first = !(filter && (v = pq_get(aTHX_ filter, "role")) 2 5 7
972 2 ▶ && SvOK(v));
Branch: 1 branch
BranchTrueFalseTotal
&& SvOK(v)); 0 2 2
973 124 pq_search_filter(aTHX_ where, fbind, &first, filter, cols);
974 }
975  
976 {
977 124 SV *sql = pq_sql_new(aTHX_ "SELECT count(*) FROM pq_workers");
978 AV *row;
979 124 pq_sql_cat_all(aTHX_ sql, where);
980 124 row = pq_selectrow(aTHX_ self, sql, fbind);
981 124 ▶ (void)hv_stores(out, "total",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(out, "total", 124 0 124
982 newSViv(row ? pq_col_iv(aTHX_ row, 0) : 0));
983 124 ▶ if (row) SvREFCNT_dec((SV *)row);
Branch: 1 branch
BranchTrueFalseTotal
if (row) SvREFCNT_dec((SV *)row); 124 0 124
984 }
985  
986 {
987 124 SV *sql = pq_sql_new(aTHX_
988 "SELECT id, host, pid, role, queues, jobs, status, inbox,"
989 " version, started, notified FROM pq_workers");
990 SV *sth;
991 124 AV *bind = pq_binds(aTHX), *row;
992 124 SSize_t n = av_len(fbind) + 1, k;
993 142 ▶ for (k = 0; k < n; k++) pq_bind_sv(aTHX_ bind, *av_fetch(fbind, k, 0));
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n; k++) pq_bind_sv(aTHX_ bind, *av_fetch(fbind, k, 0)); 18 124 142
994 124 pq_sql_cat_all(aTHX_ sql, where);
995 124 pq_sql_cat(aTHX_ sql, " ORDER BY id LIMIT ? OFFSET ?");
996 124 ▶ pq_bind_iv(aTHX_ bind, limit > 0 ? limit : 50);
Branch: 1 branch
BranchTrueFalseTotal
pq_bind_iv(aTHX_ bind, limit > 0 ? limit : 50); 3 121 124
997 124 pq_bind_iv(aTHX_ bind, offset > 0 ? offset : 0);
998  
999 124 sth = pq_sth(aTHX_ self, sql);
1000 124 (void)pq_execute(aTHX_ sth, bind);
1001 308 ▶ while ((row = pq_fetchrow(aTHX_ sth))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((row = pq_fetchrow(aTHX_ sth))) { 184 124 308
1002 184 av_push(ws, newRV_noinc((SV *)pq_worker_row_hv(aTHX_ row)));
1003 184 SvREFCNT_dec((SV *)row);
1004 }
1005 124 { SV *r = pq_call_meth(aTHX_ sth, "finish", NULL, 0, 1);
1006 124 ▶ if (r) SvREFCNT_dec(r); }
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); } 124 0 124
1007 }
1008  
1009 124 (void)hv_stores(out, "workers", newRV_noinc((SV *)ws));
1010 124 return newRV_noinc((SV *)out);
1011 }
1012  
1013 /* ---- stats -----------------------------------------------------------------
1014 *
1015 * The phase-3 shape: per-state counts, the delayed subset, worker counts,
1016 * schema version. Phase 6 adds history buckets and rates; the keys here
1017 * are stable and only ever gain siblings. */
1018  
1019 /* one grouped count -> { name => { state => n, ... }, ... } under key */
1020 194 static void pq_stats_group(pTHX_ SV *self, HV *out, const char *key,
1021 const char *sql) {
1022 194 SV *sth = pq_sth(aTHX_ self, sv_2mortal(newSVpv(sql, 0)));
1023 AV *row;
1024 194 HV *groups = newHV();
1025 194 (void)pq_execute(aTHX_ sth, NULL);
1026 540 ▶ while ((row = pq_fetchrow(aTHX_ sth))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((row = pq_fetchrow(aTHX_ sth))) { 346 194 540
1027 346 SV *gn = pq_col(aTHX_ row, 0);
1028 346 SV *st = pq_col(aTHX_ row, 1);
1029 346 IV n = pq_col_iv(aTHX_ row, 2);
1030 346 ▶ if (SvOK(gn) && SvOK(st)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvOK(gn) && SvOK(st)) { 346 0 346
if (SvOK(gn) && SvOK(st)) { 346 0 346
1031 346 HE *he = hv_fetch_ent(groups, gn, 1, 0);
1032 346 ▶ SV *slot = he ? HeVAL(he) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *slot = he ? HeVAL(he) : NULL; 346 0 346
1033 HV *per;
1034 346 ▶ if (slot && !SvROK(slot)) {
Branch: 2 branches
BranchTrueFalseTotal
if (slot && !SvROK(slot)) { 346 0 346
if (slot && !SvROK(slot)) { 225 121 346
1035 225 per = newHV();
1036 225 sv_setsv(slot, sv_2mortal(newRV_noinc((SV *)per)));
1037 }
1038 121 ▶ else per = slot ? (HV *)SvRV(slot) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
else per = slot ? (HV *)SvRV(slot) : NULL; 121 0 121
1039 346 ▶ if (per)
Branch: 1 branch
BranchTrueFalseTotal
if (per) 346 0 346
1040 692 (void)hv_store(per, SvPV_nolen(st), SvCUR(st),
1041 newSViv(n), 0);
1042 }
1043 346 SvREFCNT_dec((SV *)row);
1044 }
1045 194 { SV *r = pq_call_meth(aTHX_ sth, "finish", NULL, 0, 1);
1046 194 ▶ if (r) SvREFCNT_dec(r); }
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); } 194 0 194
1047 194 (void)hv_store(out, key, (I32)strlen(key),
1048 newRV_noinc((SV *)groups), 0);
1049 194 }
1050  
1051 97 static SV *pq_stats(pTHX_ SV *self) {
1052 97 HV *out = newHV();
1053 97 double now = pq_now(aTHX_ self);
1054 97 IV total = 0;
1055  
1056 97 (void)hv_stores(out, "inactive_jobs", newSViv(0));
1057 97 (void)hv_stores(out, "active_jobs", newSViv(0));
1058 97 (void)hv_stores(out, "failed_jobs", newSViv(0));
1059 97 (void)hv_stores(out, "finished_jobs", newSViv(0));
1060  
1061 {
1062 97 SV *sth = pq_sth(aTHX_ self, sv_2mortal(newSVpvs(
1063 "SELECT state, count(*) FROM pq_jobs GROUP BY state")));
1064 AV *row;
1065 97 (void)pq_execute(aTHX_ sth, NULL);
1066 257 ▶ while ((row = pq_fetchrow(aTHX_ sth))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((row = pq_fetchrow(aTHX_ sth))) { 160 97 257
1067 160 SV *st = pq_col(aTHX_ row, 0);
1068 160 IV n = pq_col_iv(aTHX_ row, 1);
1069 160 ▶ if (SvOK(st)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(st)) { 160 0 160
1070 160 SV *key = sv_2mortal(Perl_newSVpvf(aTHX_ "%s_jobs",
1071 SvPV_nolen(st)));
1072 160 (void)hv_store_ent(out, key, newSViv(n), 0);
1073 160 total += n;
1074 }
1075 160 SvREFCNT_dec((SV *)row);
1076 }
1077 97 { SV *r = pq_call_meth(aTHX_ sth, "finish", NULL, 0, 1);
1078 97 ▶ if (r) SvREFCNT_dec(r); }
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); } 97 0 97
1079 }
1080 97 (void)hv_stores(out, "total_jobs", newSViv(total));
1081  
1082 {
1083 97 AV *b = pq_binds(aTHX), *row;
1084 97 pq_bind_nv(aTHX_ b, now);
1085 97 row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
1086 "SELECT count(*) FROM pq_jobs"
1087 " WHERE state = 'inactive' AND delayed > ?")), b);
1088 97 ▶ (void)hv_stores(out, "delayed_jobs",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(out, "delayed_jobs", 97 0 97
1089 newSViv(row ? pq_col_iv(aTHX_ row, 0) : 0));
1090 97 ▶ if (row) SvREFCNT_dec((SV *)row);
Branch: 1 branch
BranchTrueFalseTotal
if (row) SvREFCNT_dec((SV *)row); 97 0 97
1091 }
1092  
1093 {
1094 97 AV *row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
1095 "SELECT count(*) FROM pq_workers")), NULL);
1096 97 ▶ (void)hv_stores(out, "workers",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(out, "workers", 97 0 97
1097 newSViv(row ? pq_col_iv(aTHX_ row, 0) : 0));
1098 97 ▶ if (row) SvREFCNT_dec((SV *)row);
Branch: 1 branch
BranchTrueFalseTotal
if (row) SvREFCNT_dec((SV *)row); 97 0 97
1099 }
1100  
1101 /* per-queue and per-task per-state counts, for the UI's breakdown
1102 * tables: { name => { state => n, ... }, ... } */
1103 97 pq_stats_group(aTHX_ self, out, "queues",
1104 "SELECT queue, state, count(*) FROM pq_jobs GROUP BY queue, state");
1105 97 pq_stats_group(aTHX_ self, out, "tasks",
1106 "SELECT task, state, count(*) FROM pq_jobs GROUP BY task, state");
1107  
1108 /* alive = heartbeat within missing_after; the rest are what repair
1109 * will sweep */
1110 {
1111 97 AV *b = pq_binds(aTHX), *row;
1112 97 pq_bind_nv(aTHX_ b, now - pq_opt_num(aTHX_ self, "missing_after",
1113 1800.0));
1114 97 row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
1115 "SELECT count(*) FROM pq_workers WHERE notified >= ?")), b);
1116 97 ▶ (void)hv_stores(out, "active_workers",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(out, "active_workers", 97 0 97
1117 newSViv(row ? pq_col_iv(aTHX_ row, 0) : 0));
1118 97 ▶ if (row) SvREFCNT_dec((SV *)row);
Branch: 1 branch
BranchTrueFalseTotal
if (row) SvREFCNT_dec((SV *)row); 97 0 97
1119 }
1120  
1121 /* lifetime enqueue count, approximated by the id sequence: deletes do
1122 * not shrink it, which is exactly the property a rate needs */
1123 {
1124 97 AV *row = pq_selectrow(aTHX_ self, sv_2mortal(newSVpvs(
1125 "SELECT max(id) FROM pq_jobs")), NULL);
1126 97 ▶ SV *m = row ? pq_col(aTHX_ row, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *m = row ? pq_col(aTHX_ row, 0) : NULL; 97 0 97
1127 97 ▶ (void)hv_stores(out, "enqueued_jobs",
Branch: 2 branches
BranchTrueFalseTotal
(void)hv_stores(out, "enqueued_jobs", 97 0 97
(void)hv_stores(out, "enqueued_jobs", 90 7 97
1128 newSViv((m && SvOK(m)) ? SvIV(m) : 0));
1129 97 ▶ if (row) SvREFCNT_dec((SV *)row);
Branch: 1 branch
BranchTrueFalseTotal
if (row) SvREFCNT_dec((SV *)row); 97 0 97
1130 }
1131  
1132 97 (void)hv_stores(out, "schema_version",
1133 newSViv(pq_schema_version(aTHX_ self)));
1134 97 return newRV_noinc((SV *)out);
1135 }
1136  
1137 /* ---- history ---------------------------------------------------------------
1138 *
1139 * Finished-vs-failed counts in hourly buckets over the last day and daily
1140 * buckets over the last week, for the phase-8 graph. Sparse: only buckets
1141 * with data appear, sorted ascending; the UI fills gaps. remove_after
1142 * trims what can appear (default 2 days), and the POD says so - history
1143 * reaches only as far back as retention keeps terminal rows.
1144 *
1145 * The epoch-truncation expression is the one genuinely divergent piece:
1146 * CAST truncates on SQLite but ROUNDS on Pg, so Pg uses floor(). Both
1147 * still bucket identically, which the battery asserts. */
1148  
1149 4 static AV *pq_history_scan(pTHX_ SV *self, double cutoff, IV width) {
1150 4 AV *out = newAV();
1151 SV *sql, *sth;
1152 4 AV *bind = pq_binds(aTHX), *row;
1153  
1154 4 sql = pq_sql_new(aTHX_ "SELECT ");
1155 4 ▶ if (pq_is_pg(aTHX_ self))
Branch: 1 branch
BranchTrueFalseTotal
if (pq_is_pg(aTHX_ self)) 0 4 4
1156 0 pq_sql_cat(aTHX_ sql, "(floor(finished / ?) * ?)::bigint");
1157 else
1158 4 pq_sql_cat(aTHX_ sql, "CAST(finished / ? AS INTEGER) * ?");
1159 4 pq_sql_cat(aTHX_ sql,
1160 " AS bucket, state, count(*) FROM pq_jobs"
1161 " WHERE state IN ('finished', 'failed') AND finished >= ?"
1162 " GROUP BY bucket, state ORDER BY bucket");
1163  
1164 4 pq_bind_iv(aTHX_ bind, width);
1165 4 pq_bind_iv(aTHX_ bind, width);
1166 4 pq_bind_nv(aTHX_ bind, cutoff);
1167  
1168 4 sth = pq_sth(aTHX_ self, sql);
1169 4 (void)pq_execute(aTHX_ sth, bind);
1170 {
1171 4 HV *cur = NULL;
1172 4 IV cur_epoch = -1;
1173 8 ▶ while ((row = pq_fetchrow(aTHX_ sth))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((row = pq_fetchrow(aTHX_ sth))) { 4 4 8
1174 4 IV epoch = pq_col_iv(aTHX_ row, 0);
1175 4 SV *st = pq_col(aTHX_ row, 1);
1176 4 IV cnt = pq_col_iv(aTHX_ row, 2);
1177 4 ▶ if (!cur || epoch != cur_epoch) {
Branch: 2 branches
BranchTrueFalseTotal
if (!cur || epoch != cur_epoch) { 2 2 4
if (!cur || epoch != cur_epoch) { 0 2 2
1178 2 cur = newHV();
1179 2 (void)hv_stores(cur, "epoch", newSViv(epoch));
1180 2 (void)hv_stores(cur, "finished", newSViv(0));
1181 2 (void)hv_stores(cur, "failed", newSViv(0));
1182 2 av_push(out, newRV_noinc((SV *)cur));
1183 2 cur_epoch = epoch;
1184 }
1185 4 ▶ if (SvOK(st))
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(st)) 4 0 4
1186 8 (void)hv_store(cur, SvPV_nolen(st), SvCUR(st),
1187 newSViv(cnt), 0);
1188 4 SvREFCNT_dec((SV *)row);
1189 }
1190 }
1191 4 { SV *r = pq_call_meth(aTHX_ sth, "finish", NULL, 0, 1);
1192 4 ▶ if (r) SvREFCNT_dec(r); }
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); } 4 0 4
1193 4 return out;
1194 }
1195  
1196 2 static SV *pq_history(pTHX_ SV *self) {
1197 2 HV *out = newHV();
1198 2 double now = pq_now(aTHX_ self);
1199 2 (void)hv_stores(out, "hourly", newRV_noinc((SV *)
1200 pq_history_scan(aTHX_ self, now - 86400.0, 3600)));
1201 2 (void)hv_stores(out, "daily", newRV_noinc((SV *)
1202 pq_history_scan(aTHX_ self, now - 604800.0, 86400)));
1203 2 return newRV_noinc((SV *)out);
1204 }
1205  
1206 /* ---- the sleep horizon -----------------------------------------------------
1207 *
1208 * Seconds until the next delayed job in these queues becomes claimable, or
1209 * -1 when there is none. The idle worker clamps its sleep to this, so a
1210 * delayed job wakes it at the right moment rather than at the next poll
1211 * tick - which is what makes a long dequeue_interval safe. */
1212 15 static double pq_ready_horizon(pTHX_ SV *self, AV *queues) {
1213 SV *sql;
1214 AV *bind, *row;
1215 15 ▶ SSize_t nq = queues ? av_len(queues) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
SSize_t nq = queues ? av_len(queues) + 1 : 0; 15 0 15
1216 15 double now, horizon = -1.0;
1217  
1218 15 ▶ if (nq < 1) return -1.0;
Branch: 1 branch
BranchTrueFalseTotal
if (nq < 1) return -1.0; 0 15 15
1219 15 now = pq_now(aTHX_ self);
1220  
1221 15 sql = pq_sql_new(aTHX_
1222 "SELECT min(delayed) FROM pq_jobs WHERE state = 'inactive' AND ");
1223 15 pq_sql_in(aTHX_ sql, "queue", nq);
1224 15 pq_sql_cat(aTHX_ sql, " AND delayed > ?");
1225  
1226 15 bind = pq_binds(aTHX);
1227 {
1228 SSize_t i;
1229 30 ▶ for (i = 0; i < nq; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < nq; i++) 15 15 30
1230 15 pq_bind_sv(aTHX_ bind, *av_fetch(queues, i, 0));
1231 }
1232 15 pq_bind_nv(aTHX_ bind, now);
1233  
1234 15 row = pq_selectrow(aTHX_ self, sql, bind);
1235 15 ▶ if (row) {
Branch: 1 branch
BranchTrueFalseTotal
if (row) { 15 0 15
1236 15 SV *m = pq_col(aTHX_ row, 0);
1237 15 ▶ if (m && SvOK(m)) {
Branch: 2 branches
BranchTrueFalseTotal
if (m && SvOK(m)) { 15 0 15
if (m && SvOK(m)) { 0 15 15
1238 0 horizon = SvNV(m) - now;
1239 0 ▶ if (horizon < 0) horizon = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (horizon < 0) horizon = 0; 0 0 0
1240 }
1241 15 SvREFCNT_dec((SV *)row);
1242 }
1243 15 return horizon;
1244 }
1245  
1246 /* Empty every table except pq_migrations. The CLI gates this behind an
1247 * explicit --yes; the method itself does not second-guess. */
1248 2 static void pq_reset(pTHX_ SV *self) {
1249 2 (void)pq_do_pv(aTHX_ self, "DELETE FROM pq_job_logs");
1250 2 (void)pq_do_pv(aTHX_ self, "DELETE FROM pq_job_deps");
1251 2 (void)pq_do_pv(aTHX_ self, "DELETE FROM pq_jobs");
1252 2 (void)pq_do_pv(aTHX_ self, "DELETE FROM pq_workers");
1253 2 (void)pq_do_pv(aTHX_ self, "DELETE FROM pq_locks");
1254 2 (void)pq_do_pv(aTHX_ self, "DELETE FROM pq_crons");
1255 2 }
1256  
1257 #endif /* PQ_BACKEND_H */
« xs/cron.xs ↑ Summary include/pq_log.h »