blib/lib/EV/Nats/KV.pm

filter: Statementstmt 36.7% 87 / 237 Branchbran 16.9% 24 / 142 Conditioncond 24.4% 22 / 90 MC/DCmcdc 9.6% 5 / 52 Subroutinesub 50.0% 28 / 56 Podpod 76.4% 13 / 17 totaltotal 30.1% 179 / 594 CC 107 SCAR 40.2
CC
107
Cov
28%
deliver
342.0
__ANON__
90.0
create_consumer
72.0
CRAP 55.9
↑ Summary blib/lib/EV/Nats/JetStream.pm »
1 package EV::Nats::KV;
2 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 our $VERSION = '0.09';
5 5 ▶use JSON::PP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use EV::Nats::JetStream;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 29 ▶sub new {
Subroutine new: called CC=6 SCAR=18.1
Pod documented
9 29 my ($class, %opts) = @_;
10 29 ▶ my $js = delete $opts{js} || die "js (JetStream) required";
Condition50%1/2
delete $opts{'js'} || die('js (JetStream) required')
l!l
290
MC/DC0%0/1
delete $opts{'js'} || die('js (JetStream) required')
delete $opts{'js'}
Truth table50%1/2
A
A= delete $opts{'js'}
Aresult
11
00
11 29 ▶ my $bucket = delete $opts{bucket} || die "bucket name required";
Condition50%1/2
delete $opts{'bucket'} || die('bucket name required')
l!l
290
MC/DC0%0/1
delete $opts{'bucket'} || die('bucket name required')
delete $opts{'bucket'}
Truth table50%1/2
A
A= delete $opts{'bucket'}
Aresult
11
00
12 # interpolated into subjects verbatim; the nats.go rule
13 29 ▶ die "invalid KV bucket name '$bucket'" unless $bucket =~ /\A[a-zA-Z0-9_-]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $bucket =~ /\A[a-zA-Z0-9_-]+\z/ 1 28 29
14 28 my $timeout = delete $opts{timeout};
15 28 warn "EV::Nats::KV::new: unknown option '$_'" for keys %opts;
16 bless {
17 js => $js->with_timeout($timeout),
18 bucket => $bucket,
19 stream => "KV_$bucket",
20 prefix => "\$KV.$bucket.",
21 # through a JetStream domain the server takes writes under the API
22 # prefix, as nats.go sends them
23 28 ▶ put_prefix => ($js->{prefix} eq '$JS.API' ? '' : "$js->{prefix}.") . "\$KV.$bucket.",
Branch: 1 branch
BranchTrueFalseTotal
$js->{'prefix'} eq '$JS.API' ? : 25 3 28
24 }, $class;
25 }
26  
27 # Keys go into subjects verbatim: a space is a fatal protocol error, and
28 # * or > would turn a lookup into a wildcard. The nats.go rule.
29 36 ▶sub subject {
Subroutine subject: called CC=6 SCAR=18.0
Pod undocumented
30 36 my ($self, $key) = @_;
31 36 ▶ die "invalid KV key '" . ($key // '') . "'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and $key =~ m[\A[-/_=.a-zA-Z0-9]+\z] and not $key =~ /\A\./ and not $key =~ /\.\z/ 6 30 36
Condition81%9/11
defined $key and $key =~ m[\A[-/_=.a-zA-Z0-9]+\z] and not $key =~ /\A\./ and not $key =~ /\.\z/
!ll&&!rl&&r
5130
defined $key and $key =~ m[\A[-/_=.a-zA-Z0-9]+\z] and not $key =~ /\A\./
!ll&&!rl&&r
4131
defined $key and $key =~ m[\A[-/_=.a-zA-Z0-9]+\z]
!ll&&!rl&&r
0432
$key // ""
l!l
60
MC/DC75%3/4
defined $key and $key =~ m[\A[-/_=.a-zA-Z0-9]+\z] and not $key =~ /\A\./ and not $key =~ /\.\z/
defined $key $key =~ m[\A[-/_=.a-zA-Z0-9]+\z] not $key =~ /\A\./ not $key =~ /\.\z/
MC/DC0%0/1
$key // ""
$key
Truth table80%4/5
A and B and not(C) and not(D)
A= defined $keyB= $key =~ m[\A[-/_=.a-zA-Z0-9]+\z]C= not $key =~ /\A\./D= not $key =~ /\.\z/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
Truth table50%1/2
A
A= $key
Aresult
11
00
32 unless defined $key
33 && $key =~ /\A[-\/_=.a-zA-Z0-9]+\z/
34 && $key !~ /\A\./ && $key !~ /\.\z/;
35 30 return $self->{prefix} . $key;
36 }
37  
38 17 ▶sub put_subject {
Subroutine put_subject: called CC=1 SCAR=0.0
Pod undocumented
39 17 my ($self, $key) = @_;
40 17 $self->subject($key);
41 17 return $self->{put_prefix} . $key;
42 }
43  
44 12 ▶sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
45 12 my ($self, $key, $cb) = @_;
46 6 ▶ $self->get_entry($key, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
47 6 my ($entry, $err) = @_;
48 6 ▶ $cb->($entry ? $entry->{value} : undef, $err);
Branch: 1 branch
BranchTrueFalseTotal
$entry ? : 1 5 6
49 12 });
50 }
51  
52 14 ▶sub get_entry {
Subroutine get_entry: called CC=1 SCAR=0.0
Pod documented
53 14 my ($self, $key, $cb) = @_;
54 14 my $subj = $self->subject($key);
55 8 ▶ $self->{js}->get_msg($self->{stream}, { last_by_subj => $subj }, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
56 8 my ($msg, $err) = @_;
57 8 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 1 7 8
58 7 ▶ return $cb->(undef, undef) if !$msg || EV::Nats::JetStream::msg_is_tombstone($msg);
Branch: 1 branch
BranchTrueFalseTotal
if not $msg or EV::Nats::JetStream::msg_is_tombstone($msg) 5 2 7
Condition100%3/3
not $msg or EV::Nats::JetStream::msg_is_tombstone($msg)
l!l&&r!l&&!r
412
MC/DC100%2/2
not $msg or EV::Nats::JetStream::msg_is_tombstone($msg)
not $msg EV::Nats::JetStream::msg_is_tombstone($msg)
Truth table100%3/3
not(A) or B
A= not $msgB= EV::Nats::JetStream::msg_is_tombstone($msg)
ABresult
1X1
011
000
59 2 $cb->({ value => $msg->{data}, revision => $msg->{seq} }, undef);
60 8 });
61 }
62  
63 1 ▶sub put {
Subroutine put: called CC=1 SCAR=0.2
Pod documented
64 1 my ($self, $key, $value, $cb) = @_;
65 1 ▶ $self->{js}->js_publish($self->put_subject($key), $value, sub {
Subroutine __ANON__: called CC=2 SCAR=8.1
66 1 my ($ack, $err) = @_;
67 1 ▶ $cb->($ack && $ack->{seq}, $err);
Condition33%1/3
$ack && $ack->{'seq'}
!ll&&!rl&&r
001
MC/DC0%0/2
$ack && $ack->{'seq'}
$ack $ack->{'seq'}
Truth table33%1/3
A && B
A= $ackB= $ack->{'seq'}
ABresult
0X0
100
111
68 1 });
69 }
70  
71 16 ▶sub expect_publish {
Subroutine expect_publish: called CC=2 SCAR=7.5
Pod undocumented
72 16 my ($self, $subj, $headers, $value, $cb) = @_;
73 16 ▶ return $self->{js}{nats}->hpublish($subj, $headers, $value) unless $cb;
Branch: 1 branch
BranchTrueFalseTotal
unless $cb 0 16 16
74 10 ▶ $self->{js}->js_publish_h($subj, $headers, $value, sub {
Subroutine __ANON__: called CC=2 SCAR=8.1
75 10 my ($ack, $err) = @_;
76 10 ▶ $cb->($ack && $ack->{seq}, $err);
Condition33%1/3
$ack && $ack->{'seq'}
!ll&&!rl&&r
1000
MC/DC0%0/2
$ack && $ack->{'seq'}
$ack $ack->{'seq'}
Truth table33%1/3
A && B
A= $ackB= $ack->{'seq'}
ABresult
0X0
100
111
77 16 });
78 }
79  
80 5 ▶sub create {
Subroutine create: called CC=2 SCAR=10.4
Pod documented
81 5 my ($self, $key, $value, $cb) = @_;
82 5 my $subj = $self->subject($key);
83 5 my $put = $self->put_subject($key);
84 $self->expect_publish($put,
85 "NATS/1.0\r\nNats-Expected-Last-Subject-Sequence: 0\r\n\r\n",
86 4 ▶ $value, $cb ? sub {
Subroutine __ANON__: called CC=3 SCAR=19.2
87 4 my ($seq, $err) = @_;
88 4 ▶ return $cb->($seq, $err) unless $err && $err =~ /wrong last sequence/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $err and $err =~ /wrong last sequence/i 4 0 4
Condition33%1/3
$err and $err =~ /wrong last sequence/i
!ll&&!rl&&r
040
MC/DC0%0/2
$err and $err =~ /wrong last sequence/i
$err $err =~ /wrong last sequence/i
Truth table33%1/3
A and B
A= $errB= $err =~ /wrong last sequence/i
ABresult
0X0
100
111
89 $self->{js}->get_msg($self->{stream},
90 0 ▶ { last_by_subj => $subj }, sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
91 0 my ($msg, $read_err) = @_;
92 0 ▶ return $cb->(undef, $read_err) if $read_err;
Branch: 1 branch
BranchTrueFalseTotal
if $read_err 0 0 0
93 0 ▶ return $cb->(undef, $err)
Branch: 1 branch
BranchTrueFalseTotal
unless EV::Nats::JetStream::msg_is_tombstone($msg) 0 0 0
94 unless EV::Nats::JetStream::msg_is_tombstone($msg);
95 0 $self->expect_publish($put,
96 "NATS/1.0\r\nNats-Expected-Last-Subject-Sequence: $msg->{seq}\r\n\r\n",
97 $value, $cb);
98 0 });
99 5 ▶ } : undef);
Branch: 1 branch
BranchTrueFalseTotal
$cb ? : 5 0 5
100 }
101  
102 4 ▶sub update {
Subroutine update: called CC=4 SCAR=17.1
Pod documented
103 4 my ($self, $key, $value, $rev, $cb) = @_;
104 4 my $subj = $self->put_subject($key);
105 4 ▶ die "invalid KV revision '" . ($rev // '') . "'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rev and $rev =~ /\A[1-9][0-9]*\z/ 0 4 4
Condition20%1/5
defined $rev and $rev =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
004
$rev // ""
l!l
00
MC/DC0%0/2
defined $rev and $rev =~ /\A[1-9][0-9]*\z/
defined $rev $rev =~ /\A[1-9][0-9]*\z/
MC/DC0%0/1
$rev // ""
$rev
Truth table33%1/3
A and B
A= defined $revB= $rev =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
Truth table0%0/2
A
A= $rev
Aresult
11
00
106 unless defined $rev && $rev =~ /\A[1-9][0-9]*\z/;
107 4 $self->expect_publish($subj,
108 "NATS/1.0\r\nNats-Expected-Last-Subject-Sequence: $rev\r\n\r\n",
109 $value, $cb);
110 }
111  
112 4 ▶sub delete {
Subroutine delete: called CC=1 SCAR=0.0
Pod documented
113 4 my ($self, $key, $cb) = @_;
114 4 $self->tombstone($key, "NATS/1.0\r\nKV-Operation: DEL\r\n\r\n", $cb);
115 }
116  
117 3 ▶sub purge {
Subroutine purge: called CC=1 SCAR=0.0
Pod documented
118 3 my ($self, $key, $cb) = @_;
119 3 $self->tombstone($key, "NATS/1.0\r\nKV-Operation: PURGE\r\nNats-Rollup: sub\r\n\r\n", $cb);
120 }
121  
122 # the PubAck fences the tombstone ahead of a following get
123 7 ▶sub tombstone {
Subroutine tombstone: called CC=3 SCAR=11.1
Pod undocumented
124 7 my ($self, $key, $headers, $cb) = @_;
125 7 my $subj = $self->put_subject($key);
126 7 ▶ return $self->expect_publish($subj, $headers, '') unless $cb;
Branch: 1 branch
BranchTrueFalseTotal
unless $cb 0 7 7
127 7 my $ok = eval {
128 7 ▶ $self->expect_publish($subj, $headers, '', sub { $cb->($_[1] ? (undef, $_[1]) : (1, undef)) });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$_[1] ? : 3 0 3
129 3 1;
130 };
131 7 ▶ EV::Nats::JetStream::fail_later($self->{js}{nats}, $cb, $@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 4 3 7
132 }
133  
134 1 ▶sub keys {
Subroutine keys: called CC=1 SCAR=0.0
Pod documented
135 1 my ($self, $cb) = @_;
136 1 $self->{js}->subjects_under($self->{stream}, $self->{prefix}, $cb);
137 }
138  
139 1 ▶sub watch {
Subroutine watch: called CC=6 SCAR=26.9
Pod documented
140 1 my ($self, $key_pattern, $cb, $opts) = @_;
141 1 ▶ $key_pattern //= '>';
Condition50%1/2
$key_pattern //= ">"
l!l
10
MC/DC0%0/1
$key_pattern //= ">"
$key_pattern
Truth table50%1/2
A
A= $key_pattern
Aresult
11
00
142 1 ▶ die "invalid KV watch pattern '$key_pattern'"
Branch: 1 branch
BranchTrueFalseTotal
if not length $key_pattern or $key_pattern =~ /\s/ 1 0 1
Condition33%1/3
not length $key_pattern or $key_pattern =~ /\s/
l!l&&r!l&&!r
010
MC/DC0%0/2
not length $key_pattern or $key_pattern =~ /\s/
not length $key_pattern $key_pattern =~ /\s/
Truth table33%1/3
not(A) or B
A= not length $key_patternB= $key_pattern =~ /\s/
ABresult
1X1
011
000
143 if !length $key_pattern || $key_pattern =~ /\s/;
144 0 ▶ $opts //= {};
Condition0%0/2
$opts //= {}
l!l
00
MC/DC0%0/1
$opts //= {}
$opts
Truth table0%0/2
A
A= $opts
Aresult
11
00
145 return EV::Nats::KV::Watch->new(
146 kv => $self,
147 cb => $cb,
148 filter => $self->{prefix} . $key_pattern,
149 initial => $opts->{initial} ? 1 : 0,
150 ready => $opts->{ready},
151 on_error => $opts->{on_error},
152 0 ▶ )->{sid};
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'initial'} ? : 0 0 0
153 }
154  
155 1 ▶sub create_bucket {
Subroutine create_bucket: called CC=6 SCAR=21.2
Pod documented
156 1 my ($self, $opts, $cb) = @_;
157 1 ▶ $opts //= {};
Condition50%1/2
$opts //= {}
l!l
10
MC/DC0%0/1
$opts //= {}
$opts
Truth table50%1/2
A
A= $opts
Aresult
11
00
158 my $config = {
159 name => $self->{stream},
160 subjects => [ $self->{prefix} . '>' ],
161 retention => 'limits',
162 max_msgs_per_subject => 0 + ($opts->{max_history} || 1),
163 ($opts->{max_bytes} ? (max_bytes => 0 + $opts->{max_bytes}) : ()),
164 ($opts->{max_age} ? (max_age => 0 + $opts->{max_age}) : ()),
165 1 ▶ ($opts->{replicas} ? (num_replicas => 0 + $opts->{replicas}) : ()),
Branch: 3 branches
BranchTrueFalseTotal
$opts->{'max_bytes'} ? : 1 0 1
$opts->{'max_age'} ? : 0 1 1
$opts->{'replicas'} ? : 0 1 1
Condition50%1/2
$opts->{'max_history'} || 1
l!l
10
MC/DC0%0/1
$opts->{'max_history'} || 1
$opts->{'max_history'}
Truth table50%1/2
A
A= $opts->{'max_history'}
Aresult
11
00
166 discard => 'new',
167 allow_rollup_hdrs => JSON::PP::true(),
168 allow_direct => JSON::PP::true(),
169 deny_delete => JSON::PP::true(),
170 deny_purge => JSON::PP::false(),
171 };
172 0 ▶ $self->{js}->create_bucket_stream($config, sub { $cb->(@_[0, 1]) });
Subroutine __ANON__: not called CC=1 SCAR=1.2
173 }
174  
175 1 ▶sub delete_bucket {
Subroutine delete_bucket: called CC=1 SCAR=0.0
Pod documented
176 1 my ($self, $cb) = @_;
177 1 ▶ $self->{js}->stream_delete($self->{stream}, sub { $cb->(@_[0, 1]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
178 }
179  
180 0 ▶sub status {
Subroutine status: not called CC=1 SCAR=6.9
Pod documented
181 0 my ($self, $cb) = @_;
182 0 ▶ $self->{js}->stream_info($self->{stream}, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
183 0 my ($info, $err) = @_;
184 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
185 $cb->({
186 bucket => $self->{bucket},
187 values => $info->{state}{messages},
188 bytes => $info->{state}{bytes},
189 history => $info->{config}{max_msgs_per_subject},
190 0 }, undef);
191 0 });
192 }
193  
194 # An ordered view of the bucket through an ephemeral pull consumer. After a
195 # drop the consumer is replaced by one starting right past the last revision
196 # delivered; each incarnation pulls into its own inbox token, so what a
197 # replaced one still sends is told apart. Only the subscription holds the
198 # watch strongly: unsubscribing frees it, and DESTROY deletes the consumer.
199 package EV::Nats::KV::Watch;
200 5 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
201  
202 5 my $BATCH = 256;
203 5 my $EXPIRES = 30; # s per pull
204 5 my $DEADLINE = 40; # s by which a pull has ended, or its consumer is gone
205  
206 0 ▶sub new {
Subroutine new: not called CC=1 SCAR=6.9
207 0 my ($class, %w) = @_;
208 0 my $w = bless { %w, last => 0, gen => 0 }, $class;
209 0 my $nats = $w->nats;
210 0 $w->{inbox} = $nats->new_inbox;
211 0 ▶ $w->{sid} = $nats->subscribe("$w->{inbox}.*", sub { $w->deliver(@_) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
212 0 $w->start;
213 0 return $w;
214 }
215  
216 0 ▶sub nats { $_[0]{kv}{js}{nats} }
Subroutine nats: not called CC=1 SCAR=6.9
217  
218 # held weakly, and never what keeps EV::run going
219 0 ▶sub later {
Subroutine later: not called CC=1 SCAR=6.9
220 0 my ($w, $slot, $delay, $method) = @_;
221 0 Scalar::Util::weaken(my $weak = $w);
222 0 ▶ my $t = $w->nats->timer($delay, 0, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
223 0 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 0 0
224 0 delete $weak->{$slot};
225 0 $weak->$method;
226 0 });
227 0 $t->keepalive(0);
228 0 $w->{$slot} = $t;
229 }
230  
231 0 ▶sub retry {
Subroutine retry: not called CC=3 SCAR=24.8
232 0 my ($w) = @_;
233 0 ▶ $w->{backoff} = $w->{backoff} ? ($w->{backoff} * 2 > 30 ? 30 : $w->{backoff} * 2) : 1;
Branch: 2 branches
BranchTrueFalseTotal
$w->{'backoff'} ? : 0 0 0
$w->{'backoff'} * 2 > 30 ? : 0 0 0
234 0 $w->later(retry => $w->{backoff}, 'start');
235 }
236  
237 0 ▶sub start {
Subroutine start: not called CC=4 SCAR=30.0
238 0 my ($w) = @_;
239 0 ▶ return if $w->{stopped} || !$w->nats->is_subscribed($w->{sid});
Branch: 1 branch
BranchTrueFalseTotal
if $w->{"stopped"} or not $w->nats->is_subscribed($w->{"sid"}) 0 0 0
Condition0%0/3
$w->{"stopped"} or not $w->nats->is_subscribed($w->{"sid"})
l!l&&r!l&&!r
000
MC/DC0%0/2
$w->{"stopped"} or not $w->nats->is_subscribed($w->{"sid"})
$w->{"stopped"} not $w->nats->is_subscribed($w->{"sid"})
Truth table0%0/3
A or not(B)
A= $w->{"stopped"}B= not $w->nats->is_subscribed($w->{"sid"})
ABresult
1X1
011
000
240 0 my $gen = ++$w->{gen};
241 0 my $old = delete $w->{consumer};
242 0 delete $w->{deadline};
243 0 $w->arm_disconnect;
244 0 my $kv = $w->{kv};
245 0 my $ok = eval {
246 0 ▶ $kv->{js}->stream_info($kv->{stream}, sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
247 0 my ($info, $err) = @_;
248 0 ▶ return unless $gen == $w->{gen};
Branch: 1 branch
BranchTrueFalseTotal
unless $gen == $w->{"gen"} 0 0 0
249 0 ▶ return $w->failed($err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
250 # a bucket deleted and made again restarts its sequence
251 0 ▶ my $created = $info->{created} // '';
Condition0%0/2
$info->{"created"} // ""
l!l
00
MC/DC0%0/1
$info->{"created"} // ""
$info->{"created"}
Truth table0%0/2
A
A= $info->{"created"}
Aresult
11
00
252 @$w{qw(last recreated)} = (0, 1)
253 0 ▶ if defined $w->{created} && $w->{created} ne $created;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w->{"created"} and $w->{"created"} ne $created 0 0 0
Condition0%0/3
defined $w->{"created"} and $w->{"created"} ne $created
!ll&&!rl&&r
000
MC/DC0%0/2
defined $w->{"created"} and $w->{"created"} ne $created
defined $w->{"created"} $w->{"created"} ne $created
Truth table0%0/3
A and B
A= defined $w->{"created"}B= $w->{"created"} ne $created
ABresult
0X0
100
111
254 0 $w->{created} = $created;
255 0 $w->create_consumer($gen, $old);
256 0 });
257 0 1;
258 };
259 0 ▶ $w->retry unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
260 }
261  
262 0 ▶sub create_consumer {
Subroutine create_consumer: not called CC=8 SCAR=42.8
263 0 my ($w, $gen, $old) = @_;
264 0 my $kv = $w->{kv};
265 my %cfg = (ack_policy => 'none', filter_subject => $w->{filter},
266 0 inactive_threshold => 60_000_000_000, num_replicas => 1,
267 mem_storage => JSON::PP::true());
268 0 ▶ if ($w->{recreated}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($w->{'recreated'}) { } 0 0 0
elsif ($w->{'started'} and $w->{'last'} || !$w->{'initial'}) { } 0 0 0
269 0 ▶ $cfg{deliver_policy} = $w->{initial} ? 'last_per_subject' : 'all';
Branch: 1 branch
BranchTrueFalseTotal
$w->{'initial'} ? : 0 0 0
270 ▶ } elsif ($w->{started} && ($w->{last} || !$w->{initial})) {
Condition0%0/6
$w->{"started"} and $w->{"last"} || !$w->{"initial"}
!ll&&!rl&&r
000
$w->{"last"} or not $w->{"initial"}
l!l&&r!l&&!r
000
MC/DC0%0/3
$w->{"started"} and $w->{"last"} || !$w->{"initial"}
$w->{"started"} $w->{"last"} not $w->{"initial"}
Truth table0%0/4
A and B or not(C)
A= $w->{"started"}B= $w->{"last"}C= not $w->{"initial"}
ABCresult
0XX0
1000
11X1
1011
271 0 @cfg{qw(deliver_policy opt_start_seq)} = ('by_start_sequence', $w->{last} + 1);
272 } else {
273 0 ▶ $cfg{deliver_policy} = $w->{initial} ? 'last_per_subject' : 'new';
Branch: 1 branch
BranchTrueFalseTotal
$w->{'initial'} ? : 0 0 0
274 }
275 0 my $ok = eval {
276 0 ▶ $kv->{js}->consumer_create($kv->{stream}, \%cfg, sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
277 0 my ($info, $err) = @_;
278 0 ▶ return unless $gen == $w->{gen};
Branch: 1 branch
BranchTrueFalseTotal
unless $gen == $w->{"gen"} 0 0 0
279 0 ▶ return $w->failed($err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
280 0 delete @$w{qw(backoff recreated)};
281 0 $w->{consumer} = $info->{name};
282 0 ▶ $w->drop_consumer($old) if defined $old;
Branch: 1 branch
BranchTrueFalseTotal
if defined $old 0 0 0
283 # these report the revision before their first delivery
284 $w->{last} = $info->{delivered}{stream_seq} || 0
285 0 ▶ if $cfg{deliver_policy} =~ /\A(?:new|by_start_sequence)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $cfg{"deliver_policy"} =~ /\A(?:new|by_start_sequence)\z/ 0 0 0
Condition0%0/2
$info->{'delivered'}{'stream_seq'} || 0
l!l
00
MC/DC0%0/1
$info->{'delivered'}{'stream_seq'} || 0
$info->{'delivered'}{'stream_seq'}
Truth table0%0/2
A
A= $info->{'delivered'}{'stream_seq'}
Aresult
11
00
286 0 ▶ if (!$w->{started}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($w->{"started"}++) 0 0 0
287 0 ▶ $w->{to_ready} = $info->{num_pending} || 0;
Condition0%0/2
$info->{'num_pending'} || 0
l!l
00
MC/DC0%0/1
$info->{'num_pending'} || 0
$info->{'num_pending'}
Truth table0%0/2
A
A= $info->{'num_pending'}
Aresult
11
00
288 0 ▶ $w->fire_ready unless $w->{to_ready};
Branch: 1 branch
BranchTrueFalseTotal
unless $w->{"to_ready"} 0 0 0
289 }
290 0 $w->pull;
291 0 });
292 0 1;
293 };
294 0 ▶ $w->retry unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
295 }
296  
297 0 ▶sub drop_consumer {
Subroutine drop_consumer: not called CC=1 SCAR=6.9
298 0 my ($w, $name) = @_;
299 0 my $kv = $w->{kv};
300 0 ▶ eval { $kv->{js}->consumer_delete($kv->{stream}, $name, sub {}); 1 };
Subroutine __ANON__: not called CC=1 SCAR=6.9
301 }
302  
303 0 ▶sub fire_ready {
Subroutine fire_ready: not called CC=2 SCAR=17.9
304 0 my ($w) = @_;
305 0 ▶ my $ready = delete $w->{ready} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $ready = delete $w->{"ready"} or return 0 0 0
306 0 $ready->();
307 }
308  
309 0 ▶sub pull {
Subroutine pull: not called CC=3 SCAR=24.8
310 0 my ($w) = @_;
311 0 ▶ return unless defined $w->{consumer};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $w->{"consumer"} 0 0 0
312 0 my $kv = $w->{kv};
313 0 $w->{pending} = $BATCH;
314 0 my $ok = eval {
315 0 $w->nats->publish("$kv->{js}{prefix}.CONSUMER.MSG.NEXT.$kv->{stream}.$w->{consumer}",
316 sprintf('{"batch":%d,"expires":%d}', $BATCH, $EXPIRES * 1_000_000_000),
317 "$w->{inbox}.$w->{gen}");
318 0 1;
319 };
320 0 ▶ return $w->retry unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
321 0 $w->later(deadline => $DEADLINE, 'check');
322 }
323  
324 # a pull ended unanswered or with a status: is its consumer still there?
325 0 ▶sub check {
Subroutine check: not called CC=3 SCAR=24.8
326 0 my ($w, $delay) = @_;
327 0 my ($gen, $kv) = ($w->{gen}, $w->{kv});
328 0 ▶ return unless defined $w->{consumer};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $w->{"consumer"} 0 0 0
329 0 my $ok = eval {
330 0 ▶ $kv->{js}->consumer_info($kv->{stream}, $w->{consumer}, sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
331 0 my (undef, $err) = @_;
332 0 ▶ return unless $gen == $w->{gen};
Branch: 1 branch
BranchTrueFalseTotal
unless $gen == $w->{"gen"} 0 0 0
333 0 ▶ return if defined $err && $err eq 'disconnected';
Branch: 1 branch
BranchTrueFalseTotal
if defined $err and $err eq "disconnected" 0 0 0
Condition0%0/3
defined $err and $err eq "disconnected"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $err and $err eq "disconnected"
defined $err $err eq "disconnected"
Truth table0%0/3
A and B
A= defined $errB= $err eq "disconnected"
ABresult
0X0
100
111
334 0 ▶ return $w->start if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
335 0 ▶ $delay ? $w->later(retry => $delay, 'pull') : $w->pull;
Branch: 1 branch
BranchTrueFalseTotal
$delay ? : 0 0 0
336 0 });
337 0 1;
338 };
339 0 ▶ $w->retry unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
340 }
341  
342 # a drop loses the pull in flight; starting over on the next loop pass
343 # finds the reconnect armed, so the new consumer is made once reconnected
344 0 ▶sub arm_disconnect {
Subroutine arm_disconnect: not called CC=2 SCAR=17.9
345 0 my ($w) = @_;
346 0 ▶ return if defined $w->{watch_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $w->{"watch_id"} 0 0 0
347 0 Scalar::Util::weaken(my $weak = $w);
348 0 ▶ $w->{watch_id} = $w->nats->watch_disconnect(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
349 0 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 0 0
350 0 delete $weak->{watch_id};
351 0 $weak->later(retry => 0, 'start');
352 0 });
353 }
354  
355 0 ▶sub failed {
Subroutine failed: not called CC=4 SCAR=30.0
356 0 my ($w, $err) = @_;
357 0 ▶ return if $err eq 'disconnected'; # the disconnect hook starts over
Branch: 1 branch
BranchTrueFalseTotal
if $err eq "disconnected" 0 0 0
358 # superseded consumers not yet expired fill the stream's limit for a while
359 0 ▶ return $w->retry
Branch: 1 branch
BranchTrueFalseTotal
if $err =~ /\A(?:request timeout|no responders)\z|maximum consumers limit reached/i 0 0 0
360 if $err =~ /\A(?:request timeout|no responders)\z|maximum consumers limit reached/i;
361 0 $w->stop;
362 0 ▶ my $report = $w->{on_error} || sub { warn "EV::Nats::KV watch: $_[0]\n" };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
$w->{'on_error'} || sub { warn "EV::Nats::KV watch: $_[0]\n"; }
l!l&&r!l&&!r
000
MC/DC0%0/2
$w->{'on_error'} || sub { warn "EV::Nats::KV watch: $_[0]\n"; }
$w->{'on_error'} sub { warn "EV::Nats::KV watch: $_[0]\n"; }
Truth table0%0/3
A || B
A= $w->{'on_error'}B= sub { warn "EV::Nats::KV watch: $_[0]\n"; }
ABresult
1X1
011
000
363 0 $report->($err);
364 }
365  
366 0 ▶sub stop {
Subroutine stop: not called CC=2 SCAR=17.9
367 0 my ($w) = @_;
368 0 $w->{stopped} = 1;
369 0 delete @$w{qw(retry deadline)};
370 0 ▶ $w->nats->unwatch_disconnect(delete $w->{watch_id}) if defined $w->{watch_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $w->{"watch_id"} 0 0 0
371 }
372  
373 0 ▶sub DESTROY {
Subroutine DESTROY: not called CC=5 SCAR=34.0
374 0 my ($w) = @_;
375 0 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT' || !$w->{kv};
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" or not $w->{"kv"} 0 0 0
Condition0%0/3
${^GLOBAL_PHASE} eq "DESTRUCT" or not $w->{"kv"}
l!l&&r!l&&!r
000
MC/DC0%0/2
${^GLOBAL_PHASE} eq "DESTRUCT" or not $w->{"kv"}
${^GLOBAL_PHASE} eq "DESTRUCT" not $w->{"kv"}
Truth table0%0/3
A or not(B)
A= ${^GLOBAL_PHASE} eq "DESTRUCT"B= not $w->{"kv"}
ABresult
1X1
011
000
376 0 local $@; # it runs inside the caller's unsubscribe
377 0 ▶ eval { $w->nats->unwatch_disconnect($w->{watch_id}) } if defined $w->{watch_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $w->{"watch_id"} 0 0 0
378 0 ▶ $w->drop_consumer($w->{consumer}) if defined $w->{consumer};
Branch: 1 branch
BranchTrueFalseTotal
if defined $w->{"consumer"} 0 0 0
379 }
380  
381 0 ▶sub op_of {
Subroutine op_of: not called CC=5 SCAR=34.0
382 0 my ($headers) = @_;
383 0 ▶ return 'PUT' unless defined $headers;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $headers 0 0 0
384 0 ▶ return uc $1 if $headers =~ /^KV-Operation:\s*(\S+)/im;
Branch: 1 branch
BranchTrueFalseTotal
if $headers =~ /^KV-Operation:\s*(\S+)/im 0 0 0
385 # a server TTL marker (nats-server 2.11+), as nats.go reads it
386 0 ▶ return $1 eq 'Remove' ? 'DEL' : 'PURGE'
Branch: 2 branches
BranchTrueFalseTotal
if $headers =~ /^Nats-Marker-Reason:\s*(MaxAge|Purge|Remove)/im 0 0 0
$1 eq 'Remove' ? : 0 0 0
387 if $headers =~ /^Nats-Marker-Reason:\s*(MaxAge|Purge|Remove)/im;
388 0 return 'PUT';
389 }
390  
391 0 ▶sub deliver {
Subroutine deliver: not called CC=18 SCAR=58.3
392 0 my ($w, $subject, $payload, $reply, $headers) = @_;
393 0 ▶ if (defined $headers && $headers =~ m{\ANATS/1\.0 (\d{3})}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $headers and $headers =~ m[\ANATS/1\.0 (\d{3})]) 0 0 0
Condition0%0/3
defined $headers and $headers =~ m[\ANATS/1\.0 (\d{3})]
!ll&&!rl&&r
000
MC/DC0%0/2
defined $headers and $headers =~ m[\ANATS/1\.0 (\d{3})]
defined $headers $headers =~ m[\ANATS/1\.0 (\d{3})]
Truth table0%0/3
A and B
A= defined $headersB= $headers =~ m[\ANATS/1\.0 (\d{3})]
ABresult
0X0
100
111
394 0 my $code = $1;
395 0 my ($gen) = $subject =~ /\.(\d+)\z/;
396 0 ▶ return unless $gen && $gen == $w->{gen}; # a replaced consumer's pull
Branch: 1 branch
BranchTrueFalseTotal
unless $gen and $gen == $w->{"gen"} 0 0 0
Condition0%0/3
$gen and $gen == $w->{"gen"}
!ll&&!rl&&r
000
MC/DC0%0/2
$gen and $gen == $w->{"gen"}
$gen $gen == $w->{"gen"}
Truth table0%0/3
A and B
A= $genB= $gen == $w->{"gen"}
ABresult
0X0
100
111
397 0 ▶ return if $code == 100;
Branch: 1 branch
BranchTrueFalseTotal
if $code == 100 0 0 0
398 0 ▶ return $w->pull if $code == 404 || $code == 408;
Branch: 1 branch
BranchTrueFalseTotal
if $code == 404 or $code == 408 0 0 0
Condition0%0/3
$code == 404 or $code == 408
l!l&&r!l&&!r
000
MC/DC0%0/2
$code == 404 or $code == 408
$code == 404 $code == 408
Truth table0%0/3
A or B
A= $code == 404B= $code == 408
ABresult
1X1
011
000
399 0 return $w->check(1);
400 }
401 # $JS.ACK.<stream>.<consumer>.<delivered>.<stream seq>..., with a
402 # domain and account hash ahead of the stream in the 12-token form
403 0 ▶ my @t = split /\./, $reply // '';
Condition0%0/2
$reply // ""
l!l
00
MC/DC0%0/1
$reply // ""
$reply
Truth table0%0/2
A
A= $reply
Aresult
11
00
404 0 ▶ my ($consumer, $seq) = @t == 9 ? @t[3, 5] : @t >= 12 ? @t[5, 7] : return;
Branch: 2 branches
BranchTrueFalseTotal
@t == 9 ? : 0 0 0
@t >= 12 ? : 0 0 0
405 0 ▶ return unless defined $w->{consumer} && $consumer eq $w->{consumer} && $seq > $w->{last};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $w->{"consumer"} and $consumer eq $w->{"consumer"} and $seq > $w->{"last"} 0 0 0
Condition0%0/6
defined $w->{"consumer"} and $consumer eq $w->{"consumer"} and $seq > $w->{"last"}
!ll&&!rl&&r
000
defined $w->{"consumer"} and $consumer eq $w->{"consumer"}
!ll&&!rl&&r
000
MC/DC0%0/3
defined $w->{"consumer"} and $consumer eq $w->{"consumer"} and $seq > $w->{"last"}
defined $w->{"consumer"} $consumer eq $w->{"consumer"} $seq > $w->{"last"}
Truth table0%0/4
A and B and C
A= defined $w->{"consumer"}B= $consumer eq $w->{"consumer"}C= $seq > $w->{"last"}
ABCresult
0XX0
10X0
1100
1111
406 0 $w->{last} = $seq;
407 0 ▶ $w->pull unless --$w->{pending};
Branch: 1 branch
BranchTrueFalseTotal
unless --$w->{"pending"} 0 0 0
408 0 my $ok = eval { $w->{cb}->(substr($subject, length $w->{kv}{prefix}), $payload, op_of($headers)); 1 };
409 0 my $err = $@;
410 0 ▶ $w->fire_ready if $w->{ready} && !--$w->{to_ready};
Branch: 1 branch
BranchTrueFalseTotal
if $w->{"ready"} and not --$w->{"to_ready"} 0 0 0
Condition0%0/3
$w->{"ready"} and not --$w->{"to_ready"}
!ll&&!rl&&r
000
MC/DC0%0/2
$w->{"ready"} and not --$w->{"to_ready"}
$w->{"ready"} not --$w->{"to_ready"}
Truth table0%0/3
A and not(B)
A= $w->{"ready"}B= not --$w->{"to_ready"}
ABresult
0X0
100
111
411 0 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
412 }
413  
414 package EV::Nats::KV;
415  
416 5 1;
417  
418 =head1 NAME
419  
420 EV::Nats::KV - Key-Value store on top of NATS JetStream
421  
422 =head1 SYNOPSIS
423  
424 use EV;
425 use EV::Nats;
426 use EV::Nats::JetStream;
427 use EV::Nats::KV;
428  
429 my $nats = EV::Nats->new(host => '127.0.0.1');
430 my $js = EV::Nats::JetStream->new(nats => $nats);
431 my $kv = EV::Nats::KV->new(js => $js, bucket => 'config');
432  
433 $kv->create_bucket({}, sub {
434 $kv->put('app.setting', 'on', sub {
435 $kv->get('app.setting', sub {
436 my ($val, $err) = @_;
437 print "got: $val\n";
438 });
439 });
440 });
441  
442 # Live updates
443 $kv->watch('app.>', sub {
444 my ($key, $value, $op) = @_;
445 print "$op $key = $value\n";
446 });
447  
448 EV::run;
449  
450 =head1 DESCRIPTION
451  
452 A KV bucket is a JetStream stream named C<KV_E<lt>bucketE<gt>> with
453 subjects C<$KV.E<lt>bucketE<gt>.E<gt>>, history of 1, rollup headers
454 allowed, and deletes denied (purge tombstones are used instead).
455 This module wraps that convention: C<put>/C<get> become single calls
456 that hide the underlying JetStream requests. Reads use Direct Get when
457 the bucket allows it (new buckets do, and C<create_bucket> turns it on
458 for an older one): on a replicated bucket a read can briefly trail a
459 write it follows, as with nats.go.
460  
461 Keys must match C<[-/_=.a-zA-Z0-9]+> without leading or trailing
462 dots, and are validated up front.
463  
464 =head1 METHODS
465  
466 All callbacks fire on the L<EV> loop, not synchronously.
467  
468 =head2 new
469  
470 new(js => $js, bucket => $name, [timeout => $ms])
471  
472 The bucket need not exist yet; call L</create_bucket> first to
473 provision it. C<timeout> defaults to the timeout of C<$js>. The
474 bucket name must match C<[a-zA-Z0-9_-]+>.
475  
476 =head2 get
477  
478 get($key, $cb)
479  
480 Fetch the latest value for C<$key>. Callback: C<($value, $err)>.
481 C<$value> is C<undef> if the key does not exist, or has been deleted
482 or purged (the tombstone is recognised and surfaces as a clean miss).
483  
484 =head2 get_entry
485  
486 get_entry($key, $cb)
487  
488 Like L</get>, but the callback receives
489 C<< { value => $value, revision => $rev } >>, or C<undef> for a missing
490 key; C<revision> is what L</update> expects.
491  
492 =head2 put
493  
494 put($key, $value, $cb)
495  
496 Set C<$key> to C<$value>. Callback: C<($seq, $err)>, where C<$seq> is
497 the JetStream sequence number assigned by the server.
498  
499 =head2 create
500  
501 create($key, $value, [$cb])
502  
503 Like C<put>, but only succeeds if C<$key> is missing. With a callback,
504 deleted/purged keys can be recreated using the tombstone's revision;
505 concurrent creators see a wrong-last-sequence error. Callback: C<($seq, $err)>.
506 Without C<$cb> the headered publish is fire-and-forget.
507  
508 =head2 update
509  
510 update($key, $value, $rev, [$cb])
511  
512 Like C<put>, but only succeeds if C<$key>'s current revision is
513 C<$rev> (compare-and-swap). Callback: C<($seq, $err)>.
514  
515 =head2 delete
516  
517 delete($key, [$cb])
518  
519 Mark C<$key> as deleted by publishing a C<KV-Operation: DEL> tombstone.
520 Callback: C<($ok, $err)>, once the server has stored the tombstone.
521 Without C<$cb> the publish is fire-and-forget.
522  
523 =head2 purge
524  
525 purge($key, [$cb])
526  
527 Like C<delete>, but emits C<Nats-Rollup: sub> too -- the prior history
528 of C<$key> is rolled up and replaced by the tombstone, freeing storage.
529 Callback: C<($ok, $err)>.
530  
531 =head2 keys
532  
533 keys($cb)
534  
535 List all keys currently stored in the bucket. Callback: C<(\@keys, $err)>.
536 Tombstoned keys are not filtered out -- check with C<get> if needed.
537  
538 =head2 watch
539  
540 watch($pattern, $cb, [\%opts])
541  
542 Follow the changes the bucket stores, in order, through an ephemeral
543 JetStream consumer: a write the bucket rejects (a lost C<create> or
544 C<update>) is never reported, and after a reconnect the watch resumes
545 from the last revision it delivered. C<$pattern> is a NATS subject
546 suffix relative to the bucket (e.g. C<E<gt>> for all keys, C<app.E<gt>>
547 for everything under C<app.>); it must be non-empty and contain no
548 whitespace. Callback receives C<($key, $value, $op)> where C<$op> is
549 C<PUT>, C<DEL>, or C<PURGE>. Recognised C<\%opts>:
550  
551 =over
552  
553 =item * C<initial> - deliver each matching key's current value first.
554  
555 =item * C<ready> - called once the watch is live and, with C<initial>,
556 the current values are delivered; changes from then on are reported.
557  
558 =item * C<on_error> - called with the error when the bucket refuses the
559 watch, e.g. a missing bucket; the default warns.
560  
561 =back
562  
563 Returns a subscription id; pass it to L<EV::Nats/unsubscribe> to stop.
564  
565 =head2 create_bucket
566  
567 create_bucket(\%opts, $cb)
568  
569 Provision the underlying stream. Recognised C<\%opts>:
570  
571 =over
572  
573 =item * C<max_history> - default 1; how many revisions to keep per key.
574  
575 =item * C<max_bytes> - bucket-wide storage cap.
576  
577 =item * C<max_age> - per-message TTL in nanoseconds.
578  
579 =item * C<replicas> - cluster replication factor.
580  
581 =back
582  
583 Callback: C<($info, $err)>.
584  
585 =head2 delete_bucket
586  
587 delete_bucket($cb)
588  
589 Tear down the underlying stream. Callback: C<($info, $err)>.
590  
591 =head2 status
592  
593 status($cb)
594  
595 Returns a snapshot hashref:
596  
597 { bucket => $name, values => $count, bytes => $n, history => $h }
598  
599 Callback: C<(\%status, $err)>.
600  
601 =head1 SEE ALSO
602  
603 L<EV::Nats>, L<EV::Nats::JetStream>, L<EV::Nats::ObjectStore>,
604 L<NATS KV documentation|https://docs.nats.io/nats-concepts/jetstream/key-value-store>.
605  
606 =cut
↑ Summary blib/lib/EV/Nats/JetStream.pm »