blib/lib/EV/Kafka.pm

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