blib/lib/EV/Redis.pm

filter: Statementstmt 97.2% 70 / 72 Branchbran 71.8% 46 / 64 Conditioncond 54.5% 12 / 22 MC/DCmcdc 14.2% 2 / 14 Subroutinesub 84.6% 11 / 13 Podpod 50.0% 1 / 2 totaltotal 75.9% 142 / 187 CC 41 SCAR 38.0
CC
41
Cov
81%
new
58.9
AUTOLOAD
2.0
CLONE_SKIP
2.0
CRAP 44.7
↑ Summary deps/hiredis/alloc.h »
1 package EV::Redis;
2 45 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 45 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 45 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 45 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 45 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
9 45 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 45 our $VERSION = '0.15';
11 45 XSLoader::load __PACKAGE__, $VERSION;
12 }
13  
14 45 my %new_option = map { $_ => 1 } qw(
15 host port path loop on_error on_connect on_disconnect on_push
16 connect_timeout command_timeout max_pending waiting_timeout
17 resume_waiting_on_reconnect priority keepalive prefer_ipv4 prefer_ipv6
18 source_addr tcp_user_timeout cloexec reuseaddr reconnect reconnect_delay
19 max_reconnect_attempts tls tls_ca tls_capath tls_cert tls_key
20 tls_server_name tls_verify
21 );
22  
23 61 ▶sub new {
Subroutine new: called CC=40 SCAR=40.8
Pod documented
24 61 my ($class, %args) = @_;
25  
26 # a subclass may pass options of its own
27 61 ▶ if ((ref $class || $class) eq __PACKAGE__) {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $class || $class) eq __PACKAGE__) 60 1 61
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0610
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
28 60 my @unknown = sort grep { !$new_option{$_} } keys %args;
29 60 ▶ Carp::carp("EV::Redis->new: unknown option(s): @unknown") if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 0 60 60
30 }
31  
32 Carp::croak("Cannot specify both 'host' and 'path'")
33 61 ▶ if exists $args{host} && exists $args{path};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"host"} and exists $args{"path"} 0 61 61
Condition66%2/3
exists $args{"host"} and exists $args{"path"}
!ll&&!rl&&r
5560
MC/DC0%0/2
exists $args{"host"} and exists $args{"path"}
exists $args{"host"} exists $args{"path"}
Truth table66%2/3
A and B
A= exists $args{"host"}B= exists $args{"path"}
ABresult
0X0
100
111
34 Carp::croak("Cannot specify both 'prefer_ipv4' and 'prefer_ipv6'")
35 61 ▶ if $args{prefer_ipv4} && $args{prefer_ipv6};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"prefer_ipv4"} and $args{"prefer_ipv6"} 0 61 61
Condition33%1/3
$args{"prefer_ipv4"} and $args{"prefer_ipv6"}
!ll&&!rl&&r
6100
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
36  
37 61 ▶ my $loop = $args{loop} // EV::default_loop;
Condition33%1/3
$args{"loop"} // &EV::default_loop()
l!l&&r!l&&!r
0610
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
38 61 ▶ my $self = bless $class->_new($loop), ref $class || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0610
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
39  
40 61 ▶ $self->on_error($args{on_error} // sub { die "$_[0]\n" });
Subroutine __ANON__: not called CC=1 SCAR=0.6
Condition66%2/3
$args{"on_error"} // sub { die "$_[0]\n"; }
l!l&&r!l&&!r
47140
MC/DC0%0/2
$args{"on_error"} // sub { die "$_[0]\n"; }
$args{"on_error"} sub { die "$_[0]\n"; }
Truth table66%2/3
A // B
A= $args{"on_error"}B= sub { die "$_[0]\n"; }
ABresult
1X1
011
000
41 61 ▶ $self->on_connect($args{on_connect}) if exists $args{on_connect};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_connect"} 16 45 61
42 61 ▶ $self->on_disconnect($args{on_disconnect}) if exists $args{on_disconnect};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_disconnect"} 9 52 61
43 61 ▶ $self->on_push($args{on_push}) if exists $args{on_push};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_push"} 0 61 61
44 61 ▶ $self->connect_timeout($args{connect_timeout}) if defined $args{connect_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"connect_timeout"} 5 56 61
45 61 ▶ $self->command_timeout($args{command_timeout}) if defined $args{command_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"command_timeout"} 14 47 61
46 61 ▶ $self->max_pending($args{max_pending}) if defined $args{max_pending};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"max_pending"} 0 61 61
47 61 ▶ $self->waiting_timeout($args{waiting_timeout}) if defined $args{waiting_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"waiting_timeout"} 0 61 61
48 61 ▶ $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"} 4 57 61
49 61 ▶ $self->priority($args{priority}) if defined $args{priority};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"priority"} 1 60 61
50 61 ▶ $self->keepalive($args{keepalive}) if defined $args{keepalive};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"keepalive"} 0 61 61
51 61 ▶ $self->prefer_ipv4($args{prefer_ipv4}) if exists $args{prefer_ipv4};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"prefer_ipv4"} 0 61 61
52 61 ▶ $self->prefer_ipv6($args{prefer_ipv6}) if exists $args{prefer_ipv6};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"prefer_ipv6"} 0 61 61
53 61 ▶ $self->source_addr($args{source_addr}) if defined $args{source_addr};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"source_addr"} 0 61 61
54 61 ▶ $self->tcp_user_timeout($args{tcp_user_timeout}) if defined $args{tcp_user_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"tcp_user_timeout"} 2 59 61
55 61 ▶ $self->cloexec($args{cloexec}) if exists $args{cloexec};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"cloexec"} 0 61 61
56 61 ▶ $self->reuseaddr($args{reuseaddr}) if exists $args{reuseaddr};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"reuseaddr"} 0 61 61
57  
58 61 ▶ if ($args{reconnect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"reconnect"}) 12 49 61
59 $self->reconnect(
60 1,
61 $args{reconnect_delay} // 1000,
62 12 ▶ $args{max_reconnect_attempts} // 0
Condition100%4/4
$args{"reconnect_delay"} // 1000
l!l
102
$args{"max_reconnect_attempts"} // 0
l!l
66
MC/DC100%1/1
$args{"reconnect_delay"} // 1000
$args{"reconnect_delay"}
MC/DC100%1/1
$args{"max_reconnect_attempts"} // 0
$args{"max_reconnect_attempts"}
Truth table100%2/2
A
A= $args{"reconnect_delay"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"max_reconnect_attempts"}
Aresult
11
00
63 );
64 }
65  
66 # TLS context must be set up before connect
67 61 ▶ if ($args{tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"tls"}) 3 58 61
68 3 ▶ Carp::croak("TLS support not compiled in; rebuild with EV_REDIS_SSL=1")
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_ssl 0 3 3
69 unless $self->has_ssl;
70 Carp::croak("TLS requires 'host' parameter (not 'path')")
71 3 ▶ if exists $args{path};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"path"} 1 2 3
72 $self->_setup_ssl_context(
73 $args{tls_ca}, $args{tls_capath}, $args{tls_cert}, $args{tls_key},
74 $args{tls_server_name},
75 2 ▶ exists $args{tls_verify} ? ($args{tls_verify} ? 1 : 0) : 1,
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'tls_verify'} ? : 1 1 2
$args{'tls_verify'} ? : 0 1 1
76 );
77 }
78  
79 59 ▶ if (exists $args{host}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $args{'host'}) { } 6 53 59
elsif (exists $args{'path'}) { } 3 50 53
80 6 ▶ Carp::croak("'host' must be a defined string") unless defined $args{host};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"host"} 0 6 6
81 defined $args{port}
82 ? $self->connect($args{host}, $args{port})
83 6 ▶ : $self->connect($args{host});
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'port'} ? : 6 0 6
84 }
85 elsif (exists $args{path}) {
86 3 ▶ Carp::croak("'path' must be a defined string") unless defined $args{path};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"path"} 0 3 3
87 3 $self->connect_unix($args{path});
88 }
89  
90 58 $self;
91 }
92  
93 # the XS object is a bare C pointer; a cloned interpreter would double-free it
94 0 ▶sub CLONE_SKIP { 1 }
Subroutine CLONE_SKIP: not called CC=1 SCAR=6.9
95  
96 # a thawed copy would carry the same pointer and free it with the original
97 1 ▶sub STORABLE_freeze { Carp::croak("EV::Redis objects cannot be serialized") }
Subroutine STORABLE_freeze: called CC=1 SCAR=0.0
Pod undocumented
98  
99 45 our $AUTOLOAD;
100  
101 11 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=2 SCAR=6.9
102 11 (my $method = $AUTOLOAD) =~ s/.*:://;
103 11 ▶ return if $method eq 'DESTROY';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DESTROY" 0 11 11
104  
105 43 ▶ my $sub = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
106 43 my $self = shift;
107 43 $self->command($method, @_);
108 11 };
109  
110 45 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
111 11 *$method = $sub;
112 11 goto $sub;
113 }
114  
115 45 1;
116  
117 =head1 NAME
118  
119 EV::Redis - Asynchronous redis client using hiredis and EV
120  
121 =head1 SYNOPSIS
122  
123 use EV::Redis;
124
125 my $redis = EV::Redis->new;
126 $redis->connect('127.0.0.1');
127
128 # or
129 my $redis = EV::Redis->new( host => '127.0.0.1' );
130
131 # command
132 $redis->set('foo' => 'bar', sub {
133 my ($res, $err) = @_;
134
135 print $res; # OK
136
137 $redis->get('foo', sub {
138 my ($res, $err) = @_;
139
140 print $res; # bar
141
142 $redis->disconnect;
143 });
144 });
145
146 # start main loop
147 EV::run;
148  
149 =head1 DESCRIPTION
150  
151 EV::Redis is a fork of L<EV::Hiredis> by Daisuke Murase (typester),
152 extended with reconnection, flow control, TLS, and RESP3 support. It is a
153 drop-in replacement for EV::Hiredis, except that commands which would pair
154 replies with the wrong callbacks croak (see B<Reply order note>).
155  
156 This is an asynchronous client for Redis using hiredis and L<EV> as backend.
157 It connects to L<EV> with C-level interface so that it runs faster.
158  
159 =head1 ANYEVENT INTEGRATION
160  
161 L<AnyEvent> has a support for EV as its one of backends, so L<EV::Redis> can be used in your AnyEvent applications seamlessly.
162  
163 =head1 NO UTF-8 SUPPORT
164  
165 Unlike other redis modules, this module doesn't support utf-8 string.
166  
167 This module handle all variables as bytes: command arguments are sent as
168 their byte representation regardless of Perl's internal string encoding
169 (upgraded strings are downgraded in place, unless read-only), and passing a string with characters
170 above C<0xFF> croaks with a "Wide character" error. You should encode your
171 utf-8 string before passing commands like following:
172  
173 use Encode;
174
175 # set $val
176 $redis->set(foo => encode_utf8 $val, sub { ... });
177
178 # get $val
179 $redis->get('foo', sub {
180 my $val = decode_utf8 $_[0];
181 });
182  
183 =head1 SIGPIPE
184  
185 Writing to a connection the server has already closed raises C<SIGPIPE>,
186 which terminates the process by default. Set C<$SIG{PIPE} = 'IGNORE'> so the
187 write fails instead and the connection error reaches C<on_error> as usual.
188  
189 =head1 FORK
190  
191 A child process inherits the connection's socket, which the parent goes on
192 using. The child never uses it: when the child's loop next has an event
193 for that connection, the connection fails there with "connection inherited
194 from the parent process" -- its pending commands get that error, C<on_error>
195 runs, and C<on_disconnect> too unless it was still connecting, and with
196 C<reconnect> the child connects on its own. A child forked inside a callback
197 still gets the replies the parent had already read. A child that exits, or
198 destroys the object, without running the loop changes nothing. The parent is
199 not affected. A loop other than the default needs C<< $loop->loop_fork >> in
200 the child, as L<EV> requires.
201  
202 Objects cannot be copied: C<Storable> croaks on them, and C<Clone> must not
203 be used on them: the copy shares the original's connection, and destroying
204 either one frees it for both.
205  
206 =head1 RESP3 REPLIES
207  
208 After C<HELLO 3>, maps and sets arrive as array references (a map as a flat
209 key, value, key, value list), doubles as numbers, booleans as 1 or 0, and big
210 numbers and verbatim strings as plain strings, without the verbatim format
211 tag. Attribute replies are not supported: one ahead of a reply, as
212 C<DEBUG PROTOCOL attrib> sends, is dropped and the reply arrives as usual;
213 one inside an array or map, which some modules send, fails the connection
214 with a protocol error.
215  
216 =head1 METHODS
217  
218 =head2 new(%options);
219  
220 Create new L<EV::Redis> instance.
221  
222 Available C<%options> are:
223  
224 =over
225  
226 =item * host => 'Str'
227  
228 =item * port => 'Int'
229  
230 Hostname and port number of redis-server to connect. Mutually exclusive with C<path>.
231  
232 =item * path => 'Str'
233  
234 UNIX socket path to connect. Mutually exclusive with C<host>.
235  
236 =item * on_error => $cb->($errstr)
237  
238 Error callback will be called when a connection level error occurs.
239 If not provided (or C<undef>), a default handler that calls C<die> is
240 installed. Note that exceptions thrown inside any handler (including this
241 default) or command callback are caught and reported as warnings -- they
242 do not propagate out of the event loop. In practice the default handler
243 therefore turns connection errors into warnings; install your own
244 C<on_error> to handle them programmatically. To have no error handler, call
245 C<< $obj->on_error(undef) >> after construction.
246  
247 A C<$SIG{__WARN__}> that dies while such a warning is reported cannot stop
248 the loop either: both messages are printed to STDERR instead. Perl runs a
249 C<%SIG> handler when Perl code next runs, which inside C<EV::run> is a
250 callback; a handler that dies there aborts that callback and is reported
251 as a warning, so an C<alarm> that dies does not end C<EV::run>. Use
252 C<command_timeout> or an C<EV::timer> instead.
253  
254 This callback can be set by C<< $obj->on_error($cb) >> method any time.
255  
256 =item * on_connect => $cb->()
257  
258 Connection callback will be called when connection successful and completed to redis server.
259 With C<tls>, it is called once the TCP connection is up; a failed TLS
260 handshake then arrives as C<on_error> and C<on_disconnect>.
261  
262 This callback can be set by C<< $obj->on_connect($cb) >> method any time.
263  
264 =item * on_disconnect => $cb->()
265  
266 Disconnect callback will be called when disconnection occurs (both normal and error cases).
267  
268 This callback can be set by C<< $obj->on_disconnect($cb) >> method any time.
269  
270 =item * on_push => $cb->($reply)
271  
272 RESP3 push callback for server-initiated out-of-band messages (Redis 6.0+).
273 Called with the decoded push message (an array reference). This enables
274 client-side caching invalidation and other server-push features.
275  
276 This callback can be set by C<< $obj->on_push($cb) >> method any time.
277  
278 =item * connect_timeout => $num_of_milliseconds
279  
280 Connection timeout.
281  
282 =item * command_timeout => $num_of_milliseconds
283  
284 Command timeout.
285  
286 =item * max_pending => $num
287  
288 Maximum number of commands sent to Redis concurrently. When this limit is reached,
289 additional commands are queued locally and sent as responses arrive.
290 0 means unlimited (default). Use C<waiting_count> to check the local queue size.
291  
292 =item * waiting_timeout => $num_of_milliseconds
293  
294 Maximum time a command can wait in the local queue before being cancelled with
295 "waiting timeout" error. 0 means unlimited (default).
296  
297 =item * resume_waiting_on_reconnect => $bool
298  
299 Controls behavior of waiting queue on disconnect. If false (default), waiting
300 commands are cancelled with error on disconnect and on each failed connect
301 attempt. If true, waiting commands are preserved and resumed after successful
302 reconnection; an explicit C<disconnect()>, a lost connection or failed
303 connect without C<reconnect>, or giving up on reconnecting still cancels
304 them. The settings as the connection is lost decide; a handler changing them
305 affects the next one, except that C<reconnect(0)> or C<disconnect()> there
306 cancels the kept commands at once. Commands cancelled on a lost connection
307 are off the queue before C<on_error> and C<on_disconnect> run.
308  
309 =item * reconnect => $bool
310  
311 Enable automatic reconnection on connection failure or unexpected disconnection.
312 Default is disabled (0).
313  
314 =item * reconnect_delay => $num_of_milliseconds
315  
316 Delay between reconnection attempts. Default is 1000 (1 second). Used only
317 with C<reconnect>, as is C<max_reconnect_attempts>.
318  
319 =item * max_reconnect_attempts => $num
320  
321 Maximum number of reconnection attempts. 0 means unlimited. Default is 0.
322 Negative values are treated as 0 (unlimited). Only connects that fail
323 count: an established connection starts the count again, also one that is
324 closed at once or fails its TLS handshake, so retries against such a server
325 or proxy go on.
326  
327 =item * priority => $num
328  
329 Priority for the underlying libev IO watchers. Higher priority watchers are
330 invoked before lower priority ones. Valid range is -2 (lowest) to +2 (highest),
331 with 0 being the default. See L<EV> documentation for details on priorities.
332  
333 =item * keepalive => $seconds
334  
335 Enable TCP keepalive with the specified interval in seconds (at most 32767).
336 When enabled, the OS will periodically send probes on idle connections to
337 detect dead peers. 0 means disabled (default). Recommended for long-lived
338 connections behind NAT gateways or firewalls. The interval applies on Linux
339 with glibc and on macOS; elsewhere only keepalive itself is enabled, with the
340 system's timing. Ignored for unix sockets.
341  
342 =item * prefer_ipv4 => $bool
343  
344 Resolve host names to IPv4 addresses, falling back to IPv6 only when there
345 is none; this is already the default. Mutually exclusive with
346 C<prefer_ipv6>.
347  
348 =item * prefer_ipv6 => $bool
349  
350 Resolve host names to IPv6 addresses, falling back to IPv4 only when there
351 is none. Mutually exclusive with C<prefer_ipv4>.
352  
353 =item * source_addr => 'Str'
354  
355 Local address to bind the outbound connection to. Useful on multi-homed
356 servers to select a specific network interface.
357  
358 =item * tcp_user_timeout => $num_of_milliseconds
359  
360 Set the TCP_USER_TIMEOUT socket option (Linux-specific). Controls how long
361 transmitted data may remain unacknowledged before the connection is dropped.
362 Helps detect dead connections faster on lossy networks. Ignored for unix
363 sockets; where the system lacks the option, TCP connects fail with an error.
364  
365 =item * cloexec => $bool
366  
367 Set SOCK_CLOEXEC on the Redis connection socket. Prevents the file descriptor
368 from leaking to child processes after fork/exec. Default is enabled.
369  
370 =item * reuseaddr => $bool
371  
372 Set SO_REUSEADDR on the Redis connection socket. Allows rebinding to an
373 address that is still in TIME_WAIT state. Default is disabled.
374  
375 =item * tls => $bool
376  
377 Enable TLS/SSL encryption for the connection. Requires that the module was
378 built with TLS support (auto-detected at build time, or forced with
379 C<EV_REDIS_SSL=1>). Only valid with C<host> connections, not C<path>.
380  
381 =item * tls_ca => 'Str'
382  
383 Path to CA certificate file for server verification. If not specified,
384 uses the system default CA store.
385  
386 =item * tls_capath => 'Str'
387  
388 Path to a directory containing CA certificate files in OpenSSL-compatible
389 format (hashed filenames). Alternative to C<tls_ca> for multiple CA certs.
390  
391 =item * tls_cert => 'Str'
392  
393 Path to client certificate file for mutual TLS authentication. Must be
394 specified together with C<tls_key>.
395  
396 =item * tls_key => 'Str'
397  
398 Path to client private key file. Must be specified together with C<tls_cert>.
399  
400 =item * tls_server_name => 'Str'
401  
402 Server name for SNI (Server Name Indication), sent on every connection the
403 object makes; without it no SNI is sent, which endpoints that route by SNI
404 reject. It is not checked against the certificate.
405  
406 =item * tls_verify => $bool
407  
408 Enable or disable TLS peer verification. Default is true (verify).
409 Set to false to accept self-signed certificates (not recommended for
410 production). Verification checks the certificate chain against the CAs
411 only: the bundled hiredis does not check that the certificate names the
412 host, so any certificate those CAs issued is accepted. Use C<tls_ca> with
413 a CA dedicated to your Redis servers rather than the system store.
414  
415 =item * loop => 'EV::Loop',
416  
417 EV loop for running this instance. Default is C<EV::default_loop>.
418  
419 =back
420  
421 All parameters are optional. Unknown ones warn, unless C<new> is called
422 on a subclass.
423  
424 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.
425  
426 =head2 connect($hostname [, $port])
427  
428 =head2 connect_unix($path)
429  
430 Connect to a redis-server for C<$hostname:$port> or C<$path>. C<$port>
431 defaults to 6379. Croaks if a connection is already active, C<$port> is
432 outside 1..65535, or C<$path> is too long for a unix socket (over 107 bytes
433 on Linux, 103 on BSD and macOS).
434  
435 A failure detected inside the call (a missing unix socket, a host name that
436 does not resolve) reaches C<on_error> before the method returns, also when
437 called from C<new>; with reconnect enabled a retry is then scheduled.
438  
439 The host name is resolved inside the call, and again by each reconnect
440 attempt: the event loop waits for the system resolver, C<connect_timeout>
441 does not cover it, and only the first address found is tried. Pass an IP
442 address where DNS can be slow.
443  
444 =head2 command($commands..., [$cb->($result, $error)])
445  
446 Do a redis command and return its result by callback. Returns C<REDIS_OK>
447 (0) on success or C<REDIS_ERR> (-1) if the command could not be enqueued
448 (the error is also delivered via callback, so the return value is rarely needed).
449  
450 $redis->command('get', 'foo', sub {
451 my ($result, $error) = @_;
452  
453 print $result; # value for key 'foo'
454 print $error; # redis error string, undef if no error
455 });
456  
457 If any error is occurred, C<$error> presents the error message and C<$result> is undef.
458 If no error, C<$error> is undef and C<$result> presents response from redis.
459 An error inside an array reply, such as C<EXEC>'s result for a queued
460 command that failed, arrives as its error text. Arrays nested more than 512
461 levels deep in a reply arrive empty; a reply nested more than 1024 levels
462 deep is a protocol error that closes the connection.
463  
464 The callback is optional: only a code reference in the last position is
465 taken as one, so an C<undef> there is sent as an argument. Without a
466 callback, the command runs in
467 fire-and-forget mode: the reply from Redis is silently discarded and errors
468 are not reported to Perl code (connection-level errors still trigger
469 C<on_error>). This is useful for high-volume writes where individual
470 acknowledgement is not needed:
471  
472 $redis->set('counter', 42); # fire-and-forget, no callback
473  
474 The callback is the code reference passed, so reusing a variable for it is
475 safe. Perl releases many closures in creation order slowly: with a million
476 commands outstanding, each with a closure of its own, their replies or a
477 cancel take about two minutes, against under a second with one shared code
478 reference.
479  
480 NOTE: Alternatively all commands can be called via AUTOLOAD interface,
481 including fire-and-forget:
482  
483 $redis->command('get', 'foo', sub { ... });
484  
485 is equivalent to:
486  
487 $redis->get('foo', sub { ... });
488  
489 The Redis C<COMMAND> command itself is reached as
490 C<< $redis->command('command', ...) >>, since C<command> is this method.
491  
492 B<Note:> Calling C<command()> while not connected will croak with
493 "connection required before calling command", unless automatic reconnection
494 is active (reconnect timer running). Commands issued then wait locally and
495 are sent in order once a connection is established; with
496 C<resume_waiting_on_reconnect>, so are commands issued while an attempt is
497 still connecting. Unless C<resume_waiting_on_reconnect> is set, a failed
498 attempt cancels waiting commands with its error. Queued commands respect
499 C<waiting_timeout> if set. A command issued from a command's callback that
500 reports the loss or timeout of an established connection waits too: with
501 C<reconnect> and C<resume_waiting_on_reconnect> it is sent on the next
502 connection, otherwise it fails with that error once C<on_error> and
503 C<on_disconnect> have run. After a failed connect it croaks as above, unless
504 a reconnect is scheduled: then it waits for that attempt.
505 From C<on_error> and C<on_disconnect> themselves it croaks as above: the
506 reconnect is scheduled only after they return.
507  
508 B<Pub/Sub note:> For C<subscribe> and C<psubscribe>, the callback is
509 persistent and receives all messages; at least one channel/pattern argument
510 is required. For C<unsubscribe> and C<punsubscribe>, the confirmation is
511 delivered through the original subscribe callback (this is hiredis
512 behavior). Any callback passed to unsubscribe commands is silently
513 discarded, unless hiredis refuses the command (as when nothing is
514 subscribed): then it gets the error. Subscribing again to a channel or pattern that already has a
515 callback moves it to the new callback, including confirmations still due;
516 a callback left with no channels is never called again. An error reply
517 that arrives while the connection is subscribed (RESP2 or RESP3) is taken
518 by hiredis as a connection error and closes the connection, so keep
519 pub/sub on a connection of its own. A subscribed connection waits for
520 messages without a timeout: set C<keepalive> to notice a server that is
521 gone without closing it. When the connection is lost or C<disconnect()>
522 closes it, a subscribe callback gets one error for each channel or pattern
523 it still holds; when the object is destroyed it gets one.
524  
525 B<Sharded pub/sub note:> C<ssubscribe> and C<sunsubscribe> are not
526 supported and croak: the bundled hiredis has no sharded pub/sub support, so
527 it cannot deliver C<smessage> messages to a callback. C<spublish> works as a
528 regular command.
529  
530 B<MONITOR note:> C<monitor> requires an idle connection (no pending,
531 waiting, or subscribed commands), and once active no further commands may
532 be sent on that connection -- C<command()> croaks. Both restrictions exist
533 because hiredis's monitor mode re-queues callback records in a way that is
534 unsafe to mix with other traffic. Use a dedicated connection; the state
535 clears on disconnect.
536  
537 B<Reply order note:> hiredis hands each reply to the oldest callback still
538 waiting for one, so commands that change how the server answers are
539 refused: C<CLIENT REPLY OFF>, C<CLIENT REPLY SKIP>, C<REPLCONF ACK> and
540 C<REPLCONF GETACK> croak, and so do C<SYNC> and C<PSYNC>, whose
541 replication stream is not a sequence of replies; C<RESET> croaks while the connection is
542 subscribed or a subscribe is waiting (leave with C<unsubscribe> and
543 C<punsubscribe> and wait for their replies, or disconnect), and fails
544 through its callback if a subscription was made while it waited; pub/sub
545 commands, C<monitor> and C<HELLO> sent inside C<MULTI> fail through their
546 callback. Pub/sub and C<HELLO> wait locally for outstanding transaction
547 replies before they are checked and sent; each such wait costs a round trip,
548 and commands issued meanwhile queue behind it. A C<MONITOR> the server refuses
549 leaves the connection usable. An C<EXEC> cancelled before it is sent (by
550 C<waiting_timeout> or C<skip_waiting>) leaves the transaction open: later
551 commands are answered C<QUEUED> until a C<DISCARD>.
552  
553 B<Nested event loop note:> while a callback runs for an event on this
554 connection (a reply, message or push, the connect, or the connection's
555 loss), its I/O watchers are paused, so a nested C<EV::run> (or
556 condvar-style wait) inside it cannot process replies for the same
557 connection -- they are delivered after the outer callback returns.
558 Callbacks of commands cancelled locally (C<waiting_timeout>,
559 C<skip_waiting>, C<skip_pending>, and waiting commands that C<disconnect()>
560 cancels) do not pause them. Use a separate connection if you must wait for
561 Redis inside a callback.
562  
563 =head2 disconnect
564  
565 Disconnect from redis-server. Safe to call when already disconnected.
566 Stops any pending reconnect timer, so explicit disconnect prevents automatic
567 reconnection. Triggers the C<on_disconnect> callback when disconnecting
568 from an established connection. Called while the connection is still being
569 established, it skips C<on_connect> for it; C<on_disconnect> still runs if
570 commands already sent keep it open until they are answered. Waiting
571 commands are cancelled with a
572 "disconnected" error before it returns, also while the connection is still
573 being established or finishing its pending replies, and when already
574 disconnected (e.g., commands kept by C<resume_waiting_on_reconnect>).
575 Commands already sent are not cancelled: the connection closes once their
576 replies have arrived. That holds while it is still being established too:
577 they go out when it is up and are answered first. Commands sent while the
578 connection is subscribed are cancelled with "disconnected" instead. So
579 C<disconnect()> does not drop a server that stopped answering: use
580 C<command_timeout>, or destroy the object.
581  
582 Sending C<QUIT> is no substitute: the server closing the connection is
583 reported to C<on_error> as a lost connection, and C<reconnect> connects
584 again.
585  
586 =head2 is_connected
587  
588 Returns true (1) if a connection context is active (including while the
589 connection is being established), false (0) otherwise.
590  
591 =head2 has_ssl
592  
593 Class method. Returns true (1) if the module was built with TLS support,
594 false (0) otherwise.
595  
596 if (EV::Redis->has_ssl) {
597 # TLS connections are available
598 }
599  
600 =head2 connect_timeout([$ms])
601  
602 Get or set the connection timeout in milliseconds. Pass C<0> to disable.
603 Returns the current value, or undef if never set. Can also be set via
604 constructor. It counts from the start of the connect attempt, once the host
605 name is resolved; commands
606 issued meanwhile do not extend it. Without it, a connect to a unix socket
607 whose server has a full listen queue is retried in a busy loop until the
608 server accepts it. With C<tls> it covers the TCP connect only: a stalled
609 handshake is ended by C<command_timeout>, once a command is outstanding.
610  
611 =head2 command_timeout([$ms])
612  
613 Get or set the command timeout in milliseconds. Pass C<0> to disable.
614 Returns the current value, or undef if never set. Can also be set via
615 constructor. It fires when replies are outstanding and nothing has been
616 received for that long; sending more commands does not extend it, but a
617 command too large for one write counts its bytes going out as progress, as
618 the system's socket buffer takes them, so a steady stream of such commands
619 can keep it from firing. That buffer can hold megabytes: on a slow link a
620 large command can still time out while it goes out.
621 (P)SUBSCRIBE and (P)UNSUBSCRIBE are not tracked as outstanding replies;
622 MONITOR is, so a MONITOR connection that sees no traffic for that long is
623 dropped with a timeout. A command that failed with a timeout, or with a
624 lost connection, may still have run on the server, or may still run there
625 later, even after commands sent on the next connection. Repeat only
626 commands that are safe to run twice.
627 When changed while connected, takes effect immediately on the active
628 connection, including re-arming (or stopping, for C<0>) an already-scheduled
629 timeout for commands currently in flight.
630  
631 =head2 on_error([$cb->($errstr)])
632  
633 Set error callback. With a CODE reference argument, replaces the handler
634 and returns the new handler. With C<undef> or without arguments, clears
635 the handler and returns undef; any other value clears it with a warning.
636  
637 B<Note:> Calling without arguments clears the handler. There is no way to
638 read the current handler without clearing it. This applies to all handler
639 methods (C<on_error>, C<on_connect>, C<on_disconnect>, C<on_push>).
640  
641 =head2 on_connect([$cb->()])
642  
643 Set connect callback. With a CODE reference argument, replaces the handler
644 and returns the new handler. With C<undef> or without arguments, clears
645 the handler and returns undef; any other value clears it with a warning.
646  
647 Commands issued from the callback go ahead of commands waiting in the local
648 queue and past C<max_pending>, so it suits per-connection setup such as
649 C<AUTH> or C<SELECT>. If a setup command waits for transaction replies,
650 later setup commands wait behind it, ahead of the ordinary queue.
651 Commands still waiting in the local queue when it runs (issued during a
652 reconnect delay, or over C<max_pending>) go after that setup. One sent while
653 the connection is being established -- right after C<new> or C<connect>, or
654 while a reconnect attempt is connecting -- goes ahead of it, unless both
655 C<reconnect> and C<resume_waiting_on_reconnect> are on, which make it wait.
656  
657 =head2 on_disconnect([$cb->()])
658  
659 Set disconnect callback, called on both normal and error disconnections.
660 With a CODE reference argument, replaces the handler and returns the new
661 handler. With C<undef> or without arguments, clears the handler and
662 returns undef; any other value clears it with a warning.
663  
664 =head2 on_push([$cb->($reply)])
665  
666 Set RESP3 push callback for server-initiated messages (Redis 6.0+).
667 The callback receives the decoded push message as an array reference.
668 With a CODE reference argument, replaces the handler and returns the new
669 handler. With C<undef> or without arguments, clears the handler and
670 returns undef; any other value clears it with a warning. When changed
671 while connected, takes effect immediately.
672  
673 $redis->on_push(sub {
674 my ($msg) = @_;
675 # $msg is an array ref, e.g. ['invalidate', ['key1', 'key2']]
676 });
677  
678 =head2 reconnect($enable, $delay_ms, $max_attempts)
679  
680 Configure automatic reconnection.
681  
682 $redis->reconnect(1); # enable with defaults (1s delay, unlimited)
683 $redis->reconnect(1, 0); # enable with immediate reconnect
684 $redis->reconnect(1, 2000); # enable with 2 second delay
685 $redis->reconnect(1, 1000, 5); # enable with 1s delay, max 5 attempts
686 $redis->reconnect(0); # disable
687  
688 C<$delay_ms> defaults to 1000 (1 second). 0 means immediate reconnect: a
689 local server that refuses connections then gets tens of thousands of
690 attempts a second.
691 C<$max_attempts> defaults to 0 (unlimited).
692  
693 When enabled, the client will automatically attempt to reconnect on connection
694 failure or unexpected disconnection. Intentional C<disconnect()> calls will
695 not trigger reconnection. The reconnect is scheduled after C<on_error> and
696 C<on_disconnect> return, so C<command()> still croaks inside them. A new
697 connection starts fresh: subscriptions, C<AUTH>, C<SELECT> and C<HELLO> are
698 not restored, so issue them from C<on_connect> (which says what can overtake
699 them).
700  
701 =head2 reconnect_enabled
702  
703 Returns true (1) if automatic reconnection is enabled, false (0) otherwise.
704  
705 =head2 pending_count
706  
707 Returns the number of commands sent to Redis awaiting responses.
708 Persistent commands (subscribe, psubscribe, monitor) are not
709 included in this count.
710 When called from inside a callback for a reply or a connection error, the
711 count includes the current command (it is decremented after the callback
712 returns); inside one that C<skip_pending> runs, it does not.
713  
714 =head2 waiting_count
715  
716 Returns the number of commands queued locally (not yet sent to Redis):
717 commands over the C<max_pending> limit, commands issued while a reconnect
718 is pending (with C<resume_waiting_on_reconnect>, also while an attempt is
719 connecting), commands waiting for transaction replies, and later commands
720 queued behind them to keep their order.
721  
722 =head2 max_pending($limit)
723  
724 Get or set the maximum number of concurrent commands sent to Redis.
725 Persistent commands (subscribe, psubscribe, monitor) do not count toward
726 the limit; subscribe and psubscribe wait behind it like other commands, and
727 monitor croaks unless the connection is idle.
728 0 means unlimited (default). When the limit is reached, additional commands
729 are queued locally and sent as responses arrive. Replies still owed by a
730 connection that C<disconnect()> replaced count in C<pending_count> but hold
731 no slot of the new connection.
732  
733 =head2 waiting_timeout($ms)
734  
735 Get or set the maximum time in milliseconds a command can wait in the local queue.
736 Commands exceeding this timeout are cancelled with "waiting timeout" error.
737 0 means unlimited (default). Returns the current value as an integer (0 when unset).
738 With C<reconnect> and C<resume_waiting_on_reconnect> it also covers commands
739 issued while a connect is in progress. Time spent held only for outstanding
740 transaction replies (see B<Reply order note>) does not count.
741  
742 =head2 resume_waiting_on_reconnect($bool)
743  
744 Get or set whether waiting commands are preserved on disconnect and resumed
745 after reconnection. Default is false (waiting commands cancelled on disconnect
746 and on each failed connect attempt).
747  
748 =head2 priority($priority)
749  
750 Get or set the priority for the underlying libev IO watchers. Higher priority
751 watchers are invoked before lower priority ones when multiple watchers are
752 pending. Valid range is -2 (lowest) to +2 (highest), with 0 being the default.
753 Values outside this range are clamped automatically.
754 Can be changed at any time, including while connected.
755  
756 $redis->priority(1); # higher priority
757 $redis->priority(-1); # lower priority
758 $redis->priority(99); # clamped to 2
759 my $prio = $redis->priority; # get current priority
760  
761 =head2 keepalive($seconds)
762  
763 Get or set the TCP keepalive interval in seconds (at most 32767; see the
764 constructor option for platform limits). When set, the OS sends
765 periodic probes on idle connections to detect dead peers. 0 means disabled
766 (default). When set to a positive value while connected over TCP, takes
767 effect immediately, and croaks, keeping the old value, if the system
768 refuses it. Setting to 0 while connected records the preference for future
769 connections but does not disable keepalives on the current socket.
770  
771 =head2 prefer_ipv4($bool)
772  
773 Get or set IPv4 preference for DNS resolution, already the default (see
774 C<new>). Mutually exclusive with
775 C<prefer_ipv6> (setting one clears the other). Takes effect on the next
776 connection.
777  
778 =head2 prefer_ipv6($bool)
779  
780 Get or set IPv6 preference for DNS resolution. Mutually exclusive with
781 C<prefer_ipv4> (setting one clears the other). Takes effect on the next
782 connection.
783  
784 =head2 source_addr($addr)
785  
786 Get or set the local source address to bind to when connecting. This is
787 useful on multi-homed hosts to control which network interface is used.
788 Pass C<undef> to clear. Takes effect on the next TCP connection (has no
789 effect on Unix socket connections).
790  
791 =head2 tcp_user_timeout($ms)
792  
793 Get or set the TCP user timeout in milliseconds. This controls how long
794 transmitted data may remain unacknowledged before the connection is dropped.
795 0 means use the OS default. Takes effect on the next connection. Applies to
796 TCP connections only; where the system lacks the option, TCP connects fail
797 with an error.
798  
799 =head2 cloexec($bool)
800  
801 Get or set the close-on-exec flag for the Redis socket. When enabled, the
802 socket is automatically closed in child processes after fork+exec. Enabled
803 by default. Takes effect on the next connection.
804  
805 =head2 reuseaddr($bool)
806  
807 Get or set SO_REUSEADDR on the Redis socket. Allows rebinding to an address
808 still in TIME_WAIT state. Disabled by default. Takes effect on the next
809 connection.
810  
811 =head2 skip_waiting
812  
813 Cancel only waiting (not yet sent) command callbacks. Each callback is invoked
814 with C<(undef, "skipped")>. In-flight commands continue normally. Commands
815 issued by those callbacks are not cancelled.
816  
817 =head2 skip_pending
818  
819 Cancel all pending and waiting command callbacks. Each Perl callback is
820 invoked immediately with C<(undef, "skipped")>. For pending commands,
821 the internal hiredis tracking entry remains until a reply arrives (which
822 is then discarded); no second callback fires. Commands issued by those
823 callbacks, and callbacks already running, are not cancelled.
824  
825 =head2 can($method)
826  
827 Returns code reference if method is available, undef otherwise.
828 Methods installed via AUTOLOAD (Redis commands) will return true after first call.
829  
830 =head1 DESTRUCTION BEHAVIOR
831  
832 When an EV::Redis object is destroyed (goes out of scope or is explicitly
833 undefined) while commands are still pending or waiting, hiredis invokes all
834 pending command callbacks with a disconnect error, and EV::Redis invokes
835 all waiting queue callbacks with C<"disconnected">. This ensures callbacks
836 are not orphaned. An object still alive at global destruction (a package
837 variable, or one kept by a reference cycle) runs no callbacks.
838  
839 For predictable cleanup, explicitly disconnect before destruction:
840  
841 $redis->disconnect; # waiting callbacks get "disconnected"
842 undef $redis; # pending callbacks get "disconnected"
843  
844 Or use skip methods to cancel with a specific error message:
845  
846 $redis->skip_pending; # Invokes callbacks with (undef, "skipped")
847 $redis->skip_waiting;
848 $redis->disconnect;
849 undef $redis;
850  
851 B<Circular references:> If your callbacks close over the C<$redis> variable,
852 this creates a reference cycle (C<$redis> -> object -> callback -> C<$redis>)
853 that prevents garbage collection. Break the cycle before the object goes out
854 of scope by clearing callbacks:
855  
856 $redis->on_error(undef);
857 $redis->on_connect(undef);
858 $redis->on_disconnect(undef);
859 $redis->on_push(undef);
860  
861 =head1 BENCHMARKS
862  
863 Measured on Linux with Unix socket connection, 100,000 commands with
864 100-byte values, Perl 5.40, Redis 8.x (C<bench/benchmark.pl> in the source
865 repository, C<BENCH_COMMANDS=100000>):
866  
867 Pipeline SET ~107K ops/sec
868 Pipeline GET ~112K ops/sec
869 Mixed workload ~112K ops/sec
870 Fire-and-forget SET ~655K ops/sec
871 Sequential round-trip ~39K ops/sec (SET+GET pairs)
872  
873 Fire-and-forget mode (no callback) is roughly 6x faster than callback mode
874 due to zero Perl-side overhead per command. Pipeline throughput is bounded
875 by the event loop round-trip, not by hiredis or the network.
876  
877 Flow control (C<max_pending>) has minimal impact at reasonable limits:
878  
879 unlimited ~180K ops/sec
880 max_pending=500 ~186K ops/sec
881 max_pending=100 ~146K ops/sec
882  
883 Run C<perl bench/benchmark.pl> in a checkout of the repository for full
884 results. Set C<BENCH_COMMANDS> and C<BENCH_VALUE_SIZE> environment variables
885 to customize; the default of 10,000 commands gives different rates.
886  
887 =head1 AUTHOR
888  
889 Daisuke Murase (typester) (original L<EV::Hiredis>)
890  
891 vividsnow
892  
893 =head1 COPYRIGHT AND LICENSE
894  
895 Copyright (c) 2013 Daisuke Murase, 2026 vividsnow. All rights reserved.
896  
897 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
898  
899 =cut
↑ Summary deps/hiredis/alloc.h »