blib/lib/EV/Redis.pm

filter: Statementstmt 87.6% 57 / 65 Branchbran 43.3% 26 / 60 Conditioncond 25.0% 4 / 16 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 83.3% 10 / 12 Podpod 100% 1 / 1 totaltotal 59.7% 98 / 164 CC 37 SCAR 48.9
CC
37
Cov
62%
new
176.7
AUTOLOAD
2.0
CLONE_SKIP
2.0
CRAP 132.9
↑ Summary src/libev_adapter.h »
1 package EV::Redis;
2 30 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 30 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 30 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 30 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 30 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
9 30 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 30 our $VERSION = '0.14';
11 30 XSLoader::load __PACKAGE__, $VERSION;
12 }
13  
14 6 ▶sub new {
Subroutine new: called CC=36 SCAR=51.7
Pod documented
15 6 my ($class, %args) = @_;
16  
17 Carp::croak("Cannot specify both 'host' and 'path'")
18 6 ▶ if exists $args{host} && exists $args{path};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"host"} and exists $args{"path"} 0 6 6
Condition33%1/3
exists $args{"host"} and exists $args{"path"}
!ll&&!rl&&r
600
MC/DC0%0/2
exists $args{"host"} and exists $args{"path"}
exists $args{"host"} exists $args{"path"}
Truth table33%1/3
A and B
A= exists $args{"host"}B= exists $args{"path"}
ABresult
0X0
100
111
19 Carp::croak("Cannot specify both 'prefer_ipv4' and 'prefer_ipv6'")
20 6 ▶ if $args{prefer_ipv4} && $args{prefer_ipv6};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"prefer_ipv4"} and $args{"prefer_ipv6"} 0 6 6
Condition33%1/3
$args{"prefer_ipv4"} and $args{"prefer_ipv6"}
!ll&&!rl&&r
600
MC/DC0%0/2
$args{"prefer_ipv4"} and $args{"prefer_ipv6"}
$args{"prefer_ipv4"} $args{"prefer_ipv6"}
Truth table33%1/3
A and B
A= $args{"prefer_ipv4"}B= $args{"prefer_ipv6"}
ABresult
0X0
100
111
21  
22 6 ▶ my $loop = $args{loop} // EV::default_loop;
Condition33%1/3
$args{"loop"} // &EV::default_loop()
l!l&&r!l&&!r
060
MC/DC0%0/2
$args{"loop"} // &EV::default_loop()
$args{"loop"} &EV::default_loop()
Truth table33%1/3
A // B
A= $args{"loop"}B= &EV::default_loop()
ABresult
1X1
011
000
23 6 my $self = $class->_new($loop);
24  
25 6 ▶ $self->on_error($args{on_error} // sub { die @_ });
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$args{"on_error"} // sub { die @_; }
l!l&&r!l&&!r
060
MC/DC0%0/2
$args{"on_error"} // sub { die @_; }
$args{"on_error"} sub { die @_; }
Truth table33%1/3
A // B
A= $args{"on_error"}B= sub { die @_; }
ABresult
1X1
011
000
26 6 ▶ $self->on_connect($args{on_connect}) if exists $args{on_connect};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_connect"} 0 6 6
27 6 ▶ $self->on_disconnect($args{on_disconnect}) if exists $args{on_disconnect};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_disconnect"} 0 6 6
28 6 ▶ $self->on_push($args{on_push}) if exists $args{on_push};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_push"} 0 6 6
29 6 ▶ $self->connect_timeout($args{connect_timeout}) if defined $args{connect_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"connect_timeout"} 0 6 6
30 6 ▶ $self->command_timeout($args{command_timeout}) if defined $args{command_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"command_timeout"} 0 6 6
31 6 ▶ $self->max_pending($args{max_pending}) if defined $args{max_pending};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"max_pending"} 0 6 6
32 6 ▶ $self->waiting_timeout($args{waiting_timeout}) if defined $args{waiting_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"waiting_timeout"} 0 6 6
33 6 ▶ $self->resume_waiting_on_reconnect($args{resume_waiting_on_reconnect}) if defined $args{resume_waiting_on_reconnect};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"resume_waiting_on_reconnect"} 0 6 6
34 6 ▶ $self->priority($args{priority}) if defined $args{priority};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"priority"} 0 6 6
35 6 ▶ $self->keepalive($args{keepalive}) if defined $args{keepalive};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"keepalive"} 0 6 6
36 6 ▶ $self->prefer_ipv4($args{prefer_ipv4}) if exists $args{prefer_ipv4};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"prefer_ipv4"} 0 6 6
37 6 ▶ $self->prefer_ipv6($args{prefer_ipv6}) if exists $args{prefer_ipv6};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"prefer_ipv6"} 0 6 6
38 6 ▶ $self->source_addr($args{source_addr}) if defined $args{source_addr};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"source_addr"} 0 6 6
39 6 ▶ $self->tcp_user_timeout($args{tcp_user_timeout}) if defined $args{tcp_user_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"tcp_user_timeout"} 0 6 6
40 6 ▶ $self->cloexec($args{cloexec}) if exists $args{cloexec};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"cloexec"} 0 6 6
41 6 ▶ $self->reuseaddr($args{reuseaddr}) if exists $args{reuseaddr};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"reuseaddr"} 0 6 6
42  
43 # Configure reconnect if specified
44 6 ▶ if ($args{reconnect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"reconnect"}) 0 6 6
45 $self->reconnect(
46 1,
47 $args{reconnect_delay} // 1000,
48 0 ▶ $args{max_reconnect_attempts} // 0
Condition0%0/4
$args{"reconnect_delay"} // 1000
l!l
00
$args{"max_reconnect_attempts"} // 0
l!l
00
MC/DC0%0/1
$args{"reconnect_delay"} // 1000
$args{"reconnect_delay"}
MC/DC0%0/1
$args{"max_reconnect_attempts"} // 0
$args{"max_reconnect_attempts"}
Truth table0%0/2
A
A= $args{"reconnect_delay"}
Aresult
11
00
Truth table0%0/2
A
A= $args{"max_reconnect_attempts"}
Aresult
11
00
49 );
50 }
51  
52 # Configure TLS if specified (must be done before connect)
53 6 ▶ if ($args{tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"tls"}) 1 5 6
54 1 ▶ Carp::croak("TLS support not compiled in; rebuild with EV_REDIS_SSL=1")
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_ssl 0 1 1
55 unless $self->has_ssl;
56 Carp::croak("TLS requires 'host' parameter (not 'path')")
57 1 ▶ if exists $args{path};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"path"} 1 0 1
58 $self->_setup_ssl_context(
59 $args{tls_ca}, $args{tls_capath}, $args{tls_cert}, $args{tls_key},
60 $args{tls_server_name},
61 0 ▶ exists $args{tls_verify} ? ($args{tls_verify} ? 1 : 0) : 1,
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'tls_verify'} ? : 0 0 0
$args{'tls_verify'} ? : 0 0 0
62 );
63 }
64  
65 5 ▶ if (exists $args{host}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $args{'host'}) { } 0 5 5
elsif (exists $args{'path'}) { } 0 5 5
66 0 ▶ Carp::croak("'host' must be a defined string") unless defined $args{host};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"host"} 0 0 0
67 defined $args{port}
68 ? $self->connect($args{host}, $args{port})
69 0 ▶ : $self->connect($args{host});
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'port'} ? : 0 0 0
70 }
71 elsif (exists $args{path}) {
72 0 ▶ Carp::croak("'path' must be a defined string") unless defined $args{path};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"path"} 0 0 0
73 0 $self->connect_unix($args{path});
74 }
75  
76 5 $self;
77 }
78  
79 # The XS object is a bare C pointer; a cloned interpreter would double-free
80 # it at thread teardown.
81 0 ▶sub CLONE_SKIP { 1 }
Subroutine CLONE_SKIP: not called CC=1 SCAR=6.9
82  
83 30 our $AUTOLOAD;
84  
85 1 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=2 SCAR=6.9
86 1 (my $method = $AUTOLOAD) =~ s/.*:://;
87 1 ▶ return if $method eq 'DESTROY';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DESTROY" 0 1 1
88  
89 1 ▶ my $sub = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
90 1 my $self = shift;
91 1 $self->command($method, @_);
92 1 };
93  
94 30 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
95 1 *$method = $sub;
96 1 goto $sub;
97 }
98  
99 30 1;
100  
101 =head1 NAME
102  
103 EV::Redis - Asynchronous redis client using hiredis and EV
104  
105 =head1 SYNOPSIS
106  
107 use EV::Redis;
108
109 my $redis = EV::Redis->new;
110 $redis->connect('127.0.0.1');
111
112 # or
113 my $redis = EV::Redis->new( host => '127.0.0.1' );
114
115 # command
116 $redis->set('foo' => 'bar', sub {
117 my ($res, $err) = @_;
118
119 print $res; # OK
120
121 $redis->get('foo', sub {
122 my ($res, $err) = @_;
123
124 print $res; # bar
125
126 $redis->disconnect;
127 });
128 });
129
130 # start main loop
131 EV::run;
132  
133 =head1 DESCRIPTION
134  
135 EV::Redis is a fork of L<EV::Hiredis> by Daisuke Murase (typester),
136 extended with reconnection, flow control, TLS, and RESP3 support. It is a
137 drop-in replacement: the API is fully backward-compatible with EV::Hiredis.
138  
139 This is an asynchronous client for Redis using hiredis and L<EV> as backend.
140 It connects to L<EV> with C-level interface so that it runs faster.
141  
142 =head1 ANYEVENT INTEGRATION
143  
144 L<AnyEvent> has a support for EV as its one of backends, so L<EV::Redis> can be used in your AnyEvent applications seamlessly.
145  
146 =head1 NO UTF-8 SUPPORT
147  
148 Unlike other redis modules, this module doesn't support utf-8 string.
149  
150 This module handle all variables as bytes: command arguments are sent as
151 their byte representation regardless of Perl's internal string encoding
152 (upgraded strings are downgraded), and passing a string with characters
153 above C<0xFF> croaks with a "Wide character" error. You should encode your
154 utf-8 string before passing commands like following:
155  
156 use Encode;
157
158 # set $val
159 $redis->set(foo => encode_utf8 $val, sub { ... });
160
161 # get $val
162 $redis->get(foo, sub {
163 my $val = decode_utf8 $_[0];
164 });
165  
166 =head1 METHODS
167  
168 =head2 new(%options);
169  
170 Create new L<EV::Redis> instance.
171  
172 Available C<%options> are:
173  
174 =over
175  
176 =item * host => 'Str'
177  
178 =item * port => 'Int'
179  
180 Hostname and port number of redis-server to connect. Mutually exclusive with C<path>.
181  
182 =item * path => 'Str'
183  
184 UNIX socket path to connect. Mutually exclusive with C<host>.
185  
186 =item * on_error => $cb->($errstr)
187  
188 Error callback will be called when a connection level error occurs.
189 If not provided (or C<undef>), a default handler that calls C<die> is
190 installed. Note that exceptions thrown inside any handler (including this
191 default) are caught and reported as warnings -- they do not propagate out
192 of the event loop. In practice the default handler therefore turns
193 connection errors into warnings; install your own C<on_error> to handle
194 them programmatically. To have no error handler, call
195 C<< $obj->on_error(undef) >> after construction.
196  
197 This callback can be set by C<< $obj->on_error($cb) >> method any time.
198  
199 =item * on_connect => $cb->()
200  
201 Connection callback will be called when connection successful and completed to redis server.
202  
203 This callback can be set by C<< $obj->on_connect($cb) >> method any time.
204  
205 =item * on_disconnect => $cb->()
206  
207 Disconnect callback will be called when disconnection occurs (both normal and error cases).
208  
209 This callback can be set by C<< $obj->on_disconnect($cb) >> method any time.
210  
211 =item * on_push => $cb->($reply)
212  
213 RESP3 push callback for server-initiated out-of-band messages (Redis 6.0+).
214 Called with the decoded push message (an array reference). This enables
215 client-side caching invalidation and other server-push features.
216  
217 This callback can be set by C<< $obj->on_push($cb) >> method any time.
218  
219 =item * connect_timeout => $num_of_milliseconds
220  
221 Connection timeout.
222  
223 =item * command_timeout => $num_of_milliseconds
224  
225 Command timeout.
226  
227 =item * max_pending => $num
228  
229 Maximum number of commands sent to Redis concurrently. When this limit is reached,
230 additional commands are queued locally and sent as responses arrive.
231 0 means unlimited (default). Use C<waiting_count> to check the local queue size.
232  
233 =item * waiting_timeout => $num_of_milliseconds
234  
235 Maximum time a command can wait in the local queue before being cancelled with
236 "waiting timeout" error. 0 means unlimited (default).
237  
238 =item * resume_waiting_on_reconnect => $bool
239  
240 Controls behavior of waiting queue on disconnect. If false (default), waiting
241 commands are cancelled with error on disconnect. If true, waiting commands are
242 preserved and resumed after successful reconnection.
243  
244 =item * reconnect => $bool
245  
246 Enable automatic reconnection on connection failure or unexpected disconnection.
247 Default is disabled (0).
248  
249 =item * reconnect_delay => $num_of_milliseconds
250  
251 Delay between reconnection attempts. Default is 1000 (1 second).
252  
253 =item * max_reconnect_attempts => $num
254  
255 Maximum number of reconnection attempts. 0 means unlimited. Default is 0.
256 Negative values are treated as 0 (unlimited).
257  
258 =item * priority => $num
259  
260 Priority for the underlying libev IO watchers. Higher priority watchers are
261 invoked before lower priority ones. Valid range is -2 (lowest) to +2 (highest),
262 with 0 being the default. See L<EV> documentation for details on priorities.
263  
264 =item * keepalive => $seconds
265  
266 Enable TCP keepalive with the specified interval in seconds. When enabled,
267 the OS will periodically send probes on idle connections to detect dead peers.
268 0 means disabled (default). Recommended for long-lived connections behind
269 NAT gateways or firewalls.
270  
271 =item * prefer_ipv4 => $bool
272  
273 Prefer IPv4 addresses when resolving hostnames. Mutually exclusive with
274 C<prefer_ipv6>.
275  
276 =item * prefer_ipv6 => $bool
277  
278 Prefer IPv6 addresses when resolving hostnames. Mutually exclusive with
279 C<prefer_ipv4>.
280  
281 =item * source_addr => 'Str'
282  
283 Local address to bind the outbound connection to. Useful on multi-homed
284 servers to select a specific network interface.
285  
286 =item * tcp_user_timeout => $num_of_milliseconds
287  
288 Set the TCP_USER_TIMEOUT socket option (Linux-specific). Controls how long
289 transmitted data may remain unacknowledged before the connection is dropped.
290 Helps detect dead connections faster on lossy networks.
291  
292 =item * cloexec => $bool
293  
294 Set SOCK_CLOEXEC on the Redis connection socket. Prevents the file descriptor
295 from leaking to child processes after fork/exec. Default is enabled.
296  
297 =item * reuseaddr => $bool
298  
299 Set SO_REUSEADDR on the Redis connection socket. Allows rebinding to an
300 address that is still in TIME_WAIT state. Default is disabled.
301  
302 =item * tls => $bool
303  
304 Enable TLS/SSL encryption for the connection. Requires that the module was
305 built with TLS support (auto-detected at build time, or forced with
306 C<EV_REDIS_SSL=1>). Only valid with C<host> connections, not C<path>.
307  
308 =item * tls_ca => 'Str'
309  
310 Path to CA certificate file for server verification. If not specified,
311 uses the system default CA store.
312  
313 =item * tls_capath => 'Str'
314  
315 Path to a directory containing CA certificate files in OpenSSL-compatible
316 format (hashed filenames). Alternative to C<tls_ca> for multiple CA certs.
317  
318 =item * tls_cert => 'Str'
319  
320 Path to client certificate file for mutual TLS authentication. Must be
321 specified together with C<tls_key>.
322  
323 =item * tls_key => 'Str'
324  
325 Path to client private key file. Must be specified together with C<tls_cert>.
326  
327 =item * tls_server_name => 'Str'
328  
329 Server name for SNI (Server Name Indication). Optional.
330  
331 =item * tls_verify => $bool
332  
333 Enable or disable TLS peer verification. Default is true (verify).
334 Set to false to accept self-signed certificates (not recommended for
335 production).
336  
337 =item * loop => 'EV::Loop',
338  
339 EV loop for running this instance. Default is C<EV::default_loop>.
340  
341 =back
342  
343 All parameters are optional.
344  
345 If parameters about connection (host&port or path) is not passed, you should call C<connect> or C<connect_unix> method by hand to connect to redis-server.
346  
347 =head2 connect($hostname [, $port])
348  
349 =head2 connect_unix($path)
350  
351 Connect to a redis-server for C<$hostname:$port> or C<$path>. C<$port>
352 defaults to 6379. Croaks if a connection is already active.
353  
354 =head2 command($commands..., [$cb->($result, $error)])
355  
356 Do a redis command and return its result by callback. Returns C<REDIS_OK>
357 (0) on success or C<REDIS_ERR> (-1) if the command could not be enqueued
358 (the error is also delivered via callback, so the return value is rarely needed).
359  
360 $redis->command('get', 'foo', sub {
361 my ($result, $error) = @_;
362  
363 print $result; # value for key 'foo'
364 print $error; # redis error string, undef if no error
365 });
366  
367 If any error is occurred, C<$error> presents the error message and C<$result> is undef.
368 If no error, C<$error> is undef and C<$result> presents response from redis.
369  
370 The callback is optional. Without a callback, the command runs in
371 fire-and-forget mode: the reply from Redis is silently discarded and errors
372 are not reported to Perl code (connection-level errors still trigger
373 C<on_error>). This is useful for high-volume writes where individual
374 acknowledgement is not needed:
375  
376 $redis->set('counter', 42); # fire-and-forget, no callback
377  
378 NOTE: Alternatively all commands can be called via AUTOLOAD interface,
379 including fire-and-forget:
380  
381 $redis->command('get', 'foo', sub { ... });
382  
383 is equivalent to:
384  
385 $redis->get('foo', sub { ... });
386  
387 B<Note:> Calling C<command()> while not connected will croak with
388 "connection required before calling command", unless automatic reconnection
389 is active (reconnect timer running). In that case, commands are
390 automatically queued and sent after successful reconnection. Queued
391 commands respect C<waiting_timeout> if set.
392  
393 B<Pub/Sub note:> For C<subscribe> and C<psubscribe>, the callback is
394 persistent and receives all messages; at least one channel/pattern argument
395 is required. For C<unsubscribe> and C<punsubscribe>, the confirmation is
396 delivered through the original subscribe callback (this is hiredis
397 behavior). Any callback passed to unsubscribe commands is silently
398 discarded.
399  
400 B<Sharded pub/sub note:> C<ssubscribe> and C<sunsubscribe> are not
401 supported and croak: the bundled hiredis has no sharded pub/sub support, so
402 an incoming C<smessage> would abort the process. C<spublish> works as a
403 regular command.
404  
405 B<MONITOR note:> C<monitor> requires an idle connection (no pending,
406 waiting, or subscribed commands), and once active no further commands may
407 be sent on that connection -- C<command()> croaks. Both restrictions exist
408 because hiredis's monitor mode re-queues callback records in a way that is
409 unsafe to mix with other traffic. Use a dedicated connection; the state
410 clears on disconnect.
411  
412 B<Nested event loop note:> while a callback is running, this connection's
413 own I/O watchers are skipped, so a nested C<EV::run> (or condvar-style
414 wait) inside a callback cannot process replies for the same connection --
415 they are delivered after the outer callback returns. Use a separate
416 connection if you must wait for Redis inside a callback.
417  
418 =head2 disconnect
419  
420 Disconnect from redis-server. Safe to call when already disconnected.
421 Stops any pending reconnect timer, so explicit disconnect prevents automatic
422 reconnection. Triggers the C<on_disconnect> callback when disconnecting
423 from an active connection. When called while already disconnected, clears
424 any waiting commands (e.g., preserved by C<resume_waiting_on_reconnect>),
425 invoking their callbacks with a "disconnected" error (C<on_disconnect>
426 does not fire in this case).
427  
428 =head2 is_connected
429  
430 Returns true (1) if a connection context is active (including while the
431 connection is being established), false (0) otherwise.
432  
433 =head2 has_ssl
434  
435 Class method. Returns true (1) if the module was built with TLS support,
436 false (0) otherwise.
437  
438 if (EV::Redis->has_ssl) {
439 # TLS connections are available
440 }
441  
442 =head2 connect_timeout([$ms])
443  
444 Get or set the connection timeout in milliseconds. Pass C<0> to disable.
445 Returns the current value, or undef if never set. Can also be set via
446 constructor.
447  
448 =head2 command_timeout([$ms])
449  
450 Get or set the command timeout in milliseconds. Pass C<0> to disable.
451 Returns the current value, or undef if never set. Can also be set via
452 constructor. When changed while connected, takes effect immediately on
453 the active connection, including re-arming (or stopping, for C<0>) an
454 already-scheduled timeout for commands currently in flight.
455  
456 =head2 on_error([$cb->($errstr)])
457  
458 Set error callback. With a CODE reference argument, replaces the handler
459 and returns the new handler. With C<undef> or without arguments, clears
460 the handler and returns undef.
461  
462 B<Note:> Calling without arguments clears the handler. There is no way to
463 read the current handler without clearing it. This applies to all handler
464 methods (C<on_error>, C<on_connect>, C<on_disconnect>, C<on_push>).
465  
466 =head2 on_connect([$cb->()])
467  
468 Set connect callback. With a CODE reference argument, replaces the handler
469 and returns the new handler. With C<undef> or without arguments, clears
470 the handler and returns undef.
471  
472 =head2 on_disconnect([$cb->()])
473  
474 Set disconnect callback, called on both normal and error disconnections.
475 With a CODE reference argument, replaces the handler and returns the new
476 handler. With C<undef> or without arguments, clears the handler and
477 returns undef.
478  
479 =head2 on_push([$cb->($reply)])
480  
481 Set RESP3 push callback for server-initiated messages (Redis 6.0+).
482 The callback receives the decoded push message as an array reference.
483 With a CODE reference argument, replaces the handler and returns the new
484 handler. With C<undef> or without arguments, clears the handler and
485 returns undef. When changed while connected, takes effect immediately.
486  
487 $redis->on_push(sub {
488 my ($msg) = @_;
489 # $msg is an array ref, e.g. ['invalidate', ['key1', 'key2']]
490 });
491  
492 =head2 reconnect($enable, $delay_ms, $max_attempts)
493  
494 Configure automatic reconnection.
495  
496 $redis->reconnect(1); # enable with defaults (1s delay, unlimited)
497 $redis->reconnect(1, 0); # enable with immediate reconnect
498 $redis->reconnect(1, 2000); # enable with 2 second delay
499 $redis->reconnect(1, 1000, 5); # enable with 1s delay, max 5 attempts
500 $redis->reconnect(0); # disable
501  
502 C<$delay_ms> defaults to 1000 (1 second). 0 means immediate reconnect.
503 C<$max_attempts> defaults to 0 (unlimited).
504  
505 When enabled, the client will automatically attempt to reconnect on connection
506 failure or unexpected disconnection. Intentional C<disconnect()> calls will
507 not trigger reconnection.
508  
509 =head2 reconnect_enabled
510  
511 Returns true (1) if automatic reconnection is enabled, false (0) otherwise.
512  
513 =head2 pending_count
514  
515 Returns the number of commands sent to Redis awaiting responses.
516 Persistent commands (subscribe, psubscribe, ssubscribe, monitor) are not
517 included in this count.
518 When called from inside a command callback, the count includes the
519 current command (it is decremented after the callback returns).
520  
521 =head2 waiting_count
522  
523 Returns the number of commands queued locally (not yet sent to Redis).
524 These are commands that exceeded the C<max_pending> limit.
525  
526 =head2 max_pending($limit)
527  
528 Get or set the maximum number of concurrent commands sent to Redis.
529 Persistent commands (subscribe, psubscribe, ssubscribe, monitor) are not
530 subject to this limit.
531 0 means unlimited (default). When the limit is reached, additional commands
532 are queued locally and sent as responses arrive.
533  
534 =head2 waiting_timeout($ms)
535  
536 Get or set the maximum time in milliseconds a command can wait in the local queue.
537 Commands exceeding this timeout are cancelled with "waiting timeout" error.
538 0 means unlimited (default). Returns the current value as an integer (0 when unset).
539  
540 =head2 resume_waiting_on_reconnect($bool)
541  
542 Get or set whether waiting commands are preserved on disconnect and resumed
543 after reconnection. Default is false (waiting commands cancelled on disconnect).
544  
545 =head2 priority($priority)
546  
547 Get or set the priority for the underlying libev IO watchers. Higher priority
548 watchers are invoked before lower priority ones when multiple watchers are
549 pending. Valid range is -2 (lowest) to +2 (highest), with 0 being the default.
550 Values outside this range are clamped automatically.
551 Can be changed at any time, including while connected.
552  
553 $redis->priority(1); # higher priority
554 $redis->priority(-1); # lower priority
555 $redis->priority(99); # clamped to 2
556 my $prio = $redis->priority; # get current priority
557  
558 =head2 keepalive($seconds)
559  
560 Get or set the TCP keepalive interval in seconds. When set, the OS sends
561 periodic probes on idle connections to detect dead peers. 0 means disabled
562 (default). When set to a positive value while connected, takes effect
563 immediately. Setting to 0 while connected records the preference for future
564 connections but does not disable keepalives on the current socket.
565  
566 =head2 prefer_ipv4($bool)
567  
568 Get or set IPv4 preference for DNS resolution. Mutually exclusive with
569 C<prefer_ipv6> (setting one clears the other). Takes effect on the next
570 connection.
571  
572 =head2 prefer_ipv6($bool)
573  
574 Get or set IPv6 preference for DNS resolution. Mutually exclusive with
575 C<prefer_ipv4> (setting one clears the other). Takes effect on the next
576 connection.
577  
578 =head2 source_addr($addr)
579  
580 Get or set the local source address to bind to when connecting. This is
581 useful on multi-homed hosts to control which network interface is used.
582 Pass C<undef> to clear. Takes effect on the next TCP connection (has no
583 effect on Unix socket connections).
584  
585 =head2 tcp_user_timeout($ms)
586  
587 Get or set the TCP user timeout in milliseconds. This controls how long
588 transmitted data may remain unacknowledged before the connection is dropped.
589 0 means use the OS default. Takes effect on the next connection.
590  
591 =head2 cloexec($bool)
592  
593 Get or set the close-on-exec flag for the Redis socket. When enabled, the
594 socket is automatically closed in child processes after fork+exec. Enabled
595 by default. Takes effect on the next connection.
596  
597 =head2 reuseaddr($bool)
598  
599 Get or set SO_REUSEADDR on the Redis socket. Allows rebinding to an address
600 still in TIME_WAIT state. Disabled by default. Takes effect on the next
601 connection.
602  
603 =head2 skip_waiting
604  
605 Cancel only waiting (not yet sent) command callbacks. Each callback is invoked
606 with C<(undef, "skipped")>. In-flight commands continue normally.
607  
608 =head2 skip_pending
609  
610 Cancel all pending and waiting command callbacks. Each Perl callback is
611 invoked immediately with C<(undef, "skipped")>. For pending commands,
612 the internal hiredis tracking entry remains until a reply arrives (which
613 is then discarded); no second callback fires.
614  
615 =head2 can($method)
616  
617 Returns code reference if method is available, undef otherwise.
618 Methods installed via AUTOLOAD (Redis commands) will return true after first call.
619  
620 =head1 DESTRUCTION BEHAVIOR
621  
622 When an EV::Redis object is destroyed (goes out of scope or is explicitly
623 undefined) while commands are still pending or waiting, hiredis invokes all
624 pending command callbacks with a disconnect error, and EV::Redis invokes
625 all waiting queue callbacks with C<"disconnected">. This ensures callbacks
626 are not orphaned.
627  
628 For predictable cleanup, explicitly disconnect before destruction:
629  
630 $redis->disconnect; # Clean disconnect, callbacks get error
631 undef $redis; # Safe to destroy
632  
633 Or use skip methods to cancel with a specific error message:
634  
635 $redis->skip_pending; # Invokes callbacks with (undef, "skipped")
636 $redis->skip_waiting;
637 $redis->disconnect;
638 undef $redis;
639  
640 B<Circular references:> If your callbacks close over the C<$redis> variable,
641 this creates a reference cycle (C<$redis> -> object -> callback -> C<$redis>)
642 that prevents garbage collection. Break the cycle before the object goes out
643 of scope by clearing callbacks:
644  
645 $redis->on_error(undef);
646 $redis->on_connect(undef);
647 $redis->on_disconnect(undef);
648 $redis->on_push(undef);
649  
650 =head1 BENCHMARKS
651  
652 Measured on Linux with Unix socket connection, 100-byte values, Perl 5.40,
653 Redis 8.x (C<bench/benchmark.pl>):
654  
655 Pipeline SET ~107K ops/sec
656 Pipeline GET ~112K ops/sec
657 Mixed workload ~112K ops/sec
658 Fire-and-forget SET ~655K ops/sec
659 Sequential round-trip ~39K ops/sec (SET+GET pairs)
660  
661 Fire-and-forget mode (no callback) is roughly 6x faster than callback mode
662 due to zero Perl-side overhead per command. Pipeline throughput is bounded
663 by the event loop round-trip, not by hiredis or the network.
664  
665 Flow control (C<max_pending>) has minimal impact at reasonable limits:
666  
667 unlimited ~180K ops/sec
668 max_pending=500 ~186K ops/sec
669 max_pending=100 ~146K ops/sec
670  
671 Run C<perl bench/benchmark.pl> for full results. Set C<BENCH_COMMANDS> and
672 C<BENCH_VALUE_SIZE> environment variables to customize.
673  
674 =head1 AUTHOR
675  
676 Daisuke Murase (typester) (original L<EV::Hiredis>)
677  
678 vividsnow
679  
680 =head1 COPYRIGHT AND LICENSE
681  
682 Copyright (c) 2013 Daisuke Murase, 2026 vividsnow. All rights reserved.
683  
684 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
685  
686 =cut
↑ Summary src/libev_adapter.h »