Gearman.xs

filter: Statementstmt 64.7% 931 / 1439 Branchbran 41.7% 492 / 1178 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 54.3% 1423 / 2617 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/EV/Gearman/Job.pm ↑ Summary
1 #define PERL_NO_GET_CONTEXT
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5 #define NEED_mg_findext /* ppport fallback for perls < 5.13.8 */
6 #include "ppport.h"
7  
8 #include "EVAPI.h"
9 #include "ngx-queue.h"
10  
11 #include <sys/socket.h>
12 #include <sys/un.h>
13 #include <netinet/in.h>
14 #include <netinet/tcp.h>
15 #include <netdb.h>
16 #include <fcntl.h>
17 #include <errno.h>
18 #include <unistd.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <stdint.h>
22 #include <arpa/inet.h>
23  
24 /* ================================================================
25 * Gearman binary protocol constants
26 *
27 * Wire format (all integers big-endian):
28 * Bytes 0-3 : magic - "\0REQ" for client->server, "\0RES" for server->client
29 * Bytes 4-7 : command (uint32 BE)
30 * Bytes 8-11: data length (uint32 BE)
31 * Bytes 12+ : data, with NUL-separated args; final arg has no terminator
32 * ================================================================ */
33  
34 #define GM_MAGIC_REQ "\0REQ"
35 #define GM_MAGIC_RES "\0RES"
36 #define GM_HEADER_SIZE 12
37  
38 #define GM_MAGIC_ALIVE 0xCA7C00FE
39 #define GM_MAGIC_FREED 0xDEAD0FF0
40  
41 /* Commands (request: client/worker -> server) */
42 #define GM_CMD_CAN_DO 1
43 #define GM_CMD_CANT_DO 2
44 #define GM_CMD_RESET_ABILITIES 3
45 #define GM_CMD_PRE_SLEEP 4
46 #define GM_CMD_NOOP 6
47 #define GM_CMD_SUBMIT_JOB 7
48 #define GM_CMD_JOB_CREATED 8
49 #define GM_CMD_GRAB_JOB 9
50 #define GM_CMD_NO_JOB 10
51 #define GM_CMD_JOB_ASSIGN 11
52 #define GM_CMD_WORK_STATUS 12
53 #define GM_CMD_WORK_COMPLETE 13
54 #define GM_CMD_WORK_FAIL 14
55 #define GM_CMD_GET_STATUS 15
56 #define GM_CMD_ECHO_REQ 16
57 #define GM_CMD_ECHO_RES 17
58 #define GM_CMD_SUBMIT_JOB_BG 18
59 #define GM_CMD_ERROR 19
60 #define GM_CMD_STATUS_RES 20
61 #define GM_CMD_SUBMIT_JOB_HIGH 21
62 #define GM_CMD_SET_CLIENT_ID 22
63 #define GM_CMD_CAN_DO_TIMEOUT 23
64 #define GM_CMD_ALL_YOURS 24
65 #define GM_CMD_WORK_EXCEPTION 25
66 #define GM_CMD_OPTION_REQ 26
67 #define GM_CMD_OPTION_RES 27
68 #define GM_CMD_WORK_DATA 28
69 #define GM_CMD_WORK_WARNING 29
70 #define GM_CMD_GRAB_JOB_UNIQ 30
71 #define GM_CMD_JOB_ASSIGN_UNIQ 31
72 #define GM_CMD_SUBMIT_JOB_HIGH_BG 32
73 #define GM_CMD_SUBMIT_JOB_LOW 33
74 #define GM_CMD_SUBMIT_JOB_LOW_BG 34
75 #define GM_CMD_SUBMIT_JOB_SCHED 35
76 #define GM_CMD_SUBMIT_JOB_EPOCH 36
77 #define GM_CMD_GET_STATUS_UNIQUE 41
78 #define GM_CMD_STATUS_RES_UNIQUE 42
79  
80 /* Internal request types (CB_*) — describe what we're waiting for */
81 #define CB_ECHO 1 /* expects ECHO_RES */
82 #define CB_SUBMIT 2 /* expects JOB_CREATED + work events */
83 #define CB_SUBMIT_BG 3 /* expects JOB_CREATED only */
84 #define CB_GET_STATUS 4 /* expects STATUS_RES */
85 #define CB_GET_STATUS_UNIQ 5 /* expects STATUS_RES_UNIQUE */
86 #define CB_OPTION 6 /* expects OPTION_RES */
87 #define CB_GRAB_JOB 7 /* expects JOB_ASSIGN | JOB_ASSIGN_UNIQ | NO_JOB */
88 #define CB_ADMIN 8 /* expects text-protocol response */
89  
90 #define BUF_INIT_SIZE 16384
91 #define GM_MAX_PACKET (256u * 1024u * 1024u) /* 256 MB sanity bound */
92 /* Admin (text-protocol) replies carry no length field, only a line
93 terminator, so GM_MAX_PACKET cannot bound them. A peer that never
94 sends the terminator would otherwise grow the read buffer without
95 limit; cap the buffered reply and drop the connection past this. */
96 #define GM_MAX_ADMIN_RESPONSE (16u * 1024u * 1024u)
97 /* Once a buffer has fully drained, release it back to BUF_INIT_SIZE if
98 it grew past this — a single large packet otherwise pins its
99 high-water-mark allocation for the life of the connection. */
100 #define BUF_SHRINK_THRESHOLD (1u * 1024u * 1024u)
101  
102 #define CLEAR_HANDLER(field) \
103 do { if (NULL != (field)) { SvREFCNT_dec(field); (field) = NULL; } } while(0)
104  
105 /* Silently drain an ngx_queue, freeing each entry via its cleanup
106 function. Used during global destruction and DESTROY where invoking
107 Perl callbacks would be unsafe / pointless. */
108 #define DRAIN_QUEUE_SILENT(qhead, type, cleanup) \
109 while (!ngx_queue_empty(qhead)) { \
110 ngx_queue_t *_q = ngx_queue_head(qhead); \
111 type *_e = ngx_queue_data(_q, type, queue); \
112 ngx_queue_remove(_q); \
113 cleanup(aTHX_ _e); \
114 }
115  
116 #define GM_CROAK_UNLESS_ALIVE(self) \
117 do { \
118 if (!(self)->connected && !(self)->connecting && \
119 !((self)->reconnect && (self)->reconnect_timer_active)) \
120 croak("not connected"); \
121 } while(0)
122  
123 /* ================================================================
124 * Type declarations
125 * ================================================================ */
126  
127 typedef struct ev_gm_s ev_gm_t;
128 typedef struct ev_gm_req_s ev_gm_req_t;
129 typedef struct ev_gm_wait_s ev_gm_wait_t;
130 typedef struct ev_gm_func_s ev_gm_func_t;
131 typedef struct ev_gm_active_s ev_gm_active_t;
132  
133 typedef ev_gm_t* EV__Gearman;
134  
135 /* Request awaiting a response (FIFO). For SUBMIT_JOB, holds the
136 * callback bundle that gets transferred to active_jobs once the
137 * JOB_CREATED handle is known. */
138 struct ev_gm_req_s {
139 ngx_queue_t queue;
140 int kind; /* CB_* */
141 SV *cb; /* primary callback (handle for BG, result for FG) */
142 SV *on_data;
143 SV *on_warning;
144 SV *on_status;
145 SV *on_exception;
146 int admin_terminator; /* 0 = single-line; 1 = ".\n" terminator (status/workers) */
147 ev_tstamp sent_at; /* ev_now() when queued on cb_queue; per-request
148 command_timeout budget starts here */
149 };
150  
151 /* Pending packet awaiting connect / drain */
152 struct ev_gm_wait_s {
153 ngx_queue_t queue;
154 char *packet;
155 size_t packet_len;
156 /* if non-NULL, becomes a request entry on send */
157 ev_gm_req_t *req;
158 };
159  
160 /* Active foreground job (after JOB_CREATED) */
161 struct ev_gm_active_s {
162 ngx_queue_t queue;
163 char *handle;
164 STRLEN handle_len;
165 SV *on_complete;
166 SV *on_data;
167 SV *on_warning;
168 SV *on_status;
169 SV *on_exception;
170 };
171  
172 /* Registered worker function */
173 struct ev_gm_func_s {
174 ngx_queue_t queue;
175 char *name;
176 SV *cb;
177 int async; /* if 1, callback returns nothing; user calls $job->complete */
178 int timeout; /* seconds; 0 = no timeout */
179 int no_cb_warned; /* warned once about dispatching to a cb-less can_do entry */
180 };
181  
182 struct ev_gm_s {
183 unsigned int magic;
184 struct ev_loop *loop;
185 SV *loop_sv; /* strong ref on a user-supplied loop => EV::Loop object */
186 int fd;
187 int connected;
188 int connecting;
189  
190 /* IO watchers */
191 ev_io rio, wio;
192 int reading, writing;
193  
194 /* Buffers */
195 char *rbuf;
196 size_t rbuf_len, rbuf_cap;
197 char *wbuf;
198 size_t wbuf_len, wbuf_off, wbuf_cap;
199  
200 /* User-level callbacks */
201 SV *on_error;
202 SV *on_connect;
203 SV *on_disconnect;
204  
205 /* FIFO of requests awaiting a binary response */
206 ngx_queue_t cb_queue;
207 int pending_count;
208  
209 /* Pending packets awaiting transmission (e.g. before connect) */
210 ngx_queue_t wait_queue;
211 int waiting_count;
212  
213 /* Active jobs (foreground) by handle */
214 ngx_queue_t active_jobs;
215 int active_count_cached;
216  
217 /* Worker state */
218 ngx_queue_t functions;
219 int worker_active; /* in worker loop */
220 int worker_sleeping; /* PRE_SLEEP issued, awaiting NOOP */
221 int worker_grab_inflight;/* GRAB_JOB[_UNIQ] in flight */
222 int worker_grab_uniq; /* prefer GRAB_JOB_UNIQ */
223 SV *worker_on_idle; /* fires when no jobs available */
224 int worker_one_shot; /* if 1, exit worker loop after first job */
225 char *client_id; /* for SET_CLIENT_ID */
226  
227 /* Connection target */
228 char *host;
229 int port;
230 char *path;
231  
232 /* getaddrinfo fallback list (TCP): live only while a connect
233 sequence walks it; freed on success, exhaustion or disconnect. */
234 struct addrinfo *ai_list;
235 struct addrinfo *ai_cur;
236  
237 /* Reconnect */
238 int reconnect;
239 int reconnect_delay_ms;
240 int max_reconnect_attempts;
241 int reconnect_attempts;
242 ev_timer reconnect_timer;
243 int reconnect_timer_active;
244 int intentional_disconnect;
245  
246 /* Timeouts */
247 int connect_timeout_ms;
248 ev_timer connect_timer;
249 int connect_timer_active;
250 int command_timeout_ms;
251 ev_timer cmd_timer;
252 int cmd_timer_active;
253  
254 /* Safety */
255 int callback_depth;
256 int in_cb_cleanup;
257 int in_wait_cleanup;
258 int in_active_cleanup;
259 /* Live EV::Gearman::Job objects holding a tombstone reference on
260 this struct (via sv_magicext on the job HV). While > 0 the
261 struct is never Safefreed — a DESTROYed connection becomes an
262 inert tombstone until the last job releases it, so job_resolve's
263 magic-word check never reads freed memory. */
264 U32 job_refs;
265  
266 /* Options */
267 int priority;
268 int keepalive;
269  
270 /* Options sent on connect */
271 int opt_exceptions;
272 };
273  
274 /* ================================================================
275 * Forward declarations
276 * ================================================================ */
277  
278 static void io_cb(EV_P_ ev_io *w, int revents);
279 static void reconnect_timer_cb(EV_P_ ev_timer *w, int revents);
280 static void connect_timeout_cb(EV_P_ ev_timer *w, int revents);
281 static void cmd_timeout_cb(EV_P_ ev_timer *w, int revents);
282 static void start_reading(ev_gm_t *self);
283 static void stop_reading(ev_gm_t *self);
284 static void start_writing(ev_gm_t *self);
285 static void stop_writing(ev_gm_t *self);
286 static void start_connect(pTHX_ ev_gm_t *self);
287 static void cleanup_connection(pTHX_ ev_gm_t *self);
288 static void emit_error(pTHX_ ev_gm_t *self, const char *msg);
289 static void handle_disconnect(pTHX_ ev_gm_t *self, const char *reason);
290 static void schedule_reconnect(pTHX_ ev_gm_t *self);
291 static void apply_keepalive(ev_gm_t *self);
292 static void report_connect_error(pTHX_ ev_gm_t *self, const char *errbuf);
293 static void finish_connect_success(pTHX_ ev_gm_t *self);
294 static void stop_connect_timer(ev_gm_t *self);
295 static void stop_reconnect_timer(ev_gm_t *self);
296 static int check_destroyed(ev_gm_t *self);
297 static void clear_addrinfo(ev_gm_t *self);
298 static void connect_try_from(pTHX_ ev_gm_t *self, const char *prev_err);
299 static void cancel_pending(pTHX_ ev_gm_t *self, const char *reason);
300 static void cancel_waiting(pTHX_ ev_gm_t *self, const char *reason);
301 static void cancel_active(pTHX_ ev_gm_t *self, const char *reason);
302 static void send_pending_waits(pTHX_ ev_gm_t *self);
303 static void arm_cmd_timer(ev_gm_t *self);
304 static void disarm_cmd_timer(ev_gm_t *self);
305 static void enqueue_packet(pTHX_ ev_gm_t *self,
306 uint32_t cmd, const char *data, size_t data_len, ev_gm_req_t *req);
307 static void worker_continue(pTHX_ ev_gm_t *self);
308 static void worker_send_grab(pTHX_ ev_gm_t *self);
309 static void worker_send_pre_sleep(pTHX_ ev_gm_t *self);
310 static ev_gm_func_t* find_function(ev_gm_t *self, const char *name, STRLEN len);
311  
312 /* ================================================================
313 * Big-endian helpers (no unaligned access)
314 * ================================================================ */
315  
316 82 static void gm_write_u32(char *buf, uint32_t val) {
317 82 val = htonl(val);
318 82 memcpy(buf, &val, 4);
319 82 }
320  
321 102 static uint32_t gm_read_u32(const char *buf) {
322 uint32_t val;
323 102 memcpy(&val, buf, 4);
324 102 return ntohl(val);
325 }
326  
327 /* atoi/strtol on a length-bounded ASCII run that may not be NUL-terminated
328 (gm_arg's last field returns a pointer with no trailing NUL since the
329 separator-NUL only lives between fields). Copies up to 31 bytes onto
330 the stack first. */
331 0 static IV gm_atoi_n(const char *p, size_t len) {
332 char buf[32];
333 0 ▶ if (len > sizeof(buf) - 1) len = sizeof(buf) - 1;
Branch: 1 branch
BranchTrueFalseTotal
if (len > sizeof(buf) - 1) len = sizeof(buf) - 1; 0 0 0
334 0 memcpy(buf, p, len);
335 0 buf[len] = '\0';
336 0 return (IV)atoi(buf);
337 }
338  
339 /* ================================================================
340 * Buffer management
341 * ================================================================ */
342  
343 42 static void buf_ensure_write(ev_gm_t *self, size_t needed) {
344 /* Compact first to reclaim already-sent prefix. */
345 42 ▶ if (self->wbuf_off > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->wbuf_off > 0) { 0 42 42
346 0 size_t live = self->wbuf_len - self->wbuf_off;
347 0 ▶ if (live > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (live > 0) 0 0 0
348 0 memmove(self->wbuf, self->wbuf + self->wbuf_off, live);
349 0 self->wbuf_len = live;
350 0 self->wbuf_off = 0;
351 }
352 42 size_t total = self->wbuf_len + needed;
353 42 ▶ if (self->wbuf_cap >= total) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->wbuf_cap >= total) return; 41 1 42
354 1 ▶ size_t new_cap = self->wbuf_cap ? self->wbuf_cap : BUF_INIT_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
size_t new_cap = self->wbuf_cap ? self->wbuf_cap : BUF_INIT_SIZE; 1 0 1
355 3 ▶ while (new_cap < total) new_cap *= 2;
Branch: 1 branch
BranchTrueFalseTotal
while (new_cap < total) new_cap *= 2; 2 1 3
356 1 Renew(self->wbuf, new_cap, char);
357 1 self->wbuf_cap = new_cap;
358 }
359  
360 309 static void buf_ensure_read(ev_gm_t *self, size_t needed) {
361 309 size_t total = self->rbuf_len + needed;
362 309 ▶ if (self->rbuf_cap >= total) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_cap >= total) return; 296 13 309
363 13 ▶ size_t new_cap = self->rbuf_cap ? self->rbuf_cap : BUF_INIT_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
size_t new_cap = self->rbuf_cap ? self->rbuf_cap : BUF_INIT_SIZE; 13 0 13
364 26 ▶ while (new_cap < total) new_cap *= 2;
Branch: 1 branch
BranchTrueFalseTotal
while (new_cap < total) new_cap *= 2; 13 13 26
365 13 Renew(self->rbuf, new_cap, char);
366 13 self->rbuf_cap = new_cap;
367 }
368  
369 42 static void buf_append_write(ev_gm_t *self, const char *data, size_t len) {
370 42 buf_ensure_write(self, len);
371 42 memcpy(self->wbuf + self->wbuf_len, data, len);
372 42 self->wbuf_len += len;
373 42 }
374  
375 /* Release an oversized, fully-drained buffer back to the initial size.
376 Caller guarantees the buffer holds no live bytes. */
377 51 static void buf_maybe_shrink(char **buf, size_t *cap) {
378 51 ▶ if (*cap > BUF_SHRINK_THRESHOLD) {
Branch: 1 branch
BranchTrueFalseTotal
if (*cap > BUF_SHRINK_THRESHOLD) { 0 51 51
379 0 Renew(*buf, BUF_INIT_SIZE, char);
380 0 *cap = BUF_INIT_SIZE;
381 }
382 51 }
383  
384 /* ================================================================
385 * Watcher helpers
386 * ================================================================ */
387  
388 23 static void start_reading(ev_gm_t *self) {
389 23 ▶ if (!self->reading && self->fd >= 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!self->reading && self->fd >= 0) { 23 0 23
if (!self->reading && self->fd >= 0) { 23 0 23
390 23 ev_io_start(self->loop, &self->rio);
391 23 self->reading = 1;
392 }
393 23 }
394  
395 45 static void stop_reading(ev_gm_t *self) {
396 45 ▶ if (self->reading) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reading) { 23 22 45
397 23 ev_io_stop(self->loop, &self->rio);
398 23 self->reading = 0;
399 }
400 45 }
401  
402 72 static void start_writing(ev_gm_t *self) {
403 72 ▶ if (!self->writing && self->fd >= 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!self->writing && self->fd >= 0) { 59 13 72
if (!self->writing && self->fd >= 0) { 59 0 59
404 59 ev_io_start(self->loop, &self->wio);
405 59 self->writing = 1;
406 }
407 72 }
408  
409 99 static void stop_writing(ev_gm_t *self) {
410 99 ▶ if (self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->writing) { 59 40 99
411 59 ev_io_stop(self->loop, &self->wio);
412 59 self->writing = 0;
413 }
414 99 }
415  
416 /* "Is dead" predicate with the free as a side effect. Callers use the
417 return value as "the object is dead, STOP TOUCHING IT" — which must
418 not be conflated with "it was freed": with jobs stashed, a destroyed
419 client has magic == FREED but job_refs > 0, and falls through to
420 nothing. The struct is Safefreed exactly once: when it is dead AND
421 the callback depth has unwound AND no job tombstone refs remain. */
422 496 static int check_destroyed(ev_gm_t *self) {
423 496 ▶ if (self->magic != GM_MAGIC_FREED) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_FREED) return 0; 463 33 496
424 33 ▶ if (self->callback_depth == 0 && self->job_refs == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (self->callback_depth == 0 && self->job_refs == 0) 33 0 33
if (self->callback_depth == 0 && self->job_refs == 0) 33 0 33
425 33 Safefree(self);
426 33 return 1; /* dead either way — caller must stop */
427 }
428  
429 /* ================================================================
430 * Callback invocation helpers
431 * ================================================================ */
432  
433 /* Invoke Perl callback with up to two args (any may be NULL = undef).
434 * Mortal SV transfer: caller passes refcnt=1 SVs, we mortalize them. */
435 13 static void invoke_cb2(pTHX_ ev_gm_t *self, SV *cb, SV *a, SV *b) {
436 13 ▶ if (!cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (!cb) { 0 13 13
437 0 ▶ if (a) SvREFCNT_dec(a);
Branch: 1 branch
BranchTrueFalseTotal
if (a) SvREFCNT_dec(a); 0 0 0
438 0 ▶ if (b) SvREFCNT_dec(b);
Branch: 1 branch
BranchTrueFalseTotal
if (b) SvREFCNT_dec(b); 0 0 0
439 0 return;
440 }
441 13 self->callback_depth++;
442 13 dSP;
443 13 ENTER;
444 13 SAVETMPS;
445 13 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 13 13
446 13 ▶ EXTEND(SP, 2);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 2); 0 13 13
447 13 ▶ if (a) mPUSHs(a); else PUSHs(&PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
if (a) mPUSHs(a); else PUSHs(&PL_sv_undef); 6 7 13
448 13 ▶ if (b) mPUSHs(b); else PUSHs(&PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
if (b) mPUSHs(b); else PUSHs(&PL_sv_undef); 7 6 13
449 13 PUTBACK;
450 13 call_sv(cb, G_DISCARD | G_EVAL);
451 13 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 13 0 13
if (SvTRUE(ERRSV)) { 0 13 13
452 0 ▶ warn("EV::Gearman: callback error: %s", SvPV_nolen(ERRSV));
Branch: 1 branch
BranchTrueFalseTotal
warn("EV::Gearman: callback error: %s", SvPV_nolen(ERRSV)); 0 0 0
453 0 ▶ sv_setsv(ERRSV, &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
sv_setsv(ERRSV, &PL_sv_undef); 0 0 0
454 }
455 13 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 13 0 13
456 13 LEAVE;
457 13 self->callback_depth--;
458 }
459  
460 /* Invoke a handler with at most one mortal arg; eat exceptions. */
461 61 static void invoke_handler(pTHX_ ev_gm_t *self, SV *cb, SV *arg, const char *label) {
462 61 ▶ if (!cb) { if (arg) SvREFCNT_dec(arg); return; }
Branch: 2 branches
BranchTrueFalseTotal
if (!cb) { if (arg) SvREFCNT_dec(arg); return; } 24 37 61
if (!cb) { if (arg) SvREFCNT_dec(arg); return; } 0 24 24
463 37 self->callback_depth++;
464 37 dSP;
465 37 ENTER;
466 37 SAVETMPS;
467 37 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 37 37
468 37 ▶ if (arg) XPUSHs(sv_2mortal(arg));
Branch: 2 branches
BranchTrueFalseTotal
if (arg) XPUSHs(sv_2mortal(arg)); 22 15 37
if (arg) XPUSHs(sv_2mortal(arg)); 0 22 22
469 37 PUTBACK;
470 37 call_sv(cb, G_DISCARD | G_EVAL);
471 37 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 37 0 37
if (SvTRUE(ERRSV)) { 0 37 37
472 0 ▶ warn("EV::Gearman: %s callback error: %s", label, SvPV_nolen(ERRSV));
Branch: 1 branch
BranchTrueFalseTotal
warn("EV::Gearman: %s callback error: %s", label, SvPV_nolen(ERRSV)); 0 0 0
473 0 ▶ sv_setsv(ERRSV, &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
sv_setsv(ERRSV, &PL_sv_undef); 0 0 0
474 }
475 37 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 22 15 37
476 37 LEAVE;
477 37 self->callback_depth--;
478 }
479  
480 22 static void emit_error(pTHX_ ev_gm_t *self, const char *msg) {
481 22 invoke_handler(aTHX_ self, self->on_error, newSVpv(msg, 0), "on_error");
482 22 }
483  
484 23 static void emit_connect(pTHX_ ev_gm_t *self) {
485 23 invoke_handler(aTHX_ self, self->on_connect, NULL, "on_connect");
486 23 }
487  
488 12 static void emit_disconnect(pTHX_ ev_gm_t *self) {
489 12 invoke_handler(aTHX_ self, self->on_disconnect, NULL, "on_disconnect");
490 12 }
491  
492 23 static void apply_keepalive(ev_gm_t *self) {
493 23 ▶ if (self->keepalive <= 0 || self->path) return;
Branch: 2 branches
BranchTrueFalseTotal
if (self->keepalive <= 0 || self->path) return; 0 23 23
if (self->keepalive <= 0 || self->path) return; 0 0 0
494 0 int one = 1;
495 0 setsockopt(self->fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
496 #ifdef TCP_KEEPIDLE
497 0 setsockopt(self->fd, IPPROTO_TCP, TCP_KEEPIDLE,
498 0 &self->keepalive, sizeof(self->keepalive));
499 #endif
500 }
501  
502 /* Set O_NONBLOCK and FD_CLOEXEC on an already-open socket fd. The
503 CLOEXEC step prevents the fd leaking into child processes spawned
504 via fork+exec while the connection is up. Returns 0 on success,
505 -1 on failure (caller should close and error out). */
506 31 static int gm_set_socket_flags(int fd) {
507 31 int fl = fcntl(fd, F_GETFL);
508 31 ▶ if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) return -1;
Branch: 2 branches
BranchTrueFalseTotal
if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) return -1; 31 0 31
if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) return -1; 0 31 31
509 #ifdef FD_CLOEXEC
510 31 fl = fcntl(fd, F_GETFD);
511 31 ▶ if (fl >= 0) (void)fcntl(fd, F_SETFD, fl | FD_CLOEXEC);
Branch: 1 branch
BranchTrueFalseTotal
if (fl >= 0) (void)fcntl(fd, F_SETFD, fl | FD_CLOEXEC); 31 0 31
512 #endif
513 #ifdef SO_NOSIGPIPE
514 /* macOS/BSD lack MSG_NOSIGNAL; this is their per-socket way to
515 keep a write to a closed peer from raising SIGPIPE. A library
516 must never be able to kill its embedder with a signal. */
517 { int one = 1; (void)setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one)); }
518 #endif
519 31 return 0;
520 }
521  
522 /* Shared get/set body for on_error / on_connect / on_disconnect. */
523 5 static SV* handler_accessor(pTHX_ SV **slot, int items, SV *new_cb) {
524 5 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 5 0 5
525 5 ▶ if (*slot) { SvREFCNT_dec(*slot); *slot = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (*slot) { SvREFCNT_dec(*slot); *slot = NULL; } 0 5 5
526 5 ▶ if (SvOK(new_cb) && SvROK(new_cb) && SvTYPE(SvRV(new_cb)) == SVt_PVCV)
Branch: 3 branches
BranchTrueFalseTotal
if (SvOK(new_cb) && SvROK(new_cb) && SvTYPE(SvRV(new_cb)) == SVt_PVCV) 5 0 5
if (SvOK(new_cb) && SvROK(new_cb) && SvTYPE(SvRV(new_cb)) == SVt_PVCV) 5 0 5
if (SvOK(new_cb) && SvROK(new_cb) && SvTYPE(SvRV(new_cb)) == SVt_PVCV) 5 0 5
527 5 *slot = newSVsv(new_cb);
528 }
529 5 ▶ return *slot ? newSVsv(*slot) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
return *slot ? newSVsv(*slot) : &PL_sv_undef; 5 0 5
530 }
531  
532 /* ================================================================
533 * Allocators / cleaners
534 * ================================================================ */
535  
536 /* Allocate a request entry with kind set; if cb_sv is a valid coderef,
537 bumps its refcount into r->cb. Pass NULL (or a non-coderef) for no cb. */
538 25 static ev_gm_req_t* alloc_req(int kind, SV *cb_sv) {
539 dTHX;
540 ev_gm_req_t *r;
541 25 Newxz(r, 1, ev_gm_req_t);
542 25 r->kind = kind;
543 25 ▶ if (cb_sv && SvOK(cb_sv) && SvROK(cb_sv))
Branch: 3 branches
BranchTrueFalseTotal
if (cb_sv && SvOK(cb_sv) && SvROK(cb_sv)) 13 12 25
if (cb_sv && SvOK(cb_sv) && SvROK(cb_sv)) 13 0 13
if (cb_sv && SvOK(cb_sv) && SvROK(cb_sv)) 13 0 13
544 13 r->cb = newSVsv(cb_sv);
545 25 return r;
546 }
547  
548 25 static void cleanup_req(pTHX_ ev_gm_req_t *r) {
549 25 ▶ CLEAR_HANDLER(r->cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(r->cb); 13 12 25
550 25 ▶ CLEAR_HANDLER(r->on_data);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(r->on_data); 0 25 25
551 25 ▶ CLEAR_HANDLER(r->on_warning);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(r->on_warning); 0 25 25
552 25 ▶ CLEAR_HANDLER(r->on_status);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(r->on_status); 0 25 25
553 25 ▶ CLEAR_HANDLER(r->on_exception);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(r->on_exception); 0 25 25
554 25 Safefree(r);
555 25 }
556  
557 0 static void cleanup_wait(pTHX_ ev_gm_wait_t *w) {
558 0 Safefree(w->packet);
559 0 ▶ if (w->req) cleanup_req(aTHX_ w->req);
Branch: 1 branch
BranchTrueFalseTotal
if (w->req) cleanup_req(aTHX_ w->req); 0 0 0
560 0 Safefree(w);
561 0 }
562  
563 0 static void cleanup_active(pTHX_ ev_gm_active_t *a) {
564 0 Safefree(a->handle);
565 0 ▶ CLEAR_HANDLER(a->on_complete);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(a->on_complete); 0 0 0
566 0 ▶ CLEAR_HANDLER(a->on_data);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(a->on_data); 0 0 0
567 0 ▶ CLEAR_HANDLER(a->on_warning);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(a->on_warning); 0 0 0
568 0 ▶ CLEAR_HANDLER(a->on_status);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(a->on_status); 0 0 0
569 0 ▶ CLEAR_HANDLER(a->on_exception);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(a->on_exception); 0 0 0
570 0 Safefree(a);
571 0 }
572  
573 6 static void cleanup_func(pTHX_ ev_gm_func_t *f) {
574 6 Safefree(f->name);
575 6 ▶ CLEAR_HANDLER(f->cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(f->cb); 5 1 6
576 6 Safefree(f);
577 6 }
578  
579 /* ================================================================
580 * Cancel queues
581 * ================================================================ */
582  
583 /* Drain a queue, firing each entry's user callback with reason before
584 freeing it. Bails if a callback triggers DESTROY (magic flips to
585 FREED). The flag prevents reentrancy if a callback also calls
586 disconnect() while we are mid-loop. */
587 #define CANCEL_QUEUE(qhead, type, cleanup, counter, flag, cb_expr) do { \
588 if (self->flag) break; \
589 self->flag = 1; \
590 while (!ngx_queue_empty(qhead)) { \
591 ngx_queue_t *_q = ngx_queue_head(qhead); \
592 type *_e = ngx_queue_data(_q, type, queue); \
593 ngx_queue_remove(_q); \
594 self->counter--; \
595 if (cb_expr) \
596 invoke_cb2(aTHX_ self, cb_expr, NULL, newSVpv(reason, 0)); \
597 if (self->magic == GM_MAGIC_FREED) { \
598 cleanup(aTHX_ _e); \
599 self->flag = 0; \
600 return; \
601 } \
602 cleanup(aTHX_ _e); \
603 } \
604 self->flag = 0; \
605 } while (0)
606  
607 35 static void cancel_pending(pTHX_ ev_gm_t *self, const char *reason) {
608 44 ▶ CANCEL_QUEUE(&self->cb_queue, ev_gm_req_t, cleanup_req,
Branch: 4 branches
BranchTrueFalseTotal
CANCEL_QUEUE(&self->cb_queue, ev_gm_req_t, cleanup_req, 0 35 35
CANCEL_QUEUE(&self->cb_queue, ev_gm_req_t, cleanup_req, 6 3 9
CANCEL_QUEUE(&self->cb_queue, ev_gm_req_t, cleanup_req, 0 9 9
CANCEL_QUEUE(&self->cb_queue, ev_gm_req_t, cleanup_req, 9 35 44
609 pending_count, in_cb_cleanup, _e->cb);
610 35 self->pending_count = 0;
611 }
612  
613 35 static void cancel_waiting(pTHX_ ev_gm_t *self, const char *reason) {
614 35 ▶ CANCEL_QUEUE(&self->wait_queue, ev_gm_wait_t, cleanup_wait,
Branch: 6 branches
BranchTrueFalseTotal
CANCEL_QUEUE(&self->wait_queue, ev_gm_wait_t, cleanup_wait, 0 35 35
CANCEL_QUEUE(&self->wait_queue, ev_gm_wait_t, cleanup_wait, 0 0 0
CANCEL_QUEUE(&self->wait_queue, ev_gm_wait_t, cleanup_wait, 0 0 0
CANCEL_QUEUE(&self->wait_queue, ev_gm_wait_t, cleanup_wait, 0 0 0
CANCEL_QUEUE(&self->wait_queue, ev_gm_wait_t, cleanup_wait, 0 0 0
CANCEL_QUEUE(&self->wait_queue, ev_gm_wait_t, cleanup_wait, 0 35 35
615 waiting_count, in_wait_cleanup,
616 (_e->req ? _e->req->cb : NULL));
617 35 self->waiting_count = 0;
618 }
619  
620 35 static void cancel_active(pTHX_ ev_gm_t *self, const char *reason) {
621 35 ▶ CANCEL_QUEUE(&self->active_jobs, ev_gm_active_t, cleanup_active,
Branch: 4 branches
BranchTrueFalseTotal
CANCEL_QUEUE(&self->active_jobs, ev_gm_active_t, cleanup_active, 0 35 35
CANCEL_QUEUE(&self->active_jobs, ev_gm_active_t, cleanup_active, 0 0 0
CANCEL_QUEUE(&self->active_jobs, ev_gm_active_t, cleanup_active, 0 0 0
CANCEL_QUEUE(&self->active_jobs, ev_gm_active_t, cleanup_active, 0 35 35
622 active_count_cached, in_active_cleanup, _e->on_complete);
623 35 self->active_count_cached = 0;
624 }
625  
626 /* ================================================================
627 * Connection cleanup / disconnect
628 * ================================================================ */
629  
630 45 static void cleanup_connection(pTHX_ ev_gm_t *self) {
631 45 stop_reading(self);
632 45 stop_writing(self);
633 45 stop_connect_timer(self);
634 45 disarm_cmd_timer(self);
635  
636 45 ▶ if (self->fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd >= 0) { 26 19 45
637 26 close(self->fd);
638 26 self->fd = -1;
639 }
640 45 self->connected = 0;
641 45 self->connecting = 0;
642 45 self->rbuf_len = 0;
643 45 self->wbuf_len = 0;
644 45 self->wbuf_off = 0;
645  
646 /* Worker state resets: a reconnect must re-issue CAN_DO and re-start
647 the GRAB loop from scratch. Registered functions are kept. */
648 45 self->worker_sleeping = 0;
649 45 self->worker_grab_inflight = 0;
650  
651 45 clear_addrinfo(self);
652 45 }
653  
654 /* Drop the resolved-address list, if any. It is only live while a
655 connect sequence is walking it. */
656 100 static void clear_addrinfo(ev_gm_t *self) {
657 100 ▶ if (self->ai_list) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ai_list) { 29 71 100
658 29 freeaddrinfo(self->ai_list);
659 29 self->ai_list = NULL;
660 29 self->ai_cur = NULL;
661 }
662 100 }
663  
664 12 static void handle_disconnect(pTHX_ ev_gm_t *self, const char *reason) {
665 12 int was_connected = self->connected;
666 12 cleanup_connection(aTHX_ self);
667  
668 12 cancel_pending(aTHX_ self, "disconnected");
669 12 ▶ if (self->magic == GM_MAGIC_FREED) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) return; 0 12 12
670  
671 12 cancel_active(aTHX_ self, "disconnected");
672 12 ▶ if (self->magic == GM_MAGIC_FREED) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) return; 0 12 12
673  
674 12 cancel_waiting(aTHX_ self, "disconnected");
675 12 ▶ if (self->magic == GM_MAGIC_FREED) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) return; 0 12 12
676  
677 /* Arm the reconnect BEFORE firing user callbacks: re-queueing work
678 from on_disconnect/on_error is the documented purpose of the
679 wait queue, and GM_CROAK_UNLESS_ALIVE keys off the reconnect
680 timer being active. schedule_reconnect may itself emit_error
681 ("max reconnect attempts reached"), so re-check for DESTROY. */
682 12 ▶ if (!self->intentional_disconnect && self->reconnect)
Branch: 2 branches
BranchTrueFalseTotal
if (!self->intentional_disconnect && self->reconnect) 12 0 12
if (!self->intentional_disconnect && self->reconnect) 2 10 12
683 2 schedule_reconnect(aTHX_ self);
684 12 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 12 12
685  
686 12 ▶ if (was_connected) {
Branch: 1 branch
BranchTrueFalseTotal
if (was_connected) { 12 0 12
687 12 emit_disconnect(aTHX_ self);
688 12 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 12 12
689 }
690  
691 12 ▶ if (reason) {
Branch: 1 branch
BranchTrueFalseTotal
if (reason) { 12 0 12
692 12 emit_error(aTHX_ self, reason);
693 12 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 12 12
694 }
695 }
696  
697 7 static void schedule_reconnect(pTHX_ ev_gm_t *self) {
698 /* DESTROY during a callback leaves a zombie (magic FREED, struct
699 kept alive by callback_depth); arming a timer on it would point
700 libev at freed memory once the depth unwinds. */
701 7 ▶ if (self->magic != GM_MAGIC_ALIVE) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_ALIVE) return; 0 7 7
702 7 ▶ if (self->reconnect_timer_active) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->reconnect_timer_active) return; 0 7 7
703 7 ▶ if (self->max_reconnect_attempts > 0 &&
Branch: 1 branch
BranchTrueFalseTotal
if (self->max_reconnect_attempts > 0 && 3 4 7
704 3 ▶ self->reconnect_attempts >= self->max_reconnect_attempts) {
Branch: 1 branch
BranchTrueFalseTotal
self->reconnect_attempts >= self->max_reconnect_attempts) { 1 2 3
705 1 emit_error(aTHX_ self, "max reconnect attempts reached");
706 1 return;
707 }
708 6 self->reconnect_attempts++;
709 6 ev_tstamp delay = (ev_tstamp)self->reconnect_delay_ms / 1000.0;
710 6 ▶ if (delay < 0) delay = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (delay < 0) delay = 0; 0 6 6
711 6 ev_timer_init(&self->reconnect_timer, reconnect_timer_cb, delay, 0.0);
712 6 self->reconnect_timer.data = (void *)self;
713 6 ev_timer_start(self->loop, &self->reconnect_timer);
714 6 self->reconnect_timer_active = 1;
715 }
716  
717 104 static void stop_connect_timer(ev_gm_t *self) {
718 104 ▶ if (self->connect_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_timer_active) { 0 104 104
719 0 ev_timer_stop(self->loop, &self->connect_timer);
720 0 self->connect_timer_active = 0;
721 }
722 104 }
723  
724 36 static void stop_reconnect_timer(ev_gm_t *self) {
725 36 ▶ if (self->reconnect_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reconnect_timer_active) { 1 35 36
726 1 ev_timer_stop(self->loop, &self->reconnect_timer);
727 1 self->reconnect_timer_active = 0;
728 }
729 36 }
730  
731 /* The command timeout is per-request: the request at the head of
732 cb_queue must be answered within command_timeout_ms of its sent_at
733 stamp, regardless of how much unrelated traffic flows meanwhile.
734 Arm a one-shot timer for the current head's remaining budget;
735 callers re-arm whenever the head changes (pop) or the queue empties
736 (disarm via the empty-check here). */
737 26 static void arm_cmd_timer(ev_gm_t *self) {
738 26 ▶ if (self->cmd_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->cmd_timer_active) { 0 26 26
739 0 ev_timer_stop(self->loop, &self->cmd_timer);
740 0 self->cmd_timer_active = 0;
741 }
742 26 ▶ if (self->command_timeout_ms <= 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->command_timeout_ms <= 0) return; 23 3 26
743 3 ▶ if (!self->connected) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return; 0 3 3
744 3 ▶ if (ngx_queue_empty(&self->cb_queue)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) return; 0 3 3
745 3 ev_gm_req_t *head = ngx_queue_data(ngx_queue_head(&self->cb_queue),
746 ev_gm_req_t, queue);
747 3 ev_tstamp budget = (ev_tstamp)self->command_timeout_ms / 1000.0;
748 3 ev_tstamp remaining = head->sent_at + budget - ev_now(self->loop);
749 3 ▶ if (remaining < 0) remaining = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (remaining < 0) remaining = 0; 0 3 3
750 3 ev_timer_init(&self->cmd_timer, cmd_timeout_cb, remaining, 0.0);
751 3 self->cmd_timer.data = (void *)self;
752 3 ev_timer_start(self->loop, &self->cmd_timer);
753 3 self->cmd_timer_active = 1;
754 }
755  
756 93 static void disarm_cmd_timer(ev_gm_t *self) {
757 93 ▶ if (self->cmd_timer_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->cmd_timer_active) { 1 92 93
758 1 ev_timer_stop(self->loop, &self->cmd_timer);
759 1 self->cmd_timer_active = 0;
760 }
761 93 }
762  
763 2 static void cmd_timeout_cb(EV_P_ ev_timer *w, int revents) {
764 dTHX;
765 2 ev_gm_t *self = (ev_gm_t *)w->data;
766 (void)loop; (void)revents;
767 2 ▶ if (self->magic != GM_MAGIC_ALIVE) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_ALIVE) return; 0 2 2
768 2 self->cmd_timer_active = 0; /* one-shot: already fired */
769 2 ▶ if (ngx_queue_empty(&self->cb_queue)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) return; 0 2 2
770 /* The head may have changed since this timer was armed (every arm
771 is for the then-head's budget); a current head still within
772 budget gets a re-arm for its remainder, not a disconnect. */
773 2 ev_gm_req_t *head = ngx_queue_data(ngx_queue_head(&self->cb_queue),
774 ev_gm_req_t, queue);
775 2 ev_tstamp budget = (ev_tstamp)self->command_timeout_ms / 1000.0;
776 2 ▶ if (ev_now(self->loop) - head->sent_at < budget) {
Branch: 1 branch
BranchTrueFalseTotal
if (ev_now(self->loop) - head->sent_at < budget) { 0 2 2
777 0 arm_cmd_timer(self);
778 0 return;
779 }
780 2 self->callback_depth++;
781 2 handle_disconnect(aTHX_ self, "command timeout");
782 2 self->callback_depth--;
783 2 check_destroyed(self);
784 }
785  
786 0 static void connect_timeout_cb(EV_P_ ev_timer *w, int revents) {
787 dTHX;
788 0 ev_gm_t *self = (ev_gm_t *)w->data;
789 (void)loop; (void)revents;
790 0 ▶ if (self->magic != GM_MAGIC_ALIVE) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_ALIVE) return; 0 0 0
791 0 self->connect_timer_active = 0;
792 0 self->callback_depth++;
793 0 handle_disconnect(aTHX_ self, "connect timeout");
794 0 self->callback_depth--;
795 0 check_destroyed(self);
796 }
797  
798 5 static void reconnect_timer_cb(EV_P_ ev_timer *w, int revents) {
799 dTHX;
800 5 ev_gm_t *self = (ev_gm_t *)w->data;
801 (void)loop; (void)revents;
802 5 ▶ if (self->magic != GM_MAGIC_ALIVE) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_ALIVE) return; 0 5 5
803 5 self->reconnect_timer_active = 0;
804 5 self->callback_depth++;
805 5 start_connect(aTHX_ self);
806 5 self->callback_depth--;
807 5 check_destroyed(self);
808 }
809  
810 /* ================================================================
811 * Packet build/send
812 * ================================================================ */
813  
814 /* Pack a binary packet into a fresh buffer. Caller frees with Safefree. */
815 41 static char* gm_pack(uint32_t cmd, const char *data, size_t data_len, size_t *out_len) {
816 41 size_t total = GM_HEADER_SIZE + data_len;
817 char *p;
818 41 Newx(p, total, char);
819 41 memcpy(p, GM_MAGIC_REQ, 4);
820 41 gm_write_u32(p + 4, cmd);
821 41 gm_write_u32(p + 8, (uint32_t)data_len);
822 41 ▶ if (data_len > 0) memcpy(p + 12, data, data_len);
Branch: 1 branch
BranchTrueFalseTotal
if (data_len > 0) memcpy(p + 12, data, data_len); 24 17 41
823 41 *out_len = total;
824 41 return p;
825 }
826  
827 /* Hand `pkt` (heap-allocated, plen bytes) to the write path. If
828 * already connected, append to the write buffer and Safefree pkt;
829 * otherwise transfer ownership to a new wait entry. If req is
830 * non-NULL its ownership transfers too, into cb_queue or the wait
831 * entry respectively. */
832 42 static void submit_bytes(pTHX_ ev_gm_t *self,
833 char *pkt, size_t plen, ev_gm_req_t *req)
834 {
835 42 ▶ if (self->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connected) { 40 2 42
836 40 buf_append_write(self, pkt, plen);
837 40 Safefree(pkt);
838 40 ▶ if (req) {
Branch: 1 branch
BranchTrueFalseTotal
if (req) { 23 17 40
839 23 req->sent_at = ev_now(self->loop);
840 23 ngx_queue_insert_tail(&self->cb_queue, &req->queue);
841 23 self->pending_count++;
842 23 arm_cmd_timer(self);
843 }
844 40 start_writing(self);
845 } else {
846 ev_gm_wait_t *w;
847 2 Newxz(w, 1, ev_gm_wait_t);
848 2 w->packet = pkt;
849 2 w->packet_len = plen;
850 2 w->req = req;
851 2 ngx_queue_insert_tail(&self->wait_queue, &w->queue);
852 2 self->waiting_count++;
853 }
854 42 }
855  
856 41 static void enqueue_packet(pTHX_ ev_gm_t *self,
857 uint32_t cmd, const char *data, size_t data_len, ev_gm_req_t *req)
858 {
859 size_t plen;
860 41 char *pkt = gm_pack(cmd, data, data_len, &plen);
861 41 submit_bytes(aTHX_ self, pkt, plen, req);
862 41 }
863  
864 /* The wire length field is 32-bit and the peer caps reads at
865 GM_MAX_PACKET; reject anything larger before it would truncate and
866 desync the protocol. Callers validate at the point of entry (before
867 allocating request state) so a croak here never leaks. */
868 14 static void gm_check_size(pTHX_ size_t len) {
869 14 ▶ if (len > GM_MAX_PACKET)
Branch: 1 branch
BranchTrueFalseTotal
if (len > GM_MAX_PACKET) 2 12 14
870 2 croak("EV::Gearman: payload too large (%zu bytes, max %u)",
871 len, (unsigned)GM_MAX_PACKET);
872 12 }
873  
874 23 static void send_pending_waits(pTHX_ ev_gm_t *self) {
875 25 ▶ while (!ngx_queue_empty(&self->wait_queue) && self->connected) {
Branch: 2 branches
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->wait_queue) && self->connected) { 2 23 25
while (!ngx_queue_empty(&self->wait_queue) && self->connected) { 2 0 2
876 2 ngx_queue_t *q = ngx_queue_head(&self->wait_queue);
877 2 ev_gm_wait_t *w = ngx_queue_data(q, ev_gm_wait_t, queue);
878 2 ngx_queue_remove(q);
879 2 self->waiting_count--;
880  
881 2 buf_append_write(self, w->packet, w->packet_len);
882  
883 2 ▶ if (w->req) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->req) { 2 0 2
884 2 w->req->sent_at = ev_now(self->loop);
885 2 ngx_queue_insert_tail(&self->cb_queue, &w->req->queue);
886 2 self->pending_count++;
887 2 w->req = NULL;
888 2 arm_cmd_timer(self);
889 }
890  
891 2 Safefree(w->packet); w->packet = NULL;
892 2 Safefree(w);
893  
894 2 start_writing(self);
895 }
896 23 }
897  
898 /* ================================================================
899 * Worker helpers (state machine for GRAB / NOOP / PRE_SLEEP)
900 * ================================================================ */
901  
902 10 static ev_gm_func_t* find_function(ev_gm_t *self, const char *name, STRLEN len) {
903 ngx_queue_t *q;
904 13 ▶ for (q = ngx_queue_head(&self->functions); q != ngx_queue_sentinel(&self->functions);
Branch: 1 branch
BranchTrueFalseTotal
for (q = ngx_queue_head(&self->functions); q != ngx_queue_sentinel(&self->functions); 7 6 13
905 3 q = ngx_queue_next(q))
906 {
907 7 ev_gm_func_t *f = ngx_queue_data(q, ev_gm_func_t, queue);
908 7 ▶ if (strlen(f->name) == len && memcmp(f->name, name, len) == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (strlen(f->name) == len && memcmp(f->name, name, len) == 0) 7 0 7
if (strlen(f->name) == len && memcmp(f->name, name, len) == 0) 4 3 7
909 4 return f;
910 }
911 6 return NULL;
912 }
913  
914 12 static void worker_send_grab(pTHX_ ev_gm_t *self) {
915 12 ▶ if (!self->connected) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return; 0 12 12
916 12 ▶ if (self->worker_grab_inflight) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->worker_grab_inflight) return; 0 12 12
917 12 ▶ if (ngx_queue_empty(&self->functions)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->functions)) return; 0 12 12
918 12 self->worker_grab_inflight = 1;
919 12 ev_gm_req_t *r = alloc_req(CB_GRAB_JOB, NULL);
920 12 enqueue_packet(aTHX_ self,
921 12 ▶ self->worker_grab_uniq ? GM_CMD_GRAB_JOB_UNIQ : GM_CMD_GRAB_JOB,
Branch: 1 branch
BranchTrueFalseTotal
self->worker_grab_uniq ? GM_CMD_GRAB_JOB_UNIQ : GM_CMD_GRAB_JOB, 0 12 12
922 NULL, 0, r);
923 }
924  
925 5 static void worker_send_pre_sleep(pTHX_ ev_gm_t *self) {
926 5 ▶ if (!self->connected) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return; 0 5 5
927 5 ▶ if (self->worker_sleeping) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->worker_sleeping) return; 0 5 5
928 5 self->worker_sleeping = 1;
929 5 enqueue_packet(aTHX_ self, GM_CMD_PRE_SLEEP, NULL, 0, NULL);
930 }
931  
932 /* Drive the worker loop forward: if active and not busy, GRAB. */
933 41 static void worker_continue(pTHX_ ev_gm_t *self) {
934 41 ▶ if (!self->worker_active || !self->connected) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!self->worker_active || !self->connected) return; 16 25 41
if (!self->worker_active || !self->connected) return; 4 12 16
935 12 ▶ if (self->worker_grab_inflight || self->worker_sleeping) return;
Branch: 2 branches
BranchTrueFalseTotal
if (self->worker_grab_inflight || self->worker_sleeping) return; 12 0 12
if (self->worker_grab_inflight || self->worker_sleeping) return; 0 12 12
936 12 ▶ if (ngx_queue_empty(&self->functions)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->functions)) return; 0 12 12
937 12 worker_send_grab(aTHX_ self);
938 }
939  
940 /* ================================================================
941 * Connect-success path: re-register worker functions, drain queue
942 * ================================================================ */
943  
944 /* Send a WORK_* packet whose body is "handle" + optional "\0data".
945 For WORK_FAIL pass dp=NULL; otherwise pass payload bytes. */
946 5 static void send_work_event(pTHX_ ev_gm_t *self, uint32_t cmd,
947 const char *h, STRLEN hl, const char *dp, STRLEN dl)
948 {
949 /* No size croak here: this runs on the worker completion / event
950 path (worker_dispatch_job, $job->complete), where a longjmp would
951 unwind the EV loop mid-iteration. A >4 GiB result is not a real
952 concern (the worker would OOM building it first). */
953 5 ▶ size_t plen = dp ? hl + 1 + dl : hl;
Branch: 1 branch
BranchTrueFalseTotal
size_t plen = dp ? hl + 1 + dl : hl; 5 0 5
954 char *body;
955 5 ▶ Newx(body, plen ? plen : 1, char);
Branch: 1 branch
BranchTrueFalseTotal
Newx(body, plen ? plen : 1, char); 5 0 5
956 5 memcpy(body, h, hl);
957 5 ▶ if (dp) {
Branch: 1 branch
BranchTrueFalseTotal
if (dp) { 5 0 5
958 5 body[hl] = '\0';
959 5 ▶ if (dl) memcpy(body + hl + 1, dp, dl);
Branch: 1 branch
BranchTrueFalseTotal
if (dl) memcpy(body + hl + 1, dp, dl); 5 0 5
960 }
961 5 enqueue_packet(aTHX_ self, cmd, body, plen, NULL);
962 5 Safefree(body);
963 5 }
964  
965 /* Send CAN_DO[_TIMEOUT] for one function name. Builds the
966 "name\0timeout" body on the heap to avoid the 512-byte stack-buffer
967 truncation that the older inline pattern was prone to. */
968 11 static void send_can_do(pTHX_ ev_gm_t *self,
969 const char *name, STRLEN nlen, int timeout)
970 {
971 11 ▶ if (!self->connected) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return; 4 7 11
972 7 ▶ if (timeout > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (timeout > 0) { 0 7 7
973 char tbuf[16];
974 0 int tlen = snprintf(tbuf, sizeof(tbuf), "%d", timeout);
975 0 ▶ if (tlen <= 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (tlen <= 0) return; 0 0 0
976 0 size_t plen = nlen + 1 + (size_t)tlen;
977 char *body;
978 0 Newx(body, plen, char);
979 0 memcpy(body, name, nlen);
980 0 body[nlen] = '\0';
981 0 memcpy(body + nlen + 1, tbuf, tlen);
982 0 enqueue_packet(aTHX_ self, GM_CMD_CAN_DO_TIMEOUT, body, plen, NULL);
983 0 Safefree(body);
984 } else {
985 7 enqueue_packet(aTHX_ self, GM_CMD_CAN_DO, name, nlen, NULL);
986 }
987 }
988  
989 23 static void register_all_functions(pTHX_ ev_gm_t *self) {
990 23 ▶ if (!self->connected) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return; 0 23 23
991 ngx_queue_t *q;
992 28 ▶ for (q = ngx_queue_head(&self->functions); q != ngx_queue_sentinel(&self->functions);
Branch: 1 branch
BranchTrueFalseTotal
for (q = ngx_queue_head(&self->functions); q != ngx_queue_sentinel(&self->functions); 5 23 28
993 5 q = ngx_queue_next(q))
994 {
995 5 ev_gm_func_t *f = ngx_queue_data(q, ev_gm_func_t, queue);
996 5 send_can_do(aTHX_ self, f->name, strlen(f->name), f->timeout);
997 }
998 }
999  
1000 23 static void send_options_and_id(pTHX_ ev_gm_t *self) {
1001 23 ▶ if (self->client_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->client_id) { 0 23 23
1002 0 enqueue_packet(aTHX_ self, GM_CMD_SET_CLIENT_ID,
1003 0 self->client_id, strlen(self->client_id), NULL);
1004 }
1005 23 ▶ if (self->opt_exceptions) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->opt_exceptions) { 0 23 23
1006 0 const char *opt = "exceptions";
1007 0 ev_gm_req_t *r = alloc_req(CB_OPTION, NULL);
1008 0 enqueue_packet(aTHX_ self, GM_CMD_OPTION_REQ, opt, strlen(opt), r);
1009 }
1010 23 }
1011  
1012 7 static void report_connect_error(pTHX_ ev_gm_t *self, const char *errbuf) {
1013 7 self->callback_depth++;
1014 7 emit_error(aTHX_ self, errbuf);
1015 7 self->callback_depth--;
1016 7 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 7 7
1017 7 ▶ if (!self->intentional_disconnect && self->reconnect)
Branch: 2 branches
BranchTrueFalseTotal
if (!self->intentional_disconnect && self->reconnect) 7 0 7
if (!self->intentional_disconnect && self->reconnect) 5 2 7
1018 5 schedule_reconnect(aTHX_ self);
1019 }
1020  
1021 23 static void finish_connect_success(pTHX_ ev_gm_t *self) {
1022 23 self->reconnect_attempts = 0;
1023  
1024 23 start_reading(self);
1025 23 apply_keepalive(self);
1026  
1027 23 send_options_and_id(aTHX_ self);
1028 23 register_all_functions(aTHX_ self);
1029  
1030 23 emit_connect(aTHX_ self);
1031 23 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 23 23
1032  
1033 23 send_pending_waits(aTHX_ self);
1034 23 ▶ if (check_destroyed(self)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return; 0 23 23
1035  
1036 23 worker_continue(aTHX_ self);
1037 }
1038  
1039 /* ================================================================
1040 * Response routing
1041 * ================================================================ */
1042  
1043 /* Return pointer to first byte of the i-th NUL-separated argument
1044 * (zero-indexed) and its length in *out_len. Returns NULL if not
1045 * present. The final argument is whatever remains after the last
1046 * NUL — it may itself contain NUL bytes for binary data. */
1047 18 static const char* gm_arg(const char *body, size_t body_len, int idx,
1048 int total, size_t *out_len)
1049 {
1050 /* Walk through, splitting by NUL. The (total-1) NULs separate
1051 total fields; the final field has no trailing NUL. */
1052 18 const char *p = body;
1053 18 const char *end = body + body_len;
1054 18 int cur = 0;
1055 33 ▶ while (cur < idx) {
Branch: 1 branch
BranchTrueFalseTotal
while (cur < idx) { 15 18 33
1056 15 const char *nul = memchr(p, '\0', end - p);
1057 15 ▶ if (!nul) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!nul) return NULL; 0 15 15
1058 15 p = nul + 1;
1059 15 cur++;
1060 }
1061 /* p is start of arg `idx`; find its length */
1062 18 ▶ if (idx == total - 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (idx == total - 1) { 7 11 18
1063 /* Last arg runs to end */
1064 7 *out_len = end - p;
1065 } else {
1066 11 const char *nul = memchr(p, '\0', end - p);
1067 11 ▶ if (!nul) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!nul) return NULL; 0 11 11
1068 11 *out_len = nul - p;
1069 }
1070 18 return p;
1071 }
1072  
1073 0 static ev_gm_active_t* find_active_by_handle(ev_gm_t *self,
1074 const char *handle, STRLEN handle_len)
1075 {
1076 ngx_queue_t *q;
1077 0 ▶ for (q = ngx_queue_head(&self->active_jobs); q != ngx_queue_sentinel(&self->active_jobs);
Branch: 1 branch
BranchTrueFalseTotal
for (q = ngx_queue_head(&self->active_jobs); q != ngx_queue_sentinel(&self->active_jobs); 0 0 0
1078 0 q = ngx_queue_next(q))
1079 {
1080 0 ev_gm_active_t *a = ngx_queue_data(q, ev_gm_active_t, queue);
1081 0 ▶ if (a->handle_len == handle_len &&
Branch: 1 branch
BranchTrueFalseTotal
if (a->handle_len == handle_len && 0 0 0
1082 0 ▶ memcmp(a->handle, handle, handle_len) == 0)
Branch: 1 branch
BranchTrueFalseTotal
memcmp(a->handle, handle, handle_len) == 0) 0 0 0
1083 0 return a;
1084 }
1085 0 return NULL;
1086 }
1087  
1088 /* Pop the head request entry; returns NULL if queue empty. Popping
1089 advances the head, so the per-request command timer is re-armed for
1090 the new head's budget (or disarmed when nothing remains). */
1091 16 static ev_gm_req_t* pop_req(ev_gm_t *self) {
1092 16 ▶ if (ngx_queue_empty(&self->cb_queue)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) return NULL; 0 16 16
1093 16 ngx_queue_t *q = ngx_queue_head(&self->cb_queue);
1094 16 ev_gm_req_t *r = ngx_queue_data(q, ev_gm_req_t, queue);
1095 16 ngx_queue_remove(q);
1096 16 self->pending_count--;
1097 16 ▶ if (ngx_queue_empty(&self->cb_queue)) disarm_cmd_timer(self);
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) disarm_cmd_timer(self); 15 1 16
1098 1 else arm_cmd_timer(self);
1099 16 return r;
1100 }
1101  
1102 /* ---- Response/request pairing -------------------------------------
1103 * gearmand answers the request/response commands synchronously in
1104 * wire order, so a reply whose command cannot answer the head request
1105 * means a broken or hostile peer — or a FIFO already desynced. With no
1106 * request-ids in the protocol there is no resynchronization primitive;
1107 * continuing would deliver (possibly attacker-chosen) data to the
1108 * wrong callback, so a mismatch tears the connection down. NOOP and
1109 * ERROR are excepted: a correct gearmand may emit both asynchronously.
1110 */
1111  
1112 4 static const char* gm_cmd_name(uint32_t cmd) {
1113 4 switch (cmd) {
1114 1 case GM_CMD_JOB_CREATED: return "JOB_CREATED";
1115 0 case GM_CMD_NO_JOB: return "NO_JOB";
1116 0 case GM_CMD_JOB_ASSIGN: return "JOB_ASSIGN";
1117 0 case GM_CMD_WORK_STATUS: return "WORK_STATUS";
1118 0 case GM_CMD_WORK_COMPLETE: return "WORK_COMPLETE";
1119 0 case GM_CMD_WORK_FAIL: return "WORK_FAIL";
1120 3 case GM_CMD_ECHO_RES: return "ECHO_RES";
1121 0 case GM_CMD_ERROR: return "ERROR";
1122 0 case GM_CMD_STATUS_RES: return "STATUS_RES";
1123 0 case GM_CMD_ALL_YOURS: return "ALL_YOURS";
1124 0 case GM_CMD_WORK_EXCEPTION: return "WORK_EXCEPTION";
1125 0 case GM_CMD_OPTION_RES: return "OPTION_RES";
1126 0 case GM_CMD_WORK_DATA: return "WORK_DATA";
1127 0 case GM_CMD_WORK_WARNING: return "WORK_WARNING";
1128 0 case GM_CMD_JOB_ASSIGN_UNIQ: return "JOB_ASSIGN_UNIQ";
1129 0 case GM_CMD_STATUS_RES_UNIQUE: return "STATUS_RES_UNIQUE";
1130 0 case GM_CMD_NOOP: return "NOOP";
1131 0 default: return "UNKNOWN_CMD";
1132 }
1133 }
1134  
1135 4 static const char* gm_kind_name(int kind) {
1136 4 switch (kind) {
1137 1 case CB_ECHO: return "ECHO";
1138 2 case CB_SUBMIT: return "SUBMIT";
1139 0 case CB_SUBMIT_BG: return "SUBMIT_BG";
1140 0 case CB_GET_STATUS: return "GET_STATUS";
1141 0 case CB_GET_STATUS_UNIQ: return "GET_STATUS_UNIQUE";
1142 0 case CB_OPTION: return "OPTION";
1143 1 case CB_GRAB_JOB: return "GRAB_JOB";
1144 0 case CB_ADMIN: return "ADMIN";
1145 0 default: return "UNKNOWN_KIND";
1146 }
1147 }
1148  
1149 #define GM_KIND_MASK(k) (1u << ((k) - 1)) /* CB_* are 1..8 */
1150  
1151 /* Pop the head request iff its kind can legitimately be answered by
1152 `cmd`. Empty queue: return NULL (caller decides tolerance). Kind
1153 mismatch: the FIFO is desynced — tear the connection down with a
1154 protocol error and return NULL. Callers must then touch nothing
1155 further on self; process_responses re-checks magic/connected after
1156 every arm. */
1157 19 static ev_gm_req_t* pop_req_expect(pTHX_ ev_gm_t *self, uint32_t cmd,
1158 unsigned kind_mask)
1159 {
1160 19 ▶ if (ngx_queue_empty(&self->cb_queue)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) return NULL; 0 19 19
1161 19 ev_gm_req_t *head = ngx_queue_data(ngx_queue_head(&self->cb_queue),
1162 ev_gm_req_t, queue);
1163 19 ▶ if (!(kind_mask & GM_KIND_MASK(head->kind))) {
Branch: 1 branch
BranchTrueFalseTotal
if (!(kind_mask & GM_KIND_MASK(head->kind))) { 4 15 19
1164 char msg[128];
1165 4 snprintf(msg, sizeof(msg),
1166 "protocol desync: %s cannot answer %s request",
1167 gm_cmd_name(cmd), gm_kind_name(head->kind));
1168 4 handle_disconnect(aTHX_ self, msg);
1169 4 return NULL;
1170 }
1171 15 return pop_req(self);
1172 }
1173  
1174 /* Forward declare so handle_response_packet can call into worker job dispatch */
1175 static void worker_dispatch_job(pTHX_ ev_gm_t *self, ev_gm_req_t *r,
1176 int with_unique, const char *body, size_t body_len);
1177  
1178 /* Release the tombstone reference a job holds on its client. Runs
1179 exactly once when the job HV is freed (magic lives on the referent,
1180 not the RV, so re-blessing cannot shake it and Perl code cannot
1181 remove it). The struct is still allocated here by the job_refs
1182 invariant: freed only when refs hit 0. */
1183 4 static int ev_gm_job_magic_free(pTHX_ SV *sv, MAGIC *mg) {
1184 4 ev_gm_t *self = (ev_gm_t *)mg->mg_ptr;
1185 (void)sv;
1186 4 mg->mg_ptr = NULL;
1187 4 ▶ if (self) {
Branch: 1 branch
BranchTrueFalseTotal
if (self) { 4 0 4
1188 4 ▶ if (self->job_refs > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->job_refs > 0) 4 0 4
1189 4 self->job_refs--;
1190 4 (void)check_destroyed(self);
1191 }
1192 4 return 0;
1193 }
1194  
1195 static const MGVTBL ev_gm_job_magic_vtbl = {
1196 NULL, NULL, NULL, NULL, ev_gm_job_magic_free /* svt_free only */
1197 };
1198  
1199 /* Validate a job hashref and return its (live) client + handle bytes.
1200 * Croaks with op-prefixed messages on any inconsistency. The client
1201 * pointer arrives as PERL_MAGIC_ext on the job HV (attached by
1202 * worker_dispatch_job), not as a hash key: unforgeable and
1203 * un-clobberable from Perl, and the job_refs tombstone count keeps the
1204 * struct allocated so the magic-word check below never reads freed
1205 * memory. */
1206 3 static ev_gm_t* job_resolve(pTHX_ SV *job_sv, const char **h, STRLEN *hl,
1207 const char *op)
1208 {
1209 3 ▶ if (!SvROK(job_sv)) croak("%s: invalid job", op);
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(job_sv)) croak("%s: invalid job", op); 0 3 3
1210 3 SV *ref = SvRV(job_sv);
1211 3 ▶ if (SvTYPE(ref) != SVt_PVHV)
Branch: 1 branch
BranchTrueFalseTotal
if (SvTYPE(ref) != SVt_PVHV) 0 3 3
1212 0 croak("%s: stale job (not a job hash)", op);
1213 3 MAGIC *mg = mg_findext(ref, PERL_MAGIC_ext, &ev_gm_job_magic_vtbl);
1214 3 ▶ if (!mg || !mg->mg_ptr)
Branch: 2 branches
BranchTrueFalseTotal
if (!mg || !mg->mg_ptr) 3 0 3
if (!mg || !mg->mg_ptr) 0 3 3
1215 0 croak("%s: stale job (no client pointer)", op);
1216 3 SV **handle_sv = hv_fetchs((HV *)ref, "handle", 0);
1217 3 ▶ if (!handle_sv) croak("%s: missing handle", op);
Branch: 1 branch
BranchTrueFalseTotal
if (!handle_sv) croak("%s: missing handle", op); 0 3 3
1218 3 ev_gm_t *self = (ev_gm_t *)mg->mg_ptr;
1219 3 ▶ if (self->magic != GM_MAGIC_ALIVE)
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_ALIVE) 0 3 3
1220 0 croak("%s: client destroyed", op);
1221 /* A live-but-disconnected client would silently queue this WORK_*
1222 packet into the pre-connect wait queue and flush it after a
1223 reconnect — where gearmand, which forgot the job at the drop,
1224 answers JOB_NOT_FOUND. Croak instead: the job is already dead
1225 server-side, so queuing can only produce that error. */
1226 3 ▶ if (!self->connected)
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) 0 3 3
1227 0 croak("%s: not connected", op);
1228 3 *h = SvPV(*handle_sv, *hl);
1229 3 return self;
1230 }
1231  
1232 30 static void handle_response_packet(pTHX_ ev_gm_t *self,
1233 uint32_t cmd, const char *body, size_t body_len)
1234 {
1235 30 switch (cmd) {
1236  
1237 7 case GM_CMD_ECHO_RES: {
1238 7 ev_gm_req_t *r = pop_req_expect(aTHX_ self, cmd,
1239 GM_KIND_MASK(CB_ECHO));
1240 7 ▶ if (!r) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return; 3 4 7
1241 4 ▶ if (r->cb)
Branch: 1 branch
BranchTrueFalseTotal
if (r->cb) 4 0 4
1242 4 invoke_cb2(aTHX_ self, r->cb, newSVpvn(body, body_len), NULL);
1243 4 cleanup_req(aTHX_ r);
1244 4 break;
1245 }
1246  
1247 3 case GM_CMD_JOB_CREATED: {
1248 /* Only a SUBMIT request may sit at the head; anything else is
1249 a desync (pop_req_expect disconnects). The old silent-free
1250 else branch is gone: it dropped the user's callback without
1251 an error, and with pending_count at 0 not even the command
1252 timer could fire — a permanent silent hang. */
1253 3 ev_gm_req_t *r = pop_req_expect(aTHX_ self, cmd,
1254 GM_KIND_MASK(CB_SUBMIT) | GM_KIND_MASK(CB_SUBMIT_BG));
1255 3 ▶ if (!r) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return; 1 2 3
1256 2 SV *handle_sv = newSVpvn(body, body_len);
1257 2 ▶ if (r->kind == CB_SUBMIT_BG) {
Branch: 1 branch
BranchTrueFalseTotal
if (r->kind == CB_SUBMIT_BG) { 2 0 2
1258 2 ▶ if (r->cb)
Branch: 1 branch
BranchTrueFalseTotal
if (r->cb) 2 0 2
1259 2 invoke_cb2(aTHX_ self, r->cb, handle_sv, NULL);
1260 else
1261 0 SvREFCNT_dec(handle_sv);
1262 2 cleanup_req(aTHX_ r);
1263 } else {
1264 /* Foreground: register active job, transfer callback bundle */
1265 ev_gm_active_t *a;
1266 0 Newxz(a, 1, ev_gm_active_t);
1267 0 Newx(a->handle, body_len, char);
1268 0 memcpy(a->handle, body, body_len);
1269 0 a->handle_len = body_len;
1270 0 a->on_complete = r->cb; r->cb = NULL;
1271 0 a->on_data = r->on_data; r->on_data = NULL;
1272 0 a->on_warning = r->on_warning; r->on_warning = NULL;
1273 0 a->on_status = r->on_status; r->on_status = NULL;
1274 0 a->on_exception = r->on_exception;r->on_exception = NULL;
1275 0 ngx_queue_insert_tail(&self->active_jobs, &a->queue);
1276 0 self->active_count_cached++;
1277 0 cleanup_req(aTHX_ r);
1278 0 SvREFCNT_dec(handle_sv);
1279 }
1280 2 break;
1281 }
1282  
1283 0 case GM_CMD_WORK_COMPLETE: {
1284 size_t hl, dl;
1285 0 const char *h = gm_arg(body, body_len, 0, 2, &hl);
1286 0 const char *d = gm_arg(body, body_len, 1, 2, &dl);
1287 0 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 0 0
1288 0 ev_gm_active_t *a = find_active_by_handle(self, h, hl);
1289 0 ▶ if (!a) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!a) return; 0 0 0
1290 0 ngx_queue_remove(&a->queue);
1291 0 self->active_count_cached--;
1292 0 ▶ if (a->on_complete)
Branch: 1 branch
BranchTrueFalseTotal
if (a->on_complete) 0 0 0
1293 0 ▶ invoke_cb2(aTHX_ self, a->on_complete,
Branch: 1 branch
BranchTrueFalseTotal
invoke_cb2(aTHX_ self, a->on_complete, 0 0 0
1294 0 d ? newSVpvn(d, dl) : newSVpvs(""), NULL);
1295 0 cleanup_active(aTHX_ a);
1296 0 break;
1297 }
1298  
1299 0 case GM_CMD_WORK_FAIL: {
1300 0 ev_gm_active_t *a = find_active_by_handle(self, body, body_len);
1301 0 ▶ if (!a) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!a) return; 0 0 0
1302 0 ngx_queue_remove(&a->queue);
1303 0 self->active_count_cached--;
1304 0 ▶ if (a->on_complete)
Branch: 1 branch
BranchTrueFalseTotal
if (a->on_complete) 0 0 0
1305 0 invoke_cb2(aTHX_ self, a->on_complete, NULL, newSVpvs("job failed"));
1306 0 cleanup_active(aTHX_ a);
1307 0 break;
1308 }
1309  
1310 0 case GM_CMD_WORK_DATA:
1311 case GM_CMD_WORK_WARNING: {
1312 size_t hl, dl;
1313 0 const char *h = gm_arg(body, body_len, 0, 2, &hl);
1314 0 const char *d = gm_arg(body, body_len, 1, 2, &dl);
1315 0 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 0 0
1316 0 ev_gm_active_t *a = find_active_by_handle(self, h, hl);
1317 0 ▶ if (!a) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!a) return; 0 0 0
1318 0 ▶ SV *cb = (cmd == GM_CMD_WORK_DATA) ? a->on_data : a->on_warning;
Branch: 1 branch
BranchTrueFalseTotal
SV *cb = (cmd == GM_CMD_WORK_DATA) ? a->on_data : a->on_warning; 0 0 0
1319 0 ▶ if (cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (cb) { 0 0 0
1320 0 ▶ SV *arg = d ? newSVpvn(d, dl) : newSVpvn("", 0);
Branch: 1 branch
BranchTrueFalseTotal
SV *arg = d ? newSVpvn(d, dl) : newSVpvn("", 0); 0 0 0
1321 0 invoke_handler(aTHX_ self, cb, arg, "on_data/on_warning");
1322 }
1323 0 break;
1324 }
1325  
1326 0 case GM_CMD_WORK_EXCEPTION: {
1327 /* gearmand calls fail() on the job after forwarding the
1328 exception data and does NOT emit a follow-up WORK_FAIL,
1329 so this packet is the terminal event for the active job:
1330 fire on_exception (informational) then on_complete with
1331 an "exception" error so the caller's terminal callback
1332 always runs. */
1333 size_t hl, dl;
1334 0 const char *h = gm_arg(body, body_len, 0, 2, &hl);
1335 0 const char *d = gm_arg(body, body_len, 1, 2, &dl);
1336 0 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 0 0
1337 0 ev_gm_active_t *a = find_active_by_handle(self, h, hl);
1338 0 ▶ if (!a) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!a) return; 0 0 0
1339 0 ngx_queue_remove(&a->queue);
1340 0 self->active_count_cached--;
1341 0 ▶ if (a->on_exception) {
Branch: 1 branch
BranchTrueFalseTotal
if (a->on_exception) { 0 0 0
1342 0 ▶ SV *arg = d ? newSVpvn(d, dl) : newSVpvs("");
Branch: 1 branch
BranchTrueFalseTotal
SV *arg = d ? newSVpvn(d, dl) : newSVpvs(""); 0 0 0
1343 0 invoke_handler(aTHX_ self, a->on_exception, arg, "on_exception");
1344 }
1345 0 ▶ if (self->magic != GM_MAGIC_FREED && a->on_complete)
Branch: 2 branches
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_FREED && a->on_complete) 0 0 0
if (self->magic != GM_MAGIC_FREED && a->on_complete) 0 0 0
1346 0 invoke_cb2(aTHX_ self, a->on_complete, NULL, newSVpvs("exception"));
1347 0 cleanup_active(aTHX_ a);
1348 0 break;
1349 }
1350  
1351 0 case GM_CMD_WORK_STATUS: {
1352 size_t hl, nl, dl;
1353 0 const char *h = gm_arg(body, body_len, 0, 3, &hl);
1354 0 const char *n = gm_arg(body, body_len, 1, 3, &nl);
1355 0 const char *d = gm_arg(body, body_len, 2, 3, &dl);
1356 0 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 0 0
1357 0 ev_gm_active_t *a = find_active_by_handle(self, h, hl);
1358 0 ▶ if (!a) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!a) return; 0 0 0
1359 0 ▶ if (a->on_status)
Branch: 1 branch
BranchTrueFalseTotal
if (a->on_status) 0 0 0
1360 0 ▶ invoke_cb2(aTHX_ self, a->on_status,
Branch: 2 branches
BranchTrueFalseTotal
invoke_cb2(aTHX_ self, a->on_status, 0 0 0
invoke_cb2(aTHX_ self, a->on_status, 0 0 0
1361 0 n ? newSVpvn(n, nl) : newSVpvs("0"),
1362 0 d ? newSVpvn(d, dl) : newSVpvs("0"));
1363 0 break;
1364 }
1365  
1366 0 case GM_CMD_STATUS_RES:
1367 case GM_CMD_STATUS_RES_UNIQUE: {
1368 /* Both arms decode HANDLE-or-UNIQUE then KNOWN, RUNNING, NUM,
1369 DENOM, with STATUS_RES_UNIQUE adding a final CLIENT_COUNT. */
1370 0 ▶ ev_gm_req_t *r = pop_req_expect(aTHX_ self, cmd,
Branch: 1 branch
BranchTrueFalseTotal
ev_gm_req_t *r = pop_req_expect(aTHX_ self, cmd, 0 0 0
1371 cmd == GM_CMD_STATUS_RES ? GM_KIND_MASK(CB_GET_STATUS)
1372 : GM_KIND_MASK(CB_GET_STATUS_UNIQ));
1373 0 ▶ if (!r) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return; 0 0 0
1374 0 ▶ if (r->cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (r->cb) { 0 0 0
1375 0 int with_count = (cmd == GM_CMD_STATUS_RES_UNIQUE);
1376 0 ▶ int total = with_count ? 6 : 5;
Branch: 1 branch
BranchTrueFalseTotal
int total = with_count ? 6 : 5; 0 0 0
1377 size_t l[6];
1378 const char *p[6];
1379 int i;
1380 0 ▶ for (i = 0; i < total; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < total; i++) 0 0 0
1381 0 p[i] = gm_arg(body, body_len, i, total, &l[i]);
1382 0 HV *hv = newHV();
1383 0 ▶ if (p[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (p[0]) { 0 0 0
1384 0 ▶ if (with_count) hv_stores(hv, "unique", newSVpvn(p[0], l[0]));
Branch: 1 branch
BranchTrueFalseTotal
if (with_count) hv_stores(hv, "unique", newSVpvn(p[0], l[0])); 0 0 0
1385 0 else hv_stores(hv, "handle", newSVpvn(p[0], l[0]));
1386 }
1387 0 ▶ if (p[1]) hv_stores(hv, "known", newSViv(gm_atoi_n(p[1], l[1])));
Branch: 1 branch
BranchTrueFalseTotal
if (p[1]) hv_stores(hv, "known", newSViv(gm_atoi_n(p[1], l[1]))); 0 0 0
1388 0 ▶ if (p[2]) hv_stores(hv, "running", newSViv(gm_atoi_n(p[2], l[2])));
Branch: 1 branch
BranchTrueFalseTotal
if (p[2]) hv_stores(hv, "running", newSViv(gm_atoi_n(p[2], l[2]))); 0 0 0
1389 0 ▶ if (p[3]) hv_stores(hv, "numerator", newSVpvn(p[3], l[3]));
Branch: 1 branch
BranchTrueFalseTotal
if (p[3]) hv_stores(hv, "numerator", newSVpvn(p[3], l[3])); 0 0 0
1390 0 ▶ if (p[4]) hv_stores(hv, "denominator", newSVpvn(p[4], l[4]));
Branch: 1 branch
BranchTrueFalseTotal
if (p[4]) hv_stores(hv, "denominator", newSVpvn(p[4], l[4])); 0 0 0
1391 0 ▶ if (with_count && p[5])
Branch: 2 branches
BranchTrueFalseTotal
if (with_count && p[5]) 0 0 0
if (with_count && p[5]) 0 0 0
1392 0 hv_stores(hv, "client_count", newSViv(gm_atoi_n(p[5], l[5])));
1393 0 invoke_cb2(aTHX_ self, r->cb, newRV_noinc((SV*)hv), NULL);
1394 }
1395 0 cleanup_req(aTHX_ r);
1396 0 break;
1397 }
1398  
1399 0 case GM_CMD_OPTION_RES: {
1400 0 ev_gm_req_t *r = pop_req_expect(aTHX_ self, cmd,
1401 GM_KIND_MASK(CB_OPTION));
1402 0 ▶ if (!r) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return; 0 0 0
1403 0 ▶ if (r->cb)
Branch: 1 branch
BranchTrueFalseTotal
if (r->cb) 0 0 0
1404 0 invoke_cb2(aTHX_ self, r->cb, newSViv(1), NULL);
1405 0 cleanup_req(aTHX_ r);
1406 0 break;
1407 }
1408  
1409 5 case GM_CMD_NO_JOB: {
1410 /* The grab round is over no matter what the queue looks like —
1411 clearing this FIRST is load-bearing: an early return with the
1412 flag stuck wedges the worker permanently (worker_continue
1413 gates on it). */
1414 5 self->worker_grab_inflight = 0;
1415 5 ev_gm_req_t *r = pop_req_expect(aTHX_ self, cmd,
1416 GM_KIND_MASK(CB_GRAB_JOB));
1417 5 ▶ if (!self->connected) return; /* desync disconnect in progress */
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return; /* desync disconnect in progress */ 0 5 5
1418 5 ▶ if (r) {
Branch: 1 branch
BranchTrueFalseTotal
if (r) { 5 0 5
1419 /* grab_job's caller registered a cb; fire it with "no job"
1420 so it knows to back off. The high-level work() loop never
1421 sets r->cb for its internal grabs, so this is a no-op
1422 there. */
1423 5 ▶ if (r->cb)
Branch: 1 branch
BranchTrueFalseTotal
if (r->cb) 0 5 5
1424 0 invoke_cb2(aTHX_ self, r->cb, NULL, newSVpvs("no job"));
1425 5 cleanup_req(aTHX_ r);
1426 5 ▶ if (self->magic == GM_MAGIC_FREED) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) return; 0 5 5
1427 }
1428 /* else: empty queue — tolerate. NO_JOB carries no information,
1429 nothing remains to misroute, and the flag is already clear. */
1430 5 ▶ if (self->worker_active) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->worker_active) { 5 0 5
1431 5 worker_send_pre_sleep(aTHX_ self);
1432 5 ▶ if (self->worker_on_idle)
Branch: 1 branch
BranchTrueFalseTotal
if (self->worker_on_idle) 4 1 5
1433 4 invoke_handler(aTHX_ self, self->worker_on_idle, NULL, "on_idle");
1434 }
1435 5 break;
1436 }
1437  
1438 4 case GM_CMD_JOB_ASSIGN:
1439 case GM_CMD_JOB_ASSIGN_UNIQ: {
1440 /* First statement, same load-bearing reason as NO_JOB. */
1441 4 self->worker_grab_inflight = 0;
1442 4 ▶ if (ngx_queue_empty(&self->cb_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) { 0 4 4
1443 /* A correct server only assigns in reply to a queued GRAB;
1444 an unsolicited assign carries real work we cannot
1445 attribute (and would strand server-side). Desync. */
1446 0 handle_disconnect(aTHX_ self,
1447 "protocol desync: unsolicited JOB_ASSIGN");
1448 0 return;
1449 }
1450 4 ev_gm_req_t *r = pop_req_expect(aTHX_ self, cmd,
1451 GM_KIND_MASK(CB_GRAB_JOB));
1452 4 ▶ if (!r) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return; 0 4 4
1453 4 worker_dispatch_job(aTHX_ self, r,
1454 cmd == GM_CMD_JOB_ASSIGN_UNIQ ? 1 : 0, body, body_len);
1455 4 cleanup_req(aTHX_ r);
1456 4 break;
1457 }
1458  
1459 8 case GM_CMD_NOOP: {
1460 8 self->worker_sleeping = 0;
1461 8 worker_continue(aTHX_ self);
1462 8 break;
1463 }
1464  
1465 3 case GM_CMD_ERROR: {
1466 /* ERRCODE\0ERR_TEXT. ERROR carries no handle, so attribution is
1467 impossible in general — and "pop whatever is at the head" is
1468 actively destructive: gearmand emits JOB_NOT_FOUND
1469 asynchronously for a WORK_* we sent (e.g. a double
1470 complete()), which on a worker arrives while the head is the
1471 in-flight GRAB_JOB; popping it wedges the worker for good.
1472 So: pop only a head kind that can actually fail this way
1473 (in-order rejection of that request — GRAB_JOB is never
1474 answered with ERROR, ADMIN expects text); anything else is
1475 surfaced at connection level with the FIFO left intact. */
1476 size_t cl, tl;
1477 3 const char *c = gm_arg(body, body_len, 0, 2, &cl);
1478 3 const char *t = gm_arg(body, body_len, 1, 2, &tl);
1479 SV *err;
1480 3 ▶ if (c && t)
Branch: 2 branches
BranchTrueFalseTotal
if (c && t) 3 0 3
if (c && t) 3 0 3
1481 3 err = newSVpvf("%.*s: %.*s", (int)cl, c, (int)tl, t);
1482 else
1483 0 err = newSVpvn(body, body_len);
1484 6 ev_gm_req_t *head = ngx_queue_empty(&self->cb_queue) ? NULL
1485 3 ▶ : ngx_queue_data(ngx_queue_head(&self->cb_queue),
Branch: 1 branch
BranchTrueFalseTotal
: ngx_queue_data(ngx_queue_head(&self->cb_queue), 2 1 3
1486 ev_gm_req_t, queue);
1487 3 ▶ if (head && head->kind != CB_GRAB_JOB && head->kind != CB_ADMIN) {
Branch: 3 branches
BranchTrueFalseTotal
if (head && head->kind != CB_GRAB_JOB && head->kind != CB_ADMIN) { 2 1 3
if (head && head->kind != CB_GRAB_JOB && head->kind != CB_ADMIN) { 1 1 2
if (head && head->kind != CB_GRAB_JOB && head->kind != CB_ADMIN) { 1 0 1
1488 1 pop_req(self);
1489 1 ▶ if (head->cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (head->cb) { 1 0 1
1490 1 invoke_cb2(aTHX_ self, head->cb, NULL, err);
1491 } else {
1492 0 emit_error(aTHX_ self, SvPV_nolen(err));
1493 0 SvREFCNT_dec(err);
1494 }
1495 1 cleanup_req(aTHX_ head);
1496 } else {
1497 2 emit_error(aTHX_ self, SvPV_nolen(err));
1498 2 SvREFCNT_dec(err);
1499 }
1500 3 break;
1501 }
1502  
1503 0 default:
1504 0 break;
1505 }
1506 }
1507  
1508 /* Dispatch a JOB_ASSIGN[_UNIQ]: invoke registered function callback,
1509 * deliver result back to server (for sync mode). Async mode keeps a
1510 * job object alive in Perl-land until user invokes complete/fail. */
1511 4 static void worker_dispatch_job(pTHX_ ev_gm_t *self, ev_gm_req_t *r,
1512 int with_unique, const char *body, size_t body_len)
1513 {
1514 4 ▶ int total = with_unique ? 4 : 3;
Branch: 1 branch
BranchTrueFalseTotal
int total = with_unique ? 4 : 3; 0 4 4
1515 size_t hl, fl, ul, wl;
1516 4 const char *h = gm_arg(body, body_len, 0, total, &hl);
1517 4 const char *f = gm_arg(body, body_len, 1, total, &fl);
1518 4 ▶ const char *u = with_unique ? gm_arg(body, body_len, 2, total, &ul) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
const char *u = with_unique ? gm_arg(body, body_len, 2, total, &ul) : NULL; 0 4 4
1519 4 ▶ const char *w = gm_arg(body, body_len, with_unique ? 3 : 2, total, &wl);
Branch: 1 branch
BranchTrueFalseTotal
const char *w = gm_arg(body, body_len, with_unique ? 3 : 2, total, &wl); 0 4 4
1520  
1521 4 ▶ if (!h || !f) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!h || !f) return; 4 0 4
if (!h || !f) return; 0 4 4
1522  
1523 /* Build a job hashref blessed into EV::Gearman::Job. */
1524 4 HV *job = newHV();
1525 4 hv_stores(job, "handle", newSVpvn(h, hl));
1526 4 hv_stores(job, "function", newSVpvn(f, fl));
1527 4 ▶ hv_stores(job, "unique", u ? newSVpvn(u, ul) : newSVpvn("", 0));
Branch: 1 branch
BranchTrueFalseTotal
hv_stores(job, "unique", u ? newSVpvn(u, ul) : newSVpvn("", 0)); 0 4 4
1528 4 ▶ hv_stores(job, "workload", w ? newSVpvn(w, wl) : newSVpvn("", 0));
Branch: 1 branch
BranchTrueFalseTotal
hv_stores(job, "workload", w ? newSVpvn(w, wl) : newSVpvn("", 0)); 4 0 4
1529 /* Tombstone reference on the client, carried as PERL_MAGIC_ext on
1530 the job HV — not a hash key, so user code, hash walkers and
1531 serializers can neither see nor clobber it, and a forged job
1532 hash has no magic to pass job_resolve's check. svt_free
1533 (ev_gm_job_magic_free) releases the reference; while any job
1534 lives, job_refs > 0 keeps this struct allocated (as an inert
1535 tombstone once DESTROY has run), so job_resolve's magic-word
1536 check never reads freed memory.
1537 Do NOT "simplify" this into storing the client's blessed SV with
1538 a bumped refcount: the old comment's double-DESTROY fear was
1539 unfounded (DESTROY fires once when the one blessed RV's refcount
1540 hits zero, no matter how many references a job holds), but a
1541 strong ref would invert ownership — the connection would stay
1542 connected and grabbing jobs, invisibly, for as long as any job
1543 is stashed, with no handle left to stop it. The RV is the sole
1544 owner; jobs are observers. */
1545 4 self->job_refs++;
1546 4 sv_magicext((SV *)job, NULL, PERL_MAGIC_ext,
1547 &ev_gm_job_magic_vtbl, (const char *)self, 0);
1548  
1549 /* Owned reference, NOT a mortal: io_cb is a raw libev callback and
1550 never runs inside a per-callback Perl scope, so no FREETMPS would
1551 ever pop a mortal off the tmps stack — every dispatched job would
1552 stay pinned until EV::run returns (i.e. never, for a worker
1553 daemon). We release this reference on each exit path below. */
1554 4 SV *jobref = newRV_noinc((SV*)job);
1555 4 sv_bless(jobref, gv_stashpv("EV::Gearman::Job", GV_ADD));
1556  
1557 /* grab_job mode: caller supplied an explicit cb on the request,
1558 deliver the job to it instead of the registered-function path.
1559 invoke_cb2 mortalizes its arg, taking ownership of jobref. */
1560 4 ▶ if (r->cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (r->cb) { 0 4 4
1561 0 invoke_cb2(aTHX_ self, r->cb, jobref, NULL);
1562 0 worker_continue(aTHX_ self);
1563 0 return;
1564 }
1565  
1566 4 ev_gm_func_t *fn = find_function(self, f, fl);
1567 4 ▶ if (!fn || !fn->cb) {
Branch: 2 branches
BranchTrueFalseTotal
if (!fn || !fn->cb) { 4 0 4
if (!fn || !fn->cb) { 0 4 4
1568 /* A plain can_do() entry records the ability (so reconnect
1569 re-sends CAN_DO and grab_job can pull such jobs) but carries
1570 no handler; calling it would eat "Not a CODE reference"
1571 under G_EVAL and answer every job with a silent WORK_FAIL.
1572 Fail loudly (once per function) instead. */
1573 0 ▶ if (fn && !fn->no_cb_warned) {
Branch: 2 branches
BranchTrueFalseTotal
if (fn && !fn->no_cb_warned) { 0 0 0
if (fn && !fn->no_cb_warned) { 0 0 0
1574 0 fn->no_cb_warned = 1;
1575 0 warn("EV::Gearman: no handler for function '%.*s' "
1576 "(registered via can_do without a callback); "
1577 "use register_function or grab_job", (int)fl, f);
1578 }
1579 0 SvREFCNT_dec(jobref);
1580 0 send_work_event(aTHX_ self, GM_CMD_WORK_FAIL, h, hl, NULL, 0);
1581 0 worker_continue(aTHX_ self);
1582 0 return;
1583 }
1584  
1585 /* Snapshot fn->async before invoking the user callback: the
1586 callback is allowed to call cant_do() or reset_abilities(),
1587 which would free `fn`, leaving us with a stale pointer. The
1588 SV behind fn->cb stays alive during call_sv via Perl's own
1589 sub-context refcount, so reading it is safe. */
1590 4 int is_async = fn->async;
1591  
1592 4 self->callback_depth++;
1593 4 dSP;
1594 4 ENTER; SAVETMPS;
1595 4 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 4 4
1596 4 ▶ XPUSHs(jobref);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(jobref); 0 4 4
1597 4 PUTBACK;
1598 4 ▶ int count = call_sv(fn->cb, is_async ? (G_DISCARD | G_EVAL) : (G_SCALAR | G_EVAL));
Branch: 1 branch
BranchTrueFalseTotal
int count = call_sv(fn->cb, is_async ? (G_DISCARD | G_EVAL) : (G_SCALAR | G_EVAL)); 2 2 4
1599 4 SPAGAIN;
1600  
1601 4 SV *retval = NULL;
1602 4 ▶ int had_error = SvTRUE(ERRSV) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
int had_error = SvTRUE(ERRSV) ? 1 : 0; 4 0 4
1603 4 ▶ SV *err_sv = had_error ? newSVsv(ERRSV) : NULL;
Branch: 2 branches
BranchTrueFalseTotal
SV *err_sv = had_error ? newSVsv(ERRSV) : NULL; 0 4 4
SV *err_sv = had_error ? newSVsv(ERRSV) : NULL; 0 0 0
1604 4 ▶ if (had_error)
Branch: 1 branch
BranchTrueFalseTotal
if (had_error) 0 4 4
1605 0 ▶ sv_setsv(ERRSV, &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
sv_setsv(ERRSV, &PL_sv_undef); 0 0 0
1606  
1607 4 ▶ if (!is_async && count > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!is_async && count > 0) { 2 2 4
if (!is_async && count > 0) { 2 0 2
1608 2 retval = POPs;
1609 2 SvREFCNT_inc(retval);
1610 }
1611 4 PUTBACK;
1612 4 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 2 2 4
1613 4 self->callback_depth--;
1614 /* Release our owned jobref; if the callback stashed the job (async
1615 mode) its own reference keeps the job alive. */
1616 4 SvREFCNT_dec(jobref);
1617  
1618 4 ▶ if (self->magic == GM_MAGIC_FREED) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) { 0 4 4
1619 0 ▶ if (retval) SvREFCNT_dec(retval);
Branch: 1 branch
BranchTrueFalseTotal
if (retval) SvREFCNT_dec(retval); 0 0 0
1620 0 ▶ if (err_sv) SvREFCNT_dec(err_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (err_sv) SvREFCNT_dec(err_sv); 0 0 0
1621 0 return;
1622 }
1623  
1624 4 ▶ if (!is_async) {
Branch: 1 branch
BranchTrueFalseTotal
if (!is_async) { 2 2 4
1625 2 ▶ if (had_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (had_error) { 0 2 2
1626 /* WORK_EXCEPTION is terminal at the server (gearmand calls
1627 fail() on the job after forwarding the exception data),
1628 so send it INSTEAD OF WORK_FAIL when the option is on —
1629 sending both produces a JOB_NOT_FOUND error on the
1630 second packet. */
1631 0 ▶ if (self->opt_exceptions && err_sv) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->opt_exceptions && err_sv) { 0 0 0
if (self->opt_exceptions && err_sv) { 0 0 0
1632 0 STRLEN el; const char *ep = SvPV(err_sv, el);
1633 0 send_work_event(aTHX_ self, GM_CMD_WORK_EXCEPTION, h, hl, ep, el);
1634 } else {
1635 0 send_work_event(aTHX_ self, GM_CMD_WORK_FAIL, h, hl, NULL, 0);
1636 }
1637 } else {
1638 2 STRLEN dl = 0;
1639 2 const char *dp = "";
1640 2 ▶ if (retval && SvOK(retval))
Branch: 2 branches
BranchTrueFalseTotal
if (retval && SvOK(retval)) 2 0 2
if (retval && SvOK(retval)) 2 0 2
1641 2 dp = SvPV(retval, dl);
1642 2 send_work_event(aTHX_ self, GM_CMD_WORK_COMPLETE, h, hl, dp, dl);
1643 }
1644 2 ▶ } else if (had_error && err_sv) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (had_error && err_sv) { 0 2 2
} else if (had_error && err_sv) { 0 0 0
1645 /* Async: the user keeps the job around and calls complete/fail
1646 later. We immediately grab the next job so async workers can
1647 process multiple jobs concurrently — bounded only by what the
1648 server has queued. Users who want a concurrency cap call
1649 work_stop in their callback (and work() again from
1650 complete()/fail() to resume). */
1651 0 warn("EV::Gearman: async worker callback raised: %s",
1652 SvPV_nolen(err_sv));
1653 }
1654 4 ▶ if (retval) SvREFCNT_dec(retval);
Branch: 1 branch
BranchTrueFalseTotal
if (retval) SvREFCNT_dec(retval); 2 2 4
1655 4 ▶ if (err_sv) SvREFCNT_dec(err_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (err_sv) SvREFCNT_dec(err_sv); 0 4 4
1656  
1657 4 ▶ if (self->worker_one_shot) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->worker_one_shot) { 0 4 4
1658 0 self->worker_active = 0;
1659 0 self->worker_one_shot = 0;
1660 } else {
1661 4 worker_continue(aTHX_ self);
1662 }
1663 }
1664  
1665 /* ================================================================
1666 * Read path: parse binary or text-protocol responses
1667 *
1668 * The server may emit two stream styles:
1669 * - Binary packets with magic "\0RES" (response to binary requests)
1670 * - Text lines (response to admin commands like "status\n")
1671 *
1672 * We choose dispatch based on the head request kind: if head is
1673 * CB_ADMIN, we expect text; otherwise binary. If both styles are
1674 * intermixed we parse whichever the head expects.
1675 *
1676 * Admin replies: single-line commands ("version\n") return one
1677 * line; multi-line ("status\n", "workers\n") terminate with ".\n".
1678 * ================================================================ */
1679  
1680 /* Returns 1 if a complete admin reply was parsed and consumed,
1681 * 0 if more bytes are needed, -1 on protocol error (head request
1682 * is not CB_ADMIN — caller should disconnect). */
1683 257 static int parse_admin_response(pTHX_ ev_gm_t *self) {
1684 257 ▶ if (ngx_queue_empty(&self->cb_queue)) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) return -1; 1 256 257
1685 256 ngx_queue_t *q = ngx_queue_head(&self->cb_queue);
1686 256 ev_gm_req_t *r = ngx_queue_data(q, ev_gm_req_t, queue);
1687 256 ▶ if (r->kind != CB_ADMIN) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (r->kind != CB_ADMIN) return -1; 0 256 256
1688  
1689 256 size_t consumed = 0;
1690 256 size_t result_len = 0;
1691 256 ▶ if (r->admin_terminator) {
Branch: 1 branch
BranchTrueFalseTotal
if (r->admin_terminator) { 0 256 256
1692 /* Find ".\n" at start of a line. */
1693 0 const char *start = self->rbuf;
1694 0 const char *end = self->rbuf + self->rbuf_len;
1695 0 const char *p = start;
1696 0 const char *terminator = NULL;
1697 0 ▶ while (p < end) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < end) { 0 0 0
1698 0 ▶ if (p == start || *(p - 1) == '\n') {
Branch: 2 branches
BranchTrueFalseTotal
if (p == start || *(p - 1) == '\n') { 0 0 0
if (p == start || *(p - 1) == '\n') { 0 0 0
1699 0 ▶ if (p[0] == '.' && (p + 1 < end) && p[1] == '\n') {
Branch: 3 branches
BranchTrueFalseTotal
if (p[0] == '.' && (p + 1 < end) && p[1] == '\n') { 0 0 0
if (p[0] == '.' && (p + 1 < end) && p[1] == '\n') { 0 0 0
if (p[0] == '.' && (p + 1 < end) && p[1] == '\n') { 0 0 0
1700 0 terminator = p;
1701 0 break;
1702 }
1703 }
1704 0 p++;
1705 }
1706 0 ▶ if (!terminator) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!terminator) return 0; 0 0 0
1707 0 consumed = (terminator - start) + 2; /* include ".\n" */
1708 0 result_len = terminator - start;
1709 } else {
1710 256 const char *nl = memchr(self->rbuf, '\n', self->rbuf_len);
1711 256 ▶ if (!nl) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) return 0; 256 0 256
1712 0 consumed = (nl - self->rbuf) + 1;
1713 0 result_len = nl - self->rbuf;
1714 }
1715  
1716 0 ngx_queue_remove(&r->queue);
1717 0 self->pending_count--;
1718 0 ▶ if (ngx_queue_empty(&self->cb_queue)) disarm_cmd_timer(self);
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) disarm_cmd_timer(self); 0 0 0
1719 0 else arm_cmd_timer(self);
1720 /* gearmand's text-protocol error replies are single-line
1721 "ERR ..." — deliver them as the error argument, not as a
1722 successful result (mirrors the binary ERROR convention). The
1723 raw text is kept intact. */
1724 0 ▶ int is_err = (!r->admin_terminator && result_len >= 4 &&
Branch: 2 branches
BranchTrueFalseTotal
int is_err = (!r->admin_terminator && result_len >= 4 && 0 0 0
int is_err = (!r->admin_terminator && result_len >= 4 && 0 0 0
1725 0 ▶ memcmp(self->rbuf, "ERR ", 4) == 0);
Branch: 1 branch
BranchTrueFalseTotal
memcmp(self->rbuf, "ERR ", 4) == 0); 0 0 0
1726 /* invoke_cb2 dec's the SV when r->cb is NULL, so build it
1727 unconditionally and let the helper handle the no-cb case. */
1728 0 ▶ invoke_cb2(aTHX_ self, r->cb,
Branch: 2 branches
BranchTrueFalseTotal
invoke_cb2(aTHX_ self, r->cb, 0 0 0
invoke_cb2(aTHX_ self, r->cb, 0 0 0
1729 0 is_err ? NULL : newSVpvn(self->rbuf, result_len),
1730 0 is_err ? newSVpvn(self->rbuf, result_len) : NULL);
1731 0 cleanup_req(aTHX_ r);
1732  
1733 0 ▶ if (self->magic == GM_MAGIC_FREED) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) return 1; 0 0 0
1734 /* The callback may have called disconnect(), which zeroes rbuf_len
1735 via cleanup_connection. Bail before the bookkeeping below would
1736 underflow it (mirrors the binary path in process_responses). */
1737 0 ▶ if (!self->connected) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return 1; 0 0 0
1738  
1739 0 self->rbuf_len -= consumed;
1740 0 ▶ if (self->rbuf_len > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len > 0) 0 0 0
1741 0 memmove(self->rbuf, self->rbuf + consumed, self->rbuf_len);
1742 0 return 1;
1743 }
1744  
1745 307 static void process_responses(pTHX_ ev_gm_t *self) {
1746 333 ▶ while (self->rbuf_len > 0) {
Branch: 1 branch
BranchTrueFalseTotal
while (self->rbuf_len > 0) { 309 24 333
1747 /* Binary response packets start with "\0RES"; the text/admin
1748 protocol never emits a leading NUL, so the first byte is
1749 enough to pick a parser. */
1750 309 int is_admin = (self->rbuf[0] != '\0');
1751  
1752 309 ▶ if (is_admin) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_admin) { 257 52 309
1753 257 int rv = parse_admin_response(aTHX_ self);
1754 257 ▶ if (rv == 0) { /* need more bytes */
Branch: 1 branch
BranchTrueFalseTotal
if (rv == 0) { /* need more bytes */ 256 1 257
1755 /* A broken/hostile peer can stream an unterminated
1756 admin reply forever; without a length prefix there is
1757 no other bound on the accumulation. (rv == 0 implies
1758 the head request is CB_ADMIN.) */
1759 256 ▶ if (self->rbuf_len > GM_MAX_ADMIN_RESPONSE) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len > GM_MAX_ADMIN_RESPONSE) { 1 255 256
1760 1 handle_disconnect(aTHX_ self, "admin response too large");
1761 1 return;
1762 }
1763 255 break;
1764 }
1765 1 ▶ if (rv < 0) { /* protocol error */
Branch: 1 branch
BranchTrueFalseTotal
if (rv < 0) { /* protocol error */ 1 0 1
1766 1 handle_disconnect(aTHX_ self,
1767 "unexpected admin response (queue head is not admin)");
1768 1 return;
1769 }
1770 0 ▶ if (self->magic == GM_MAGIC_FREED) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) return; 0 0 0
1771 0 ▶ if (!self->connected) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return; 0 0 0
1772 0 continue;
1773 }
1774  
1775 52 ▶ if (self->rbuf_len < GM_HEADER_SIZE) break;
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len < GM_HEADER_SIZE) break; 0 52 52
1776 52 ▶ if (memcmp(self->rbuf, GM_MAGIC_RES, 4) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (memcmp(self->rbuf, GM_MAGIC_RES, 4) != 0) { 1 51 52
1777 1 handle_disconnect(aTHX_ self, "invalid response magic");
1778 1 return;
1779 }
1780 51 uint32_t cmd = gm_read_u32(self->rbuf + 4);
1781 51 uint32_t body_len = gm_read_u32(self->rbuf + 8);
1782 51 ▶ if (body_len > GM_MAX_PACKET) {
Branch: 1 branch
BranchTrueFalseTotal
if (body_len > GM_MAX_PACKET) { 1 50 51
1783 1 handle_disconnect(aTHX_ self, "response packet too large");
1784 1 return;
1785 }
1786 50 size_t total = (size_t)GM_HEADER_SIZE + body_len;
1787 50 ▶ if (self->rbuf_len < total) break;
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len < total) break; 20 30 50
1788  
1789 /* rbuf is input-only — dispatch may grow wbuf but never rbuf,
1790 so the body pointer stays valid until the memmove below. */
1791 30 const char *body = self->rbuf + GM_HEADER_SIZE;
1792 30 handle_response_packet(aTHX_ self, cmd, body, body_len);
1793 30 ▶ if (self->magic == GM_MAGIC_FREED) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) return; 0 30 30
1794 30 ▶ if (!self->connected) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) return; 4 26 30
1795  
1796 26 self->rbuf_len -= total;
1797 26 ▶ if (self->rbuf_len > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len > 0) 2 24 26
1798 2 memmove(self->rbuf, self->rbuf + total, self->rbuf_len);
1799 }
1800  
1801 /* Fully consumed: release an oversized read buffer (e.g. after a
1802 single large packet) instead of pinning it for the connection's
1803 lifetime. */
1804 299 ▶ if (self->rbuf_len == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->rbuf_len == 0) 24 275 299
1805 24 buf_maybe_shrink(&self->rbuf, &self->rbuf_cap);
1806 }
1807  
1808 /* ================================================================
1809 * Read/write IO
1810 * ================================================================ */
1811  
1812 309 static void on_readable(pTHX_ ev_gm_t *self) {
1813 309 buf_ensure_read(self, 4096);
1814 309 ssize_t n = read(self->fd, self->rbuf + self->rbuf_len,
1815 309 self->rbuf_cap - self->rbuf_len);
1816 309 ▶ if (n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) { 307 2 309
1817 307 self->rbuf_len += n;
1818 307 process_responses(aTHX_ self);
1819 2 ▶ } else if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (n == 0) { 2 0 2
1820 2 handle_disconnect(aTHX_ self, "connection closed by server");
1821 } else {
1822 0 ▶ if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
Branch: 3 branches
BranchTrueFalseTotal
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) 0 0 0
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) 0 0 0
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) 0 0 0
1823 0 return;
1824 char errbuf[128];
1825 0 snprintf(errbuf, sizeof(errbuf), "read error: %s", strerror(errno));
1826 0 handle_disconnect(aTHX_ self, errbuf);
1827 }
1828 }
1829  
1830 27 static int try_write(ev_gm_t *self) {
1831 54 ▶ while (self->wbuf_off < self->wbuf_len) {
Branch: 1 branch
BranchTrueFalseTotal
while (self->wbuf_off < self->wbuf_len) { 27 27 54
1832 /* MSG_NOSIGNAL where it exists (Linux, NetBSD); elsewhere
1833 SO_NOSIGPIPE was set at socket creation. Both are defensive
1834 hygiene — the first write to a dead peer normally just
1835 returns ECONNRESET — since installing a SIGPIPE handler is
1836 the embedder's business, not a library's. */
1837 #ifdef MSG_NOSIGNAL
1838 27 ssize_t n = send(self->fd, self->wbuf + self->wbuf_off,
1839 27 self->wbuf_len - self->wbuf_off, MSG_NOSIGNAL);
1840 #else
1841 ssize_t n = write(self->fd, self->wbuf + self->wbuf_off,
1842 self->wbuf_len - self->wbuf_off);
1843 #endif
1844 27 ▶ if (n > 0) self->wbuf_off += n;
Branch: 1 branch
BranchTrueFalseTotal
if (n > 0) self->wbuf_off += n; 27 0 27
1845 0 ▶ else if (n < 0) {
Branch: 1 branch
BranchTrueFalseTotal
else if (n < 0) { 0 0 0
1846 0 ▶ if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
Branch: 3 branches
BranchTrueFalseTotal
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) 0 0 0
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) 0 0 0
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) 0 0 0
1847 0 return 0;
1848 0 return -1;
1849 }
1850 }
1851 27 self->wbuf_len = 0;
1852 27 self->wbuf_off = 0;
1853 27 buf_maybe_shrink(&self->wbuf, &self->wbuf_cap);
1854 27 stop_writing(self);
1855 27 return 1;
1856 }
1857  
1858 /* Attempt one non-blocking connect to the candidate at self->ai_cur.
1859 Returns 1 when the sequence stops here: the connect either completed
1860 synchronously (finish_connect_success already ran) or is in flight
1861 (EINPROGRESS; on_connect_complete finishes it). Returns 0 on
1862 immediate failure with errbuf filled; the caller advances. */
1863 30 static int connect_attempt(pTHX_ ev_gm_t *self, char *errbuf, size_t errbuf_size) {
1864 30 struct addrinfo *ai = self->ai_cur;
1865 int fd, ret;
1866  
1867 #ifdef SOCK_CLOEXEC
1868 30 fd = socket(ai->ai_family, ai->ai_socktype | SOCK_CLOEXEC, ai->ai_protocol);
1869 30 ▶ if (fd < 0 && errno == EINVAL) /* old kernels: fall back */
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0 && errno == EINVAL) /* old kernels: fall back */ 0 30 30
if (fd < 0 && errno == EINVAL) /* old kernels: fall back */ 0 0 0
1870 0 fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1871 #else
1872 fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1873 #endif
1874 30 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 0 30 30
1875 0 snprintf(errbuf, errbuf_size, "socket: %s", strerror(errno));
1876 0 return 0;
1877 }
1878 30 ▶ if (gm_set_socket_flags(fd) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (gm_set_socket_flags(fd) < 0) { 0 30 30
1879 0 close(fd);
1880 0 snprintf(errbuf, errbuf_size, "fcntl set socket flags failed");
1881 0 return 0;
1882 }
1883 30 int one = 1;
1884 30 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
1885 30 self->fd = fd;
1886 30 ret = connect(fd, ai->ai_addr, ai->ai_addrlen);
1887  
1888 /* Watcher init is the same for the immediate-success, EINPROGRESS
1889 and immediate-failure branches; only ev_io_start (via start_*)
1890 differs. Init'd-but-not-started watchers are inert, so it is
1891 safe to run this even in the failure branch which closes the fd. */
1892 30 ev_io_init(&self->rio, io_cb, self->fd, EV_READ);
1893 30 self->rio.data = (void *)self;
1894 30 ev_io_init(&self->wio, io_cb, self->fd, EV_WRITE);
1895 30 self->wio.data = (void *)self;
1896 30 ev_set_priority(&self->rio, self->priority);
1897 30 ev_set_priority(&self->wio, self->priority);
1898  
1899 30 ▶ if (ret == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret == 0) { 0 30 30
1900 0 clear_addrinfo(self);
1901 0 stop_connect_timer(self);
1902 0 self->connected = 1;
1903 0 finish_connect_success(aTHX_ self);
1904 0 return 1;
1905 }
1906 30 ▶ if (errno != EINPROGRESS) {
Branch: 1 branch
BranchTrueFalseTotal
if (errno != EINPROGRESS) { 0 30 30
1907 0 snprintf(errbuf, errbuf_size, "connect: %s", strerror(errno));
1908 0 close(self->fd);
1909 0 self->fd = -1;
1910 0 return 0;
1911 }
1912 30 self->connecting = 1;
1913 30 start_writing(self);
1914  
1915 /* Armed only on the first async candidate: the timeout bounds the
1916 whole candidate sequence, not each individual attempt. */
1917 30 ▶ if (!self->connect_timer_active && self->connect_timeout_ms > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!self->connect_timer_active && self->connect_timeout_ms > 0) { 30 0 30
if (!self->connect_timer_active && self->connect_timeout_ms > 0) { 0 30 30
1918 0 ev_tstamp delay = (ev_tstamp)self->connect_timeout_ms / 1000.0;
1919 0 ev_timer_init(&self->connect_timer, connect_timeout_cb, delay, 0.0);
1920 0 self->connect_timer.data = (void *)self;
1921 0 ev_timer_start(self->loop, &self->connect_timer);
1922 0 self->connect_timer_active = 1;
1923 }
1924 30 return 1;
1925 }
1926  
1927 /* Walk candidates from self->ai_cur onward until one connects (or is
1928 in flight). prev_err is the failure text of the candidate that just
1929 failed; when the list runs out, report the most recent error and
1930 let the reconnect logic run. */
1931 33 static void connect_try_from(pTHX_ ev_gm_t *self, const char *prev_err) {
1932 char errbuf[160];
1933 33 snprintf(errbuf, sizeof(errbuf), "%s", prev_err);
1934 33 ▶ while (self->ai_cur) {
Branch: 1 branch
BranchTrueFalseTotal
while (self->ai_cur) { 30 3 33
1935 30 ▶ if (connect_attempt(aTHX_ self, errbuf, sizeof(errbuf)))
Branch: 1 branch
BranchTrueFalseTotal
if (connect_attempt(aTHX_ self, errbuf, sizeof(errbuf))) 30 0 30
1936 30 return;
1937 0 self->ai_cur = self->ai_cur->ai_next;
1938 }
1939 3 stop_connect_timer(self);
1940 3 clear_addrinfo(self);
1941 3 report_connect_error(aTHX_ self, errbuf);
1942 }
1943  
1944 27 static void on_connect_complete(pTHX_ ev_gm_t *self) {
1945 27 int err = 0;
1946 27 socklen_t len = sizeof(err);
1947 27 ▶ if (getsockopt(self->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0 || err != 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (getsockopt(self->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0 || err != 0) { 27 0 27
if (getsockopt(self->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0 || err != 0) { 4 23 27
1948 char errbuf[128];
1949 4 snprintf(errbuf, sizeof(errbuf), "connect failed: %s",
1950 4 ▶ strerror(err ? err : errno));
Branch: 1 branch
BranchTrueFalseTotal
strerror(err ? err : errno)); 0 4 4
1951 4 close(self->fd);
1952 4 self->fd = -1;
1953 4 self->connecting = 0;
1954 4 stop_writing(self);
1955 /* Fall through to the next resolved address, if any (e.g. a
1956 dual-stack 'localhost' refusing ::1 while 127.0.0.1 would
1957 answer). The connect timer keeps running; on exhaustion
1958 connect_try_from stops it and reports the last error. */
1959 4 ▶ if (self->ai_cur)
Branch: 1 branch
BranchTrueFalseTotal
if (self->ai_cur) 4 0 4
1960 4 self->ai_cur = self->ai_cur->ai_next;
1961 4 connect_try_from(aTHX_ self, errbuf);
1962 4 return;
1963 }
1964 23 self->connecting = 0;
1965 23 self->connected = 1;
1966 23 stop_writing(self);
1967 23 stop_connect_timer(self);
1968 23 clear_addrinfo(self);
1969 23 finish_connect_success(aTHX_ self);
1970 }
1971  
1972 363 static void io_cb(EV_P_ ev_io *w, int revents) {
1973 dTHX;
1974 363 ev_gm_t *self = (ev_gm_t *)w->data;
1975 (void)loop;
1976 363 ▶ if (self->magic != GM_MAGIC_ALIVE) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_ALIVE) return; 0 363 363
1977 363 self->callback_depth++;
1978  
1979 363 ▶ if (self->connecting) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connecting) { 27 336 363
1980 27 ▶ if (revents & EV_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (revents & EV_WRITE) { 27 0 27
1981 27 on_connect_complete(aTHX_ self);
1982 }
1983 27 self->callback_depth--;
1984 27 check_destroyed(self);
1985 27 return;
1986 }
1987  
1988 336 ▶ if (revents & EV_READ) {
Branch: 1 branch
BranchTrueFalseTotal
if (revents & EV_READ) { 309 27 336
1989 309 on_readable(aTHX_ self);
1990 309 ▶ if (self->magic != GM_MAGIC_ALIVE) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != GM_MAGIC_ALIVE) { 0 309 309
1991 0 self->callback_depth--;
1992 0 check_destroyed(self);
1993 0 return;
1994 }
1995 }
1996 336 ▶ if (revents & EV_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (revents & EV_WRITE) { 27 309 336
1997 27 int rv = try_write(self);
1998 27 ▶ if (rv < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (rv < 0) { 0 27 27
1999 char errbuf[128];
2000 0 snprintf(errbuf, sizeof(errbuf), "write error: %s", strerror(errno));
2001 0 handle_disconnect(aTHX_ self, errbuf);
2002 }
2003 }
2004 336 self->callback_depth--;
2005 336 check_destroyed(self);
2006 }
2007  
2008 /* ================================================================
2009 * start_connect
2010 * ================================================================ */
2011  
2012 33 static void start_connect(pTHX_ ev_gm_t *self) {
2013 int fd, ret;
2014  
2015 33 ▶ if (!self->path) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->path) { 29 4 33
2016 29 struct addrinfo hints, *res = NULL;
2017 char port_str[16];
2018 29 snprintf(port_str, sizeof(port_str), "%d", self->port);
2019 29 memset(&hints, 0, sizeof(hints));
2020 29 hints.ai_family = AF_UNSPEC;
2021 29 hints.ai_socktype = SOCK_STREAM;
2022  
2023 29 ret = getaddrinfo(self->host, port_str, &hints, &res);
2024 29 ▶ if (ret != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret != 0) { 0 29 29
2025 char errbuf[256];
2026 0 snprintf(errbuf, sizeof(errbuf), "getaddrinfo: %s", gai_strerror(ret));
2027 0 report_connect_error(aTHX_ self, errbuf);
2028 0 return;
2029 }
2030 /* Try every resolved address in turn: a dual-stack 'localhost'
2031 typically resolves to ::1 first, which a gearmand bound to
2032 127.0.0.1 will refuse — the fallback list is the only way
2033 such a host stays reachable by name. */
2034 29 clear_addrinfo(self);
2035 29 self->ai_list = res;
2036 29 self->ai_cur = res;
2037 29 connect_try_from(aTHX_ self, "connect: no resolved addresses");
2038 29 return;
2039 }
2040  
2041 /* Unix-domain socket: a single fixed address, no fallback list. */
2042 {
2043 struct sockaddr_un addr;
2044 4 memset(&addr, 0, sizeof(addr));
2045 4 addr.sun_family = AF_UNIX;
2046 4 ▶ if (strlen(self->path) >= sizeof(addr.sun_path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (strlen(self->path) >= sizeof(addr.sun_path)) { 3 1 4
2047 3 report_connect_error(aTHX_ self, "unix socket path too long");
2048 3 return;
2049 }
2050 1 strncpy(addr.sun_path, self->path, sizeof(addr.sun_path) - 1);
2051  
2052 #ifdef SOCK_CLOEXEC
2053 1 fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
2054 1 ▶ if (fd < 0 && errno == EINVAL) /* old kernels: fall back */
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0 && errno == EINVAL) /* old kernels: fall back */ 0 1 1
if (fd < 0 && errno == EINVAL) /* old kernels: fall back */ 0 0 0
2055 0 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2056 #else
2057 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2058 #endif
2059 1 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 0 1 1
2060 char errbuf[128];
2061 0 snprintf(errbuf, sizeof(errbuf), "socket: %s", strerror(errno));
2062 0 report_connect_error(aTHX_ self, errbuf);
2063 0 return;
2064 }
2065 1 ▶ if (gm_set_socket_flags(fd) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (gm_set_socket_flags(fd) < 0) { 0 1 1
2066 0 close(fd);
2067 0 report_connect_error(aTHX_ self, "fcntl set socket flags failed");
2068 0 return;
2069 }
2070 1 self->fd = fd;
2071 1 ret = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
2072 }
2073  
2074 /* Watcher init is the same for the immediate-success and
2075 EINPROGRESS branches; only ev_io_start (via start_*) differs.
2076 Init'd-but-not-started watchers are inert, so it is safe to
2077 run this even in the failure branch which closes the fd. */
2078 1 ev_io_init(&self->rio, io_cb, self->fd, EV_READ);
2079 1 self->rio.data = (void *)self;
2080 1 ev_io_init(&self->wio, io_cb, self->fd, EV_WRITE);
2081 1 self->wio.data = (void *)self;
2082 1 ev_set_priority(&self->rio, self->priority);
2083 1 ev_set_priority(&self->wio, self->priority);
2084  
2085 1 ▶ if (ret == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret == 0) { 0 1 1
2086 0 self->connected = 1;
2087 0 finish_connect_success(aTHX_ self);
2088 0 return;
2089 }
2090 1 ▶ if (errno != EINPROGRESS) {
Branch: 1 branch
BranchTrueFalseTotal
if (errno != EINPROGRESS) { 1 0 1
2091 char errbuf[128];
2092 1 snprintf(errbuf, sizeof(errbuf), "connect: %s", strerror(errno));
2093 1 close(self->fd);
2094 1 self->fd = -1;
2095 1 report_connect_error(aTHX_ self, errbuf);
2096 1 return;
2097 }
2098 0 self->connecting = 1;
2099 0 start_writing(self);
2100  
2101 0 ▶ if (self->connect_timeout_ms > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_timeout_ms > 0) { 0 0 0
2102 0 ev_tstamp delay = (ev_tstamp)self->connect_timeout_ms / 1000.0;
2103 0 ev_timer_init(&self->connect_timer, connect_timeout_cb, delay, 0.0);
2104 0 self->connect_timer.data = (void *)self;
2105 0 ev_timer_start(self->loop, &self->connect_timer);
2106 0 self->connect_timer_active = 1;
2107 }
2108 }
2109  
2110 /* ================================================================
2111 * Helper to encode a multi-arg body: NUL-separated.
2112 * ================================================================ */
2113  
2114 /* Concatenate args with NUL separators into out (caller frees).
2115 * args: array of {ptr, len} pairs; n_args entries.
2116 * Returns total length in *out_len. NULL ptr is treated as empty. */
2117 4 static char* gm_encode_args(int n_args, const char **ptrs, const STRLEN *lens, size_t *out_len) {
2118 4 size_t total = 0;
2119 int i;
2120 18 ▶ for (i = 0; i < n_args; i++) total += (ptrs[i] ? lens[i] : 0);
Branch: 2 branches
BranchTrueFalseTotal
for (i = 0; i < n_args; i++) total += (ptrs[i] ? lens[i] : 0); 14 0 14
for (i = 0; i < n_args; i++) total += (ptrs[i] ? lens[i] : 0); 14 4 18
2121 4 ▶ if (n_args > 1) total += (n_args - 1);
Branch: 1 branch
BranchTrueFalseTotal
if (n_args > 1) total += (n_args - 1); 4 0 4
2122 char *out;
2123 4 ▶ Newx(out, total ? total : 1, char);
Branch: 1 branch
BranchTrueFalseTotal
Newx(out, total ? total : 1, char); 4 0 4
2124 4 char *p = out;
2125 18 ▶ for (i = 0; i < n_args; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n_args; i++) { 14 4 18
2126 14 ▶ if (i > 0) { *p++ = '\0'; }
Branch: 1 branch
BranchTrueFalseTotal
if (i > 0) { *p++ = '\0'; } 10 4 14
2127 14 ▶ if (ptrs[i] && lens[i] > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (ptrs[i] && lens[i] > 0) { 14 0 14
if (ptrs[i] && lens[i] > 0) { 11 3 14
2128 11 memcpy(p, ptrs[i], lens[i]);
2129 11 p += lens[i];
2130 }
2131 }
2132 4 *out_len = total;
2133 4 return out;
2134 }
2135  
2136 /* ================================================================
2137 * XS interface
2138 * ================================================================ */
2139  
2140 MODULE = EV::Gearman PACKAGE = EV::Gearman
2141  
2142 BOOT:
2143 {
2144 30 ▶ I_EV_API("EV::Gearman");
Branch: 3 branches
BranchTrueFalseTotal
I_EV_API("EV::Gearman"); 0 30 30
I_EV_API("EV::Gearman"); 30 0 30
I_EV_API("EV::Gearman"); 0 30 30
2145 }
2146  
2147 EV::Gearman
2148 new(char *class, ...)
2149 CODE:
2150 {
2151 PERL_UNUSED_VAR(class);
2152 37 ▶ if ((items - 1) % 2 != 0) croak("odd number of arguments");
Branch: 1 branch
BranchTrueFalseTotal
if ((items - 1) % 2 != 0) croak("odd number of arguments"); 1 36 37
2153  
2154 36 Newxz(RETVAL, 1, ev_gm_t);
2155 36 RETVAL->magic = GM_MAGIC_ALIVE;
2156 36 RETVAL->fd = -1;
2157 36 RETVAL->port = 4730;
2158 36 ngx_queue_init(&RETVAL->cb_queue);
2159 36 ngx_queue_init(&RETVAL->wait_queue);
2160 36 ngx_queue_init(&RETVAL->active_jobs);
2161 36 ngx_queue_init(&RETVAL->functions);
2162 36 Newx(RETVAL->rbuf, BUF_INIT_SIZE, char);
2163 36 RETVAL->rbuf_cap = BUF_INIT_SIZE;
2164 36 Newx(RETVAL->wbuf, BUF_INIT_SIZE, char);
2165 36 RETVAL->wbuf_cap = BUF_INIT_SIZE;
2166  
2167 /* Default error handler. eval_pv hands back the result without
2168 transferring a reference we own (it stays mortal), so take one
2169 to keep the sub alive past the current statement. */
2170 36 RETVAL->on_error = eval_pv("sub { warn \"EV::Gearman error: @_\\n\" }", TRUE);
2171 36 SvREFCNT_inc_simple_void_NN(RETVAL->on_error);
2172  
2173 36 SV *host_sv = NULL, *path_sv = NULL;
2174 36 int port = 4730;
2175 36 int do_reconnect = 0, reconnect_delay = 1000, max_reconnect_attempts = 0;
2176 36 RETVAL->loop = EV_DEFAULT;
2177  
2178 int i;
2179 147 ▶ for (i = 1; i < items; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i < items; i += 2) { 113 34 147
2180 113 const char *k = SvPV_nolen(ST(i));
2181 113 SV *v = ST(i + 1);
2182  
2183 113 ▶ if (strEQ(k, "host")) host_sv = v;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(k, "host")) host_sv = v; 26 87 113
2184 87 ▶ else if (strEQ(k, "port")) port = SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "port")) port = SvIV(v); 25 62 87
2185 62 ▶ else if (strEQ(k, "path")) path_sv = v;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "path")) path_sv = v; 3 59 62
2186 59 ▶ else if (strEQ(k, "on_error")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "on_error")) { 25 34 59
2187 25 ▶ CLEAR_HANDLER(RETVAL->on_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_error); 25 0 25
2188 25 ▶ if (SvOK(v) && SvROK(v)) RETVAL->on_error = newSVsv(v);
Branch: 2 branches
BranchTrueFalseTotal
if (SvOK(v) && SvROK(v)) RETVAL->on_error = newSVsv(v); 25 0 25
if (SvOK(v) && SvROK(v)) RETVAL->on_error = newSVsv(v); 25 0 25
2189 }
2190 34 ▶ else if (strEQ(k, "on_connect")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "on_connect")) { 6 28 34
2191 6 ▶ if (SvOK(v) && SvROK(v)) RETVAL->on_connect = newSVsv(v);
Branch: 2 branches
BranchTrueFalseTotal
if (SvOK(v) && SvROK(v)) RETVAL->on_connect = newSVsv(v); 6 0 6
if (SvOK(v) && SvROK(v)) RETVAL->on_connect = newSVsv(v); 6 0 6
2192 }
2193 28 ▶ else if (strEQ(k, "on_disconnect")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "on_disconnect")) { 2 26 28
2194 2 ▶ if (SvOK(v) && SvROK(v)) RETVAL->on_disconnect = newSVsv(v);
Branch: 2 branches
BranchTrueFalseTotal
if (SvOK(v) && SvROK(v)) RETVAL->on_disconnect = newSVsv(v); 2 0 2
if (SvOK(v) && SvROK(v)) RETVAL->on_disconnect = newSVsv(v); 2 0 2
2195 }
2196 26 ▶ else if (strEQ(k, "connect_timeout")) RETVAL->connect_timeout_ms = SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "connect_timeout")) RETVAL->connect_timeout_ms = SvIV(v); 1 25 26
2197 25 ▶ else if (strEQ(k, "command_timeout")) RETVAL->command_timeout_ms = SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "command_timeout")) RETVAL->command_timeout_ms = SvIV(v); 5 20 25
2198 20 ▶ else if (strEQ(k, "priority")) RETVAL->priority = SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "priority")) RETVAL->priority = SvIV(v); 1 19 20
2199 19 ▶ else if (strEQ(k, "keepalive")) RETVAL->keepalive = SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "keepalive")) RETVAL->keepalive = SvIV(v); 1 18 19
2200 18 ▶ else if (strEQ(k, "reconnect")) do_reconnect = SvTRUE(v) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "reconnect")) do_reconnect = SvTRUE(v) ? 1 : 0; 5 13 18
2201 13 ▶ else if (strEQ(k, "reconnect_delay")) reconnect_delay = SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "reconnect_delay")) reconnect_delay = SvIV(v); 5 8 13
2202 8 ▶ else if (strEQ(k, "max_reconnect_attempts")) max_reconnect_attempts = SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "max_reconnect_attempts")) max_reconnect_attempts = SvIV(v); 2 6 8
2203 6 ▶ else if (strEQ(k, "exceptions")) RETVAL->opt_exceptions = SvTRUE(v) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "exceptions")) RETVAL->opt_exceptions = SvTRUE(v) ? 1 : 0; 1 5 6
2204 5 ▶ else if (strEQ(k, "client_id")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "client_id")) { 1 4 5
2205 2 ▶ if (SvOK(v)) RETVAL->client_id = savepv(SvPV_nolen(v));
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(v)) RETVAL->client_id = savepv(SvPV_nolen(v)); 1 0 1
2206 }
2207 4 ▶ else if (strEQ(k, "grab_unique")) RETVAL->worker_grab_uniq = SvTRUE(v) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "grab_unique")) RETVAL->worker_grab_uniq = SvTRUE(v) ? 1 : 0; 1 3 4
2208 3 ▶ else if (strEQ(k, "loop")) {
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(k, "loop")) { 1 2 3
2209 1 ▶ if (!SvROK(v) || !sv_derived_from(v, "EV::Loop")) {
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(v) || !sv_derived_from(v, "EV::Loop")) { 1 0 1
if (!SvROK(v) || !sv_derived_from(v, "EV::Loop")) { 0 1 1
2210 0 Safefree(RETVAL->rbuf);
2211 0 Safefree(RETVAL->wbuf);
2212 0 ▶ CLEAR_HANDLER(RETVAL->on_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_error); 0 0 0
2213 0 ▶ CLEAR_HANDLER(RETVAL->on_connect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_connect); 0 0 0
2214 0 ▶ CLEAR_HANDLER(RETVAL->on_disconnect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_disconnect); 0 0 0
2215 0 ▶ CLEAR_HANDLER(RETVAL->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->loop_sv); 0 0 0
2216 0 ▶ if (RETVAL->client_id) Safefree(RETVAL->client_id);
Branch: 1 branch
BranchTrueFalseTotal
if (RETVAL->client_id) Safefree(RETVAL->client_id); 0 0 0
2217 0 Safefree(RETVAL);
2218 0 croak("loop => must be an EV::Loop object");
2219 }
2220 /* An EV::Loop object is a blessed scalar holding the
2221 struct ev_loop pointer in its IV slot (T_PTROBJ style);
2222 the PV slot is NULL, so SvPVX would read garbage. */
2223 1 RETVAL->loop = INT2PTR(struct ev_loop *, SvIV(SvRV(v)));
2224 /* Hold a strong ref so the loop outlives the client even
2225 when the caller drops their own reference to it. */
2226 1 ▶ CLEAR_HANDLER(RETVAL->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->loop_sv); 0 1 1
2227 1 RETVAL->loop_sv = newSVsv(v);
2228 }
2229 else {
2230 /* An unknown key is almost always a typo ("reconect") that
2231 would silently leave the intended option unset — fail
2232 loudly. Tear the partial object down exactly like the
2233 loop-validation branch above. */
2234 2 Safefree(RETVAL->rbuf);
2235 2 Safefree(RETVAL->wbuf);
2236 2 ▶ CLEAR_HANDLER(RETVAL->on_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_error); 2 0 2
2237 2 ▶ CLEAR_HANDLER(RETVAL->on_connect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_connect); 0 2 2
2238 2 ▶ CLEAR_HANDLER(RETVAL->on_disconnect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_disconnect); 0 2 2
2239 2 ▶ CLEAR_HANDLER(RETVAL->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->loop_sv); 0 2 2
2240 2 ▶ if (RETVAL->client_id) Safefree(RETVAL->client_id);
Branch: 1 branch
BranchTrueFalseTotal
if (RETVAL->client_id) Safefree(RETVAL->client_id); 0 2 2
2241 2 Safefree(RETVAL);
2242 2 croak("EV::Gearman: unknown constructor option '%s'", k);
2243 }
2244 }
2245  
2246 34 ▶ if (host_sv && path_sv) {
Branch: 2 branches
BranchTrueFalseTotal
if (host_sv && path_sv) { 26 8 34
if (host_sv && path_sv) { 1 25 26
2247 1 Safefree(RETVAL->rbuf);
2248 1 Safefree(RETVAL->wbuf);
2249 1 ▶ CLEAR_HANDLER(RETVAL->on_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_error); 1 0 1
2250 1 ▶ CLEAR_HANDLER(RETVAL->on_connect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_connect); 0 1 1
2251 1 ▶ CLEAR_HANDLER(RETVAL->on_disconnect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->on_disconnect); 0 1 1
2252 1 ▶ CLEAR_HANDLER(RETVAL->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(RETVAL->loop_sv); 0 1 1
2253 1 ▶ if (RETVAL->client_id) Safefree(RETVAL->client_id);
Branch: 1 branch
BranchTrueFalseTotal
if (RETVAL->client_id) Safefree(RETVAL->client_id); 0 1 1
2254 1 Safefree(RETVAL);
2255 1 croak("cannot specify both 'host' and 'path'");
2256 }
2257  
2258 33 RETVAL->port = port;
2259 33 ▶ if (do_reconnect) {
Branch: 1 branch
BranchTrueFalseTotal
if (do_reconnect) { 5 28 33
2260 5 RETVAL->reconnect = 1;
2261 5 RETVAL->reconnect_delay_ms = reconnect_delay >= 0 ? reconnect_delay : 0;
2262 5 RETVAL->max_reconnect_attempts = max_reconnect_attempts >= 0 ? max_reconnect_attempts : 0;
2263 }
2264  
2265 33 ▶ if (host_sv && SvOK(host_sv)) {
Branch: 2 branches
BranchTrueFalseTotal
if (host_sv && SvOK(host_sv)) { 25 8 33
if (host_sv && SvOK(host_sv)) { 25 0 25
2266 25 RETVAL->host = savepv(SvPV_nolen(host_sv));
2267 25 start_connect(aTHX_ RETVAL);
2268 8 ▶ } else if (path_sv && SvOK(path_sv)) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (path_sv && SvOK(path_sv)) { 2 6 8
} else if (path_sv && SvOK(path_sv)) { 2 0 2
2269 2 RETVAL->path = savepv(SvPV_nolen(path_sv));
2270 2 start_connect(aTHX_ RETVAL);
2271 }
2272 }
2273 OUTPUT:
2274 RETVAL
2275  
2276 void
2277 DESTROY(EV::Gearman self)
2278 CODE:
2279 {
2280 33 ▶ if (self->magic == GM_MAGIC_FREED) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic == GM_MAGIC_FREED) return; 0 33 33
2281  
2282 33 ▶ if (self->callback_depth > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->callback_depth > 0) { 0 33 33
2283 0 self->magic = GM_MAGIC_FREED;
2284 0 self->connected = 0;
2285 0 self->connecting = 0;
2286 0 stop_reading(self);
2287 0 stop_writing(self);
2288 0 stop_connect_timer(self);
2289 0 disarm_cmd_timer(self);
2290 0 stop_reconnect_timer(self);
2291 0 ▶ if (self->fd >= 0) { close(self->fd); self->fd = -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd >= 0) { close(self->fd); self->fd = -1; } 0 0 0
2292  
2293 /* Drain queues firing user callbacks with the disconnect error.
2294 connected is cleared (so GM_CROAK_UNLESS_ALIVE makes any
2295 method called from a callback croak) and magic == FREED (so a
2296 nested DESTROY no-ops at the top of this function). cancel_*
2297 would bail on FREED, so drain inline. */
2298 0 ▶ while (!ngx_queue_empty(&self->cb_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->cb_queue)) { 0 0 0
2299 0 ngx_queue_t *q = ngx_queue_head(&self->cb_queue);
2300 0 ev_gm_req_t *r = ngx_queue_data(q, ev_gm_req_t, queue);
2301 0 ngx_queue_remove(q);
2302 0 ▶ if (r->cb)
Branch: 1 branch
BranchTrueFalseTotal
if (r->cb) 0 0 0
2303 0 invoke_cb2(aTHX_ self, r->cb, NULL, newSVpvs("disconnected"));
2304 0 cleanup_req(aTHX_ r);
2305 }
2306 0 ▶ while (!ngx_queue_empty(&self->active_jobs)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->active_jobs)) { 0 0 0
2307 0 ngx_queue_t *q = ngx_queue_head(&self->active_jobs);
2308 0 ev_gm_active_t *a = ngx_queue_data(q, ev_gm_active_t, queue);
2309 0 ngx_queue_remove(q);
2310 0 self->active_count_cached--;
2311 0 ▶ if (a->on_complete)
Branch: 1 branch
BranchTrueFalseTotal
if (a->on_complete) 0 0 0
2312 0 invoke_cb2(aTHX_ self, a->on_complete, NULL, newSVpvs("disconnected"));
2313 0 cleanup_active(aTHX_ a);
2314 }
2315 0 ▶ while (!ngx_queue_empty(&self->wait_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->wait_queue)) { 0 0 0
2316 0 ngx_queue_t *q = ngx_queue_head(&self->wait_queue);
2317 0 ev_gm_wait_t *w = ngx_queue_data(q, ev_gm_wait_t, queue);
2318 0 ngx_queue_remove(q);
2319 0 ▶ if (w->req && w->req->cb)
Branch: 2 branches
BranchTrueFalseTotal
if (w->req && w->req->cb) 0 0 0
if (w->req && w->req->cb) 0 0 0
2320 0 invoke_cb2(aTHX_ self, w->req->cb, NULL, newSVpvs("disconnected"));
2321 0 cleanup_wait(aTHX_ w);
2322 }
2323 0 ▶ DRAIN_QUEUE_SILENT(&self->functions, ev_gm_func_t, cleanup_func);
Branch: 1 branch
BranchTrueFalseTotal
DRAIN_QUEUE_SILENT(&self->functions, ev_gm_func_t, cleanup_func); 0 0 0
2324 0 self->pending_count = 0;
2325 0 self->waiting_count = 0;
2326 0 self->active_count_cached = 0;
2327 0 clear_addrinfo(self);
2328 0 ▶ CLEAR_HANDLER(self->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->loop_sv); 0 0 0
2329 0 ▶ CLEAR_HANDLER(self->on_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_error); 0 0 0
2330 0 ▶ CLEAR_HANDLER(self->on_connect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_connect); 0 0 0
2331 0 ▶ CLEAR_HANDLER(self->on_disconnect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_disconnect); 0 0 0
2332 0 ▶ CLEAR_HANDLER(self->worker_on_idle);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->worker_on_idle); 0 0 0
2333 0 Safefree(self->host); self->host = NULL;
2334 0 Safefree(self->path); self->path = NULL;
2335 0 Safefree(self->client_id);self->client_id = NULL;
2336 0 Safefree(self->rbuf); self->rbuf = NULL;
2337 0 Safefree(self->wbuf); self->wbuf = NULL;
2338 0 return;
2339 }
2340  
2341 33 stop_connect_timer(self);
2342 33 disarm_cmd_timer(self);
2343 33 stop_reconnect_timer(self);
2344 33 cleanup_connection(aTHX_ self);
2345  
2346 33 ▶ if (!PL_dirty) {
Branch: 1 branch
BranchTrueFalseTotal
if (!PL_dirty) { 23 10 33
2347 23 self->callback_depth++;
2348 23 cancel_pending(aTHX_ self, "disconnected");
2349 23 cancel_active(aTHX_ self, "disconnected");
2350 23 cancel_waiting(aTHX_ self, "disconnected");
2351 23 self->callback_depth--;
2352 } else {
2353 10 ▶ DRAIN_QUEUE_SILENT(&self->cb_queue, ev_gm_req_t, cleanup_req);
Branch: 1 branch
BranchTrueFalseTotal
DRAIN_QUEUE_SILENT(&self->cb_queue, ev_gm_req_t, cleanup_req); 0 10 10
2354 10 ▶ DRAIN_QUEUE_SILENT(&self->wait_queue, ev_gm_wait_t, cleanup_wait);
Branch: 1 branch
BranchTrueFalseTotal
DRAIN_QUEUE_SILENT(&self->wait_queue, ev_gm_wait_t, cleanup_wait); 0 10 10
2355 10 ▶ DRAIN_QUEUE_SILENT(&self->active_jobs, ev_gm_active_t, cleanup_active);
Branch: 1 branch
BranchTrueFalseTotal
DRAIN_QUEUE_SILENT(&self->active_jobs, ev_gm_active_t, cleanup_active); 0 10 10
2356 }
2357  
2358 39 ▶ DRAIN_QUEUE_SILENT(&self->functions, ev_gm_func_t, cleanup_func);
Branch: 1 branch
BranchTrueFalseTotal
DRAIN_QUEUE_SILENT(&self->functions, ev_gm_func_t, cleanup_func); 6 33 39
2359  
2360 33 self->magic = GM_MAGIC_FREED;
2361 33 ▶ CLEAR_HANDLER(self->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->loop_sv); 1 32 33
2362 33 ▶ CLEAR_HANDLER(self->on_error);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_error); 33 0 33
2363 33 ▶ CLEAR_HANDLER(self->on_connect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_connect); 11 22 33
2364 33 ▶ CLEAR_HANDLER(self->on_disconnect);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->on_disconnect); 2 31 33
2365 33 ▶ CLEAR_HANDLER(self->worker_on_idle);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->worker_on_idle); 2 31 33
2366 /* NULL after free: with jobs outstanding the struct survives as an
2367 inert tombstone (freed by the last job's svt_free via
2368 check_destroyed), so no dangling bytes may linger in it. */
2369 33 Safefree(self->host); self->host = NULL;
2370 33 Safefree(self->path); self->path = NULL;
2371 33 Safefree(self->client_id); self->client_id = NULL;
2372 33 Safefree(self->rbuf); self->rbuf = NULL;
2373 33 Safefree(self->wbuf); self->wbuf = NULL;
2374 /* Depth is 0 in this branch, so this frees iff no job holds a
2375 tombstone reference; otherwise the last job release does. */
2376 33 (void)check_destroyed(self);
2377 }
2378  
2379 void
2380 connect(EV::Gearman self, const char *host, int port = 4730)
2381 CODE:
2382 {
2383 0 ▶ if (self->connected || self->connecting) croak("already connected");
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected || self->connecting) croak("already connected"); 0 0 0
if (self->connected || self->connecting) croak("already connected"); 0 0 0
2384 0 stop_reconnect_timer(self);
2385 0 Safefree(self->host); self->host = savepv(host);
2386 0 self->port = port;
2387 0 Safefree(self->path); self->path = NULL;
2388 0 self->intentional_disconnect = 0;
2389 0 start_connect(aTHX_ self);
2390 }
2391  
2392 void
2393 connect_unix(EV::Gearman self, const char *path)
2394 CODE:
2395 {
2396 1 ▶ if (self->connected || self->connecting) croak("already connected");
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected || self->connecting) croak("already connected"); 1 0 1
if (self->connected || self->connecting) croak("already connected"); 0 1 1
2397 1 stop_reconnect_timer(self);
2398 1 Safefree(self->path); self->path = savepv(path);
2399 1 Safefree(self->host); self->host = NULL;
2400 1 self->intentional_disconnect = 0;
2401 1 start_connect(aTHX_ self);
2402 }
2403  
2404 void
2405 disconnect(EV::Gearman self)
2406 CODE:
2407 {
2408 0 self->intentional_disconnect = 1;
2409 0 self->worker_active = 0;
2410 0 stop_reconnect_timer(self);
2411 0 self->callback_depth++;
2412 0 ▶ if (self->connected || self->connecting) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected || self->connecting) { 0 0 0
if (self->connected || self->connecting) { 0 0 0
2413 0 handle_disconnect(aTHX_ self, NULL);
2414 } else {
2415 0 cancel_waiting(aTHX_ self, "disconnected");
2416 }
2417 0 self->callback_depth--;
2418 0 check_destroyed(self);
2419 }
2420  
2421 int
2422 is_connected(EV::Gearman self)
2423 CODE:
2424 9 ▶ RETVAL = self->connected || self->connecting;
Branch: 3 branches
BranchTrueFalseTotal
RETVAL = self->connected || self->connecting; 5 4 9
RETVAL = self->connected || self->connecting; 0 5 5
RETVAL = self->connected || self->connecting; 0 9 9
2425 OUTPUT:
2426 RETVAL
2427  
2428 int
2429 pending_count(EV::Gearman self)
2430 CODE:
2431 0 ▶ RETVAL = self->pending_count;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->pending_count; 0 0 0
2432 OUTPUT:
2433 RETVAL
2434  
2435 int
2436 waiting_count(EV::Gearman self)
2437 CODE:
2438 1 ▶ RETVAL = self->waiting_count;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->waiting_count; 0 1 1
2439 OUTPUT:
2440 RETVAL
2441  
2442 int
2443 active_count(EV::Gearman self)
2444 CODE:
2445 0 ▶ RETVAL = self->active_count_cached;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->active_count_cached; 0 0 0
2446 OUTPUT:
2447 RETVAL
2448  
2449 # Internal: current (read, write) buffer capacities in bytes. Used by
2450 # the test suite to assert that oversized buffers are released after a
2451 # large packet drains. Not part of the public API.
2452 void
2453 _buf_caps(EV::Gearman self)
2454 PPCODE:
2455 {
2456 1 ▶ EXTEND(SP, 2);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 2); 0 1 1
2457 1 mPUSHu(self->rbuf_cap);
2458 1 mPUSHu(self->wbuf_cap);
2459 }
2460  
2461 # Internal: number of live EV::Gearman::Job objects holding a tombstone
2462 # reference on this connection. Used by the test suite to assert that
2463 # dispatched-then-dropped jobs accumulate nothing. Not public API.
2464 int
2465 _job_refs(EV::Gearman self)
2466 CODE:
2467 0 ▶ RETVAL = self->job_refs;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->job_refs; 0 0 0
2468 OUTPUT:
2469 RETVAL
2470  
2471 SV *
2472 on_error(EV::Gearman self, ...)
2473 CODE:
2474 0 ▶ RETVAL = handler_accessor(aTHX_ &self->on_error, items,
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = handler_accessor(aTHX_ &self->on_error, items, 0 0 0
2475 0 items > 1 ? ST(1) : &PL_sv_undef);
2476 OUTPUT:
2477 RETVAL
2478  
2479 SV *
2480 on_connect(EV::Gearman self, ...)
2481 CODE:
2482 10 ▶ RETVAL = handler_accessor(aTHX_ &self->on_connect, items,
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = handler_accessor(aTHX_ &self->on_connect, items, 5 0 5
2483 5 items > 1 ? ST(1) : &PL_sv_undef);
2484 OUTPUT:
2485 RETVAL
2486  
2487 SV *
2488 on_disconnect(EV::Gearman self, ...)
2489 CODE:
2490 0 ▶ RETVAL = handler_accessor(aTHX_ &self->on_disconnect, items,
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = handler_accessor(aTHX_ &self->on_disconnect, items, 0 0 0
2491 0 items > 1 ? ST(1) : &PL_sv_undef);
2492 OUTPUT:
2493 RETVAL
2494  
2495 void
2496 echo(EV::Gearman self, SV *data_sv, SV *cb_sv = &PL_sv_undef)
2497 CODE:
2498 {
2499 9 ▶ GM_CROAK_UNLESS_ALIVE(self);
Branch: 4 branches
BranchTrueFalseTotal
GM_CROAK_UNLESS_ALIVE(self); 2 7 9
GM_CROAK_UNLESS_ALIVE(self); 1 1 2
GM_CROAK_UNLESS_ALIVE(self); 1 0 1
GM_CROAK_UNLESS_ALIVE(self); 0 1 1
2500 STRLEN dlen;
2501 9 const char *data = SvPV(data_sv, dlen);
2502 9 gm_check_size(aTHX_ dlen); /* parity with submit/epoch */
2503 8 ev_gm_req_t *r = alloc_req(CB_ECHO, cb_sv);
2504 8 enqueue_packet(aTHX_ self, GM_CMD_ECHO_REQ, data, dlen, r);
2505 }
2506  
2507 void
2508 _submit_internal(EV::Gearman self, int cmd_idx, SV *func_sv, SV *workload_sv, SV *unique_sv, SV *opts_sv, SV *cb_sv)
2509 CODE:
2510 {
2511 /* cmd_idx mapping: 0=submit_job, 1=high, 2=low,
2512 3=submit_job_bg, 4=high_bg, 5=low_bg */
2513 static const uint32_t cmd_map[] = {
2514 GM_CMD_SUBMIT_JOB, GM_CMD_SUBMIT_JOB_HIGH, GM_CMD_SUBMIT_JOB_LOW,
2515 GM_CMD_SUBMIT_JOB_BG, GM_CMD_SUBMIT_JOB_HIGH_BG, GM_CMD_SUBMIT_JOB_LOW_BG
2516 };
2517 3 ▶ if (cmd_idx < 0 || cmd_idx > 5) croak("invalid submit cmd index");
Branch: 2 branches
BranchTrueFalseTotal
if (cmd_idx < 0 || cmd_idx > 5) croak("invalid submit cmd index"); 3 0 3
if (cmd_idx < 0 || cmd_idx > 5) croak("invalid submit cmd index"); 0 3 3
2518 3 ▶ GM_CROAK_UNLESS_ALIVE(self);
Branch: 4 branches
BranchTrueFalseTotal
GM_CROAK_UNLESS_ALIVE(self); 1 2 3
GM_CROAK_UNLESS_ALIVE(self); 0 1 1
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
2519 3 int is_bg = (cmd_idx >= 3);
2520  
2521 3 STRLEN flen, wlen, ulen = 0;
2522 3 ▶ const char *fname = SvPV(func_sv, flen);
Branch: 1 branch
BranchTrueFalseTotal
const char *fname = SvPV(func_sv, flen); 3 0 3
2523 3 const char *wload = SvPV(workload_sv, wlen);
2524 3 const char *uniq = "";
2525 3 ▶ if (SvOK(unique_sv)) uniq = SvPV(unique_sv, ulen);
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(unique_sv)) uniq = SvPV(unique_sv, ulen); 0 3 3
2526  
2527 /* Validate the eventual body size (3 args + 2 NUL separators)
2528 before allocating anything, so the croak can't leak r/body. */
2529 3 gm_check_size(aTHX_ flen + ulen + wlen + 2);
2530  
2531 2 ▶ ev_gm_req_t *r = alloc_req(is_bg ? CB_SUBMIT_BG : CB_SUBMIT, cb_sv);
Branch: 1 branch
BranchTrueFalseTotal
ev_gm_req_t *r = alloc_req(is_bg ? CB_SUBMIT_BG : CB_SUBMIT, cb_sv); 0 2 2
2532  
2533 /* Optional callback bundle for foreground (opts_sv may be hashref) */
2534 2 ▶ if (!is_bg && SvROK(opts_sv) && SvTYPE(SvRV(opts_sv)) == SVt_PVHV) {
Branch: 3 branches
BranchTrueFalseTotal
if (!is_bg && SvROK(opts_sv) && SvTYPE(SvRV(opts_sv)) == SVt_PVHV) { 2 0 2
if (!is_bg && SvROK(opts_sv) && SvTYPE(SvRV(opts_sv)) == SVt_PVHV) { 0 2 2
if (!is_bg && SvROK(opts_sv) && SvTYPE(SvRV(opts_sv)) == SVt_PVHV) { 0 0 0
2535 0 HV *opts = (HV *)SvRV(opts_sv);
2536 SV **v;
2537 0 ▶ if ((v = hv_fetchs(opts, "on_data", 0)) && SvROK(*v)) r->on_data = newSVsv(*v);
Branch: 2 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "on_data", 0)) && SvROK(*v)) r->on_data = newSVsv(*v); 0 0 0
if ((v = hv_fetchs(opts, "on_data", 0)) && SvROK(*v)) r->on_data = newSVsv(*v); 0 0 0
2538 0 ▶ if ((v = hv_fetchs(opts, "on_warning", 0)) && SvROK(*v)) r->on_warning = newSVsv(*v);
Branch: 2 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "on_warning", 0)) && SvROK(*v)) r->on_warning = newSVsv(*v); 0 0 0
if ((v = hv_fetchs(opts, "on_warning", 0)) && SvROK(*v)) r->on_warning = newSVsv(*v); 0 0 0
2539 0 ▶ if ((v = hv_fetchs(opts, "on_status", 0)) && SvROK(*v)) r->on_status = newSVsv(*v);
Branch: 2 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "on_status", 0)) && SvROK(*v)) r->on_status = newSVsv(*v); 0 0 0
if ((v = hv_fetchs(opts, "on_status", 0)) && SvROK(*v)) r->on_status = newSVsv(*v); 0 0 0
2540 0 ▶ if ((v = hv_fetchs(opts, "on_exception", 0)) && SvROK(*v)) r->on_exception = newSVsv(*v);
Branch: 2 branches
BranchTrueFalseTotal
if ((v = hv_fetchs(opts, "on_exception", 0)) && SvROK(*v)) r->on_exception = newSVsv(*v); 0 0 0
if ((v = hv_fetchs(opts, "on_exception", 0)) && SvROK(*v)) r->on_exception = newSVsv(*v); 0 0 0
2541 }
2542  
2543 2 const char *ptrs[3] = { fname, uniq, wload };
2544 2 STRLEN lens[3] = { flen, ulen, wlen };
2545 size_t blen;
2546 2 char *body = gm_encode_args(3, ptrs, lens, &blen);
2547 2 enqueue_packet(aTHX_ self, cmd_map[cmd_idx], body, blen, r);
2548 2 Safefree(body);
2549 }
2550  
2551 void
2552 _submit_epoch(EV::Gearman self, SV *func_sv, SV *workload_sv, SV *unique_sv, UV epoch, SV *cb_sv)
2553 CODE:
2554 {
2555 2 ▶ GM_CROAK_UNLESS_ALIVE(self);
Branch: 4 branches
BranchTrueFalseTotal
GM_CROAK_UNLESS_ALIVE(self); 0 2 2
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
2556 2 STRLEN flen, wlen, ulen = 0;
2557 2 ▶ const char *fname = SvPV(func_sv, flen);
Branch: 1 branch
BranchTrueFalseTotal
const char *fname = SvPV(func_sv, flen); 2 0 2
2558 2 const char *wload = SvPV(workload_sv, wlen);
2559 2 const char *uniq = "";
2560 3 ▶ if (SvOK(unique_sv)) uniq = SvPV(unique_sv, ulen);
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(unique_sv)) uniq = SvPV(unique_sv, ulen); 1 1 2
2561  
2562 char epoch_buf[32];
2563 2 int epoch_len = snprintf(epoch_buf, sizeof(epoch_buf), "%lu", (unsigned long)epoch);
2564  
2565 /* Validate body size (4 args + 3 NUL separators) before allocating. */
2566 2 gm_check_size(aTHX_ flen + ulen + (STRLEN)epoch_len + wlen + 3);
2567  
2568 2 ev_gm_req_t *r = alloc_req(CB_SUBMIT_BG, cb_sv);
2569  
2570 /* SUBMIT_JOB_EPOCH: FUNC\0UNIQ\0EPOCH\0DATA */
2571 2 const char *ptrs[4] = { fname, uniq, epoch_buf, wload };
2572 2 STRLEN lens[4] = { flen, ulen, (STRLEN)epoch_len, wlen };
2573 size_t blen;
2574 2 char *body = gm_encode_args(4, ptrs, lens, &blen);
2575 2 enqueue_packet(aTHX_ self, GM_CMD_SUBMIT_JOB_EPOCH, body, blen, r);
2576 2 Safefree(body);
2577 }
2578  
2579 void
2580 get_status(EV::Gearman self, SV *handle_sv, SV *cb_sv = &PL_sv_undef)
2581 CODE:
2582 {
2583 0 ▶ GM_CROAK_UNLESS_ALIVE(self);
Branch: 4 branches
BranchTrueFalseTotal
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
2584 STRLEN hlen;
2585 0 const char *h = SvPV(handle_sv, hlen);
2586 0 ev_gm_req_t *r = alloc_req(CB_GET_STATUS, cb_sv);
2587 0 enqueue_packet(aTHX_ self, GM_CMD_GET_STATUS, h, hlen, r);
2588 }
2589  
2590 void
2591 get_status_unique(EV::Gearman self, SV *unique_sv, SV *cb_sv = &PL_sv_undef)
2592 CODE:
2593 {
2594 0 ▶ GM_CROAK_UNLESS_ALIVE(self);
Branch: 4 branches
BranchTrueFalseTotal
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
2595 STRLEN ulen;
2596 0 const char *u = SvPV(unique_sv, ulen);
2597 0 ev_gm_req_t *r = alloc_req(CB_GET_STATUS_UNIQ, cb_sv);
2598 0 enqueue_packet(aTHX_ self, GM_CMD_GET_STATUS_UNIQUE, u, ulen, r);
2599 }
2600  
2601 void
2602 option(EV::Gearman self, SV *name_sv, SV *cb_sv = &PL_sv_undef)
2603 CODE:
2604 {
2605 0 ▶ GM_CROAK_UNLESS_ALIVE(self);
Branch: 4 branches
BranchTrueFalseTotal
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
2606 STRLEN nlen;
2607 0 const char *n = SvPV(name_sv, nlen);
2608 /* Track common options client-side */
2609 0 ▶ if (nlen == 10 && memcmp(n, "exceptions", 10) == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (nlen == 10 && memcmp(n, "exceptions", 10) == 0) 0 0 0
if (nlen == 10 && memcmp(n, "exceptions", 10) == 0) 0 0 0
2610 0 self->opt_exceptions = 1;
2611 0 ev_gm_req_t *r = alloc_req(CB_OPTION, cb_sv);
2612 0 enqueue_packet(aTHX_ self, GM_CMD_OPTION_REQ, n, nlen, r);
2613 }
2614  
2615 void
2616 set_client_id(EV::Gearman self, SV *id_sv)
2617 CODE:
2618 {
2619 STRLEN ilen;
2620 0 const char *id = SvPV(id_sv, ilen);
2621 0 Safefree(self->client_id);
2622 0 self->client_id = savepv(id);
2623 0 ▶ if (self->connected)
Branch: 1 branch
BranchTrueFalseTotal
if (self->connected) 0 0 0
2624 0 enqueue_packet(aTHX_ self, GM_CMD_SET_CLIENT_ID, id, ilen, NULL);
2625 }
2626  
2627 void
2628 can_do(EV::Gearman self, SV *func_sv, ...)
2629 CODE:
2630 {
2631 STRLEN flen;
2632 1 const char *fname = SvPV(func_sv, flen);
2633 1 int timeout = 0;
2634 1 ▶ if (items > 2 && SvOK(ST(2))) timeout = SvIV(ST(2));
Branch: 2 branches
BranchTrueFalseTotal
if (items > 2 && SvOK(ST(2))) timeout = SvIV(ST(2)); 0 1 1
if (items > 2 && SvOK(ST(2))) timeout = SvIV(ST(2)); 0 0 0
2635  
2636 /* Without a Perl handler the caller must use grab_job to receive
2637 jobs; the entry just records the ability so reconnect re-sends
2638 the CAN_DO. */
2639 1 ev_gm_func_t *existing = find_function(self, fname, flen);
2640 1 ▶ if (!existing) {
Branch: 1 branch
BranchTrueFalseTotal
if (!existing) { 1 0 1
2641 ev_gm_func_t *f;
2642 1 Newxz(f, 1, ev_gm_func_t);
2643 1 f->name = savepv(fname);
2644 1 f->timeout = timeout;
2645 1 ngx_queue_insert_tail(&self->functions, &f->queue);
2646 } else {
2647 0 existing->timeout = timeout;
2648 }
2649 1 send_can_do(aTHX_ self, fname, flen, timeout);
2650  
2651 /* If the worker is idle (asleep after NO_JOB), gearmand won't wake us
2652 for jobs already queued under this new ability — it only NOOPs on
2653 fresh submissions. Poll once so that backlog isn't stranded; a
2654 spurious poll is harmless (NO_JOB just re-sleeps). */
2655 1 ▶ if (self->worker_active && self->worker_sleeping) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->worker_active && self->worker_sleeping) { 1 0 1
if (self->worker_active && self->worker_sleeping) { 1 0 1
2656 1 self->worker_sleeping = 0;
2657 1 worker_continue(aTHX_ self);
2658 }
2659 }
2660  
2661 void
2662 cant_do(EV::Gearman self, SV *func_sv)
2663 CODE:
2664 {
2665 STRLEN flen;
2666 0 const char *fname = SvPV(func_sv, flen);
2667 /* Remove from registered functions */
2668 ngx_queue_t *q;
2669 0 ▶ for (q = ngx_queue_head(&self->functions); q != ngx_queue_sentinel(&self->functions); ) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = ngx_queue_head(&self->functions); q != ngx_queue_sentinel(&self->functions); ) { 0 0 0
2670 0 ev_gm_func_t *f = ngx_queue_data(q, ev_gm_func_t, queue);
2671 0 ngx_queue_t *nx = ngx_queue_next(q);
2672 0 ▶ if (strlen(f->name) == flen && memcmp(f->name, fname, flen) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (strlen(f->name) == flen && memcmp(f->name, fname, flen) == 0) { 0 0 0
if (strlen(f->name) == flen && memcmp(f->name, fname, flen) == 0) { 0 0 0
2673 0 ngx_queue_remove(q);
2674 0 cleanup_func(aTHX_ f);
2675 }
2676 0 q = nx;
2677 }
2678 0 ▶ if (self->connected)
Branch: 1 branch
BranchTrueFalseTotal
if (self->connected) 0 0 0
2679 0 enqueue_packet(aTHX_ self, GM_CMD_CANT_DO, fname, flen, NULL);
2680 }
2681  
2682 void
2683 reset_abilities(EV::Gearman self)
2684 CODE:
2685 {
2686 0 ▶ DRAIN_QUEUE_SILENT(&self->functions, ev_gm_func_t, cleanup_func);
Branch: 1 branch
BranchTrueFalseTotal
DRAIN_QUEUE_SILENT(&self->functions, ev_gm_func_t, cleanup_func); 0 0 0
2687 0 ▶ if (self->connected)
Branch: 1 branch
BranchTrueFalseTotal
if (self->connected) 0 0 0
2688 0 enqueue_packet(aTHX_ self, GM_CMD_RESET_ABILITIES, NULL, 0, NULL);
2689 }
2690  
2691 void
2692 _register_function(EV::Gearman self, SV *name_sv, SV *cb_sv, int timeout, int async)
2693 CODE:
2694 {
2695 STRLEN nlen;
2696 5 const char *name = SvPV(name_sv, nlen);
2697 5 ▶ if (!SvROK(cb_sv) || SvTYPE(SvRV(cb_sv)) != SVt_PVCV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(cb_sv) || SvTYPE(SvRV(cb_sv)) != SVt_PVCV) 5 0 5
if (!SvROK(cb_sv) || SvTYPE(SvRV(cb_sv)) != SVt_PVCV) 0 5 5
2698 0 croak("register_function: callback must be a coderef");
2699  
2700 5 ev_gm_func_t *existing = find_function(self, name, nlen);
2701 5 ▶ if (existing) {
Branch: 1 branch
BranchTrueFalseTotal
if (existing) { 0 5 5
2702 0 ▶ CLEAR_HANDLER(existing->cb);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(existing->cb); 0 0 0
2703 0 existing->cb = newSVsv(cb_sv);
2704 0 existing->async = async ? 1 : 0;
2705 0 existing->timeout = timeout;
2706 0 existing->no_cb_warned = 0;
2707 } else {
2708 ev_gm_func_t *f;
2709 5 Newxz(f, 1, ev_gm_func_t);
2710 5 f->name = savepv(name);
2711 5 f->cb = newSVsv(cb_sv);
2712 5 f->async = async ? 1 : 0;
2713 5 f->timeout = timeout;
2714 5 ngx_queue_insert_tail(&self->functions, &f->queue);
2715 }
2716  
2717 5 send_can_do(aTHX_ self, name, nlen, timeout);
2718  
2719 /* Wake an idle worker to grab the new ability's backlog (see can_do). */
2720 5 ▶ if (self->worker_active && self->worker_sleeping) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->worker_active && self->worker_sleeping) { 1 4 5
if (self->worker_active && self->worker_sleeping) { 1 0 1
2721 1 self->worker_sleeping = 0;
2722 1 worker_continue(aTHX_ self);
2723 }
2724 }
2725  
2726 void
2727 work(EV::Gearman self, ...)
2728 CODE:
2729 {
2730 /* Start (or restart) the worker GRAB loop */
2731 4 self->worker_active = 1;
2732 4 self->worker_one_shot = 0;
2733 4 ▶ if (items > 1 && SvOK(ST(1)) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1))) == SVt_PVCV) {
Branch: 4 branches
BranchTrueFalseTotal
if (items > 1 && SvOK(ST(1)) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1))) == SVt_PVCV) { 2 2 4
if (items > 1 && SvOK(ST(1)) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1))) == SVt_PVCV) { 2 0 2
if (items > 1 && SvOK(ST(1)) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1))) == SVt_PVCV) { 2 0 2
if (items > 1 && SvOK(ST(1)) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1))) == SVt_PVCV) { 2 0 2
2734 2 ▶ CLEAR_HANDLER(self->worker_on_idle);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->worker_on_idle); 0 2 2
2735 2 self->worker_on_idle = newSVsv(ST(1));
2736 }
2737 4 worker_continue(aTHX_ self);
2738 }
2739  
2740 void
2741 work_one(EV::Gearman self, SV *cb_sv = &PL_sv_undef)
2742 CODE:
2743 {
2744 0 ▶ SV *cb = (SvOK(cb_sv) && SvROK(cb_sv)) ? cb_sv : NULL;
Branch: 2 branches
BranchTrueFalseTotal
SV *cb = (SvOK(cb_sv) && SvROK(cb_sv)) ? cb_sv : NULL; 0 0 0
SV *cb = (SvOK(cb_sv) && SvROK(cb_sv)) ? cb_sv : NULL; 0 0 0
2745 0 self->worker_active = 1;
2746 0 self->worker_one_shot = 1;
2747 0 ▶ if (cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (cb) { 0 0 0
2748 0 ▶ CLEAR_HANDLER(self->worker_on_idle);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_HANDLER(self->worker_on_idle); 0 0 0
2749 0 self->worker_on_idle = newSVsv(cb);
2750 }
2751 0 worker_continue(aTHX_ self);
2752 }
2753  
2754 void
2755 work_stop(EV::Gearman self)
2756 CODE:
2757 {
2758 0 self->worker_active = 0;
2759 0 self->worker_one_shot = 0;
2760 }
2761  
2762 void
2763 grab_job(EV::Gearman self, SV *cb_sv)
2764 CODE:
2765 {
2766 0 ▶ GM_CROAK_UNLESS_ALIVE(self);
Branch: 4 branches
BranchTrueFalseTotal
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
2767 0 ▶ if (!SvROK(cb_sv) || SvTYPE(SvRV(cb_sv)) != SVt_PVCV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(cb_sv) || SvTYPE(SvRV(cb_sv)) != SVt_PVCV) 0 0 0
if (!SvROK(cb_sv) || SvTYPE(SvRV(cb_sv)) != SVt_PVCV) 0 0 0
2768 0 croak("grab_job: callback required");
2769 0 self->worker_grab_inflight = 1;
2770 0 ev_gm_req_t *r = alloc_req(CB_GRAB_JOB, cb_sv);
2771 0 enqueue_packet(aTHX_ self,
2772 0 ▶ self->worker_grab_uniq ? GM_CMD_GRAB_JOB_UNIQ : GM_CMD_GRAB_JOB,
Branch: 1 branch
BranchTrueFalseTotal
self->worker_grab_uniq ? GM_CMD_GRAB_JOB_UNIQ : GM_CMD_GRAB_JOB, 0 0 0
2773 NULL, 0, r);
2774 }
2775  
2776 void
2777 all_yours(EV::Gearman self)
2778 CODE:
2779 {
2780 0 ▶ if (self->connected)
Branch: 1 branch
BranchTrueFalseTotal
if (self->connected) 0 0 0
2781 0 enqueue_packet(aTHX_ self, GM_CMD_ALL_YOURS, NULL, 0, NULL);
2782 }
2783  
2784 void
2785 admin(EV::Gearman self, SV *cmd_sv, ...)
2786 CODE:
2787 {
2788 1 ▶ GM_CROAK_UNLESS_ALIVE(self);
Branch: 4 branches
BranchTrueFalseTotal
GM_CROAK_UNLESS_ALIVE(self); 1 0 1
GM_CROAK_UNLESS_ALIVE(self); 0 1 1
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
GM_CROAK_UNLESS_ALIVE(self); 0 0 0
2789 STRLEN clen;
2790 1 const char *cmd = SvPV(cmd_sv, clen);
2791 1 SV *cb = NULL;
2792 1 ▶ if (items > 2 && SvOK(ST(items-1)) && SvROK(ST(items-1)) && SvTYPE(SvRV(ST(items-1))) == SVt_PVCV)
Branch: 4 branches
BranchTrueFalseTotal
if (items > 2 && SvOK(ST(items-1)) && SvROK(ST(items-1)) && SvTYPE(SvRV(ST(items-1))) == SVt_PVCV) 1 0 1
if (items > 2 && SvOK(ST(items-1)) && SvROK(ST(items-1)) && SvTYPE(SvRV(ST(items-1))) == SVt_PVCV) 1 0 1
if (items > 2 && SvOK(ST(items-1)) && SvROK(ST(items-1)) && SvTYPE(SvRV(ST(items-1))) == SVt_PVCV) 1 0 1
if (items > 2 && SvOK(ST(items-1)) && SvROK(ST(items-1)) && SvTYPE(SvRV(ST(items-1))) == SVt_PVCV) 1 0 1
2793 1 cb = ST(items-1);
2794  
2795 /* Multi-line admin commands terminate with ".\n"; single-line ones
2796 don't (gearmand 1.1.21):
2797 multi-line: status, workers, prioritystatus — arguments are
2798 ignored by the server and the reply stays
2799 multi-line, so these match on the leading word;
2800 "show jobs", "show unique jobs" — no-argument
2801 forms only (with extra arguments the server
2802 answers a single-line ERR UNKNOWN_SHOW_ARGUMENTS,
2803 so they must only match exactly);
2804 single-line: version, getpid, verbose, maxqueue F N,
2805 cancel job H, create function, drop function, and
2806 anything unrecognized (a one-line ERR). */
2807 1 int multi = 0;
2808 /* Strip trailing whitespace for matching */
2809 1 size_t cl = clen;
2810 1 ▶ while (cl > 0 && (cmd[cl-1] == '\n' || cmd[cl-1] == ' ' || cmd[cl-1] == '\t' || cmd[cl-1] == '\r'))
Branch: 5 branches
BranchTrueFalseTotal
while (cl > 0 && (cmd[cl-1] == '\n' || cmd[cl-1] == ' ' || cmd[cl-1] == '\t' || cmd[cl-1] == '\r')) 1 0 1
while (cl > 0 && (cmd[cl-1] == '\n' || cmd[cl-1] == ' ' || cmd[cl-1] == '\t' || cmd[cl-1] == '\r')) 0 1 1
while (cl > 0 && (cmd[cl-1] == '\n' || cmd[cl-1] == ' ' || cmd[cl-1] == '\t' || cmd[cl-1] == '\r')) 0 1 1
while (cl > 0 && (cmd[cl-1] == '\n' || cmd[cl-1] == ' ' || cmd[cl-1] == '\t' || cmd[cl-1] == '\r')) 0 1 1
while (cl > 0 && (cmd[cl-1] == '\n' || cmd[cl-1] == ' ' || cmd[cl-1] == '\t' || cmd[cl-1] == '\r')) 0 1 1
2811 0 cl--;
2812 /* leading-word match with a word boundary, so "status quo" counts
2813 but "statusquo" does not */
2814 #define GM_ADMIN_WORD(c, l, w) \
2815 (l >= sizeof(w) - 1 && memcmp(c, w, sizeof(w) - 1) == 0 && \
2816 (l == sizeof(w) - 1 || c[sizeof(w) - 1] == ' ' || c[sizeof(w) - 1] == '\t'))
2817 1 ▶ multi = GM_ADMIN_WORD(cmd, cl, "status")
Branch: 4 branches
BranchTrueFalseTotal
multi = GM_ADMIN_WORD(cmd, cl, "status") 0 1 1
multi = GM_ADMIN_WORD(cmd, cl, "status") 0 0 0
multi = GM_ADMIN_WORD(cmd, cl, "status") 0 0 0
multi = GM_ADMIN_WORD(cmd, cl, "status") 0 0 0
2818 1 ▶ || GM_ADMIN_WORD(cmd, cl, "workers")
Branch: 5 branches
BranchTrueFalseTotal
|| GM_ADMIN_WORD(cmd, cl, "workers") 1 0 1
|| GM_ADMIN_WORD(cmd, cl, "workers") 0 1 1
|| GM_ADMIN_WORD(cmd, cl, "workers") 0 0 0
|| GM_ADMIN_WORD(cmd, cl, "workers") 0 0 0
|| GM_ADMIN_WORD(cmd, cl, "workers") 0 0 0
2819 1 ▶ || GM_ADMIN_WORD(cmd, cl, "prioritystatus")
Branch: 5 branches
BranchTrueFalseTotal
|| GM_ADMIN_WORD(cmd, cl, "prioritystatus") 0 1 1
|| GM_ADMIN_WORD(cmd, cl, "prioritystatus") 0 0 0
|| GM_ADMIN_WORD(cmd, cl, "prioritystatus") 0 0 0
|| GM_ADMIN_WORD(cmd, cl, "prioritystatus") 0 0 0
|| GM_ADMIN_WORD(cmd, cl, "prioritystatus") 0 0 0
2820 1 ▶ || (cl == 9 && memcmp(cmd, "show jobs", 9) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (cl == 9 && memcmp(cmd, "show jobs", 9) == 0) 0 1 1
|| (cl == 9 && memcmp(cmd, "show jobs", 9) == 0) 0 0 0
2821 2 ▶ || (cl == 16 && memcmp(cmd, "show unique jobs", 16) == 0);
Branch: 3 branches
BranchTrueFalseTotal
|| (cl == 16 && memcmp(cmd, "show unique jobs", 16) == 0); 1 0 1
|| (cl == 16 && memcmp(cmd, "show unique jobs", 16) == 0); 0 1 1
|| (cl == 16 && memcmp(cmd, "show unique jobs", 16) == 0); 0 0 0
2822 #undef GM_ADMIN_WORD
2823  
2824 /* Build full text command (must end in \n) */
2825 char *txt;
2826 size_t txt_len;
2827 1 ▶ int has_nl = (clen > 0 && cmd[clen-1] == '\n');
Branch: 2 branches
BranchTrueFalseTotal
int has_nl = (clen > 0 && cmd[clen-1] == '\n'); 1 0 1
int has_nl = (clen > 0 && cmd[clen-1] == '\n'); 0 1 1
2828 1 txt_len = clen + (has_nl ? 0 : 1);
2829 1 Newx(txt, txt_len, char);
2830 1 memcpy(txt, cmd, clen);
2831 1 ▶ if (!has_nl) txt[txt_len - 1] = '\n';
Branch: 1 branch
BranchTrueFalseTotal
if (!has_nl) txt[txt_len - 1] = '\n'; 1 0 1
2832  
2833 1 ev_gm_req_t *r = alloc_req(CB_ADMIN, cb);
2834 1 r->admin_terminator = multi;
2835  
2836 /* submit_bytes takes ownership of txt and Safefrees it. */
2837 1 submit_bytes(aTHX_ self, txt, txt_len, r);
2838 }
2839  
2840 int
2841 connect_timeout(EV::Gearman self, ...)
2842 CODE:
2843 {
2844 0 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 0 0 0
2845 0 self->connect_timeout_ms = SvIV(ST(1));
2846 0 ▶ if (self->connect_timeout_ms < 0) self->connect_timeout_ms = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_timeout_ms < 0) self->connect_timeout_ms = 0; 0 0 0
2847 }
2848 0 ▶ RETVAL = self->connect_timeout_ms;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->connect_timeout_ms; 0 0 0
2849 }
2850 OUTPUT:
2851 RETVAL
2852  
2853 int
2854 command_timeout(EV::Gearman self, ...)
2855 CODE:
2856 {
2857 0 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 0 0 0
2858 0 self->command_timeout_ms = SvIV(ST(1));
2859 0 ▶ if (self->command_timeout_ms < 0) self->command_timeout_ms = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->command_timeout_ms < 0) self->command_timeout_ms = 0; 0 0 0
2860 0 ▶ if (self->command_timeout_ms == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (self->command_timeout_ms == 0) 0 0 0
2861 0 disarm_cmd_timer(self);
2862 0 ▶ else if (!ngx_queue_empty(&self->cb_queue))
Branch: 1 branch
BranchTrueFalseTotal
else if (!ngx_queue_empty(&self->cb_queue)) 0 0 0
2863 0 arm_cmd_timer(self);
2864 }
2865 0 ▶ RETVAL = self->command_timeout_ms;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->command_timeout_ms; 0 0 0
2866 }
2867 OUTPUT:
2868 RETVAL
2869  
2870 void
2871 reconnect(EV::Gearman self, ...)
2872 CODE:
2873 {
2874 /* Optional args: only overwrite delay / max_attempts when the
2875 caller supplies them, so reconnect(1) re-enables without
2876 resetting the values configured at construction time. */
2877 3 ▶ if (items < 2) croak("reconnect: enable arg required");
Branch: 1 branch
BranchTrueFalseTotal
if (items < 2) croak("reconnect: enable arg required"); 1 2 3
2878 2 self->reconnect = SvTRUE(ST(1)) ? 1 : 0;
2879 2 ▶ if (items > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 2) { 0 2 2
2880 0 int d = SvIV(ST(2));
2881 0 self->reconnect_delay_ms = d >= 0 ? d : 0;
2882 }
2883 2 ▶ if (items > 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 3) { 0 2 2
2884 0 int m = SvIV(ST(3));
2885 0 self->max_reconnect_attempts = m >= 0 ? m : 0;
2886 }
2887 2 ▶ if (!self->reconnect) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->reconnect) { 2 0 2
2888 2 self->reconnect_attempts = 0;
2889 2 stop_reconnect_timer(self);
2890 }
2891 }
2892  
2893 int
2894 reconnect_enabled(EV::Gearman self)
2895 CODE:
2896 0 ▶ RETVAL = self->reconnect;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->reconnect; 0 0 0
2897 OUTPUT:
2898 RETVAL
2899  
2900 int
2901 priority(EV::Gearman self, ...)
2902 CODE:
2903 {
2904 0 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 0 0 0
2905 0 self->priority = SvIV(ST(1));
2906 0 ▶ if (self->priority < -2) self->priority = -2;
Branch: 1 branch
BranchTrueFalseTotal
if (self->priority < -2) self->priority = -2; 0 0 0
2907 0 ▶ if (self->priority > 2) self->priority = 2;
Branch: 1 branch
BranchTrueFalseTotal
if (self->priority > 2) self->priority = 2; 0 0 0
2908 0 ▶ if (self->reading) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reading) { 0 0 0
2909 0 ev_io_stop(self->loop, &self->rio);
2910 0 ev_set_priority(&self->rio, self->priority);
2911 0 ev_io_start(self->loop, &self->rio);
2912 } else {
2913 0 ev_set_priority(&self->rio, self->priority);
2914 }
2915 0 ▶ if (self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->writing) { 0 0 0
2916 0 ev_io_stop(self->loop, &self->wio);
2917 0 ev_set_priority(&self->wio, self->priority);
2918 0 ev_io_start(self->loop, &self->wio);
2919 } else {
2920 0 ev_set_priority(&self->wio, self->priority);
2921 }
2922 }
2923 0 ▶ RETVAL = self->priority;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->priority; 0 0 0
2924 }
2925 OUTPUT:
2926 RETVAL
2927  
2928 int
2929 keepalive(EV::Gearman self, ...)
2930 CODE:
2931 {
2932 0 ▶ if (items > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items > 1) { 0 0 0
2933 0 self->keepalive = SvIV(ST(1));
2934 0 ▶ if (self->keepalive < 0) self->keepalive = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->keepalive < 0) self->keepalive = 0; 0 0 0
2935 0 ▶ if (self->connected && self->fd >= 0)
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected && self->fd >= 0) 0 0 0
if (self->connected && self->fd >= 0) 0 0 0
2936 0 apply_keepalive(self);
2937 }
2938 0 ▶ RETVAL = self->keepalive;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->keepalive; 0 0 0
2939 }
2940 OUTPUT:
2941 RETVAL
2942  
2943 # ===== Job object methods (called from Perl via $job->complete etc.) =====
2944  
2945 MODULE = EV::Gearman PACKAGE = EV::Gearman::Job
2946  
2947 void
2948 _send_event(SV *job_sv, int kind, SV *data_sv = &PL_sv_undef)
2949 CODE:
2950 {
2951 /* kind: 0=complete, 1=fail, 2=exception, 3=data, 4=warning */
2952 STRLEN hl;
2953 const char *h;
2954 3 ev_gm_t *self = job_resolve(aTHX_ job_sv, &h, &hl, "_send_event");
2955  
2956 3 STRLEN dl = 0;
2957 6 ▶ const char *dp = SvOK(data_sv) ? SvPV(data_sv, dl) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
const char *dp = SvOK(data_sv) ? SvPV(data_sv, dl) : NULL; 3 0 3
2958  
2959 static const uint32_t cmds[] = {
2960 GM_CMD_WORK_COMPLETE, GM_CMD_WORK_FAIL, GM_CMD_WORK_EXCEPTION,
2961 GM_CMD_WORK_DATA, GM_CMD_WORK_WARNING,
2962 };
2963 3 ▶ if (kind < 0 || kind >= (int)(sizeof(cmds)/sizeof(cmds[0])))
Branch: 2 branches
BranchTrueFalseTotal
if (kind < 0 || kind >= (int)(sizeof(cmds)/sizeof(cmds[0]))) 3 0 3
if (kind < 0 || kind >= (int)(sizeof(cmds)/sizeof(cmds[0]))) 0 3 3
2964 0 croak("_send_event: unknown kind %d", kind);
2965  
2966 /* WORK_FAIL takes no data; the rest take handle\0data even if data
2967 is empty (the trailing NUL is the separator, not a terminator). */
2968 6 ▶ send_work_event(aTHX_ self, cmds[kind], h, hl,
Branch: 1 branch
BranchTrueFalseTotal
send_work_event(aTHX_ self, cmds[kind], h, hl, 3 0 3
2969 3 ▶ kind == 1 ? NULL : (dp ? dp : ""), dl);
Branch: 1 branch
BranchTrueFalseTotal
kind == 1 ? NULL : (dp ? dp : ""), dl); 3 0 3
2970 }
2971  
2972 void
2973 _send_status(SV *job_sv, SV *num_sv, SV *denom_sv)
2974 CODE:
2975 {
2976 STRLEN hl;
2977 const char *h;
2978 0 ev_gm_t *self = job_resolve(aTHX_ job_sv, &h, &hl, "_send_status");
2979  
2980 STRLEN nl, dl;
2981 0 ▶ const char *n = SvPV(num_sv, nl);
Branch: 1 branch
BranchTrueFalseTotal
const char *n = SvPV(num_sv, nl); 0 0 0
2982 0 const char *d = SvPV(denom_sv, dl);
2983 0 const char *ptrs[3] = { h, n, d };
2984 0 STRLEN lens[3] = { hl, nl, dl };
2985 size_t blen;
2986 0 char *body = gm_encode_args(3, ptrs, lens, &blen);
2987 0 enqueue_packet(aTHX_ self, GM_CMD_WORK_STATUS, body, blen, NULL);
2988 0 Safefree(body);
2989 }
2990  
« blib/lib/EV/Gearman/Job.pm ↑ Summary