blib/lib/Async/Redis.pm

filter: Statementstmt 37.0% 403 / 1088 Branchbran 27.7% 122 / 440 Conditioncond 29.3% 67 / 228 MC/DCmcdc 14.8% 20 / 135 Subroutinesub 44.4% 60 / 135 Podpod 73.4% 36 / 49 totaltotal 34.1% 708 / 2075 CC 329 SCAR 49.2
CC
329
Cov
34%
_run_reader
1260.0
disconnect
380.0
_redis_handshake
132.0
CRAP 136.6
↑ Summary blib/lib/Async/Redis/Subscription.pm »
1 package Async::Redis;
2  
3 91 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 91 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 91 ▶use 5.018;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 91 our $VERSION = '0.002000';
8  
9 91 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 91 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 91 ▶use Future::IO 0.23;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 91 ▶use Future::Selector 0.05;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 91 ▶use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 91 ▶use Socket qw(pack_sockaddr_in pack_sockaddr_un inet_aton AF_INET AF_UNIX SOCK_STREAM);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 91 ▶use IO::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 91 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 91 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 # Error classes
20 91 ▶use Async::Redis::Error::Connection;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 91 ▶use Async::Redis::Error::Timeout;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 91 ▶use Async::Redis::Error::Disconnected;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 91 ▶use Async::Redis::Error::Redis;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 91 ▶use Async::Redis::Error::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 # Import auto-generated command methods
27 91 ▶use Async::Redis::Commands;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 91 our @ISA = qw(Async::Redis::Commands);
29  
30 # Key extraction for prefixing
31 91 ▶use Async::Redis::KeyExtractor;
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 # Transaction support
34 91 ▶use Async::Redis::Transaction;
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 # Script support
37 91 ▶use Async::Redis::Script;
Subroutine BEGIN: called CC=1 SCAR=0.0
38  
39 # Iterator support
40 91 ▶use Async::Redis::Iterator;
Subroutine BEGIN: called CC=1 SCAR=0.0
41  
42 # Pipeline support
43 91 ▶use Async::Redis::Pipeline;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 91 ▶use Async::Redis::AutoPipeline;
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46 # PubSub support
47 91 ▶use Async::Redis::Subscription;
Subroutine BEGIN: called CC=1 SCAR=0.0
48  
49 # Telemetry support
50 91 ▶use Async::Redis::Telemetry;
Subroutine BEGIN: called CC=1 SCAR=0.0
51  
52 # Try XS version first, fall back to pure Perl
53 91 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.1
54 91 ▶ eval { require Protocol::Redis::XS; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Protocol::Redis::XS; 1 } } or require Protocol::Redis 91 0 91
55 or require Protocol::Redis;
56 }
57  
58 0 ▶sub _parser_class {
Subroutine _parser_class: not called CC=2 SCAR=17.9
59 0 ▶ return $INC{'Protocol/Redis/XS.pm'} ? 'Protocol::Redis::XS' : 'Protocol::Redis';
Branch: 1 branch
BranchTrueFalseTotal
$INC{'Protocol/Redis/XS.pm'} ? : 0 0 0
60 }
61  
62 3 ▶sub _calculate_backoff {
Subroutine _calculate_backoff: called CC=3 SCAR=12.0
63 3 my ($self, $attempt) = @_;
64  
65 # Exponential: delay * 2^(attempt-1)
66 3 my $delay = $self->{reconnect_delay} * (2 ** ($attempt - 1));
67  
68 # Cap at max
69 3 ▶ $delay = $self->{reconnect_delay_max} if $delay > $self->{reconnect_delay_max};
Branch: 1 branch
BranchTrueFalseTotal
if $delay > $self->{"reconnect_delay_max"} 1 2 3
70  
71 # Apply jitter: delay * (1 +/- jitter)
72 3 ▶ if ($self->{reconnect_jitter} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"reconnect_jitter"} > 0) 0 3 3
73 0 my $jitter_range = $delay * $self->{reconnect_jitter};
74 0 my $jitter = (rand(2) - 1) * $jitter_range;
75 0 $delay += $jitter;
76 }
77  
78 3 return $delay;
79 }
80  
81 # Free function, not a method. Call as _await_with_deadline($f, $deadline).
82 # Race a read future against a deadline. Returns a Future resolving to
83 # ($read_future, $timed_out_bool). The caller inspects $timed_out and
84 # $read_future->is_failed explicitly; we never throw from here.
85 #
86 # On timeout win: $read_future is left pending. _reader_fatal is the sole
87 # owner of its cancellation (it must happen before _close_socket so
88 # Future::IO unregisters while fileno is still valid).
89 # On read win: the internal timeout timer is cancelled here for hygiene.
90 5 ▶sub _await_with_deadline {
Subroutine _await_with_deadline: called CC=3 SCAR=11.1
91 5 my ($read_f, $deadline) = @_;
92  
93 5 ▶ if (!defined $deadline) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $deadline) 1 4 5
94 1 ▶ return $read_f->followed_by(sub { Future->done($read_f, 0) });
Subroutine __ANON__: called CC=1 SCAR=0.0
95 }
96  
97 4 my $remaining = $deadline - Time::HiRes::time();
98 4 ▶ if ($remaining <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining <= 0) 1 3 4
99 1 return Future->done($read_f, 1);
100 }
101  
102 my $timeout_f = Future::IO->sleep($remaining)
103 3 ▶ ->then(sub { Future->fail('__deadline__') });
Subroutine __ANON__: called CC=1 SCAR=0.0
104  
105 # Use without_cancel so that if timeout wins, wait_any's cancel of the
106 # losing future does not propagate to $read_f (caller owns its lifecycle).
107 return Future->wait_any($read_f->without_cancel, $timeout_f)
108 3 ▶ ->followed_by(sub {
Subroutine __ANON__: called CC=6 SCAR=19.3
109 3 my ($f) = @_;
110 3 ▶ my $timed_out = $f->is_failed
Branch: 1 branch
BranchTrueFalseTotal
$f->is_failed && (($f->failure)[0] // '') eq '__deadline__' ? : 1 2 3
Condition60%3/5
$f->is_failed and (($f->failure)[0] // "") eq "__deadline__"
!ll&&!rl&&r
201
($f->failure)[0] // ""
l!l
10
MC/DC50%1/2
$f->is_failed and (($f->failure)[0] // "") eq "__deadline__"
$f->is_failed ($f->failure)[0]
Truth table66%2/3
A and B
A= $f->is_failedB= ($f->failure)[0]
ABresult
0X0
100
111
111 && (($f->failure)[0] // '') eq '__deadline__' ? 1 : 0;
112  
113 3 ▶ if (!$timed_out && !$timeout_f->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($timed_out or $timeout_f->is_ready) 0 3 3
Condition66%2/3
$timed_out or $timeout_f->is_ready
l!l&&r!l&&!r
120
MC/DC0%0/2
$timed_out or $timeout_f->is_ready
$timed_out $timeout_f->is_ready
Truth table66%2/3
A or B
A= $timed_outB= $timeout_f->is_ready
ABresult
1X1
011
000
114 0 $timeout_f->cancel;
115 }
116  
117 3 return Future->done($read_f, $timed_out);
118 3 });
119 }
120  
121 109 ▶sub new {
Subroutine new: called CC=26 SCAR=34.3
Pod documented
122 109 my ($class, %args) = @_;
123  
124 # Parse URI if provided
125 109 ▶ if ($args{uri}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"uri"}) 2 107 109
126 2 require Async::Redis::URI;
127 2 my $uri = Async::Redis::URI->parse($args{uri});
128 2 ▶ if ($uri) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uri) 2 0 2
129 2 my %uri_args = $uri->to_hash;
130 # URI values are defaults, explicit args override
131 2 %args = (%uri_args, %args);
132 2 delete $args{uri}; # don't store the string
133 }
134 }
135  
136 my $self = bless {
137 path => $args{path},
138 host => $args{path} ? undef : ($args{host} // 'localhost'),
139 port => $args{path} ? undef : ($args{port} // 6379),
140 socket => undef,
141 parser => undef,
142 connected => 0,
143 _socket_live => 0,
144 _fatal_in_progress => 0,
145 _reader_running => 0, # dedup guard; the selector owns the reader Future itself
146 _write_lock => undef, # will be a Future used as a lock, populated lazily
147 _reconnect_future => undef,
148 _tasks => Future::Selector->new,
149  
150 # Timeout settings
151 connect_timeout => $args{connect_timeout} // 10,
152 request_timeout => $args{request_timeout} // 5,
153 blocking_timeout_buffer => $args{blocking_timeout_buffer} // 2,
154  
155 # Inflight tracking with deadlines
156 # Entry: { future => $f, cmd => $cmd, args => \@args, deadline => $t, sent_at => $t }
157 inflight => [],
158  
159 # Reconnection settings
160 reconnect => $args{reconnect} // 0,
161 reconnect_delay => $args{reconnect_delay} // 0.1,
162 reconnect_delay_max => $args{reconnect_delay_max} // 60,
163 reconnect_jitter => $args{reconnect_jitter} // 0.25,
164 reconnect_max_attempts => $args{reconnect_max_attempts} // 10, # 0 = unlimited
165 _reconnect_attempt => 0,
166  
167 # Callbacks
168 on_connect => $args{on_connect},
169 on_disconnect => $args{on_disconnect},
170 on_error => $args{on_error},
171  
172 # Authentication
173 password => $args{password},
174 username => $args{username},
175 database => $args{database} // 0,
176 client_name => $args{client_name},
177  
178 # TLS
179 tls => $args{tls},
180  
181 # Key prefixing
182 prefix => $args{prefix},
183  
184 # Pipeline settings
185 pipeline_depth => $args{pipeline_depth} // 10000,
186 auto_pipeline => $args{auto_pipeline} // 0,
187  
188 # Backpressure: max queued messages before _dispatch_frame's slot wait blocks.
189 message_queue_depth => do {
190 109 ▶ my $d = $args{message_queue_depth} // 1;
Condition100%2/2
$args{"message_queue_depth"} // 1
l!l
3106
MC/DC100%1/1
$args{"message_queue_depth"} // 1
$args{"message_queue_depth"}
Truth table100%2/2
A
A= $args{"message_queue_depth"}
Aresult
11
00
191 109 ▶ die "message_queue_depth must be >= 1 (got $d)" if $d < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $d < 1 2 107 109
192 107 ▶ $d;
Condition50%2/4
$args{"otel_include_args"} // 0
l!l
0107
$args{"otel_redact"} // 1
l!l
0107
MC/DC0%0/1
$args{"otel_include_args"} // 0
$args{"otel_include_args"}
MC/DC0%0/1
$args{"otel_redact"} // 1
$args{"otel_redact"}
Truth table50%1/2
A
A= $args{"otel_include_args"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"otel_redact"}
Aresult
11
00
193 },
194  
195 # Transaction state
196 in_multi => 0,
197 watching => 0,
198  
199 # PubSub state
200 in_pubsub => 0,
201 _subscription => undef,
202 _pump_running => 0,
203  
204 # Fork safety
205 _pid => $$,
206  
207 # Script registry
208 _scripts => {},
209  
210 # Current read future for clean disconnect cancellation
211 _current_read_future => undef,
212  
213 # Telemetry options
214 debug => $args{debug},
215 otel_tracer => $args{otel_tracer},
216 otel_meter => $args{otel_meter},
217 otel_include_args => $args{otel_include_args} // 0,
218 109 ▶ otel_redact => $args{otel_redact} // 1,
Branch: 2 branches
BranchTrueFalseTotal
$args{'path'} ? : 4 105 109
$args{'path'} ? : 4 105 109
Condition92%24/26
$args{"host"} // "localhost"
l!l
1032
$args{"port"} // 6379
l!l
9411
$args{"connect_timeout"} // 10
l!l
7831
$args{"request_timeout"} // 5
l!l
1108
$args{"blocking_timeout_buffer"} // 2
l!l
1108
$args{"reconnect"} // 0
l!l
1108
$args{"reconnect_delay"} // "0.1"
l!l
3106
$args{"reconnect_delay_max"} // 60
l!l
3106
$args{"reconnect_jitter"} // "0.25"
l!l
3106
$args{"reconnect_max_attempts"} // 10
l!l
3106
$args{"database"} // 0
l!l
1108
$args{"pipeline_depth"} // 10000
l!l
0109
$args{"auto_pipeline"} // 0
l!l
0109
MC/DC100%1/1
$args{"host"} // "localhost"
$args{"host"}
MC/DC100%1/1
$args{"port"} // 6379
$args{"port"}
MC/DC100%1/1
$args{"connect_timeout"} // 10
$args{"connect_timeout"}
MC/DC100%1/1
$args{"request_timeout"} // 5
$args{"request_timeout"}
MC/DC100%1/1
$args{"blocking_timeout_buffer"} // 2
$args{"blocking_timeout_buffer"}
MC/DC100%1/1
$args{"reconnect"} // 0
$args{"reconnect"}
MC/DC100%1/1
$args{"reconnect_delay"} // "0.1"
$args{"reconnect_delay"}
MC/DC100%1/1
$args{"reconnect_delay_max"} // 60
$args{"reconnect_delay_max"}
MC/DC100%1/1
$args{"reconnect_jitter"} // "0.25"
$args{"reconnect_jitter"}
MC/DC100%1/1
$args{"reconnect_max_attempts"} // 10
$args{"reconnect_max_attempts"}
MC/DC100%1/1
$args{"database"} // 0
$args{"database"}
MC/DC0%0/1
$args{"pipeline_depth"} // 10000
$args{"pipeline_depth"}
MC/DC0%0/1
$args{"auto_pipeline"} // 0
$args{"auto_pipeline"}
Truth table100%2/2
A
A= $args{"host"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"port"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"connect_timeout"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"request_timeout"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"blocking_timeout_buffer"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"reconnect"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"reconnect_delay"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"reconnect_delay_max"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"reconnect_jitter"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"reconnect_max_attempts"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"database"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"pipeline_depth"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"auto_pipeline"}
Aresult
11
00
219 }, $class;
220  
221 # Initialize telemetry if any observability enabled
222 107 ▶ if ($self->{debug} || $self->{otel_tracer} || $self->{otel_meter}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"} or $self->{"otel_tracer"} or $self->{"otel_meter"}) 0 107 107
Condition33%2/6
$self->{"debug"} or $self->{"otel_tracer"} or $self->{"otel_meter"}
l!l&&r!l&&!r
00107
$self->{"debug"} or $self->{"otel_tracer"}
l!l&&r!l&&!r
00107
MC/DC0%0/3
$self->{"debug"} or $self->{"otel_tracer"} or $self->{"otel_meter"}
$self->{"debug"} $self->{"otel_tracer"} $self->{"otel_meter"}
Truth table25%1/4
A or B or C
A= $self->{"debug"}B= $self->{"otel_tracer"}C= $self->{"otel_meter"}
ABCresult
1XX1
01X1
0011
0000
223 $self->{_telemetry} = Async::Redis::Telemetry->new(
224 tracer => $self->{otel_tracer},
225 meter => $self->{otel_meter},
226 debug => $self->{debug},
227 include_args => $self->{otel_include_args},
228 redact => $self->{otel_redact},
229 host => $self->{host},
230 port => $self->{port},
231 0 ▶ database => $self->{database} // 0,
Condition0%0/2
$self->{"database"} // 0
l!l
00
MC/DC0%0/1
$self->{"database"} // 0
$self->{"database"}
Truth table0%0/2
A
A= $self->{"database"}
Aresult
11
00
232 );
233 }
234  
235 107 return $self;
236 }
237  
238 # Connect to Redis server
239 78 ▶async sub connect {
Subroutine connect: called CC=17 SCAR=43.5
Pod documented
240 78 my ($self) = @_;
241  
242 78 ▶ return $self if $self->{connected};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"connected"} 0 78 78
243  
244 # Create socket — AF_UNIX for path, AF_INET for host:port
245 78 my ($socket, $sockaddr);
246  
247 78 ▶ if ($self->{path}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'path'}) { } 1 77 78
248 socket($socket, AF_UNIX, SOCK_STREAM, 0)
249 or die Async::Redis::Error::Connection->new(
250 message => "Cannot create unix socket: $!",
251 host => $self->{path},
252 1 ▶ port => 0,
Branch: 1 branch
BranchTrueFalseTotal
socket $socket, 1, 1, 0 or die "Async::Redis::Error::Connection"->new("message", "Cannot create unix socket: $!", "host", $self->{"path"}, "port", 0) 1 0 1
253 );
254 1 IO::Handle::blocking($socket, 0);
255 1 $sockaddr = pack_sockaddr_un($self->{path});
256 } else {
257 $socket = IO::Socket::INET->new(
258 Proto => 'tcp',
259 Blocking => 0,
260 ) or die Async::Redis::Error::Connection->new(
261 message => "Cannot create socket: $!",
262 host => $self->{host},
263 port => $self->{port},
264 77 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$socket = "IO::Socket::INET"->new("Proto", "tcp", "Blocking", 0) or die "Async::Redis::Error::Connection"->new("message", "Cannot create socket: $!", "host", $self->{"host"}, "port", $self->{"port"}) 77 0 77
265  
266 # Build sockaddr
267 my $addr = inet_aton($self->{host})
268 or die Async::Redis::Error::Connection->new(
269 message => "Cannot resolve host: $self->{host}",
270 host => $self->{host},
271 port => $self->{port},
272 77 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
my $addr = inet_aton($self->{"host"}) or die "Async::Redis::Error::Connection"->new("message", qq[Cannot resolve host: $self->{"host"}], "host", $self->{"host"}, "port", $self->{"port"}) 77 0 77
273 77 $sockaddr = pack_sockaddr_in($self->{port}, $addr);
274 }
275  
276 # Connect with timeout using Future->wait_any
277 78 my $connect_f = Future::IO->connect($socket, $sockaddr);
278 78 my $sleep_f = Future::IO->sleep($self->{connect_timeout});
279  
280 0 ▶ my $timeout_f = $sleep_f->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
281 0 return Future->fail('connect_timeout');
282 78 });
283  
284 78 my $wait_f = Future->wait_any($connect_f, $timeout_f);
285  
286 # Use followed_by to handle both success and failure without await propagating failure
287 78 ▶ my $result_f = $wait_f->followed_by(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
288 78 my ($f) = @_;
289 78 return Future->done($f); # wrap the future itself
290 78 });
291  
292 78 my $completed_f = await $result_f;
293  
294 # Now check the result
295 78 ▶ if ($completed_f->is_failed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($completed_f->is_failed) 78 0 78
296 78 my ($error) = $completed_f->failure;
297 # Don't call close() - let $socket go out of scope when we die.
298 # Perl's DESTROY will close it after the exception unwinds.
299  
300 78 ▶ if ($error eq 'connect_timeout') {
Branch: 1 branch
BranchTrueFalseTotal
if ($error eq "connect_timeout") 0 78 78
301 die Async::Redis::Error::Timeout->new(
302 message => "Connect timed out after $self->{connect_timeout}s",
303 timeout => $self->{connect_timeout},
304 0 );
305 }
306 die Async::Redis::Error::Connection->new(
307 message => "$error",
308 host => $self->{path} // $self->{host},
309 78 ▶ port => $self->{port} // 0,
Condition80%4/5
$self->{"path"} // $self->{"host"}
l!l&&r!l&&!r
1770
$self->{"port"} // 0
l!l
771
MC/DC0%0/2
$self->{"path"} // $self->{"host"}
$self->{"path"} $self->{"host"}
MC/DC100%1/1
$self->{"port"} // 0
$self->{"port"}
Truth table66%2/3
A // B
A= $self->{"path"}B= $self->{"host"}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $self->{"port"}
Aresult
11
00
310 );
311 }
312  
313 # TLS upgrade if enabled
314 0 ▶ if ($self->{tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tls"}) 0 0 0
315 0 eval {
316 0 $socket = await $self->_tls_upgrade($socket);
317 };
318 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
319 # Don't call close() - let $socket go out of scope when we die.
320 # Perl's DESTROY will close it after the exception unwinds.
321 0 die $@;
322 }
323 }
324  
325 0 $self->{socket} = $socket;
326 0 $self->{parser} = _parser_class()->new(api => 1);
327 0 $self->{_socket_live} = 1; # write gate and reader can now submit
328 0 $self->{inflight} = [];
329 0 $self->{_pid} = $$; # Track PID for fork safety
330 0 $self->{_current_read_future} = undef;
331  
332 # Run Redis protocol handshake (AUTH, SELECT, CLIENT SETNAME).
333 # connected stays 0 during handshake; set it only on success so
334 # callers never see a half-initialised object.
335 0 my $handshake_ok = eval { await $self->_redis_handshake; 1 };
336 0 ▶ unless ($handshake_ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($handshake_ok) 0 0 0
337 0 my $err = $@;
338 0 $self->_reset_connection('handshake_failure');
339 0 die $err;
340 }
341  
342 0 $self->{connected} = 1;
343  
344 # Initialize auto-pipeline if enabled
345 0 ▶ if ($self->{auto_pipeline}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"auto_pipeline"}) 0 0 0
346 $self->{_auto_pipeline} = Async::Redis::AutoPipeline->new(
347 redis => $self,
348 max_depth => $self->{pipeline_depth},
349 0 );
350 }
351  
352 # Fire on_connect callback and reset reconnect counter
353 0 ▶ if ($self->{on_connect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"on_connect"}) 0 0 0
354 0 $self->{on_connect}->($self);
355 }
356 0 $self->{_reconnect_attempt} = 0;
357  
358 # Telemetry: record connection
359 0 ▶ if ($self->{_telemetry}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_telemetry"}) 0 0 0
360 0 $self->{_telemetry}->record_connection(1);
361 $self->{_telemetry}->log_event('connected',
362 0 ▶ $self->{path} // "$self->{host}:$self->{port}");
Condition0%0/2
$self->{"path"} // qq[$self->{"host"}:$self->{"port"}]
l!l
00
MC/DC0%0/1
$self->{"path"} // qq[$self->{"host"}:$self->{"port"}]
$self->{"path"}
Truth table0%0/2
A
A= $self->{"path"}
Aresult
11
00
363 }
364  
365 0 return $self;
366 91 }
367  
368 # Redis protocol handshake after TCP connect
369 0 ▶async sub _redis_handshake {
Subroutine _redis_handshake: not called CC=11 SCAR=48.8
370 0 my ($self) = @_;
371  
372 # Use connect_timeout for the entire handshake (AUTH, SELECT, CLIENT SETNAME)
373 # This ensures the handshake can't block forever if Redis hangs
374 0 my $deadline = Time::HiRes::time() + $self->{connect_timeout};
375  
376 # AUTH (password or username+password for ACL)
377 0 ▶ if (defined $self->{password}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"password"}) 0 0 0
378 0 my @auth_args = ('AUTH');
379 0 ▶ push @auth_args, $self->{username} if defined $self->{username};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"username"} 0 0 0
380 0 push @auth_args, $self->{password};
381  
382 0 my $cmd = $self->_build_command(@auth_args);
383 0 await $self->_send($cmd);
384  
385 0 my $response = await $self->_read_response_with_deadline($deadline, ['AUTH']);
386 0 my $result = $self->_decode_response($response);
387  
388 # AUTH returns OK on success, throws on failure
389 0 ▶ unless ($result && $result eq 'OK') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result and $result eq "OK") 0 0 0
Condition0%0/3
$result and $result eq "OK"
!ll&&!rl&&r
000
MC/DC0%0/2
$result and $result eq "OK"
$result $result eq "OK"
Truth table0%0/3
A and B
A= $resultB= $result eq "OK"
ABresult
0X0
100
111
390 0 die Async::Redis::Error::Redis->new(
391 message => "Authentication failed: $result",
392 type => 'NOAUTH',
393 );
394 }
395 }
396  
397 # SELECT database
398 0 ▶ if ($self->{database} && $self->{database} != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"database"} and $self->{"database"} != 0) 0 0 0
Condition0%0/3
$self->{"database"} and $self->{"database"} != 0
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"database"} and $self->{"database"} != 0
$self->{"database"} $self->{"database"} != 0
Truth table0%0/3
A and B
A= $self->{"database"}B= $self->{"database"} != 0
ABresult
0X0
100
111
399 0 my $cmd = $self->_build_command('SELECT', $self->{database});
400 0 await $self->_send($cmd);
401  
402 0 my $response = await $self->_read_response_with_deadline($deadline, ['SELECT', $self->{database}]);
403 0 my $result = $self->_decode_response($response);
404  
405 0 ▶ unless ($result && $result eq 'OK') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result and $result eq "OK") 0 0 0
Condition0%0/3
$result and $result eq "OK"
!ll&&!rl&&r
000
MC/DC0%0/2
$result and $result eq "OK"
$result $result eq "OK"
Truth table0%0/3
A and B
A= $resultB= $result eq "OK"
ABresult
0X0
100
111
406 0 die Async::Redis::Error::Redis->new(
407 message => "SELECT failed: $result",
408 type => 'ERR',
409 );
410 }
411 }
412  
413 # CLIENT SETNAME
414 0 ▶ if (defined $self->{client_name} && length $self->{client_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"client_name"} and length $self->{"client_name"}) 0 0 0
Condition0%0/3
defined $self->{"client_name"} and length $self->{"client_name"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"client_name"} and length $self->{"client_name"}
defined $self->{"client_name"} length $self->{"client_name"}
Truth table0%0/3
A and B
A= defined $self->{"client_name"}B= length $self->{"client_name"}
ABresult
0X0
100
111
415 0 my $cmd = $self->_build_command('CLIENT', 'SETNAME', $self->{client_name});
416 0 await $self->_send($cmd);
417  
418 0 my $response = await $self->_read_response_with_deadline($deadline, ['CLIENT', 'SETNAME']);
419 # Ignore result - SETNAME failing shouldn't prevent connection
420 }
421 91 }
422  
423 # Check if connected to Redis
424 0 ▶sub is_connected {
Subroutine is_connected: not called CC=2 SCAR=17.9
Pod documented
425 0 my ($self) = @_;
426 0 ▶ return $self->{connected} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'connected'} ? : 0 0 0
427 }
428  
429 # Disconnect from Redis — user-initiated path.
430 #
431 # Distinct from _reader_fatal (which handles stream-level failure): this
432 # path is deterministic for user context. Key differences:
433 # - Inflight futures fail with Async::Redis::Error::Disconnected
434 # ("Client disconnect") rather than Connection ("Connection closed
435 # by peer"). Callers can distinguish "I disconnected" from "the
436 # server/network dropped me."
437 # - Subscription gets _close (clean; iterator next() returns undef,
438 # callback driver exits cleanly) rather than _fail_fatal.
439 # - No reconnect handoff — disconnect means stay down.
440 #
441 # Relationship to the selector (_tasks): this method does explicit
442 # teardown rather than relying on _reader_fatal propagation. Any tasks
443 # still in the selector (e.g., in-flight reconnect, autopipeline submit)
444 # will see their underlying I/O fail when the socket is closed and
445 # unwind via their existing on_fail handlers. Cancelling them explicitly
446 # would be cleaner but requires Future::Selector API that doesn't yet
447 # exist; this is acceptable because the failing I/O is a deterministic
448 # wakeup.
449 0 ▶sub disconnect {
Subroutine disconnect: not called CC=19 SCAR=59.4
Pod documented
450 0 my ($self) = @_;
451 0 ▶ return $self unless $self->{_socket_live} || $self->{connected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_socket_live"} or $self->{"connected"} 0 0 0
Condition0%0/3
$self->{"_socket_live"} or $self->{"connected"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_socket_live"} or $self->{"connected"}
$self->{"_socket_live"} $self->{"connected"}
Truth table0%0/3
A or B
A= $self->{"_socket_live"}B= $self->{"connected"}
ABresult
1X1
011
000
452  
453 0 my $was_connected = $self->{connected};
454  
455 # Close subscription cleanly before socket close so the pubsub branch
456 # in any subsequent _reader_fatal (triggered by the failing read)
457 # sees _closed and no-ops on _fail_fatal.
458 0 ▶ if (my $sub = $self->{_subscription}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sub = $self->{"_subscription"}) 0 0 0
459 0 ▶ $sub->_close unless $sub->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $sub->is_closed 0 0 0
460 }
461  
462 # Detach inflight + auto-pipeline queue before socket close so
463 # _close_socket doesn't cancel them — we will fail them explicitly
464 # with a user-context error type.
465 0 my $detached_inflight = $self->{inflight};
466 0 $self->{inflight} = [];
467 0 my $detached_autopipe = [];
468 0 ▶ if (my $ap = $self->{_auto_pipeline}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ap = $self->{"_auto_pipeline"}) 0 0 0
469 0 $detached_autopipe = $ap->_detach_queued;
470 }
471  
472 # Cancel current read BEFORE closing socket so Future::IO can
473 # unregister its watcher while fileno is still valid.
474 0 ▶ if ($self->{_current_read_future}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready) 0 0 0
Condition0%0/3
$self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready
$self->{"_current_read_future"} not $self->{"_current_read_future"}->is_ready
Truth table0%0/3
A and not(B)
A= $self->{"_current_read_future"}B= not $self->{"_current_read_future"}->is_ready
ABresult
0X0
100
111
475 && !$self->{_current_read_future}->is_ready) {
476 0 $self->{_current_read_future}->cancel;
477 }
478 0 $self->{_current_read_future} = undef;
479  
480 # Cancel any in-flight reconnect task so it doesn't re-establish
481 # state (connecting a new socket, setting _socket_live=1) after the
482 # user has intentionally disconnected.
483 0 ▶ if (my $rf = delete $self->{_reconnect_future}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rf = delete $self->{"_reconnect_future"}) 0 0 0
484 0 ▶ $rf->cancel unless $rf->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $rf->is_ready 0 0 0
485 }
486  
487 0 my $err = Async::Redis::Error::Disconnected->new(
488 message => "Client disconnect",
489 );
490  
491 # Wake the write-gate chain. Any commands waiting in
492 # _acquire_write_lock's `await $prev` unwind via their await
493 # throwing, and their _execute_command eval rethrows Disconnected
494 # to the caller. Without this, write-gate waiters stay suspended
495 # because the normal release path only runs when the current
496 # holder's body completes.
497 0 ▶ if (my $lock = delete $self->{_write_lock}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $lock = delete $self->{"_write_lock"}) 0 0 0
498 0 ▶ $lock->fail($err) unless $lock->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $lock->is_ready 0 0 0
499 }
500  
501 0 ▶ $self->_close_socket if $self->{socket};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"socket"} 0 0 0
502 0 $self->{_socket_live} = 0;
503 0 $self->{_fatal_in_progress} = 0;
504 0 $self->{_reader_running} = 0;
505 0 $self->{connected} = 0;
506 0 $self->{parser} = undef;
507 0 $self->{in_pubsub} = 0;
508  
509 # Fail detached futures with the user-context type so callers can
510 # distinguish "I disconnected" from Connection/EOF.
511 0 for my $entry (@$detached_inflight, @$detached_autopipe) {
512 0 ▶ next if $entry->{future}->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $entry->{"future"}->is_ready 0 0 0
513 0 $entry->{future}->fail($err);
514 }
515  
516 # on_disconnect + telemetry fire only if we were publicly connected,
517 # mirroring _reader_fatal's guard so a failed initial handshake
518 # doesn't spuriously emit these.
519 0 ▶ if ($was_connected && $self->{on_disconnect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($was_connected and $self->{"on_disconnect"}) 0 0 0
Condition0%0/3
$was_connected and $self->{"on_disconnect"}
!ll&&!rl&&r
000
MC/DC0%0/2
$was_connected and $self->{"on_disconnect"}
$was_connected $self->{"on_disconnect"}
Truth table0%0/3
A and B
A= $was_connectedB= $self->{"on_disconnect"}
ABresult
0X0
100
111
520 0 $self->{on_disconnect}->($self, 'client disconnect');
521 }
522 0 ▶ if ($was_connected && $self->{_telemetry}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($was_connected and $self->{"_telemetry"}) 0 0 0
Condition0%0/3
$was_connected and $self->{"_telemetry"}
!ll&&!rl&&r
000
MC/DC0%0/2
$was_connected and $self->{"_telemetry"}
$was_connected $self->{"_telemetry"}
Truth table0%0/3
A and B
A= $was_connectedB= $self->{"_telemetry"}
ABresult
0X0
100
111
523 0 $self->{_telemetry}->record_connection(-1);
524 0 $self->{_telemetry}->log_event('disconnected', 'client disconnect');
525 }
526  
527 0 return $self;
528 }
529  
530 # Destructor - clean up socket when object is garbage collected
531 104 ▶sub DESTROY {
Subroutine DESTROY: called CC=3 SCAR=14.2
532 104 my ($self) = @_;
533 # Only clean up if we have a socket and it's still open
534 104 ▶ if ($self->{socket} && fileno($self->{socket})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"socket"} and fileno $self->{"socket"}) 0 104 104
Condition33%1/3
$self->{"socket"} and fileno $self->{"socket"}
!ll&&!rl&&r
10400
MC/DC0%0/2
$self->{"socket"} and fileno $self->{"socket"}
$self->{"socket"} fileno $self->{"socket"}
Truth table33%1/3
A and B
A= $self->{"socket"}B= fileno $self->{"socket"}
ABresult
0X0
100
111
535 0 $self->_close_socket;
536 }
537 }
538  
539 # Properly close socket, canceling any pending futures first
540 0 ▶sub _close_socket {
Subroutine _close_socket: not called CC=7 SCAR=40.3
541 0 my ($self) = @_;
542  
543 # Take ownership - removes from $self immediately
544 0 ▶ my $socket = delete $self->{socket} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $socket = delete $self->{"socket"} or return 0 0 0
545 0 my $fileno = fileno($socket);
546  
547 # Cancel any pending inflight futures - this propagates to
548 # Future::IO internals and cleans up any watchers on this socket.
549 # Important: must happen while fileno is still valid!
550 0 ▶ if (my $inflight = delete $self->{inflight}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $inflight = delete $self->{"inflight"}) 0 0 0
551 0 for my $entry (@$inflight) {
552 0 ▶ if ($entry->{future} && !$entry->{future}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{"future"} and not $entry->{"future"}->is_ready) 0 0 0
Condition0%0/3
$entry->{"future"} and not $entry->{"future"}->is_ready
!ll&&!rl&&r
000
MC/DC0%0/2
$entry->{"future"} and not $entry->{"future"}->is_ready
$entry->{"future"} not $entry->{"future"}->is_ready
Truth table0%0/3
A and not(B)
A= $entry->{"future"}B= not $entry->{"future"}->is_ready
ABresult
0X0
100
111
553 0 $entry->{future}->cancel;
554 }
555 }
556 }
557 0 $self->{inflight} = [];
558  
559 # Initiate clean TCP shutdown (FIN) while fileno still valid
560 0 ▶ shutdown($socket, 2) if defined $fileno;
Branch: 1 branch
BranchTrueFalseTotal
if defined $fileno 0 0 0
561  
562 # DON'T call close()!
563 # $socket falls out of scope here, Perl's DESTROY calls close().
564 # By this point, Future::IO has already unregistered its watchers
565 # via the cancel() calls above.
566 }
567  
568 # Check if fork occurred and invalidate connection
569 2 ▶sub _check_fork {
Subroutine _check_fork: called CC=4 SCAR=24.0
570 2 my ($self) = @_;
571  
572 2 ▶ if ($self->{_pid} && $self->{_pid} != $$) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_pid"} and $self->{"_pid"} != $$) 0 2 2
Condition33%1/3
$self->{"_pid"} and $self->{"_pid"} != $$
!ll&&!rl&&r
020
MC/DC0%0/2
$self->{"_pid"} and $self->{"_pid"} != $$
$self->{"_pid"} $self->{"_pid"} != $$
Truth table33%1/3
A and B
A= $self->{"_pid"}B= $self->{"_pid"} != $$
ABresult
0X0
100
111
573 # Fork detected - invalidate connection (parent owns the socket)
574 # Don't cancel futures - they belong to the parent's event loop
575 # Just clear references so we don't try to use them
576 0 $self->{connected} = 0;
577 0 $self->{_socket_live} = 0;
578 0 $self->{socket} = undef;
579 0 $self->{parser} = undef;
580 0 $self->{inflight} = [];
581 0 $self->{_current_read_future} = undef; # Clear stale reference
582  
583 0 my $old_pid = $self->{_pid};
584 0 $self->{_pid} = $$;
585  
586 0 ▶ if ($self->{_telemetry}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_telemetry"}) 0 0 0
587 0 $self->{_telemetry}->log_event('fork_detected', "old PID: $old_pid, new PID: $$");
588 }
589  
590 0 return 1; # Fork occurred
591 }
592  
593 2 return 0;
594 }
595  
596 # Build Redis command in RESP format
597 2 ▶sub _build_command {
Subroutine _build_command: called CC=4 SCAR=14.0
598 2 my ($self, @args) = @_;
599  
600 2 my $cmd = "*" . scalar(@args) . "\r\n";
601 2 for my $arg (@args) {
602 3 ▶ $arg //= '';
Condition50%1/2
$arg //= ""
l!l
30
MC/DC0%0/1
$arg //= ""
$arg
Truth table50%1/2
A
A= $arg
Aresult
11
00
603 3 my $bytes = "$arg"; # stringify
604 3 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 0 3 3
605 3 $cmd .= "\$" . length($bytes) . "\r\n" . $bytes . "\r\n";
606 }
607 2 return $cmd;
608 }
609  
610 # Send raw data
611 0 ▶async sub _send {
Subroutine _send: not called CC=1 SCAR=6.9
612 0 my ($self, $data) = @_;
613 0 await Future::IO->write_exactly($self->{socket}, $data);
614 0 return length($data);
615 91 }
616  
617 # Add command to inflight queue - returns queue depth.
618 # redis_error_policy: 'fail' (default) fails the future on -ERR frames;
619 # 'capture' calls ->done($err_obj) so callers can inspect per-slot errors
620 # (used by pipelining in Task N+).
621 0 ▶sub _add_inflight {
Subroutine _add_inflight: not called CC=2 SCAR=17.9
622 0 my ($self, $future, $cmd, $args, $deadline, $redis_error_policy) = @_;
623 0 ▶ push @{$self->{inflight}}, {
Condition0%0/2
$redis_error_policy // "fail"
l!l
00
MC/DC0%0/1
$redis_error_policy // "fail"
$redis_error_policy
Truth table0%0/2
A
A= $redis_error_policy
Aresult
11
00
624 future => $future,
625 cmd => $cmd,
626 args => $args,
627 deadline => $deadline,
628 redis_error => $redis_error_policy // 'fail',
629 sent_at => Time::HiRes::time(),
630 };
631 0 return scalar @{$self->{inflight}};
632 }
633  
634 # Shift first entry from inflight queue
635 0 ▶sub _shift_inflight {
Subroutine _shift_inflight: not called CC=1 SCAR=6.9
636 0 my ($self) = @_;
637 0 return shift @{$self->{inflight}};
638 }
639  
640 # Fail all pending inflight futures with given error
641 0 ▶sub _fail_all_inflight {
Subroutine _fail_all_inflight: not called CC=4 SCAR=30.0
642 0 my ($self, $error) = @_;
643 0 ▶ while (my $entry = $self->_shift_inflight) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $entry = $self->_shift_inflight) 0 0 0
644 0 ▶ if ($entry->{future} && !$entry->{future}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{"future"} and not $entry->{"future"}->is_ready) 0 0 0
Condition0%0/3
$entry->{"future"} and not $entry->{"future"}->is_ready
!ll&&!rl&&r
000
MC/DC0%0/2
$entry->{"future"} and not $entry->{"future"}->is_ready
$entry->{"future"} not $entry->{"future"}->is_ready
Truth table0%0/3
A and not(B)
A= $entry->{"future"}B= not $entry->{"future"}->is_ready
ABresult
0X0
100
111
645 0 $entry->{future}->fail($error);
646 }
647 }
648 }
649  
650 # The single socket reader. Runs while there is work (inflight or pubsub).
651 # Calls _reader_fatal on any stream-alignment failure. The selector
652 # (_tasks) owns this task; _reader_running is cleared on every exit path
653 # via on_ready so _ensure_reader can restart it on the next submission.
654 0 ▶async sub _run_reader {
Subroutine _run_reader: not called CC=35 SCAR=71.4
655 0 my ($self) = @_;
656  
657 0 while (1) {
658 # Exit conditions.
659 0 ▶ return unless $self->{_socket_live};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_socket_live"} 0 0 0
660 0 ▶ last if !$self->{in_pubsub} && !@{$self->{inflight}};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"in_pubsub"} or @{$self->{"inflight"};} 0 0 0
Condition0%0/3
$self->{"in_pubsub"} or @{$self->{"inflight"};}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"in_pubsub"} or @{$self->{"inflight"};}
$self->{"in_pubsub"} @{$self->{"inflight"};}
Truth table0%0/3
A or B
A= $self->{"in_pubsub"}B= @{$self->{"inflight"};}
ABresult
1X1
011
000
661 0 ▶ last if $self->{in_pubsub} && !$self->{_subscription};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"in_pubsub"} and not $self->{"_subscription"} 0 0 0
Condition0%0/3
$self->{"in_pubsub"} and not $self->{"_subscription"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"in_pubsub"} and not $self->{"_subscription"}
$self->{"in_pubsub"} not $self->{"_subscription"}
Truth table0%0/3
A and not(B)
A= $self->{"in_pubsub"}B= not $self->{"_subscription"}
ABresult
0X0
100
111
662  
663 0 my $head = $self->{inflight}[0];
664 0 ▶ my $deadline = $head ? $head->{deadline} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$head ? : 0 0 0
665  
666 # Set up read future; track so _reader_fatal can cancel it.
667 0 my $read_f = Future::IO->read($self->{socket}, 65536);
668 0 $self->{_current_read_future} = $read_f;
669  
670 0 my ($returned_f, $timed_out) = await _await_with_deadline($read_f, $deadline);
671  
672 # Clear slot on success path; fatal clears it on timeout/cancel.
673 $self->{_current_read_future} = undef
674 0 ▶ if !$timed_out && $returned_f->is_ready && !$returned_f->is_failed;
Branch: 1 branch
BranchTrueFalseTotal
if not $timed_out and $returned_f->is_ready and not $returned_f->is_failed 0 0 0
Condition0%0/6
not $timed_out and $returned_f->is_ready and not $returned_f->is_failed
!ll&&!rl&&r
000
not $timed_out and $returned_f->is_ready
!ll&&!rl&&r
000
MC/DC0%0/3
not $timed_out and $returned_f->is_ready and not $returned_f->is_failed
not $timed_out $returned_f->is_ready not $returned_f->is_failed
Truth table0%0/4
not(A) and B and not(C)
A= not $timed_outB= $returned_f->is_readyC= not $returned_f->is_failed
ABCresult
0XX0
10X0
1100
1111
675  
676 0 ▶ if ($timed_out) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timed_out) 0 0 0
677 my $err = Async::Redis::Error::Timeout->new(
678 message => "Request timed out",
679 command => $head ? $head->{args} : undef,
680 timeout => $self->{request_timeout},
681 0 ▶ maybe_executed => 1,
Branch: 1 branch
BranchTrueFalseTotal
$head ? : 0 0 0
682 );
683 0 $self->_reader_fatal($err);
684 0 return;
685 }
686  
687 0 ▶ if ($returned_f->is_failed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($returned_f->is_failed) 0 0 0
688 0 my ($rerr) = $returned_f->failure;
689 my $err = Async::Redis::Error::Connection->new(
690 message => "Connection read error: $rerr",
691 host => $self->{host},
692 port => $self->{port},
693 0 );
694 0 $self->_reader_fatal($err);
695 0 return;
696 }
697  
698 0 my $buf = $returned_f->get;
699 0 ▶ if (!defined $buf || length($buf) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $buf or length $buf == 0) 0 0 0
Condition0%0/3
not defined $buf or length $buf == 0
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $buf or length $buf == 0
not defined $buf length $buf == 0
Truth table0%0/3
not(A) or B
A= not defined $bufB= length $buf == 0
ABresult
1X1
011
000
700 my $err = Async::Redis::Error::Connection->new(
701 message => "Connection closed by peer",
702 host => $self->{host},
703 port => $self->{port},
704 0 );
705 0 $self->_reader_fatal($err);
706 0 return;
707 }
708  
709 0 $self->{parser}->parse($buf);
710  
711 # Drain all complete messages the parser has.
712 0 ▶ while (my $msg = $self->{parser}->get_message) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = $self->{"parser"}->get_message) 0 0 0
713 0 my ($kind, $value) = $self->_decode_response_result($msg);
714  
715 0 ▶ if ($kind eq 'protocol_error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "protocol_error") 0 0 0
716 0 $self->_reader_fatal($value);
717 0 return;
718 }
719  
720 0 my $is_pubsub_message = 0;
721 0 ▶ if ($self->{in_pubsub} && $kind eq 'ok' && ref($value) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"in_pubsub"} and $kind eq "ok" and ref $value eq "ARRAY") 0 0 0
Condition0%0/6
$self->{"in_pubsub"} and $kind eq "ok" and ref $value eq "ARRAY"
!ll&&!rl&&r
000
$self->{"in_pubsub"} and $kind eq "ok"
!ll&&!rl&&r
000
MC/DC0%0/3
$self->{"in_pubsub"} and $kind eq "ok" and ref $value eq "ARRAY"
$self->{"in_pubsub"} $kind eq "ok" ref $value eq "ARRAY"
Truth table0%0/4
A and B and C
A= $self->{"in_pubsub"}B= $kind eq "ok"C= ref $value eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
722 0 ▶ my $frame_name = $value->[0] // '';
Condition0%0/2
$value->[0] // ""
l!l
00
MC/DC0%0/1
$value->[0] // ""
$value->[0]
Truth table0%0/2
A
A= $value->[0]
Aresult
11
00
723 0 ▶ $is_pubsub_message = 1
Branch: 1 branch
BranchTrueFalseTotal
if $frame_name eq "message" or $frame_name eq "pmessage" or $frame_name eq "smessage" 0 0 0
Condition0%0/6
$frame_name eq "message" or $frame_name eq "pmessage" or $frame_name eq "smessage"
l!l&&r!l&&!r
000
$frame_name eq "message" or $frame_name eq "pmessage"
l!l&&r!l&&!r
000
MC/DC0%0/3
$frame_name eq "message" or $frame_name eq "pmessage" or $frame_name eq "smessage"
$frame_name eq "message" $frame_name eq "pmessage" $frame_name eq "smessage"
Truth table0%0/4
A or B or C
A= $frame_name eq "message"B= $frame_name eq "pmessage"C= $frame_name eq "smessage"
ABCresult
1XX1
01X1
0011
0000
724 if $frame_name eq 'message'
725 || $frame_name eq 'pmessage'
726 || $frame_name eq 'smessage';
727 }
728  
729 0 ▶ if ($is_pubsub_message) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_pubsub_message) 0 0 0
730 0 my $sub = $self->{_subscription};
731 0 ▶ if (!$sub) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sub) 0 0 0
732 # No active subscription but got a message frame: strict desync.
733 0 $self->_reader_fatal(
734 Async::Redis::Error::Protocol->new(
735 message => "message frame but no active subscription",
736 )
737 );
738 0 return;
739 }
740 # _dispatch_frame is sync today (returns undef) and will become
741 # async in Task 15 (returning a Future for backpressure). Await
742 # only if we got a Future back.
743 0 my $dispatch_result = $sub->_dispatch_frame($value);
744 0 ▶ if (blessed($dispatch_result) && $dispatch_result->isa('Future')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($dispatch_result) and $dispatch_result->isa("Future")) 0 0 0
Condition0%0/3
builtin::blessed($dispatch_result) and $dispatch_result->isa("Future")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($dispatch_result) and $dispatch_result->isa("Future")
builtin::blessed($dispatch_result) $dispatch_result->isa("Future")
Truth table0%0/3
A and B
A= builtin::blessed($dispatch_result)B= $dispatch_result->isa("Future")
ABresult
0X0
100
111
745 0 await $dispatch_result;
746 }
747 0 next;
748 }
749  
750 0 ▶ if (!@{$self->{inflight}}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$self->{"inflight"};}) 0 0 0
751 # Strict: unexpected frame with empty inflight = desync.
752 0 $self->_reader_fatal(
753 Async::Redis::Error::Protocol->new(
754 message => "unexpected frame (kind=$kind) with empty inflight",
755 )
756 );
757 0 return;
758 }
759  
760 0 my $entry = shift @{$self->{inflight}};
761 0 ▶ if ($kind eq 'redis_error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq 'redis_error') { } 0 0 0
762 0 ▶ if (($entry->{redis_error} // 'fail') eq 'capture') {
Branch: 1 branch
BranchTrueFalseTotal
if (($entry->{'redis_error'} // 'fail') eq 'capture') { } 0 0 0
Condition0%0/2
$entry->{"redis_error"} // "fail"
l!l
00
MC/DC0%0/1
$entry->{"redis_error"} // "fail"
$entry->{"redis_error"}
Truth table0%0/2
A
A= $entry->{"redis_error"}
Aresult
11
00
763 0 ▶ $entry->{future}->done($value) unless $entry->{future}->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $entry->{"future"}->is_ready 0 0 0
764 } else {
765 0 ▶ $entry->{future}->fail($value) unless $entry->{future}->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $entry->{"future"}->is_ready 0 0 0
766 }
767 } else {
768 0 ▶ $entry->{future}->done($value) unless $entry->{future}->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $entry->{"future"}->is_ready 0 0 0
769 }
770 }
771 }
772 91 }
773  
774 # Start the reader if not already running. Idempotent.
775 #
776 # Ownership: the reader Future lives in $self->{_tasks} (a Future::Selector).
777 # The selector holds the strong reference and auto-removes the item on
778 # completion. $self->{_reader_running} is a boolean dedup guard — it's NOT
779 # a second source of truth about ownership, only a "is one already running?"
780 # flag that's cheap to check without peeking at selector internals.
781 #
782 # Failure propagation: because the reader is in the selector, any awaiting
783 # caller using $self->{_tasks}->run_until_ready($their_future) will see the
784 # reader's failure propagated to them. That's the structured-concurrency
785 # guarantee — no hanging callers when the reader dies unhandled.
786 0 ▶sub _ensure_reader {
Subroutine _ensure_reader: not called CC=2 SCAR=17.9
787 0 my ($self) = @_;
788 0 ▶ return if $self->{_reader_running};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_reader_running"} 0 0 0
789 0 $self->{_reader_running} = 1;
790 0 my $f = $self->_run_reader;
791 0 ▶ $f->on_ready(sub { $self->{_reader_running} = 0 });
Subroutine __ANON__: not called CC=1 SCAR=6.9
792 0 $self->{_tasks}->add(data => 'reader', f => $f);
793 0 return;
794 }
795  
796 # Read and parse one response
797 0 ▶async sub _read_response {
Subroutine _read_response: not called CC=5 SCAR=34.0
798 0 my ($self) = @_;
799  
800 # First check if parser already has a complete message
801 # (from previous read that contained multiple responses)
802 0 ▶ if (my $msg = $self->{parser}->get_message) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = $self->{"parser"}->get_message) 0 0 0
803 0 return $msg;
804 }
805  
806 # Read until we get a complete message
807 0 while (1) {
808 0 my $buf = await Future::IO->read($self->{socket}, 65536);
809  
810 # EOF
811 0 ▶ if (!defined $buf || length($buf) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $buf or length $buf == 0) 0 0 0
Condition0%0/3
not defined $buf or length $buf == 0
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $buf or length $buf == 0
not defined $buf length $buf == 0
Truth table0%0/3
not(A) or B
A= not defined $bufB= length $buf == 0
ABresult
1X1
011
000
812 0 die "Connection closed by server";
813 }
814  
815 0 $self->{parser}->parse($buf);
816  
817 0 ▶ if (my $msg = $self->{parser}->get_message) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = $self->{"parser"}->get_message) 0 0 0
818 0 return $msg;
819 }
820 }
821 91 }
822  
823 # Dispatch table mapping each blocking command to how its timeout is encoded.
824 # position: 'last' => final argument (seconds)
825 # position: N (integer) => argument at index N (seconds, unless unit=>'ms')
826 # position: 'block_option' => scan for BLOCK keyword, next arg is timeout (ms)
827 # unit: 'ms' => divide raw value by 1000 to get seconds
828 # A timeout of zero means "block indefinitely" — no client-side deadline.
829 91 my %BLOCKING_TIMEOUT = (
830 BLPOP => { position => 'last' },
831 BRPOP => { position => 'last' },
832 BRPOPLPUSH => { position => 'last' },
833 BLMOVE => { position => 'last' },
834 BZPOPMIN => { position => 'last' },
835 BZPOPMAX => { position => 'last' },
836 BLMPOP => { position => 0 },
837 BZMPOP => { position => 0 },
838 XREAD => { position => 'block_option', unit => 'ms' },
839 XREADGROUP => { position => 'block_option', unit => 'ms' },
840 WAIT => { position => 'last', unit => 'ms' },
841 WAITAOF => { position => 'last', unit => 'ms' },
842 );
843  
844 # Calculate deadline based on command type
845 14 ▶sub _calculate_deadline {
Subroutine _calculate_deadline: called CC=14 SCAR=26.4
846 14 my ($self, $cmd, @args) = @_;
847 14 ▶ $cmd = uc($cmd // '');
Condition50%1/2
$cmd // ""
l!l
140
MC/DC0%0/1
$cmd // ""
$cmd
Truth table50%1/2
A
A= $cmd
Aresult
11
00
848  
849 14 my $spec = $BLOCKING_TIMEOUT{$cmd};
850 14 ▶ if (!$spec) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($spec) 3 11 14
851 3 return Time::HiRes::time() + $self->{request_timeout};
852 }
853  
854 11 my $raw;
855 11 my $pos = $spec->{position};
856  
857 11 ▶ if ($pos eq 'last') {
Branch: 2 branches
BranchTrueFalseTotal
if ($pos eq 'last') { } 5 6 11
elsif ($pos eq 'block_option') { } 3 3 6
858 5 $raw = $args[-1];
859 }
860 elsif ($pos eq 'block_option') {
861 3 for my $i (0 .. $#args - 1) {
862 4 ▶ if (uc($args[$i] // '') eq 'BLOCK') {
Branch: 1 branch
BranchTrueFalseTotal
if (uc($args[$i] // "") eq "BLOCK") 2 2 4
Condition50%1/2
$args[$i] // ""
l!l
40
MC/DC0%0/1
$args[$i] // ""
$args[$i]
Truth table50%1/2
A
A= $args[$i]
Aresult
11
00
863 2 $raw = $args[$i + 1];
864 2 last;
865 }
866 }
867 # No BLOCK option found — non-blocking variant; use request_timeout
868 return Time::HiRes::time() + $self->{request_timeout}
869 3 ▶ unless defined $raw;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 1 2 3
870 }
871 else {
872 # Numeric index into @args
873 3 $raw = $args[$pos];
874 }
875  
876 10 ▶ if (!defined $raw || $raw !~ /^-?\d+(?:\.\d+)?$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $raw and $raw =~ /^-?\d+(?:\.\d+)?$/u) 1 9 10
Condition66%2/3
defined $raw and $raw =~ /^-?\d+(?:\.\d+)?$/u
!ll&&!rl&&r
019
MC/DC50%1/2
defined $raw and $raw =~ /^-?\d+(?:\.\d+)?$/u
defined $raw $raw =~ /^-?\d+(?:\.\d+)?$/u
Truth table66%2/3
A and B
A= defined $rawB= $raw =~ /^-?\d+(?:\.\d+)?$/u
ABresult
0X0
100
111
877 1 warn "_calculate_deadline: non-numeric timeout for $cmd; falling back to request_timeout\n";
878 1 return Time::HiRes::time() + $self->{request_timeout};
879 }
880  
881 9 ▶ my $seconds = ($spec->{unit} // 'seconds') eq 'ms'
Branch: 1 branch
BranchTrueFalseTotal
($spec->{'unit'} // 'seconds') eq 'ms' ? : 4 5 9
Condition100%2/2
$spec->{"unit"} // "seconds"
l!l
45
MC/DC100%1/1
$spec->{"unit"} // "seconds"
$spec->{"unit"}
Truth table100%2/2
A
A= $spec->{"unit"}
Aresult
11
00
882 ? $raw / 1000
883 : $raw + 0;
884  
885 # Zero means block indefinitely — no client-side deadline
886 9 ▶ return undef if $seconds == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $seconds == 0 3 6 9
887  
888 6 return Time::HiRes::time() + $seconds + $self->{blocking_timeout_buffer};
889 }
890  
891 7 ▶sub _ssl_verify_peer {
Subroutine _ssl_verify_peer: called CC=1 SCAR=0.0
892 7 require IO::Socket::SSL;
893 7 return IO::Socket::SSL::SSL_VERIFY_PEER();
894 }
895  
896 2 ▶sub _ssl_verify_none {
Subroutine _ssl_verify_none: called CC=1 SCAR=0.0
897 2 require IO::Socket::SSL;
898 2 return IO::Socket::SSL::SSL_VERIFY_NONE();
899 }
900  
901 # Build the IO::Socket::SSL option hash for the current connection.
902 # Handles chain verification, SNI, hostname identity checking, and
903 # client cert/key/CA forwarding. Called by _tls_upgrade and directly
904 # by unit tests.
905 5 ▶sub _build_tls_options {
Subroutine _build_tls_options: called CC=9 SCAR=22.0
906 5 my ($self) = @_;
907 5 my %ssl_opts = (SSL_startHandshake => 0);
908  
909 5 my $tls = $self->{tls};
910 5 ▶ my $tls_hash = ref $tls eq 'HASH' ? $tls : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $tls eq 'HASH' ? : 3 2 5
911  
912 5 ▶ my $verify = exists $tls_hash->{verify} ? !!$tls_hash->{verify} : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $tls_hash->{'verify'} ? : 1 4 5
913 5 ▶ my $verify_hostname = exists $tls_hash->{verify_hostname} ? !!$tls_hash->{verify_hostname} : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $tls_hash->{'verify_hostname'} ? : 1 4 5
914  
915 5 ▶ $ssl_opts{SSL_ca_file} = $tls_hash->{ca_file} if $tls_hash->{ca_file};
Branch: 1 branch
BranchTrueFalseTotal
if $tls_hash->{"ca_file"} 1 4 5
916 5 ▶ $ssl_opts{SSL_cert_file} = $tls_hash->{cert_file} if $tls_hash->{cert_file};
Branch: 1 branch
BranchTrueFalseTotal
if $tls_hash->{"cert_file"} 1 4 5
917 5 ▶ $ssl_opts{SSL_key_file} = $tls_hash->{key_file} if $tls_hash->{key_file};
Branch: 1 branch
BranchTrueFalseTotal
if $tls_hash->{"key_file"} 1 4 5
918  
919 5 ▶ if ($verify) {
Branch: 1 branch
BranchTrueFalseTotal
if ($verify) { } 4 1 5
920 4 $ssl_opts{SSL_verify_mode} = $self->_ssl_verify_peer;
921 4 $ssl_opts{SSL_hostname} = $self->{host};
922  
923 4 ▶ if ($verify_hostname) {
Branch: 1 branch
BranchTrueFalseTotal
if ($verify_hostname) 3 1 4
924 3 $ssl_opts{SSL_verifycn_name} = $self->{host};
925 3 $ssl_opts{SSL_verifycn_scheme} = 'default';
926 }
927 } else {
928 1 $ssl_opts{SSL_verify_mode} = $self->_ssl_verify_none;
929 }
930  
931 5 return %ssl_opts;
932 }
933  
934 # Non-blocking TLS upgrade
935 0 ▶async sub _tls_upgrade {
Subroutine _tls_upgrade: not called CC=9 SCAR=45.0
936 0 my ($self, $socket) = @_;
937  
938 0 require IO::Socket::SSL;
939  
940 0 my %ssl_opts = $self->_build_tls_options;
941  
942 # Start SSL (does not block because SSL_startHandshake => 0)
943 IO::Socket::SSL->start_SSL($socket, %ssl_opts)
944 or die Async::Redis::Error::Connection->new(
945 message => "SSL setup failed: " . IO::Socket::SSL::errstr(),
946 host => $self->{host},
947 port => $self->{port},
948 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
"IO::Socket::SSL"->start_SSL($socket, %ssl_opts) or die "Async::Redis::Error::Connection"->new("message", 'SSL setup failed: ' . IO::Socket::SSL::errstr(), "host", $self->{"host"}, "port", $self->{"port"}) 0 0 0
949  
950 # Drive handshake with non-blocking loop
951 0 my $deadline = Time::HiRes::time() + $self->{connect_timeout};
952  
953 0 while (1) {
954 # Check timeout
955 0 ▶ if (Time::HiRes::time() >= $deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Time::HiRes::time() >= $deadline) 0 0 0
956 die Async::Redis::Error::Timeout->new(
957 message => "TLS handshake timed out",
958 timeout => $self->{connect_timeout},
959 0 );
960 }
961  
962 # Attempt handshake step
963 0 my $rv = $socket->connect_SSL;
964  
965 0 ▶ if ($rv) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rv) 0 0 0
966 # Handshake complete!
967 0 return $socket;
968 }
969  
970 # Check what the handshake needs
971 0 my $remaining = $deadline - Time::HiRes::time();
972 0 ▶ $remaining = 0.1 if $remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining <= 0 0 0 0
973  
974 0 ▶ if ($IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_ERROR_WANT_READ()) {
Branch: 2 branches
BranchTrueFalseTotal
if ($IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_ERROR_WANT_READ()) { } 0 0 0
elsif ($IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_ERROR_WANT_WRITE()) { } 0 0 0
975 # Wait for socket to become readable with timeout
976 0 my $read_f = Future::IO->waitfor_readable($socket);
977 0 ▶ my $timeout_f = Future::IO->sleep($remaining)->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
978 0 return Future->fail('tls_timeout');
979 0 });
980  
981 0 my $wait_f = Future->wait_any($read_f, $timeout_f);
982 0 await $wait_f;
983  
984 0 ▶ if ($wait_f->is_failed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait_f->is_failed) 0 0 0
985 die Async::Redis::Error::Timeout->new(
986 message => "TLS handshake timed out",
987 timeout => $self->{connect_timeout},
988 0 );
989 }
990 }
991 elsif ($IO::Socket::SSL::SSL_ERROR == IO::Socket::SSL::SSL_ERROR_WANT_WRITE()) {
992 # Wait for socket to become writable with timeout
993 0 my $write_f = Future::IO->waitfor_writable($socket);
994 0 ▶ my $timeout_f = Future::IO->sleep($remaining)->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
995 0 return Future->fail('tls_timeout');
996 0 });
997  
998 0 my $wait_f = Future->wait_any($write_f, $timeout_f);
999 0 await $wait_f;
1000  
1001 0 ▶ if ($wait_f->is_failed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait_f->is_failed) 0 0 0
1002 die Async::Redis::Error::Timeout->new(
1003 message => "TLS handshake timed out",
1004 timeout => $self->{connect_timeout},
1005 0 );
1006 }
1007 }
1008 else {
1009 # Actual error
1010 die Async::Redis::Error::Connection->new(
1011 message => "TLS handshake failed: " . IO::Socket::SSL::errstr(),
1012 host => $self->{host},
1013 port => $self->{port},
1014 0 );
1015 }
1016 }
1017 91 }
1018  
1019 # Reconnect with exponential backoff
1020 5 ▶async sub _reconnect {
Subroutine _reconnect: called CC=6 SCAR=18.0
1021 5 my ($self) = @_;
1022  
1023 5 my $max = $self->{reconnect_max_attempts};
1024 5 my $attempt = 0;
1025  
1026 5 ▶ while (!$self->{connected}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"connected"}) 8 0 8
1027 8 $attempt++;
1028 8 $self->{_reconnect_attempt} = $attempt;
1029  
1030 8 my $ok = eval {
1031 8 await $self->connect;
1032 2 1;
1033 };
1034  
1035 8 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) 2 6 8
1036 2 $self->{_reconnect_attempt} = 0;
1037 2 last;
1038 }
1039  
1040 6 my $error = $@;
1041  
1042 # Fire on_error callback
1043 6 ▶ if ($self->{on_error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"on_error"}) 0 6 6
1044 0 $self->{on_error}->($self, $error);
1045 }
1046  
1047 # Honor reconnect_max_attempts cap so an unreachable Redis
1048 # doesn't spin forever. 0 means unlimited.
1049 6 ▶ if ($max && $attempt >= $max) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max and $attempt >= $max) 3 3 6
Condition66%2/3
$max and $attempt >= $max
!ll&&!rl&&r
033
MC/DC50%1/2
$max and $attempt >= $max
$max $attempt >= $max
Truth table66%2/3
A and B
A= $maxB= $attempt >= $max
ABresult
0X0
100
111
1050 3 $self->{_reconnect_attempt} = 0;
1051 3 die Async::Redis::Error::Disconnected->new(
1052 message => "Reconnect gave up after $max attempts",
1053 );
1054 }
1055  
1056 3 my $delay = $self->_calculate_backoff($attempt);
1057 3 await Future::IO->sleep($delay);
1058 }
1059  
1060 # Reset attempt counter on success so subsequent reconnects start fresh.
1061 2 $self->{_reconnect_attempt} = 0;
1062 91 }
1063  
1064 # Ensure the socket is live, reconnecting if configured.
1065 #
1066 # Dedup: $self->{_reconnect_future} is the Future for the in-flight
1067 # reconnect. Concurrent callers share it. The slot is the shared-await
1068 # signal, NOT the ownership — ownership lives in $self->{_tasks}.
1069 #
1070 # Structured-concurrency: the reconnect task is added to the selector
1071 # so any caller currently awaiting via run_until_ready sees reconnect
1072 # failures propagated.
1073 #
1074 # NOTE: dedup is race-safe only when called from inside the write
1075 # gate (which serialises callers). Outside the gate, a failed reconnect
1076 # could be observed after on_ready clears the slot, allowing a second
1077 # reconnect to start before state converges.
1078 0 ▶async sub _ensure_connected {
Subroutine _ensure_connected: not called CC=3 SCAR=24.8
1079 0 my ($self) = @_;
1080 0 ▶ return if $self->{_socket_live};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_socket_live"} 0 0 0
1081 0 ▶ if (my $f = $self->{_reconnect_future}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $f = $self->{"_reconnect_future"}) 0 0 0
1082 0 await $f;
1083 0 return;
1084 }
1085 0 my $f = $self->_reconnect;
1086 0 $self->{_reconnect_future} = $f;
1087 0 $self->{_tasks}->add(data => 'reconnect', f => $f);
1088 0 ▶ $f->on_ready(sub { $self->{_reconnect_future} = undef });
Subroutine __ANON__: not called CC=1 SCAR=6.9
1089 0 await $f;
1090 91 }
1091  
1092 # Reconnect and replay pubsub subscriptions
1093 1 ▶async sub _reconnect_pubsub {
Subroutine _reconnect_pubsub: called CC=4 SCAR=17.2
1094 1 my ($self) = @_;
1095  
1096 my $sub = $self->{_subscription}
1097 1 ▶ or die Async::Redis::Error::Disconnected->new(
Branch: 1 branch
BranchTrueFalseTotal
my $sub = $self->{"_subscription"} or die "Async::Redis::Error::Disconnected"->new("message", "No subscription to replay") 1 0 1
1098 message => "No subscription to replay",
1099 );
1100  
1101 1 my @replay = $sub->get_replay_commands;
1102  
1103 # Ensure connection state is fully cleaned up before reconnecting.
1104 # _reset_connection may have already been called by _read_response,
1105 # but if the socket was closed externally, we need to clean up
1106 # stale IO watchers and state here. It is safe to call twice —
1107 # the on_disconnect callback is guarded by $was_connected.
1108 1 $self->_reset_connection('pubsub_reconnect');
1109  
1110 1 await $self->_reconnect;
1111  
1112 # Re-enter pubsub mode before replaying so the unified reader
1113 # classifies incoming message frames correctly during replay.
1114 0 $self->{in_pubsub} = 1;
1115  
1116 # Replay all subscription commands through the write gate and unified
1117 # reader. Each channel/pattern gets its own command so confirmations
1118 # are matched one-to-one via the inflight queue.
1119 0 for my $cmd (@replay) {
1120 0 my ($command, @args) = @$cmd;
1121 0 for my $arg (@args) {
1122 0 await $self->_pubsub_command($command, $arg);
1123 }
1124 }
1125 91 }
1126  
1127 # Asynchronously reconnect after a pubsub connection drop. Called by
1128 # _reader_fatal when reconnect is enabled and a subscription is active.
1129 # Fires _resume_after_reconnect on the subscription on success, or
1130 # _fail_fatal on unrecoverable reconnect failure.
1131 0 ▶sub _reconnect_async {
Subroutine _reconnect_async: not called CC=3 SCAR=24.8
1132 0 my ($self, $sub) = @_;
1133  
1134 # Dedup against any reconnect already in progress (from either this
1135 # path or _ensure_connected). The slot is the shared signal.
1136 return if $self->{_reconnect_future}
1137 0 ▶ && !$self->{_reconnect_future}->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_reconnect_future"} and not $self->{"_reconnect_future"}->is_ready 0 0 0
Condition0%0/3
$self->{"_reconnect_future"} and not $self->{"_reconnect_future"}->is_ready
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"_reconnect_future"} and not $self->{"_reconnect_future"}->is_ready
$self->{"_reconnect_future"} not $self->{"_reconnect_future"}->is_ready
Truth table0%0/3
A and not(B)
A= $self->{"_reconnect_future"}B= not $self->{"_reconnect_future"}->is_ready
ABresult
0X0
100
111
1138  
1139 0 weaken(my $weak_self = $self);
1140 0 weaken(my $weak_sub = $sub);
1141  
1142 0 ▶ my $f = (async sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1143 # Reconnect the socket. _reconnect handles retry/backoff and
1144 # dies with Disconnected if reconnect_max_attempts is exhausted.
1145 0 await $weak_self->_reconnect;
1146  
1147 # Delegate the replay, on_reconnect, and driver-restart work to
1148 # the subscription's unified resume path. _resume_after_reconnect
1149 # handles clearing _paused, setting in_pubsub, replaying all
1150 # tracked channels/patterns, firing on_reconnect, and starting
1151 # the driver. Keeps the "who restarts what after reconnect"
1152 # logic in one place.
1153 0 ▶ if ($weak_sub) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_sub) 0 0 0
1154 0 await $weak_sub->_resume_after_reconnect;
1155 }
1156 0 })->();
1157  
1158 # Ownership: the selector owns the task; the slot is the dedup signal.
1159 # No ->retain — the selector holds the strong reference.
1160 0 $self->{_reconnect_future} = $f;
1161 0 $self->{_tasks}->add(data => 'pubsub-reconnect', f => $f);
1162  
1163 0 ▶ $f->on_ready(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1164 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
1165 0 $weak_self->{_reconnect_future} = undef;
1166 0 });
1167 0 ▶ $f->on_fail(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1168 0 my $err = shift;
1169 0 ▶ return unless $weak_sub;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_sub 0 0 0
1170 0 $weak_sub->_fail_fatal($err);
1171 0 });
1172  
1173 0 return;
1174 }
1175  
1176 # Execute a Redis command
1177 2 ▶async sub command {
Subroutine command: called CC=13 SCAR=37.3
Pod documented
1178 2 my ($self, $cmd, @args) = @_;
1179  
1180 # Check for fork - invalidate connection if PID changed
1181 2 $self->_check_fork;
1182  
1183 # Block regular commands on pubsub connection
1184 2 ▶ if ($self->{in_pubsub}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"in_pubsub"}) 0 2 2
1185 0 ▶ my $ucmd = uc($cmd // '');
Condition0%0/2
$cmd // ""
l!l
00
MC/DC0%0/1
$cmd // ""
$cmd
Truth table0%0/2
A
A= $cmd
Aresult
11
00
1186 0 ▶ unless ($ucmd =~ /^(SUBSCRIBE|UNSUBSCRIBE|PSUBSCRIBE|PUNSUBSCRIBE|SSUBSCRIBE|SUNSUBSCRIBE|PING|QUIT)$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ucmd =~ /^(SUBSCRIBE|UNSUBSCRIBE|PSUBSCRIBE|PUNSUBSCRIBE|SSUBSCRIBE|SUNSUBSCRIBE|PING|QUIT)$/u) 0 0 0
1187 0 die Async::Redis::Error::Protocol->new(
1188 message => "Cannot execute '$cmd' on connection in PubSub mode",
1189 );
1190 }
1191 }
1192  
1193 # Apply key prefixing if configured
1194 2 ▶ if (defined $self->{prefix} && $self->{prefix} ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"prefix"} and $self->{"prefix"} ne "") 0 2 2
Condition33%1/3
defined $self->{"prefix"} and $self->{"prefix"} ne ""
!ll&&!rl&&r
200
MC/DC0%0/2
defined $self->{"prefix"} and $self->{"prefix"} ne ""
defined $self->{"prefix"} $self->{"prefix"} ne ""
Truth table33%1/3
A and B
A= defined $self->{"prefix"}B= $self->{"prefix"} ne ""
ABresult
0X0
100
111
1195 @args = Async::Redis::KeyExtractor::apply_prefix(
1196 0 $self->{prefix}, $cmd, @args
1197 );
1198 }
1199  
1200 # Route through auto-pipeline if enabled
1201 2 ▶ if ($self->{_auto_pipeline}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_auto_pipeline"}) 0 2 2
1202 0 return await $self->{_auto_pipeline}->command($cmd, @args);
1203 }
1204  
1205 # Telemetry: start span and log send
1206 2 my $span_context;
1207 2 my $start_time = Time::HiRes::time();
1208 2 ▶ if ($self->{_telemetry}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_telemetry"}) 0 2 2
1209 0 $span_context = $self->{_telemetry}->start_command_span($cmd, @args);
1210 0 $self->{_telemetry}->log_send($cmd, @args);
1211 }
1212  
1213 2 my $raw_cmd = $self->_build_command($cmd, @args);
1214 2 my $deadline = $self->_calculate_deadline($cmd, @args);
1215 2 my $response = Future->new;
1216  
1217 2 my $result;
1218 my $error;
1219  
1220 2 my $submit_ok = eval {
1221 2 ▶ await $self->_with_write_gate(sub {
Subroutine __ANON__: called CC=1 SCAR=0.7
1222 2 ▶ return (async sub {
Subroutine __ANON__: called CC=3 SCAR=13.5
1223 # Ensure the socket is live. Reconnect if enabled, else fail.
1224 2 ▶ if (!$self->{_socket_live}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_socket_live"}) 2 0 2
1225 2 ▶ if ($self->_reconnect_enabled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_reconnect_enabled) { } 0 2 2
1226 0 await $self->_ensure_connected;
1227 } else {
1228 2 die Async::Redis::Error::Disconnected->new(
1229 message => "Not connected",
1230 );
1231 }
1232 }
1233 # Register inflight BEFORE writing so order matches the wire.
1234 0 $self->_add_inflight($response, $cmd, \@args, $deadline, 'fail');
1235 0 await $self->_send($raw_cmd);
1236 2 })->();
1237 2 });
1238 0 1;
1239 };
1240  
1241 2 ▶ if (!$submit_ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $submit_ok) { } 2 0 2
1242 2 $error = $@;
1243 # _with_write_gate already called _reader_fatal on write failure.
1244 } else {
1245 0 $self->_ensure_reader;
1246 # run_until_ready awaits $response while the selector pumps the
1247 # reader (and any other adopted tasks). If any selector task fails
1248 # unhandled — in particular, the reader — the failure propagates
1249 # here, so callers never hang waiting on a dead reader.
1250 0 my $await_ok = eval {
1251 0 $result = await $self->{_tasks}->run_until_ready($response);
1252 0 1;
1253 };
1254 0 ▶ if (!$await_ok) { $error = $@ }
Branch: 1 branch
BranchTrueFalseTotal
unless ($await_ok) 0 0 0
1255 }
1256  
1257 # Telemetry: log result and end span
1258 2 ▶ if ($self->{_telemetry}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_telemetry"}) 0 2 2
1259 0 my $elapsed_ms = (Time::HiRes::time() - $start_time) * 1000;
1260 0 ▶ if ($error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error) { } 0 0 0
1261 0 $self->{_telemetry}->log_error($error);
1262 }
1263 else {
1264 0 $self->{_telemetry}->log_recv($result, $elapsed_ms);
1265 }
1266 0 $self->{_telemetry}->end_command_span($span_context, $error);
1267 }
1268  
1269 2 ▶ die $error if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 2 0 2
1270 0 return $result;
1271 91 }
1272  
1273 # Read response with deadline enforcement
1274 0 ▶async sub _read_response_with_deadline {
Subroutine _read_response_with_deadline: not called CC=9 SCAR=45.0
1275 0 my ($self, $deadline, $cmd_ref) = @_;
1276  
1277 # First check if parser already has a complete message
1278 0 ▶ if (my $msg = $self->{parser}->get_message) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = $self->{"parser"}->get_message) 0 0 0
1279 0 return $msg;
1280 }
1281  
1282 # Read until we get a complete message
1283 0 while (1) {
1284 0 my $remaining = $deadline - Time::HiRes::time();
1285  
1286 0 ▶ if ($remaining <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining <= 0) 0 0 0
1287 0 $self->_reset_connection;
1288 die Async::Redis::Error::Timeout->new(
1289 message => "Request timed out after $self->{request_timeout}s",
1290 command => $cmd_ref,
1291 timeout => $self->{request_timeout},
1292 0 maybe_executed => 1, # already sent the command
1293 );
1294 }
1295  
1296 # Use wait_any for timeout
1297 0 my $read_f = Future::IO->read($self->{socket}, 65536);
1298  
1299 # Store reference so disconnect() can cancel it
1300 0 $self->{_current_read_future} = $read_f;
1301  
1302 0 ▶ my $timeout_f = Future::IO->sleep($remaining)->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1303 0 return Future->fail('read_timeout');
1304 0 });
1305  
1306 0 my $wait_f = Future->wait_any($read_f, $timeout_f);
1307 0 await $wait_f;
1308  
1309 # Clear stored reference after await completes
1310 0 $self->{_current_read_future} = undef;
1311  
1312 # Check if read was cancelled (by disconnect)
1313 0 ▶ if ($read_f->is_cancelled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($read_f->is_cancelled) 0 0 0
1314 0 die Async::Redis::Error::Disconnected->new(
1315 message => "Disconnected during read",
1316 );
1317 }
1318  
1319 0 ▶ if ($wait_f->is_failed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait_f->is_failed) 0 0 0
1320 0 my ($error) = $wait_f->failure;
1321 0 ▶ if ($error eq 'read_timeout') {
Branch: 1 branch
BranchTrueFalseTotal
if ($error eq "read_timeout") 0 0 0
1322 0 $self->_reset_connection;
1323 die Async::Redis::Error::Timeout->new(
1324 message => "Request timed out after $self->{request_timeout}s",
1325 command => $cmd_ref,
1326 timeout => $self->{request_timeout},
1327 0 maybe_executed => 1,
1328 );
1329 }
1330 0 $self->_reset_connection;
1331 0 die Async::Redis::Error::Connection->new(
1332 message => "$error",
1333 );
1334 }
1335  
1336 # Get the read result
1337 0 my $buf = $wait_f->get;
1338  
1339 # EOF
1340 0 ▶ if (!defined $buf || length($buf) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $buf or length $buf == 0) 0 0 0
Condition0%0/3
not defined $buf or length $buf == 0
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $buf or length $buf == 0
not defined $buf length $buf == 0
Truth table0%0/3
not(A) or B
A= not defined $bufB= length $buf == 0
ABresult
1X1
011
000
1341 0 $self->_reset_connection;
1342 0 die Async::Redis::Error::Connection->new(
1343 message => "Connection closed by server",
1344 );
1345 }
1346  
1347 0 $self->{parser}->parse($buf);
1348  
1349 0 ▶ if (my $msg = $self->{parser}->get_message) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = $self->{"parser"}->get_message) 0 0 0
1350 0 return $msg;
1351 }
1352 }
1353 91 }
1354  
1355 # Reset connection after timeout (stream is desynced)
1356 2 ▶sub _reset_connection {
Subroutine _reset_connection: called CC=11 SCAR=30.7
1357 2 my ($self, $reason) = @_;
1358 2 ▶ $reason //= 'timeout';
Condition50%1/2
$reason //= "timeout"
l!l
20
MC/DC0%0/1
$reason //= "timeout"
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
1359  
1360 2 my $was_connected = $self->{connected};
1361  
1362 # Cancel any active read future BEFORE closing socket
1363 # This ensures Future::IO unregisters its watcher while fileno is still valid
1364 2 ▶ if ($self->{_current_read_future} && !$self->{_current_read_future}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready) 0 2 2
Condition33%1/3
$self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready
!ll&&!rl&&r
200
MC/DC0%0/2
$self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready
$self->{"_current_read_future"} not $self->{"_current_read_future"}->is_ready
Truth table33%1/3
A and not(B)
A= $self->{"_current_read_future"}B= not $self->{"_current_read_future"}->is_ready
ABresult
0X0
100
111
1365 0 $self->{_current_read_future}->cancel;
1366 0 $self->{_current_read_future} = undef;
1367 }
1368  
1369 # Cancel any pending inflight operations before closing socket
1370 2 ▶ if (my $inflight = $self->{inflight}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $inflight = $self->{"inflight"}) 2 0 2
1371 2 for my $entry (@$inflight) {
1372 0 ▶ if ($entry->{future} && !$entry->{future}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{"future"} and not $entry->{"future"}->is_ready) 0 0 0
Condition0%0/3
$entry->{"future"} and not $entry->{"future"}->is_ready
!ll&&!rl&&r
000
MC/DC0%0/2
$entry->{"future"} and not $entry->{"future"}->is_ready
$entry->{"future"} not $entry->{"future"}->is_ready
Truth table0%0/3
A and not(B)
A= $entry->{"future"}B= not $entry->{"future"}->is_ready
ABresult
0X0
100
111
1373 0 $entry->{future}->cancel;
1374 }
1375 }
1376 2 $self->{inflight} = [];
1377 }
1378  
1379 2 ▶ if ($self->{socket}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"socket"}) 0 2 2
1380 0 $self->_close_socket;
1381 }
1382  
1383 2 $self->{_socket_live} = 0;
1384 2 $self->{_fatal_in_progress} = 0;
1385 2 $self->{_reader_running} = 0;
1386 2 $self->{_reconnect_future} = undef;
1387 2 $self->{connected} = 0;
1388 2 $self->{parser} = undef;
1389 2 $self->{in_pubsub} = 0;
1390  
1391 2 ▶ if ($was_connected && $self->{on_disconnect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($was_connected and $self->{"on_disconnect"}) 0 2 2
Condition66%2/3
$was_connected and $self->{"on_disconnect"}
!ll&&!rl&&r
110
MC/DC0%0/2
$was_connected and $self->{"on_disconnect"}
$was_connected $self->{"on_disconnect"}
Truth table66%2/3
A and B
A= $was_connectedB= $self->{"on_disconnect"}
ABresult
0X0
100
111
1392 0 $self->{on_disconnect}->($self, $reason);
1393 }
1394 }
1395  
1396 # Async write lock. The lock is a Future that resolves when the current
1397 # holder releases. Waiters chain onto it; each waiter replaces the slot
1398 # with its own Future before returning to the caller.
1399 5 ▶async sub _acquire_write_lock {
Subroutine _acquire_write_lock: called CC=3 SCAR=11.0
1400 5 my ($self) = @_;
1401  
1402 # Wait out any in-progress fatal. _reader_fatal is synchronous so this
1403 # is typically immediate, but a callback inside fatal could yield.
1404 # NOTE: this is a poll loop (sleep(0) per tick). Acceptable because
1405 # _reader_fatal's transition is synchronous; if teardown ever becomes
1406 # async, replace with a one-shot Future waiters can await on.
1407 5 ▶ while ($self->{_fatal_in_progress}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_fatal_in_progress"}) 42 5 47
1408 42 await Future::IO->sleep(0);
1409 }
1410  
1411 # Chain onto the existing lock Future if any.
1412 5 ▶ while (my $prev = $self->{_write_lock}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $prev = $self->{"_write_lock"}) 1 5 6
1413 1 await $prev;
1414 }
1415  
1416 # We are the owner now. Install our own Future so the next caller
1417 # waits on us.
1418 5 $self->{_write_lock} = Future->new;
1419 5 return;
1420 91 }
1421  
1422 5 ▶sub _release_write_lock {
Subroutine _release_write_lock: called CC=3 SCAR=12.5
1423 5 my ($self) = @_;
1424 5 my $f = delete $self->{_write_lock};
1425 5 ▶ $f->done if $f && !$f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $f and not $f->is_ready 5 0 5
Condition33%1/3
$f and not $f->is_ready
!ll&&!rl&&r
005
MC/DC0%0/2
$f and not $f->is_ready
$f not $f->is_ready
Truth table33%1/3
A and not(B)
A= $fB= not $f->is_ready
ABresult
0X0
100
111
1426 }
1427  
1428 # Wrap a body in gate acquire/release with guaranteed release even if the
1429 # body dies. On body failure, calls _reader_fatal with a transport error.
1430 2 ▶async sub _with_write_gate {
Subroutine _with_write_gate: called CC=4 SCAR=14.8
1431 2 my ($self, $body) = @_;
1432 2 await $self->_acquire_write_lock;
1433 0 my $ok = eval { await $body->(); 1 };
1434 2 my $err = $@;
1435 2 $self->_release_write_lock;
1436 2 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 2 0 2
1437 # Convert to a typed transport error if not already.
1438 2 my $typed = (ref $err && eval { $err->isa('Async::Redis::Error') })
1439 ? $err
1440 : Async::Redis::Error::Connection->new(
1441 message => "Write failed: $err",
1442 host => $self->{host},
1443 port => $self->{port},
1444 2 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
ref $err && eval { do { $err->isa('Async::Redis::Error') } } ? : 2 0 2
Condition33%1/3
ref $err and eval { do { $err->isa("Async::Redis::Error") } }
!ll&&!rl&&r
002
MC/DC0%0/2
ref $err and eval { do { $err->isa("Async::Redis::Error") } }
ref $err eval { do { $err->isa("Async::Redis::Error") } }
Truth table33%1/3
A and B
A= ref $errB= eval { do { $err->isa("Async::Redis::Error") } }
ABresult
0X0
100
111
1445 2 $self->_reader_fatal($typed);
1446 2 die $typed;
1447 }
1448 0 return;
1449 91 }
1450  
1451 # Is reconnect enabled for this client?
1452 2 ▶sub _reconnect_enabled {
Subroutine _reconnect_enabled: called CC=1 SCAR=0.0
1453 2 my ($self) = @_;
1454 2 return !!$self->{reconnect};
1455 }
1456  
1457 # Central "something went wrong with the stream" transition. Detaches
1458 # inflight BEFORE closing the socket so the typed error is preserved
1459 # (the old _reset_connection cancels inflight directly, which would
1460 # overwrite $typed_error with a generic cancellation).
1461 10 ▶sub _reader_fatal {
Subroutine _reader_fatal: called CC=19 SCAR=35.6
1462 10 my ($self, $typed_error) = @_;
1463  
1464 10 ▶ return if $self->{_fatal_in_progress};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_fatal_in_progress"} 1 9 10
1465 9 $self->{_fatal_in_progress} = 1;
1466  
1467 9 my $ok = eval {
1468 # 1. Capture pre-reset state BEFORE any mutation.
1469 9 my $was_connected = $self->{connected};
1470 9 my $was_pubsub = $self->{in_pubsub};
1471 9 my $subscription = $self->{_subscription};
1472  
1473 # 2. Detach inflight so the close path cannot cancel them.
1474 9 my $detached_inflight = $self->{inflight};
1475 9 $self->{inflight} = [];
1476  
1477 # 3. Detach auto-pipeline's queued-but-not-registered commands.
1478 9 my $detached_autopipe = [];
1479 9 ▶ if (my $ap = $self->{_auto_pipeline}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ap = $self->{"_auto_pipeline"}) 1 8 9
1480 1 $detached_autopipe = $ap->_detach_queued;
1481 }
1482  
1483 # 4. Cancel the current read BEFORE closing the socket.
1484 9 ▶ if ($self->{_current_read_future}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready) 0 9 9
Condition33%1/3
$self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready
!ll&&!rl&&r
900
MC/DC0%0/2
$self->{"_current_read_future"} and not $self->{"_current_read_future"}->is_ready
$self->{"_current_read_future"} not $self->{"_current_read_future"}->is_ready
Truth table33%1/3
A and not(B)
A= $self->{"_current_read_future"}B= not $self->{"_current_read_future"}->is_ready
ABresult
0X0
100
111
1485 && !$self->{_current_read_future}->is_ready) {
1486 0 $self->{_current_read_future}->cancel;
1487 }
1488 9 $self->{_current_read_future} = undef;
1489  
1490 # 5. Close socket, clear internal state.
1491 9 ▶ $self->_close_socket if $self->{socket};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"socket"} 0 9 9
1492 9 $self->{_socket_live} = 0;
1493 9 $self->{connected} = 0;
1494 9 $self->{parser} = undef;
1495 9 $self->{in_pubsub} = 0;
1496 9 $self->{_reader_running} = 0;
1497  
1498 # 6. Fail all detached futures with the SAME typed error.
1499 9 for my $entry (@$detached_inflight, @$detached_autopipe) {
1500 3 ▶ next if $entry->{future}->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $entry->{"future"}->is_ready 0 3 3
1501 3 $entry->{future}->fail($typed_error);
1502 }
1503  
1504 # 7. Pubsub reconnect handoff. _fail_fatal and _pause_for_reconnect
1505 # land in Phase 2 (Task 14); for now this branch only triggers
1506 # when the subscription API is used, and we call the older
1507 # _close path as a placeholder until Task 14 replaces it.
1508 9 ▶ if ($was_pubsub && $subscription) {
Branch: 1 branch
BranchTrueFalseTotal
if ($was_pubsub and $subscription) 0 9 9
Condition33%1/3
$was_pubsub and $subscription
!ll&&!rl&&r
900
MC/DC0%0/2
$was_pubsub and $subscription
$was_pubsub $subscription
Truth table33%1/3
A and B
A= $was_pubsubB= $subscription
ABresult
0X0
100
111
1509 0 ▶ if ($self->_reconnect_enabled
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_reconnect_enabled and $subscription->can('_pause_for_reconnect')) { } 0 0 0
elsif ($subscription->can('_fail_fatal')) { } 0 0 0
Condition0%0/3
$self->_reconnect_enabled and $subscription->can("_pause_for_reconnect")
!ll&&!rl&&r
000
MC/DC0%0/2
$self->_reconnect_enabled and $subscription->can("_pause_for_reconnect")
$self->_reconnect_enabled $subscription->can("_pause_for_reconnect")
Truth table0%0/3
A and B
A= $self->_reconnect_enabledB= $subscription->can("_pause_for_reconnect")
ABresult
0X0
100
111
1510 && $subscription->can('_pause_for_reconnect')) {
1511 0 $subscription->_pause_for_reconnect;
1512 0 ▶ if ($self->can('_reconnect_async')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can("_reconnect_async")) 0 0 0
1513 0 $self->_reconnect_async($subscription);
1514 }
1515 }
1516 elsif ($subscription->can('_fail_fatal')) {
1517 0 $subscription->_fail_fatal($typed_error);
1518 }
1519 else {
1520 # Pre-Phase-2 fallback: existing _close method.
1521 0 ▶ $subscription->_close if $subscription->can('_close');
Branch: 1 branch
BranchTrueFalseTotal
if $subscription->can("_close") 0 0 0
1522 }
1523 }
1524  
1525 # 8. on_disconnect: only if we were publicly connected.
1526 9 ▶ if ($was_connected && $self->{on_disconnect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($was_connected and $self->{"on_disconnect"}) 4 5 9
Condition100%3/3
$was_connected and $self->{"on_disconnect"}
!ll&&!rl&&r
324
MC/DC100%2/2
$was_connected and $self->{"on_disconnect"}
$was_connected $self->{"on_disconnect"}
Truth table100%3/3
A and B
A= $was_connectedB= $self->{"on_disconnect"}
ABresult
0X0
100
111
1527 4 $self->{on_disconnect}->($self, "$typed_error");
1528 }
1529  
1530 8 1;
1531 };
1532  
1533 9 my $caught = $@;
1534 # Always clear the guard, even if a callback died.
1535 9 $self->{_fatal_in_progress} = 0;
1536 9 ▶ die $caught if !$ok && $caught;
Branch: 1 branch
BranchTrueFalseTotal
if not $ok and $caught 1 8 9
Condition66%2/3
not $ok and $caught
!ll&&!rl&&r
801
MC/DC50%1/2
not $ok and $caught
not $ok $caught
Truth table66%2/3
not(A) and B
A= not $okB= $caught
ABresult
0X0
100
111
1537 }
1538  
1539 # Decode Protocol::Redis response to Perl value
1540 0 ▶sub _decode_response {
Subroutine _decode_response: not called CC=8 SCAR=42.8
1541 0 my ($self, $msg) = @_;
1542  
1543 0 ▶ return undef unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 0 0 0
1544  
1545 0 my $type = $msg->{type};
1546 0 my $data = $msg->{data};
1547  
1548 # Simple string (+)
1549 0 ▶ if ($type eq '+') {
Branch: 5 branches
BranchTrueFalseTotal
if ($type eq '+') { } 0 0 0
elsif ($type eq '-') { } 0 0 0
elsif ($type eq ':') { } 0 0 0
elsif ($type eq '$') { } 0 0 0
elsif ($type eq '*') { } 0 0 0
1550 0 return $data;
1551 }
1552 # Error (-)
1553 elsif ($type eq '-') {
1554 0 die Async::Redis::Error::Redis->from_message($data);
1555 }
1556 # Integer (:)
1557 elsif ($type eq ':') {
1558 0 return 0 + $data;
1559 }
1560 # Bulk string ($)
1561 elsif ($type eq '$') {
1562 0 return $data; # undef for null bulk
1563 }
1564 # Array (*)
1565 elsif ($type eq '*') {
1566 0 ▶ return undef unless defined $data; # null array
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 0 0
1567 0 return [ map { $self->_decode_response($_) } @$data ];
1568 }
1569  
1570 0 return $data;
1571 }
1572  
1573 # Non-throwing decoder used by the unified reader. Classifies each frame
1574 # as one of:
1575 # ('ok', $decoded_value) - normal response
1576 # ('redis_error', $error_object) - -ERR frame from Redis
1577 # ('protocol_error', $error_object) - fatal desync (malformed)
1578 14 ▶sub _decode_response_result {
Subroutine _decode_response_result: called CC=12 SCAR=25.1
1579 14 my ($self, $msg) = @_;
1580  
1581 14 ▶ if (!defined $msg) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $msg) 1 13 14
1582 1 return ('protocol_error', Async::Redis::Error::Protocol->new(
1583 message => 'undef message from parser',
1584 ));
1585 }
1586  
1587 13 ▶ my $type = $msg->{type} // '';
Condition50%1/2
$msg->{"type"} // ""
l!l
130
MC/DC0%0/1
$msg->{"type"} // ""
$msg->{"type"}
Truth table50%1/2
A
A= $msg->{"type"}
Aresult
11
00
1588 13 my $data = $msg->{data};
1589  
1590 13 ▶ if ($type eq '+') {
Branch: 5 branches
BranchTrueFalseTotal
if ($type eq '+') { } 3 10 13
elsif ($type eq '-') { } 2 8 10
elsif ($type eq ':') { } 3 5 8
elsif ($type eq '$') { } 2 3 5
elsif ($type eq '*') { } 2 1 3
1591 3 return ('ok', $data);
1592 }
1593 elsif ($type eq '-') {
1594 2 return ('redis_error', Async::Redis::Error::Redis->from_message($data));
1595 }
1596 elsif ($type eq ':') {
1597 3 ▶ return ('ok', 0 + ($data // 0));
Condition50%1/2
$data // 0
l!l
30
MC/DC0%0/1
$data // 0
$data
Truth table50%1/2
A
A= $data
Aresult
11
00
1598 }
1599 elsif ($type eq '$') {
1600 2 return ('ok', $data);
1601 }
1602 elsif ($type eq '*') {
1603 2 ▶ return ('ok', undef) if !defined $data; # nil array
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 2 2
1604 2 my @out;
1605 2 for my $child (@$data) {
1606 5 my ($k, $v) = $self->_decode_response_result($child);
1607 5 ▶ if ($k eq 'protocol_error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($k eq "protocol_error") 0 5 5
1608 0 return ($k, $v); # propagate fatal
1609 }
1610 5 push @out, $v;
1611 }
1612 2 return ('ok', \@out);
1613 }
1614 else {
1615 1 return ('protocol_error', Async::Redis::Error::Protocol->new(
1616 message => "unknown frame type: $type",
1617 ));
1618 }
1619 }
1620  
1621 # ============================================================================
1622 # Convenience Commands
1623 # ============================================================================
1624  
1625 0 ▶async sub ping {
Subroutine ping: not called CC=1 SCAR=6.9
Pod documented
1626 0 my ($self) = @_;
1627 0 return await $self->command('PING');
1628 91 }
1629  
1630 0 ▶async sub set {
Subroutine set: not called CC=5 SCAR=34.0
Pod undocumented
1631 0 my ($self, $key, $value, %opts) = @_;
1632 0 my @cmd = ('SET', $key, $value);
1633 0 ▶ push @cmd, 'EX', $opts{ex} if exists $opts{ex};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"ex"} 0 0 0
1634 0 ▶ push @cmd, 'PX', $opts{px} if exists $opts{px};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"px"} 0 0 0
1635 0 ▶ push @cmd, 'NX' if $opts{nx};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"nx"} 0 0 0
1636 0 ▶ push @cmd, 'XX' if $opts{xx};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"xx"} 0 0 0
1637 0 return await $self->command(@cmd);
1638 91 }
1639  
1640 0 ▶async sub get {
Subroutine get: not called CC=1 SCAR=6.9
Pod undocumented
1641 0 my ($self, $key) = @_;
1642 0 return await $self->command('GET', $key);
1643 91 }
1644  
1645 0 ▶async sub del {
Subroutine del: not called CC=1 SCAR=6.9
Pod undocumented
1646 0 my ($self, @keys) = @_;
1647 0 return await $self->command('DEL', @keys);
1648 91 }
1649  
1650 0 ▶async sub incr {
Subroutine incr: not called CC=1 SCAR=6.9
Pod undocumented
1651 0 my ($self, $key) = @_;
1652 0 return await $self->command('INCR', $key);
1653 91 }
1654  
1655 0 ▶async sub lpush {
Subroutine lpush: not called CC=1 SCAR=6.9
Pod undocumented
1656 0 my ($self, $key, @values) = @_;
1657 0 return await $self->command('LPUSH', $key, @values);
1658 91 }
1659  
1660 0 ▶async sub rpush {
Subroutine rpush: not called CC=1 SCAR=6.9
Pod undocumented
1661 0 my ($self, $key, @values) = @_;
1662 0 return await $self->command('RPUSH', $key, @values);
1663 91 }
1664  
1665 0 ▶async sub lpop {
Subroutine lpop: not called CC=1 SCAR=6.9
Pod undocumented
1666 0 my ($self, $key) = @_;
1667 0 return await $self->command('LPOP', $key);
1668 91 }
1669  
1670 0 ▶async sub lrange {
Subroutine lrange: not called CC=1 SCAR=6.9
Pod undocumented
1671 0 my ($self, $key, $start, $stop) = @_;
1672 0 return await $self->command('LRANGE', $key, $start, $stop);
1673 91 }
1674  
1675 0 ▶async sub keys {
Subroutine keys: not called CC=2 SCAR=17.9
Pod documented
1676 0 my ($self, $pattern) = @_;
1677 0 ▶ return await $self->command('KEYS', $pattern // '*');
Condition0%0/2
$pattern // "*"
l!l
00
MC/DC0%0/1
$pattern // "*"
$pattern
Truth table0%0/2
A
A= $pattern
Aresult
11
00
1678 91 }
1679  
1680 0 ▶async sub flushdb {
Subroutine flushdb: not called CC=1 SCAR=6.9
Pod undocumented
1681 0 my ($self) = @_;
1682 0 return await $self->command('FLUSHDB');
1683 91 }
1684  
1685 # ============================================================================
1686 # Lua Scripting
1687 # ============================================================================
1688  
1689 0 ▶async sub script_load {
Subroutine script_load: not called CC=1 SCAR=6.9
Pod documented
1690 0 my ($self, $script) = @_;
1691 0 return await $self->command('SCRIPT', 'LOAD', $script);
1692 91 }
1693  
1694 0 ▶async sub script_exists {
Subroutine script_exists: not called CC=1 SCAR=6.9
Pod documented
1695 0 my ($self, @shas) = @_;
1696 0 return await $self->command('SCRIPT', 'EXISTS', @shas);
1697 91 }
1698  
1699 0 ▶async sub script_flush {
Subroutine script_flush: not called CC=2 SCAR=17.9
Pod documented
1700 0 my ($self, $mode) = @_;
1701 0 my @args = ('SCRIPT', 'FLUSH');
1702 0 ▶ push @args, $mode if $mode; # ASYNC or SYNC
Branch: 1 branch
BranchTrueFalseTotal
if $mode 0 0 0
1703 0 return await $self->command(@args);
1704 91 }
1705  
1706 0 ▶async sub script_kill {
Subroutine script_kill: not called CC=1 SCAR=6.9
Pod documented
1707 0 my ($self) = @_;
1708 0 return await $self->command('SCRIPT', 'KILL');
1709 91 }
1710  
1711 0 ▶async sub evalsha_or_eval {
Subroutine evalsha_or_eval: not called CC=3 SCAR=24.8
Pod undocumented
1712 0 my ($self, $sha, $script, $numkeys, @keys_and_args) = @_;
1713  
1714 # Try EVALSHA first
1715 0 my $result;
1716 0 eval {
1717 0 $result = await $self->evalsha($sha, $numkeys, @keys_and_args);
1718 };
1719  
1720 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1721 0 my $error = $@;
1722  
1723 # Check if it's a NOSCRIPT error
1724 0 ▶ if ("$error" =~ /NOSCRIPT/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ("$error" =~ /NOSCRIPT/iu) { } 0 0 0
1725 # Fall back to EVAL (which also loads the script)
1726 0 $result = await $self->eval($script, $numkeys, @keys_and_args);
1727 }
1728 else {
1729 # Re-throw other errors
1730 0 die $error;
1731 }
1732 }
1733  
1734 0 return $result;
1735 91 }
1736  
1737 0 ▶sub script {
Subroutine script: not called CC=1 SCAR=6.9
Pod documented
1738 0 my ($self, $code) = @_;
1739 0 return Async::Redis::Script->new(
1740 redis => $self,
1741 script => $code,
1742 );
1743 }
1744  
1745 # Define a named script command
1746 # Usage: $redis->define_command(name => { keys => N, lua => '...' })
1747 0 ▶sub define_command {
Subroutine define_command: not called CC=8 SCAR=42.8
Pod documented
1748 0 my ($self, $name, $def) = @_;
1749  
1750 0 ▶ die "Command name required" unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 0 0
Condition0%0/3
defined $name and length $name
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table0%0/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
1751 0 ▶ die "Command definition required" unless ref $def eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $def eq "HASH" 0 0 0
1752 0 ▶ die "Lua script required (lua => '...')" unless defined $def->{lua};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $def->{"lua"} 0 0 0
1753 die "define_command install option is not supported; use run_script()"
1754 0 ▶ if exists $def->{install};
Branch: 1 branch
BranchTrueFalseTotal
if exists $def->{"install"} 0 0 0
1755  
1756 # Validate name (alphanumeric and underscore only)
1757 0 ▶ die "Invalid command name '$name' - use only alphanumeric and underscore"
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/u 0 0 0
1758 unless $name =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/;
1759  
1760 my $script = Async::Redis::Script->new(
1761 redis => $self,
1762 script => $def->{lua},
1763 name => $name,
1764 num_keys => $def->{keys} // 'dynamic',
1765 description => $def->{description},
1766 0 ▶ );
Condition0%0/2
$def->{"keys"} // "dynamic"
l!l
00
MC/DC0%0/1
$def->{"keys"} // "dynamic"
$def->{"keys"}
Truth table0%0/2
A
A= $def->{"keys"}
Aresult
11
00
1767  
1768 0 $self->{_scripts}{$name} = $script;
1769  
1770 0 return $script;
1771 }
1772  
1773 # Run a registered script by name
1774 # Usage: $redis->run_script('name', @keys_then_args)
1775 # If num_keys is 'dynamic', first arg is the key count
1776 0 ▶async sub run_script {
Subroutine run_script: not called CC=4 SCAR=30.0
Pod documented
1777 0 my ($self, $name, @args) = @_;
1778  
1779 0 ▶ my $script = $self->{_scripts}{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $script = $self->{"_scripts"}{$name} or die "Unknown script: '${name}' - use define_command() first" 0 0 0
1780 or die "Unknown script: '$name' - use define_command() first";
1781  
1782 0 my $num_keys = $script->num_keys;
1783  
1784 # Handle dynamic key count
1785 0 ▶ if ($num_keys eq 'dynamic') {
Branch: 1 branch
BranchTrueFalseTotal
if ($num_keys eq "dynamic") 0 0 0
1786 0 $num_keys = shift @args;
1787 0 ▶ die "Key count required as first argument for dynamic script '$name'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $num_keys 0 0 0
1788 unless defined $num_keys;
1789 }
1790  
1791 # Split args into keys and argv
1792 0 my @keys = splice(@args, 0, $num_keys);
1793 0 return await $script->run(\@keys, \@args);
1794 91 }
1795  
1796 # Get a registered script by name
1797 0 ▶sub get_script {
Subroutine get_script: not called CC=1 SCAR=6.9
Pod documented
1798 0 my ($self, $name) = @_;
1799 0 return $self->{_scripts}{$name};
1800 }
1801  
1802 # List all registered script names
1803 0 ▶sub list_scripts {
Subroutine list_scripts: not called CC=1 SCAR=6.9
Pod documented
1804 0 my ($self) = @_;
1805 0 return CORE::keys %{$self->{_scripts}};
1806 }
1807  
1808 # Preload all registered scripts to Redis
1809 # Useful before pipeline execution
1810 0 ▶async sub preload_scripts {
Subroutine preload_scripts: not called CC=3 SCAR=24.8
Pod documented
1811 0 my ($self) = @_;
1812  
1813 0 my @names = $self->list_scripts;
1814 0 ▶ return 0 unless @names;
Branch: 1 branch
BranchTrueFalseTotal
unless @names 0 0 0
1815  
1816 0 for my $name (@names) {
1817 0 my $script = $self->{_scripts}{$name};
1818 0 await $self->script_load($script->script);
1819 }
1820  
1821 0 return scalar @names;
1822 91 }
1823  
1824 # ============================================================================
1825 # SCAN Iterators
1826 # ============================================================================
1827  
1828 0 ▶sub scan_iter {
Subroutine scan_iter: not called CC=1 SCAR=6.9
Pod documented
1829 0 my ($self, %opts) = @_;
1830 return Async::Redis::Iterator->new(
1831 redis => $self,
1832 command => 'SCAN',
1833 match => $opts{match},
1834 count => $opts{count},
1835 type => $opts{type},
1836 0 );
1837 }
1838  
1839 0 ▶sub hscan_iter {
Subroutine hscan_iter: not called CC=1 SCAR=6.9
Pod undocumented
1840 0 my ($self, $key, %opts) = @_;
1841 return Async::Redis::Iterator->new(
1842 redis => $self,
1843 command => 'HSCAN',
1844 key => $key,
1845 match => $opts{match},
1846 count => $opts{count},
1847 0 );
1848 }
1849  
1850 0 ▶sub sscan_iter {
Subroutine sscan_iter: not called CC=1 SCAR=6.9
Pod undocumented
1851 0 my ($self, $key, %opts) = @_;
1852 return Async::Redis::Iterator->new(
1853 redis => $self,
1854 command => 'SSCAN',
1855 key => $key,
1856 match => $opts{match},
1857 count => $opts{count},
1858 0 );
1859 }
1860  
1861 0 ▶sub zscan_iter {
Subroutine zscan_iter: not called CC=1 SCAR=6.9
Pod undocumented
1862 0 my ($self, $key, %opts) = @_;
1863 return Async::Redis::Iterator->new(
1864 redis => $self,
1865 command => 'ZSCAN',
1866 key => $key,
1867 match => $opts{match},
1868 count => $opts{count},
1869 0 );
1870 }
1871  
1872 # ============================================================================
1873 # Transactions
1874 # ============================================================================
1875  
1876 0 ▶async sub multi {
Subroutine multi: not called CC=4 SCAR=30.0
Pod documented
1877 0 my ($self, $callback) = @_;
1878  
1879 # Prevent nested multi() calls
1880 die "Cannot nest multi() calls - already in a transaction"
1881 0 ▶ if $self->{in_multi};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"in_multi"} 0 0 0
1882  
1883 # Mark that we're collecting transaction commands
1884 0 $self->{in_multi} = 1;
1885  
1886 0 my @commands;
1887 0 eval {
1888 # Create transaction collector
1889 0 my $tx = Async::Redis::Transaction->new(redis => $self);
1890  
1891 # Run callback to collect commands
1892 0 await $callback->($tx);
1893  
1894 0 @commands = $tx->commands;
1895 };
1896 0 my $collect_error = $@;
1897  
1898 0 ▶ if ($collect_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($collect_error) 0 0 0
1899 0 $self->{in_multi} = 0;
1900 0 die $collect_error;
1901 }
1902  
1903 # If no commands queued, return empty result
1904 0 ▶ unless (@commands) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@commands) 0 0 0
1905 0 $self->{in_multi} = 0;
1906 0 return [];
1907 }
1908  
1909 # Execute transaction (in_multi already set)
1910 0 return await $self->_execute_transaction(\@commands);
1911 91 }
1912  
1913 0 ▶async sub _execute_transaction {
Subroutine _execute_transaction: not called CC=3 SCAR=24.8
1914 0 my ($self, $commands) = @_;
1915  
1916 # in_multi should already be set by caller
1917  
1918 0 my $results;
1919 0 eval {
1920 # Send MULTI
1921 0 await $self->command('MULTI');
1922  
1923 # Queue all commands (they return +QUEUED)
1924 0 for my $cmd (@$commands) {
1925 0 await $self->command(@$cmd);
1926 }
1927  
1928 # Execute and get results
1929 0 $results = await $self->command('EXEC');
1930 };
1931 0 my $error = $@;
1932  
1933 # Always clear transaction state
1934 0 $self->{in_multi} = 0;
1935  
1936 0 ▶ if ($error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error) 0 0 0
1937 # Try to clean up
1938 0 eval { await $self->command('DISCARD') };
1939 0 die $error;
1940 }
1941  
1942 0 return $results;
1943 91 }
1944  
1945 # Accessor for pool cleanliness tracking
1946 1 ▶sub in_multi { shift->{in_multi} }
Subroutine in_multi: called CC=1 SCAR=0.0
Pod documented
1947 1 ▶sub watching { shift->{watching} }
Subroutine watching: called CC=1 SCAR=0.0
Pod documented
1948 0 ▶sub in_pubsub { shift->{in_pubsub} }
Subroutine in_pubsub: not called CC=1 SCAR=6.9
Pod documented
1949 0 ▶sub inflight_count { scalar @{shift->{inflight} // []} }
Subroutine inflight_count: not called CC=2 SCAR=17.9
Pod documented
Condition0%0/2
+(shift())->{"inflight"} // []
l!l
00
MC/DC0%0/1
+(shift())->{"inflight"} // []
+(shift())->{"inflight"}
Truth table0%0/2
A
A= +(shift())->{"inflight"}
Aresult
11
00
1950  
1951 # Is connection dirty (unsafe to reuse)?
1952 2 ▶sub is_dirty {
Subroutine is_dirty: called CC=6 SCAR=19.3
Pod documented
1953 2 my ($self) = @_;
1954  
1955 2 ▶ return 1 if $self->{in_multi};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"in_multi"} 0 2 2
1956 2 ▶ return 1 if $self->{watching};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"watching"} 0 2 2
1957 2 ▶ return 1 if $self->{in_pubsub};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"in_pubsub"} 0 2 2
1958 2 ▶ return 1 if @{$self->{inflight} // []} > 0;
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"inflight"} // [];} > 0 0 2 2
Condition50%1/2
$self->{"inflight"} // []
l!l
20
MC/DC0%0/1
$self->{"inflight"} // []
$self->{"inflight"}
Truth table50%1/2
A
A= $self->{"inflight"}
Aresult
11
00
1959  
1960 2 return 0;
1961 }
1962  
1963 1 ▶async sub watch {
Subroutine watch: called CC=1 SCAR=0.6
Pod documented
1964 1 my ($self, @keys) = @_;
1965 1 my $result = await $self->command('WATCH', @keys);
1966 0 $self->{watching} = 1;
1967 0 return $result;
1968 91 }
1969  
1970 0 ▶async sub unwatch {
Subroutine unwatch: not called CC=1 SCAR=6.9
Pod documented
1971 0 my ($self) = @_;
1972 0 my $result = await $self->command('UNWATCH');
1973 0 $self->{watching} = 0;
1974 0 return $result;
1975 91 }
1976  
1977 1 ▶async sub multi_start {
Subroutine multi_start: called CC=1 SCAR=0.6
Pod documented
1978 1 my ($self) = @_;
1979 1 my $result = await $self->command('MULTI');
1980 0 $self->{in_multi} = 1;
1981 0 return $result;
1982 91 }
1983  
1984 0 ▶async sub exec {
Subroutine exec: not called CC=1 SCAR=6.9
Pod documented
1985 0 my ($self) = @_;
1986 0 my $result = await $self->command('EXEC');
1987 0 $self->{in_multi} = 0;
1988 0 $self->{watching} = 0; # EXEC clears watches
1989 0 return $result;
1990 91 }
1991  
1992 0 ▶async sub discard {
Subroutine discard: not called CC=1 SCAR=6.9
Pod documented
1993 0 my ($self) = @_;
1994 0 my $result = await $self->command('DISCARD');
1995 0 $self->{in_multi} = 0;
1996 0 $self->{watching} = 0; # DISCARD clears watches
1997 0 return $result;
1998 91 }
1999  
2000 0 ▶async sub watch_multi {
Subroutine watch_multi: not called CC=7 SCAR=40.3
Pod documented
2001 0 my ($self, $keys, $callback) = @_;
2002  
2003 0 my $watch_active = 0;
2004 0 my $multi_started = 0;
2005 0 my $results;
2006  
2007 0 my $ok = eval {
2008 # WATCH must be unwound on any pre-MULTI failure, including a
2009 # callback die, otherwise the connection remains poisoned.
2010 0 await $self->watch(@$keys);
2011 0 $watch_active = 1;
2012  
2013 # Get current values of watched keys
2014 0 my %watched;
2015 0 for my $key (@$keys) {
2016 0 $watched{$key} = await $self->get($key);
2017 }
2018  
2019 # Create transaction collector
2020 0 my $tx = Async::Redis::Transaction->new(redis => $self);
2021  
2022 # Run callback with watched values
2023 0 await $callback->($tx, \%watched);
2024  
2025 0 my @commands = $tx->commands;
2026  
2027 # If no commands queued, just unwatch and return empty
2028 0 ▶ unless (@commands) {
Branch: 1 branch
BranchTrueFalseTotal
if (@commands) { } 0 0 0
2029 0 await $self->unwatch;
2030 0 $watch_active = 0;
2031 0 $results = [];
2032 }
2033 else {
2034 0 await $self->multi_start;
2035 0 $multi_started = 1;
2036  
2037 0 for my $cmd (@commands) {
2038 0 await $self->command(@$cmd);
2039 }
2040  
2041 0 $results = await $self->exec;
2042 0 $multi_started = 0;
2043 0 $watch_active = 0;
2044 }
2045  
2046 0 1;
2047 };
2048 0 my $error = $@;
2049  
2050 0 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
2051 0 ▶ if ($multi_started) {
Branch: 2 branches
BranchTrueFalseTotal
if ($multi_started) { } 0 0 0
elsif ($watch_active) { } 0 0 0
2052 0 eval { await $self->discard; 1 };
2053 }
2054 elsif ($watch_active) {
2055 0 eval { await $self->unwatch; 1 };
2056 }
2057  
2058 # Cleanup can fail on a dead socket; keep local state conservative
2059 # and preserve the original caller-facing error.
2060 0 $self->{in_multi} = 0;
2061 0 $self->{watching} = 0;
2062  
2063 0 die $error;
2064 }
2065  
2066 # EXEC returns undef/nil if WATCH failed
2067 0 return $results;
2068 91 }
2069  
2070 # ============================================================================
2071 # PUB/SUB
2072 # ============================================================================
2073  
2074 # Wait for inflight commands to complete before mode change
2075 0 ▶async sub _wait_for_inflight_drain {
Subroutine _wait_for_inflight_drain: not called CC=6 SCAR=37.4
2076 0 my ($self, $timeout) = @_;
2077 0 ▶ $timeout //= 30;
Condition0%0/2
$timeout //= 30
l!l
00
MC/DC0%0/1
$timeout //= 30
$timeout
Truth table0%0/2
A
A= $timeout
Aresult
11
00
2078  
2079 0 ▶ return unless @{$self->{inflight}};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"inflight"};} 0 0 0
2080  
2081 0 my $deadline = Time::HiRes::time() + $timeout;
2082  
2083 0 ▶ while (@{$self->{inflight}} && Time::HiRes::time() < $deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"inflight"};} and &Time::HiRes::time() < $deadline) 0 0 0
Condition0%0/3
@{$self->{"inflight"};} and &Time::HiRes::time() < $deadline
!ll&&!rl&&r
000
MC/DC0%0/2
@{$self->{"inflight"};} and &Time::HiRes::time() < $deadline
@{$self->{"inflight"};} &Time::HiRes::time() < $deadline
Truth table0%0/3
A and B
A= @{$self->{"inflight"};}B= &Time::HiRes::time() < $deadline
ABresult
0X0
100
111
2084 0 await Future::IO->sleep(0.001);
2085 }
2086  
2087 0 ▶ if (@{$self->{inflight}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"inflight"};}) 0 0 0
2088 0 $self->_fail_all_inflight("Timeout waiting for inflight commands");
2089 }
2090 91 }
2091  
2092 0 ▶async sub publish {
Subroutine publish: not called CC=1 SCAR=6.9
Pod documented
2093 0 my ($self, $channel, $message) = @_;
2094 0 return await $self->command('PUBLISH', $channel, $message);
2095 91 }
2096  
2097 0 ▶async sub spublish {
Subroutine spublish: not called CC=1 SCAR=6.9
Pod documented
2098 0 my ($self, $channel, $message) = @_;
2099 0 return await $self->command('SPUBLISH', $channel, $message);
2100 91 }
2101  
2102 # Subscribe to channels - returns a Subscription object
2103 0 ▶async sub subscribe {
Subroutine subscribe: not called CC=6 SCAR=37.4
Pod documented
2104 0 my ($self, @channels) = @_;
2105  
2106 die Async::Redis::Error::Disconnected->new(
2107 message => "Not connected",
2108 0 ▶ ) unless $self->{connected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"connected"} 0 0 0
2109  
2110 # Wait for pending commands before entering PubSub mode
2111 0 await $self->_wait_for_inflight_drain;
2112  
2113 # Clear a stale closed subscription so we allocate a fresh object.
2114 0 ▶ if ($self->{_subscription} && $self->{_subscription}->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_subscription"} and $self->{"_subscription"}->is_closed) 0 0 0
Condition0%0/3
$self->{"_subscription"} and $self->{"_subscription"}->is_closed
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"_subscription"} and $self->{"_subscription"}->is_closed
$self->{"_subscription"} $self->{"_subscription"}->is_closed
Truth table0%0/3
A and B
A= $self->{"_subscription"}B= $self->{"_subscription"}->is_closed
ABresult
0X0
100
111
2115 0 delete $self->{_subscription};
2116 }
2117  
2118 # Create or reuse subscription
2119 0 ▶ my $sub = $self->{_subscription} //= Async::Redis::Subscription->new(redis => $self);
Condition0%0/3
$self->{"_subscription"} //= "Async::Redis::Subscription"->new("redis", $self)
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_subscription"} //= "Async::Redis::Subscription"->new("redis", $self)
$self->{"_subscription"} "Async::Redis::Subscription"->new("redis", $self)
Truth table0%0/3
A //= B
A= $self->{"_subscription"}B= "Async::Redis::Subscription"->new("redis", $self)
ABresult
1X1
011
000
2120  
2121 # Set in_pubsub BEFORE submitting so the unified reader classifies
2122 # racing message frames correctly (e.g. published before our
2123 # confirmation arrives).
2124 0 $self->{in_pubsub} = 1;
2125  
2126 # Issue one SUBSCRIBE per channel through the write gate and unified
2127 # reader. Each call awaits its matching confirmation frame.
2128 0 for my $ch (@channels) {
2129 0 await $self->_pubsub_command('SUBSCRIBE', $ch);
2130 0 $sub->_add_channel($ch);
2131 }
2132  
2133 0 return $sub;
2134 91 }
2135  
2136 # Pattern subscribe
2137 0 ▶async sub psubscribe {
Subroutine psubscribe: not called CC=6 SCAR=37.4
Pod documented
2138 0 my ($self, @patterns) = @_;
2139  
2140 die Async::Redis::Error::Disconnected->new(
2141 message => "Not connected",
2142 0 ▶ ) unless $self->{connected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"connected"} 0 0 0
2143  
2144 # Wait for pending commands before entering PubSub mode
2145 0 await $self->_wait_for_inflight_drain;
2146  
2147 # Clear a stale closed subscription so we allocate a fresh object.
2148 0 ▶ if ($self->{_subscription} && $self->{_subscription}->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_subscription"} and $self->{"_subscription"}->is_closed) 0 0 0
Condition0%0/3
$self->{"_subscription"} and $self->{"_subscription"}->is_closed
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"_subscription"} and $self->{"_subscription"}->is_closed
$self->{"_subscription"} $self->{"_subscription"}->is_closed
Truth table0%0/3
A and B
A= $self->{"_subscription"}B= $self->{"_subscription"}->is_closed
ABresult
0X0
100
111
2149 0 delete $self->{_subscription};
2150 }
2151  
2152 0 ▶ my $sub = $self->{_subscription} //= Async::Redis::Subscription->new(redis => $self);
Condition0%0/3
$self->{"_subscription"} //= "Async::Redis::Subscription"->new("redis", $self)
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_subscription"} //= "Async::Redis::Subscription"->new("redis", $self)
$self->{"_subscription"} "Async::Redis::Subscription"->new("redis", $self)
Truth table0%0/3
A //= B
A= $self->{"_subscription"}B= "Async::Redis::Subscription"->new("redis", $self)
ABresult
1X1
011
000
2153  
2154 0 $self->{in_pubsub} = 1;
2155  
2156 0 for my $p (@patterns) {
2157 0 await $self->_pubsub_command('PSUBSCRIBE', $p);
2158 0 $sub->_add_pattern($p);
2159 }
2160  
2161 0 return $sub;
2162 91 }
2163  
2164 # Sharded subscribe (Redis 7+)
2165 0 ▶async sub ssubscribe {
Subroutine ssubscribe: not called CC=6 SCAR=37.4
Pod documented
2166 0 my ($self, @channels) = @_;
2167  
2168 die Async::Redis::Error::Disconnected->new(
2169 message => "Not connected",
2170 0 ▶ ) unless $self->{connected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"connected"} 0 0 0
2171  
2172 # Wait for pending commands before entering PubSub mode
2173 0 await $self->_wait_for_inflight_drain;
2174  
2175 # Clear a stale closed subscription so we allocate a fresh object.
2176 0 ▶ if ($self->{_subscription} && $self->{_subscription}->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_subscription"} and $self->{"_subscription"}->is_closed) 0 0 0
Condition0%0/3
$self->{"_subscription"} and $self->{"_subscription"}->is_closed
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"_subscription"} and $self->{"_subscription"}->is_closed
$self->{"_subscription"} $self->{"_subscription"}->is_closed
Truth table0%0/3
A and B
A= $self->{"_subscription"}B= $self->{"_subscription"}->is_closed
ABresult
0X0
100
111
2177 0 delete $self->{_subscription};
2178 }
2179  
2180 0 ▶ my $sub = $self->{_subscription} //= Async::Redis::Subscription->new(redis => $self);
Condition0%0/3
$self->{"_subscription"} //= "Async::Redis::Subscription"->new("redis", $self)
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_subscription"} //= "Async::Redis::Subscription"->new("redis", $self)
$self->{"_subscription"} "Async::Redis::Subscription"->new("redis", $self)
Truth table0%0/3
A //= B
A= $self->{"_subscription"}B= "Async::Redis::Subscription"->new("redis", $self)
ABresult
1X1
011
000
2181  
2182 0 $self->{in_pubsub} = 1;
2183  
2184 0 for my $ch (@channels) {
2185 0 await $self->_pubsub_command('SSUBSCRIBE', $ch);
2186 0 $sub->_add_sharded_channel($ch);
2187 }
2188  
2189 0 return $sub;
2190 91 }
2191  
2192 # Read pubsub frame (subscription confirmation or message)
2193 1 ▶async sub _read_pubsub_frame {
Subroutine _read_pubsub_frame: called CC=2 SCAR=8.4
2194 1 my ($self) = @_;
2195  
2196 die Async::Redis::Error::Disconnected->new(
2197 message => "Not connected",
2198 1 ▶ ) unless $self->{connected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"connected"} 1 0 1
2199  
2200 0 my $msg = await $self->_read_response();
2201 0 return $self->_decode_response($msg);
2202 91 }
2203  
2204 # Execute a single pubsub management command (SUBSCRIBE, UNSUBSCRIBE,
2205 # PSUBSCRIBE, PUNSUBSCRIBE, SSUBSCRIBE, SUNSUBSCRIBE) through the write
2206 # gate and unified reader. Each call registers one inflight entry and
2207 # awaits the matching confirmation frame from the reader.
2208 #
2209 # Use instead of _send_command + _read_pubsub_frame when in_pubsub=1
2210 # so that the unified reader (_run_reader) remains the sole socket
2211 # reader. Does not apply prefix or go through auto-pipeline.
2212 0 ▶async sub _pubsub_command {
Subroutine _pubsub_command: not called CC=2 SCAR=17.9
2213 0 my ($self, $cmd, @args) = @_;
2214  
2215 0 my $raw_cmd = $self->_build_command($cmd, @args);
2216 0 my $deadline = $self->_calculate_deadline($cmd, @args);
2217 0 my $response = Future->new;
2218  
2219 0 my $submit_ok = eval {
2220 0 ▶ await $self->_with_write_gate(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2221 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2222 0 ▶ if (!$self->{_socket_live}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_socket_live"}) 0 0 0
2223 0 die Async::Redis::Error::Disconnected->new(
2224 message => "Not connected",
2225 );
2226 }
2227 # Register inflight BEFORE writing so order matches the wire.
2228 0 $self->_add_inflight($response, $cmd, \@args, $deadline, 'fail');
2229 0 await $self->_send($raw_cmd);
2230 0 })->();
2231 0 });
2232 0 1;
2233 };
2234  
2235 0 ▶ unless ($submit_ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($submit_ok) 0 0 0
2236 0 my $err = $@;
2237 0 die $err;
2238 }
2239  
2240 0 $self->_ensure_reader;
2241 0 return await $response;
2242 91 }
2243  
2244 # Send command without reading response (for pubsub)
2245 0 ▶async sub _send_command {
Subroutine _send_command: not called CC=1 SCAR=6.9
2246 0 my ($self, @args) = @_;
2247  
2248 0 my $cmd = $self->_build_command(@args);
2249 0 await $self->_send($cmd);
2250 91 }
2251  
2252 # Read next pubsub message (blocking) - for compatibility
2253 0 ▶async sub _read_pubsub_message {
Subroutine _read_pubsub_message: not called CC=1 SCAR=6.9
2254 0 my ($self) = @_;
2255  
2256 0 my $msg = await $self->_read_response();
2257  
2258 # Message format: ['message', $channel, $payload]
2259 # or: ['pmessage', $pattern, $channel, $payload]
2260 0 return $msg;
2261 91 }
2262  
2263 # ============================================================================
2264 # Pipelining
2265 # ============================================================================
2266  
2267 0 ▶sub pipeline {
Subroutine pipeline: not called CC=2 SCAR=17.9
Pod documented
2268 0 my ($self, %opts) = @_;
2269 return Async::Redis::Pipeline->new(
2270 redis => $self,
2271 max_depth => $opts{max_depth} // $self->{pipeline_depth},
2272 0 ▶ );
Condition0%0/3
$opts{"max_depth"} // $self->{"pipeline_depth"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{"max_depth"} // $self->{"pipeline_depth"}
$opts{"max_depth"} $self->{"pipeline_depth"}
Truth table0%0/3
A // B
A= $opts{"max_depth"}B= $self->{"pipeline_depth"}
ABresult
1X1
011
000
2273 }
2274  
2275 # Execute multiple commands, return all responses
2276 0 ▶async sub _execute_pipeline {
Subroutine _execute_pipeline: not called CC=8 SCAR=42.8
2277 0 my ($self, $commands) = @_;
2278 0 ▶ return [] unless @$commands;
Branch: 1 branch
BranchTrueFalseTotal
unless @$commands 0 0 0
2279  
2280 0 my $start_time = Time::HiRes::time();
2281 0 my $count = scalar @$commands;
2282  
2283 # Build one RESP buffer and one Future per command up front.
2284 0 my $buffer = '';
2285 0 my @futures;
2286 my @deadlines;
2287 0 for my $cmd (@$commands) {
2288 0 $buffer .= $self->_build_command(@$cmd);
2289 0 push @futures, Future->new;
2290 0 push @deadlines, $self->_calculate_deadline(@$cmd);
2291 }
2292  
2293 0 ▶ await $self->_with_write_gate(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2294 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
2295 0 ▶ if (!$self->{_socket_live}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_socket_live"}) 0 0 0
2296 0 ▶ if ($self->_reconnect_enabled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_reconnect_enabled) { } 0 0 0
2297 0 await $self->_ensure_connected;
2298 } else {
2299 0 die Async::Redis::Error::Disconnected->new(
2300 message => "Not connected",
2301 );
2302 }
2303 }
2304 0 for my $i (0 .. $#$commands) {
2305 $self->_add_inflight(
2306 $futures[$i],
2307 $commands->[$i][0],
2308 0 [ @{$commands->[$i]}[1..$#{$commands->[$i]}] ],
2309 $deadlines[$i],
2310 'capture',
2311 );
2312 }
2313 0 await $self->_send($buffer);
2314 0 })->();
2315 0 });
2316  
2317 0 $self->_ensure_reader;
2318  
2319 # Await every future. capture policy means Redis errors come back as
2320 # done($error_object); transport failures come back as fail().
2321 0 my @results;
2322 0 for my $i (0 .. $#futures) {
2323 0 my $ok = eval { push @results, await $futures[$i]; 1 };
2324 0 ▶ next if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
2325 # Transport failure mid-pipeline: the remaining futures already
2326 # got _reader_fatal's typed error. Collect them too (as error
2327 # values) so the caller sees a full array.
2328 0 push @results, $@;
2329 0 for my $j ($i + 1 .. $#futures) {
2330 0 my $r_ok = eval { push @results, await $futures[$j]; 1 };
2331 0 ▶ push @results, $@ unless $r_ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $r_ok 0 0 0
2332 }
2333 0 last;
2334 }
2335  
2336 0 ▶ if ($self->{_telemetry}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_telemetry"}) 0 0 0
2337 0 my $elapsed_ms = (Time::HiRes::time() - $start_time) * 1000;
2338 0 $self->{_telemetry}->record_pipeline($count, $elapsed_ms);
2339 }
2340  
2341 0 return \@results;
2342 91 }
2343  
2344 91 1;
2345  
2346 __END__
↑ Summary blib/lib/Async/Redis/Subscription.pm »