blib/lib/EV/Gearman.pm

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