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