blib/lib/EV/Gearman.pm

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