blib/lib/EV/Nats/JetStream.pm

filter: Statementstmt 90.0% 271 / 301 Branchbran 83.1% 128 / 154 Conditioncond 57.6% 64 / 111 MC/DCmcdc 38.4% 25 / 65 Subroutinesub 86.9% 60 / 69 Podpod 55.2% 21 / 38 totaltotal 77.1% 569 / 738 CC 124 SCAR 23.9
CC
124
Cov
82%
__ANON__
110.0
__ANON__
13.1
__ANON__
12.0
CRAP 10.9
« blib/lib/EV/Nats/KV.pm ↑ Summary blib/lib/EV/Nats/ObjectStore.pm »
1 package EV::Nats::JetStream;
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  
7 50 ▶sub new {
Subroutine new: called CC=6 SCAR=17.9
Pod documented
8 50 my ($class, %opts) = @_;
9 50 ▶ my $nats = delete $opts{nats} || die "nats connection required";
Condition50%1/2
delete $opts{'nats'} || die('nats connection required')
l!l
500
MC/DC0%0/1
delete $opts{'nats'} || die('nats connection required')
delete $opts{'nats'}
Truth table50%1/2
A
A= delete $opts{'nats'}
Aresult
11
00
10 50 ▶ my $prefix = delete $opts{prefix} || '$JS.API';
Condition100%2/2
delete $opts{'prefix'} || '$JS.API'
l!l
149
MC/DC100%1/1
delete $opts{'prefix'} || '$JS.API'
delete $opts{'prefix'}
Truth table100%2/2
A
A= delete $opts{'prefix'}
Aresult
11
00
11 50 ▶ my $timeout = delete $opts{timeout} || 5000;
Condition100%2/2
delete $opts{'timeout'} || 5000
l!l
1337
MC/DC100%1/1
delete $opts{'timeout'} || 5000
delete $opts{'timeout'}
Truth table100%2/2
A
A= delete $opts{'timeout'}
Aresult
11
00
12 50 ▶ my $with_status = delete $opts{with_status} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $opts{'with_status'} ? : 3 47 50
13 50 warn "EV::Nats::JetStream::new: unknown option '$_'" for keys %opts;
14 50 bless {
15 nats => $nats,
16 prefix => $prefix,
17 timeout => $timeout,
18 with_status => $with_status,
19 }, $class;
20 }
21  
22 # the same client with another request timeout; the direct-get cache is shared
23 51 ▶sub with_timeout {
Subroutine with_timeout: called CC=4 SCAR=13.9
Pod undocumented
24 51 my ($self, $ms) = @_;
25 51 ▶ return $self if !$ms || $ms == $self->{timeout};
Branch: 1 branch
BranchTrueFalseTotal
if not $ms or $ms == $self->{"timeout"} 47 4 51
Condition66%2/3
not $ms or $ms == $self->{"timeout"}
l!l&&r!l&&!r
4704
MC/DC50%1/2
not $ms or $ms == $self->{"timeout"}
not $ms $ms == $self->{"timeout"}
Truth table66%2/3
not(A) or B
A= not $msB= $ms == $self->{"timeout"}
ABresult
1X1
011
000
26 4 ▶ return bless { %$self, direct => ($self->{direct} //= {}), timeout => $ms }, ref $self;
Condition100%2/2
$self->{"direct"} //= {}
l!l
13
MC/DC100%1/1
$self->{"direct"} //= {}
$self->{"direct"}
Truth table100%2/2
A
A= $self->{"direct"}
Aresult
11
00
27 }
28  
29 5 my $JSON = eval { require Cpanel::JSON::XS; Cpanel::JSON::XS->new }
30 0 ▶ || eval { require JSON::XS; JSON::XS->new }
Condition33%2/6
eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS'->new } } || eval { do { require JSON::XS; 'JSON::XS'->new } } || 'JSON::PP'->new
l!l&&r!l&&!r
500
eval { do { require Cpanel::JSON::XS; "Cpanel::JSON::XS"->new } } or eval { do { require JSON::XS; "JSON::XS"->new } }
l!l&&r!l&&!r
500
MC/DC0%0/3
eval { do { require Cpanel::JSON::XS; 'Cpanel::JSON::XS'->new } } || eval { do { require JSON::XS; 'JSON::XS'->new } } || 'JSON::PP'->new
eval { do { require Cpanel::JSON::XS; "Cpanel::JSON::XS"->new } } eval { do { require JSON::XS; "JSON::XS"->new } } 'JSON::PP'->new
Truth table25%1/4
A or B || C
A= eval { do { require Cpanel::JSON::XS; "Cpanel::JSON::XS"->new } }B= eval { do { require JSON::XS; "JSON::XS"->new } }C= 'JSON::PP'->new
ABCresult
1XX1
01X1
0011
0000
31 || JSON::PP->new;
32 5 $JSON->utf8->allow_nonref;
33  
34 94 ▶sub decode_json_or_error {
Subroutine decode_json_or_error: called CC=2 SCAR=6.9
Pod undocumented
35 94 my ($json) = @_;
36 94 local $@;
37 94 my $r = eval { $JSON->decode($json) };
38 94 ▶ return ($r, undef) unless $@;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ 93 1 94
39 1 return (undef, "JSON decode error: $@");
40 }
41  
42 22 ▶sub msg_is_tombstone {
Subroutine msg_is_tombstone: called CC=4 SCAR=13.9
Pod undocumented
43 22 my ($msg) = @_;
44 22 ▶ return 0 unless $msg && defined $msg->{headers};
Branch: 1 branch
BranchTrueFalseTotal
unless $msg and defined $msg->{"headers"} 7 15 22
Condition66%2/3
$msg and defined $msg->{"headers"}
!ll&&!rl&&r
0715
MC/DC50%1/2
$msg and defined $msg->{"headers"}
$msg defined $msg->{"headers"}
Truth table66%2/3
A and B
A= $msgB= defined $msg->{"headers"}
ABresult
0X0
100
111
45 # or a server TTL marker (nats-server 2.11+), as nats.go reads it
46 15 ▶ return $msg->{headers} =~ /KV-Operation:\s*(?:DEL|PURGE)|Nats-Marker-Reason:\s*(?:MaxAge|Purge|Remove)/i
Branch: 1 branch
BranchTrueFalseTotal
$msg->{'headers'} =~ /KV-Operation:\s*(?:DEL|PURGE)|Nats-Marker-Reason:\s*(?:MaxAge|Purge|Remove)/i ? : 1 14 15
47 ? 1 : 0;
48 }
49  
50 73 ▶sub json_api {
Subroutine json_api: called CC=2 SCAR=6.9
Pod undocumented
51 73 my ($self, $subj, $data, $cb) = @_;
52 73 ▶ my $payload = defined $data ? JSON::PP::encode_json($data) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $data ? : 52 21 73
53 73 $self->{nats}->request("$self->{prefix}.$subj", $payload, $self->decoded($cb), $self->{timeout});
54 }
55  
56 # a request callback decoding the reply for $cb; API errors become strings
57 106 ▶sub decoded {
Subroutine decoded: called CC=1 SCAR=0.0
Pod undocumented
58 106 my ($self, $cb) = @_;
59 95 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
60 95 my ($resp, $err) = @_;
61 95 ▶ return $cb->(undef, $err, $self->err_status($err)) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 26 69 95
62 69 my ($decoded, $derr) = decode_json_or_error($resp);
63 69 ▶ return $cb->(undef, $derr) if $derr;
Branch: 1 branch
BranchTrueFalseTotal
if $derr 0 69 69
64 69 ▶ my $e = ref $decoded eq 'HASH' ? $decoded->{error} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $decoded eq 'HASH' ? : 68 1 69
65 69 ▶ return $cb->(undef, "$e->{description} (code $e->{code})", $self->{with_status} ? $e : ())
Branch: 2 branches
BranchTrueFalseTotal
if $e 5 64 69
$self->{'with_status'} ? : 2 3 5
66 if $e;
67 64 $cb->($decoded, undef);
68 106 };
69 }
70  
71 27 ▶sub err_status {
Subroutine err_status: called CC=3 SCAR=11.1
Pod undocumented
72 27 my ($self, $err) = @_;
73 27 ▶ return $self->{with_status} && $err eq 'no responders' ? ({ code => 503, description => '' }) : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->{'with_status'} && $err eq 'no responders' ? : 1 26 27
Condition66%2/3
$self->{"with_status"} and $err eq "no responders"
!ll&&!rl&&r
2601
MC/DC50%1/2
$self->{"with_status"} and $err eq "no responders"
$self->{"with_status"} $err eq "no responders"
Truth table66%2/3
A and B
A= $self->{"with_status"}B= $err eq "no responders"
ABresult
0X0
100
111
74 }
75  
76 8 ▶sub later {
Subroutine later: called CC=1 SCAR=0.0
Pod undocumented
77 8 my ($nats, $code) = @_;
78 8 my $t;
79 8 ▶ $t = $nats->timer(0, 0, sub { undef $t; $code->() });
Subroutine __ANON__: called CC=1 SCAR=0.0
80 8 return;
81 }
82  
83 # report a croak through $cb on the next loop iteration
84 5 ▶sub fail_later {
Subroutine fail_later: called CC=3 SCAR=11.6
Pod undocumented
85 5 my ($nats, $cb, $err) = @_;
86 5 ▶ $err = 'not connected' unless defined $err && length $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and length $err 0 5 5
Condition33%1/3
defined $err and length $err
!ll&&!rl&&r
005
MC/DC0%0/2
defined $err and length $err
defined $err length $err
Truth table33%1/3
A and B
A= defined $errB= length $err
ABresult
0X0
100
111
87 5 $err =~ s/ at \S+ line \d+.*//s;
88 5 $err =~ s/\n\z//;
89 5 ▶ later($nats, sub { $cb->(undef, $err) });
Subroutine __ANON__: called CC=1 SCAR=0.0
90 }
91  
92 # the subjects under $prefix that hold messages, without the prefix; the
93 # server pages them, 100k per reply
94 2 ▶sub subjects_under {
Subroutine subjects_under: called CC=1 SCAR=0.0
Pod undocumented
95 2 my ($self, $stream, $prefix, $cb) = @_;
96 2 my $plen = length $prefix;
97 6 ▶ $self->offset_pages(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
98 6 my ($offset, $done) = @_;
99 6 ▶ $self->stream_info($stream, { subjects_filter => "$prefix>", ($offset ? (offset => $offset) : ()) }, sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
100 6 my ($info, $err) = @_;
101 6 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 6 6
102 $done->($info, $info->{total},
103 17 map { [ $_, substr $_, $plen ] } grep { substr($_, 0, $plen) eq $prefix }
104 6 ▶ sort keys %{ $info->{state}{subjects} || {} });
Condition50%1/2
$info->{'state'}{'subjects'} || {}
l!l
60
MC/DC0%0/1
$info->{'state'}{'subjects'} || {}
$info->{'state'}{'subjects'}
Truth table50%1/2
A
A= $info->{'state'}{'subjects'}
Aresult
11
00
105 6 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
$offset ? : 3 3 6
106 2 ▶ }, sub { $cb->($_[0], undef) });
Subroutine __ANON__: called CC=1 SCAR=0.0
107 }
108  
109 5 my $RELIST = 3; # list again from the start at most this often, then settle
110  
111 # The API pages a name-sorted list by offset, so an entry created or deleted
112 # ahead of the offset between two requests shifts the next page. Each later
113 # page is asked one entry early: when it does not start with the last entry
114 # held, the list moved and is read again. Past $RELIST, plain offsets finish
115 # it without duplicates. $fetch->($offset, $done) answers
116 # $done->($resp, $total, [$name, $item]...) in server order, or reports an
117 # error itself; $cb gets ([$item...], $last_resp).
118 53 ▶sub offset_pages {
Subroutine offset_pages: called CC=4 SCAR=13.9
Pod undocumented
119 53 my ($self, $fetch, $cb, $st) = @_;
120 53 ▶ $st //= { items => [], seen => {}, relists => 0, offset => undef };
Condition100%2/2
$st //= {"items", [], "seen", {}, "relists", 0, "offset", undef}
l!l
467
MC/DC100%1/1
$st //= {"items", [], "seen", {}, "relists", 0, "offset", undef}
$st
Truth table100%2/2
A
A= $st
Aresult
11
00
121 53 my $items = $st->{items};
122 53 ▶ my $offset = $st->{offset} // (@$items ? @$items - 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
@$items ? : 37 13 50
Condition100%2/2
$st->{"offset"} // (@$items ? @$items - 1 : 0)
l!l
350
MC/DC100%1/1
$st->{"offset"} // (@$items ? @$items - 1 : 0)
$st->{"offset"}
Truth table100%2/2
A
A= $st->{"offset"}
Aresult
11
00
123 53 ▶ $fetch->($offset, sub {
Subroutine __ANON__: called CC=13 SCAR=25.7
124 53 my ($resp, $total, @page) = @_;
125 53 my $had = @$items;
126 53 ▶ if ($had && !defined $st->{offset}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($had and not defined $st->{"offset"}) 37 16 53
Condition100%3/3
$had and not defined $st->{"offset"}
!ll&&!rl&&r
13337
MC/DC100%2/2
$had and not defined $st->{"offset"}
$had not defined $st->{"offset"}
Truth table100%3/3
A and not(B)
A= $hadB= not defined $st->{"offset"}
ABresult
0X0
100
111
127 37 ▶ if (@page && $page[0][0] eq $items->[-1][0]) {
Branch: 2 branches
BranchTrueFalseTotal
if (@page and $page[0][0] eq $items->[-1][0]) { } 30 7 37
elsif ($st->{'relists'}++ < $RELIST) { } 6 1 7
Condition66%2/3
@page and $page[0][0] eq $items->[-1][0]
!ll&&!rl&&r
0730
MC/DC50%1/2
@page and $page[0][0] eq $items->[-1][0]
@page $page[0][0] eq $items->[-1][0]
Truth table66%2/3
A and B
A= @pageB= $page[0][0] eq $items->[-1][0]
ABresult
0X0
100
111
128 30 shift @page;
129 } elsif ($st->{relists}++ < $RELIST) {
130 6 @$items = ();
131 6 %{ $st->{seen} } = ();
132 6 return $self->offset_pages($fetch, $cb, $st);
133 } else {
134 1 $st->{offset} = $offset;
135 }
136 }
137 47 ▶ $st->{offset} += @page if defined $st->{offset};
Branch: 1 branch
BranchTrueFalseTotal
if defined $st->{"offset"} 4 43 47
138 47 push @$items, grep { !$st->{seen}{ $_->[0] }++ } @page;
139 47 ▶ my $more = defined $st->{offset} ? @page && $st->{offset} < ($total // 0)
Branch: 1 branch
BranchTrueFalseTotal
defined $st->{'offset'} ? : 4 43 47
Condition80%8/10
@page and $st->{"offset"} < ($total // 0)
!ll&&!rl&&r
013
$total // 0
l!l
40
@$items > $had and @$items < ($total // 0)
!ll&&!rl&&r
2437
$total // 0
l!l
401
MC/DC50%1/2
@page and $st->{"offset"} < ($total // 0)
@page $st->{"offset"} < ($total // 0)
MC/DC0%0/1
$total // 0
$total
MC/DC100%2/2
@$items > $had and @$items < ($total // 0)
@$items > $had @$items < ($total // 0)
MC/DC100%1/1
$total // 0
$total
Truth table66%2/3
A and B
A= @pageB= $st->{"offset"} < ($total // 0)
ABresult
0X0
100
111
Truth table50%1/2
A
A= $total
Aresult
11
00
Truth table100%3/3
A and B
A= @$items > $hadB= @$items < ($total // 0)
ABresult
0X0
100
111
Truth table100%2/2
A
A= $total
Aresult
11
00
140 : @$items > $had && @$items < ($total // 0);
141 47 ▶ return $self->offset_pages($fetch, $cb, $st) if $more;
Branch: 1 branch
BranchTrueFalseTotal
if $more 40 7 47
142 7 $cb->([ map { $_->[1] } @$items ], $resp);
143 53 });
144 }
145  
146 # remember a stream's allow_direct from any reply carrying its config
147 12 ▶sub noting_direct {
Subroutine noting_direct: called CC=1 SCAR=0.0
Pod undocumented
148 12 my ($self, $name, $cb) = @_;
149 10 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
150 $self->{direct}{$name} = $_[0]{config}{allow_direct} ? 1 : 0
151 10 ▶ if ref $_[0] eq 'HASH' && $_[0]{config};
Branch: 2 branches
BranchTrueFalseTotal
if ref $_[0] eq "HASH" and $_[0]{"config"} 4 6 10
$_[0]{'config'}{'allow_direct'} ? : 2 2 4
Condition100%3/3
ref $_[0] eq "HASH" and $_[0]{"config"}
!ll&&!rl&&r
154
MC/DC100%2/2
ref $_[0] eq "HASH" and $_[0]{"config"}
ref $_[0] eq "HASH" $_[0]{"config"}
Truth table100%3/3
A and B
A= ref $_[0] eq "HASH"B= $_[0]{"config"}
ABresult
0X0
100
111
152 10 $cb->(@_);
153 12 };
154 }
155  
156 0 ▶sub stream_create {
Subroutine stream_create: not called CC=2 SCAR=17.9
Pod documented
157 0 my ($self, $config, $cb) = @_;
158 0 ▶ my $name = $config->{name} || die "stream name required";
Condition0%0/2
$config->{'name'} || die('stream name required')
l!l
00
MC/DC0%0/1
$config->{'name'} || die('stream name required')
$config->{'name'}
Truth table0%0/2
A
A= $config->{'name'}
Aresult
11
00
159 0 $self->json_api("STREAM.CREATE.$name", $config, $self->noting_direct($name, $cb));
160 }
161  
162 0 ▶sub stream_update {
Subroutine stream_update: not called CC=2 SCAR=17.9
Pod documented
163 0 my ($self, $config, $cb) = @_;
164 0 ▶ my $name = $config->{name} || die "stream name required";
Condition0%0/2
$config->{'name'} || die('stream name required')
l!l
00
MC/DC0%0/1
$config->{'name'} || die('stream name required')
$config->{'name'}
Truth table0%0/2
A
A= $config->{'name'}
Aresult
11
00
165 0 $self->json_api("STREAM.UPDATE.$name", $config, $self->noting_direct($name, $cb));
166 }
167  
168 # A KV or ObjectStore bucket made before allow_direct differs from $config
169 # only there: turn it on, keeping the stream's other settings, as nats.go
170 # does. A difference in a field the bucket sets is still refused. The
171 # server leaves false booleans out of the config it reports, and these
172 # limits when unset.
173 5 my %BUCKET_DEFAULT = (max_bytes => -1, max_age => 0, num_replicas => 1);
174  
175 1 ▶sub create_bucket_stream {
Subroutine create_bucket_stream: called CC=1 SCAR=6.2
Pod undocumented
176 1 my ($self, $config, $cb) = @_;
177 0 ▶ $self->stream_create($config, sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
178 0 my ($info, $err) = @_;
179 0 ▶ return $cb->($info, $err) unless $err && $err =~ /already in use with a different configuration/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $err and $err =~ /already in use with a different configuration/i 0 0 0
Condition0%0/3
$err and $err =~ /already in use with a different configuration/i
!ll&&!rl&&r
000
MC/DC0%0/2
$err and $err =~ /already in use with a different configuration/i
$err $err =~ /already in use with a different configuration/i
Truth table0%0/3
A and B
A= $errB= $err =~ /already in use with a different configuration/i
ABresult
0X0
100
111
180 0 ▶ $self->stream_info($config->{name}, sub {
Subroutine __ANON__: not called CC=10 SCAR=47.0
181 0 ▶ my $have = $_[0] && $_[0]{config} or return $cb->(undef, $err);
Branch: 1 branch
BranchTrueFalseTotal
my $have = $_[0] && $_[0]{"config"} or return &$cb(undef, $err) 0 0 0
Condition0%0/3
$_[0] && $_[0]{'config'}
!ll&&!rl&&r
000
MC/DC0%0/2
$_[0] && $_[0]{'config'}
$_[0] $_[0]{'config'}
Truth table0%0/3
A && B
A= $_[0]B= $_[0]{'config'}
ABresult
0X0
100
111
182 0 for my $k (grep { $_ ne 'allow_direct' } keys %$config, keys %BUCKET_DEFAULT) {
183 my ($x, $y) = map {
184 0 ▶ ref($_) eq 'ARRAY' ? join("\0", @$_) : ref($_) || !defined($_) ? ($_ ? 1 : 0) : "$_"
Branch: 3 branches
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 0 0 0
ref $_ || !defined($_) ? : 0 0 0
$_ ? : 0 0 0
Condition0%0/3
ref $_ or not defined $_
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $_ or not defined $_
ref $_ not defined $_
Truth table0%0/3
A or not(B)
A= ref $_B= not defined $_
ABresult
1X1
011
000
185 0 ▶ } map { $_->{$k} // $BUCKET_DEFAULT{$k} } $have, $config;
Condition0%0/3
$_->{$k} // $BUCKET_DEFAULT{$k}
l!l&&r!l&&!r
000
MC/DC0%0/2
$_->{$k} // $BUCKET_DEFAULT{$k}
$_->{$k} $BUCKET_DEFAULT{$k}
Truth table0%0/3
A // B
A= $_->{$k}B= $BUCKET_DEFAULT{$k}
ABresult
1X1
011
000
186 0 ▶ return $cb->(undef, $err) if $x ne $y;
Branch: 1 branch
BranchTrueFalseTotal
if $x ne $y 0 0 0
187 }
188 0 ▶ $self->stream_update({ %$have, allow_direct => JSON::PP::true() }, sub { $cb->(@_[0, 1]) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
189 0 });
190 1 });
191 }
192  
193 1 ▶sub stream_delete {
Subroutine stream_delete: called CC=1 SCAR=0.0
Pod documented
194 1 my ($self, $name, $cb) = @_;
195 1 delete $self->{direct}{$name};
196 1 $self->json_api("STREAM.DELETE.$name", undef, $cb);
197 }
198  
199 12 ▶sub stream_info {
Subroutine stream_info: called CC=1 SCAR=0.0
Pod documented
200 12 my ($self, $name, @rest) = @_;
201 12 my $cb = pop @rest;
202 12 my $opts = $rest[0];
203 12 $self->json_api("STREAM.INFO.$name", $opts, $self->noting_direct($name, $cb));
204 }
205  
206 # $leader: read through the stream leader. A Direct Get may be answered by
207 # a replica that has not applied the latest write yet.
208 79 ▶sub get_msg {
Subroutine get_msg: called CC=6 SCAR=17.9
Pod undocumented
209 79 my ($self, $stream, $opts, $cb, $leader) = @_;
210 79 ▶ return $self->get_msg_using($stream, $opts, 0, $cb) if $leader;
Branch: 1 branch
BranchTrueFalseTotal
if $leader 57 22 79
211 22 my $direct = $self->{direct}{$stream};
212 22 ▶ return $self->get_msg_using($stream, $opts, $direct, $cb) if defined $direct;
Branch: 1 branch
BranchTrueFalseTotal
if defined $direct 2 20 22
213 20 ▶ my $waiting = $self->{direct_wait}{$stream} //= [];
Condition100%2/2
$self->{"direct_wait"}{$stream} //= []
l!l
218
MC/DC100%1/1
$self->{"direct_wait"}{$stream} //= []
$self->{"direct_wait"}{$stream}
Truth table100%2/2
A
A= $self->{"direct_wait"}{$stream}
Aresult
11
00
214 20 push @$waiting, [$opts, $cb];
215 20 ▶ return if @$waiting > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @$waiting > 1 2 18 20
216 18 my $asked = eval {
217 16 ▶ $self->stream_info($stream, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
218 16 my ($info, $err) = @_;
219 16 for (@{ delete $self->{direct_wait}{$stream} }) {
220 18 my ($o, $c) = @$_;
221 18 ▶ $err ? $c->(undef, $err) : $self->get_msg_using($stream, $o, $self->{direct}{$stream}, $c);
Branch: 1 branch
BranchTrueFalseTotal
$err ? : 1 17 18
222 }
223 18 });
224 16 1;
225 };
226 18 ▶ return if $asked;
Branch: 1 branch
BranchTrueFalseTotal
if $asked 16 2 18
227 2 delete $self->{direct_wait}{$stream};
228 2 die $@;
229 }
230  
231 77 ▶sub get_msg_using {
Subroutine get_msg_using: called CC=2 SCAR=6.9
Pod undocumented
232 77 my ($self, $stream, $opts, $direct, $cb) = @_;
233 77 ▶ if ($direct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($direct) 3 74 77
234 3 ▶ return $self->direct_get($stream, $opts, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
235 3 my ($msg, $err) = @_;
236 3 ▶ return $cb->($msg, $err) unless defined $err && $err eq 'no responders';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and $err eq "no responders" 2 1 3
Condition66%2/3
defined $err and $err eq "no responders"
!ll&&!rl&&r
201
MC/DC50%1/2
defined $err and $err eq "no responders"
defined $err $err eq "no responders"
Truth table66%2/3
A and B
A= defined $errB= $err eq "no responders"
ABresult
0X0
100
111
237 1 $self->{direct}{$stream} = 0;
238 1 $self->get_msg_using($stream, $opts, 0, $cb);
239 3 });
240 }
241 74 ▶ $self->json_api("STREAM.MSG.GET.$stream", $opts, sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
242 74 my ($resp, $err) = @_;
243 74 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 42 32 74
244 42 ▶ return $cb->(undef, undef) if $err =~ /no message found|\(code 10037\)/;
Branch: 1 branch
BranchTrueFalseTotal
if $err =~ /no message found|\(code 10037\)/ 41 1 42
245 1 return $cb->(undef, $err);
246 }
247 32 ▶ my $m = $resp->{message} or return $cb->(undef, undef);
Branch: 1 branch
BranchTrueFalseTotal
my $m = $resp->{"message"} or return &$cb(undef, undef) 32 0 32
248 32 require MIME::Base64;
249 $cb->({
250 subject => $m->{subject},
251 seq => $m->{seq},
252 time => $m->{time},
253 data => MIME::Base64::decode_base64($m->{data} // ''),
254 32 ▶ headers => defined $m->{hdrs} ? MIME::Base64::decode_base64($m->{hdrs}) : undef,
Branch: 1 branch
BranchTrueFalseTotal
defined $m->{'hdrs'} ? : 15 17 32
Condition50%1/2
$m->{"data"} // ""
l!l
320
MC/DC0%0/1
$m->{"data"} // ""
$m->{"data"}
Truth table50%1/2
A
A= $m->{"data"}
Aresult
11
00
255 }, undef);
256 74 });
257 }
258  
259 5 ▶sub direct_get {
Subroutine direct_get: called CC=1 SCAR=0.0
Pod documented
260 5 my ($self, $stream, $opts, $cb) = @_;
261 5 ▶ $self->{nats}->request("$self->{prefix}.DIRECT.GET.$stream", JSON::PP::encode_json($opts), sub {
Subroutine __ANON__: called CC=10 SCAR=23.6
262 5 my ($data, $err, $hdr) = @_;
263 5 ▶ return $cb->(undef, $err, $self->err_status($err)) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 1 4 5
264 4 ▶ $hdr //= '';
Condition50%1/2
$hdr //= ""
l!l
40
MC/DC0%0/1
$hdr //= ""
$hdr
Truth table50%1/2
A
A= $hdr
Aresult
11
00
265 4 ▶ if ($hdr =~ m{\ANATS/1\.0 (\d{3})(?: ([^\r\n]*))?}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr =~ m[\ANATS/1\.0 (\d{3})(?: ([^\r\n]*))?]) 2 2 4
266 2 ▶ my ($code, $desc) = ($1, $2 // '');
Condition50%1/2
$2 // ""
l!l
20
MC/DC0%0/1
$2 // ""
$2
Truth table50%1/2
A
A= $2
Aresult
11
00
267 2 ▶ return $cb->(undef, undef) if $code == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $code == 404 1 1 2
268 return $cb->(undef, "direct get failed: NATS/1.0 $code" . (length $desc ? " $desc" : ''),
269 1 ▶ $self->{with_status} ? ({ code => 0 + $code, description => $desc }) : ());
Branch: 2 branches
BranchTrueFalseTotal
length $desc ? : 1 0 1
$self->{'with_status'} ? : 0 1 1
270 }
271 2 ▶ my %nats_hdr = map { /\ANats-([\w-]+):\s*(.*)\z/i ? (lc $1 => $2) : () } split /\r\n/, $hdr;
Branch: 1 branch
BranchTrueFalseTotal
/\ANats-([\w-]+):\s*(.*)\z/i ? : 8 3 11
272 $cb->({
273 subject => $nats_hdr{subject},
274 seq => defined $nats_hdr{sequence} ? 0 + $nats_hdr{sequence} : undef,
275 2 ▶ time => $nats_hdr{'time-stamp'},
Branch: 1 branch
BranchTrueFalseTotal
defined $nats_hdr{'sequence'} ? : 2 0 2
276 data => $data,
277 headers => $hdr,
278 }, undef);
279 5 }, $self->{timeout});
280 }
281  
282 1 ▶sub stream_list {
Subroutine stream_list: called CC=1 SCAR=0.0
Pod documented
283 1 my ($self, $cb) = @_;
284 1 $self->all_pages("STREAM.LIST", 'streams', $cb);
285 }
286  
287 # the API pages its lists (256 per reply): one reply with every page merged
288 5 ▶sub all_pages {
Subroutine all_pages: called CC=1 SCAR=0.1
Pod undocumented
289 5 my ($self, $subj, $key, $cb) = @_;
290 47 ▶ $self->offset_pages(sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
291 47 my ($offset, $done) = @_;
292 47 ▶ $self->json_api($subj, $offset ? { offset => $offset } : undef, sub {
Subroutine __ANON__: called CC=5 SCAR=17.2
293 47 my ($resp, $err) = @_;
294 47 ▶ return $cb->(@_) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 47 47
295 $done->($resp, $resp->{total},
296 47 ▶ map { [ $_->{name} // $_->{config}{name} // '', $_ ] } @{ $resp->{$key} || [] });
Condition57%4/7
($_->{"name"} // $_->{"config"}{"name"}) // ""
l!l
1350
$_->{"name"} // $_->{"config"}{"name"}
l!l&&r!l&&!r
123120
$resp->{$key} || []
l!l
470
MC/DC0%0/2
($_->{"name"} // $_->{"config"}{"name"}) // ""
$_->{"name"} $_->{"config"}{"name"}
MC/DC0%0/1
$resp->{$key} || []
$resp->{$key}
Truth table66%2/3
A // B
A= $_->{"name"}B= $_->{"config"}{"name"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $resp->{$key}
Aresult
11
00
297 47 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
$offset ? : 37 10 47
298 5 ▶ }, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
299 5 my ($items, $resp) = @_;
300 5 $cb->({ %$resp, $key => $items, offset => 0, limit => scalar @$items }, undef);
301 5 });
302 }
303  
304 0 ▶sub stream_purge {
Subroutine stream_purge: not called CC=1 SCAR=6.9
Pod documented
305 0 my ($self, $name, $cb) = @_;
306 0 $self->json_api("STREAM.PURGE.$name", undef, $cb);
307 }
308  
309 0 ▶sub stream_msg_get {
Subroutine stream_msg_get: not called CC=1 SCAR=6.9
Pod documented
310 0 my ($self, $stream, $opts, $cb) = @_;
311 0 $self->json_api("STREAM.MSG.GET.$stream", $opts, $cb);
312 }
313  
314 0 ▶sub consumer_create {
Subroutine consumer_create: not called CC=3 SCAR=24.8
Pod documented
315 0 my ($self, $stream, $config, $cb) = @_;
316 0 ▶ my $name = $config->{durable_name} || $config->{name};
Condition0%0/3
$config->{'durable_name'} || $config->{'name'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$config->{'durable_name'} || $config->{'name'}
$config->{'durable_name'} $config->{'name'}
Truth table0%0/3
A || B
A= $config->{'durable_name'}B= $config->{'name'}
ABresult
1X1
011
000
317 0 ▶ my $subj = $name
Branch: 1 branch
BranchTrueFalseTotal
$name ? : 0 0 0
318 ? "CONSUMER.CREATE.$stream.$name"
319 : "CONSUMER.CREATE.$stream";
320 0 $self->json_api($subj, { stream_name => $stream, config => $config }, $cb);
321 }
322  
323 0 ▶sub consumer_delete {
Subroutine consumer_delete: not called CC=1 SCAR=6.9
Pod documented
324 0 my ($self, $stream, $consumer, $cb) = @_;
325 0 $self->json_api("CONSUMER.DELETE.$stream.$consumer", undef, $cb);
326 }
327  
328 3 ▶sub consumer_info {
Subroutine consumer_info: called CC=1 SCAR=0.0
Pod documented
329 3 my ($self, $stream, $consumer, $cb) = @_;
330 3 $self->json_api("CONSUMER.INFO.$stream.$consumer", undef, $cb);
331 }
332  
333 4 ▶sub consumer_list {
Subroutine consumer_list: called CC=1 SCAR=0.0
Pod documented
334 4 my ($self, $stream, $cb) = @_;
335 4 $self->all_pages("CONSUMER.LIST.$stream", 'consumers', $cb);
336 }
337  
338 10 ▶sub js_publish {
Subroutine js_publish: called CC=1 SCAR=0.0
Pod documented
339 10 my ($self, $subject, $payload, $cb) = @_;
340 10 $self->{nats}->request($subject, $payload, $self->decoded($cb), $self->{timeout});
341 }
342  
343 23 ▶sub js_publish_h {
Subroutine js_publish_h: called CC=1 SCAR=0.0
Pod documented
344 23 my ($self, $subject, $headers, $payload, $cb) = @_;
345 23 $self->{nats}->hrequest($subject, $headers, $payload, $self->decoded($cb), $self->{timeout});
346 }
347  
348 # The server serves a pull until it expires even after a cancel or a
349 # reconnect, so the inbox stays open until then and late messages are -NAKed.
350 13 ▶sub fetch {
Subroutine fetch: called CC=9 SCAR=22.0
Pod documented
351 13 my ($self, $stream, $consumer, $opts, $cb) = @_;
352 13 ▶ $opts //= {};
Condition50%1/2
$opts //= {}
l!l
130
MC/DC0%0/1
$opts //= {}
$opts
Truth table50%1/2
A
A= $opts
Aresult
11
00
353 # numified: JSON::PP sends a string the server rejects for an integer
354 13 ▶ my $batch = 0 + ($opts->{batch} || 1);
Condition100%2/2
$opts->{'batch'} || 1
l!l
103
MC/DC100%1/1
$opts->{'batch'} || 1
$opts->{'batch'}
Truth table100%2/2
A
A= $opts->{'batch'}
Aresult
11
00
355 13 ▶ my $expires_ns = 0 + ($opts->{expires} || 5_000_000_000);
Condition100%2/2
$opts->{'expires'} || 5000000000
l!l
85
MC/DC100%1/1
$opts->{'expires'} || 5000000000
$opts->{'expires'}
Truth table100%2/2
A
A= $opts->{'expires'}
Aresult
11
00
356 13 ▶ my $no_wait = $opts->{no_wait} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'no_wait'} ? : 1 12 13
357 13 ▶ my $wait = $no_wait ? $self->{timeout} / 1000 : $expires_ns / 1e9 + 1;
Branch: 1 branch
BranchTrueFalseTotal
$no_wait ? : 1 12 13
358  
359 13 my $nats = $self->{nats};
360 13 my $inbox = $nats->new_inbox;
361  
362 13 my (@messages, $sid, $timer, $watch, $answered, $cancelled);
363 13 my $seen = 0;
364  
365 13 ▶ my $nak = sub { $self->nak($_) for grep { defined $_->{reply} } @_ };
Subroutine __ANON__: called CC=2 SCAR=6.9
366 12 ▶ my $close = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
367 12 ▶ return unless $timer;
Branch: 1 branch
BranchTrueFalseTotal
unless $timer 0 12 12
368 12 $timer->stop;
369 12 undef $timer;
370 12 ▶ $nats->unwatch_disconnect($watch) if defined $watch;
Branch: 1 branch
BranchTrueFalseTotal
if defined $watch 9 3 12
371 12 undef $watch;
372 12 eval { $nats->unsubscribe($sid) };
373 13 };
374 11 ▶ my $answer = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
375 11 ▶ return if $answered++;
Branch: 1 branch
BranchTrueFalseTotal
if $answered++ 4 7 11
376 7 $cb->(@_);
377 13 };
378  
379 8 ▶ $sid = $nats->subscribe($inbox, sub {
Subroutine __ANON__: called CC=11 SCAR=24.1
380 8 my ($subject, $payload, $reply, $headers) = @_;
381 # Status lines are exactly "NATS/1.0 <3 digits>"; a loose \s+ would
382 # swallow a headered DATA message's first header as a status frame.
383 8 ▶ if ($headers && $headers =~ m{\A(NATS/1\.0 (\d{3})(?: ([^\r\n]*))?)(?:[\r\n]|\z)}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers and $headers =~ m[\A(NATS/1\.0 (\d{3})(?: ([^\r\n]*))?)(?:[\r\n]|\z)]) 5 3 8
Condition66%2/3
$headers and $headers =~ m[\A(NATS/1\.0 (\d{3})(?: ([^\r\n]*))?)(?:[\r\n]|\z)]
!ll&&!rl&&r
305
MC/DC50%1/2
$headers and $headers =~ m[\A(NATS/1\.0 (\d{3})(?: ([^\r\n]*))?)(?:[\r\n]|\z)]
$headers $headers =~ m[\A(NATS/1\.0 (\d{3})(?: ([^\r\n]*))?)(?:[\r\n]|\z)]
Truth table66%2/3
A and B
A= $headersB= $headers =~ m[\A(NATS/1\.0 (\d{3})(?: ([^\r\n]*))?)(?:[\r\n]|\z)]
ABresult
0X0
100
111
384 5 ▶ my ($line, $code, $desc) = ($1, $2, $3 // '');
Condition50%1/2
$3 // ""
l!l
50
MC/DC0%0/1
$3 // ""
$3
Truth table50%1/2
A
A= $3
Aresult
11
00
385 # 100 is a heartbeat; 404/408 end the batch; anything else
386 # (409, 503, 400) is a failure the caller must see.
387 5 ▶ return if $code == 100;
Branch: 1 branch
BranchTrueFalseTotal
if $code == 100 0 5 5
388 5 $close->();
389 5 ▶ return if $answered;
Branch: 1 branch
BranchTrueFalseTotal
if $answered 1 4 5
390 my @status = $self->{with_status}
391 4 ▶ ? ({ code => 0 + $code, description => $desc }) : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->{'with_status'} ? : 2 2 4
392 4 ▶ return $answer->([splice @messages], undef, @status)
Branch: 1 branch
BranchTrueFalseTotal
if $code == 404 or $code == 408 2 2 4
Condition66%2/3
$code == 404 or $code == 408
l!l&&r!l&&!r
202
MC/DC50%1/2
$code == 404 or $code == 408
$code == 404 $code == 408
Truth table66%2/3
A or B
A= $code == 404B= $code == 408
ABresult
1X1
011
000
393 if $code == 404 || $code == 408;
394 2 $nak->(splice @messages);
395 2 return $answer->(undef, "fetch failed: $line", @status);
396 }
397 3 my $msg = {
398 subject => $subject,
399 payload => $payload,
400 reply => $reply,
401 headers => $headers,
402 };
403 3 ▶ if ($answered) { $nak->($msg) } else { push @messages, $msg }
Branch: 1 branch
BranchTrueFalseTotal
if ($answered) { } 2 1 3
404 3 ▶ return if ++$seen < $batch;
Branch: 1 branch
BranchTrueFalseTotal
if ++$seen < $batch 2 1 3
405 1 $close->();
406 1 $answer->([splice @messages]);
407 13 });
408  
409 13 my %req = (batch => $batch);
410 # no_wait with an expires is pointless: the server waits the expires
411 # out instead of answering immediately.
412 13 ▶ $req{expires} = $expires_ns unless $no_wait;
Branch: 1 branch
BranchTrueFalseTotal
unless $no_wait 12 1 13
413 13 ▶ $req{no_wait} = JSON::PP::true() if $no_wait;
Branch: 1 branch
BranchTrueFalseTotal
if $no_wait 1 12 13
414 13 my $req_body = JSON::PP::encode_json(\%req);
415 13 my $subj = "$self->{prefix}.CONSUMER.MSG.NEXT.$stream.$consumer";
416 13 ▶ if (!eval { $nats->publish($subj, $req_body, $inbox); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $nats->publish($subj, $req_body, $inbox); 1 } }) 1 12 13
417 1 my $err = $@;
418 1 eval { $nats->unsubscribe($sid) };
419 1 die $err;
420 }
421  
422 6 ▶ $timer = $nats->timer($wait, 0, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
423 6 $close->();
424 6 $answer->([splice @messages]);
425 12 });
426 3 ▶ $watch = $nats->watch_disconnect(sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
427 3 undef $watch;
428 3 ▶ return if $answered++;
Branch: 1 branch
BranchTrueFalseTotal
if $answered++ 0 3 3
429 3 my @undelivered = splice @messages;
430 3 ▶ later($nats, sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
431 3 $nak->(@undelivered);
432 3 ▶ $cb->(undef, 'disconnected') unless $cancelled;
Branch: 1 branch
BranchTrueFalseTotal
unless $cancelled 3 0 3
433 3 });
434 12 });
435  
436 3 ▶ return bless sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
437 3 $cancelled = 1;
438 3 ▶ return if $answered++;
Branch: 1 branch
BranchTrueFalseTotal
if $answered++ 1 2 3
439 2 $nak->(splice @messages);
440 12 }, 'EV::Nats::JetStream::Fetch';
441 }
442  
443 3 ▶sub ack { $_[0]->ack_reply($_[1], '+ACK') }
Subroutine ack: called CC=1 SCAR=0.0
Pod documented
444 1 ▶sub in_progress { $_[0]->ack_reply($_[1], '+WPI') }
Subroutine in_progress: called CC=1 SCAR=0.0
Pod documented
445  
446 6 ▶sub nak {
Subroutine nak: called CC=3 SCAR=11.0
Pod documented
447 6 my ($self, $msg, $delay) = @_;
448 6 ▶ return $self->ack_reply($msg, '-NAK') unless defined $delay;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $delay 4 2 6
449 2 ▶ die "invalid nak delay '$delay'" unless $delay =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $delay =~ /\A[0-9]+\z/ 1 1 2
450 1 $self->ack_reply($msg, qq{-NAK {"delay":$delay}});
451 }
452  
453 2 ▶sub term {
Subroutine term: called CC=3 SCAR=11.1
Pod documented
454 2 my ($self, $msg, $reason) = @_;
455 2 ▶ $self->ack_reply($msg, defined $reason && length $reason ? "+TERM $reason" : '+TERM');
Branch: 1 branch
BranchTrueFalseTotal
defined $reason && length $reason ? : 1 1 2
Condition66%2/3
defined $reason and length $reason
!ll&&!rl&&r
101
MC/DC50%1/2
defined $reason and length $reason
defined $reason length $reason
Truth table66%2/3
A and B
A= defined $reasonB= length $reason
ABresult
0X0
100
111
456 }
457  
458 3 ▶sub ack_sync {
Subroutine ack_sync: called CC=3 SCAR=11.0
Pod documented
459 3 my ($self, $msg, $cb, $timeout_ms) = @_;
460 3 my $reply = reply_of($msg);
461 3 my $sent = eval {
462 2 ▶ $self->{nats}->request($reply, '+ACK', sub { $cb->($_[1] ? (undef, $_[1]) : (1, undef)) },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[1] ? : 1 1 2
463 3 ▶ $timeout_ms // $self->{timeout});
Condition66%2/3
$timeout_ms // $self->{"timeout"}
l!l&&r!l&&!r
120
MC/DC0%0/2
$timeout_ms // $self->{"timeout"}
$timeout_ms $self->{"timeout"}
Truth table66%2/3
A // B
A= $timeout_msB= $self->{"timeout"}
ABresult
1X1
011
000
464 2 1;
465 };
466 3 ▶ return 1 if $sent;
Branch: 1 branch
BranchTrueFalseTotal
if $sent 2 1 3
467 1 fail_later($self->{nats}, $cb, $@);
468 1 return 0;
469 }
470  
471 14 ▶sub reply_of {
Subroutine reply_of: called CC=4 SCAR=13.9
Pod undocumented
472 14 my ($msg) = @_;
473 14 ▶ my $reply = ref $msg ? $msg->{reply} : $msg;
Branch: 1 branch
BranchTrueFalseTotal
ref $msg ? : 9 5 14
474 14 ▶ die "message has no reply subject" unless defined $reply && length $reply;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reply and length $reply 1 13 14
Condition66%2/3
defined $reply and length $reply
!ll&&!rl&&r
1013
MC/DC50%1/2
defined $reply and length $reply
defined $reply length $reply
Truth table66%2/3
A and B
A= defined $replyB= length $reply
ABresult
0X0
100
111
475 13 return $reply;
476 }
477  
478 11 ▶sub ack_reply {
Subroutine ack_reply: called CC=2 SCAR=6.9
Pod undocumented
479 11 my ($self, $msg, $body) = @_;
480 11 my $reply = reply_of($msg);
481 10 ▶ return eval { $self->{nats}->publish($reply, $body); 1 } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->{'nats'}->publish($reply, $body); 1 } } ? : 9 1 10
482 }
483  
484 package EV::Nats::JetStream::Fetch;
485  
486 3 ▶sub cancel { $_[0]->(); return }
Subroutine cancel: called CC=1 SCAR=0.0
487  
488 5 1;
489  
490 =head1 NAME
491  
492 EV::Nats::JetStream - JetStream API client for L<EV::Nats>
493  
494 =head1 SYNOPSIS
495  
496 use EV;
497 use EV::Nats;
498 use EV::Nats::JetStream;
499  
500 my $nats = EV::Nats->new(host => '127.0.0.1');
501 my $js = EV::Nats::JetStream->new(nats => $nats);
502  
503 $js->stream_create({ name => 'ORDERS', subjects => ['orders.>'] },
504 sub {
505 my ($info, $err) = @_;
506 die $err if $err;
507 $js->js_publish('orders.new', '{"item":"widget"}', sub {
508 my ($ack, $err) = @_;
509 print "stored at seq=$ack->{seq}\n";
510 });
511 });
512  
513 EV::run;
514  
515 =head1 DESCRIPTION
516  
517 Thin async wrapper over the JetStream C<$JS.API.*> request/reply
518 endpoints. Each method is a single request whose callback is invoked
519 with the decoded JSON response (or an error string). The C<$nats>
520 connection passed to L</new> handles all the actual I/O.
521  
522 L<EV::Nats::KV> and L<EV::Nats::ObjectStore> build on top of this
523 module -- see those for higher-level KV / blob APIs.
524  
525 =head1 METHODS
526  
527 All methods are async. Callbacks fire on the L<EV> loop.
528  
529 =head2 new
530  
531 new(%opts)
532  
533 my $js = EV::Nats::JetStream->new(
534 nats => $nats,
535 prefix => '$JS.API', # default API subject prefix
536 timeout => 5000, # ms; default 5000
537 with_status => 0, # see below
538 );
539  
540 With C<with_status>, callbacks receive a third argument when the server
541 reported a status: a JetStream API error's object,
542 C<< { code => 404, err_code => 10014, description => 'consumer not found' } >>,
543 C<< { code => 503, description => '' } >> for C<"no responders">, or the status that ended
544 a L</fetch>.
545  
546 =head2 Stream management
547  
548 =head3 stream_create
549  
550 stream_create($config, $cb)
551  
552 Create a stream. C<$config> is passed verbatim as the
553 C<StreamConfig> request body. Callback: C<($info, $err)>.
554  
555 =head3 stream_update
556  
557 stream_update($config, $cb)
558  
559 Update an existing stream. Same shape as C<stream_create>.
560  
561 =head3 stream_delete
562  
563 stream_delete($name, $cb)
564  
565 Delete the stream by name.
566  
567 =head3 stream_info
568  
569 stream_info($name, [\%opts], $cb)
570  
571 Fetch stream config + state. Optional C<\%opts> may include
572 C<subjects_filter> (e.g. C<E<gt>>) to populate C<state.subjects>;
573 without it the server omits that field for performance.
574  
575 =head3 stream_list
576  
577 stream_list($cb)
578  
579 List all streams' info, every page of the API's reply merged.
580  
581 =head3 stream_purge
582  
583 stream_purge($name, $cb)
584  
585 Purge all messages from the stream.
586  
587 =head3 stream_msg_get
588  
589 stream_msg_get($stream, \%opts, $cb)
590  
591 Fetch a single message from C<$stream>. C<\%opts> selects the message:
592  
593 { seq => $n } # by sequence number
594 { last_by_subj => $subject } # latest matching subject
595 { next_by_subj => $subject, seq => $start } # next at-or-after $start
596  
597 The message body and headers in the response are base64-encoded
598 under C<< $resp->{message}{data} >> and C<< $resp->{message}{hdrs} >>,
599 so a message larger than about 3/4 of C<max_payload> cannot be read
600 this way; see L</direct_get>.
601  
602 =head3 direct_get
603  
604 direct_get($stream, \%opts, $cb)
605  
606 Fetch a single message with Direct Get, from a stream created with
607 C<< allow_direct => true >>. Any replica may answer, so on a replicated
608 stream the result can trail a write that came just before.
609 C<\%opts> selects the message as for L</stream_msg_get>. Callback:
610 C<($msg, $err)>, with C<$msg>
611  
612 {
613 subject => 'orders.new',
614 seq => 42,
615 time => '2026-11-26T11:36:54.412Z',
616 data => '...', # raw bytes
617 headers => "...", # raw NATS/1.0 block, Nats-* headers included
618 }
619  
620 or C<undef> for a missing message.
621  
622 =head2 Consumer management
623  
624 =head3 consumer_create
625  
626 consumer_create($stream, $config, $cb)
627  
628 Create a consumer (push or pull). C<$config> is the consumer config
629 hashref; C<durable_name> makes it durable, C<ack_policy> controls
630 ack semantics.
631  
632 =head3 consumer_delete
633  
634 consumer_delete($stream, $consumer, $cb)
635  
636 =head3 consumer_info
637  
638 consumer_info($stream, $consumer, $cb)
639  
640 =head3 consumer_list
641  
642 consumer_list($stream, $cb)
643  
644 Every page of the API's reply merged, as for L</stream_list>.
645  
646 =head2 Publishing and fetching
647  
648 =head3 js_publish
649  
650 js_publish($subject, $payload, $cb)
651  
652 Publish with JetStream acknowledgment. Callback: C<($ack, $err)>
653 where C<$ack> is C<{ stream, seq, duplicate }>.
654  
655 =head3 js_publish_h
656  
657 js_publish_h($subject, $headers, $payload, $cb)
658  
659 Like L</js_publish> but sends C<$headers> (a full C<NATS/1.0> header
660 block, e.g. C<"NATS/1.0\r\nNats-Rollup: sub\r\n\r\n">) with the
661 message, waiting for the PubAck on a one-shot reply inbox. Used for
662 rollup publishes where the acknowledged sequence still matters
663 (L<EV::Nats::ObjectStore> metadata). Callback: C<($ack, $err)>.
664  
665 =head3 fetch
666  
667 my $fetch = fetch($stream, $consumer, \%opts, $cb)
668  
669 Pull messages from a pull-mode consumer. Options:
670  
671 =over
672  
673 =item C<batch>
674  
675 Maximum number of messages to fetch (default 1).
676  
677 =item C<expires>
678  
679 Server-side wait time in nanoseconds (default 5_000_000_000 = 5s).
680 Ignored with C<no_wait>.
681  
682 =item C<no_wait>
683  
684 If true, the server answers at once with what is available; a fetch
685 nobody answers ends after C<timeout>.
686  
687 =back
688  
689 Callback: C<(\@messages, $err)>. Each message is a hashref:
690  
691 {
692 subject => 'orders.new',
693 payload => '...',
694 reply => '$JS.ACK....', # for ack/nak/in_progress/term
695 headers => "...", # raw NATS/1.0 header block, or undef
696 }
697  
698 A 404 (no messages) or 408 (expired) status ends the batch; any other
699 status fails the fetch (C<"fetch failed: NATS/1.0 409 Server Shutdown">)
700 and C<-NAK>s the messages received so far. A dropped connection fails it
701 with C<"disconnected">. With C<with_status> the ending status is passed
702 as C<< { code => 409, description => 'Server Shutdown' } >>. An unknown
703 stream or consumer may get no answer at all: the fetch then ends with an
704 empty batch.
705  
706 Returns a handle: C<< $fetch->cancel >> ends the fetch without calling
707 C<$cb>; messages that still arrive for the pull before it expires are
708 C<-NAK>ed.
709  
710 =head3 ack
711  
712 ack($msg)
713  
714 =head3 nak
715  
716 nak($msg, [$delay_ns])
717  
718 Redeliver, after C<$delay_ns> nanoseconds if given.
719  
720 =head3 in_progress
721  
722 in_progress($msg)
723  
724 Extend the message's C<ack_wait>.
725  
726 =head3 term
727  
728 term($msg, [$reason])
729  
730 Never redeliver the message.
731  
732 These take a fetched message hashref or its reply subject, and return
733 true once the acknowledgement is sent or queued, or false when it
734 cannot be (C<$@> holds why). They die on a message without a reply
735 subject.
736  
737 =head3 ack_sync
738  
739 ack_sync($msg, $cb, [$timeout_ms])
740  
741 Acknowledge and wait for the server to confirm it applied the ack.
742 Callback: C<($ok, $err)>; C<$err> is C<"request timeout"> when nothing
743 answers (e.g. a server in lame duck mode, or a consumer that is gone),
744 C<"no responders"> for a gone consumer when the connection has
745 C<no_responders> enabled, or C<"disconnected">. C<$timeout_ms> defaults
746 to the JetStream C<timeout>.
747  
748 =head1 SEE ALSO
749  
750 L<EV::Nats>, L<EV::Nats::KV>, L<EV::Nats::ObjectStore>,
751 L<JetStream API reference|https://docs.nats.io/reference/reference-protocols/nats_api_reference>.
752  
753 =cut
« blib/lib/EV/Nats/KV.pm ↑ Summary blib/lib/EV/Nats/ObjectStore.pm »