blib/lib/EV/Kafka.pm

filter: Statementstmt 81.4% 1130 / 1388 Branchbran 54.2% 445 / 820 Conditioncond 46.9% 257 / 547 MC/DCmcdc 19.3% 59 / 305 Subroutinesub 85.7% 108 / 126 Podpod 100% 1 / 1 totaltotal 62.7% 2000 / 3187 CC 692 SCAR 39.4
CC
692
Cov
66%
__ANON__
322.4
__ANON__
272.0
offsets_for
112.7
CRAP 51.3
↑ Summary Kafka.xs »
1 package EV::Kafka;
2 34 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 34 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 34 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 34 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
7 34 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 34 our $VERSION = '0.06';
9 34 XSLoader::load __PACKAGE__, $VERSION;
10 }
11  
12 55 ▶sub new {
Subroutine new: called CC=23 SCAR=32.2
Pod documented
13 55 my ($class, %opts) = @_;
14  
15 55 my $loop = delete $opts{loop}; # passed through to per-conn _new on demand
16  
17 # Parse brokers
18 55 ▶ my $brokers = delete $opts{brokers} // '127.0.0.1:9092';
Condition100%2/2
delete $opts{"brokers"} // "127.0.0.1:9092"
l!l
523
MC/DC100%1/1
delete $opts{"brokers"} // "127.0.0.1:9092"
delete $opts{"brokers"}
Truth table100%2/2
A
A= delete $opts{"brokers"}
Aresult
11
00
19 55 my @bootstrap;
20 55 for my $b (split /,/, $brokers) {
21 58 $b =~ s/^\s+|\s+$//g;
22 58 my ($h, $p) = split /:/, $b, 2;
23 58 ▶ $p //= 9092;
Condition100%2/2
$p //= 9092
l!l
571
MC/DC100%1/1
$p //= 9092
$p
Truth table100%2/2
A
A= $p
Aresult
11
00
24 58 push @bootstrap, [$h, $p + 0];
25 }
26  
27 # Store config
28 my $cfg = {
29 bootstrap => \@bootstrap,
30 client_id => delete $opts{client_id} // 'ev-kafka',
31 tls => delete $opts{tls} // 0,
32 tls_ca_file => delete $opts{tls_ca_file},
33 tls_skip_verify => delete $opts{tls_skip_verify} // 0,
34 sasl => delete $opts{sasl},
35 0 ▶ on_error => delete $opts{on_error} // sub { die "EV::Kafka: @_\n" },
Subroutine __ANON__: not called CC=1 SCAR=6.9
36 on_connect => delete $opts{on_connect},
37 on_message => delete $opts{on_message},
38 acks => delete $opts{acks} // -1,
39 linger_ms => delete $opts{linger_ms} // 5,
40 batch_size => delete $opts{batch_size} // 16384,
41 partitioner => delete $opts{partitioner},
42 compression => delete $opts{compression}, # 'lz4', 'gzip', or undef
43 idempotent => delete $opts{idempotent} // 0,
44 transactional_id => delete $opts{transactional_id}, # enables transactions
45 fetch_max_wait_ms => delete $opts{fetch_max_wait_ms} // 500,
46 fetch_max_bytes => delete $opts{fetch_max_bytes} // 1048576,
47 fetch_min_bytes => delete $opts{fetch_min_bytes} // 1,
48 metadata_refresh => delete $opts{metadata_refresh} // 300,
49 55 ▶ flush_timeout => delete $opts{flush_timeout} // 30,
Condition70%19/27
delete $opts{"client_id"} // "ev-kafka"
l!l
055
delete $opts{"tls"} // 0
l!l
154
delete $opts{"tls_skip_verify"} // 0
l!l
055
delete $opts{"on_error"} // sub { die "EV::Kafka: @_\n"; }
l!l&&r!l&&!r
45100
delete $opts{"acks"} // -1
l!l
352
delete $opts{"linger_ms"} // 5
l!l
055
delete $opts{"batch_size"} // 16384
l!l
055
delete $opts{"idempotent"} // 0
l!l
451
delete $opts{"fetch_max_wait_ms"} // 500
l!l
055
delete $opts{"fetch_max_bytes"} // 1048576
l!l
055
delete $opts{"fetch_min_bytes"} // 1
l!l
055
delete $opts{"metadata_refresh"} // 300
l!l
154
delete $opts{"flush_timeout"} // 30
l!l
154
MC/DC0%0/1
delete $opts{"client_id"} // "ev-kafka"
delete $opts{"client_id"}
MC/DC100%1/1
delete $opts{"tls"} // 0
delete $opts{"tls"}
MC/DC0%0/1
delete $opts{"tls_skip_verify"} // 0
delete $opts{"tls_skip_verify"}
MC/DC0%0/2
delete $opts{"on_error"} // sub { die "EV::Kafka: @_\n"; }
delete $opts{"on_error"} sub { die "EV::Kafka: @_\n"; }
MC/DC100%1/1
delete $opts{"acks"} // -1
delete $opts{"acks"}
MC/DC0%0/1
delete $opts{"linger_ms"} // 5
delete $opts{"linger_ms"}
MC/DC0%0/1
delete $opts{"batch_size"} // 16384
delete $opts{"batch_size"}
MC/DC100%1/1
delete $opts{"idempotent"} // 0
delete $opts{"idempotent"}
MC/DC0%0/1
delete $opts{"fetch_max_wait_ms"} // 500
delete $opts{"fetch_max_wait_ms"}
MC/DC0%0/1
delete $opts{"fetch_max_bytes"} // 1048576
delete $opts{"fetch_max_bytes"}
MC/DC0%0/1
delete $opts{"fetch_min_bytes"} // 1
delete $opts{"fetch_min_bytes"}
MC/DC100%1/1
delete $opts{"metadata_refresh"} // 300
delete $opts{"metadata_refresh"}
MC/DC100%1/1
delete $opts{"flush_timeout"} // 30
delete $opts{"flush_timeout"}
Truth table50%1/2
A
A= delete $opts{"client_id"}
Aresult
11
00
Truth table100%2/2
A
A= delete $opts{"tls"}
Aresult
11
00
Truth table50%1/2
A
A= delete $opts{"tls_skip_verify"}
Aresult
11
00
Truth table66%2/3
A // B
A= delete $opts{"on_error"}B= sub { die "EV::Kafka: @_\n"; }
ABresult
1X1
011
000
Truth table100%2/2
A
A= delete $opts{"acks"}
Aresult
11
00
Truth table50%1/2
A
A= delete $opts{"linger_ms"}
Aresult
11
00
Truth table50%1/2
A
A= delete $opts{"batch_size"}
Aresult
11
00
Truth table100%2/2
A
A= delete $opts{"idempotent"}
Aresult
11
00
Truth table50%1/2
A
A= delete $opts{"fetch_max_wait_ms"}
Aresult
11
00
Truth table50%1/2
A
A= delete $opts{"fetch_max_bytes"}
Aresult
11
00
Truth table50%1/2
A
A= delete $opts{"fetch_min_bytes"}
Aresult
11
00
Truth table100%2/2
A
A= delete $opts{"metadata_refresh"}
Aresult
11
00
Truth table100%2/2
A
A= delete $opts{"flush_timeout"}
Aresult
11
00
50 };
51  
52 55 ▶ Carp::croak("EV::Kafka: unknown option(s): " . join(', ', sort keys %opts))
Branch: 1 branch
BranchTrueFalseTotal
if %opts 1 54 55
53 if %opts;
54  
55 # Internal state
56 54 $cfg->{closed} = 0; # set by close()/DESTROY; gates everything
57 54 $cfg->{conns} = {}; # node_id => EV::Kafka::Conn
58 54 $cfg->{meta} = undef; # latest metadata response
59 54 $cfg->{leaders} = {}; # "topic:partition" => node_id
60 54 $cfg->{broker_map}= {}; # node_id => {host, port}
61 54 $cfg->{connected} = 0;
62 54 $cfg->{meta_pending} = 0;
63 54 $cfg->{pending_ops} = []; # ops waiting for metadata
64  
65 # Producer state
66 54 $cfg->{batches} = {}; # "topic:partition" => [{rec, cb}]
67 54 $cfg->{next_sequence} = {}; # "topic:partition" => next sequence number
68 54 $cfg->{producer_id} = -1;
69 54 $cfg->{producer_epoch} = -1;
70 54 $cfg->{rr_counter} = 0;
71 # InitProducerId state machine: idle | init | ready | failed:$msg.
72 # Single-flight: 'init' queues completion callbacks in _pid_cbs.
73 54 $cfg->{_pid} = 'idle';
74 54 $cfg->{_pid_cbs} = [];
75 54 $cfg->{_txn_gen} = 0; # bumped on every txn state transition
76 54 $cfg->{_conn_state} = {}; # "$conn" => {auto_reconnect, was_ready}
77  
78 # Consumer state
79 54 $cfg->{assignments} = []; # [{topic, partition, offset}]
80 54 $cfg->{fetch_active} = 0;
81 54 $cfg->{group} = undef;
82  
83 54 my $self = bless { cfg => $cfg, loop => $loop }, "${class}::Client";
84  
85 # Warn on credentials over plaintext.
86 54 ▶ if ($cfg->{sasl} && !$cfg->{tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"sasl"} and not $cfg->{"tls"}) 1 53 54
Condition100%3/3
$cfg->{"sasl"} and not $cfg->{"tls"}
!ll&&!rl&&r
5211
MC/DC100%2/2
$cfg->{"sasl"} and not $cfg->{"tls"}
$cfg->{"sasl"} not $cfg->{"tls"}
Truth table100%3/3
A and not(B)
A= $cfg->{"sasl"}B= not $cfg->{"tls"}
ABresult
0X0
100
111
87 1 ▶ my $mech = $cfg->{sasl}{mechanism} // '';
Condition50%1/2
$cfg->{"sasl"}{"mechanism"} // ""
l!l
10
MC/DC0%0/1
$cfg->{"sasl"}{"mechanism"} // ""
$cfg->{"sasl"}{"mechanism"}
Truth table50%1/2
A
A= $cfg->{"sasl"}{"mechanism"}
Aresult
11
00
88 1 ▶ if ($mech eq 'PLAIN' || $mech =~ /^SCRAM-/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mech eq "PLAIN" or $mech =~ /^SCRAM-/) 1 0 1
Condition33%1/3
$mech eq "PLAIN" or $mech =~ /^SCRAM-/
l!l&&r!l&&!r
100
MC/DC0%0/2
$mech eq "PLAIN" or $mech =~ /^SCRAM-/
$mech eq "PLAIN" $mech =~ /^SCRAM-/
Truth table33%1/3
A or B
A= $mech eq "PLAIN"B= $mech =~ /^SCRAM-/
ABresult
1X1
011
000
89 1 warn "EV::Kafka: SASL $mech configured without TLS — "
90 . "credentials will be sent over plaintext\n";
91 }
92 }
93  
94 54 return $self;
95 }
96  
97 package EV::Kafka::Client;
98 34 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
99 34 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
100 34 ▶use Scalar::Util 'weaken';
Subroutine BEGIN: called CC=1 SCAR=0.0
101  
102 69 ▶sub _any_conn {
Subroutine _any_conn: called CC=6 SCAR=17.9
103 69 my ($self) = @_;
104 69 my $cfg = $self->{cfg};
105 69 ▶ return undef if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 69 69
106 69 my $conn = $cfg->{bootstrap_conn};
107 69 for my $c (values %{$cfg->{conns}}) {
108 28 ▶ if ($c->connected) { $conn = $c; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($c->connected) 24 4 28
109 }
110 69 ▶ return ($conn && $conn->connected) ? $conn : undef;
Branch: 1 branch
BranchTrueFalseTotal
$conn && $conn->connected ? : 55 14 69
Condition100%3/3
$conn and $conn->connected
!ll&&!rl&&r
10455
MC/DC100%2/2
$conn and $conn->connected
$conn $conn->connected
Truth table100%3/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
111 }
112  
113 69 ▶sub _get_or_create_conn {
Subroutine _get_or_create_conn: called CC=4 SCAR=14.0
114 69 my ($self, $node_id) = @_;
115 69 my $cfg = $self->{cfg};
116 69 ▶ return undef if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 69 69
117 69 ▶ return $cfg->{conns}{$node_id} if $cfg->{conns}{$node_id};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"conns"}{$node_id} 68 1 69
118  
119 1 my $info = $cfg->{broker_map}{$node_id};
120 1 ▶ return undef unless $info;
Branch: 1 branch
BranchTrueFalseTotal
unless $info 0 1 1
121  
122 1 my $conn = EV::Kafka::Conn::_new('EV::Kafka::Conn', $self->{loop});
123 1 $self->_configure_conn($conn);
124 1 $conn->auto_reconnect(1, 1000);
125 1 $cfg->{_conn_state}{"$conn"}{auto_reconnect} = 1;
126  
127 1 $cfg->{conns}{$node_id} = $conn;
128 1 weaken(my $weak = $self);
129 1 ▶ $conn->on_connect(sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
130 1 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 1 0 1
131 1 my $cfg = $s->{cfg};
132 1 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 1 1
133 1 $cfg->{_conn_state}{"$conn"}{was_ready} = 1;
134 1 $s->_drain_pending_for($node_id);
135 1 });
136 1 $conn->connect($info->{host}, $info->{port}, 10.0);
137  
138 1 return $conn;
139 }
140  
141 33 ▶sub _configure_conn {
Subroutine _configure_conn: called CC=5 SCAR=23.4
142 33 my ($self, $conn) = @_;
143 33 my $cfg = $self->{cfg};
144 33 $conn->client_id($cfg->{client_id});
145 33 ▶ if ($cfg->{tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"tls"}) 0 33 33
146 # Omit an undef CA: it would arrive in XS as "" and break
147 # SSL_CTX_load_verify_locations (NULL = system trust store).
148 0 my @tls_args = (1);
149 0 ▶ if (defined $cfg->{tls_ca_file}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $cfg->{'tls_ca_file'}) { } 0 0 0
elsif ($cfg->{'tls_skip_verify'}) { } 0 0 0
150 0 push @tls_args, $cfg->{tls_ca_file}, $cfg->{tls_skip_verify};
151 } elsif ($cfg->{tls_skip_verify}) {
152 0 push @tls_args, '', 1;
153 }
154 0 $conn->tls(@tls_args);
155 }
156 33 ▶ if ($cfg->{sasl}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"sasl"}) 0 33 33
157 0 $conn->sasl($cfg->{sasl}{mechanism}, $cfg->{sasl}{username}, $cfg->{sasl}{password});
158 }
159 33 $self->_wire_conn_handlers($conn);
160 }
161  
162 # Error/disconnect reporting for client-managed conns. An
163 # auto_reconnect conn reports its loss ONCE via on_disconnect; reconnect
164 # attempts stay silent so on_error (default: die) doesn't storm.
165 64 ▶sub _wire_conn_handlers {
Subroutine _wire_conn_handlers: called CC=2 SCAR=7.1
166 64 my ($self, $conn) = @_;
167 64 my $cfg = $self->{cfg};
168 64 ▶ $cfg->{_conn_state}{"$conn"} //= { auto_reconnect => 0, was_ready => 0 };
Condition100%2/2
$cfg->{"_conn_state"}{"$conn"} //= {"auto_reconnect", 0, "was_ready", 0}
l!l
3133
MC/DC100%1/1
$cfg->{"_conn_state"}{"$conn"} //= {"auto_reconnect", 0, "was_ready", 0}
$cfg->{"_conn_state"}{"$conn"}
Truth table100%2/2
A
A= $cfg->{"_conn_state"}{"$conn"}
Aresult
11
00
169 64 weaken(my $weak_cfg = $cfg);
170 2 ▶ $conn->on_error(sub {
Subroutine __ANON__: called CC=7 SCAR=20.9
171 2 ▶ my $cfg = $weak_cfg or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $weak_cfg or return 2 0 2
172 2 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 2 2
173 2 ▶ my $st = $cfg->{_conn_state}{"$conn"} // {};
Condition50%1/2
$cfg->{"_conn_state"}{"$conn"} // {}
l!l
20
MC/DC0%0/1
$cfg->{"_conn_state"}{"$conn"} // {}
$cfg->{"_conn_state"}{"$conn"}
Truth table50%1/2
A
A= $cfg->{"_conn_state"}{"$conn"}
Aresult
11
00
174 2 ▶ return if $st->{auto_reconnect} && !$conn->connected;
Branch: 1 branch
BranchTrueFalseTotal
if $st->{"auto_reconnect"} and not $conn->connected 1 1 2
Condition66%2/3
$st->{"auto_reconnect"} and not $conn->connected
!ll&&!rl&&r
011
MC/DC50%1/2
$st->{"auto_reconnect"} and not $conn->connected
$st->{"auto_reconnect"} not $conn->connected
Truth table66%2/3
A and not(B)
A= $st->{"auto_reconnect"}B= not $conn->connected
ABresult
0X0
100
111
175 1 ▶ $cfg->{on_error}->($_[0]) if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 1 0 1
176 64 });
177 11 ▶ $conn->on_disconnect(sub {
Subroutine __ANON__: called CC=6 SCAR=18.8
178 11 ▶ my $cfg = $weak_cfg or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $weak_cfg or return 11 0 11
179 11 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 11 11
180 11 ▶ my $st = $cfg->{_conn_state}{"$conn"} // {};
Condition50%1/2
$cfg->{"_conn_state"}{"$conn"} // {}
l!l
110
MC/DC0%0/1
$cfg->{"_conn_state"}{"$conn"} // {}
$cfg->{"_conn_state"}{"$conn"}
Truth table50%1/2
A
A= $cfg->{"_conn_state"}{"$conn"}
Aresult
11
00
181 11 ▶ return unless $st->{was_ready}; # never came up: nothing lost
Branch: 1 branch
BranchTrueFalseTotal
unless $st->{"was_ready"} 4 7 11
182 7 $st->{was_ready} = 0; # report once per loss
183 $cfg->{on_error}->("connection to broker lost; reconnecting")
184 7 ▶ if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 7 0 7
185 64 });
186 }
187  
188 31 ▶sub _bootstrap_connect {
Subroutine _bootstrap_connect: called CC=1 SCAR=0.0
189 31 my ($self) = @_;
190 31 $self->_bootstrap_try(0);
191 }
192  
193 32 ▶sub _bootstrap_try {
Subroutine _bootstrap_try: called CC=7 SCAR=21.8
194 32 my ($self, $idx) = @_;
195 32 my $cfg = $self->{cfg};
196 32 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 32 32
197  
198 32 my @bs = @{$cfg->{bootstrap}};
199 32 ▶ if ($idx >= @bs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx >= @bs) 0 32 32
200 0 $cfg->{_bootstrap_attempt} = undef;
201 # Connect callbacks are queued (not captured) so close() can fail
202 # them and nothing retains them past the first fire.
203 0 ▶ my @cbs = @{delete $cfg->{_connect_cbs} // []};
Condition0%0/2
delete $cfg->{"_connect_cbs"} // []
l!l
00
MC/DC0%0/1
delete $cfg->{"_connect_cbs"} // []
delete $cfg->{"_connect_cbs"}
Truth table0%0/2
A
A= delete $cfg->{"_connect_cbs"}
Aresult
11
00
204 0 ▶ if (@cbs) {
Branch: 2 branches
BranchTrueFalseTotal
if (@cbs) { } 0 0 0
elsif ($cfg->{'on_error'}) { } 0 0 0
205 0 $_->(undef, "all bootstrap brokers unreachable") for @cbs;
206 } elsif ($cfg->{on_error}) {
207 0 $cfg->{on_error}->("all bootstrap brokers unreachable");
208 }
209 0 return;
210 }
211 32 my ($host, $port) = @{$bs[$idx]};
212  
213 32 my $conn = EV::Kafka::Conn::_new('EV::Kafka::Conn', $self->{loop});
214 32 $self->_configure_conn($conn);
215  
216 # Keeps the attempt conn alive until on_connect/on_error fires,
217 # without a closure cycle.
218 32 $cfg->{_bootstrap_attempt} = $conn;
219  
220 32 weaken(my $weak = $self);
221 # Replace the forwarding on_error from _configure_conn with the
222 # try-next-broker handler for the duration of the bootstrap.
223 1 ▶ $conn->on_error(sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
224 1 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 1 0 1
225 1 my $cfg = $s->{cfg};
226 1 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 1 1
227 1 $cfg->{_bootstrap_attempt} = undef;
228 1 $s->_bootstrap_try($idx + 1);
229 32 });
230  
231 # State-driven: this handler outlives the bootstrap (XS refires
232 # on_connect after auto-reconnect), so it must not refire the cb.
233 38 ▶ $conn->on_connect(sub {
Subroutine __ANON__: called CC=6 SCAR=18.3
234 38 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 38 0 38
235 38 my $cfg = $s->{cfg};
236 38 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 38 38
237 38 ▶ if (!$cfg->{connected}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $cfg->{'connected'}) { } 31 7 38
238 # first successful bootstrap: promote attempt to bootstrap_conn
239 31 ▶ my $conn = delete $cfg->{_bootstrap_attempt} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $conn = delete $cfg->{"_bootstrap_attempt"} or return 31 0 31
240 31 $cfg->{bootstrap_conn} = $conn;
241 31 $cfg->{connected} = 1;
242 # Now a pooled conn: auto-reconnect on loss, and the standard
243 # suppressing handlers replace the try-next-broker one.
244 31 $conn->auto_reconnect(1, 1000);
245 31 $cfg->{_conn_state}{"$conn"} = { auto_reconnect => 1, was_ready => 1 };
246 31 $s->_wire_conn_handlers($conn);
247 31 $s->_refresh_metadata;
248 } else {
249 # auto-reconnect: refresh metadata, do NOT refire the callback
250 7 ▶ $s->_refresh_metadata unless $cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"meta_pending"} 7 0 7
251 }
252 32 });
253  
254 32 $conn->connect($host, $port, 10.0);
255 }
256  
257 34 ▶sub connect {
Subroutine connect: called CC=8 SCAR=21.1
258 34 my ($self, $cb) = @_;
259 34 my $cfg = $self->{cfg};
260 34 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 33 34
261 # Already up: fire immediately. Otherwise queue; every connect cb
262 # fires exactly once — ($meta) on success, (undef, $err) on failure.
263 33 ▶ if ($cfg->{connected} && $cfg->{meta}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"connected"} and $cfg->{"meta"}) 1 32 33
Condition66%2/3
$cfg->{"connected"} and $cfg->{"meta"}
!ll&&!rl&&r
3201
MC/DC50%1/2
$cfg->{"connected"} and $cfg->{"meta"}
$cfg->{"connected"} $cfg->{"meta"}
Truth table66%2/3
A and B
A= $cfg->{"connected"}B= $cfg->{"meta"}
ABresult
0X0
100
111
264 1 ▶ $cb->($cfg->{meta}) if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
265 1 return;
266 }
267 32 ▶ push @{$cfg->{_connect_cbs}}, $cb if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 32 0 32
268 $self->_bootstrap_connect
269 32 ▶ unless $cfg->{_bootstrap_attempt} || $cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"_bootstrap_attempt"} or $cfg->{"meta_pending"} 31 1 32
Condition66%2/3
$cfg->{"_bootstrap_attempt"} or $cfg->{"meta_pending"}
l!l&&r!l&&!r
1031
MC/DC50%1/2
$cfg->{"_bootstrap_attempt"} or $cfg->{"meta_pending"}
$cfg->{"_bootstrap_attempt"} $cfg->{"meta_pending"}
Truth table66%2/3
A or B
A= $cfg->{"_bootstrap_attempt"}B= $cfg->{"meta_pending"}
ABresult
1X1
011
000
270 }
271  
272 40 ▶sub _merge_metadata {
Subroutine _merge_metadata: called CC=9 SCAR=22.2
273 40 my ($cfg, $meta) = @_;
274 40 ▶ for my $b (@{$meta->{brokers} // []}) {
Condition100%2/2
$meta->{"brokers"} // []
l!l
382
MC/DC100%1/1
$meta->{"brokers"} // []
$meta->{"brokers"}
Truth table100%2/2
A
A= $meta->{"brokers"}
Aresult
11
00
275 $cfg->{broker_map}{$b->{node_id}} = {
276 host => $b->{host}, port => $b->{port}
277 39 };
278 }
279 40 ▶ for my $t (@{$meta->{topics} // []}) {
Condition50%1/2
$meta->{"topics"} // []
l!l
400
MC/DC0%0/1
$meta->{"topics"} // []
$meta->{"topics"}
Truth table50%1/2
A
A= $meta->{"topics"}
Aresult
11
00
280 41 ▶ next if $t->{error_code};
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"error_code"} 0 41 41
281 # Evict existing leaders first: a topic that shrank must not keep
282 # routing to its old partition count. (Names can't contain ':'.)
283 41 my $prefix = "$t->{name}:";
284 delete $cfg->{leaders}{$_}
285 41 for grep { index($_, $prefix) == 0 } keys %{$cfg->{leaders}};
286 41 ▶ for my $p (@{$t->{partitions} // []}) {
Condition50%1/2
$t->{"partitions"} // []
l!l
410
MC/DC0%0/1
$t->{"partitions"} // []
$t->{"partitions"}
Truth table50%1/2
A
A= $t->{"partitions"}
Aresult
11
00
287 43 $cfg->{leaders}{"$t->{name}:$p->{partition}"} = $p->{leader};
288 }
289 }
290 }
291  
292 49 ▶sub _refresh_metadata {
Subroutine _refresh_metadata: called CC=4 SCAR=14.2
293 49 my ($self) = @_;
294 49 my $cfg = $self->{cfg};
295 49 ▶ return if $cfg->{closed} || $cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} or $cfg->{"meta_pending"} 0 49 49
Condition33%1/3
$cfg->{"closed"} or $cfg->{"meta_pending"}
l!l&&r!l&&!r
0049
MC/DC0%0/2
$cfg->{"closed"} or $cfg->{"meta_pending"}
$cfg->{"closed"} $cfg->{"meta_pending"}
Truth table33%1/3
A or B
A= $cfg->{"closed"}B= $cfg->{"meta_pending"}
ABresult
1X1
011
000
296 49 $cfg->{meta_pending} = 1;
297  
298 49 my $conn = $self->_any_conn;
299 49 ▶ unless ($conn) { $cfg->{meta_pending} = 0; return }
Branch: 1 branch
BranchTrueFalseTotal
unless ($conn) 10 39 49
300  
301 39 weaken(my $weak = $self);
302 39 ▶ $conn->metadata(undef, sub {
Subroutine __ANON__: called CC=12 SCAR=25.8
303 39 my ($meta, $err) = @_;
304 39 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 39 0 39
305 39 my $cfg = $s->{cfg};
306 39 $cfg->{meta_pending} = 0;
307 39 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 38 39
308 38 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 38 38
309 0 ▶ $cfg->{on_error}->("metadata: $err") if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 0 0 0
310 0 return;
311 }
312  
313 38 $cfg->{meta} = $meta;
314 38 _merge_metadata($cfg, $meta);
315  
316 # assign bootstrap_conn a node_id if possible
317 38 ▶ if ($cfg->{bootstrap_conn} && $meta->{brokers} && @{$meta->{brokers}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"bootstrap_conn"} and $meta->{"brokers"} and @{$meta->{"brokers"};}) 38 0 38
Condition33%2/6
$cfg->{"bootstrap_conn"} and $meta->{"brokers"} and @{$meta->{"brokers"};}
!ll&&!rl&&r
0038
$cfg->{"bootstrap_conn"} and $meta->{"brokers"}
!ll&&!rl&&r
0038
MC/DC0%0/3
$cfg->{"bootstrap_conn"} and $meta->{"brokers"} and @{$meta->{"brokers"};}
$cfg->{"bootstrap_conn"} $meta->{"brokers"} @{$meta->{"brokers"};}
Truth table25%1/4
A and B and C
A= $cfg->{"bootstrap_conn"}B= $meta->{"brokers"}C= @{$meta->{"brokers"};}
ABCresult
0XX0
10X0
1100
1111
318 38 my $binfo = $meta->{brokers}[0];
319 38 ▶ $cfg->{conns}{$binfo->{node_id}} //= $cfg->{bootstrap_conn};
Condition66%2/3
$cfg->{"conns"}{$binfo->{"node_id"}} //= $cfg->{"bootstrap_conn"}
l!l&&r!l&&!r
8300
MC/DC0%0/2
$cfg->{"conns"}{$binfo->{"node_id"}} //= $cfg->{"bootstrap_conn"}
$cfg->{"conns"}{$binfo->{"node_id"}} $cfg->{"bootstrap_conn"}
Truth table66%2/3
A //= B
A= $cfg->{"conns"}{$binfo->{"node_id"}}B= $cfg->{"bootstrap_conn"}
ABresult
1X1
011
000
320 }
321  
322 # Fire the one-shot connect callbacks; delete the queue first so
323 # close() can't fail a callback that is already firing.
324 37 ▶ my $fire = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
325 37 ▶ my @cbs = @{delete $cfg->{_connect_cbs} // []};
Condition100%2/2
delete $cfg->{"_connect_cbs"} // []
l!l
298
MC/DC100%1/1
delete $cfg->{"_connect_cbs"} // []
delete $cfg->{"_connect_cbs"}
Truth table100%2/2
A
A= delete $cfg->{"_connect_cbs"}
Aresult
11
00
326 37 $_->($meta) for @cbs;
327 37 ▶ $cfg->{on_connect}->() if $cfg->{on_connect};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_connect"} 1 36 37
328 37 $cfg->{on_connect} = undef;
329 38 };
330  
331 38 ▶ if (($cfg->{idempotent} || $cfg->{transactional_id}) && $cfg->{_pid} eq 'idle') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'idempotent'} || $cfg->{'transactional_id'} and $cfg->{'_pid'} eq 'idle') { } 6 32 38
Condition100%6/6
$cfg->{"idempotent"} || $cfg->{"transactional_id"} and $cfg->{"_pid"} eq "idle"
!ll&&!rl&&r
3116
$cfg->{"idempotent"} or $cfg->{"transactional_id"}
l!l&&r!l&&!r
4331
MC/DC100%3/3
$cfg->{"idempotent"} || $cfg->{"transactional_id"} and $cfg->{"_pid"} eq "idle"
$cfg->{"idempotent"} $cfg->{"transactional_id"} $cfg->{"_pid"} eq "idle"
Truth table80%4/5
A or B and C
A= $cfg->{"idempotent"}B= $cfg->{"transactional_id"}C= $cfg->{"_pid"} eq "idle"
ABCresult
00X0
1X00
0100
1X11
0111
332 6 ▶ $s->_init_idempotent(sub {
Subroutine __ANON__: called CC=6 SCAR=18.2
333 6 ▶ my $s2 = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s2 = $weak or return 6 0 6
334 6 ▶ return if $s2->{cfg}{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $s2->{"cfg"}{"closed"} 0 6 6
335 6 ▶ if ($cfg->{_pid} =~ /^failed:(.*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"_pid"} =~ /^failed:(.*)/) 1 5 6
336 # idempotence was requested but could not be set up:
337 # the connect callbacks get the error, not metadata.
338 1 ▶ my @cbs = @{delete $cfg->{_connect_cbs} // []};
Condition50%1/2
delete $cfg->{"_connect_cbs"} // []
l!l
10
MC/DC0%0/1
delete $cfg->{"_connect_cbs"} // []
delete $cfg->{"_connect_cbs"}
Truth table50%1/2
A
A= delete $cfg->{"_connect_cbs"}
Aresult
11
00
339 1 $_->(undef, $1) for @cbs;
340 1 return;
341 }
342 5 $s2->_drain_all_pending;
343 5 $fire->();
344 6 });
345 } else {
346 32 $s->_drain_all_pending;
347 32 $fire->();
348 }
349  
350 # Arm periodic metadata refresh (after first successful fetch).
351 38 $s->_arm_metadata_timer;
352 39 });
353 }
354  
355 38 ▶sub _arm_metadata_timer {
Subroutine _arm_metadata_timer: called CC=4 SCAR=14.2
356 38 my ($self) = @_;
357 38 my $cfg = $self->{cfg};
358 38 ▶ return if $cfg->{_meta_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"_meta_timer"} 8 30 38
359 30 ▶ my $interval = $cfg->{metadata_refresh} || 0;
Condition50%1/2
$cfg->{'metadata_refresh'} || 0
l!l
300
MC/DC0%0/1
$cfg->{'metadata_refresh'} || 0
$cfg->{'metadata_refresh'}
Truth table50%1/2
A
A= $cfg->{'metadata_refresh'}
Aresult
11
00
360 30 ▶ return if $interval <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $interval <= 0 0 30 30
361 30 weaken(my $weak = $self);
362 1 ▶ $cfg->{_meta_timer} = EV::timer $interval, $interval, sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
363 1 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 1 1
364 1 ▶ $weak->_refresh_metadata unless $weak->{cfg}{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak->{"cfg"}{"meta_pending"} 1 0 1
365 30 };
366 }
367  
368 54 ▶sub _disarm_metadata_timer {
Subroutine _disarm_metadata_timer: called CC=1 SCAR=0.0
369 54 my ($self) = @_;
370 54 undef $self->{cfg}{_meta_timer};
371 }
372  
373 2 ▶sub _refresh_metadata_for_topic {
Subroutine _refresh_metadata_for_topic: called CC=11 SCAR=41.1
374 2 my ($self, $topic) = @_;
375 2 my $cfg = $self->{cfg};
376 2 ▶ return if $cfg->{closed} || $cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} or $cfg->{"meta_pending"} 0 2 2
Condition33%1/3
$cfg->{"closed"} or $cfg->{"meta_pending"}
l!l&&r!l&&!r
002
MC/DC0%0/2
$cfg->{"closed"} or $cfg->{"meta_pending"}
$cfg->{"closed"} $cfg->{"meta_pending"}
Truth table33%1/3
A or B
A= $cfg->{"closed"}B= $cfg->{"meta_pending"}
ABresult
1X1
011
000
377  
378 # Bound retries so a permanently-unavailable topic can't accumulate
379 # produce ops in pending_ops indefinitely.
380 2 my $tries = ++$cfg->{_topic_meta_tries}{$topic};
381 2 ▶ if ($tries > 10) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tries > 10) 2 0 2
382 2 delete $cfg->{_topic_meta_tries}{$topic};
383 2 my $msg = "metadata: topic '$topic' unavailable after $tries tries";
384 # Drop this topic's pending ops and report: to the op's callback
385 # if it has one, else on_error — never both (default on_error dies).
386 2 my (@keep, $reported);
387 2 for my $op (@{$cfg->{pending_ops}}) {
388 2 ▶ if ($op->{topic} && $op->{topic} eq $topic) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op->{'topic'} and $op->{'topic'} eq $topic) { } 2 0 2
Condition33%1/3
$op->{"topic"} and $op->{"topic"} eq $topic
!ll&&!rl&&r
002
MC/DC0%0/2
$op->{"topic"} and $op->{"topic"} eq $topic
$op->{"topic"} $op->{"topic"} eq $topic
Truth table33%1/3
A and B
A= $op->{"topic"}B= $op->{"topic"} eq $topic
ABresult
0X0
100
111
389 2 ▶ if ($op->{cb}) { $op->{cb}->(undef, $msg); $reported = 1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($op->{"cb"}) 1 1 2
390 } else {
391 0 push @keep, $op;
392 }
393 }
394 2 $cfg->{pending_ops} = \@keep;
395 2 ▶ $cfg->{on_error}->($msg) if !$reported && $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if not $reported and $cfg->{"on_error"} 1 1 2
Condition66%2/3
not $reported and $cfg->{"on_error"}
!ll&&!rl&&r
101
MC/DC50%1/2
not $reported and $cfg->{"on_error"}
not $reported $cfg->{"on_error"}
Truth table66%2/3
not(A) and B
A= not $reportedB= $cfg->{"on_error"}
ABresult
0X0
100
111
396 2 return;
397 }
398  
399 0 $cfg->{meta_pending} = 1;
400  
401 0 my $conn = $self->_any_conn;
402 0 ▶ unless ($conn) { $cfg->{meta_pending} = 0; return }
Branch: 1 branch
BranchTrueFalseTotal
unless ($conn) 0 0 0
403  
404 0 weaken(my $weak = $self);
405 0 ▶ $conn->metadata([$topic], sub {
Subroutine __ANON__: not called CC=16 SCAR=56.1
406 0 my ($meta, $err) = @_;
407 0 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 0 0 0
408 0 my $cfg = $s->{cfg};
409 0 $cfg->{meta_pending} = 0;
410 0 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 0 0
411 0 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
412 0 ▶ $cfg->{on_error}->("metadata: $err") if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 0 0 0
413 0 return;
414 }
415  
416 0 _merge_metadata($cfg, $meta);
417  
418 # Fold the per-topic response into $cfg->{meta} so _num_partitions
419 # (which reads from {meta}{topics}) sees auto-created topics.
420 0 ▶ if ($cfg->{meta} && ref $cfg->{meta}{topics} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'meta'} and ref $cfg->{'meta'}{'topics'} eq 'ARRAY') { } 0 0 0
Condition0%0/3
$cfg->{"meta"} and ref $cfg->{"meta"}{"topics"} eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$cfg->{"meta"} and ref $cfg->{"meta"}{"topics"} eq "ARRAY"
$cfg->{"meta"} ref $cfg->{"meta"}{"topics"} eq "ARRAY"
Truth table0%0/3
A and B
A= $cfg->{"meta"}B= ref $cfg->{"meta"}{"topics"} eq "ARRAY"
ABresult
0X0
100
111
421 0 my %by_name = map { $_->{name} => $_ } @{$cfg->{meta}{topics}};
422 0 ▶ for my $t (@{$meta->{topics} // []}) {
Condition0%0/2
$meta->{"topics"} // []
l!l
00
MC/DC0%0/1
$meta->{"topics"} // []
$meta->{"topics"}
Truth table0%0/2
A
A= $meta->{"topics"}
Aresult
11
00
423 0 $by_name{$t->{name}} = $t;
424 }
425 0 $cfg->{meta}{topics} = [values %by_name];
426 } else {
427 0 $cfg->{meta} = $meta;
428 }
429  
430 # if topic still has error, retry after delay
431 0 my $topic_ok = 0;
432 0 ▶ for my $t (@{$meta->{topics} // []}) {
Condition0%0/2
$meta->{"topics"} // []
l!l
00
MC/DC0%0/1
$meta->{"topics"} // []
$meta->{"topics"}
Truth table0%0/2
A
A= $meta->{"topics"}
Aresult
11
00
433 0 ▶ if ($t->{name} eq $topic && !$t->{error_code} && @{$t->{partitions} // []}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($t->{"name"} eq $topic and not $t->{"error_code"} and @{$t->{"partitions"} // [];}) 0 0 0
Condition0%0/8
$t->{"name"} eq $topic and not $t->{"error_code"} and @{$t->{"partitions"} // [];}
!ll&&!rl&&r
000
$t->{"name"} eq $topic and not $t->{"error_code"}
!ll&&!rl&&r
000
$t->{"partitions"} // []
l!l
00
MC/DC0%0/3
$t->{"name"} eq $topic and not $t->{"error_code"} and @{$t->{"partitions"} // [];}
$t->{"name"} eq $topic not $t->{"error_code"} @{$t->{"partitions"} // [];}
MC/DC0%0/1
$t->{"partitions"} // []
$t->{"partitions"}
Truth table0%0/4
A and not(B) and C
A= $t->{"name"} eq $topicB= not $t->{"error_code"}C= @{$t->{"partitions"} // [];}
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/2
A
A= $t->{"partitions"}
Aresult
11
00
434 0 $topic_ok = 1;
435 0 last;
436 }
437 }
438  
439 0 ▶ if ($topic_ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($topic_ok) { } 0 0 0
440 0 delete $cfg->{_topic_meta_tries}{$topic};
441 0 $s->_drain_all_pending;
442 } else {
443 # retry after short delay (topic being created); bounded above.
444 0 ▶ my $t; $t = EV::timer 0.5, 0, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
445 0 undef $t;
446 0 ▶ $weak->_refresh_metadata_for_topic($topic) if $weak;
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
447 0 };
448 }
449 0 });
450 }
451  
452 # InitProducerId, single-flight. 'init' queues completion callbacks in
453 # _pid_cbs; failed:$msg is sticky (produce fails, begin_transaction dies).
454 8 ▶sub _init_idempotent {
Subroutine _init_idempotent: called CC=8 SCAR=23.4
455 8 my ($self, $cb) = @_;
456 8 my $cfg = $self->{cfg};
457 8 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 8 8
458 8 ▶ if ($cfg->{_pid} eq 'init') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"_pid"} eq "init") 1 7 8
459 1 ▶ push @{$cfg->{_pid_cbs}}, $cb if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
460 1 return;
461 }
462 7 ▶ if ($cfg->{_pid} eq 'ready' || $cfg->{_pid} =~ /^failed:/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"_pid"} eq "ready" or $cfg->{"_pid"} =~ /^failed:/) 0 7 7
Condition33%1/3
$cfg->{"_pid"} eq "ready" or $cfg->{"_pid"} =~ /^failed:/
l!l&&r!l&&!r
007
MC/DC0%0/2
$cfg->{"_pid"} eq "ready" or $cfg->{"_pid"} =~ /^failed:/
$cfg->{"_pid"} eq "ready" $cfg->{"_pid"} =~ /^failed:/
Truth table33%1/3
A or B
A= $cfg->{"_pid"} eq "ready"B= $cfg->{"_pid"} =~ /^failed:/
ABresult
1X1
011
000
463 0 ▶ $cb->() if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 0 0 0
464 0 return;
465 }
466 7 $cfg->{_pid} = 'init';
467 7 $cfg->{_pid_cbs} = [];
468 7 ▶ push @{$cfg->{_pid_cbs}}, $cb if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 7 0 7
469 7 $self->_pid_attempt(1);
470 }
471  
472 9 ▶sub _pid_attempt {
Subroutine _pid_attempt: called CC=5 SCAR=18.9
473 9 my ($self, $attempt) = @_;
474 9 my $cfg = $self->{cfg};
475 9 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 9 9
476  
477 9 weaken(my $weak = $self);
478 3 ▶ my $retry = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
479 3 my ($err) = @_;
480 3 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 3 0 3
481 3 ▶ if ($attempt < 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attempt < 3) { } 2 1 3
482 2 ▶ my $t; $t = EV::timer 0.5, 0, sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
483 2 undef $t;
484 2 ▶ $weak->_pid_attempt($attempt + 1) if $weak;
Branch: 1 branch
BranchTrueFalseTotal
if $weak 2 0 2
485 2 };
486 } else {
487 1 $s->_pid_finish($err);
488 }
489 9 };
490  
491 9 ▶ my $do_init = sub {
Subroutine __ANON__: called CC=2 SCAR=7.3
492 9 my ($conn) = @_;
493 9 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 9 9
494 9 ▶ $conn->init_producer_id($cfg->{transactional_id}, 30000, sub {
Subroutine __ANON__: called CC=8 SCAR=22.6
495 9 my ($res, $err) = @_;
496 9 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 9 9
497 9 ▶ if (!$err && $res && !$res->{error_code}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $err and $res and not $res->{'error_code'}) { } 6 3 9
Condition50%3/6
not $err and $res and not $res->{"error_code"}
!ll&&!rl&&r
036
not $err and $res
!ll&&!rl&&r
009
MC/DC33%1/3
not $err and $res and not $res->{"error_code"}
not $err $res not $res->{"error_code"}
Truth table50%2/4
not(A) and B and not(C)
A= not $errB= $resC= not $res->{"error_code"}
ABCresult
0XX0
10X0
1100
1111
498 6 $cfg->{producer_id} = $res->{producer_id};
499 6 $cfg->{producer_epoch} = $res->{producer_epoch};
500 6 ▶ $weak->_pid_finish(undef) if $weak;
Branch: 1 branch
BranchTrueFalseTotal
if $weak 6 0 6
501 } else {
502 3 ▶ my $msg = $err || "InitProducerId error: " . ($res->{error_code} // '?');
Condition50%2/4
$err || 'InitProducerId error: ' . ($res->{'error_code'} // '?')
l!l
03
$res->{"error_code"} // "?"
l!l
30
MC/DC0%0/1
$err || 'InitProducerId error: ' . ($res->{'error_code'} // '?')
$err
MC/DC0%0/1
$res->{"error_code"} // "?"
$res->{"error_code"}
Truth table50%1/2
A
A= $err
Aresult
11
00
Truth table50%1/2
A
A= $res->{"error_code"}
Aresult
11
00
503 3 $retry->($msg);
504 }
505 9 });
506 9 };
507  
508 9 ▶ if ($cfg->{transactional_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'transactional_id'}) { } 2 7 9
509 # Transactional InitProducerId must go to the transaction
510 # coordinator; any other broker answers NOT_COORDINATOR.
511 2 my $conn = $self->_any_conn;
512 2 ▶ unless ($conn) { $retry->("no broker connection for FindCoordinator"); return }
Branch: 1 branch
BranchTrueFalseTotal
unless ($conn) 0 2 2
513 2 ▶ $conn->find_coordinator($cfg->{transactional_id}, sub {
Subroutine __ANON__: called CC=9 SCAR=33.8
514 2 my ($res, $err) = @_;
515 2 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 2 0 2
516 2 my $cfg = $s->{cfg};
517 2 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 2 2
518 2 ▶ if ($err || ($res && $res->{error_code})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err or $res and $res->{"error_code"}) 0 2 2
Condition33%2/6
$err or $res and $res->{"error_code"}
l!l&&r!l&&!r
002
$res and $res->{"error_code"}
!ll&&!rl&&r
020
MC/DC0%0/3
$err or $res and $res->{"error_code"}
$err $res $res->{"error_code"}
Truth table25%1/4
A or B and C
A= $errB= $resC= $res->{"error_code"}
ABCresult
1XX1
0111
00X0
0100
519 0 ▶ my $msg = $err || "FindCoordinator(txn) error: $res->{error_code}";
Condition0%0/2
$err || "FindCoordinator(txn) error: $res->{'error_code'}"
l!l
00
MC/DC0%0/1
$err || "FindCoordinator(txn) error: $res->{'error_code'}"
$err
Truth table0%0/2
A
A= $err
Aresult
11
00
520 0 $retry->($msg);
521 0 return;
522 }
523 $cfg->{broker_map}{$res->{node_id}} = {
524 host => $res->{host}, port => $res->{port}
525 2 };
526 2 my $txn_conn = $s->_get_or_create_conn($res->{node_id});
527 2 ▶ if ($txn_conn && $txn_conn->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($txn_conn and $txn_conn->connected) { } 2 0 2
Condition33%1/3
$txn_conn and $txn_conn->connected
!ll&&!rl&&r
002
MC/DC0%0/2
$txn_conn and $txn_conn->connected
$txn_conn $txn_conn->connected
Truth table33%1/3
A and B
A= $txn_connB= $txn_conn->connected
ABresult
0X0
100
111
528 2 $cfg->{_txn_coordinator} = $txn_conn;
529 2 $do_init->($txn_conn);
530 } else {
531 0 push @{$cfg->{pending_ops}}, {
532 node_id => $res->{node_id},
533 0 ▶ run => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
534 0 ▶ my $s2 = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s2 = $weak or return 0 0 0
535 my $tc = $cfg->{_txn_coordinator} =
536 0 $s2->_get_or_create_conn($res->{node_id});
537 0 ▶ if ($tc && $tc->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tc and $tc->connected) { } 0 0 0
Condition0%0/3
$tc and $tc->connected
!ll&&!rl&&r
000
MC/DC0%0/2
$tc and $tc->connected
$tc $tc->connected
Truth table0%0/3
A and B
A= $tcB= $tc->connected
ABresult
0X0
100
111
538 0 $do_init->($tc);
539 } else {
540 0 $retry->("transaction coordinator unreachable");
541 }
542 },
543 0 };
544 }
545 2 }, 1);
546 } else {
547 # idempotent only: any broker works
548 7 my $conn = $self->_any_conn;
549 7 ▶ unless ($conn) { $retry->("no broker connection for InitProducerId"); return }
Branch: 1 branch
BranchTrueFalseTotal
unless ($conn) 0 7 7
550 7 $do_init->($conn);
551 }
552 }
553  
554 7 ▶sub _pid_finish {
Subroutine _pid_finish: called CC=9 SCAR=22.6
555 7 my ($self, $err) = @_;
556 7 my $cfg = $self->{cfg};
557 7 ▶ if (defined $err) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $err) { } 1 6 7
558 1 $cfg->{_pid} = "failed:$err";
559 1 ▶ $cfg->{on_error}->($err) if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 1 0 1
560 # Queued produce ops can never succeed now: fail their callbacks.
561 # Non-produce ops (poll, group) are not producer-gated; keep them.
562 1 my @keep;
563 1 for my $op (@{$cfg->{pending_ops}}) {
564 1 ▶ if ($op->{topic}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op->{'topic'}) { } 1 0 1
565 1 ▶ next unless $op->{cb};
Branch: 1 branch
BranchTrueFalseTotal
unless $op->{"cb"} 0 1 1
566 1 eval { $op->{cb}->(undef, "idempotent producer unavailable: $err") };
567 1 ▶ warn "EV::Kafka: produce callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
568 } else {
569 0 push @keep, $op;
570 }
571 }
572 1 $cfg->{pending_ops} = \@keep;
573 } else {
574 6 $cfg->{_pid} = 'ready';
575 }
576 7 ▶ my @cbs = @{delete $cfg->{_pid_cbs} // []};
Condition50%1/2
delete $cfg->{"_pid_cbs"} // []
l!l
70
MC/DC0%0/1
delete $cfg->{"_pid_cbs"} // []
delete $cfg->{"_pid_cbs"}
Truth table50%1/2
A
A= delete $cfg->{"_pid_cbs"}
Aresult
11
00
577 7 $_->() for @cbs;
578 }
579  
580 2 ▶sub _drain_pending_for {
Subroutine _drain_pending_for: called CC=6 SCAR=19.1
581 2 my ($self, $node_id) = @_;
582 2 my $cfg = $self->{cfg};
583 2 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 2 2
584 # Copy-then-run: an op's run() may push new ops (reentrant produce),
585 # which rewriting the array after running would silently drop.
586 2 my (@run, @remaining);
587 2 for my $op (@{$cfg->{pending_ops}}) {
588 2 ▶ if (defined $op->{node_id} && $op->{node_id} == $node_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $op->{'node_id'} and $op->{'node_id'} == $node_id) { } 2 0 2
Condition33%1/3
defined $op->{"node_id"} and $op->{"node_id"} == $node_id
!ll&&!rl&&r
002
MC/DC0%0/2
defined $op->{"node_id"} and $op->{"node_id"} == $node_id
defined $op->{"node_id"} $op->{"node_id"} == $node_id
Truth table33%1/3
A and B
A= defined $op->{"node_id"}B= $op->{"node_id"} == $node_id
ABresult
0X0
100
111
589 2 push @run, $op;
590 } else {
591 0 push @remaining, $op;
592 }
593 }
594 2 $cfg->{pending_ops} = \@remaining;
595 2 $_->{run}->() for @run;
596 }
597  
598 37 ▶sub _drain_all_pending {
Subroutine _drain_all_pending: called CC=6 SCAR=18.9
599 37 my ($self) = @_;
600 37 my $cfg = $self->{cfg};
601 37 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 37 37
602 37 my @ops = @{$cfg->{pending_ops}};
603 37 $cfg->{pending_ops} = [];
604 37 for my $op (@ops) {
605 3 ▶ if (defined $op->{node_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $op->{'node_id'}) { } 1 2 3
606 1 my $conn = $self->_get_or_create_conn($op->{node_id});
607 1 ▶ if ($conn && $conn->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conn and $conn->connected) { } 1 0 1
Condition33%1/3
$conn and $conn->connected
!ll&&!rl&&r
001
MC/DC0%0/2
$conn and $conn->connected
$conn $conn->connected
Truth table33%1/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
608 1 $op->{run}->();
609 } else {
610 0 push @{$cfg->{pending_ops}}, $op;
611 }
612 } else {
613 2 $op->{run}->();
614 }
615 }
616 }
617  
618 62 ▶sub _get_leader {
Subroutine _get_leader: called CC=1 SCAR=0.0
619 62 my ($self, $topic, $partition) = @_;
620 62 return $self->{cfg}{leaders}{"$topic:$partition"};
621 }
622  
623 16 ▶sub _num_partitions {
Subroutine _num_partitions: called CC=5 SCAR=17.5
624 16 my ($self, $topic) = @_;
625 16 ▶ my $meta = $self->{cfg}{meta} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $meta = $self->{"cfg"}{"meta"} or return 0 16 0 16
626 16 ▶ for my $t (@{$meta->{topics} // []}) {
Condition50%1/2
$meta->{"topics"} // []
l!l
160
MC/DC0%0/1
$meta->{"topics"} // []
$meta->{"topics"}
Truth table50%1/2
A
A= $meta->{"topics"}
Aresult
11
00
627 16 ▶ return scalar @{$t->{partitions}} if $t->{name} eq $topic;
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"name"} eq $topic 16 0 16
628 }
629 0 return 0;
630 }
631  
632 16 ▶sub _select_partition {
Subroutine _select_partition: called CC=5 SCAR=18.7
633 16 my ($self, $topic, $key) = @_;
634 16 my $np = $self->_num_partitions($topic);
635 16 ▶ return 0 unless $np > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $np > 0 0 16 16
636  
637 16 my $cfg = $self->{cfg};
638 16 ▶ if ($cfg->{partitioner}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"partitioner"}) 0 16 16
639 0 return $cfg->{partitioner}->($topic, $key, $np);
640 }
641 16 ▶ if (defined $key && length $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key and length $key) 16 0 16
Condition33%1/3
defined $key and length $key
!ll&&!rl&&r
0016
MC/DC0%0/2
defined $key and length $key
defined $key length $key
Truth table33%1/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
642 16 return EV::Kafka::_murmur2($key) % $np;
643 }
644 0 return $cfg->{rr_counter}++ % $np;
645 }
646  
647 # --- Producer ---
648  
649 27 ▶sub produce {
Subroutine produce: called CC=28 SCAR=38.1
650 27 my ($self, $topic, $key, $value, @rest) = @_;
651 27 my $cb;
652 my %opts;
653 27 for my $a (@rest) {
654 26 ▶ if (ref $a eq 'CODE') { $cb = $a }
Branch: 2 branches
BranchTrueFalseTotal
if (ref $a eq 'CODE') { } 23 3 26
elsif (ref $a eq 'HASH') { } 3 0 3
655 3 elsif (ref $a eq 'HASH') { %opts = %$a }
656 }
657 27 for my $k (keys %opts) {
658 3 ▶ croak "EV::Kafka: produce: unknown option '$k'"
Branch: 1 branch
BranchTrueFalseTotal
unless $k eq "partition" or $k eq "headers" 1 2 3
Condition66%2/3
$k eq "partition" or $k eq "headers"
l!l&&r!l&&!r
201
MC/DC50%1/2
$k eq "partition" or $k eq "headers"
$k eq "partition" $k eq "headers"
Truth table66%2/3
A or B
A= $k eq "partition"B= $k eq "headers"
ABresult
1X1
011
000
659 unless $k eq 'partition' || $k eq 'headers';
660 }
661  
662 26 my $cfg = $self->{cfg};
663 26 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 25 26
664 25 weaken(my $weak = $self);
665  
666 # ensure we have metadata
667 25 ▶ unless ($cfg->{meta}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"meta"}) 6 19 25
668 6 push @{$cfg->{pending_ops}}, {
669 topic => $topic,
670 cb => $cb,
671 1 ▶ run => sub { $weak->produce($topic, $key, $value, @rest) if $weak },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $weak 1 0 1
672 6 };
673 6 ▶ $self->_refresh_metadata unless $cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"meta_pending"} 6 0 6
674 6 return;
675 }
676  
677 # Idempotent/transactional producers must wait for InitProducerId:
678 # a batch sent without producer_id/epoch silently voids exactly-once.
679 19 ▶ if (($cfg->{idempotent} || $cfg->{transactional_id})
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"idempotent"} || $cfg->{"transactional_id"} and $cfg->{"_pid"} ne "ready") 1 18 19
Condition100%6/6
$cfg->{"idempotent"} || $cfg->{"transactional_id"} and $cfg->{"_pid"} ne "ready"
!ll&&!rl&&r
1081
$cfg->{"idempotent"} or $cfg->{"transactional_id"}
l!l&&r!l&&!r
5410
MC/DC66%2/3
$cfg->{"idempotent"} || $cfg->{"transactional_id"} and $cfg->{"_pid"} ne "ready"
$cfg->{"idempotent"} $cfg->{"transactional_id"} $cfg->{"_pid"} ne "ready"
Truth table80%4/5
A or B and C
A= $cfg->{"idempotent"}B= $cfg->{"transactional_id"}C= $cfg->{"_pid"} ne "ready"
ABCresult
00X0
1X00
0100
1X11
0111
680 && $cfg->{_pid} ne 'ready') {
681 1 ▶ if ($cfg->{_pid} =~ /^failed:(.*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"_pid"} =~ /^failed:(.*)/) 1 0 1
682 1 ▶ $cb->(undef, "idempotent producer unavailable: $1") if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
683 1 return;
684 }
685 0 push @{$cfg->{pending_ops}}, {
686 topic => $topic,
687 cb => $cb,
688 0 ▶ run => sub { $weak->produce($topic, $key, $value, @rest) if $weak },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
689 0 };
690 0 ▶ $self->_init_idempotent if $cfg->{_pid} eq 'idle';
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"_pid"} eq "idle" 0 0 0
691 0 return;
692 }
693  
694 my $partition = exists $opts{partition}
695 ? $opts{partition}
696 18 ▶ : $self->_select_partition($topic, $key);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'partition'} ? : 2 16 18
697  
698 18 my $leader_id = $self->_get_leader($topic, $partition);
699 18 ▶ unless (defined $leader_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $leader_id) 0 18 18
700 # topic/partition unknown — request metadata to trigger auto-creation.
701 # Tag with topic+cb so the retry-bound cleanup can report the error
702 # instead of leaking the op in pending_ops forever.
703 0 push @{$cfg->{pending_ops}}, {
704 topic => $topic,
705 cb => $cb,
706 0 ▶ run => sub { $weak->produce($topic, $key, $value, @rest) if $weak },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
707 0 };
708 0 ▶ $self->_refresh_metadata_for_topic($topic) unless $cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"meta_pending"} 0 0 0
709 0 return;
710 }
711  
712 18 my $conn = $self->_get_or_create_conn($leader_id);
713 18 ▶ unless ($conn && $conn->connected) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($conn and $conn->connected) 1 17 18
Condition66%2/3
$conn and $conn->connected
!ll&&!rl&&r
0117
MC/DC50%1/2
$conn and $conn->connected
$conn $conn->connected
Truth table66%2/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
714 # Tag with topic+cb too, so the retry-bound cleanup can report it.
715 1 push @{$cfg->{pending_ops}}, {
716 node_id => $leader_id,
717 topic => $topic,
718 cb => $cb,
719 1 ▶ run => sub { $weak->produce($topic, $key, $value, @rest) if $weak },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $weak 1 0 1
720 1 };
721 1 return;
722 }
723  
724 # Accumulate into batch
725 17 my $bkey = "$topic:$partition";
726 17 my $rec = { key => $key, value => $value };
727 17 ▶ $rec->{headers} = $opts{headers} if $opts{headers};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"headers"} 0 17 17
728 17 ▶ push @{$cfg->{batches}{$bkey} //= []}, { rec => $rec, cb => $cb };
Condition100%2/2
$cfg->{"batches"}{$bkey} //= []
l!l
116
MC/DC100%1/1
$cfg->{"batches"}{$bkey} //= []
$cfg->{"batches"}{$bkey}
Truth table100%2/2
A
A= $cfg->{"batches"}{$bkey}
Aresult
11
00
729  
730 # Check batch size threshold
731 17 my $batch = $cfg->{batches}{$bkey};
732 17 my $batch_bytes = 0;
733 17 for my $b (@$batch) {
734 18 ▶ $batch_bytes += length($b->{rec}{value} // '') + length($b->{rec}{key} // '') + 20;
Condition50%2/4
$b->{"rec"}{"value"} // ""
l!l
180
$b->{"rec"}{"key"} // ""
l!l
180
MC/DC0%0/1
$b->{"rec"}{"value"} // ""
$b->{"rec"}{"value"}
MC/DC0%0/1
$b->{"rec"}{"key"} // ""
$b->{"rec"}{"key"}
Truth table50%1/2
A
A= $b->{"rec"}{"value"}
Aresult
11
00
Truth table50%1/2
A
A= $b->{"rec"}{"key"}
Aresult
11
00
735 }
736  
737 17 ▶ if ($batch_bytes >= $cfg->{batch_size}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($batch_bytes >= $cfg->{'batch_size'}) { } 0 17 17
elsif (not $cfg->{'_linger_active'}) { } 15 2 17
738 0 $self->_flush_batch($topic, $partition, $conn);
739 } elsif (!$cfg->{_linger_active}) {
740 # start linger timer
741 15 $cfg->{_linger_active} = 1;
742 15 weaken(my $weak = $self);
743 10 ▶ $cfg->{_linger_timer} = EV::timer $cfg->{linger_ms} / 1000.0, 0, sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
744 10 $cfg->{_linger_active} = 0;
745 10 ▶ $weak->_flush_all_batches if $weak;
Branch: 1 branch
BranchTrueFalseTotal
if $weak 10 0 10
746 15 };
747 }
748 }
749  
750 16 ▶sub _flush_batch {
Subroutine _flush_batch: called CC=12 SCAR=29.2
751 16 my ($self, $topic, $partition, $conn) = @_;
752 16 my $cfg = $self->{cfg};
753 16 my $bkey = "$topic:$partition";
754 16 ▶ my $idempotent = defined $cfg->{producer_id} && $cfg->{producer_id} >= 0;
Condition66%2/3
defined $cfg->{'producer_id'} && $cfg->{'producer_id'} >= 0
!ll&&!rl&&r
079
MC/DC50%1/2
defined $cfg->{'producer_id'} && $cfg->{'producer_id'} >= 0
defined $cfg->{'producer_id'} $cfg->{'producer_id'} >= 0
Truth table66%2/3
A && B
A= defined $cfg->{'producer_id'}B= $cfg->{'producer_id'} >= 0
ABresult
0X0
100
111
755  
756 # Idempotent: one in-flight batch per partition — racing batches can
757 # alias sequence numbers (OutOfOrderSequenceNumber, non-retriable).
758 16 ▶ return if $idempotent && $cfg->{_inflight}{$bkey};
Branch: 1 branch
BranchTrueFalseTotal
if $idempotent and $cfg->{"_inflight"}{$bkey} 0 16 16
Condition66%2/3
$idempotent and $cfg->{"_inflight"}{$bkey}
!ll&&!rl&&r
790
MC/DC0%0/2
$idempotent and $cfg->{"_inflight"}{$bkey}
$idempotent $cfg->{"_inflight"}{$bkey}
Truth table66%2/3
A and B
A= $idempotentB= $cfg->{"_inflight"}{$bkey}
ABresult
0X0
100
111
759  
760 16 my $batch = delete $cfg->{batches}{$bkey};
761 16 ▶ return unless $batch && @$batch;
Branch: 1 branch
BranchTrueFalseTotal
unless $batch and @$batch 0 16 16
Condition33%1/3
$batch and @$batch
!ll&&!rl&&r
0016
MC/DC0%0/2
$batch and @$batch
$batch @$batch
Truth table33%1/3
A and B
A= $batchB= @$batch
ABresult
0X0
100
111
762  
763 16 my @records = map { $_->{rec} } @$batch;
764 16 my @cbs = map { $_->{cb} } @$batch;
765  
766 16 my %popts = (acks => $cfg->{acks});
767 16 ▶ $popts{compression} = $cfg->{compression} if $cfg->{compression};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"compression"} 0 16 16
768 16 ▶ $popts{transactional_id} = $cfg->{transactional_id} if $cfg->{_txn_active};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"_txn_active"} 3 13 16
769 16 my $saved_seq;
770 16 ▶ if ($idempotent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idempotent) 9 7 16
771 9 $popts{producer_id} = $cfg->{producer_id};
772 9 $popts{producer_epoch} = $cfg->{producer_epoch};
773 9 ▶ $saved_seq = $cfg->{next_sequence}{$bkey} // 0;
Condition100%2/2
$cfg->{"next_sequence"}{$bkey} // 0
l!l
18
MC/DC100%1/1
$cfg->{"next_sequence"}{$bkey} // 0
$cfg->{"next_sequence"}{$bkey}
Truth table100%2/2
A
A= $cfg->{"next_sequence"}{$bkey}
Aresult
11
00
774 9 $popts{base_sequence} = $saved_seq;
775 9 $cfg->{next_sequence}{$bkey} = $saved_seq + scalar @records;
776 9 $cfg->{_inflight}{$bkey} = 1;
777 }
778  
779 16 ▶ $self->_add_txn_partition($topic, $partition) if $cfg->{_txn_active};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"_txn_active"} 3 13 16
780  
781 # retry count persists on the batch across re-queues
782 16 ▶ $cfg->{_batch_retries}{$bkey} //= 3;
Condition100%2/2
$cfg->{"_batch_retries"}{$bkey} //= 3
l!l
214
MC/DC100%1/1
$cfg->{"_batch_retries"}{$bkey} //= 3
$cfg->{"_batch_retries"}{$bkey}
Truth table100%2/2
A
A= $cfg->{"_batch_retries"}{$bkey}
Aresult
11
00
783  
784 # Transaction generation at send time: a late response must never
785 # re-queue a batch from an aborted/committed transaction.
786 16 my $txn_gen = $cfg->{_txn_gen};
787  
788 16 weaken(my $weak_self = $self);
789 16 ▶ $conn->produce_batch($topic, $partition, \@records, \%popts, sub {
Subroutine __ANON__: called CC=61 SCAR=57.8
790 16 my ($result, $err) = @_;
791 16 ▶ delete $cfg->{_inflight}{$bkey} if $idempotent;
Branch: 1 branch
BranchTrueFalseTotal
if $idempotent 9 7 16
792  
793 16 my $retriable = 0;
794 16 my $fatal_seq = 0;
795 16 my $dup_seq = 0;
796 16 ▶ if (!$err && $result && ref $result->{topics} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $err and $result and ref $result->{"topics"} eq "ARRAY") 12 4 16
Condition66%4/6
not $err and $result and ref $result->{"topics"} eq "ARRAY"
!ll&&!rl&&r
4012
not $err and $result
!ll&&!rl&&r
4012
MC/DC33%1/3
not $err and $result and ref $result->{"topics"} eq "ARRAY"
not $err $result ref $result->{"topics"} eq "ARRAY"
Truth table50%2/4
not(A) and B and C
A= not $errB= $resultC= ref $result->{"topics"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
797 12 for my $t (@{$result->{topics}}) {
798 12 ▶ for my $p (@{$t->{partitions} // []}) {
Condition50%1/2
$t->{"partitions"} // []
l!l
120
MC/DC0%0/1
$t->{"partitions"} // []
$t->{"partitions"}
Truth table50%1/2
A
A= $t->{"partitions"}
Aresult
11
00
799 12 ▶ my $ec = $p->{error_code} // 0;
Condition50%1/2
$p->{"error_code"} // 0
l!l
120
MC/DC0%0/1
$p->{"error_code"} // 0
$p->{"error_code"}
Truth table50%1/2
A
A= $p->{"error_code"}
Aresult
11
00
800 12 ▶ $retriable = $ec if $ec == 6 || $ec == 15 || $ec == 16;
Branch: 1 branch
BranchTrueFalseTotal
if $ec == 6 or $ec == 15 or $ec == 16 0 12 12
Condition33%2/6
$ec == 6 or $ec == 15 or $ec == 16
l!l&&r!l&&!r
0012
$ec == 6 or $ec == 15
l!l&&r!l&&!r
0012
MC/DC0%0/3
$ec == 6 or $ec == 15 or $ec == 16
$ec == 6 $ec == 15 $ec == 16
Truth table25%1/4
A or B or C
A= $ec == 6B= $ec == 15C= $ec == 16
ABCresult
1XX1
01X1
0011
0000
801 # 45/47: broker fenced this producer — re-init and retry.
802 # 46 = DUPLICATE_SEQUENCE: broker already has this batch;
803 # treat as an ack (re-sending would create the duplicates).
804 12 ▶ $fatal_seq = $ec if $ec == 45 || $ec == 47;
Branch: 1 branch
BranchTrueFalseTotal
if $ec == 45 or $ec == 47 2 10 12
Condition66%2/3
$ec == 45 or $ec == 47
l!l&&r!l&&!r
0210
MC/DC50%1/2
$ec == 45 or $ec == 47
$ec == 45 $ec == 47
Truth table66%2/3
A or B
A= $ec == 45B= $ec == 47
ABresult
1X1
011
000
805 12 ▶ $dup_seq = 1 if $ec == 46;
Branch: 1 branch
BranchTrueFalseTotal
if $ec == 46 1 11 12
806 }
807 }
808 }
809  
810 # 46 is an ack: clear it in the delivered result.
811 16 ▶ if ($dup_seq && !$fatal_seq && !$retriable && $result) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dup_seq and not $fatal_seq and not $retriable and $result) 1 15 16
Condition66%6/9
$dup_seq and not $fatal_seq and not $retriable and $result
!ll&&!rl&&r
1501
$dup_seq and not $fatal_seq and not $retriable
!ll&&!rl&&r
1501
$dup_seq and not $fatal_seq
!ll&&!rl&&r
1501
MC/DC25%1/4
$dup_seq and not $fatal_seq and not $retriable and $result
$dup_seq not $fatal_seq not $retriable $result
Truth table40%2/5
A and not(B) and not(C) and D
A= $dup_seqB= not $fatal_seqC= not $retriableD= $result
ABCDresult
0XXX0
10XX0
110X0
11100
11111
812 1 for my $t (@{$result->{topics}}) {
813 1 ▶ for my $p (@{$t->{partitions} // []}) {
Condition50%1/2
$t->{"partitions"} // []
l!l
10
MC/DC0%0/1
$t->{"partitions"} // []
$t->{"partitions"}
Truth table50%1/2
A
A= $t->{"partitions"}
Aresult
11
00
814 1 ▶ $p->{error_code} = 0 if ($p->{error_code} // 0) == 46;
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"error_code"} // 0) == 46 1 0 1
Condition50%1/2
$p->{"error_code"} // 0
l!l
10
MC/DC0%0/1
$p->{"error_code"} // 0
$p->{"error_code"}
Truth table50%1/2
A
A= $p->{"error_code"}
Aresult
11
00
815 }
816 }
817 }
818  
819 # Fatal sequence error: re-init producer id/epoch and retry the
820 # batch (guarded against a stale txn generation by the $txn_gen check).
821 16 ▶ if ($idempotent && $fatal_seq && !$cfg->{closed}
Branch: 1 branch
BranchTrueFalseTotal
if ($idempotent and $fatal_seq and not $cfg->{"closed"} and $txn_gen == $cfg->{"_txn_gen"}) 2 14 16
Condition77%7/9
$idempotent and $fatal_seq and not $cfg->{"closed"} and $txn_gen == $cfg->{"_txn_gen"}
!ll&&!rl&&r
1402
$idempotent and $fatal_seq and not $cfg->{"closed"}
!ll&&!rl&&r
1402
$idempotent and $fatal_seq
!ll&&!rl&&r
772
MC/DC50%2/4
$idempotent and $fatal_seq and not $cfg->{"closed"} and $txn_gen == $cfg->{"_txn_gen"}
$idempotent $fatal_seq not $cfg->{"closed"} $txn_gen == $cfg->{"_txn_gen"}
Truth table60%3/5
A and B and not(C) and D
A= $idempotentB= $fatal_seqC= not $cfg->{"closed"}D= $txn_gen == $cfg->{"_txn_gen"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
822 && $txn_gen == $cfg->{_txn_gen}) {
823 2 ▶ if ($cfg->{_txn_active}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"_txn_active"}) 0 2 2
824 # fenced mid-transaction: the txn is dead; only abort ->
825 # begin can continue. Surface it, don't silently re-init.
826 0 my $msg = "producer fenced by broker (code $fatal_seq) during transaction";
827 0 ▶ $cfg->{on_error}->($msg) if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 0 0 0
828 0 delete $cfg->{_batch_retries}{$bkey};
829 0 for my $cb (@cbs) {
830 0 ▶ next unless $cb;
Branch: 1 branch
BranchTrueFalseTotal
unless $cb 0 0 0
831 0 eval { $cb->(undef, $msg) };
832 0 ▶ warn "EV::Kafka: produce callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
833 }
834 0 return;
835 }
836 2 ▶ if (($cfg->{_epoch_retries}{$bkey} //= 1) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (($cfg->{"_epoch_retries"}{$bkey} //= 1) > 0) 2 0 2
Condition50%1/2
$cfg->{"_epoch_retries"}{$bkey} //= 1
l!l
02
MC/DC0%0/1
$cfg->{"_epoch_retries"}{$bkey} //= 1
$cfg->{"_epoch_retries"}{$bkey}
Truth table50%1/2
A
A= $cfg->{"_epoch_retries"}{$bkey}
Aresult
11
00
837 2 $cfg->{_epoch_retries}{$bkey}--;
838 # rewind sequence and re-queue the batch
839 2 $cfg->{next_sequence} = {};
840 2 $cfg->{_acked_sequence} = {};
841 2 ▶ if (exists $cfg->{batches}{$bkey}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cfg->{'batches'}{$bkey}) { } 0 2 2
842 0 unshift @{$cfg->{batches}{$bkey}}, @$batch;
843 } else {
844 2 $cfg->{batches}{$bkey} = $batch;
845 }
846 # force re-init then re-flush; _pid single-flight makes N
847 # fenced partitions share ONE InitProducerId round trip.
848 2 $cfg->{producer_id} = -1;
849 2 $cfg->{producer_epoch} = -1;
850 2 ▶ $cfg->{_pid} = 'idle' if $cfg->{_pid} ne 'init';
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"_pid"} ne "init" 1 1 2
851 2 ▶ $weak_self->_init_idempotent(sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
852 2 ▶ $weak_self->_flush_all_batches if $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self 2 0 2
853 2 ▶ }) if $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self 2 0 2
854 2 return;
855 }
856 # recovery budget exhausted: fall through to error delivery
857 }
858  
859 14 ▶ if ($retriable && !$cfg->{closed} && $txn_gen == $cfg->{_txn_gen}
Branch: 1 branch
BranchTrueFalseTotal
if ($retriable and not $cfg->{"closed"} and $txn_gen == $cfg->{"_txn_gen"} and ($cfg->{"_batch_retries"}{$bkey} // 0) > 0) 0 14 14
Condition27%3/11
$retriable and not $cfg->{"closed"} and $txn_gen == $cfg->{"_txn_gen"} and ($cfg->{"_batch_retries"}{$bkey} // 0) > 0
!ll&&!rl&&r
1400
$retriable and not $cfg->{"closed"} and $txn_gen == $cfg->{"_txn_gen"}
!ll&&!rl&&r
1400
$retriable and not $cfg->{"closed"}
!ll&&!rl&&r
1400
$cfg->{"_batch_retries"}{$bkey} // 0
l!l
00
MC/DC0%0/4
$retriable and not $cfg->{"closed"} and $txn_gen == $cfg->{"_txn_gen"} and ($cfg->{"_batch_retries"}{$bkey} // 0) > 0
$retriable not $cfg->{"closed"} $txn_gen == $cfg->{"_txn_gen"} $cfg->{"_batch_retries"}{$bkey}
Truth table20%1/5
A and not(B) and C and D
A= $retriableB= not $cfg->{"closed"}C= $txn_gen == $cfg->{"_txn_gen"}D= $cfg->{"_batch_retries"}{$bkey}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
860 && ($cfg->{_batch_retries}{$bkey} // 0) > 0) {
861 0 $cfg->{_batch_retries}{$bkey}--;
862 0 ▶ $cfg->{next_sequence}{$bkey} = $saved_seq if defined $saved_seq;
Branch: 1 branch
BranchTrueFalseTotal
if defined $saved_seq 0 0 0
863 0 ▶ if (exists $cfg->{batches}{$bkey}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cfg->{'batches'}{$bkey}) { } 0 0 0
864 0 unshift @{$cfg->{batches}{$bkey}}, @$batch;
865 } else {
866 0 $cfg->{batches}{$bkey} = $batch;
867 }
868 0 ▶ $weak_self->_refresh_metadata if $weak_self && !$cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self and not $cfg->{"meta_pending"} 0 0 0
Condition0%0/3
$weak_self and not $cfg->{"meta_pending"}
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self and not $cfg->{"meta_pending"}
$weak_self not $cfg->{"meta_pending"}
Truth table0%0/3
A and not(B)
A= $weak_selfB= not $cfg->{"meta_pending"}
ABresult
0X0
100
111
869 0 ▶ my $rt; $rt = EV::timer 0.5, 0, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
870 0 undef $rt;
871 0 ▶ $weak_self->_flush_all_batches if $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self 0 0 0
872 0 };
873 0 return;
874 }
875 14 delete $cfg->{_batch_retries}{$bkey};
876  
877 # Track the broker-acked sequence high-water mark so
878 # abort_transaction can roll back next_sequence without gaps, and
879 # restore the epoch-retry budget. 45/47 don't advance the mark.
880 14 ▶ if ($idempotent && !$err && !$fatal_seq && defined $saved_seq) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idempotent and not $err and not $fatal_seq and defined $saved_seq) 6 8 14
Condition77%7/9
$idempotent and not $err and not $fatal_seq and defined $saved_seq
!ll&&!rl&&r
806
$idempotent and not $err and not $fatal_seq
!ll&&!rl&&r
806
$idempotent and not $err
!ll&&!rl&&r
716
MC/DC50%2/4
$idempotent and not $err and not $fatal_seq and defined $saved_seq
$idempotent not $err not $fatal_seq defined $saved_seq
Truth table60%3/5
A and not(B) and not(C) and D
A= $idempotentB= not $errC= not $fatal_seqD= defined $saved_seq
ABCDresult
0XXX0
10XX0
110X0
11100
11111
881 6 my $next = $saved_seq + scalar @records;
882 6 ▶ my $cur = $cfg->{_acked_sequence}{$bkey} // 0;
Condition50%1/2
$cfg->{"_acked_sequence"}{$bkey} // 0
l!l
06
MC/DC0%0/1
$cfg->{"_acked_sequence"}{$bkey} // 0
$cfg->{"_acked_sequence"}{$bkey}
Truth table50%1/2
A
A= $cfg->{"_acked_sequence"}{$bkey}
Aresult
11
00
883 6 ▶ $cfg->{_acked_sequence}{$bkey} = $next if $next > $cur;
Branch: 1 branch
BranchTrueFalseTotal
if $next > $cur 6 0 6
884 6 delete $cfg->{_epoch_retries}{$bkey};
885 }
886  
887 # Each record callback fires even if a sibling's callback dies.
888 14 for my $cb (@cbs) {
889 15 ▶ next unless $cb;
Branch: 1 branch
BranchTrueFalseTotal
unless $cb 2 13 15
890 13 eval { $cb->($result, $err) };
891 13 ▶ warn "EV::Kafka: produce callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 12 13
892 }
893  
894 # Idempotent: kick any batch that accumulated while we were in-flight.
895 14 ▶ if ($idempotent && !$cfg->{closed} && $weak_self
Branch: 1 branch
BranchTrueFalseTotal
if ($idempotent and not $cfg->{"closed"} and $weak_self and $cfg->{"batches"}{$bkey} and @{$cfg->{"batches"}{$bkey};}) 0 14 14
Condition58%7/12
$idempotent and not $cfg->{"closed"} and $weak_self and $cfg->{"batches"}{$bkey} and @{$cfg->{"batches"}{$bkey};}
!ll&&!rl&&r
1400
$idempotent and not $cfg->{"closed"} and $weak_self and $cfg->{"batches"}{$bkey}
!ll&&!rl&&r
770
$idempotent and not $cfg->{"closed"} and $weak_self
!ll&&!rl&&r
707
$idempotent and not $cfg->{"closed"}
!ll&&!rl&&r
707
MC/DC0%0/5
$idempotent and not $cfg->{"closed"} and $weak_self and $cfg->{"batches"}{$bkey} and @{$cfg->{"batches"}{$bkey};}
$idempotent not $cfg->{"closed"} $weak_self $cfg->{"batches"}{$bkey} @{$cfg->{"batches"}{$bkey};}
Truth table33%2/6
A and not(B) and C and D and E
A= $idempotentB= not $cfg->{"closed"}C= $weak_selfD= $cfg->{"batches"}{$bkey}E= @{$cfg->{"batches"}{$bkey};}
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
896 0 && $cfg->{batches}{$bkey} && @{$cfg->{batches}{$bkey}}) {
897 0 $weak_self->_flush_all_batches;
898 }
899 16 });
900 }
901  
902 28 ▶sub _flush_all_batches {
Subroutine _flush_all_batches: called CC=8 SCAR=20.9
903 28 my ($self) = @_;
904 28 my $cfg = $self->{cfg};
905 28 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 28 28
906 28 my $skipped = 0;
907 28 for my $bkey (keys %{$cfg->{batches}}) {
908 27 my ($topic, $partition) = split /:/, $bkey, 2;
909 27 my $leader_id = $self->_get_leader($topic, $partition);
910 27 ▶ unless (defined $leader_id) { $skipped++; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $leader_id) 1 26 27
911 26 my $conn = $self->_get_or_create_conn($leader_id);
912 26 ▶ unless ($conn && $conn->connected) { $skipped++; next }
Branch: 1 branch
BranchTrueFalseTotal
unless ($conn and $conn->connected) 10 16 26
Condition66%2/3
$conn and $conn->connected
!ll&&!rl&&r
01016
MC/DC50%1/2
$conn and $conn->connected
$conn $conn->connected
Truth table66%2/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
913 16 $self->_flush_batch($topic, $partition, $conn);
914 }
915 # re-arm timer if batches were skipped (connection not yet ready)
916 28 ▶ if ($skipped && keys %{$cfg->{batches}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skipped and keys %{$$cfg{"batches"};}) 11 17 28
Condition66%2/3
$skipped and keys %{$$cfg{"batches"};}
!ll&&!rl&&r
17011
MC/DC50%1/2
$skipped and keys %{$$cfg{"batches"};}
$skipped keys %{$$cfg{"batches"};}
Truth table66%2/3
A and B
A= $skippedB= keys %{$$cfg{"batches"};}
ABresult
0X0
100
111
917 11 $cfg->{_linger_active} = 1;
918 11 weaken(my $weak = $self);
919 10 ▶ $cfg->{_linger_timer} = EV::timer 0.1, 0, sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
920 10 $cfg->{_linger_active} = 0;
921 10 ▶ $weak->_flush_all_batches if $weak;
Branch: 1 branch
BranchTrueFalseTotal
if $weak 10 0 10
922 11 };
923 }
924 }
925  
926 3 ▶sub produce_many {
Subroutine produce_many: called CC=11 SCAR=34.0
927 3 my ($self, $messages, $cb) = @_;
928 3 ▶ croak "EV::Kafka: client is closed" if $self->{cfg}{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cfg"}{"closed"} 1 2 3
929 2 my $remaining = scalar @$messages;
930 2 ▶ return $cb->() if $cb && !$remaining;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and not $remaining 1 1 2
Condition66%2/3
$cb and not $remaining
!ll&&!rl&&r
011
MC/DC50%1/2
$cb and not $remaining
$cb not $remaining
Truth table66%2/3
A and not(B)
A= $cbB= not $remaining
ABresult
0X0
100
111
931 1 my @errors;
932 1 my $acks0 = ($self->{cfg}{acks} == 0);
933 1 for my $msg (@$messages) {
934 2 my ($topic, $key, $value, @rest);
935 2 ▶ if (ref $msg eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $msg eq 'ARRAY') { } 2 0 2
936 2 ($topic, $key, $value, @rest) = @$msg;
937 } else {
938 0 ($topic, $key, $value) = @{$msg}{qw(topic key value)};
939 0 my %opts = %$msg;
940 0 delete @opts{qw(topic key value)};
941 0 ▶ push @rest, \%opts if %opts;
Branch: 1 branch
BranchTrueFalseTotal
if %opts 0 0 0
942 }
943 2 ▶ if ($acks0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($acks0) { } 2 0 2
944 2 $self->produce($topic, $key, $value, @rest);
945 } else {
946 0 ▶ $self->produce($topic, $key, $value, @rest, sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
947 0 my ($result, $err) = @_;
948 0 ▶ push @errors, $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
949 0 ▶ if (--$remaining <= 0 && $cb) {
Branch: 1 branch
BranchTrueFalseTotal
if (--$remaining <= 0 and $cb) 0 0 0
Condition0%0/3
--$remaining <= 0 and $cb
!ll&&!rl&&r
000
MC/DC0%0/2
--$remaining <= 0 and $cb
--$remaining <= 0 $cb
Truth table0%0/3
A and B
A= --$remaining <= 0B= $cb
ABresult
0X0
100
111
950 0 ▶ $cb->(@errors ? \@errors : ());
Branch: 1 branch
BranchTrueFalseTotal
@errors ? : 0 0 0
951 }
952 0 });
953 }
954 }
955 1 ▶ $cb->(@errors ? \@errors : ()) if $cb && $acks0;
Branch: 2 branches
BranchTrueFalseTotal
if $cb and $acks0 1 0 1
@errors ? : 0 1 1
Condition33%1/3
$cb and $acks0
!ll&&!rl&&r
001
MC/DC0%0/2
$cb and $acks0
$cb $acks0
Truth table33%1/3
A and B
A= $cbB= $acks0
ABresult
0X0
100
111
956 }
957  
958 6 ▶sub flush {
Subroutine flush: called CC=6 SCAR=18.2
959 6 my ($self, $cb) = @_;
960 6 my $cfg = $self->{cfg};
961 6 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 5 6
962  
963 # flush any accumulated linger batches first
964 5 $self->_flush_all_batches;
965 5 undef $cfg->{_linger_timer};
966 5 $cfg->{_linger_active} = 0;
967  
968 # Drained when all of these reach zero: in-flight requests on every
969 # connection, pre-metadata pending_ops, gated/queued idempotent batches.
970 114 ▶ my $outstanding = sub {
Subroutine __ANON__: called CC=11 SCAR=25.9
971 114 my $p = 0;
972 114 my %seen;
973 114 ▶ for my $c (values %{$cfg->{conns} // {}}) {
Condition50%1/2
$cfg->{"conns"} // {}
l!l
1140
MC/DC0%0/1
$cfg->{"conns"} // {}
$cfg->{"conns"}
Truth table50%1/2
A
A= $cfg->{"conns"}
Aresult
11
00
974 113 ▶ next unless $c && $c->connected;
Branch: 1 branch
BranchTrueFalseTotal
unless $c and $c->connected 72 41 113
Condition66%2/3
$c and $c->connected
!ll&&!rl&&r
07241
MC/DC50%1/2
$c and $c->connected
$c $c->connected
Truth table66%2/3
A and B
A= $cB= $c->connected
ABresult
0X0
100
111
975 41 $p += $c->pending;
976 41 $seen{$$c} = 1;
977 }
978 $p += $cfg->{bootstrap_conn}->pending
979 if $cfg->{bootstrap_conn} && $cfg->{bootstrap_conn}->connected
980 114 ▶ && !$seen{${$cfg->{bootstrap_conn}}};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"bootstrap_conn"} and $cfg->{"bootstrap_conn"}->connected and not $seen{${$cfg->{"bootstrap_conn"};}} 0 114 114
Condition83%5/6
$cfg->{"bootstrap_conn"} and $cfg->{"bootstrap_conn"}->connected and not $seen{${$cfg->{"bootstrap_conn"};}}
!ll&&!rl&&r
73410
$cfg->{"bootstrap_conn"} and $cfg->{"bootstrap_conn"}->connected
!ll&&!rl&&r
17241
MC/DC0%0/3
$cfg->{"bootstrap_conn"} and $cfg->{"bootstrap_conn"}->connected and not $seen{${$cfg->{"bootstrap_conn"};}}
$cfg->{"bootstrap_conn"} $cfg->{"bootstrap_conn"}->connected not $seen{${$cfg->{"bootstrap_conn"};}}
Truth table75%3/4
A and B and not(C)
A= $cfg->{"bootstrap_conn"}B= $cfg->{"bootstrap_conn"}->connectedC= not $seen{${$cfg->{"bootstrap_conn"};}}
ABCresult
0XX0
10X0
1100
1111
981 114 ▶ $p += scalar @{$cfg->{pending_ops} // []};
Condition50%1/2
$cfg->{"pending_ops"} // []
l!l
1140
MC/DC0%0/1
$cfg->{"pending_ops"} // []
$cfg->{"pending_ops"}
Truth table50%1/2
A
A= $cfg->{"pending_ops"}
Aresult
11
00
982 114 ▶ $p += scalar grep { $_ && @$_ } values %{$cfg->{batches} // {}};
Condition20%1/5
$_ && @$_
!ll&&!rl&&r
000
$cfg->{"batches"} // {}
l!l
1140
MC/DC0%0/2
$_ && @$_
$_ @$_
MC/DC0%0/1
$cfg->{"batches"} // {}
$cfg->{"batches"}
Truth table0%0/3
A && B
A= $_B= @$_
ABresult
0X0
100
111
Truth table50%1/2
A
A= $cfg->{"batches"}
Aresult
11
00
983 114 return $p;
984 5 };
985  
986 5 ▶ if ($outstanding->() == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$outstanding() == 0) 1 4 5
987 1 ▶ $cb->() if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
988 1 return;
989 }
990 4 ▶ my $timeout = $cfg->{flush_timeout} // 0;
Condition50%1/2
$cfg->{"flush_timeout"} // 0
l!l
40
MC/DC0%0/1
$cfg->{"flush_timeout"} // 0
$cfg->{"flush_timeout"}
Truth table50%1/2
A
A= $cfg->{"flush_timeout"}
Aresult
11
00
991 4 ▶ my $deadline = $timeout > 0 ? EV::now + $timeout : 0;
Branch: 1 branch
BranchTrueFalseTotal
$timeout > 0 ? : 4 0 4
992 4 ▶ my $check; $check = EV::timer 0, 0.01, sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
993 110 ▶ if ($deadline && EV::now >= $deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if ($deadline and &EV::now() >= $deadline) 1 109 110
Condition66%2/3
$deadline and &EV::now() >= $deadline
!ll&&!rl&&r
01091
MC/DC50%1/2
$deadline and &EV::now() >= $deadline
$deadline &EV::now() >= $deadline
Truth table66%2/3
A and B
A= $deadlineB= &EV::now() >= $deadline
ABresult
0X0
100
111
994 1 undef $check;
995 1 $cfg->{_flush_timer} = undef;
996 1 my $fcb = delete $cfg->{_flush_cb};
997 1 ▶ $fcb->("flush timed out") if $fcb;
Branch: 1 branch
BranchTrueFalseTotal
if $fcb 1 0 1
998 1 return;
999 }
1000 109 ▶ return if $outstanding->() > 0;
Branch: 1 branch
BranchTrueFalseTotal
if &$outstanding() > 0 106 3 109
1001 3 undef $check;
1002 3 $cfg->{_flush_timer} = undef;
1003 3 my $fcb = delete $cfg->{_flush_cb};
1004 3 ▶ $fcb->() if $fcb;
Branch: 1 branch
BranchTrueFalseTotal
if $fcb 2 1 3
1005 4 };
1006 # Stored so close() can fail the callback instead of stranding it.
1007 4 $cfg->{_flush_timer} = $check;
1008 4 $cfg->{_flush_cb} = $cb;
1009 }
1010  
1011 # --- Consumer ---
1012  
1013 11 ▶sub assign {
Subroutine assign: called CC=2 SCAR=6.9
1014 11 my ($self, $partitions) = @_;
1015 11 my $cfg = $self->{cfg};
1016 11 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 10 11
1017 10 $cfg->{assignments} = $partitions;
1018 10 $cfg->{_fetch_err_seen} = {}; # fresh assignment: fresh error budget
1019 }
1020  
1021 6 ▶sub seek {
Subroutine seek: called CC=12 SCAR=25.3
1022 6 my ($self, $topic, $partition, $offset_or_ts, $cb) = @_;
1023 6 ▶ croak "EV::Kafka: client is closed" if $self->{cfg}{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"cfg"}{"closed"} 1 5 6
1024 # offset_or_ts: integer offset, or -1 (latest), -2 (earliest)
1025 5 for my $a (@{$self->{cfg}{assignments}}) {
1026 5 ▶ if ($a->{topic} eq $topic && $a->{partition} == $partition) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a->{"topic"} eq $topic and $a->{"partition"} == $partition) 4 1 5
Condition66%2/3
$a->{"topic"} eq $topic and $a->{"partition"} == $partition
!ll&&!rl&&r
104
MC/DC50%1/2
$a->{"topic"} eq $topic and $a->{"partition"} == $partition
$a->{"topic"} eq $topic $a->{"partition"} == $partition
Truth table66%2/3
A and B
A= $a->{"topic"} eq $topicB= $a->{"partition"} == $partition
ABresult
0X0
100
111
1027 4 ▶ if ($offset_or_ts >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset_or_ts >= 0) { } 1 3 4
1028 1 $a->{offset} = $offset_or_ts;
1029 1 ▶ $cb->() if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 0 1 1
1030 } else {
1031 # resolve via list_offsets
1032 3 my $leader_id = $self->_get_leader($topic, $partition);
1033 3 ▶ my $conn = defined($leader_id) ? $self->_get_or_create_conn($leader_id) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $leader_id ? : 2 1 3
1034 3 ▶ if ($conn && $conn->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conn and $conn->connected) { } 2 1 3
Condition66%2/3
$conn and $conn->connected
!ll&&!rl&&r
102
MC/DC50%1/2
$conn and $conn->connected
$conn $conn->connected
Truth table66%2/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
1035 2 ▶ $conn->list_offsets($topic, $partition, $offset_or_ts, sub {
Subroutine __ANON__: called CC=5 SCAR=16.6
1036 2 my ($res, $err) = @_;
1037 2 ▶ if (!$err && $res) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $err and $res) 1 1 2
Condition66%2/3
not $err and $res
!ll&&!rl&&r
101
MC/DC50%1/2
not $err and $res
not $err $res
Truth table66%2/3
not(A) and B
A= not $errB= $res
ABresult
0X0
100
111
1038 1 my $off = $res->{topics}[0]{partitions}[0]{offset};
1039 1 ▶ $a->{offset} = $off if defined $off;
Branch: 1 branch
BranchTrueFalseTotal
if defined $off 1 0 1
1040 }
1041 2 ▶ $cb->($res, $err) if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 2 0 2
1042 2 });
1043 } else {
1044 1 ▶ $cb->(undef, "seek: no connection to leader for $topic:$partition")
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
1045 if $cb;
1046 }
1047 }
1048 4 return;
1049 }
1050 }
1051 1 ▶ $cb->(undef, "seek: $topic:$partition is not assigned") if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
1052 }
1053  
1054 17 ▶sub poll {
Subroutine poll: called CC=15 SCAR=27.7
1055 17 my ($self, $cb) = @_;
1056 17 my $cfg = $self->{cfg};
1057 17 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 16 17
1058 # Empty assignment is a successful empty poll, not a dropped callback.
1059 16 ▶ if (!@{$cfg->{assignments}}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$cfg->{"assignments"};}) 1 15 16
1060 1 ▶ $cb->() if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
1061 1 return;
1062 }
1063  
1064 15 ▶ unless ($cfg->{meta}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"meta"}) 2 13 15
1065 2 weaken(my $weak = $self);
1066 2 push @{$cfg->{pending_ops}}, {
1067 cb => $cb,
1068 1 ▶ run => sub { $weak->poll($cb) if $weak },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $weak 1 0 1
1069 2 };
1070 2 ▶ $self->_refresh_metadata unless $cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"meta_pending"} 2 0 2
1071 2 return;
1072 }
1073  
1074 # Group assignments by leader for multi-partition fetch
1075 13 my %by_leader; # leader_id => { topic => [{partition, offset, assign_ref}] }
1076 13 for my $a (@{$cfg->{assignments}}) {
1077 13 my $leader_id = $self->_get_leader($a->{topic}, $a->{partition});
1078 13 ▶ next unless defined $leader_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $leader_id 1 12 13
1079 12 push @{$by_leader{$leader_id}{$a->{topic}}}, {
1080 partition => $a->{partition},
1081 offset => $a->{offset},
1082 12 _assign => $a,
1083 };
1084 }
1085  
1086 13 my $dispatched = 0;
1087 13 my $first_err;
1088 13 weaken(my $weak = $self);
1089 13 for my $leader_id (keys %by_leader) {
1090 12 my $conn = $self->_get_or_create_conn($leader_id);
1091 12 ▶ next unless $conn && $conn->connected;
Branch: 1 branch
BranchTrueFalseTotal
unless $conn and $conn->connected 1 11 12
Condition66%2/3
$conn and $conn->connected
!ll&&!rl&&r
0111
MC/DC50%1/2
$conn and $conn->connected
$conn $conn->connected
Truth table66%2/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
1092 11 $dispatched++;
1093  
1094 # build fetch_multi argument: {topic => [{partition, offset}]}
1095 11 my %fetch_arg;
1096 my %assign_map; # "topic:partition" => [assignment ref, requested offset]
1097 11 for my $topic (keys %{$by_leader{$leader_id}}) {
1098 11 for my $p (@{$by_leader{$leader_id}{$topic}}) {
1099 11 push @{$fetch_arg{$topic}}, {
1100 partition => $p->{partition},
1101 offset => $p->{offset},
1102 11 };
1103 11 $assign_map{"$topic:$p->{partition}"} = [$p->{_assign}, $p->{offset}];
1104 }
1105 }
1106  
1107 $conn->fetch_multi(\%fetch_arg, {
1108 max_bytes => $cfg->{fetch_max_bytes},
1109 max_wait_ms => $cfg->{fetch_max_wait_ms},
1110 min_bytes => $cfg->{fetch_min_bytes},
1111 11 ▶ }, sub {
Subroutine __ANON__: called CC=25 SCAR=34.8
1112 11 my ($result, $err) = @_;
1113 11 $dispatched--;
1114 11 ▶ $first_err //= $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 1 10 11
Condition33%1/3
$first_err //= $err
l!l&&r!l&&!r
010
MC/DC0%0/2
$first_err //= $err
$first_err $err
Truth table33%1/3
A //= B
A= $first_errB= $err
ABresult
1X1
011
000
1115  
1116 # close() silences messages but never drops the poll callback.
1117 11 ▶ if (!$cfg->{closed} && !$err && $result && ref $result->{topics} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $cfg->{"closed"} || $err and $result and ref $result->{"topics"} eq "ARRAY") 10 1 11
Condition66%6/9
not $cfg->{"closed"} || $err and $result and ref $result->{"topics"} eq "ARRAY"
!ll&&!rl&&r
1010
not $cfg->{"closed"} || $err and $result
!ll&&!rl&&r
1010
$cfg->{'closed'} || $err
l!l&&r!l&&!r
1010
MC/DC25%1/4
not $cfg->{"closed"} || $err and $result and ref $result->{"topics"} eq "ARRAY"
$cfg->{'closed'} $err $result ref $result->{"topics"} eq "ARRAY"
Truth table40%2/5
not(A || B) and C and D
A= $cfg->{'closed'}B= $errC= $resultD= ref $result->{"topics"} eq "ARRAY"
ABCDresult
1XXX0
01XX0
000X0
00100
00111
1118 10 for my $t (@{$result->{topics}}) {
1119 10 ▶ for my $p (@{$t->{partitions} // []}) {
Condition50%1/2
$t->{"partitions"} // []
l!l
100
MC/DC0%0/1
$t->{"partitions"} // []
$t->{"partitions"}
Truth table50%1/2
A
A= $t->{"partitions"}
Aresult
11
00
1120 10 my $entry = $assign_map{"$t->{topic}:$p->{partition}"};
1121 10 ▶ my $ec = $p->{error_code} // 0;
Condition50%1/2
$p->{"error_code"} // 0
l!l
100
MC/DC0%0/1
$p->{"error_code"} // 0
$p->{"error_code"}
Truth table50%1/2
A
A= $p->{"error_code"}
Aresult
11
00
1122 10 ▶ if ($ec) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ec) 3 7 10
1123 # Per-partition error: recover or report.
1124 3 ▶ if ($weak) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak) 3 0 3
1125 my $emsg = $weak->_fetch_partition_error(
1126 3 ▶ $t->{topic}, $p->{partition}, $ec,
Branch: 1 branch
BranchTrueFalseTotal
$entry ? : 3 0 3
1127 $entry ? $entry->[0] : undef);
1128 3 ▶ $first_err //= $emsg if $emsg;
Branch: 1 branch
BranchTrueFalseTotal
if $emsg 1 2 3
Condition33%1/3
$first_err //= $emsg
l!l&&r!l&&!r
010
MC/DC0%0/2
$first_err //= $emsg
$first_err $emsg
Truth table33%1/3
A //= B
A= $first_errB= $emsg
ABresult
1X1
011
000
1129 }
1130 3 next;
1131 }
1132 7 ▶ my $records = $p->{records} // [];
Condition50%1/2
$p->{"records"} // []
l!l
70
MC/DC0%0/1
$p->{"records"} // []
$p->{"records"}
Truth table50%1/2
A
A= $p->{"records"}
Aresult
11
00
1133 7 for my $r (@$records) {
1134 6 ▶ next unless $cfg->{on_message};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"on_message"} 0 6 6
1135 # a die must not skip the remaining records
1136 6 eval {
1137 $cfg->{on_message}->(
1138 $t->{topic}, $p->{partition},
1139 $r->{offset}, $r->{key}, $r->{value},
1140 $r->{headers}
1141 6 );
1142 };
1143 6 ▶ warn "EV::Kafka: on_message error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 5 6
1144 }
1145 # Seek-clobber guard: a seek() that landed while
1146 # this fetch was in flight wins; don't overwrite.
1147 7 ▶ if (@$records && $entry
Branch: 1 branch
BranchTrueFalseTotal
if (@$records and $entry and $entry->[0]{"offset"} == $entry->[1]) 3 4 7
Condition83%5/6
@$records and $entry and $entry->[0]{"offset"} == $entry->[1]
!ll&&!rl&&r
313
@$records and $entry
!ll&&!rl&&r
304
MC/DC66%2/3
@$records and $entry and $entry->[0]{"offset"} == $entry->[1]
@$records $entry $entry->[0]{"offset"} == $entry->[1]
Truth table75%3/4
A and B and C
A= @$recordsB= $entryC= $entry->[0]{"offset"} == $entry->[1]
ABCresult
0XX0
10X0
1100
1111
1148 && $entry->[0]{offset} == $entry->[1]) {
1149 3 $entry->[0]{offset} = $records->[-1]{offset} + 1;
1150 }
1151 }
1152 }
1153 }
1154  
1155 11 ▶ $cb->($first_err) if $cb && $dispatched <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and $dispatched <= 0 11 0 11
Condition33%1/3
$cb and $dispatched <= 0
!ll&&!rl&&r
0011
MC/DC0%0/2
$cb and $dispatched <= 0
$cb $dispatched <= 0
Truth table33%1/3
A and B
A= $cbB= $dispatched <= 0
ABresult
0X0
100
111
1156 11 });
1157 }
1158 13 ▶ $cb->($first_err) if $cb && !$dispatched;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and not $dispatched 2 11 13
Condition66%2/3
$cb and not $dispatched
!ll&&!rl&&r
0112
MC/DC50%1/2
$cb and not $dispatched
$cb not $dispatched
Truth table66%2/3
A and not(B)
A= $cbB= not $dispatched
ABresult
0X0
100
111
1159 }
1160  
1161 # Per-partition fetch errors. OFFSET_OUT_OF_RANGE (1): the position is
1162 # stale — re-resolve per auto_offset_reset and report to the poll
1163 # callback. Other codes: report to on_error, once per partition per
1164 # rebalance (budget resets on assign/rejoin).
1165 3 ▶sub _fetch_partition_error {
Subroutine _fetch_partition_error: called CC=9 SCAR=23.3
1166 3 my ($self, $topic, $partition, $ec, $a) = @_;
1167 3 my $cfg = $self->{cfg};
1168 3 ▶ return undef if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 3 3
1169 3 ▶ if ($ec == 1 && $a) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ec == 1 and $a) 1 2 3
Condition66%2/3
$ec == 1 and $a
!ll&&!rl&&r
201
MC/DC50%1/2
$ec == 1 and $a
$ec == 1 $a
Truth table66%2/3
A and B
A= $ec == 1B= $a
ABresult
0X0
100
111
1170 my $reset = $cfg->{group}
1171 1 ▶ ? ($cfg->{group}{auto_offset_reset} // 'earliest')
Branch: 1 branch
BranchTrueFalseTotal
$cfg->{'group'} ? : 0 1 1
Condition0%0/2
$cfg->{"group"}{"auto_offset_reset"} // "earliest"
l!l
00
MC/DC0%0/1
$cfg->{"group"}{"auto_offset_reset"} // "earliest"
$cfg->{"group"}{"auto_offset_reset"}
Truth table0%0/2
A
A= $cfg->{"group"}{"auto_offset_reset"}
Aresult
11
00
1172 : 'earliest';
1173 1 ▶ $self->seek($topic, $partition, $reset eq 'latest' ? -1 : -2, sub { });
Subroutine __ANON__: called CC=1 SCAR=0.4
Branch: 1 branch
BranchTrueFalseTotal
$reset eq 'latest' ? : 0 1 1
1174 1 return sprintf "fetch %s:%d: %s (code %d); offset reset to $reset",
1175 $topic, $partition, $self->error_name($ec), $ec;
1176 }
1177 2 my $key = "$topic:$partition:$ec";
1178 2 ▶ if (!$cfg->{_fetch_err_seen}{$key}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"_fetch_err_seen"}{$key}++) 1 1 2
1179 $cfg->{on_error}->(sprintf "fetch %s:%d: %s (code %d)",
1180 $topic, $partition, $self->error_name($ec), $ec)
1181 1 ▶ if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 1 0 1
1182 }
1183 2 return undef;
1184 }
1185  
1186 1 ▶sub offsets_for {
Subroutine offsets_for: called CC=11 SCAR=47.2
1187 1 my ($self, $topic, $cb) = @_;
1188 1 my $cfg = $self->{cfg};
1189 1 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 0 1
1190  
1191 0 my $np = $self->_num_partitions($topic);
1192 0 ▶ return $cb->({}) if $cb && !$np;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and not $np 0 0 0
Condition0%0/3
$cb and not $np
!ll&&!rl&&r
000
MC/DC0%0/2
$cb and not $np
$cb not $np
Truth table0%0/3
A and not(B)
A= $cbB= not $np
ABresult
0X0
100
111
1193  
1194 0 my $result = {};
1195 0 my $remaining = $np;
1196 0 my $first_err;
1197 0 for my $p (0..$np-1) {
1198 0 my $pid = $p;
1199 0 my $leader_id = $self->_get_leader($topic, $pid);
1200 0 ▶ my $conn = defined($leader_id) ? $self->_get_or_create_conn($leader_id) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $leader_id ? : 0 0 0
1201 0 ▶ unless ($conn && $conn->connected) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($conn and $conn->connected) 0 0 0
Condition0%0/3
$conn and $conn->connected
!ll&&!rl&&r
000
MC/DC0%0/2
$conn and $conn->connected
$conn $conn->connected
Truth table0%0/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
1202 0 $result->{$pid} = {};
1203 0 ▶ $cb->($result, $first_err) if $cb && --$remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and --$remaining <= 0 0 0 0
Condition0%0/3
$cb and --$remaining <= 0
!ll&&!rl&&r
000
MC/DC0%0/2
$cb and --$remaining <= 0
$cb --$remaining <= 0
Truth table0%0/3
A and B
A= $cbB= --$remaining <= 0
ABresult
0X0
100
111
1204 0 next;
1205 }
1206 0 my %pdata;
1207 0 my $pdone = 0;
1208 0 for my $ts (-2, -1) {
1209 0 ▶ $conn->list_offsets($topic, $pid, $ts, sub {
Subroutine __ANON__: not called CC=10 SCAR=47.0
1210 0 my ($res, $err) = @_;
1211 0 ▶ $first_err //= $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
Condition0%0/3
$first_err //= $err
l!l&&r!l&&!r
000
MC/DC0%0/2
$first_err //= $err
$first_err $err
Truth table0%0/3
A //= B
A= $first_errB= $err
ABresult
1X1
011
000
1212 0 ▶ if (!$err && $res && ref $res->{topics} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $err and $res and ref $res->{"topics"} eq "ARRAY") 0 0 0
Condition0%0/6
not $err and $res and ref $res->{"topics"} eq "ARRAY"
!ll&&!rl&&r
000
not $err and $res
!ll&&!rl&&r
000
MC/DC0%0/3
not $err and $res and ref $res->{"topics"} eq "ARRAY"
not $err $res ref $res->{"topics"} eq "ARRAY"
Truth table0%0/4
not(A) and B and C
A= not $errB= $resC= ref $res->{"topics"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
1213 0 my $off = $res->{topics}[0]{partitions}[0]{offset};
1214 0 ▶ if ($ts == -2) { $pdata{earliest} = $off }
Branch: 1 branch
BranchTrueFalseTotal
if ($ts == -2) { } 0 0 0
1215 0 else { $pdata{latest} = $off }
1216 }
1217 0 ▶ if (++$pdone == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$pdone == 2) 0 0 0
1218 0 $result->{$pid} = \%pdata;
1219 0 ▶ $cb->($result, $first_err) if $cb && --$remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and --$remaining <= 0 0 0 0
Condition0%0/3
$cb and --$remaining <= 0
!ll&&!rl&&r
000
MC/DC0%0/2
$cb and --$remaining <= 0
$cb --$remaining <= 0
Truth table0%0/3
A and B
A= $cbB= --$remaining <= 0
ABresult
0X0
100
111
1220 }
1221 0 });
1222 }
1223 }
1224 }
1225  
1226 1 ▶sub lag {
Subroutine lag: called CC=11 SCAR=47.1
1227 1 my ($self, $cb) = @_;
1228 1 my $cfg = $self->{cfg};
1229 1 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 0 1
1230 0 ▶ my @assignments = @{$cfg->{assignments} // []};
Condition0%0/2
$cfg->{"assignments"} // []
l!l
00
MC/DC0%0/1
$cfg->{"assignments"} // []
$cfg->{"assignments"}
Truth table0%0/2
A
A= $cfg->{"assignments"}
Aresult
11
00
1231 0 ▶ return $cb->({}) if $cb && !@assignments;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and not @assignments 0 0 0
Condition0%0/3
$cb and not @assignments
!ll&&!rl&&r
000
MC/DC0%0/2
$cb and not @assignments
$cb not @assignments
Truth table0%0/3
A and not(B)
A= $cbB= not @assignments
ABresult
0X0
100
111
1232  
1233 0 my $result = {};
1234 0 my $remaining = scalar @assignments;
1235 0 my $first_err;
1236 0 for my $a (@assignments) {
1237 0 my $key = "$a->{topic}:$a->{partition}";
1238 0 my $leader_id = $self->_get_leader($a->{topic}, $a->{partition});
1239 0 ▶ my $conn = defined($leader_id) ? $self->_get_or_create_conn($leader_id) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $leader_id ? : 0 0 0
1240 0 ▶ if ($conn && $conn->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($conn and $conn->connected) { } 0 0 0
Condition0%0/3
$conn and $conn->connected
!ll&&!rl&&r
000
MC/DC0%0/2
$conn and $conn->connected
$conn $conn->connected
Truth table0%0/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
1241 0 ▶ $conn->list_offsets($a->{topic}, $a->{partition}, -1, sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
1242 0 my ($res, $err) = @_;
1243 0 ▶ $first_err //= $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
Condition0%0/3
$first_err //= $err
l!l&&r!l&&!r
000
MC/DC0%0/2
$first_err //= $err
$first_err $err
Truth table0%0/3
A //= B
A= $first_errB= $err
ABresult
1X1
011
000
1244 0 my $hw = 0;
1245 0 ▶ if (!$err && $res && ref $res->{topics} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $err and $res and ref $res->{"topics"} eq "ARRAY") 0 0 0
Condition0%0/6
not $err and $res and ref $res->{"topics"} eq "ARRAY"
!ll&&!rl&&r
000
not $err and $res
!ll&&!rl&&r
000
MC/DC0%0/3
not $err and $res and ref $res->{"topics"} eq "ARRAY"
not $err $res ref $res->{"topics"} eq "ARRAY"
Truth table0%0/4
not(A) and B and C
A= not $errB= $resC= ref $res->{"topics"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
1246 0 ▶ $hw = $res->{topics}[0]{partitions}[0]{offset} // 0;
Condition0%0/2
$res->{"topics"}[0]{"partitions"}[0]{"offset"} // 0
l!l
00
MC/DC0%0/1
$res->{"topics"}[0]{"partitions"}[0]{"offset"} // 0
$res->{"topics"}[0]{"partitions"}[0]{"offset"}
Truth table0%0/2
A
A= $res->{"topics"}[0]{"partitions"}[0]{"offset"}
Aresult
11
00
1247 }
1248 $result->{$key} = {
1249 current => $a->{offset},
1250 latest => $hw,
1251 lag => $hw - $a->{offset},
1252 0 };
1253 0 ▶ $cb->($result, $first_err) if $cb && --$remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and --$remaining <= 0 0 0 0
Condition0%0/3
$cb and --$remaining <= 0
!ll&&!rl&&r
000
MC/DC0%0/2
$cb and --$remaining <= 0
$cb --$remaining <= 0
Truth table0%0/3
A and B
A= $cbB= --$remaining <= 0
ABresult
0X0
100
111
1254 0 });
1255 } else {
1256 0 $result->{$key} = { current => $a->{offset}, latest => 0, lag => 0 };
1257 0 ▶ $cb->($result, $first_err) if $cb && --$remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cb and --$remaining <= 0 0 0 0
Condition0%0/3
$cb and --$remaining <= 0
!ll&&!rl&&r
000
MC/DC0%0/2
$cb and --$remaining <= 0
$cb --$remaining <= 0
Truth table0%0/3
A and B
A= $cbB= --$remaining <= 0
ABresult
0X0
100
111
1258 }
1259 }
1260 }
1261  
1262 2 ▶sub error_name {
Subroutine error_name: called CC=2 SCAR=7.2
1263 2 ▶ shift if ref $_[0]; # allow $kafka->error_name or EV::Kafka::Client::error_name
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] 2 0 2
1264 2 return EV::Kafka::_error_name($_[0]);
1265 }
1266  
1267 # --- Consumer Group ---
1268  
1269 9 ▶sub subscribe {
Subroutine subscribe: called CC=15 SCAR=27.9
1270 9 my ($self, @args) = @_;
1271 9 my @topics;
1272 my %opts;
1273  
1274 # subscribe('topic1', 'topic2', group_id => 'g', ...)
1275 9 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 25 8 33
1276 25 ▶ if ($args[0] =~ /^(group_id|group_instance_id|on_assign|on_revoke|session_timeout|rebalance_timeout|heartbeat_interval|auto_commit|auto_offset_reset)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args[0] =~ /^(group_id|group_instance_id|on_assign|on_revoke|session_timeout|rebalance_timeout|heartbeat_interval|auto_commit|auto_offset_reset)$/) { } 16 9 25
1277 16 my $k = shift @args;
1278 16 ▶ croak "EV::Kafka: subscribe: option '$k' requires a value"
Branch: 1 branch
BranchTrueFalseTotal
unless @args 1 15 16
1279 unless @args;
1280 15 $opts{$k} = shift @args;
1281 } else {
1282 9 push @topics, shift @args;
1283 }
1284 }
1285 8 for my $t (@topics) {
1286 8 ▶ croak "EV::Kafka: subscribe: invalid topic name '$t'"
Branch: 1 branch
BranchTrueFalseTotal
unless $t =~ /^[A-Za-z0-9._-]+$/ 1 7 8
1287 unless $t =~ /^[A-Za-z0-9._-]+$/;
1288 }
1289  
1290 7 my $cfg = $self->{cfg};
1291 7 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 6 7
1292 6 my $group_id = $opts{group_id};
1293 6 ▶ die "group_id required" unless defined $group_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $group_id 0 6 6
1294  
1295 $cfg->{group} = {
1296 group_id => $group_id,
1297 member_id => '',
1298 generation => -1,
1299 topics => \@topics,
1300 on_assign => $opts{on_assign},
1301 on_revoke => $opts{on_revoke},
1302 session_timeout => $opts{session_timeout} // 30000,
1303 rebalance_timeout => $opts{rebalance_timeout} // 60000,
1304 heartbeat_interval => $opts{heartbeat_interval} // 3,
1305 auto_commit => $opts{auto_commit} // 1,
1306 auto_offset_reset => $opts{auto_offset_reset} // 'earliest',
1307 group_instance_id => $opts{group_instance_id},
1308 6 ▶ coordinator => undef,
Condition60%6/10
$opts{"session_timeout"} // 30000
l!l
06
$opts{"rebalance_timeout"} // 60000
l!l
06
$opts{"heartbeat_interval"} // 3
l!l
42
$opts{"auto_commit"} // 1
l!l
06
$opts{"auto_offset_reset"} // "earliest"
l!l
06
MC/DC0%0/1
$opts{"session_timeout"} // 30000
$opts{"session_timeout"}
MC/DC0%0/1
$opts{"rebalance_timeout"} // 60000
$opts{"rebalance_timeout"}
MC/DC100%1/1
$opts{"heartbeat_interval"} // 3
$opts{"heartbeat_interval"}
MC/DC0%0/1
$opts{"auto_commit"} // 1
$opts{"auto_commit"}
MC/DC0%0/1
$opts{"auto_offset_reset"} // "earliest"
$opts{"auto_offset_reset"}
Truth table50%1/2
A
A= $opts{"session_timeout"}
Aresult
11
00
Truth table50%1/2
A
A= $opts{"rebalance_timeout"}
Aresult
11
00
Truth table100%2/2
A
A= $opts{"heartbeat_interval"}
Aresult
11
00
Truth table50%1/2
A
A= $opts{"auto_commit"}
Aresult
11
00
Truth table50%1/2
A
A= $opts{"auto_offset_reset"}
Aresult
11
00
1309 heartbeat_timer => undef,
1310 state => 'init',
1311 };
1312  
1313 # Step 1: ensure we have metadata
1314 6 ▶ unless ($cfg->{meta}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"meta"}) 2 4 6
1315 2 weaken(my $weak = $self);
1316 2 push @{$cfg->{pending_ops}}, {
1317 0 ▶ run => sub { $weak->_group_start if $weak },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
1318 2 };
1319 2 ▶ $self->_refresh_metadata unless $cfg->{meta_pending};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"meta_pending"} 2 0 2
1320 2 return;
1321 }
1322  
1323 4 $self->_group_start;
1324 }
1325  
1326 11 ▶sub _group_start {
Subroutine _group_start: called CC=4 SCAR=17.4
1327 11 my ($self) = @_;
1328 11 my $cfg = $self->{cfg};
1329 11 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 11 11
1330 11 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 11 0 11
1331  
1332 11 my $conn = $self->_any_conn;
1333 11 ▶ return $self->_group_retry('no broker connection for group start')
Branch: 1 branch
BranchTrueFalseTotal
unless $conn 4 7 11
1334 unless $conn;
1335  
1336 7 $g->{state} = 'finding';
1337 7 weaken(my $weak = $self);
1338 7 ▶ $conn->find_coordinator($g->{group_id}, sub {
Subroutine __ANON__: called CC=10 SCAR=34.1
1339 7 my ($res, $err) = @_;
1340 7 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 7 0 7
1341 7 my $cfg = $s->{cfg};
1342 7 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 7 7
1343 7 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 7 0 7
1344 7 ▶ if ($err || $res->{error_code}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err or $res->{"error_code"}) 0 7 7
Condition33%1/3
$err or $res->{"error_code"}
l!l&&r!l&&!r
007
MC/DC0%0/2
$err or $res->{"error_code"}
$err $res->{"error_code"}
Truth table33%1/3
A or B
A= $errB= $res->{"error_code"}
ABresult
1X1
011
000
1345 0 ▶ my $msg = $err || "FindCoordinator error: $res->{error_code}";
Condition0%0/2
$err || "FindCoordinator error: $res->{'error_code'}"
l!l
00
MC/DC0%0/1
$err || "FindCoordinator error: $res->{'error_code'}"
$err
Truth table0%0/2
A
A= $err
Aresult
11
00
1346 0 ▶ $cfg->{on_error}->($msg) if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 0 0 0
1347 # retry after delay
1348 0 ▶ my $t; $t = EV::timer 1, 0, sub { undef $t; $weak->_group_start if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
1349 0 return;
1350 }
1351  
1352 # Store coordinator info and connect
1353 $cfg->{broker_map}{$res->{node_id}} = {
1354 host => $res->{host}, port => $res->{port}
1355 7 };
1356 7 my $coord = $s->_get_or_create_conn($res->{node_id});
1357 7 $g->{coordinator} = $coord;
1358 7 $g->{coordinator_id} = $res->{node_id};
1359  
1360 7 ▶ if ($coord && $coord->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($coord and $coord->connected) { } 7 0 7
Condition33%1/3
$coord and $coord->connected
!ll&&!rl&&r
007
MC/DC0%0/2
$coord and $coord->connected
$coord $coord->connected
Truth table33%1/3
A and B
A= $coordB= $coord->connected
ABresult
0X0
100
111
1361 7 $s->_group_join;
1362 } else {
1363 0 push @{$cfg->{pending_ops}}, {
1364 node_id => $res->{node_id},
1365 0 ▶ run => sub { $weak->_group_join if $weak },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
1366 0 };
1367 }
1368 7 });
1369 }
1370  
1371 # Bounded retry for coordinator request failures (usually a dead
1372 # coordinator conn): re-run discovery via _group_start. After 5 attempts
1373 # stop the group and surface the error. Budget resets at 'stable'.
1374 8 ▶sub _group_retry {
Subroutine _group_retry: called CC=5 SCAR=16.3
1375 8 my ($self, $msg) = @_;
1376 8 my $cfg = $self->{cfg};
1377 8 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 8 8
1378 8 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 8 0 8
1379 8 ▶ if (++$g->{_start_retries} > 5) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$g->{"_start_retries"} > 5) 1 7 8
1380 1 $g->{_start_retries} = 0;
1381 1 $g->{state} = 'stopped';
1382 1 ▶ $cfg->{on_error}->($msg) if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 1 0 1
1383 1 return;
1384 }
1385 7 weaken(my $weak = $self);
1386 7 ▶ my $t; $t = EV::timer 1, 0, sub { undef $t; $weak->_group_start if $weak };
Subroutine __ANON__: called CC=2 SCAR=7.0
Branch: 1 branch
BranchTrueFalseTotal
if $weak 7 0 7
1387 }
1388  
1389 8 ▶sub _group_join {
Subroutine _group_join: called CC=4 SCAR=18.6
1390 8 my ($self) = @_;
1391 8 my $cfg = $self->{cfg};
1392 8 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 8 8
1393 8 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 8 0 8
1394 8 ▶ my $coord = $g->{coordinator} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $coord = $g->{"coordinator"} or return 8 0 8
1395  
1396 8 $g->{state} = 'joining';
1397 8 weaken(my $weak = $self);
1398 $coord->join_group(
1399 $g->{group_id}, $g->{member_id},
1400 8 ▶ $g->{topics}, sub {
Subroutine __ANON__: called CC=19 SCAR=45.0
1401 8 my ($res, $err) = @_;
1402 8 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 8 0 8
1403 8 my $cfg = $s->{cfg};
1404 8 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 8 8
1405 8 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 8 0 8
1406 8 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 4 4 8
1407 4 $s->_group_retry("JoinGroup: $err");
1408 4 return;
1409 }
1410  
1411 4 ▶ if ($res->{error_code} == 15 || $res->{error_code} == 16) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error_code"} == 15 or $res->{"error_code"} == 16) 0 4 4
Condition33%1/3
$res->{"error_code"} == 15 or $res->{"error_code"} == 16
l!l&&r!l&&!r
004
MC/DC0%0/2
$res->{"error_code"} == 15 or $res->{"error_code"} == 16
$res->{"error_code"} == 15 $res->{"error_code"} == 16
Truth table33%1/3
A or B
A= $res->{"error_code"} == 15B= $res->{"error_code"} == 16
ABresult
1X1
011
000
1412 # COORDINATOR_NOT_AVAILABLE / NOT_COORDINATOR — re-discover
1413 0 ▶ my $t; $t = EV::timer 1, 0, sub { undef $t; $weak->_group_start if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
1414 0 return;
1415 }
1416 4 ▶ if ($res->{error_code} == 27) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error_code"} == 27) 0 4 4
1417 # REBALANCE_IN_PROGRESS — retry
1418 0 ▶ my $t; $t = EV::timer 1, 0, sub { undef $t; $weak->_group_join if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
1419 0 return;
1420 }
1421 4 ▶ if ($res->{error_code} == 79) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error_code"} == 79) 0 4 4
1422 # MEMBER_ID_REQUIRED — retry with assigned member_id
1423 0 ▶ $g->{member_id} = $res->{member_id} if $res->{member_id};
Branch: 1 branch
BranchTrueFalseTotal
if $res->{"member_id"} 0 0 0
1424 0 $s->_group_join;
1425 0 return;
1426 }
1427 4 ▶ if ($res->{error_code} == 22 || $res->{error_code} == 25) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error_code"} == 22 or $res->{"error_code"} == 25) 0 4 4
Condition33%1/3
$res->{"error_code"} == 22 or $res->{"error_code"} == 25
l!l&&r!l&&!r
004
MC/DC0%0/2
$res->{"error_code"} == 22 or $res->{"error_code"} == 25
$res->{"error_code"} == 22 $res->{"error_code"} == 25
Truth table33%1/3
A or B
A= $res->{"error_code"} == 22B= $res->{"error_code"} == 25
ABresult
1X1
011
000
1428 # ILLEGAL_GENERATION / UNKNOWN_MEMBER_ID — broker-side
1429 # session expired or generation rolled. Reset state and
1430 # rejoin from scratch.
1431 0 $g->{member_id} = '';
1432 0 $g->{generation} = -1;
1433 0 ▶ my $t; $t = EV::timer 1, 0, sub { undef $t; $weak->_group_start if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
1434 0 return;
1435 }
1436 4 ▶ if ($res->{error_code}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error_code"}) 0 4 4
1437 $cfg->{on_error}->(sprintf "JoinGroup: %s (code %d)",
1438 $s->error_name($res->{error_code}),
1439 0 ▶ $res->{error_code}) if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 0 0 0
1440 0 return;
1441 }
1442  
1443 4 $g->{member_id} = $res->{member_id};
1444 4 $g->{generation} = $res->{generation_id};
1445 my $is_leader = defined($res->{leader}) && defined($res->{member_id})
1446 4 ▶ && $res->{leader} eq $res->{member_id};
Condition33%2/6
defined $res->{'leader'} && defined $res->{'member_id'} && $res->{'leader'} eq $res->{'member_id'}
!ll&&!rl&&r
004
defined $res->{"leader"} and defined $res->{"member_id"}
!ll&&!rl&&r
004
MC/DC0%0/3
defined $res->{'leader'} && defined $res->{'member_id'} && $res->{'leader'} eq $res->{'member_id'}
defined $res->{"leader"} defined $res->{"member_id"} $res->{'leader'} eq $res->{'member_id'}
Truth table25%1/4
A and B && C
A= defined $res->{"leader"}B= defined $res->{"member_id"}C= $res->{'leader'} eq $res->{'member_id'}
ABCresult
0XX0
10X0
1100
1111
1447  
1448 # Build assignments (if leader)
1449 4 my $assignments = [];
1450 4 ▶ if ($is_leader && $res->{members} && @{$res->{members}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_leader and $res->{"members"} and @{$res->{"members"};}) 4 0 4
Condition33%2/6
$is_leader and $res->{"members"} and @{$res->{"members"};}
!ll&&!rl&&r
004
$is_leader and $res->{"members"}
!ll&&!rl&&r
004
MC/DC0%0/3
$is_leader and $res->{"members"} and @{$res->{"members"};}
$is_leader $res->{"members"} @{$res->{"members"};}
Truth table25%1/4
A and B and C
A= $is_leaderB= $res->{"members"}C= @{$res->{"members"};}
ABCresult
0XX0
10X0
1100
1111
1451 4 $assignments = $s->_assign_partitions($res->{members}, $g->{topics});
1452 }
1453  
1454 4 $s->_group_sync($assignments);
1455 },
1456 $g->{session_timeout}, $g->{rebalance_timeout},
1457 $g->{group_instance_id}
1458 8 );
1459 }
1460  
1461 11 ▶sub _assign_partitions {
Subroutine _assign_partitions: called CC=23 SCAR=31.4
1462 11 my ($self, $members, $topics) = @_;
1463 11 my $cfg = $self->{cfg};
1464 11 ▶ my $meta = $cfg->{meta} or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $meta = $cfg->{"meta"} or return [] 11 0 11
1465  
1466 11 my @all_parts;
1467 11 ▶ for my $t (@{$meta->{topics} // []}) {
Condition50%1/2
$meta->{"topics"} // []
l!l
110
MC/DC0%0/1
$meta->{"topics"} // []
$meta->{"topics"}
Truth table50%1/2
A
A= $meta->{"topics"}
Aresult
11
00
1468 15 my $tname = $t->{name};
1469 15 ▶ next unless grep { $_ eq $tname } @$topics;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $tname;} @$topics 0 15 15
1470 15 ▶ for my $p (@{$t->{partitions} // []}) {
Condition50%1/2
$t->{"partitions"} // []
l!l
150
MC/DC0%0/1
$t->{"partitions"} // []
$t->{"partitions"}
Truth table50%1/2
A
A= $t->{"partitions"}
Aresult
11
00
1471 40 push @all_parts, { topic => $tname, partition => $p->{partition} };
1472 }
1473 }
1474 11 ▶ @all_parts = sort { $a->{topic} cmp $b->{topic} || $a->{partition} <=> $b->{partition} } @all_parts;
Condition66%2/3
$EV::Kafka::Client::a->{'topic'} cmp $EV::Kafka::Client::b->{'topic'} || $EV::Kafka::Client::a->{'partition'} <=> $EV::Kafka::Client::b->{'partition'}
l!l&&r!l&&!r
16320
MC/DC0%0/2
$EV::Kafka::Client::a->{'topic'} cmp $EV::Kafka::Client::b->{'topic'} || $EV::Kafka::Client::a->{'partition'} <=> $EV::Kafka::Client::b->{'partition'}
$EV::Kafka::Client::a->{'topic'} cmp $EV::Kafka::Client::b->{'topic'} $EV::Kafka::Client::a->{'partition'} <=> $EV::Kafka::Client::b->{'partition'}
Truth table66%2/3
A || B
A= $EV::Kafka::Client::a->{'topic'} cmp $EV::Kafka::Client::b->{'topic'}B= $EV::Kafka::Client::a->{'partition'} <=> $EV::Kafka::Client::b->{'partition'}
ABresult
1X1
011
000
1475  
1476 11 my @member_ids = sort map { $_->{member_id} } @$members;
1477 11 my $nm = scalar @member_ids;
1478  
1479 # Sticky assignment: preserve previous assignments where possible
1480 11 ▶ my $prev = $cfg->{_prev_assignments} // {};
Condition100%2/2
$cfg->{"_prev_assignments"} // {}
l!l
65
MC/DC100%1/1
$cfg->{"_prev_assignments"} // {}
$cfg->{"_prev_assignments"}
Truth table100%2/2
A
A= $cfg->{"_prev_assignments"}
Aresult
11
00
1481 11 my %member_parts; # member_id => [@parts]
1482 my %assigned; # "topic:partition" => 1
1483  
1484 11 ▶ my $max_per = int(@all_parts / $nm) + ((@all_parts % $nm) ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
@all_parts % $nm ? : 1 10 11
1485  
1486 # Step 1: keep valid previous assignments (but cap at max_per)
1487 11 for my $mid (@member_ids) {
1488 18 $member_parts{$mid} = [];
1489 18 ▶ for my $p (@{$prev->{$mid} // []}) {
Condition100%2/2
$prev->{$mid} // []
l!l
513
MC/DC100%1/1
$prev->{$mid} // []
$prev->{$mid}
Truth table100%2/2
A
A= $prev->{$mid}
Aresult
11
00
1490 11 my $key = "$p->{topic}:$p->{partition}";
1491 11 ▶ if (grep { $_->{topic} eq $p->{topic} && $_->{partition} == $p->{partition} } @all_parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_->{"topic"} eq $p->{"topic"} and $_->{"partition"} == $p->{"partition"};} @all_parts) 11 0 11
Condition100%3/3
$_->{'topic'} eq $p->{'topic'} && $_->{'partition'} == $p->{'partition'}
!ll&&!rl&&r
302011
MC/DC100%2/2
$_->{'topic'} eq $p->{'topic'} && $_->{'partition'} == $p->{'partition'}
$_->{'topic'} eq $p->{'topic'} $_->{'partition'} == $p->{'partition'}
Truth table100%3/3
A && B
A= $_->{'topic'} eq $p->{'topic'}B= $_->{'partition'} == $p->{'partition'}
ABresult
0X0
100
111
1492 11 ▶ if (scalar @{$member_parts{$mid}} < $max_per) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$member_parts{$mid};} < $max_per) 9 2 11
1493 9 push @{$member_parts{$mid}}, $p;
1494 9 $assigned{$key} = 1;
1495 }
1496 }
1497 }
1498 }
1499  
1500 # Step 2: distribute unassigned partitions to least-loaded members
1501 11 my @unassigned = grep { !$assigned{"$_->{topic}:$_->{partition}"} } @all_parts;
1502 11 for my $p (@unassigned) {
1503 31 my $min_mid = $member_ids[0];
1504 31 my $min_count = scalar @{$member_parts{$min_mid}};
1505 31 for my $mid (@member_ids) {
1506 55 ▶ if (scalar @{$member_parts{$mid}} < $min_count) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$member_parts{$mid};} < $min_count) 10 45 55
1507 10 $min_count = scalar @{$member_parts{$mid}};
1508 10 $min_mid = $mid;
1509 }
1510 }
1511 31 push @{$member_parts{$min_mid}}, $p;
1512 }
1513  
1514 # Save for next rebalance
1515 11 $cfg->{_prev_assignments} = { %member_parts };
1516  
1517 # Encode assignments
1518 11 my @assignments;
1519 11 for my $mid (@member_ids) {
1520 18 my %by_topic;
1521 18 for my $p (@{$member_parts{$mid}}) {
1522 40 push @{$by_topic{$p->{topic}}}, $p->{partition};
1523 }
1524  
1525 18 my $buf = '';
1526 18 $buf .= pack('n', 0); # version
1527 18 $buf .= pack('N', scalar keys %by_topic);
1528 18 for my $t (sort keys %by_topic) {
1529 24 $buf .= pack('n', length($t)) . $t;
1530 24 $buf .= pack('N', scalar @{$by_topic{$t}});
1531 24 for my $pid (@{$by_topic{$t}}) {
1532 40 $buf .= pack('N', $pid);
1533 }
1534 }
1535 18 $buf .= pack('N', -1); # user_data = null
1536  
1537 18 push @assignments, {
1538 member_id => $mid,
1539 assignment => $buf,
1540 };
1541 }
1542  
1543 11 return \@assignments;
1544 }
1545  
1546 4 ▶sub _group_sync {
Subroutine _group_sync: called CC=4 SCAR=15.8
1547 4 my ($self, $assignments) = @_;
1548 4 my $cfg = $self->{cfg};
1549 4 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 4 4
1550 4 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 4 0 4
1551 4 ▶ my $coord = $g->{coordinator} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $coord = $g->{"coordinator"} or return 4 0 4
1552  
1553 4 $g->{state} = 'syncing';
1554 4 weaken(my $weak = $self);
1555 4 ▶ my $sync_cb = sub {
Subroutine __ANON__: called CC=20 SCAR=38.3
1556 4 my ($res, $err) = @_;
1557 4 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 4 0 4
1558 4 my $cfg = $s->{cfg};
1559 4 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 4 4
1560 4 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 4 0 4
1561 4 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 4 4
1562 0 $s->_group_retry("SyncGroup: $err");
1563 0 return;
1564 }
1565 4 ▶ if ($res->{error_code} == 27) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error_code"} == 27) 0 4 4
1566 # REBALANCE_IN_PROGRESS — rejoin
1567 0 ▶ my $t; $t = EV::timer 1, 0, sub { undef $t; $weak->_group_join if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
1568 0 return;
1569 }
1570 4 ▶ if ($res->{error_code} == 22 || $res->{error_code} == 25) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error_code"} == 22 or $res->{"error_code"} == 25) 0 4 4
Condition33%1/3
$res->{"error_code"} == 22 or $res->{"error_code"} == 25
l!l&&r!l&&!r
004
MC/DC0%0/2
$res->{"error_code"} == 22 or $res->{"error_code"} == 25
$res->{"error_code"} == 22 $res->{"error_code"} == 25
Truth table33%1/3
A or B
A= $res->{"error_code"} == 22B= $res->{"error_code"} == 25
ABresult
1X1
011
000
1571 # ILLEGAL_GENERATION / UNKNOWN_MEMBER_ID — start over.
1572 0 $g->{member_id} = '';
1573 0 $g->{generation} = -1;
1574 0 ▶ my $t; $t = EV::timer 1, 0, sub { undef $t; $weak->_group_start if $weak };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $weak 0 0 0
1575 0 return;
1576 }
1577 4 ▶ if ($res->{error_code}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"error_code"}) 0 4 4
1578 $cfg->{on_error}->(sprintf "SyncGroup: %s (code %d)",
1579 $s->error_name($res->{error_code}),
1580 0 ▶ $res->{error_code}) if $cfg->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"on_error"} 0 0 0
1581 0 return;
1582 }
1583  
1584 # Decode assignment
1585 4 ▶ my $data = $res->{assignment} // '';
Condition50%1/2
$res->{"assignment"} // ""
l!l
40
MC/DC0%0/1
$res->{"assignment"} // ""
$res->{"assignment"}
Truth table50%1/2
A
A= $res->{"assignment"}
Aresult
11
00
1586 4 my $dlen = length $data;
1587 4 my @my_assignments;
1588 4 ▶ if ($dlen >= 6) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dlen >= 6) 4 0 4
1589 4 my $off = 2; # skip version
1590 4 my $tc = unpack('N', substr($data, $off, 4)); $off += 4;
1591 4 for my $i (0..$tc-1) {
1592 4 ▶ last unless $off + 2 <= $dlen;
Branch: 1 branch
BranchTrueFalseTotal
unless $off + 2 <= $dlen 0 4 4
1593 4 my $tlen = unpack('n', substr($data, $off, 2)); $off += 2;
1594 4 ▶ last unless $off + $tlen <= $dlen;
Branch: 1 branch
BranchTrueFalseTotal
unless $off + $tlen <= $dlen 0 4 4
1595 4 my $tname = substr($data, $off, $tlen); $off += $tlen;
1596 4 ▶ last unless $off + 4 <= $dlen;
Branch: 1 branch
BranchTrueFalseTotal
unless $off + 4 <= $dlen 0 4 4
1597 4 my $pc = unpack('N', substr($data, $off, 4)); $off += 4;
1598 4 for my $j (0..$pc-1) {
1599 4 ▶ last unless $off + 4 <= $dlen;
Branch: 1 branch
BranchTrueFalseTotal
unless $off + 4 <= $dlen 0 4 4
1600 4 my $pid = unpack('N', substr($data, $off, 4)); $off += 4;
1601 4 ▶ my $reset = ($g->{auto_offset_reset} // 'earliest') eq 'latest' ? -1 : -2;
Branch: 1 branch
BranchTrueFalseTotal
($g->{'auto_offset_reset'} // 'earliest') eq 'latest' ? : 0 4 4
Condition50%1/2
$g->{"auto_offset_reset"} // "earliest"
l!l
40
MC/DC0%0/1
$g->{"auto_offset_reset"} // "earliest"
$g->{"auto_offset_reset"}
Truth table50%1/2
A
A= $g->{"auto_offset_reset"}
Aresult
11
00
1602 4 push @my_assignments, {
1603 topic => $tname, partition => $pid, offset => $reset
1604 };
1605 }
1606 }
1607 }
1608  
1609 4 $g->{state} = 'stable';
1610 4 $g->{_start_retries} = 0; # join/sync retry budget resets
1611  
1612 # Fetch committed offsets, then start consuming
1613 4 ▶ $s->_fetch_committed_offsets(\@my_assignments, sub {
Subroutine __ANON__: called CC=5 SCAR=16.7
1614 4 ▶ my $s2 = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s2 = $weak or return 4 0 4
1615 4 my $cfg = $s2->{cfg};
1616 4 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 4 4
1617 4 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 4 0 4
1618 4 $cfg->{assignments} = \@my_assignments;
1619 4 $cfg->{_fetch_err_seen} = {}; # rebalance: fresh error budget
1620  
1621 # Fire on_assign
1622 4 ▶ $g->{on_assign}->(\@my_assignments) if $g->{on_assign};
Branch: 1 branch
BranchTrueFalseTotal
if $g->{"on_assign"} 4 0 4
1623  
1624 # Start heartbeat
1625 4 $s2->_start_heartbeat;
1626  
1627 # Start fetch loop
1628 4 $s2->_start_fetch_loop;
1629 4 });
1630 4 };
1631 $coord->sync_group(
1632 $g->{group_id}, $g->{generation}, $g->{member_id},
1633 $assignments, $sync_cb, $g->{group_instance_id}
1634 4 );
1635 }
1636  
1637 4 ▶sub _fetch_committed_offsets {
Subroutine _fetch_committed_offsets: called CC=8 SCAR=23.2
1638 4 my ($self, $assignments, $cb) = @_;
1639 4 my $cfg = $self->{cfg};
1640 4 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 4 4
1641 4 ▶ my $g = $cfg->{group} or return $cb->();
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return &$cb() 4 0 4
1642 4 my $coord = $g->{coordinator};
1643 4 ▶ return $cb->() unless $coord && $coord->connected && @$assignments;
Branch: 1 branch
BranchTrueFalseTotal
unless $coord and $coord->connected and @$assignments 0 4 4
Condition33%2/6
$coord and $coord->connected and @$assignments
!ll&&!rl&&r
004
$coord and $coord->connected
!ll&&!rl&&r
004
MC/DC0%0/3
$coord and $coord->connected and @$assignments
$coord $coord->connected @$assignments
Truth table25%1/4
A and B and C
A= $coordB= $coord->connectedC= @$assignments
ABCresult
0XX0
10X0
1100
1111
1644  
1645 # Build topics array for offset_fetch
1646 4 my %by_topic;
1647 4 for my $a (@$assignments) {
1648 4 push @{$by_topic{$a->{topic}}}, $a->{partition};
1649 }
1650 4 my @topics;
1651 4 for my $t (sort keys %by_topic) {
1652 4 push @topics, { topic => $t, partitions => $by_topic{$t} };
1653 }
1654  
1655 4 weaken(my $weak = $self);
1656 4 ▶ $coord->offset_fetch($g->{group_id}, \@topics, sub {
Subroutine __ANON__: called CC=20 SCAR=36.0
1657 4 my ($res, $err) = @_;
1658 4 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 4 0 4
1659 4 my $cfg = $s->{cfg};
1660 4 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 4 4
1661 4 ▶ if (!$err && $res && ref $res->{topics} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $err and $res and ref $res->{"topics"} eq "ARRAY") 4 0 4
Condition33%2/6
not $err and $res and ref $res->{"topics"} eq "ARRAY"
!ll&&!rl&&r
004
not $err and $res
!ll&&!rl&&r
004
MC/DC0%0/3
not $err and $res and ref $res->{"topics"} eq "ARRAY"
not $err $res ref $res->{"topics"} eq "ARRAY"
Truth table25%1/4
not(A) and B and C
A= not $errB= $resC= ref $res->{"topics"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
1662 4 for my $t (@{$res->{topics}}) {
1663 4 ▶ for my $p (@{$t->{partitions} // []}) {
Condition50%1/2
$t->{"partitions"} // []
l!l
40
MC/DC0%0/1
$t->{"partitions"} // []
$t->{"partitions"}
Truth table50%1/2
A
A= $t->{"partitions"}
Aresult
11
00
1664 4 ▶ next if $p->{error_code};
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"error_code"} 0 4 4
1665 4 ▶ next if $p->{offset} < 0; # no committed offset
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"offset"} < 0 1 3 4
1666 3 for my $a (@$assignments) {
1667 3 ▶ if ($a->{topic} eq $t->{topic} && $a->{partition} == $p->{partition}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a->{"topic"} eq $t->{"topic"} and $a->{"partition"} == $p->{"partition"}) 3 0 3
Condition33%1/3
$a->{"topic"} eq $t->{"topic"} and $a->{"partition"} == $p->{"partition"}
!ll&&!rl&&r
003
MC/DC0%0/2
$a->{"topic"} eq $t->{"topic"} and $a->{"partition"} == $p->{"partition"}
$a->{"topic"} eq $t->{"topic"} $a->{"partition"} == $p->{"partition"}
Truth table33%1/3
A and B
A= $a->{"topic"} eq $t->{"topic"}B= $a->{"partition"} == $p->{"partition"}
ABresult
0X0
100
111
1668 3 $a->{offset} = $p->{offset};
1669 }
1670 }
1671 }
1672 }
1673 }
1674  
1675 # For partitions with unresolved offset (-2=earliest, -1=latest), resolve via ListOffsets
1676 4 my @need_offsets = grep { $_->{offset} < 0 } @$assignments;
1677 4 ▶ if (@need_offsets) {
Branch: 1 branch
BranchTrueFalseTotal
if (@need_offsets) { } 1 3 4
1678 1 my $remaining = scalar @need_offsets;
1679 1 for my $a (@need_offsets) {
1680 1 my $leader_id = $s->_get_leader($a->{topic}, $a->{partition});
1681 1 ▶ my $lconn = defined($leader_id) ? $s->_get_or_create_conn($leader_id) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $leader_id ? : 1 0 1
1682 1 ▶ if ($lconn && $lconn->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lconn and $lconn->connected) { } 1 0 1
Condition33%1/3
$lconn and $lconn->connected
!ll&&!rl&&r
001
MC/DC0%0/2
$lconn and $lconn->connected
$lconn $lconn->connected
Truth table33%1/3
A and B
A= $lconnB= $lconn->connected
ABresult
0X0
100
111
1683 1 ▶ $lconn->list_offsets($a->{topic}, $a->{partition}, $a->{offset}, sub {
Subroutine __ANON__: called CC=9 SCAR=25.2
1684 1 my ($lres, $lerr) = @_;
1685 1 ▶ if (!$lerr && $lres && ref $lres->{topics} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $lerr and $lres and ref $lres->{"topics"} eq "ARRAY") 1 0 1
Condition33%2/6
not $lerr and $lres and ref $lres->{"topics"} eq "ARRAY"
!ll&&!rl&&r
001
not $lerr and $lres
!ll&&!rl&&r
001
MC/DC0%0/3
not $lerr and $lres and ref $lres->{"topics"} eq "ARRAY"
not $lerr $lres ref $lres->{"topics"} eq "ARRAY"
Truth table25%1/4
not(A) and B and C
A= not $lerrB= $lresC= ref $lres->{"topics"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
1686 1 for my $lt (@{$lres->{topics}}) {
1687 1 ▶ for my $lp (@{$lt->{partitions} // []}) {
Condition50%1/2
$lt->{"partitions"} // []
l!l
10
MC/DC0%0/1
$lt->{"partitions"} // []
$lt->{"partitions"}
Truth table50%1/2
A
A= $lt->{"partitions"}
Aresult
11
00
1688 1 ▶ $a->{offset} = $lp->{offset} if !$lp->{error_code};
Branch: 1 branch
BranchTrueFalseTotal
unless $lp->{"error_code"} 1 0 1
1689 }
1690 }
1691 }
1692 1 $remaining--;
1693 1 ▶ $cb->() if $remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining <= 0 1 0 1
1694 1 });
1695 } else {
1696 0 $a->{offset} = 0;
1697 0 $remaining--;
1698 0 ▶ $cb->() if $remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining <= 0 0 0 0
1699 }
1700 }
1701 } else {
1702 3 $cb->();
1703 }
1704 4 });
1705 }
1706  
1707 4 ▶sub _start_heartbeat {
Subroutine _start_heartbeat: called CC=3 SCAR=13.6
1708 4 my ($self) = @_;
1709 4 my $cfg = $self->{cfg};
1710 4 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 4 4
1711 4 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 4 0 4
1712  
1713 # Weak $self only; group state is re-derived per tick, so a stale
1714 # group after re-subscribe is never acted on.
1715 4 weaken(my $weak = $self);
1716 1 ▶ $g->{heartbeat_timer} = EV::timer $g->{heartbeat_interval}, $g->{heartbeat_interval}, sub {
Subroutine __ANON__: called CC=7 SCAR=25.7
1717 1 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 1 0 1
1718 1 my $cfg = $s->{cfg};
1719 1 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 1 1
1720 1 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 1 0 1
1721 1 ▶ return unless $g->{state} eq 'stable';
Branch: 1 branch
BranchTrueFalseTotal
unless $g->{"state"} eq "stable" 0 1 1
1722 1 my $coord = $g->{coordinator};
1723 1 ▶ return unless $coord && $coord->connected;
Branch: 1 branch
BranchTrueFalseTotal
unless $coord and $coord->connected 0 1 1
Condition33%1/3
$coord and $coord->connected
!ll&&!rl&&r
001
MC/DC0%0/2
$coord and $coord->connected
$coord $coord->connected
Truth table33%1/3
A and B
A= $coordB= $coord->connected
ABresult
0X0
100
111
1724  
1725 1 ▶ $coord->heartbeat($g->{group_id}, $g->{generation}, $g->{member_id}, sub {
Subroutine __ANON__: called CC=13 SCAR=37.9
1726 1 my ($res, $err) = @_;
1727 1 ▶ my $s = $weak or return;
Branch: 1 branch
BranchTrueFalseTotal
my $s = $weak or return 1 0 1
1728 1 my $cfg = $s->{cfg};
1729 1 ▶ return if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 0 1 1
1730 1 ▶ my $g = $cfg->{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $cfg->{"group"} or return 1 0 1
1731 1 ▶ if ($err) { return }
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 1 1
1732 1 ▶ return unless $res;
Branch: 1 branch
BranchTrueFalseTotal
unless $res 0 1 1
1733 1 ▶ my $ec = $res->{error_code} // 0;
Condition50%1/2
$res->{"error_code"} // 0
l!l
10
MC/DC0%0/1
$res->{"error_code"} // 0
$res->{"error_code"}
Truth table50%1/2
A
A= $res->{"error_code"}
Aresult
11
00
1734 1 ▶ if ($ec == 27) {
Branch: 3 branches
BranchTrueFalseTotal
if ($ec == 27) { } 1 0 1
elsif ($ec == 22 or $ec == 25) { } 0 0 0
elsif ($ec == 15 or $ec == 16) { } 0 0 0
1735 # REBALANCE_IN_PROGRESS
1736 1 $g->{state} = 'rebalancing';
1737 1 ▶ $g->{on_revoke}->($cfg->{assignments}) if $g->{on_revoke};
Branch: 1 branch
BranchTrueFalseTotal
if $g->{"on_revoke"} 0 1 1
1738 1 $s->_stop_heartbeat;
1739 1 $s->_stop_fetch_loop;
1740 1 $s->_group_join;
1741 ▶ } elsif ($ec == 22 || $ec == 25) {
Condition0%0/3
$ec == 22 or $ec == 25
l!l&&r!l&&!r
000
MC/DC0%0/2
$ec == 22 or $ec == 25
$ec == 22 $ec == 25
Truth table0%0/3
A or B
A= $ec == 22B= $ec == 25
ABresult
1X1
011
000
1742 # ILLEGAL_GENERATION / UNKNOWN_MEMBER_ID — start over.
1743 0 $g->{state} = 'rebalancing';
1744 0 $g->{member_id} = '';
1745 0 $g->{generation} = -1;
1746 0 $s->_stop_heartbeat;
1747 0 $s->_stop_fetch_loop;
1748 0 $s->_group_start;
1749 ▶ } elsif ($ec == 15 || $ec == 16) {
Condition0%0/3
$ec == 15 or $ec == 16
l!l&&r!l&&!r
000
MC/DC0%0/2
$ec == 15 or $ec == 16
$ec == 15 $ec == 16
Truth table0%0/3
A or B
A= $ec == 15B= $ec == 16
ABresult
1X1
011
000
1750 # Coordinator moved — re-discover. Stop the fetch loop
1751 # too: assignments are stale until the new coordinator
1752 # confirms generation.
1753 0 $g->{state} = 'rebalancing';
1754 0 $s->_stop_heartbeat;
1755 0 $s->_stop_fetch_loop;
1756 0 $s->_group_start;
1757 }
1758 1 }, $g->{group_instance_id});
1759 4 };
1760 }
1761  
1762 56 ▶sub _stop_heartbeat {
Subroutine _stop_heartbeat: called CC=2 SCAR=6.9
1763 56 my ($self) = @_;
1764 56 ▶ my $g = $self->{cfg}{group} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $g = $self->{"cfg"}{"group"} or return 7 49 56
1765 7 undef $g->{heartbeat_timer};
1766 }
1767  
1768 4 ▶sub _start_fetch_loop {
Subroutine _start_fetch_loop: called CC=3 SCAR=11.4
1769 4 my ($self) = @_;
1770 4 my $cfg = $self->{cfg};
1771 4 ▶ return if $cfg->{closed} || $cfg->{fetch_active};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} or $cfg->{"fetch_active"} 0 4 4
Condition33%1/3
$cfg->{"closed"} or $cfg->{"fetch_active"}
l!l&&r!l&&!r
004
MC/DC0%0/2
$cfg->{"closed"} or $cfg->{"fetch_active"}
$cfg->{"closed"} $cfg->{"fetch_active"}
Truth table33%1/3
A or B
A= $cfg->{"closed"}B= $cfg->{"fetch_active"}
ABresult
1X1
011
000
1772 4 $cfg->{fetch_active} = 1;
1773 # Generation-tagged in-flight flag: a completion from a previous
1774 # loop instance must not clear THIS loop's flag.
1775 4 my $gen = ++$cfg->{_fetch_gen};
1776 4 $cfg->{_fetch_in_flight} = 0;
1777  
1778 4 weaken(my $weak = $self);
1779 20 ▶ $cfg->{fetch_timer} = EV::timer 0, 0.1, sub {
Subroutine __ANON__: called CC=4 SCAR=14.5
1780 20 ▶ return unless $weak && $cfg->{fetch_active};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak and $cfg->{"fetch_active"} 0 20 20
Condition33%1/3
$weak and $cfg->{"fetch_active"}
!ll&&!rl&&r
0020
MC/DC0%0/2
$weak and $cfg->{"fetch_active"}
$weak $cfg->{"fetch_active"}
Truth table33%1/3
A and B
A= $weakB= $cfg->{"fetch_active"}
ABresult
0X0
100
111
1781 # skip ticks while a prior poll round is still in flight
1782 20 ▶ return if $cfg->{_fetch_in_flight};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"_fetch_in_flight"} 15 5 20
1783 5 $cfg->{_fetch_in_flight} = $gen;
1784 5 ▶ $weak->poll(sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
1785 $cfg->{_fetch_in_flight} = 0
1786 5 ▶ if ($cfg->{_fetch_in_flight} // 0) == $gen;
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"_fetch_in_flight"} // 0) == $gen 3 2 5
Condition50%1/2
$cfg->{"_fetch_in_flight"} // 0
l!l
50
MC/DC0%0/1
$cfg->{"_fetch_in_flight"} // 0
$cfg->{"_fetch_in_flight"}
Truth table50%1/2
A
A= $cfg->{"_fetch_in_flight"}
Aresult
11
00
1787 5 });
1788 4 };
1789 }
1790  
1791 56 ▶sub _stop_fetch_loop {
Subroutine _stop_fetch_loop: called CC=1 SCAR=0.0
1792 56 my ($self) = @_;
1793 56 my $cfg = $self->{cfg};
1794 56 $cfg->{fetch_active} = 0;
1795 56 $cfg->{_fetch_gen}++; # invalidate completions from the stopped loop
1796 56 $cfg->{_fetch_in_flight} = 0;
1797 56 undef $cfg->{fetch_timer};
1798 }
1799  
1800 3 ▶sub commit {
Subroutine commit: called CC=12 SCAR=31.0
1801 3 my ($self, $cb) = @_;
1802 3 my $cfg = $self->{cfg};
1803 3 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 2 3
1804 2 my $g = $cfg->{group};
1805 2 ▶ unless ($g) { $cb->() if $cb; return }
Branch: 2 branches
BranchTrueFalseTotal
unless ($g) 0 2 2
if $cb 0 0 0
1806 2 my $coord = $g->{coordinator};
1807 2 ▶ unless ($coord && $coord->connected) { $cb->() if $cb; return }
Branch: 2 branches
BranchTrueFalseTotal
unless ($coord and $coord->connected) 0 2 2
if $cb 0 0 0
Condition33%1/3
$coord and $coord->connected
!ll&&!rl&&r
002
MC/DC0%0/2
$coord and $coord->connected
$coord $coord->connected
Truth table33%1/3
A and B
A= $coordB= $coord->connected
ABresult
0X0
100
111
1808  
1809 # Build offset commit data from current assignments
1810 2 my %by_topic;
1811 2 ▶ for my $a (@{$cfg->{assignments} // []}) {
Condition50%1/2
$cfg->{"assignments"} // []
l!l
20
MC/DC0%0/1
$cfg->{"assignments"} // []
$cfg->{"assignments"}
Truth table50%1/2
A
A= $cfg->{"assignments"}
Aresult
11
00
1812 2 push @{$by_topic{$a->{topic}}}, {
1813 partition => $a->{partition},
1814 offset => $a->{offset},
1815 2 };
1816 }
1817  
1818 2 my @topics;
1819 2 for my $t (sort keys %by_topic) {
1820 2 push @topics, { topic => $t, partitions => $by_topic{$t} };
1821 }
1822  
1823 2 ▶ if (!@topics) { $cb->() if $cb; return }
Branch: 2 branches
BranchTrueFalseTotal
unless (@topics) 0 2 2
if $cb 0 0 0
1824  
1825 2 ▶ $coord->offset_commit($g->{group_id}, $g->{generation}, $g->{member_id}, \@topics, sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
1826 2 my ($res, $err) = @_;
1827 2 ▶ $cb->($err) if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 2 0 2
1828 2 });
1829 }
1830  
1831 2 ▶sub unsubscribe {
Subroutine unsubscribe: called CC=4 SCAR=16.4
1832 2 my ($self, $cb) = @_;
1833 2 my $cfg = $self->{cfg};
1834 2 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 1 2
1835 1 my $g = $cfg->{group};
1836  
1837 1 $self->_stop_heartbeat;
1838 1 $self->_stop_fetch_loop;
1839  
1840 1 ▶ my $finish = sub {
Subroutine __ANON__: called CC=6 SCAR=25.3
1841 # send LeaveGroup to coordinator for fast rebalance
1842 1 ▶ if ($g && $g->{coordinator} && $g->{coordinator}->connected && $g->{member_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($g and $g->{'coordinator'} and $g->{'coordinator'}->connected and $g->{'member_id'}) { } 1 0 1
Condition33%3/9
$g and $g->{"coordinator"} and $g->{"coordinator"}->connected and $g->{"member_id"}
!ll&&!rl&&r
001
$g and $g->{"coordinator"} and $g->{"coordinator"}->connected
!ll&&!rl&&r
001
$g and $g->{"coordinator"}
!ll&&!rl&&r
001
MC/DC0%0/4
$g and $g->{"coordinator"} and $g->{"coordinator"}->connected and $g->{"member_id"}
$g $g->{"coordinator"} $g->{"coordinator"}->connected $g->{"member_id"}
Truth table20%1/5
A and B and C and D
A= $gB= $g->{"coordinator"}C= $g->{"coordinator"}->connectedD= $g->{"member_id"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1843 1 ▶ $g->{coordinator}->leave_group($g->{group_id}, $g->{member_id}, sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
1844 1 $cfg->{assignments} = [];
1845 1 $cfg->{group} = undef;
1846 1 ▶ $cb->() if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
1847 1 });
1848 } else {
1849 0 $cfg->{assignments} = [];
1850 0 $cfg->{group} = undef;
1851 0 ▶ $cb->() if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 0 0 0
1852 }
1853 1 };
1854  
1855 1 ▶ if ($g && $g->{auto_commit}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($g and $g->{'auto_commit'}) { } 1 0 1
Condition33%1/3
$g and $g->{"auto_commit"}
!ll&&!rl&&r
001
MC/DC0%0/2
$g and $g->{"auto_commit"}
$g $g->{"auto_commit"}
Truth table33%1/3
A and B
A= $gB= $g->{"auto_commit"}
ABresult
0X0
100
111
1856 1 ▶ $self->commit(sub { $finish->() });
Subroutine __ANON__: called CC=1 SCAR=0.0
1857 } else {
1858 0 $finish->();
1859 }
1860 }
1861  
1862 # --- Transactions ---
1863  
1864 4 ▶sub begin_transaction {
Subroutine begin_transaction: called CC=6 SCAR=18.8
1865 4 my ($self) = @_;
1866 4 my $cfg = $self->{cfg};
1867 4 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 3 4
1868 3 ▶ die "transactional_id required" unless $cfg->{transactional_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"transactional_id"} 0 3 3
1869 3 ▶ die "EV::Kafka: $1" if $cfg->{_pid} =~ /^failed:(.*)/;
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"_pid"} =~ /^failed:(.*)/ 0 3 3
1870 3 ▶ die "producer_id not initialized" unless defined $cfg->{producer_id} && $cfg->{producer_id} >= 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cfg->{"producer_id"} and $cfg->{"producer_id"} >= 0 0 3 3
Condition33%1/3
defined $cfg->{"producer_id"} and $cfg->{"producer_id"} >= 0
!ll&&!rl&&r
003
MC/DC0%0/2
defined $cfg->{"producer_id"} and $cfg->{"producer_id"} >= 0
defined $cfg->{"producer_id"} $cfg->{"producer_id"} >= 0
Truth table33%1/3
A and B
A= defined $cfg->{"producer_id"}B= $cfg->{"producer_id"} >= 0
ABresult
0X0
100
111
1871 3 $cfg->{_txn_active} = 1;
1872 3 $cfg->{_txn_gen}++;
1873 3 $cfg->{_txn_partitions} = {}; # "topic:partition" => 1
1874 }
1875  
1876 7 ▶sub _txn_conn {
Subroutine _txn_conn: called CC=3 SCAR=12.7
1877 7 my ($self) = @_;
1878 7 my $cfg = $self->{cfg};
1879 7 my $conn = $cfg->{_txn_coordinator};
1880 7 ▶ return $conn if $conn && $conn->connected;
Branch: 1 branch
BranchTrueFalseTotal
if $conn and $conn->connected 7 0 7
Condition33%1/3
$conn and $conn->connected
!ll&&!rl&&r
007
MC/DC0%0/2
$conn and $conn->connected
$conn $conn->connected
Truth table33%1/3
A and B
A= $connB= $conn->connected
ABresult
0X0
100
111
1881 0 return $self->_any_conn;
1882 }
1883  
1884 3 ▶sub _add_txn_partition {
Subroutine _add_txn_partition: called CC=4 SCAR=14.2
1885 3 my ($self, $topic, $partition) = @_;
1886 3 my $cfg = $self->{cfg};
1887 3 ▶ return unless $cfg->{_txn_active};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"_txn_active"} 0 3 3
1888 3 my $key = "$topic:$partition";
1889 3 ▶ return if $cfg->{_txn_partitions}{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"_txn_partitions"}{$key}++ 0 3 3
1890  
1891 3 my $conn = $self->_txn_conn;
1892 3 ▶ return unless $conn;
Branch: 1 branch
BranchTrueFalseTotal
unless $conn 0 3 3
1893  
1894 $conn->add_partitions_to_txn(
1895 $cfg->{transactional_id}, $cfg->{producer_id},
1896 $cfg->{producer_epoch},
1897 [{ topic => $topic, partitions => [$partition] }],
1898 3 ▶ sub {}
Subroutine __ANON__: called CC=1 SCAR=0.0
1899 3 );
1900 }
1901  
1902 3 ▶sub commit_transaction {
Subroutine commit_transaction: called CC=3 SCAR=12.3
1903 3 my ($self, $cb) = @_;
1904 3 my $cfg = $self->{cfg};
1905 3 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 2 3
1906 2 ▶ die "no active transaction" unless $cfg->{_txn_active};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"_txn_active"} 0 2 2
1907  
1908 # flush all pending batches first
1909 2 ▶ $self->flush(sub {
Subroutine __ANON__: called CC=6 SCAR=22.1
1910 2 my ($err) = @_;
1911 2 ▶ my $s = $self or return; # torn down during global destruction
Branch: 1 branch
BranchTrueFalseTotal
my $s = $self or return 2 0 2
1912 2 ▶ if ($err) { $cb->(undef, $err) if $cb; return }
Branch: 2 branches
BranchTrueFalseTotal
if ($err) 0 2 2
if $cb 0 0 0
1913 2 my $conn = $s->_txn_conn;
1914 2 ▶ unless ($conn) { $cb->(undef) if $cb; return }
Branch: 2 branches
BranchTrueFalseTotal
unless ($conn) 0 2 2
if $cb 0 0 0
1915  
1916 $conn->end_txn($cfg->{transactional_id}, $cfg->{producer_id},
1917 2 ▶ $cfg->{producer_epoch}, 1, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1918 2 my ($res, $err) = @_;
1919 2 $cfg->{_txn_active} = 0;
1920 2 $cfg->{_txn_gen}++;
1921 2 $cfg->{_txn_partitions} = {};
1922 2 ▶ $cb->($res, $err) if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 2 0 2
1923 2 });
1924 2 });
1925 }
1926  
1927 2 ▶sub send_offsets_to_transaction {
Subroutine send_offsets_to_transaction: called CC=14 SCAR=31.4
1928 2 my ($self, $group_id, $cb) = @_;
1929 2 my $cfg = $self->{cfg};
1930 2 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 1 2
1931 1 ▶ die "no active transaction" unless $cfg->{_txn_active};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"_txn_active"} 0 1 1
1932 1 ▶ die "transactional_id required" unless $cfg->{transactional_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"transactional_id"} 0 1 1
1933  
1934 # gather current consumer offsets
1935 1 my %by_topic;
1936 1 ▶ for my $a (@{$cfg->{assignments} // []}) {
Condition50%1/2
$cfg->{"assignments"} // []
l!l
10
MC/DC0%0/1
$cfg->{"assignments"} // []
$cfg->{"assignments"}
Truth table50%1/2
A
A= $cfg->{"assignments"}
Aresult
11
00
1937 1 push @{$by_topic{$a->{topic}}}, {
1938 partition => $a->{partition},
1939 offset => $a->{offset},
1940 1 };
1941 }
1942  
1943 1 my @topics;
1944 1 for my $t (sort keys %by_topic) {
1945 1 push @topics, { topic => $t, partitions => $by_topic{$t} };
1946 }
1947  
1948 1 ▶ unless (@topics) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@topics) 0 1 1
1949 0 ▶ $cb->() if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 0 0 0
1950 0 return;
1951 }
1952  
1953 1 my $conn = $self->_txn_conn;
1954 1 ▶ unless ($conn) { $cb->() if $cb; return }
Branch: 2 branches
BranchTrueFalseTotal
unless ($conn) 0 1 1
if $cb 0 0 0
1955  
1956 1 my $g = $cfg->{group};
1957 1 ▶ my $generation = $g ? $g->{generation} : -1;
Branch: 1 branch
BranchTrueFalseTotal
$g ? : 0 1 1
1958 1 ▶ my $member_id = $g ? ($g->{member_id} // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
$g ? : 0 1 1
Condition0%0/2
$g->{"member_id"} // ""
l!l
00
MC/DC0%0/1
$g->{"member_id"} // ""
$g->{"member_id"}
Truth table0%0/2
A
A= $g->{"member_id"}
Aresult
11
00
1959  
1960 $conn->txn_offset_commit(
1961 $cfg->{transactional_id}, $group_id,
1962 $cfg->{producer_id}, $cfg->{producer_epoch},
1963 $generation, $member_id,
1964 1 ▶ \@topics, sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
1965 1 my ($res, $err) = @_;
1966 1 ▶ $cb->($res, $err) if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
1967 }
1968 1 );
1969 }
1970  
1971 2 ▶sub abort_transaction {
Subroutine abort_transaction: called CC=7 SCAR=20.3
1972 2 my ($self, $cb) = @_;
1973 2 my $cfg = $self->{cfg};
1974 2 ▶ croak "EV::Kafka: client is closed" if $cfg->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"closed"} 1 1 2
1975 1 ▶ die "no active transaction" unless $cfg->{_txn_active};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"_txn_active"} 0 1 1
1976  
1977 # discard unsent batches — they must not reach the broker after abort
1978 1 $cfg->{batches} = {};
1979 1 undef $cfg->{_linger_timer};
1980 1 $cfg->{_linger_active} = 0;
1981 # Invalidate requeue decisions by in-flight batches: a late 45/46/47
1982 # response must not resurrect an aborted batch.
1983 1 $cfg->{_txn_gen}++;
1984 # Clear per-partition idempotent state; late in-flight responses run
1985 # their callbacks but must not block produce after begin_transaction.
1986 1 $cfg->{_inflight} = {};
1987 1 $cfg->{_batch_retries} = {};
1988 1 $cfg->{_epoch_retries} = {};
1989 # Roll next_sequence back to the acked high-water mark so discarded
1990 # reservations leave no gaps (OutOfOrderSequenceNumber) next txn.
1991 1 for my $bkey (keys %{$cfg->{next_sequence}}) {
1992 1 ▶ $cfg->{next_sequence}{$bkey} = $cfg->{_acked_sequence}{$bkey} // 0;
Condition50%1/2
$cfg->{"_acked_sequence"}{$bkey} // 0
l!l
01
MC/DC0%0/1
$cfg->{"_acked_sequence"}{$bkey} // 0
$cfg->{"_acked_sequence"}{$bkey}
Truth table50%1/2
A
A= $cfg->{"_acked_sequence"}{$bkey}
Aresult
11
00
1993 }
1994  
1995 1 my $conn = $self->_txn_conn;
1996 1 ▶ unless ($conn) { $cb->(undef) if $cb; return }
Branch: 2 branches
BranchTrueFalseTotal
unless ($conn) 0 1 1
if $cb 0 0 0
1997  
1998 $conn->end_txn($cfg->{transactional_id}, $cfg->{producer_id},
1999 1 ▶ $cfg->{producer_epoch}, 0, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
2000 1 my ($res, $err) = @_;
2001 1 $cfg->{_txn_active} = 0;
2002 1 $cfg->{_txn_partitions} = {};
2003 1 ▶ $cb->($res, $err) if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 1 0 1
2004 1 });
2005 }
2006  
2007 62 ▶sub close {
Subroutine close: called CC=24 SCAR=32.1
2008 62 my ($self, $cb) = @_;
2009 62 ▶ my $cfg = $self->{cfg} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cfg = $self->{"cfg"} or return 62 0 62
2010 62 ▶ if ($cfg->{closed}) { $cb->() if $cb; return } # idempotent
Branch: 2 branches
BranchTrueFalseTotal
if ($cfg->{"closed"}) 8 54 62
if $cb 1 7 8
2011 54 $cfg->{closed} = 1;
2012  
2013 # 1. Stop every timer the client may have armed.
2014 54 $self->_stop_heartbeat;
2015 54 $self->_stop_fetch_loop;
2016 54 $self->_disarm_metadata_timer;
2017 54 undef $cfg->{_linger_timer};
2018 54 $cfg->{_linger_active} = 0;
2019 54 undef $cfg->{_flush_timer};
2020  
2021 # 2. Fail every callback the Perl layer still owns. XS fails
2022 # in-flight requests on disconnect (step 3), so each callback
2023 # fires exactly once: unsent here, in-flight there.
2024 54 ▶ for my $bkey (keys %{$cfg->{batches} // {}}) {
Condition50%1/2
$cfg->{"batches"} // {}
l!l
540
MC/DC0%0/1
$cfg->{"batches"} // {}
$cfg->{"batches"}
Truth table50%1/2
A
A= $cfg->{"batches"}
Aresult
11
00
2025 3 ▶ for my $item (@{$cfg->{batches}{$bkey} // []}) {
Condition50%1/2
$cfg->{"batches"}{$bkey} // []
l!l
30
MC/DC0%0/1
$cfg->{"batches"}{$bkey} // []
$cfg->{"batches"}{$bkey}
Truth table50%1/2
A
A= $cfg->{"batches"}{$bkey}
Aresult
11
00
2026 3 ▶ next unless $item->{cb};
Branch: 1 branch
BranchTrueFalseTotal
unless $item->{"cb"} 1 2 3
2027 2 eval { $item->{cb}->(undef, "client closed") };
2028 2 ▶ warn "EV::Kafka: produce callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 2 2
2029 }
2030 }
2031 54 $cfg->{batches} = {};
2032  
2033 54 ▶ for my $op (@{$cfg->{pending_ops} // []}) {
Condition50%1/2
$cfg->{"pending_ops"} // []
l!l
540
MC/DC0%0/1
$cfg->{"pending_ops"} // []
$cfg->{"pending_ops"}
Truth table50%1/2
A
A= $cfg->{"pending_ops"}
Aresult
11
00
2034 8 ▶ next unless $op->{cb};
Branch: 1 branch
BranchTrueFalseTotal
unless $op->{"cb"} 4 4 8
2035 4 eval { $op->{cb}->(undef, "client closed") };
2036 4 ▶ warn "EV::Kafka: pending op callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
2037 }
2038 54 $cfg->{pending_ops} = [];
2039  
2040 54 ▶ if (my $fcb = delete $cfg->{_flush_cb}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fcb = delete $cfg->{"_flush_cb"}) 1 53 54
2041 1 eval { $fcb->("client closed") };
2042 1 ▶ warn "EV::Kafka: flush callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
2043 }
2044 54 ▶ for my $ucb (@{delete $cfg->{_connect_cbs} // []}) {
Condition100%2/2
delete $cfg->{"_connect_cbs"} // []
l!l
153
MC/DC100%1/1
delete $cfg->{"_connect_cbs"} // []
delete $cfg->{"_connect_cbs"}
Truth table100%2/2
A
A= delete $cfg->{"_connect_cbs"}
Aresult
11
00
2045 1 eval { $ucb->(undef, "client closed") };
2046 1 ▶ warn "EV::Kafka: connect callback error: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
2047 }
2048  
2049 # 3. Strip our handlers from every conn, then disconnect (XS fails
2050 # the in-flight requests; cleared handlers can't refire).
2051 54 my %seen;
2052 54 ▶ for my $conn (grep { $_ && !$seen{"$_"}++ }
Condition100%3/3
$_ && !$seen{"$_"}++
!ll&&!rl&&r
773032
MC/DC100%2/2
$_ && !$seen{"$_"}++
$_ !$seen{"$_"}++
Truth table100%3/3
A && not(B)
A= $_B= !$seen{"$_"}++
ABresult
0X0
100
111
2053 54 ▶ values(%{$cfg->{conns} // {}}),
Condition50%1/2
$cfg->{"conns"} // {}
l!l
540
MC/DC0%0/1
$cfg->{"conns"} // {}
$cfg->{"conns"}
Truth table50%1/2
A
A= $cfg->{"conns"}
Aresult
11
00
2054 $cfg->{bootstrap_conn}, $cfg->{_bootstrap_attempt}) {
2055 32 eval { $conn->on_connect(undef) };
2056 32 eval { $conn->on_disconnect(undef) };
2057 32 eval { $conn->on_error(undef) };
2058 32 ▶ eval { $conn->disconnect if $conn->connected };
Branch: 1 branch
BranchTrueFalseTotal
if $conn->connected 30 2 32
2059 }
2060  
2061 # 4. Clear the conn registries (drops the last refs), then group state.
2062 54 $cfg->{conns} = {};
2063 54 $cfg->{bootstrap_conn} = undef;
2064 54 $cfg->{_bootstrap_attempt} = undef;
2065 54 $cfg->{_txn_coordinator} = undef;
2066 54 $cfg->{_conn_state} = {};
2067 54 $cfg->{group} = undef;
2068  
2069 54 ▶ $cb->() if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 0 54 54
2070 }
2071  
2072 54 ▶sub DESTROY {
Subroutine DESTROY: called CC=3 SCAR=12.5
2073 54 my $self = shift;
2074 54 ▶ return unless $self && $self->{cfg};
Branch: 1 branch
BranchTrueFalseTotal
unless $self and $self->{"cfg"} 0 54 54
Condition33%1/3
$self and $self->{"cfg"}
!ll&&!rl&&r
0054
MC/DC0%0/2
$self and $self->{"cfg"}
$self $self->{"cfg"}
Truth table33%1/3
A and B
A= $selfB= $self->{"cfg"}
ABresult
0X0
100
111
2075 54 $self->close;
2076 }
2077  
2078 package EV::Kafka::Conn;
2079  
2080 34 1;
2081  
2082 =head1 NAME
2083  
2084 EV::Kafka - High-performance asynchronous Kafka/Redpanda client using EV
2085  
2086 =head1 SYNOPSIS
2087  
2088 use EV::Kafka;
2089  
2090 my $kafka = EV::Kafka->new(
2091 brokers => '127.0.0.1:9092',
2092 acks => -1,
2093 on_error => sub { warn "kafka: @_" },
2094 on_message => sub {
2095 my ($topic, $partition, $offset, $key, $value, $headers) = @_;
2096 print "$topic:$partition @ $offset $key = $value\n";
2097 },
2098 );
2099  
2100 # Producer
2101 $kafka->connect(sub {
2102 $kafka->produce('my-topic', 'key', 'value', sub {
2103 my ($result, $err) = @_;
2104 my $off = $result->{topics}[0]{partitions}[0]{base_offset};
2105 print "produced at offset $off\n";
2106 });
2107 });
2108  
2109 # Consumer (manual assignment)
2110 $kafka->assign([{ topic => 'my-topic', partition => 0, offset => 0 }]);
2111 my $poll = EV::timer 0, 0.1, sub { $kafka->poll };
2112  
2113 # Consumer group
2114 $kafka->subscribe('my-topic',
2115 group_id => 'my-group',
2116 on_assign => sub { ... },
2117 on_revoke => sub { ... },
2118 );
2119  
2120 EV::run;
2121  
2122 =head1 DESCRIPTION
2123  
2124 EV::Kafka is a high-performance asynchronous Kafka client that implements
2125 the Kafka binary protocol in XS with L<EV> event loop integration. It
2126 targets Redpanda and Apache Kafka (protocol version 0.11+).
2127  
2128 Two-layer architecture:
2129  
2130 =over
2131  
2132 =item * B<EV::Kafka::Conn> (XS) -- single broker TCP connection with
2133 protocol encoding/decoding, correlation ID matching, pipelining,
2134 optional TLS and SASL (PLAIN, SCRAM-SHA-256/512) authentication.
2135  
2136 =item * B<EV::Kafka::Client> (Perl) -- cluster management with metadata
2137 discovery, broker connection pooling, partition leader routing, producer
2138 with key-based partitioning, consumer with manual assignment or consumer
2139 groups.
2140  
2141 =back
2142  
2143 Features:
2144  
2145 =over
2146  
2147 =item * Binary protocol implemented in pure XS (no librdkafka dependency)
2148  
2149 =item * Automatic request pipelining per broker connection
2150  
2151 =item * Metadata-driven partition leader routing
2152  
2153 =item * Producer: acks modes (-1/0/1), key-based partitioning (murmur2),
2154 headers, fire-and-forget (acks=0), idempotent producer with epoch-bump
2155 recovery, transactional / exactly-once stream processing
2156  
2157 =item * Consumer: manual partition assignment, offset tracking, poll-based
2158 message delivery; consumer groups with JoinGroup/SyncGroup/Heartbeat,
2159 sticky partition assignment, offset commit/fetch, automatic rebalancing,
2160 session-expiry recovery
2161  
2162 =item * Compression: lz4, gzip, zstd, snappy (each gated by build-time
2163 library detection)
2164  
2165 =item * TLS (OpenSSL) and SASL/PLAIN, SCRAM-SHA-256/512 (with full
2166 RFC 5802 server-signature verification)
2167  
2168 =item * Automatic reconnection at the connection layer; bootstrap-broker
2169 failover; periodic metadata refresh
2170  
2171 =back
2172  
2173 =head1 CLIENT LIFETIME
2174  
2175 An C<EV::Kafka::Client> is a handle, like an EV watcher: the application
2176 must keep a reference to it for as long as it is in use. When the last
2177 reference is dropped the client tears itself down immediately and
2178 silently, exactly as if C<close()> had been called. This means
2179  
2180 EV::Kafka->new(brokers => ...)->connect(sub { ... });
2181 EV::run;
2182  
2183 does NOT work -- the client is destroyed at the end of the statement and
2184 the connect callback never fires. Keep the object:
2185  
2186 my $kafka = EV::Kafka->new(brokers => ...);
2187 $kafka->connect(sub { ... });
2188 EV::run;
2189  
2190 The callback contract, both for explicit C<close()> and for teardown by
2191 garbage collection:
2192  
2193 =over
2194  
2195 =item * B<No operation callback is ever silently dropped.> Once an
2196 operation accepts a callback it is invoked exactly once. If the client
2197 is closed first, pending callbacks are invoked with an error in their
2198 documented error position: produce callbacks get C<(undef, $err)>,
2199 C<flush>/C<poll> callbacks get C<($err)>, C<connect> and C<seek>
2200 callbacks get C<(undef, $err)>. Requests already sent to a broker are
2201 failed by the connection layer; queued, unsent work is failed by
2202 C<close()> itself.
2203  
2204 =item * B<Event handlers are not operation callbacks.> C<on_message>,
2205 C<on_assign>, C<on_revoke> and C<on_connect> simply stop firing at
2206 close; they are not invoked with an error.
2207  
2208 =item * B<Public methods croak after close.> Calling any operation
2209 method on a closed client dies with C<"EV::Kafka: client is closed">.
2210 C<close()> itself is idempotent.
2211  
2212 =item * C<close()> does not send LeaveGroup; call C<unsubscribe()>
2213 first for a clean consumer-group leave.
2214  
2215 =back
2216  
2217 =head1 RECONNECTION
2218  
2219 Client-managed broker connections reconnect automatically after a loss
2220 (bootstrap-broker failover at C<connect()> time; C<auto_reconnect> with a
2221 1s delay on every pooled connection afterwards). Operations queued while
2222 a broker is down complete when it returns. A lost connection is reported
2223 once via the C<on_error> handler (C<"connection to broker lost;
2224 reconnecting">); the reconnect attempts themselves are not reported --
2225 with the default die-on-error handler, a broker outage is survivable.
2226 Retries use capped exponential backoff with jitter. C<flush()> bounds
2227 the wait: see C<flush_timeout>.
2228  
2229 =head1 ANYEVENT INTEGRATION
2230  
2231 L<AnyEvent> has EV as one of its backends, so EV::Kafka can be used
2232 in AnyEvent applications seamlessly.
2233  
2234 =head1 NO UTF-8 SUPPORT
2235  
2236 This module handles all values as bytes. Encode your UTF-8 strings
2237 before passing them:
2238  
2239 use Encode;
2240  
2241 $kafka->produce($topic, $key, encode_utf8($val), sub { ... });
2242  
2243 =head1 CLUSTER CLIENT METHODS
2244  
2245 =head2 new(%options)
2246  
2247 Create a new EV::Kafka client. Returns a blessed C<EV::Kafka::Client>
2248 object. Unknown option names croak (C<"EV::Kafka: unknown option(s):
2249 ...">), so typos fail at construction instead of being silently ignored.
2250  
2251 my $kafka = EV::Kafka->new(
2252 brokers => '10.0.0.1:9092,10.0.0.2:9092',
2253 acks => -1,
2254 on_error => sub { warn @_ },
2255 );
2256  
2257 Options:
2258  
2259 =over
2260  
2261 =item brokers => 'Str'
2262  
2263 Comma-separated list of bootstrap broker addresses (host:port).
2264 Default: C<127.0.0.1:9092>.
2265  
2266 =item client_id => 'Str' (default 'ev-kafka')
2267  
2268 Client identifier sent to brokers.
2269  
2270 =item tls => Bool
2271  
2272 Enable TLS encryption.
2273  
2274 =item tls_ca_file => 'Str'
2275  
2276 Path to CA certificate file for TLS verification.
2277  
2278 =item tls_skip_verify => Bool
2279  
2280 Skip TLS certificate verification.
2281  
2282 =item sasl => \%opts
2283  
2284 Enable SASL authentication. Supported mechanisms: C<PLAIN>,
2285 C<SCRAM-SHA-256>, C<SCRAM-SHA-512>.
2286  
2287 sasl => { mechanism => 'PLAIN', username => 'user', password => 'pass' }
2288  
2289 =item acks => Int (default -1)
2290  
2291 Producer acknowledgment mode. C<-1> = all in-sync replicas, C<0> = no
2292 acknowledgment (fire-and-forget), C<1> = leader only.
2293  
2294 =item linger_ms => Int (default 5)
2295  
2296 Time in milliseconds to accumulate records before flushing a batch.
2297 Lower values reduce latency; higher values improve throughput.
2298  
2299 =item batch_size => Int (default 16384)
2300  
2301 Maximum batch size in bytes before a batch is flushed immediately.
2302  
2303 =item compression => 'Str'
2304  
2305 Compression type for produce batches: C<'lz4'> (requires liblz4),
2306 C<'gzip'> (requires zlib), C<'zstd'> (requires libzstd),
2307 C<'snappy'> (requires libsnappy), or C<undef> for none.
2308  
2309 =item idempotent => Bool (default 0)
2310  
2311 Enable idempotent producer. Calls C<InitProducerId> on connect and
2312 sets producer_id/epoch/sequence in each RecordBatch for exactly-once
2313 delivery (broker-side deduplication). Only one batch per
2314 (topic, partition) is in-flight at a time when this is enabled, to
2315 prevent sequence-number aliasing on retry. Produce calls made before
2316 C<InitProducerId> completes are queued, never sent non-idempotent.
2317 If C<InitProducerId> fails after bounded retries, the failure is
2318 sticky: queued and later produce callbacks receive an error and
2319 C<begin_transaction> dies -- the client never silently degrades to
2320 non-idempotent production. C<DUPLICATE_SEQUENCE> (46) responses are
2321 treated as acks (the broker already has the batch), while
2322 C<OUT_OF_ORDER_SEQUENCE_NUMBER> (45) and C<INVALID_PRODUCER_EPOCH> (47)
2323 trigger a single epoch-bump re-initialization shared by all affected
2324 partitions, then the batch is retried.
2325  
2326 =item transactional_id => 'Str'
2327  
2328 Enable transactional producer. Implies idempotent. Required for
2329 C<begin_transaction>/C<commit_transaction>/C<abort_transaction>
2330 and C<send_offsets_to_transaction> (full EOS). The transactional
2331 C<InitProducerId> request is sent only to the transaction coordinator
2332 (discovered via FindCoordinator), never to an arbitrary broker.
2333  
2334 =item partitioner => $cb->($topic, $key, $num_partitions)
2335  
2336 Custom partition selection function. Default: murmur2 hash of key,
2337 or round-robin for null keys.
2338  
2339 =item on_error => $cb->($errstr)
2340  
2341 Error callback. Default: C<die>.
2342  
2343 =item on_connect => $cb->()
2344  
2345 Called once after initial metadata fetch completes.
2346  
2347 =item on_message => $cb->($topic, $partition, $offset, $key, $value, $headers)
2348  
2349 Message delivery callback for consumer operations.
2350  
2351 =item fetch_max_wait_ms => Int (default 500)
2352  
2353 Maximum time the broker waits to accumulate C<fetch_min_bytes> of data
2354 before returning a fetch response.
2355  
2356 =item fetch_max_bytes => Int (default 1048576)
2357  
2358 Maximum bytes per fetch response.
2359  
2360 =item fetch_min_bytes => Int (default 1)
2361  
2362 Minimum bytes before the broker responds to a fetch.
2363  
2364 =item metadata_refresh => Int (default 300)
2365  
2366 Periodic metadata refresh interval in seconds. Set to C<0> to disable.
2367 Refreshes happen in the background, so consumers and producers pick up
2368 leader changes without waiting for a request to fail first.
2369  
2370 =item flush_timeout => N (default 30)
2371  
2372 Seconds C<flush()> waits for outstanding work before giving up and
2373 calling its callback with an error. Set to C<0> to wait forever.
2374  
2375 =item loop => $ev_loop
2376  
2377 EV loop object to use. Default: C<EV::default_loop>.
2378  
2379 =back
2380  
2381 =head2 connect([$cb])
2382  
2383 Connect to the cluster. Connects to the first available bootstrap
2384 broker, fetches cluster metadata, then fires C<$cb-E<gt>($metadata)>.
2385 On bootstrap-broker failure the next address is tried; if all fail,
2386 C<$cb> is invoked as C<$cb-E<gt>(undef, $err)> (without a callback, the
2387 C<on_error> handler fires instead). If the client is closed before the
2388 connection completes, C<$cb> is invoked as C<$cb-E<gt>(undef, $err)>.
2389  
2390 Calling C<connect()> more than once is defined: callbacks registered
2391 while a connection is in progress are queued and each fires exactly
2392 once; calling C<connect()> on an already-connected client fires the
2393 callback immediately with the cached metadata. If idempotent producer
2394 initialization was requested but fails, queued connect callbacks are
2395 invoked as C<$cb-E<gt>(undef, $err)> instead of with metadata.
2396  
2397 $kafka->connect(sub {
2398 my $meta = shift;
2399 # $meta->{brokers}, $meta->{topics}
2400 });
2401  
2402 =head2 produce($topic, $key, $value, [\%opts,] [$cb])
2403  
2404 Produce a message. Routes to the correct partition leader automatically.
2405 C<%opts> accepts only C<partition> and C<headers>; any other key croaks
2406 (C<"EV::Kafka: produce: unknown option ...">), catching typos like
2407 C<partiton>.
2408  
2409 # with callback (acks=1 or acks=-1)
2410 $kafka->produce('topic', 'key', 'value', sub {
2411 my ($result, $err) = @_;
2412 });
2413  
2414 # with headers
2415 $kafka->produce('topic', 'key', 'value',
2416 { headers => { 'h1' => 'v1' } }, sub { ... });
2417  
2418 # fire-and-forget (acks=0)
2419 $kafka->produce('topic', 'key', 'value');
2420  
2421 # explicit partition
2422 $kafka->produce('topic', 'key', 'value',
2423 { partition => 3 }, sub { ... });
2424  
2425 =head2 produce_many(\@messages, $cb)
2426  
2427 Produce multiple messages with a single completion callback. Each
2428 message is an arrayref C<[$topic, $key, $value]> or a hashref
2429 C<{topic, key, value}>. C<$cb> fires when all messages are acknowledged.
2430  
2431 $kafka->produce_many([
2432 ['my-topic', 'k1', 'v1'],
2433 ['my-topic', 'k2', 'v2'],
2434 ], sub {
2435 my $errors = shift;
2436 warn "some failed: @$errors" if $errors;
2437 });
2438  
2439 =head2 flush([$cb])
2440  
2441 Flush all accumulated produce batches and wait for all in-flight
2442 requests to complete. C<$cb> fires when all pending responses have
2443 been received, as C<$cb-E<gt>($err)> on failure: C<"flush timed out">
2444 after C<flush_timeout> seconds (default 30, C<0> waits forever), or
2445 C<"client closed"> if the client is closed while a flush is outstanding.
2446  
2447 =head2 assign(\@partitions)
2448  
2449 Manually assign partitions for consuming.
2450  
2451 $kafka->assign([
2452 { topic => 'my-topic', partition => 0, offset => 0 },
2453 { topic => 'my-topic', partition => 1, offset => 100 },
2454 ]);
2455  
2456 =head2 seek($topic, $partition, $offset, [$cb])
2457  
2458 Seek a partition to a specific offset. Use C<-2> for earliest, C<-1>
2459 for latest. Updates the assignment in-place. Errors are delivered as
2460 the callback's second argument: C<$cb-E<gt>(undef, $err)> fires when
2461 the partition is not assigned, when the partition leader is
2462 unreachable, or when the underlying ListOffsets request fails.
2463  
2464 $kafka->seek('my-topic', 0, -1, sub {
2465 my ($res, $err) = @_;
2466 warn "seek failed: $err" if $err;
2467 });
2468  
2469 A seek that lands while a fetch for the same partition is in flight is
2470 not clobbered by the in-flight fetch response.
2471  
2472 =head2 offsets_for($topic, $cb)
2473  
2474 Get earliest and latest offsets for all partitions of a topic.
2475 The callback is C<$cb-E<gt>($offsets, $err)>; C<$err> is the first
2476 ListOffsets failure encountered, if any.
2477  
2478 $kafka->offsets_for('my-topic', sub {
2479 my $offsets = shift;
2480 # { 0 => { earliest => 0, latest => 42 }, 1 => ... }
2481 });
2482  
2483 =head2 lag($cb)
2484  
2485 Get consumer lag for all assigned partitions. The callback is
2486 C<$cb-E<gt>($lag, $err)>; C<$err> is the first ListOffsets failure
2487 encountered, if any.
2488  
2489 $kafka->lag(sub {
2490 my $lag = shift;
2491 # { "topic:0" => { current => 10, latest => 42, lag => 32 } }
2492 });
2493  
2494 =head2 error_name($code)
2495  
2496 Convert a Kafka numeric error code to its name. Callable as a method
2497 or class function.
2498  
2499 $kafka->error_name(3); # "UNKNOWN_TOPIC_OR_PARTITION"
2500 EV::Kafka::Client::error_name(3); # same
2501  
2502 =head2 poll([$cb])
2503  
2504 Fetch messages from assigned partitions. Calls C<on_message> for each
2505 received record. C<$cb> fires as C<$cb-E<gt>($err)> when all fetch
2506 responses have arrived; C<$err> is undef on success.
2507  
2508 Per-partition fetch errors are surfaced and, where possible, recovered:
2509  
2510 =over
2511  
2512 =item * C<OFFSET_OUT_OF_RANGE> (1): the position is re-resolved via
2513 ListOffsets according to C<auto_offset_reset> (C<'earliest'> for
2514 manually assigned consumers), and the poll callback receives the error.
2515 An out-of-range partition therefore recovers instead of failing every
2516 subsequent poll with the same stale offset.
2517  
2518 =item * Other error codes: reported to the C<on_error> handler once per
2519 partition per rebalance (a new C<assign()> or group rejoin resets the
2520 budget); the poll callback is not invoked with these.
2521  
2522 =back
2523  
2524 An errored partition's position is never advanced by its error
2525 response. A die inside C<on_message> is caught, reported via C<warn>,
2526 and does not prevent delivery of the remaining records in the batch.
2527  
2528 my $timer = EV::timer 0, 0.1, sub { $kafka->poll };
2529  
2530 =head2 subscribe(@topics, %opts)
2531  
2532 Join a consumer group and subscribe to one or more topics. The list
2533 of topic names comes first, followed by option key/value pairs. The
2534 group protocol handles partition assignment automatically.
2535  
2536 Topic names must match the Kafka charset (C<[A-Za-z0-9._-]>); anything
2537 else croaks. Option names are reserved words: C<group_id>,
2538 C<group_instance_id>, C<on_assign>, C<on_revoke>, C<session_timeout>,
2539 C<rebalance_timeout>, C<heartbeat_interval>, C<auto_commit>,
2540 C<auto_offset_reset>. Because the API is positional, a misspelled
2541 option name cannot be detected (it would be a legal topic name), so
2542 avoid these strings as topic names. A reserved name given without a
2543 value croaks. C<group_id> only needs to be defined, so
2544 C<group_id =E<gt> '0'> is accepted.
2545  
2546 If the coordinator connection fails during JoinGroup/SyncGroup, the
2547 client retries with full coordinator re-discovery (5 attempts, 1s
2548 apart). On exhaustion the group enters the C<stopped> state and the
2549 failure is reported via C<on_error> instead of retrying forever.
2550  
2551 $kafka->subscribe('topic-a', 'topic-b',
2552 group_id => 'my-group',
2553 session_timeout => 30000, # ms
2554 rebalance_timeout => 60000, # ms
2555 heartbeat_interval => 3, # seconds
2556 auto_commit => 1, # commit on unsubscribe (default)
2557 auto_offset_reset => 'earliest', # or 'latest'
2558 group_instance_id => 'pod-abc', # KIP-345 static membership
2559 on_assign => sub {
2560 my $partitions = shift;
2561 # [{topic, partition, offset}, ...]
2562 },
2563 on_revoke => sub {
2564 my $partitions = shift;
2565 },
2566 );
2567  
2568 =head2 commit([$cb])
2569  
2570 Commit current consumer offsets to the group coordinator.
2571  
2572 $kafka->commit(sub {
2573 my $err = shift;
2574 warn "commit failed: $err" if $err;
2575 });
2576  
2577 =head2 unsubscribe([$cb])
2578  
2579 Leave the consumer group (sends LeaveGroup for fast rebalance),
2580 stop heartbeat and fetch loop. If C<auto_commit> is enabled,
2581 commits offsets before leaving.
2582  
2583 =head2 begin_transaction
2584  
2585 Start a transaction. Requires C<transactional_id> in constructor.
2586  
2587 =head2 send_offsets_to_transaction($group_id, [$cb])
2588  
2589 Commit consumer offsets within the current transaction via
2590 C<TxnOffsetCommit>. This is the key step for exactly-once
2591 consume-process-produce pipelines.
2592  
2593 $kafka->send_offsets_to_transaction('my-group', sub {
2594 my ($result, $err) = @_;
2595 });
2596  
2597 =head2 commit_transaction([$cb])
2598  
2599 Commit the current transaction. All produced messages and offset
2600 commits within the transaction become visible atomically.
2601  
2602 =head2 abort_transaction([$cb])
2603  
2604 Abort the current transaction. All produced messages are discarded
2605 and offset commits are rolled back.
2606  
2607 =head2 close([$cb])
2608  
2609 Graceful shutdown: stop all timers, fail every pending operation
2610 callback with an error (see L</CLIENT LIFETIME>), disconnect all broker
2611 connections. Idempotent. After close, calling any operation method
2612 croaks with C<"EV::Kafka: client is closed">. Does not send LeaveGroup --
2613 call C<unsubscribe()> first for a clean consumer-group leave.
2614  
2615 $kafka->close(sub { EV::break });
2616  
2617 =head1 LOW-LEVEL CONNECTION METHODS
2618  
2619 C<EV::Kafka::Conn> provides direct access to a single broker connection.
2620 Useful for custom protocols, debugging, or when cluster-level routing
2621 is not needed.
2622  
2623 my $conn = EV::Kafka::Conn::_new('EV::Kafka::Conn', undef);
2624 $conn->on_error(sub { warn @_ });
2625 $conn->on_connect(sub { ... });
2626 $conn->connect('127.0.0.1', 9092, 5.0);
2627  
2628 =head2 connect($host, $port, [$timeout])
2629  
2630 Connect to a broker. Timeout in seconds; 0 selects a 10-second default.
2631 The timeout covers the TCP connect AND every handshake phase (TLS,
2632 ApiVersions, SASL): a peer that accepts but then stays silent fails the
2633 connection with a "handshake timeout" error instead of hanging forever.
2634  
2635 =head2 disconnect
2636  
2637 Disconnect from broker.
2638  
2639 =head2 connected
2640  
2641 Returns true if the connection is ready (ApiVersions handshake complete).
2642  
2643 =head2 metadata(\@topics, $cb)
2644  
2645 Request cluster metadata. Pass C<undef> for all topics.
2646  
2647 $conn->metadata(['my-topic'], sub {
2648 my ($result, $err) = @_;
2649 # $result->{brokers}, $result->{topics}
2650 });
2651  
2652 =head2 produce($topic, $partition, $key, $value, [\%opts,] [$cb])
2653  
2654 Produce a message to a specific partition.
2655  
2656 $conn->produce('topic', 0, 'key', 'value', sub {
2657 my ($result, $err) = @_;
2658 });
2659  
2660 Options: C<acks> (default 1), C<headers> (hashref), C<timestamp>
2661 (epoch ms, default now), C<compression> (C<'none'>, C<'lz4'>,
2662 C<'gzip'>, C<'zstd'>, C<'snappy'>; each requires its respective
2663 library at build time). With C<acks =E<gt> 0> the broker sends no
2664 response, so the callback fires immediately with an empty success
2665 result: it means "handed to the socket", not "broker acknowledged".
2666  
2667 =head2 produce_batch($topic, $partition, \@records, [\%opts,] [$cb])
2668  
2669 Produce multiple records in a single RecordBatch. Each record is
2670 C<{key, value, headers}>. Options: C<acks>, C<compression>,
2671 C<producer_id>, C<producer_epoch>, C<base_sequence>.
2672  
2673 $conn->produce_batch('topic', 0, [
2674 { key => 'k1', value => 'v1' },
2675 { key => 'k2', value => 'v2' },
2676 ], sub { my ($result, $err) = @_ });
2677  
2678 =head2 fetch($topic, $partition, $offset, [\%opts,] $cb)
2679  
2680 Fetch messages from a partition starting at C<$offset>. C<%opts> may
2681 set C<max_bytes> (per-partition cap, default 1 MiB), C<max_wait_ms>
2682 (broker block-time, default 500), C<min_bytes> (default 1).
2683  
2684 $conn->fetch('topic', 0, 0, sub {
2685 my ($result, $err) = @_;
2686 for my $rec (@{ $result->{topics}[0]{partitions}[0]{records} }) {
2687 printf "offset=%d key=%s value=%s\n",
2688 $rec->{offset}, $rec->{key}, $rec->{value};
2689 }
2690 });
2691  
2692 =head2 fetch_multi(\%topics, [\%opts,] $cb)
2693  
2694 Multi-partition fetch in a single request. Groups multiple
2695 topic-partitions into one Fetch call to the broker. C<%opts> accepts
2696 the same keys as C<fetch>.
2697  
2698 $conn->fetch_multi({
2699 'topic-a' => [{ partition => 0, offset => 10 },
2700 { partition => 1, offset => 20 }],
2701 'topic-b' => [{ partition => 0, offset => 0 }],
2702 }, sub { my ($result, $err) = @_ });
2703  
2704 Used internally by C<poll()> to batch fetches by broker leader, with
2705 C<max_bytes>/C<max_wait_ms>/C<min_bytes> taken from the cluster client
2706 config.
2707  
2708 =head2 list_offsets($topic, $partition, $timestamp, $cb)
2709  
2710 Get offsets by timestamp. Use C<-2> for earliest, C<-1> for latest.
2711  
2712 =head2 find_coordinator($key, $cb, [$key_type])
2713  
2714 Find the coordinator broker. C<$key_type>: 0=group (default),
2715 1=transaction.
2716  
2717 =head2 join_group($group_id, $member_id, \@topics, $cb, [$session_timeout_ms, $rebalance_timeout_ms, $group_instance_id])
2718  
2719 Join a consumer group. Pass C<$group_instance_id> for KIP-345 static
2720 membership.
2721  
2722 =head2 sync_group($group_id, $generation_id, $member_id, \@assignments, $cb, [$group_instance_id])
2723  
2724 Synchronize group state after join.
2725  
2726 =head2 heartbeat($group_id, $generation_id, $member_id, $cb, [$group_instance_id])
2727  
2728 Send heartbeat to group coordinator.
2729  
2730 =head2 offset_commit($group_id, $generation_id, $member_id, \@offsets, $cb)
2731  
2732 Commit consumer offsets.
2733  
2734 =head2 offset_fetch($group_id, \@topics, $cb)
2735  
2736 Fetch committed offsets for a consumer group.
2737  
2738 =head2 api_versions
2739  
2740 Returns a hashref of supported API keys to max versions, or undef
2741 if not yet negotiated.
2742  
2743 my $vers = $conn->api_versions;
2744 # { 0 => 7, 1 => 11, 3 => 8, ... }
2745  
2746 =head2 on_error([$cb]), on_connect([$cb]), on_disconnect([$cb])
2747  
2748 Set connection-level handler callbacks. Call with no argument or
2749 C<undef> to clear.
2750  
2751 If no C<on_error> handler is installed, connection errors are reported
2752 via C<warn()> rather than by throwing an exception from inside the event
2753 loop. C<on_disconnect> fires exactly once per actual disconnection, so
2754 calling C<disconnect()> from inside C<on_error> or C<on_disconnect> is
2755 safe and does not retrigger it. When a connection drops with requests
2756 still in flight, their callbacks fire with an error string BEFORE
2757 C<on_disconnect> fires.
2758  
2759 =head2 client_id($id)
2760  
2761 Set the client identifier.
2762  
2763 =head2 tls($enable, [$ca_file, $skip_verify])
2764  
2765 Configure TLS.
2766  
2767 =head2 sasl($mechanism, [$username, $password])
2768  
2769 Configure SASL authentication.
2770  
2771 =head2 auto_reconnect($enable, [$delay_ms])
2772  
2773 Enable automatic reconnection. C<$delay_ms> (default 1000) is the base
2774 delay: the first retry happens after exactly C<$delay_ms>, later retries
2775 use capped exponential backoff (doubling each attempt, up to 30s, with
2776 +/-25% jitter), resetting once a connection succeeds. Reconnects reuse
2777 the timeout from the original C<connect()> call.
2778  
2779 =head2 leave_group($group_id, $member_id, $cb)
2780  
2781 Send LeaveGroup to coordinator for fast partition rebalance.
2782  
2783 =head2 create_topics(\@topics, $timeout_ms, $cb)
2784  
2785 Create topics. Each element: C<{name, num_partitions, replication_factor}>.
2786  
2787 $conn->create_topics(
2788 [{ name => 'new-topic', num_partitions => 3, replication_factor => 1 }],
2789 5000, sub { my ($res, $err) = @_ }
2790 );
2791  
2792 =head2 delete_topics(\@topic_names, $timeout_ms, $cb)
2793  
2794 Delete topics by name.
2795  
2796 =head2 init_producer_id($transactional_id, $txn_timeout_ms, $cb)
2797  
2798 Initialize a producer ID for idempotent/transactional produce.
2799 Pass C<undef> for non-transactional idempotent producer.
2800  
2801 =head2 add_partitions_to_txn($txn_id, $producer_id, $epoch, \@topics, $cb)
2802  
2803 Register partitions with the transaction coordinator.
2804  
2805 =head2 end_txn($txn_id, $producer_id, $epoch, $committed, $cb)
2806  
2807 Commit (C<$committed=1>) or abort (C<$committed=0>) a transaction.
2808  
2809 =head2 txn_offset_commit($txn_id, $group_id, $producer_id, $epoch, $generation, $member_id, \@offsets, $cb)
2810  
2811 Commit consumer offsets within a transaction (API 28).
2812  
2813 =head2 pending
2814  
2815 Number of requests awaiting broker response.
2816  
2817 =head2 state
2818  
2819 Connection state as integer (0=disconnected, 6=ready).
2820  
2821 =head2 Object lifetime
2822  
2823 The connection is torn down when its last reference drops, or when
2824 C<DESTROY> is called explicitly; explicit destruction is idempotent.
2825 Pending request callbacks are invoked with a C<'destroyed'> error during
2826 teardown. Once destroyed, the object is inert: every subsequent method
2827 call on it (from any copy of the reference) croaks with
2828 C<EV::Kafka::Conn: method called on destroyed connection> -- including
2829 calls made from callbacks running during the teardown itself (those
2830 exceptions are caught by the callback dispatcher and reported via
2831 C<warn()>). A conn passed a custom C<EV::Loop> holds a reference on it,
2832 so the loop cannot be destroyed while the conn is alive.
2833  
2834 =head1 UTILITY FUNCTIONS
2835  
2836 =head2 EV::Kafka::_murmur2($key)
2837  
2838 Kafka-compatible murmur2 hash. Returns a non-negative 31-bit integer.
2839  
2840 =head2 EV::Kafka::_crc32c($data)
2841  
2842 CRC32C checksum (Castagnoli). Used internally for RecordBatch integrity.
2843  
2844 =head2 EV::Kafka::_error_name($code)
2845  
2846 Convert Kafka error code to string name.
2847  
2848 =head1 RESULT STRUCTURES
2849  
2850 =head2 Produce result
2851  
2852 $result = {
2853 topics => [{
2854 topic => 'name',
2855 partitions => [{
2856 partition => 0,
2857 error_code => 0,
2858 base_offset => 42,
2859 }],
2860 }],
2861 };
2862  
2863 =head2 Fetch result
2864  
2865 $result = {
2866 topics => [{
2867 topic => 'name',
2868 partitions => [{
2869 partition => 0,
2870 error_code => 0,
2871 high_watermark => 100,
2872 records => [{
2873 offset => 42,
2874 timestamp => 1712345678000,
2875 key => 'key', # or undef
2876 value => 'value', # or undef
2877 headers => { h => 'v' }, # if present
2878 }],
2879 }],
2880 }],
2881 };
2882  
2883 =head2 Metadata result
2884  
2885 $result = {
2886 controller_id => 0,
2887 brokers => [{ node_id => 0, host => '10.0.0.1', port => 9092 }],
2888 topics => [{
2889 name => 'topic',
2890 error_code => 0,
2891 partitions => [{
2892 partition => 0,
2893 leader => 0,
2894 error_code => 0,
2895 }],
2896 }],
2897 };
2898  
2899 =head1 ERROR HANDLING
2900  
2901 Errors are delivered through two channels:
2902  
2903 =over
2904  
2905 =item B<Connection-level errors> fire the C<on_error> callback (or
2906 C<croak> if none set). These include connection refused, DNS failure,
2907 TLS errors, SASL auth failure, and protocol violations.
2908  
2909 =item B<Request-level errors> are delivered as the second argument to
2910 the request callback: C<$cb-E<gt>($result, $error)>. If C<$error> is
2911 defined, C<$result> may be undef.
2912  
2913 =back
2914  
2915 An error that belongs to a specific operation is reported to that
2916 operation's callback I<or> to the C<on_error> handler, never both --
2917 this matters because the default C<on_error> handler dies. Errors with
2918 no owning operation (connection loss, metadata failures, group protocol
2919 failures, per-partition fetch errors) go to C<on_error>.
2920  
2921 A die inside a user callback (C<on_message>, a produce callback) does
2922 not propagate out of the event loop: it is caught, reported via
2923 C<warn>, and the remaining callbacks in the same batch still run.
2924  
2925 Within result structures, per-partition C<error_code> fields use Kafka
2926 numeric codes:
2927  
2928 0 No error
2929 1 OFFSET_OUT_OF_RANGE
2930 3 UNKNOWN_TOPIC_OR_PARTITION
2931 6 NOT_LEADER_OR_FOLLOWER (retried by the producer)
2932 15 COORDINATOR_NOT_AVAILABLE (retried)
2933 16 NOT_COORDINATOR (retried)
2934 22 ILLEGAL_GENERATION (group rejoin)
2935 25 UNKNOWN_MEMBER_ID (group rejoin)
2936 27 REBALANCE_IN_PROGRESS (group rejoin)
2937 36 TOPIC_ALREADY_EXISTS
2938 45 OUT_OF_ORDER_SEQUENCE_NUMBER (idempotent: epoch bump)
2939 46 DUPLICATE_SEQUENCE_NUMBER (idempotent: treated as an ack)
2940 47 INVALID_PRODUCER_EPOCH (idempotent: epoch bump)
2941 79 MEMBER_ID_REQUIRED (group rejoin with assigned id)
2942  
2943 Use C<EV::Kafka::Client::error_name($code)> for the full list.
2944  
2945 When a broker disconnects mid-flight, all pending callbacks receive
2946 C<(undef, "connection closed by broker")> or C<(undef, "disconnected")>.
2947  
2948 =head1 ENVIRONMENT VARIABLES
2949  
2950 These are used by tests and examples (not by the module itself):
2951  
2952 TEST_KAFKA_BROKER broker address for tests (host:port)
2953 KAFKA_BROKER broker address for examples
2954 KAFKA_HOST broker hostname for low-level examples
2955 KAFKA_PORT broker port for low-level examples
2956 KAFKA_TOPIC topic name for examples
2957 KAFKA_GROUP_ID consumer group for examples
2958 KAFKA_LIMIT message limit for consume example
2959 KAFKA_COUNT message count for fire-and-forget
2960 BENCH_BROKER broker for benchmarks
2961 BENCH_MESSAGES message count for benchmarks
2962 BENCH_VALUE_SIZE value size in bytes for benchmarks
2963 BENCH_TOPIC topic name for benchmarks
2964  
2965 =head1 QUICK START
2966  
2967 Minimal producer + consumer lifecycle:
2968  
2969 use EV;
2970 use EV::Kafka;
2971  
2972 my $kafka = EV::Kafka->new(
2973 brokers => '127.0.0.1:9092',
2974 acks => 1,
2975 on_error => sub { warn "kafka: @_\n" },
2976 on_message => sub {
2977 my ($topic, $part, $offset, $key, $value) = @_;
2978 print "got: $key=$value\n";
2979 },
2980 );
2981  
2982 $kafka->connect(sub {
2983 # produce
2984 $kafka->produce('test', 'k1', 'hello', sub {
2985 print "produced\n";
2986  
2987 # consume from the beginning
2988 $kafka->assign([{topic=>'test', partition=>0, offset=>0}]);
2989 $kafka->seek('test', 0, -2, sub {
2990 my $t = EV::timer 0, 0.1, sub { $kafka->poll };
2991 $kafka->{cfg}{_t} = $t;
2992 });
2993 });
2994 });
2995  
2996 EV::run;
2997  
2998 =head1 COOKBOOK
2999  
3000 =head2 Produce JSON with headers
3001  
3002 use JSON::PP;
3003 my $json = JSON::PP->new->utf8;
3004  
3005 $kafka->produce('events', 'user-42',
3006 $json->encode({ action => 'click', page => '/home' }),
3007 { headers => { 'content-type' => 'application/json' } },
3008 sub { ... }
3009 );
3010  
3011 =head2 Consume from latest offset only
3012  
3013 $kafka->subscribe('live-feed',
3014 group_id => 'realtime',
3015 auto_offset_reset => 'latest',
3016 on_assign => sub { print "ready\n" },
3017 );
3018  
3019 =head2 Graceful shutdown
3020  
3021 $SIG{INT} = sub {
3022 $kafka->commit(sub {
3023 $kafka->unsubscribe(sub {
3024 $kafka->close(sub { EV::break });
3025 });
3026 });
3027 };
3028  
3029 =head2 At-least-once processing
3030  
3031 $kafka->subscribe('jobs',
3032 group_id => 'workers',
3033 auto_commit => 0,
3034 );
3035  
3036 # in on_message: process, then commit
3037 on_message => sub {
3038 process($_[4]);
3039 $kafka->commit if ++$count % 100 == 0;
3040 },
3041  
3042 =head2 Batch produce
3043  
3044 $kafka->produce_many([
3045 ['events', 'k1', 'v1'],
3046 ['events', 'k2', 'v2'],
3047 ['events', 'k3', 'v3'],
3048 ], sub {
3049 my $errs = shift;
3050 print $errs ? "some failed\n" : "all done\n";
3051 });
3052  
3053 =head2 Exactly-once stream processing (EOS)
3054  
3055 my $kafka = EV::Kafka->new(
3056 brokers => '...',
3057 transactional_id => 'my-eos-app',
3058 acks => -1,
3059 on_message => sub {
3060 my ($t, $p, $off, $key, $value) = @_;
3061 my $result = process($value);
3062 $kafka->produce('output-topic', $key, $result);
3063 },
3064 );
3065  
3066 # consume-process-produce loop:
3067 $kafka->begin_transaction;
3068 $kafka->poll(sub {
3069 $kafka->send_offsets_to_transaction('my-group', sub {
3070 $kafka->commit_transaction(sub {
3071 $kafka->begin_transaction; # next transaction
3072 });
3073 });
3074 });
3075  
3076 =head2 Topic administration
3077  
3078 my $conn = EV::Kafka::Conn::_new('EV::Kafka::Conn', undef);
3079 $conn->on_connect(sub {
3080 $conn->create_topics(
3081 [{ name => 'new-topic', num_partitions => 6, replication_factor => 3 }],
3082 10000, sub { ... }
3083 );
3084 });
3085  
3086 =head1 BENCHMARKS
3087  
3088 Measured on Linux with TCP loopback to Redpanda, 100-byte values,
3089 Perl 5.40.2, 20K messages (C<bench/benchmark.pl>):
3090  
3091 Pipeline produce (acks=1) 100K msg/sec 11.0 MB/s
3092 Fire-and-forget (acks=0) 120K msg/sec 13.2 MB/s
3093 Sequential round-trip 24K msg/sec 42 us avg latency
3094 Metadata request 21K req/sec 47 us avg latency
3095  
3096 Throughput by value size (pipelined, acks=1):
3097  
3098 10 bytes 105K msg/sec 1.5 MB/s
3099 100 bytes 100K msg/sec 10.5 MB/s
3100 1000 bytes 70K msg/sec 70.7 MB/s
3101 10000 bytes 20K msg/sec 202.0 MB/s
3102  
3103 Latency histogram (20K round-trips, acks=1, C<bench/latency.pl>):
3104  
3105 median: 39 us p90: 59 us p95: 75 us p99: 122 us
3106  
3107 Pipeline produce throughput is limited by Perl callback overhead per
3108 message. Fire-and-forget mode (C<acks=0>) skips the response cycle
3109 entirely, reaching ~120K msg/sec. Sequential round-trip (one produce,
3110 wait for ack, repeat) measures raw broker latency around 39us median.
3111  
3112 The fetch path is sequential (fetch, process, fetch again) which
3113 introduces one round-trip per batch. With larger C<max_bytes> and
3114 dense topics, fetch throughput increases proportionally.
3115  
3116 Run C<perl bench/benchmark.pl> for throughput results. Set
3117 C<BENCH_BROKER>, C<BENCH_MESSAGES>, C<BENCH_VALUE_SIZE>, and
3118 C<BENCH_TOPIC> to customize.
3119  
3120 Run C<perl bench/latency.pl> for a latency histogram with percentiles
3121 (min, avg, median, p90, p95, p99, max).
3122  
3123 =head1 KAFKA PROTOCOL
3124  
3125 This module implements the Kafka binary protocol directly in XS.
3126 All integers are big-endian. Requests use a 4-byte size prefix
3127 followed by a header (API key, version, correlation ID, client ID)
3128 and a version-specific body.
3129  
3130 Responses are matched to requests by correlation ID. The broker
3131 guarantees FIFO ordering per connection, so the response queue is
3132 a simple FIFO.
3133  
3134 RecordBatch encoding (magic=2) is used for produce. CRC32C covers
3135 the batch from attributes through the last record. Records use
3136 ZigZag-encoded varints for lengths and deltas.
3137  
3138 The connection handshake sends ApiVersions (v0) on connect to
3139 discover supported protocol versions. SASL authentication uses
3140 SaslHandshake (v1) + SaslAuthenticate (v2) with PLAIN mechanism.
3141  
3142 Consumer group protocol uses sticky partition assignment with
3143 MEMBER_ID_REQUIRED (error 79) retry per KIP-394.
3144  
3145 Non-flexible API versions are used throughout (capped below the
3146 flexible-version threshold for each API) to avoid the compact
3147 encoding complexity.
3148  
3149 =head1 LIMITATIONS
3150  
3151 =over
3152  
3153 =item * B<Blocking DNS for hostnames> -- numeric IPv4/IPv6 literals
3154 take a fast path (C<AI_NUMERICHOST>) and never block. Non-literal
3155 hostnames call C<getaddrinfo> synchronously, blocking the EV loop
3156 until the resolver responds. For fully non-blocking operation against
3157 named brokers, pre-resolve in Perl-land.
3158  
3159 =item * B<No GSSAPI/OAUTHBEARER> -- only SASL/PLAIN and
3160 SCRAM-SHA-256/512 are implemented.
3161  
3162 =item * B<No flexible API versions> -- all API versions are capped
3163 below the flexible-version threshold to avoid compact string/array
3164 encoding. Works with Kafka 0.11+ and Redpanda; loses access to a few
3165 newer protocol features.
3166  
3167 =item * B<Producer retry policy> -- transient errors (NOT_LEADER,
3168 COORDINATOR_NOT_AVAILABLE) trigger metadata refresh and up to 3
3169 retries with backoff. DUPLICATE_SEQUENCE is treated as an ack;
3170 OUT_OF_ORDER_SEQUENCE and INVALID_PRODUCER_EPOCH trigger one
3171 InitProducerId-with-fresh-epoch recovery attempt. Other broker errors
3172 are surfaced to the callback immediately.
3173  
3174 =back
3175  
3176 =head1 CAVEATS
3177  
3178 =over
3179  
3180 =item * B<SIGPIPE on Linux with TLS> -- writes on plain connections are
3181 protected (C<MSG_NOSIGNAL> on Linux, C<SO_NOSIGPIPE> on BSD/macOS), but
3182 TLS writes on Linux are not: C<SSL_write> takes no per-call flags and
3183 Linux has no C<SO_NOSIGPIPE>, so a broker RST racing a write can
3184 deliver SIGPIPE and terminate the process. Applications using
3185 C<tls =E<gt> 1> on Linux should set C<$SIG{PIPE} = 'IGNORE';> at
3186 startup. Ignoring it is harmless: failed writes surface as EPIPE
3187 through the normal connection error path. The module deliberately does
3188 not set this itself -- a library must not change a process-global
3189 signal disposition its embedding application may rely on.
3190  
3191 =back
3192  
3193 =head1 AUTHOR
3194  
3195 vividsnow
3196  
3197 =head1 LICENSE
3198  
3199 This library is free software; you can redistribute it and/or modify it
3200 under the same terms as Perl itself.
3201  
3202 =cut
3203  
↑ Summary Kafka.xs »