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