blib/lib/EV/Memcached.pm

filter: Statementstmt 100% 15 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 100% 20 / 20 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Memcached.xs ↑ Summary
1 package EV::Memcached;
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 EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 33 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
7 33 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 33 our $VERSION = '0.06';
9 33 XSLoader::load __PACKAGE__, $VERSION;
10 }
11  
12 33 1;
13  
14 =head1 NAME
15  
16 EV::Memcached - asynchronous memcached client on libev
17  
18 =head1 SYNOPSIS
19  
20 use EV;
21 use EV::Memcached;
22  
23 my $mc = EV::Memcached->new(
24 host => '127.0.0.1',
25 port => 11211,
26 on_error => sub { warn "memcached: @_" },
27 );
28  
29 $mc->set('foo', 'bar', sub {
30 my ($ok, $err) = @_;
31 warn "set failed: $err" if $err;
32  
33 $mc->get('foo', sub {
34 my ($value, $err) = @_;
35 print "foo = $value\n"; # bar
36 $mc->disconnect;
37 });
38 });
39  
40 EV::run;
41  
42 =head1 DESCRIPTION
43  
44 A pure-XS memcached client built on the L<EV> event loop. Implements the
45 memcached binary protocol directly -- no external C client library is
46 needed. All commands are non-blocking; results are delivered through
47 callbacks dispatched by the EV loop.
48  
49 Highlights:
50  
51 =over
52  
53 =item *
54  
55 Binary protocol with pipelining, multi-get via GETKQ + NOOP fence, and
56 fire-and-forget quiet variants (SETQ, FLUSHQ).
57  
58 =item *
59  
60 TCP and Unix socket transports, optional SASL PLAIN authentication
61 (automatic re-auth on reconnect).
62  
63 =item *
64  
65 Flow control via C<max_pending>, local C<waiting_queue> with optional
66 replay across reconnects, configurable connect / command / waiting
67 timeouts.
68  
69 =item *
70  
71 Predictable lifecycle: pending callbacks always fire, DESTROY is
72 reentrancy-safe across callback contexts.
73  
74 =back
75  
76 L<AnyEvent> applications can use this module unchanged, since AnyEvent
77 runs on top of EV when EV is loaded.
78  
79 Do not share a client across fork(); reconnect in the child instead.
80  
81 =head1 ENCODING
82  
83 This module treats all keys and values as byte strings. Encode UTF-8
84 strings before passing them in:
85  
86 use Encode;
87 $mc->set(foo => encode_utf8($val), sub { ... });
88 $mc->get('foo', sub {
89 my $val = decode_utf8($_[0]);
90 });
91  
92 =head1 CALLBACK CONVENTIONS
93  
94 Every command callback receives C<($result, $err)>. On success C<$err>
95 is C<undef>; on protocol error C<$err> holds a string like C<NOT_STORED>
96 or C<NOT_FOUND>. On a cache miss for C<get>/C<gat>, B<both> arguments
97 are C<undef> (a miss is not an error).
98  
99 Callback exceptions are caught with C<G_EVAL> and reported via C<warn>
100 so a stray C<die> never unwinds the libev event loop. To abort on
101 errors, set a flag and break the loop; do not rely on C<die>
102 propagating out of a callback.
103  
104 =head1 CONSTRUCTOR
105  
106 =head2 new(%options)
107  
108 Construct an instance. All options are optional; with none, the client
109 is unconfigured and you must call C<connect> / C<connect_unix> later.
110 Specifying C<host> (or C<path>) at construction time triggers an
111 immediate non-blocking connect. C<on_connect> is always delivered from
112 the event loop, never synchronously from the constructor, so installing
113 handlers right after C<new> is safe.
114  
115 my $mc = EV::Memcached->new(
116 host => '127.0.0.1',
117 port => 11211,
118 on_error => sub { warn "@_" },
119 );
120  
121 =head3 Connection
122  
123 =over
124  
125 =item host => $str
126  
127 =item port => $int (default 11211)
128  
129 TCP host and port. Mutually exclusive with C<path>. Every resolved
130 address is tried in turn. Name resolution is synchronous; prefer
131 numeric IPs.
132  
133 =item path => $str
134  
135 Unix socket path. Mutually exclusive with C<host>.
136  
137 =item loop => $ev_loop
138  
139 EV loop to attach to. Default: C<EV::default_loop>.
140  
141 =item priority => $num (-2 to +2)
142  
143 EV watcher priority. Higher = serviced before other EV watchers.
144  
145 =item keepalive => $seconds
146  
147 TCP keepalive idle time. Set to 0 to disable. Ignored on Unix sockets.
148  
149 =back
150  
151 =head3 Timeouts and flow control
152  
153 =over
154  
155 =item connect_timeout => $ms
156  
157 Abort an in-progress non-blocking connect after this many milliseconds.
158 0 = no timeout (default). Applies to any connect that does not complete
159 immediately (including unix sockets under rare kernel backlog
160 conditions); immediately-completing connects finish on the next event
161 loop iteration without arming this timer.
162  
163 =item command_timeout => $ms
164  
165 Disconnect with C<"command timeout"> error if no response arrives
166 within this interval. The timer resets on every response from the
167 server. 0 = no timeout (default).
168  
169 =item max_pending => $num
170  
171 Cap on concurrent in-flight commands. Excess commands are held in a
172 local waiting queue. 0 = unlimited (default). An C<mget>/C<mgets>
173 counts as one command against the cap and in
174 C<pending_count>/C<waiting_count>; its keys are always sent together.
175 Chunk very large key lists.
176  
177 =item waiting_timeout => $ms
178  
179 Maximum time a command may sit in the waiting queue before its callback
180 fires with C<"waiting timeout">. Expired fire-and-forget commands are
181 dropped silently. 0 = unlimited (default).
182  
183 =item resume_waiting_on_reconnect => $bool
184  
185 If true, the waiting queue survives a disconnect and is replayed on
186 reconnect. Default: false.
187  
188 =back
189  
190 =head3 Reconnect
191  
192 =over
193  
194 =item reconnect => $bool
195  
196 Enable automatic reconnection on transport errors.
197  
198 =item reconnect_delay => $ms (default 1000)
199  
200 Delay before each reconnect attempt. The delay is always honored via a
201 timer; setting it to 0 still defers through the event loop (no
202 synchronous retry recursion).
203  
204 =item max_reconnect_attempts => $num
205  
206 Give up after this many consecutive failures and emit
207 C<"max reconnect attempts reached">. 0 = unlimited (default).
208  
209 =back
210  
211 =head3 Authentication
212  
213 =over
214  
215 =item username => $str
216  
217 =item password => $str
218  
219 SASL PLAIN credentials. When both are set, the client authenticates
220 after every successful connect (and reconnect). Commands issued
221 before authentication completes sit in the waiting queue until SASL
222 finishes. Requires a memcached build with SASL support and the C<-S>
223 flag.
224  
225 =back
226  
227 =head3 Event handlers
228  
229 =over
230  
231 =item on_error => $cb->($errstr)
232  
233 Connection-level error callback. Default: write the message to
234 C<STDERR> via C<warn>. Callbacks are run under C<G_EVAL>, so any
235 C<die> in a custom handler is demoted to a warning -- use an explicit
236 flag if you need to terminate.
237  
238 =item on_connect => $cb->()
239  
240 Fires once the connection is fully established (after SASL, when
241 applicable; on SASL auth failure it never fires). Always delivered from
242 the event loop -- never synchronously from C<new> / C<connect> /
243 C<connect_unix> -- so a handler installed right after the constructor
244 still fires.
245  
246 =item on_disconnect => $cb->()
247  
248 Fires after a disconnect, after pending callbacks have been cancelled.
249 For server-initiated close, this fires before C<on_error>.
250  
251 =back
252  
253 =head1 LIFECYCLE
254  
255 =head2 connect($host, [$port])
256  
257 Connect to a TCP host. Port defaults to 11211. Stops any pending
258 auto-reconnect timer and clears any prior C<path> setting.
259  
260 =head2 connect_unix($path)
261  
262 Connect via Unix domain socket. Stops any pending auto-reconnect timer
263 and clears any prior C<host> setting.
264  
265 =head2 disconnect
266  
267 Disconnect cleanly. Cancels any pending reconnect, drains pending
268 command callbacks with C<(undef, "disconnected")>, then fires
269 C<on_disconnect> when a session exists or a connect is in progress.
270 For an intentional disconnect, C<on_error> does B<not> fire -- that
271 distinction lets you tell user-initiated teardown from server-side
272 close.
273  
274 =head2 is_connected
275  
276 Returns true while a session is established B<or> in progress (TCP
277 handshake / SASL exchange). Commands issued in the connecting phase
278 are queued and sent on completion. Commands issued while neither
279 connected nor reconnect-pending croak with C<"not connected">.
280  
281 =head2 quit([$cb])
282  
283 Send a memcached C<QUIT> and let the server close the connection.
284 Treated as an intentional disconnect: C<on_disconnect> fires when the
285 server closes, but C<on_error> does not, and auto-reconnect is
286 suppressed.
287  
288 =head1 STORAGE COMMANDS
289  
290 Each command's callback receives C<($result, $err)>. C<$result> is C<1>
291 on success.
292  
293 =head2 set($key, $value, [$expiry, [$flags,]] [$cb])
294  
295 Store unconditionally. Without C<$cb> this becomes fire-and-forget
296 (SETQ): no response is received and any server-side failure is silently
297 dropped.
298  
299 =head2 add($key, $value, [$expiry, [$flags,]] [$cb])
300  
301 Store only if the key does not exist. Errors with C<EXISTS> if
302 present (the server may append a message, e.g.
303 C<"EXISTS: Data exists for key.">).
304  
305 =head2 replace($key, $value, [$expiry, [$flags,]] [$cb])
306  
307 Store only if the key already exists. Errors with C<NOT_FOUND> if
308 absent.
309  
310 =head2 cas($key, $value, $cas, [$expiry, [$flags,]] [$cb])
311  
312 Compare-and-swap. The C<$cas> token comes from a prior C<gets> /
313 C<gats> / C<mgets>. Errors with C<EXISTS> on token mismatch or
314 C<NOT_FOUND> if the key disappeared.
315  
316 =head2 append($key, $data, [$cb])
317  
318 Append bytes to an existing value. Errors with C<NOT_STORED> if the
319 key does not exist. Without C<$cb> the result is discarded, but the
320 server still sends a response (the non-quiet opcode is used); this is
321 not fire-and-forget like C<set>.
322  
323 =head2 prepend($key, $data, [$cb])
324  
325 Prepend bytes to an existing value. Same error and discard semantics
326 as C<append>.
327  
328 =head2 delete($key, [$cb])
329  
330 Delete a key. Errors with C<NOT_FOUND> if absent.
331  
332 =head1 RETRIEVAL COMMANDS
333  
334 =head2 get($key, [$cb->($value, $err)])
335  
336 Retrieve a value. On a cache miss, both C<$value> and C<$err> are
337 C<undef> -- a miss is not an error.
338  
339 =head2 gets($key, [$cb->($info, $err)])
340  
341 Like C<get> but returns C<{ value =E<gt> ..., flags =E<gt> ..., cas =E<gt> ... }>.
342  
343 =head2 mget(\@keys, [$cb->(\%values, $err)])
344  
345 Multi-get, internally pipelined as a sequence of GETKQ packets
346 terminated by a NOOP fence. Returns a hash containing only the keys
347 that were hits:
348  
349 $mc->mget([qw(k1 k2 k3)], sub {
350 my ($values, $err) = @_;
351 # $values = { k1 => 'v1', k3 => 'v3' } # k2 was a miss
352 });
353  
354 An empty list invokes the callback synchronously with C<{}>.
355  
356 =head2 mgets(\@keys, [$cb->(\%info, $err)])
357  
358 Like C<mget> but each value carries metadata:
359  
360 $mc->mgets([qw(k1 k2)], sub {
361 my ($info, $err) = @_;
362 # $info = { k1 => { value => 'v', flags => 0, cas => 123 } }
363 });
364  
365 =head1 ATOMIC COUNTERS
366  
367 =head2 incr($key, [$delta, [$initial, [$expiry,]]] [$cb->($new_value, $err)])
368  
369 Atomic increment. C<$delta> defaults to 1. C<$expiry> defaults to
370 C<0xFFFFFFFF>, which means "do not auto-create" (the call then errors
371 with C<NOT_FOUND>). Pass any other expiry to auto-create with
372 C<$initial>:
373  
374 $mc->incr('counter', 1, sub { ... }); # require existing
375 $mc->incr('counter', 1, 100, 300, sub { ... }); # auto-create at 100, 5min TTL
376  
377 C<$new_value> is the post-increment counter value.
378  
379 =head2 decr($key, [$delta, [$initial, [$expiry,]]] [$cb->($new_value, $err)])
380  
381 Atomic decrement. Memcached clamps the result at 0 (never negative).
382 Same auto-create semantics as C<incr>.
383  
384 =head1 EXPIRATION
385  
386 =head2 touch($key, $expiry, [$cb])
387  
388 Update an existing key's expiration without fetching the value. Errors
389 with C<NOT_FOUND> if absent.
390  
391 =head2 gat($key, $expiry, [$cb->($value, $err)])
392  
393 Get-and-touch: retrieve and update expiration in one round-trip. Same
394 miss semantics as C<get>.
395  
396 =head2 gats($key, $expiry, [$cb->($info, $err)])
397  
398 Get-and-touch with metadata. Same shape as C<gets>.
399  
400 =head1 SERVER COMMANDS
401  
402 =head2 flush([$expiry,] [$cb])
403  
404 Invalidate every item. Optional delay in seconds before the flush takes
405 effect. Without C<$cb>, sent as fire-and-forget (FLUSHQ).
406  
407 =head2 noop([$cb])
408  
409 No-operation round-trip. Useful as a pipeline fence to wait until all
410 previously-sent commands have been processed.
411  
412 =head2 version([$cb->($version, $err)])
413  
414 Server version string.
415  
416 =head2 stats([$name,] [$cb->(\%stats, $err)])
417  
418 Server statistics. Without C<$name>, returns the default stats group.
419 Common groups: C<settings>, C<items>, C<sizes>, C<slabs>, C<conns>.
420  
421 =head1 AUTHENTICATION
422  
423 =head2 sasl_auth($username, $password, [$cb])
424  
425 Authenticate via SASL PLAIN. Auto-invoked on connect when both
426 C<username> and C<password> were passed to the constructor; call
427 manually only when authenticating after a no-auth construction.
428  
429 =head2 sasl_list_mechs([$cb->($mechs, $err)])
430  
431 Query the server's supported mechanisms; returns a space-separated
432 string such as C<"PLAIN">.
433  
434 =head1 LOCAL CONTROL
435  
436 =head2 skip_pending
437  
438 Drain the in-flight queue, firing every callback with
439 C<(undef, "skipped")>. Responses for skipped commands are consumed and
440 discarded when they later arrive (strict FIFO opaque matching is
441 preserved); the connection genuinely stays usable for new commands.
442  
443 =head2 skip_waiting
444  
445 Same, but for the local waiting queue (commands not yet sent).
446  
447 =head2 pending_count
448  
449 Number of commands sent and awaiting a response.
450  
451 =head2 waiting_count
452  
453 Number of commands held in the local waiting queue (because the
454 connection is not ready, SASL is in progress, or C<max_pending> is
455 saturated). Commands retain their issue order while queued.
456  
457 =head1 ACCESSORS
458  
459 The following options have a getter/setter of the same name (there are
460 no accessors for C<host>, C<port>, C<path>, C<username>, C<password>,
461 C<reconnect_delay>, C<max_reconnect_attempts>, or C<loop>). Calling
462 without arguments reads the current value; with one argument it writes
463 and (where meaningful, e.g. C<keepalive>) takes effect immediately.
464  
465 =over
466  
467 =item C<connect_timeout([$ms])>
468  
469 =item C<command_timeout([$ms])>
470  
471 =item C<max_pending([$num])>
472  
473 =item C<waiting_timeout([$ms])>
474  
475 =item C<resume_waiting_on_reconnect([$bool])>
476  
477 =item C<priority([$num])>
478  
479 =item C<keepalive([$seconds])>
480  
481 =item C<reconnect_enabled>
482  
483 Read-only; configure via C<reconnect>.
484  
485 =item C<reconnect($enable, [$delay_ms], [$max_attempts])>
486  
487 Reconfigure auto-reconnect at runtime.
488  
489 =item C<on_error([$cb])>
490  
491 =item C<on_connect([$cb])>
492  
493 =item C<on_disconnect([$cb])>
494  
495 Get/set the corresponding handler. Pass C<undef> to clear.
496  
497 =back
498  
499 =head1 DESTRUCTION
500  
501 If C<$mc> goes out of scope while commands are in flight or queued,
502 every pending and waiting callback fires once with
503 C<(undef, "disconnected")>. This holds whether you call C<disconnect>
504 first or simply drop the reference -- including dropping the B<last>
505 reference from inside one of the object's own callbacks (deferred
506 DESTROY fires the remaining callbacks before tearing down).
507  
508 The one exception is global destruction (interpreter shutdown): no
509 Perl callbacks are invoked then; queues are freed silently.
510  
511 The clean shutdown idiom is:
512  
513 $mc->disconnect; # drains queues, fires on_disconnect
514 undef $mc;
515  
516 If a callback closes over C<$mc> (a common mistake -- every reference
517 inside a callback closure keeps the object alive), break the cycle
518 before dropping the outer reference:
519  
520 $mc->on_error(undef);
521 $mc->on_connect(undef);
522 $mc->on_disconnect(undef);
523 undef $mc;
524  
525 DESTROY is reentrant-safe: if a callback fired during teardown drops
526 the last external reference to a separate C<EV::Memcached>, that
527 object's DESTROY is correctly deferred and run once unwound.
528  
529 =head1 BINARY PROTOCOL NOTES
530  
531 The wire format is the memcached binary protocol -- a 24-byte header
532 plus body, with each request tagged by an opaque field used for
533 in-flight matching and pipelining. Multi-get is sent as a run of
534 GETKQ packets ending in a NOOP fence: the server emits a response
535 only on hit, and the NOOP reply terminates the batch. Fire-and-forget
536 C<set>/C<flush> use the quiet SETQ / FLUSHQ opcodes so the server
537 sends no response at all.
538  
539 Commands that can legitimately fail (C<add>, C<replace>, C<append>,
540 C<prepend>, C<delete>, C<incr>, ...) always use the non-quiet opcode so
541 error responses are consumed by the client even when the user passed no
542 callback. Response matching is strict FIFO per connection: responses
543 must arrive in request order, so only in-order servers are supported
544 (reordering proxies are unsupported). Keys are
545 validated against the 250-byte protocol limit before any bytes go on
546 the wire.
547  
548 =head1 BENCHMARKS
549  
550 Numbers from C<bench/benchmark.pl> on Linux, TCP loopback, 100-byte
551 values, Perl 5.40, memcached 1.6.41:
552  
553 50K cmds 200K cmds
554 Pipeline SET 213K 68K ops/sec
555 Pipeline GET 216K 67K ops/sec
556 Mixed workload 226K 69K ops/sec
557 Fire-and-forget SET 1.13M 1.29M ops/sec (SETQ)
558 Multi-get (GETKQ) 1.30M 1.17M ops/sec (per key)
559 Sequential round-trip 41K 38K ops/sec
560  
561 Fire-and-forget is roughly 5x faster than callback mode because there
562 is no per-command Perl SV allocation. Multi-get is the fastest read
563 path since misses generate no traffic. Callback-mode throughput drops
564 as batch size grows because SV allocation for closures dominates;
565 realistic workloads (interleaved sends and receives) stay close to the
566 50K-command column.
567  
568 C<max_pending> overhead (100K commands, hence the faster baseline):
569  
570 unlimited ~131K ops/sec
571 max_pending=500 ~126K ops/sec
572 max_pending=100 ~120K ops/sec
573 max_pending=50 ~117K ops/sec
574  
575 Override C<BENCH_COMMANDS>, C<BENCH_VALUE_SIZE>, C<BENCH_HOST>, and
576 C<BENCH_PORT> to retune.
577  
578 =head1 SEE ALSO
579  
580 L<EV>, L<AnyEvent>, L<Cache::Memcached::Fast>, L<Memcached::Client>,
581 L<https://github.com/memcached/memcached/wiki/BinaryProtocolRevamped>.
582  
583 =head1 AUTHOR
584  
585 vividsnow
586  
587 =head1 LICENSE
588  
589 This library is free software; you can redistribute it and/or modify it
590 under the same terms as Perl itself.
591  
592 =cut
« Memcached.xs ↑ Summary