blib/lib/EV/Gearman.pm

filter: Statementstmt 80.8% 55 / 68 Branchbran 41.6% 10 / 24 Conditioncond 33.3% 6 / 18 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 81.2% 13 / 16 Podpod 100% 4 / 4 totaltotal 61.9% 88 / 142 CC 19 SCAR 21.8
CC
19
Cov
65%
register_function
24.8
_opts_cb
7.5
submit_job_epoch
6.0
CRAP 8.8
↑ Summary blib/lib/EV/Gearman/Job.pm »
1 package EV::Gearman;
2 20 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 20 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 20 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
5 20 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 20 ▶use EV::Gearman::Job ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 BEGIN {
9 20 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 20 ▶ our $VERSION = '0.01';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 20 XSLoader::load __PACKAGE__, $VERSION;
12 }
13  
14 # ===== Submit-job dispatch wrappers =====
15 #
16 # Public form:
17 # $g->submit_job($func, $workload [, \%opts] [, $cb])
18 # $g->submit_job_high($func, $workload [, \%opts] [, $cb])
19 # $g->submit_job_low($func, $workload [, \%opts] [, $cb])
20 # $g->submit_job_bg($func, $workload [, \%opts] [, $cb])
21 # $g->submit_job_high_bg(...)
22 # $g->submit_job_low_bg(...)
23  
24 # Strip an optional trailing \%opts and \&cb in either order.
25 sub _opts_cb {
26 1 ▶ my $opts = (@_ && ref $_[0] eq 'HASH') ? shift : undef;
Subroutine _opts_cb: called CC=5 SCAR=20.1
Branch: 1 branch
BranchTrueFalseTotal
@_ && ref $_[0] eq 'HASH' ? : 0 1 1
Condition33%1/3
@_ and ref $_[0] eq "HASH"
!ll&&!rl&&r
010
MC/DC0%0/2
@_ and ref $_[0] eq "HASH"
@_ ref $_[0] eq "HASH"
Truth table33%1/3
A and B
A= @_B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
27 1 ▶ my $cb = (@_ && ref $_[0] eq 'CODE') ? shift : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ && ref $_[0] eq 'CODE' ? : 1 0 1
Condition33%1/3
@_ and ref $_[0] eq "CODE"
!ll&&!rl&&r
001
MC/DC0%0/2
@_ and ref $_[0] eq "CODE"
@_ ref $_[0] eq "CODE"
Truth table33%1/3
A and B
A= @_B= ref $_[0] eq "CODE"
ABresult
0X0
100
111
28 1 ($opts, $cb);
29 }
30  
31 sub _build_submitter {
32 120 ▶ my ($cmd_idx) = @_;
Subroutine _build_submitter: called CC=1 SCAR=0.0
33 return sub {
34 1 ▶ my $self = shift;
Subroutine __ANON__: called CC=2 SCAR=7.0
35 1 my $func = shift;
36 1 my $workload = shift;
37 1 my ($opts, $cb) = _opts_cb(@_);
38 1 ▶ my $unique = $opts ? $opts->{unique} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$opts ? : 0 1 1
39 1 $self->_submit_internal($cmd_idx, $func, $workload, $unique, $opts, $cb);
40 120 };
41 }
42  
43 20 *submit_job = _build_submitter(0);
44 20 *submit_job_high = _build_submitter(1);
45 20 *submit_job_low = _build_submitter(2);
46 20 *submit_job_bg = _build_submitter(3);
47 20 *submit_job_high_bg = _build_submitter(4);
48 20 *submit_job_low_bg = _build_submitter(5);
49  
50 sub submit_job_epoch {
51 0 ▶ my ($self, $func, $workload, $epoch) = (shift, shift, shift, shift);
Subroutine submit_job_epoch: not called CC=2 SCAR=17.9
Pod documented
52 0 my ($opts, $cb) = _opts_cb(@_);
53 0 ▶ my $unique = $opts ? $opts->{unique} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$opts ? : 0 0 0
54 0 $self->_submit_epoch($func, $workload, $unique, $epoch, $cb);
55 }
56  
57 sub register_function {
58 2 ▶ my $self = shift;
Subroutine register_function: called CC=8 SCAR=32.1
Pod documented
59 2 my $name = shift;
60 2 ▶ my $opts = (@_ && ref $_[0] eq 'HASH') ? shift : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ && ref $_[0] eq 'HASH' ? : 0 2 2
Condition66%2/3
@_ and ref $_[0] eq "HASH"
!ll&&!rl&&r
110
MC/DC0%0/2
@_ and ref $_[0] eq "HASH"
@_ ref $_[0] eq "HASH"
Truth table66%2/3
A and B
A= @_B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
61 2 my $cb = shift;
62 2 ▶ Carp::croak("register_function: callback required") unless ref $cb eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 2 0 2
63 0 ▶ my $timeout = $opts && $opts->{timeout} ? int $opts->{timeout} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts && $opts->{'timeout'} ? : 0 0 0
Condition0%0/3
$opts and $opts->{"timeout"}
!ll&&!rl&&r
000
MC/DC0%0/2
$opts and $opts->{"timeout"}
$opts $opts->{"timeout"}
Truth table0%0/3
A and B
A= $optsB= $opts->{"timeout"}
ABresult
0X0
100
111
64 0 ▶ my $async = $opts && $opts->{async} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts && $opts->{'async'} ? : 0 0 0
Condition0%0/3
$opts and $opts->{"async"}
!ll&&!rl&&r
000
MC/DC0%0/2
$opts and $opts->{"async"}
$opts $opts->{"async"}
Truth table0%0/3
A and B
A= $optsB= $opts->{"async"}
ABresult
0X0
100
111
65 0 $self->_register_function($name, $cb, $timeout, $async);
66 }
67  
68 {
69 20 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
70 20 *unregister_function = \&cant_do;
71 20 for my $cmd (qw(status workers version)) {
72 0 ▶ *{"server_$cmd"} = sub { my $self = shift; $self->admin($cmd, @_) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
73 }
74 }
75  
76 sub maxqueue {
77 4 ▶ my ($self, $func, $size, $cb) = @_;
Subroutine maxqueue: called CC=5 SCAR=16.6
Pod documented
78 # $func and $size are interpolated into a newline-delimited text
79 # command, so whitespace/newlines could inject a second admin
80 # command. Validate both.
81 4 ▶ Carp::croak("maxqueue: function name required") unless defined $func;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $func 1 3 4
82 3 ▶ Carp::croak("maxqueue: function name may not contain whitespace")
Branch: 1 branch
BranchTrueFalseTotal
if $func =~ /\s/ 1 2 3
83 if $func =~ /\s/;
84 2 ▶ Carp::croak("maxqueue: size must be a non-negative integer")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size and $size =~ /\A[0-9]+\z/ 2 0 2
Condition66%2/3
defined $size and $size =~ /\A[0-9]+\z/
!ll&&!rl&&r
110
MC/DC0%0/2
defined $size and $size =~ /\A[0-9]+\z/
defined $size $size =~ /\A[0-9]+\z/
Truth table66%2/3
A and B
A= defined $sizeB= $size =~ /\A[0-9]+\z/
ABresult
0X0
100
111
85 unless defined($size) && $size =~ /\A[0-9]+\z/;
86 0 $self->admin("maxqueue $func $size", $cb);
87 }
88  
89 sub shutdown_server {
90 0 ▶ my ($self, %opts) = @_;
Subroutine shutdown_server: not called CC=2 SCAR=17.9
Pod documented
91 0 ▶ my $graceful = $opts{graceful} ? ' graceful' : '';
Branch: 1 branch
BranchTrueFalseTotal
$opts{'graceful'} ? : 0 0 0
92 0 $self->admin("shutdown$graceful", $opts{cb});
93 }
94  
95 20 1;
96  
97 =encoding utf8
98  
99 =head1 NAME
100  
101 EV::Gearman - asynchronous Gearman client and worker on libev
102  
103 =head1 SYNOPSIS
104  
105 use EV;
106 use EV::Gearman;
107  
108 # ----- client -----
109 my $cli = EV::Gearman->new(host => '127.0.0.1', port => 4730);
110  
111 # foreground job: callback fires once on WORK_COMPLETE / WORK_FAIL,
112 # after any number of intermediate WORK_DATA / WORK_STATUS events
113 $cli->submit_job(reverse => 'hello', sub {
114 my ($result, $err) = @_;
115 die "job failed: $err" if $err;
116 print "got: $result\n"; # "olleh"
117 EV::break;
118 });
119  
120 # foreground job with progress events
121 $cli->submit_job(crunch => $payload, {
122 unique => 'job-key', # de-duplicate identical jobs
123 on_data => sub { print "partial: $_[0]\n" },
124 on_status => sub { printf "%d/%d\n", @_ },
125 on_warning => sub { warn "worker warning: $_[0]" },
126 }, sub {
127 my ($result, $err) = @_;
128 ...
129 });
130  
131 # background job: callback fires once on JOB_CREATED with handle
132 $cli->submit_job_bg('mail::send', $payload, sub {
133 my ($handle, $err) = @_;
134 warn "queued: $handle\n";
135 });
136  
137 # ----- worker -----
138 my $w = EV::Gearman->new(
139 host => '127.0.0.1',
140 port => 4730,
141 client_id => "worker-$$",
142 reconnect => 1,
143 );
144  
145 # synchronous worker: return value -> WORK_COMPLETE; die -> WORK_FAIL
146 $w->register_function(reverse => sub {
147 my ($job) = @_; # EV::Gearman::Job
148 return scalar reverse $job->workload;
149 });
150  
151 # asynchronous worker: defer completion via a timer / external IO
152 $w->register_function(slow => { async => 1 }, sub {
153 my $job = shift;
154 my $t; $t = EV::timer 5, 0, sub { $job->complete("done"); undef $t };
155 });
156  
157 $w->work; # GRAB → JOB_ASSIGN → WORK_COMPLETE
158 EV::run;
159  
160 =head1 DESCRIPTION
161  
162 A pure-XS Gearman client and worker built on the L<EV> event loop.
163 The binary protocol is implemented directly — no C<libgearman> build
164 dependency, no glue layer between Perl and a third-party C client.
165  
166 A single C<EV::Gearman> instance can act as a client, a worker, or
167 both: foreground submissions and worker C<GRAB_JOB> packets multiplex
168 over the same connection, and responses are routed by their request
169 type (head of FIFO) or by the job handle (work events). Pipelining is
170 the default, so submitting N jobs in a tight loop ships them in one
171 batched write and lets the server stream replies back at full
172 throughput.
173  
174 The text/admin protocol (C<status>, C<workers>, C<version>,
175 C<maxqueue>, C<shutdown>) shares the connection too; multi-line
176 replies are buffered to the C<".\n"> terminator and delivered as a
177 single string.
178  
179 L<AnyEvent> applications work unchanged when EV is the active
180 backend.
181  
182 =head1 PROTOCOL OVERVIEW
183  
184 The Gearman wire format is a 12-byte header followed by a payload:
185  
186 +--------+---------------+----------------+----------------+
187 | magic | command (BE) | data len (BE) | data |
188 | 4 byte | 4 bytes | 4 bytes | data len B |
189 +--------+---------------+----------------+----------------+
190 "\0REQ" uint32 uint32 NUL-separated
191 or args (last arg
192 "\0RES" unterminated)
193  
194 Foreground job lifecycle (client perspective):
195  
196 SUBMIT_JOB --> # request
197 <-- JOB_CREATED(handle) # ack
198 <-- WORK_DATA(handle, ...)* # 0..N
199 <-- WORK_WARNING(handle, ...)*
200 <-- WORK_STATUS(handle, n,d)*
201 <-- WORK_EXCEPTION(handle,..)* # if option set
202 <-- WORK_COMPLETE(handle, r) # terminal
203 -- or --
204 <-- WORK_FAIL(handle) # terminal
205  
206 The handle binds the per-job event callbacks to the right submission
207 even when many submissions are in flight at once.
208  
209 Worker lifecycle:
210  
211 CAN_DO(func) --> # advertise
212 repeat ----------------------+
213 GRAB_JOB --> |
214 <-- JOB_ASSIGN(h,fn,wl) | # got work
215 ... user callback |
216 WORK_COMPLETE(h, r) --> |
217 -------------- or -----------+
218 <-- NO_JOB |
219 PRE_SLEEP --> |
220 <-- NOOP | # wake-up
221 ----------------------------+
222  
223 C<EV::Gearman> drives that state machine in C; the per-function
224 callback only sees a ready-to-process L<EV::Gearman::Job>.
225  
226 =head1 ENCODING
227  
228 All function names, payloads, results, and handles are byte strings
229 on the wire. Encode UTF-8 yourself before passing data in:
230  
231 use Encode;
232 $cli->submit_job(reverse => encode_utf8($str), sub {
233 my $result = decode_utf8($_[0] // '');
234 ...
235 });
236  
237 Workload and result values can contain arbitrary bytes including
238 embedded NULs — Gearman's framing puts the payload last in the
239 packet and uses the header's length field, so it is not NUL-bounded.
240  
241 =head1 CALLBACK CONVENTIONS
242  
243 Every command callback receives C<($result, $err)>. On success
244 C<$err> is C<undef>; on failure C<$err> is a string like
245 C<"disconnected">, C<"job failed">, C<"command timeout">, or text
246 forwarded from the server (e.g. C<"INVALID_FUNCTION_NAME: ...">).
247  
248 Callback exceptions are caught with C<G_EVAL> and surfaced via
249 C<warn> so a stray C<die> from your code never unwinds the libev
250 event loop. Use C<EV::break> to abort the loop deliberately.
251  
252 =head1 CONSTRUCTOR
253  
254 =head2 new(%options)
255  
256 my $g = EV::Gearman->new(
257 host => '127.0.0.1',
258 port => 4730,
259 on_error => sub { warn "@_" },
260 on_connect => sub { ... },
261 on_disconnect => sub { ... },
262 connect_timeout => 5_000, # ms
263 command_timeout => 30_000, # ms
264 reconnect => 1,
265 reconnect_delay => 1000, # ms
266 keepalive => 60, # seconds (TCP only)
267 exceptions => 1, # request "exceptions" option
268 client_id => "worker-$$",
269 grab_unique => 1, # use GRAB_JOB_UNIQ
270 );
271  
272 If C<host> (or C<path>) is given, a non-blocking connect starts
273 immediately. With neither, the object is unconfigured; call
274 C<< $g->connect >> / C<< $g->connect_unix >> later.
275  
276 All keys default to C<undef> unless noted. Booleans accept any Perl
277 truthy value.
278  
279 =head3 Connection
280  
281 =over
282  
283 =item C<host =E<gt> $str>
284  
285 =item C<port =E<gt> $int>
286  
287 TCP host and port. Default port: C<4730>. Mutually exclusive with
288 C<path>.
289  
290 Name resolution is currently synchronous: a non-numeric C<host> is
291 passed straight to C<getaddrinfo>, which can block the event loop
292 for the system resolver timeout. Pass an IP literal (or pre-resolve
293 once) to keep reconnect cycles fully non-blocking.
294  
295 =item C<path =E<gt> $str>
296  
297 Unix-domain socket path. Mutually exclusive with C<host>.
298  
299 =item C<loop =E<gt> $ev_loop>
300  
301 EV loop to attach to. Default: C<EV::default_loop>.
302  
303 =item C<priority =E<gt> $num>
304  
305 EV watcher priority in C<-2 .. +2>. Higher = serviced before other
306 EV watchers in the same iteration. Default C<0>.
307  
308 =item C<keepalive =E<gt> $seconds>
309  
310 TCP keepalive idle interval. C<0> disables. Ignored on Unix sockets.
311  
312 =back
313  
314 =head3 Timeouts
315  
316 =over
317  
318 =item C<connect_timeout =E<gt> $ms>
319  
320 Abort an in-progress non-blocking connect after this many ms. C<0>
321 = no timeout (default).
322  
323 =item C<command_timeout =E<gt> $ms>
324  
325 Disconnect with C<"command timeout"> if no response arrives within
326 this interval. The timer resets on every byte received. C<0> = no
327 timeout (default).
328  
329 =back
330  
331 =head3 Reconnect
332  
333 =over
334  
335 =item C<reconnect =E<gt> $bool>
336  
337 Enable automatic reconnect on transport errors.
338  
339 =item C<reconnect_delay =E<gt> $ms>
340  
341 Wait this many ms before each reconnect attempt. Default C<1000>.
342 The delay is always honored via a timer, so even C<0> defers
343 through the event loop (no synchronous retry recursion).
344  
345 =item C<max_reconnect_attempts =E<gt> $num>
346  
347 Give up after this many consecutive failures and emit
348 C<"max reconnect attempts reached">. C<0> = unlimited (default).
349  
350 =back
351  
352 After a reconnect, all worker C<CAN_DO>/C<CAN_DO_TIMEOUT>
353 registrations and the C<exceptions> option are re-sent
354 automatically.
355  
356 =head3 Worker / option flags
357  
358 =over
359  
360 =item C<exceptions =E<gt> $bool>
361  
362 If true, the C<exceptions> option is sent on every connect, so
363 foreground clients receive C<WORK_EXCEPTION> packets. For workers,
364 this also enables forwarding C<die> messages from sync callbacks
365 as exceptions before the C<WORK_FAIL>.
366  
367 =item C<client_id =E<gt> $str>
368  
369 Sent as C<SET_CLIENT_ID> on every connect. Visible in the admin
370 C<workers> output.
371  
372 =item C<grab_unique =E<gt> $bool>
373  
374 If true, the worker GRAB loop uses C<GRAB_JOB_UNIQ>, so the job
375 object exposes the unique key supplied by the submitter.
376  
377 =back
378  
379 =head3 Event handlers
380  
381 =over
382  
383 =item C<on_error =E<gt> $cb-E<gt>($errstr)>
384  
385 Connection-level error callback. Default: C<warn>. User callbacks
386 are run under C<G_EVAL>.
387  
388 =item C<on_connect =E<gt> $cb-E<gt>()>
389  
390 Fires once the TCP/Unix connection is fully established and the
391 client has enqueued its options and worker-function CAN_DOs.
392 Those packets sit ahead of any user submissions made from inside
393 the callback — so submitting a job here is safe even though the
394 ability registrations haven't yet hit the socket.
395  
396 =item C<on_disconnect =E<gt> $cb-E<gt>()>
397  
398 Fires after a disconnect, after pending callbacks have been
399 cancelled with the disconnect error. For server-initiated close,
400 this fires before C<on_error>.
401  
402 =back
403  
404 =head1 CONNECTION
405  
406 =head2 connect($host, [$port])
407  
408 Connect to a TCP host. Port defaults to 4730. Cancels any pending
409 auto-reconnect timer and clears any prior C<path>.
410  
411 =head2 connect_unix($path)
412  
413 Connect via Unix socket.
414  
415 =head2 disconnect
416  
417 Disconnect cleanly. Cancels reconnect, drains pending callbacks
418 with C<(undef, "disconnected")>, fires C<on_disconnect>.
419 C<on_error> does B<not> fire on user-initiated disconnect — this
420 distinguishes it from server-initiated close.
421  
422 =head2 is_connected
423  
424 Returns true while a session is established B<or> connection is in
425 progress.
426  
427 =head1 CLIENT API
428  
429 =head2 echo($data, [$cb-E<gt>($echoed, $err)])
430  
431 Round-trip C<ECHO_REQ>. Useful as a ping or to verify that all
432 prior pipelined requests have been consumed.
433  
434 =head2 submit_job($func, $workload, [\%opts], [$cb])
435  
436 =head2 submit_job_high($func, $workload, [\%opts], [$cb])
437  
438 =head2 submit_job_low($func, $workload, [\%opts], [$cb])
439  
440 Foreground submission with normal / high / low priority. The
441 callback fires once on the terminal event:
442  
443 $cb->($result, undef) # WORK_COMPLETE
444 $cb->(undef, "job failed") # WORK_FAIL
445 $cb->(undef, "exception") # WORK_EXCEPTION (data via on_exception)
446 $cb->(undef, $errstr) # ERROR / disconnect
447  
448 Optional opts:
449  
450 unique => $key # de-dup / coalesce
451 on_data => $cb->($partial) # WORK_DATA
452 on_warning => $cb->($w) # WORK_WARNING
453 on_status => $cb->($num, $denom) # WORK_STATUS
454 on_exception => $cb->($exc) # WORK_EXCEPTION
455  
456 The status callback receives C<$numerator> and C<$denominator> as
457 strings, matching the wire format (Gearman doesn't constrain them
458 to integers).
459  
460 A single packet (function name + unique key + workload) is capped at
461 256 MiB; a larger submission C<croak>s before anything is sent. This
462 applies to every C<submit_job*> variant.
463  
464 =head2 submit_job_bg($func, $workload, [\%opts], [$cb])
465  
466 =head2 submit_job_high_bg($func, $workload, [\%opts], [$cb])
467  
468 =head2 submit_job_low_bg($func, $workload, [\%opts], [$cb])
469  
470 Background submission. Callback fires once on C<JOB_CREATED> with
471 C<($handle, $err)>; subsequent work events are not delivered to
472 this client. C<unique> in C<%opts> is honored; per-event handlers
473 (C<on_data>, C<on_warning>, ...) are ignored because the server
474 emits no work events to a background submitter.
475  
476 =head2 submit_job_epoch($func, $workload, $epoch, [\%opts], [$cb])
477  
478 Schedule a background job for absolute epoch time C<$epoch>
479 (seconds since 1970-01-01 UTC). Same callback shape as
480 C<submit_job_bg>: C<($handle, $err)> on C<JOB_CREATED>. Of
481 C<%opts>, only C<unique> is meaningful — the per-event handlers
482 (C<on_data>, C<on_warning>, etc.) are silently ignored because the
483 server delivers no work events to the submitting client for
484 scheduled / background jobs. Server must be built with persistent
485 queue support for scheduled jobs to survive a restart.
486  
487 =head2 get_status($handle, $cb-E<gt>($info, $err))
488  
489 Query the server about a known handle:
490  
491 $info = {
492 handle => 'H:host:1',
493 known => 0|1, # server has the job
494 running => 0|1, # a worker grabbed it
495 numerator => '42', # last reported progress
496 denominator => '100',
497 }
498  
499 =head2 get_status_unique($unique, $cb-E<gt>($info, $err))
500  
501 Status by unique key; C<$info> additionally has C<unique> and
502 C<client_count> (how many clients are listening).
503  
504 =head2 option($name, [$cb-E<gt>($ok, $err)])
505  
506 Send an C<OPTION_REQ>. The C<exceptions> option is also tracked
507 client-side so reconnects re-enable it without your help.
508  
509 =head1 WORKER API
510  
511 =head2 register_function($name, [\%opts], $cb-E<gt>($job))
512  
513 Register a worker handler for function C<$name>. Sends C<CAN_DO>
514 (or C<CAN_DO_TIMEOUT>) on the wire if connected; otherwise the
515 ability is queued and sent on connect.
516  
517 C<%opts>:
518  
519 timeout => $seconds # CAN_DO_TIMEOUT instead of CAN_DO
520 async => $bool # see below
521  
522 Sync mode (default): the callback's return value is sent as the
523 C<WORK_COMPLETE> body. C<die> becomes C<WORK_FAIL> (and
524 C<WORK_EXCEPTION> when the C<exceptions> option is on).
525  
526 Async mode: the callback's return value is ignored; you must
527 explicitly call C<< $job->complete($result) >>, C<< $job->fail >>,
528 or C<< $job->exception($data) >> from a later event. The worker
529 loop B<does> immediately grab the next job after dispatching to
530 your async callback, so async workers process jobs concurrently —
531 bounded only by what the server has queued. To cap concurrency,
532 call C<< $g->work_stop >> in the callback when you reach the cap
533 and C<< $g->work >> again from C<complete>/C<fail> when a slot
534 frees up. See C<eg/worker_pool.pl> for a worked example.
535  
536 =head2 unregister_function($name)
537  
538 Alias for C<cant_do>.
539  
540 =head2 can_do($name, [$timeout])
541  
542 Lower-level: announce ability without a Perl handler. Combine with
543 C<grab_job> to build a custom worker loop.
544  
545 =head2 cant_do($name)
546  
547 Withdraw an ability.
548  
549 =head2 reset_abilities
550  
551 Withdraw all abilities (sends C<RESET_ABILITIES>).
552  
553 =head2 set_client_id($id)
554  
555 Send C<SET_CLIENT_ID>. This is what shows up in the admin
556 C<workers> command.
557  
558 =head2 work([$on_idle])
559  
560 Activate the worker loop. Issues a C<GRAB_JOB[_UNIQ]> on the
561 wire as soon as the connection is established (deferred until
562 then if called pre-connect); on C<JOB_ASSIGN> the registered
563 function callback runs; on C<NO_JOB> the connection sleeps via
564 C<PRE_SLEEP> until the server sends C<NOOP>, then resumes
565 grabbing. C<$on_idle> fires every time the loop enters the
566 sleep state.
567  
568 =head2 work_one([$cb])
569  
570 Dispatch exactly one job, then stop the loop. Issues a
571 C<GRAB_JOB>; on C<NO_JOB> the worker enters C<PRE_SLEEP> and
572 waits for the server's C<NOOP> wake-up just like C<work>, so
573 this is a "wait for one job" — not "try once and bail" (use
574 C<grab_job> for that).
575  
576 In B<sync> mode the loop stops after the user callback returns
577 and the C<WORK_COMPLETE>/C<WORK_FAIL> packet has been queued.
578 In B<async> mode it stops as soon as the user callback has been
579 B<dispatched> — the job is still in flight at the server until
580 the user explicitly calls C<< $job->complete(...) >> or
581 C<< $job->fail >>.
582  
583 The optional C<$cb> is invoked when the worker enters the sleep
584 state, and shares storage with C<work>'s C<$on_idle> — calling
585 C<work_one> after C<work> overwrites whatever idle handler
586 C<work> set, and vice versa.
587  
588 =head2 work_stop
589  
590 Drop out of the worker loop. The connection stays up; in-flight
591 jobs continue to deliver their results, but no new C<GRAB_JOB>
592 will be sent.
593  
594 =head2 grab_job($cb)
595  
596 Lower-level: request exactly one C<GRAB_JOB[_UNIQ]>. The callback
597 gets a job object on C<JOB_ASSIGN>, or C<(undef, "no job")> on
598 C<NO_JOB>. The user is responsible for completing the job. Requires a
599 prior C<can_do> (or C<register_function>) so the server knows this
600 connection serves the function.
601  
602 Unlike the managed C<work> loop, C<grab_job> does not de-duplicate:
603 calling it again before the previous grab has been answered puts a
604 second C<GRAB_JOB> on the wire. Drive one grab at a time (issue the
605 next from the previous callback) as in F<eg/cron_consumer.pl>.
606  
607 =head2 all_yours
608  
609 Send C<ALL_YOURS>. Hint to the server that this worker handles all
610 known abilities and should be preferred for new jobs.
611  
612 =head1 ADMIN / TEXT PROTOCOL
613  
614 The Gearman text protocol shares the same TCP/Unix connection. We
615 dispatch each incoming byte stream to either the binary parser or
616 the text parser based on whether the first byte is C<\0> (binary)
617 or printable (admin). Multi-line replies are accumulated to the
618 C<".\n"> terminator and delivered as a single string.
619  
620 =head2 admin($command, [$cb-E<gt>($text, $err)])
621  
622 Send a raw text command (newline appended automatically). Replies
623 are accumulated until the C<".\n"> terminator for the multi-line
624 commands C<status>, C<workers>, and C<prioritystatus>; everything
625 else is treated as single-line.
626  
627 =head2 server_status([$cb])
628  
629 Tab-separated lines: C<FUNC \t TOTAL_JOBS \t RUNNING_JOBS \t WORKERS>.
630  
631 =head2 server_workers([$cb])
632  
633 One line per connected worker.
634  
635 =head2 server_version([$cb])
636  
637 Single-line reply (e.g. C<"OK 1.1.21+ds">).
638  
639 =head2 maxqueue($func, $size, [$cb])
640  
641 Set the per-function queue size cap. Reply is C<"OK\n">.
642  
643 =head2 shutdown_server(graceful => $bool, cb => $cb)
644  
645 Send C<shutdown> or C<shutdown graceful>. The server replies with
646 C<"OK\n"> and then closes the connection.
647  
648 =head1 INTROSPECTION
649  
650 =head2 pending_count
651  
652 Number of binary requests sent and awaiting a response.
653  
654 =head2 waiting_count
655  
656 Number of requests held in the local pre-connect queue.
657  
658 =head2 active_count
659  
660 Number of foreground jobs whose handle has been received but
661 which haven't yet completed.
662  
663 =head1 ACCESSORS
664  
665 These tunables have a getter / setter of the same name. Calling
666 without arguments reads the current value; with one argument, writes
667 and (where meaningful) takes effect immediately:
668  
669 $g->connect_timeout($ms);
670 $g->command_timeout($ms);
671 $g->priority($num);
672 $g->keepalive($seconds);
673 $g->on_error($cb); # set; pass undef to clear
674 $g->on_connect($cb);
675 $g->on_disconnect($cb);
676  
677 The remaining C<new> options (C<host>, C<port>, C<path>,
678 C<exceptions>, C<client_id>, C<grab_unique>, ...) are set once at
679 construction and have no accessor.
680  
681 C<reconnect> is the exception — it is a setter only; pass C<0>/C<1>
682 plus optional new delay and attempt cap:
683  
684 $g->reconnect($enable, [$delay_ms], [$max_attempts]);
685  
686 Omitting C<$delay_ms> / C<$max_attempts> leaves the previously
687 configured values unchanged.
688  
689 =head2 reconnect_enabled
690  
691 The getter that C<reconnect> lacks: returns true while automatic
692 reconnect is enabled, false otherwise. Takes no arguments.
693  
694 =head1 LIFECYCLE AND DESTRUCTION
695  
696 When a connection drops, the FIFO of pending requests is drained
697 with C<(undef, "disconnected")>; foreground active jobs are drained
698 with the same error. Reconnect (if enabled) re-runs the connect
699 sequence and re-registers worker abilities.
700  
701 When the C<EV::Gearman> object goes out of scope, every pending
702 and active callback fires once with C<(undef, "disconnected")>,
703 then the FD is closed. The clean-shutdown idiom is:
704  
705 $g->disconnect; # drains queues, fires on_disconnect
706 undef $g;
707  
708 If callbacks close over C<$g> (a common mistake — every reference
709 inside a closure keeps the object alive), break the cycle first:
710  
711 $g->on_error(undef);
712 $g->on_connect(undef);
713 $g->on_disconnect(undef);
714 undef $g;
715  
716 DESTROY is reentrancy-safe: if a callback fired during teardown
717 drops the last external reference to a separate C<EV::Gearman>,
718 that object's DESTROY is correctly deferred and run once unwound.
719  
720 =head1 PERFORMANCE
721  
722 Loopback benchmark on Linux, Perl 5.40, gearmand 1.1.21, single
723 worker (always L<EV::Gearman> so the worker isn't the bottleneck).
724  
725 C<bench/benchmark.pl> measures one client by itself:
726  
727 ops/sec
728 Pipelined foreground jobs ~53,000
729 Sequential round-trip ~19,000
730 Background submissions ~280,000
731  
732 C<bench/vs.pl> compares against the existing CPAN clients
733 (L<Gearman::Client> 2.004.015 sync, L<AnyEvent::Gearman> 0.10
734 async). Numbers in operations / second:
735  
736 EV::Gearman AnyEvent::Gearman Gearman::Client
737 pipelined foreground ~51,000 ~5,200 n/a (1)
738 sequential round-trip ~19,000 ~5,900 ~5,400
739 background submits ~248,000 ~5,400 n/a (1)
740  
741 (1) Gearman::Client is synchronous — it has neither pipelining
742 nor concurrent background submits.
743  
744 EV::Gearman is roughly B<10x> the foreground throughput of
745 AnyEvent::Gearman, B<45x> the background submission rate, and
746 B<3x> the sequential round-trip rate. The gap comes from three
747 places:
748  
749 =over
750  
751 =item *
752  
753 Pipelining is the default. Submitting N jobs in a tight loop
754 ships them in batched writes; responses are demultiplexed by
755 handle as they stream back. AnyEvent::Gearman is async but
756 serializes one request per round-trip, so it pays a full RTT per
757 job.
758  
759 =item *
760  
761 The protocol implementation is C/XS — packet encode/decode,
762 buffer growth, and FIFO bookkeeping run without per-call Perl
763 allocations.
764  
765 =item *
766  
767 The IO layer is direct C<ev_io> on the gearmand socket, so each
768 read/write involves no AnyEvent guard-object construction or
769 backend-dispatch overhead.
770  
771 =back
772  
773 Background submissions are particularly fast because the
774 JOB_CREATED reply is the only round-trip — no work events to
775 demultiplex — so the limit is just network latency and parser
776 throughput.
777  
778 Sequential round-trip throughput is the worst case: each job
779 waits for its own reply before the next is built, so pipelining
780 buys nothing. EV::Gearman is still ~3x faster here purely from
781 the C-side protocol parser.
782  
783 Numbers reproduce with C<bench/vs.pl> (run with C<--help> for
784 options).
785  
786 =head2 Memory
787  
788 Each connection keeps one read and one write buffer that grow on
789 demand to fit the largest packet seen. After a buffer fully drains,
790 anything that grew past ~1 MiB is released back to the initial 16 KiB,
791 so a one-off large job (or status reply) does not pin its
792 high-water-mark allocation for the life of the connection. Steady
793 small-packet traffic never reallocates.
794  
795 Pass byte strings, not Perl lists: building an N-byte payload with
796 C<join '', map chr(...), 1..$n> materializes N scalars first. For
797 large payloads use the repeat operator (C<$block x $count>) or
798 C<pack>.
799  
800 =head1 EXAMPLES
801  
802 The C<eg/> directory has runnable scripts (point them at a local
803 gearmand on C<127.0.0.1:4730>):
804  
805 =over
806  
807 =item *
808  
809 B<Clients> — C<client.pl> (one foreground job), C<pipeline.pl>
810 (concurrent submissions), C<background.pl> (fire-and-forget),
811 C<scheduled.pl> (C<submit_job_epoch> delayed jobs), C<unique.pl>
812 (job coalescing + C<get_status_unique>), C<event_client.pl>
813 (consume C<WORK_DATA>/C<WORK_STATUS>), C<fanout.pl> (scatter/gather),
814 C<priority_queue.pl>, C<json_payload.pl> (structured payloads),
815 C<retry.pl> (client-side backoff).
816  
817 =item *
818  
819 B<Workers> — C<worker.pl> (serve forever), C<async_worker.pl>
820 (timer-driven completion), C<worker_pool.pl> (concurrency cap),
821 C<graceful_worker.pl> (drain on C<SIGTERM>), C<cron_consumer.pl>
822 (C<grab_job> drain-and-exit batch), C<exceptions.pl>
823 (C<WORK_EXCEPTION> round-trip).
824  
825 =item *
826  
827 B<Operations> — C<admin.pl>, C<monitoring.pl> (poll metrics),
828 C<reconnect.pl> (survive a server bounce), C<multi_server.pl>
829 (round-robin across a farm), C<unix_socket.pl> (C<connect_unix>),
830 C<error_handling.pl>, C<anyevent.pl> (run under L<AnyEvent>).
831  
832 =back
833  
834 =head1 SEE ALSO
835  
836 L<EV>, L<AnyEvent>.
837  
838 L<Gearman::Client>, L<Gearman::Worker> — the synchronous reference
839 client and worker on CPAN.
840  
841 L<AnyEvent::Gearman> — older AE-based async client.
842  
843 L<https://gearman.org/protocol/> — the upstream protocol spec.
844  
845 This module is one of the C<EV-*> family on CPAN by the same
846 author: L<EV::Memcached>, L<EV::Redis>, L<EV::Nats>, L<EV::Pg>,
847 L<EV::ClickHouse>, L<EV::Kafka>, L<EV::MariaDB>, L<EV::cares>,
848 L<EV::Etcd>, L<EV::Websockets>.
849  
850 =head1 AUTHOR
851  
852 vividsnow
853  
854 =head1 LICENSE
855  
856 This library is free software; you can redistribute it and/or
857 modify it under the same terms as Perl itself.
858  
859 =cut
↑ Summary blib/lib/EV/Gearman/Job.pm »