blib/lib/EV/Nats/JetStream.pm

filter: Statementstmt 85.2% 144 / 169 Branchbran 86.7% 59 / 68 Conditioncond 55.2% 21 / 38 MC/DCmcdc 36.3% 8 / 22 Subroutinesub 78.0% 32 / 41 Podpod 100% 21 / 21 totaltotal 79.3% 285 / 359 CC 53 SCAR 15.8
CC
53
Cov
81%
consumer_create
12.0
__ANON__
11.1
fetch
9.0
CRAP 4.9
« blib/lib/EV/Nats/ObjectStore.pm ↑ Summary blib/lib/EV/Nats.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.07';
5 5 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use JSON::PP ();
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 $nats = delete $opts{nats} || die "nats connection required";
Condition50%1/2
delete $opts{'nats'} || die('nats connection required')
l!l
290
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
11 29 ▶ my $prefix = delete $opts{prefix} || '$JS.API';
Condition50%1/2
delete $opts{'prefix'} || '$JS.API'
l!l
029
MC/DC0%0/1
delete $opts{'prefix'} || '$JS.API'
delete $opts{'prefix'}
Truth table50%1/2
A
A= delete $opts{'prefix'}
Aresult
11
00
12 29 ▶ my $timeout = delete $opts{timeout} || 5000;
Condition100%2/2
delete $opts{'timeout'} || 5000
l!l
1217
MC/DC100%1/1
delete $opts{'timeout'} || 5000
delete $opts{'timeout'}
Truth table100%2/2
A
A= delete $opts{'timeout'}
Aresult
11
00
13 29 ▶ my $with_status = delete $opts{with_status} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $opts{'with_status'} ? : 2 27 29
14 29 warn "EV::Nats::JetStream::new: unknown option '$_'" for keys %opts;
15 29 bless {
16 nats => $nats,
17 prefix => $prefix,
18 timeout => $timeout,
19 with_status => $with_status,
20 }, $class;
21 }
22  
23 8 ▶sub _api {
Subroutine _api: called CC=2 SCAR=7.1
24 8 my ($self, $subj, $payload, $cb) = @_;
25 8 ▶ $payload //= '';
Condition50%1/2
$payload //= ""
l!l
80
MC/DC0%0/1
$payload //= ""
$payload
Truth table50%1/2
A
A= $payload
Aresult
11
00
26 $self->{nats}->request(
27 "$self->{prefix}.$subj",
28 $payload, $cb, $self->{timeout},
29 8 );
30 }
31  
32 ## Public to sibling modules (KV, ObjectStore, ...) -- not part of the user
33 ## API. Decode a JSON string; returns ($decoded, $error_or_undef) where
34 ## $error already includes a "JSON decode error: ..." prefix when set.
35 ## Gates on $@ so falsy-but-valid JSON (null/0/false/empty-string) doesn't
36 ## get misreported as a decode failure.
37 24 ▶sub decode_json_or_error {
Subroutine decode_json_or_error: called CC=2 SCAR=7.2
Pod documented
38 24 my ($json) = @_;
39 24 local $@;
40 24 my $r = eval { JSON::PP::decode_json($json) };
41 24 ▶ return ($r, undef) unless $@;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ 24 0 24
42 0 return (undef, "JSON decode error: $@");
43 }
44  
45 ## Public to sibling modules. True if a STREAM.MSG.GET response message
46 ## carries a KV-Operation: DEL or PURGE tombstone header. $msg is the
47 ## decoded {message} hash; its {hdrs} field is base64-encoded by the server.
48 19 ▶sub msg_is_tombstone {
Subroutine msg_is_tombstone: called CC=4 SCAR=14.0
Pod documented
49 19 my ($msg) = @_;
50 19 ▶ return 0 unless $msg && $msg->{hdrs};
Branch: 1 branch
BranchTrueFalseTotal
unless $msg and $msg->{"hdrs"} 7 12 19
Condition66%2/3
$msg and $msg->{"hdrs"}
!ll&&!rl&&r
0712
MC/DC50%1/2
$msg and $msg->{"hdrs"}
$msg $msg->{"hdrs"}
Truth table66%2/3
A and B
A= $msgB= $msg->{"hdrs"}
ABresult
0X0
100
111
51 12 require MIME::Base64;
52 12 my $hdrs = MIME::Base64::decode_base64($msg->{hdrs});
53 12 ▶ return $hdrs =~ /KV-Operation:\s*(?:DEL|PURGE)/i ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$hdrs =~ /KV-Operation:\s*(?:DEL|PURGE)/i ? : 0 12 12
54 }
55  
56 8 ▶sub _json_api {
Subroutine _json_api: called CC=2 SCAR=6.9
57 8 my ($self, $subj, $data, $cb) = @_;
58 8 ▶ my $payload = defined $data ? JSON::PP::encode_json($data) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $data ? : 5 3 8
59 8 $self->_api($subj, $payload, $self->_decoded($cb));
60 }
61  
62 ## Public to sibling modules. A request callback that decodes the JSON
63 ## reply for $cb and turns an API error object into an error string.
64 32 ▶sub _decoded {
Subroutine _decoded: called CC=1 SCAR=0.0
65 32 my ($self, $cb) = @_;
66 27 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
67 27 my ($resp, $err) = @_;
68 27 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 20 7 27
69 7 my ($decoded, $derr) = decode_json_or_error($resp);
70 7 ▶ return $cb->(undef, $derr) if $derr;
Branch: 1 branch
BranchTrueFalseTotal
if $derr 0 7 7
71 7 my $e = $decoded->{error};
72 7 ▶ return $cb->(undef, "$e->{description} (code $e->{code})", $self->{with_status} ? $e : ())
Branch: 2 branches
BranchTrueFalseTotal
if $e 5 2 7
$self->{'with_status'} ? : 2 3 5
73 if $e;
74 2 $cb->($decoded, undef);
75 32 };
76 }
77  
78 6 ▶sub _defer {
Subroutine _defer: called CC=1 SCAR=0.0
79 6 my ($nats, $code) = @_;
80 6 my $t;
81 6 ▶ $t = $nats->_timer(0, 0, sub { undef $t; $code->() });
Subroutine __ANON__: called CC=1 SCAR=0.0
82 6 return;
83 }
84  
85 # Stream management
86  
87 0 ▶sub stream_create {
Subroutine stream_create: not called CC=2 SCAR=17.9
Pod documented
88 0 my ($self, $config, $cb) = @_;
89 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
90 0 $self->_json_api("STREAM.CREATE.$name", $config, $cb);
91 }
92  
93 0 ▶sub stream_update {
Subroutine stream_update: not called CC=2 SCAR=17.9
Pod documented
94 0 my ($self, $config, $cb) = @_;
95 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
96 0 $self->_json_api("STREAM.UPDATE.$name", $config, $cb);
97 }
98  
99 1 ▶sub stream_delete {
Subroutine stream_delete: called CC=1 SCAR=0.0
Pod documented
100 1 my ($self, $name, $cb) = @_;
101 1 $self->_json_api("STREAM.DELETE.$name", undef, $cb);
102 }
103  
104 0 ▶sub stream_info {
Subroutine stream_info: not called CC=1 SCAR=6.9
Pod documented
105 0 my ($self, $name, @rest) = @_;
106 0 my $cb = pop @rest;
107 0 my $opts = $rest[0];
108 0 $self->_json_api("STREAM.INFO.$name", $opts, $cb);
109 }
110  
111 0 ▶sub stream_list {
Subroutine stream_list: not called CC=1 SCAR=6.9
Pod documented
112 0 my ($self, $cb) = @_;
113 0 $self->_json_api("STREAM.LIST", undef, $cb);
114 }
115  
116 0 ▶sub stream_purge {
Subroutine stream_purge: not called CC=1 SCAR=6.9
Pod documented
117 0 my ($self, $name, $cb) = @_;
118 0 $self->_json_api("STREAM.PURGE.$name", undef, $cb);
119 }
120  
121 # Fetch a single message from a stream by sequence, last-by-subject, or
122 # next-by-subject. \%opts is passed verbatim as the request body
123 # (server accepts: seq, last_by_subj, next_by_subj).
124 0 ▶sub stream_msg_get {
Subroutine stream_msg_get: not called CC=1 SCAR=6.9
Pod documented
125 0 my ($self, $stream, $opts, $cb) = @_;
126 0 $self->_json_api("STREAM.MSG.GET.$stream", $opts, $cb);
127 }
128  
129 # Consumer management
130  
131 0 ▶sub consumer_create {
Subroutine consumer_create: not called CC=3 SCAR=24.8
Pod documented
132 0 my ($self, $stream, $config, $cb) = @_;
133 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
134 0 ▶ my $subj = $name
Branch: 1 branch
BranchTrueFalseTotal
$name ? : 0 0 0
135 ? "CONSUMER.CREATE.$stream.$name"
136 : "CONSUMER.CREATE.$stream";
137 0 $self->_json_api($subj, { stream_name => $stream, config => $config }, $cb);
138 }
139  
140 0 ▶sub consumer_delete {
Subroutine consumer_delete: not called CC=1 SCAR=6.9
Pod documented
141 0 my ($self, $stream, $consumer, $cb) = @_;
142 0 $self->_json_api("CONSUMER.DELETE.$stream.$consumer", undef, $cb);
143 }
144  
145 2 ▶sub consumer_info {
Subroutine consumer_info: called CC=1 SCAR=0.0
Pod documented
146 2 my ($self, $stream, $consumer, $cb) = @_;
147 2 $self->_json_api("CONSUMER.INFO.$stream.$consumer", undef, $cb);
148 }
149  
150 0 ▶sub consumer_list {
Subroutine consumer_list: not called CC=1 SCAR=6.9
Pod documented
151 0 my ($self, $stream, $cb) = @_;
152 0 $self->_json_api("CONSUMER.LIST.$stream", undef, $cb);
153 }
154  
155 # Publishing with ack
156  
157 8 ▶sub js_publish {
Subroutine js_publish: called CC=1 SCAR=0.0
Pod documented
158 8 my ($self, $subject, $payload, $cb) = @_;
159 8 $self->{nats}->request($subject, $payload, $self->_decoded($cb), $self->{timeout});
160 }
161  
162 7 ▶sub js_publish_h {
Subroutine js_publish_h: called CC=1 SCAR=0.0
Pod documented
163 7 my ($self, $subject, $headers, $payload, $cb) = @_;
164 7 $self->{nats}->hrequest($subject, $headers, $payload, $self->_decoded($cb), $self->{timeout});
165 }
166  
167 # The server serves a pull until it expires even after a cancel or a
168 # reconnect, so the inbox stays open until then and late messages are -NAKed.
169 11 ▶sub fetch {
Subroutine fetch: called CC=9 SCAR=22.0
Pod documented
170 11 my ($self, $stream, $consumer, $opts, $cb) = @_;
171 11 ▶ $opts //= {};
Condition50%1/2
$opts //= {}
l!l
110
MC/DC0%0/1
$opts //= {}
$opts
Truth table50%1/2
A
A= $opts
Aresult
11
00
172 11 ▶ my $batch = $opts->{batch} || 1;
Condition100%2/2
$opts->{'batch'} || 1
l!l
83
MC/DC100%1/1
$opts->{'batch'} || 1
$opts->{'batch'}
Truth table100%2/2
A
A= $opts->{'batch'}
Aresult
11
00
173 11 ▶ my $expires_ns = $opts->{expires} || 5_000_000_000;
Condition100%2/2
$opts->{'expires'} || 5000000000
l!l
65
MC/DC100%1/1
$opts->{'expires'} || 5000000000
$opts->{'expires'}
Truth table100%2/2
A
A= $opts->{'expires'}
Aresult
11
00
174 11 ▶ my $no_wait = $opts->{no_wait} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'no_wait'} ? : 1 10 11
175 11 ▶ my $wait = $no_wait ? $self->{timeout} / 1000 : $expires_ns / 1e9 + 1;
Branch: 1 branch
BranchTrueFalseTotal
$no_wait ? : 1 10 11
176  
177 11 my $nats = $self->{nats};
178 11 my $inbox = $nats->new_inbox;
179  
180 11 my (@messages, $sid, $timer, $watch, $answered, $cancelled);
181 11 my $seen = 0;
182  
183 11 ▶ my $nak = sub { $self->nak($_) for grep { defined $_->{reply} } @_ };
Subroutine __ANON__: called CC=2 SCAR=6.9
184 10 ▶ my $close = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
185 10 ▶ return unless $timer;
Branch: 1 branch
BranchTrueFalseTotal
unless $timer 0 10 10
186 10 $timer->stop;
187 10 undef $timer;
188 10 ▶ $nats->_unwatch_disconnect($watch) if defined $watch;
Branch: 1 branch
BranchTrueFalseTotal
if defined $watch 8 2 10
189 10 undef $watch;
190 10 eval { $nats->unsubscribe($sid) };
191 11 };
192 9 ▶ my $answer = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
193 9 ▶ return if $answered++;
Branch: 1 branch
BranchTrueFalseTotal
if $answered++ 2 7 9
194 7 $cb->(@_);
195 11 };
196  
197 8 ▶ $sid = $nats->subscribe($inbox, sub {
Subroutine __ANON__: called CC=11 SCAR=24.1
198 8 my ($subject, $payload, $reply, $headers) = @_;
199 # Status lines are exactly "NATS/1.0 <3 digits>"; a loose \s+ would
200 # swallow a headered DATA message's first header as a status frame.
201 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
202 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
203 # 100 is a heartbeat; 404/408 end the batch; anything else
204 # (409, 503, 400) is a failure the caller must see.
205 5 ▶ return if $code == 100;
Branch: 1 branch
BranchTrueFalseTotal
if $code == 100 0 5 5
206 5 $close->();
207 5 ▶ return if $answered;
Branch: 1 branch
BranchTrueFalseTotal
if $answered 1 4 5
208 my @status = $self->{with_status}
209 4 ▶ ? ({ code => 0 + $code, description => $desc }) : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->{'with_status'} ? : 2 2 4
210 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
211 if $code == 404 || $code == 408;
212 2 $nak->(splice @messages);
213 2 return $answer->(undef, "fetch failed: $line", @status);
214 }
215 3 my $msg = {
216 subject => $subject,
217 payload => $payload,
218 reply => $reply,
219 headers => $headers,
220 };
221 3 ▶ if ($answered) { $nak->($msg) } else { push @messages, $msg }
Branch: 1 branch
BranchTrueFalseTotal
if ($answered) { } 2 1 3
222 3 ▶ return if ++$seen < $batch;
Branch: 1 branch
BranchTrueFalseTotal
if ++$seen < $batch 2 1 3
223 1 $close->();
224 1 $answer->([splice @messages]);
225 11 });
226  
227 11 my %req = (batch => $batch);
228 # no_wait with an expires is pointless: the server waits the expires
229 # out instead of answering immediately.
230 11 ▶ $req{expires} = $expires_ns unless $no_wait;
Branch: 1 branch
BranchTrueFalseTotal
unless $no_wait 10 1 11
231 11 ▶ $req{no_wait} = JSON::PP::true() if $no_wait;
Branch: 1 branch
BranchTrueFalseTotal
if $no_wait 1 10 11
232 11 my $req_body = JSON::PP::encode_json(\%req);
233 11 my $subj = "$self->{prefix}.CONSUMER.MSG.NEXT.$stream.$consumer";
234 11 ▶ if (!eval { $nats->publish($subj, $req_body, $inbox); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $nats->publish($subj, $req_body, $inbox); 1 } }) 1 10 11
235 1 my $err = $@;
236 1 eval { $nats->unsubscribe($sid) };
237 1 die $err;
238 }
239  
240 4 ▶ $timer = $nats->_timer($wait, 0, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
241 4 $close->();
242 4 $answer->([splice @messages]);
243 10 });
244 2 ▶ $watch = $nats->_watch_disconnect(sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
245 2 undef $watch;
246 2 ▶ return if $answered++;
Branch: 1 branch
BranchTrueFalseTotal
if $answered++ 0 2 2
247 2 my @undelivered = splice @messages;
248 2 ▶ _defer($nats, sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
249 2 $nak->(@undelivered);
250 2 ▶ $cb->(undef, 'disconnected') unless $cancelled;
Branch: 1 branch
BranchTrueFalseTotal
unless $cancelled 2 0 2
251 2 });
252 10 });
253  
254 2 ▶ return bless sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
255 2 $cancelled = 1;
256 2 ▶ return if $answered++;
Branch: 1 branch
BranchTrueFalseTotal
if $answered++ 1 1 2
257 1 $nak->(splice @messages);
258 10 }, 'EV::Nats::JetStream::Fetch';
259 }
260  
261 3 ▶sub ack { $_[0]->_ack_reply($_[1], '+ACK') }
Subroutine ack: called CC=1 SCAR=0.0
Pod documented
262 1 ▶sub in_progress { $_[0]->_ack_reply($_[1], '+WPI') }
Subroutine in_progress: called CC=1 SCAR=0.0
Pod documented
263  
264 6 ▶sub nak {
Subroutine nak: called CC=3 SCAR=11.0
Pod documented
265 6 my ($self, $msg, $delay) = @_;
266 6 ▶ return $self->_ack_reply($msg, '-NAK') unless defined $delay;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $delay 4 2 6
267 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
268 1 $self->_ack_reply($msg, qq{-NAK {"delay":$delay}});
269 }
270  
271 2 ▶sub term {
Subroutine term: called CC=3 SCAR=11.1
Pod documented
272 2 my ($self, $msg, $reason) = @_;
273 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
274 }
275  
276 11 ▶sub _ack_reply {
Subroutine _ack_reply: called CC=5 SCAR=16.1
277 11 my ($self, $msg, $body) = @_;
278 11 ▶ my $reply = ref $msg ? $msg->{reply} : $msg;
Branch: 1 branch
BranchTrueFalseTotal
ref $msg ? : 8 3 11
279 11 ▶ die "message has no reply subject" unless defined $reply && length $reply;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reply and length $reply 1 10 11
Condition66%2/3
defined $reply and length $reply
!ll&&!rl&&r
1010
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
280 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
281 }
282  
283 package EV::Nats::JetStream::Fetch;
284  
285 2 ▶sub cancel { $_[0]->(); return }
Subroutine cancel: called CC=1 SCAR=0.0
286  
287 5 1;
288  
289 =head1 NAME
290  
291 EV::Nats::JetStream - JetStream API client for L<EV::Nats>
292  
293 =head1 SYNOPSIS
294  
295 use EV;
296 use EV::Nats;
297 use EV::Nats::JetStream;
298  
299 my $nats = EV::Nats->new(host => '127.0.0.1');
300 my $js = EV::Nats::JetStream->new(nats => $nats);
301  
302 $js->stream_create({ name => 'ORDERS', subjects => ['orders.>'] },
303 sub {
304 my ($info, $err) = @_;
305 die $err if $err;
306 $js->js_publish('orders.new', '{"item":"widget"}', sub {
307 my ($ack, $err) = @_;
308 print "stored at seq=$ack->{seq}\n";
309 });
310 });
311  
312 EV::run;
313  
314 =head1 DESCRIPTION
315  
316 Thin async wrapper over the JetStream C<$JS.API.*> request/reply
317 endpoints. Each method is a single request whose callback is invoked
318 with the decoded JSON response (or an error string). The C<$nats>
319 connection passed to L</new> handles all the actual I/O.
320  
321 L<EV::Nats::KV> and L<EV::Nats::ObjectStore> build on top of this
322 module -- see those for higher-level KV / blob APIs.
323  
324 =head1 METHODS
325  
326 All methods are async. Callbacks fire on the L<EV> loop.
327  
328 =head2 new
329  
330 new(%opts)
331  
332 my $js = EV::Nats::JetStream->new(
333 nats => $nats,
334 prefix => '$JS.API', # default API subject prefix
335 timeout => 5000, # ms; default 5000
336 with_status => 0, # see below
337 );
338  
339 With C<with_status>, callbacks receive a third argument when the server
340 reported a status: a JetStream API error's object,
341 C<< { code => 404, err_code => 10014, description => 'consumer not found' } >>,
342 or the status that ended a L</fetch>.
343  
344 =head2 Stream management
345  
346 =head3 stream_create
347  
348 stream_create($config, $cb)
349  
350 Create a stream. C<$config> is passed verbatim as the
351 C<StreamConfig> request body. Callback: C<($info, $err)>.
352  
353 =head3 stream_update
354  
355 stream_update($config, $cb)
356  
357 Update an existing stream. Same shape as C<stream_create>.
358  
359 =head3 stream_delete
360  
361 stream_delete($name, $cb)
362  
363 Delete the stream by name.
364  
365 =head3 stream_info
366  
367 stream_info($name, [\%opts], $cb)
368  
369 Fetch stream config + state. Optional C<\%opts> may include
370 C<subjects_filter> (e.g. C<E<gt>>) to populate C<state.subjects>;
371 without it the server omits that field for performance.
372  
373 =head3 stream_list
374  
375 stream_list($cb)
376  
377 List all streams' info.
378  
379 =head3 stream_purge
380  
381 stream_purge($name, $cb)
382  
383 Purge all messages from the stream.
384  
385 =head3 stream_msg_get
386  
387 stream_msg_get($stream, \%opts, $cb)
388  
389 Fetch a single message from C<$stream>. C<\%opts> selects the message:
390  
391 { seq => $n } # by sequence number
392 { last_by_subj => $subject } # latest matching subject
393 { next_by_subj => $subject, seq => $start } # next at-or-after $start
394  
395 The message body and headers in the response are base64-encoded
396 under C<< $resp->{message}{data} >> and C<< $resp->{message}{hdrs} >>.
397  
398 =head2 Consumer management
399  
400 =head3 consumer_create
401  
402 consumer_create($stream, $config, $cb)
403  
404 Create a consumer (push or pull). C<$config> is the consumer config
405 hashref; C<durable_name> makes it durable, C<ack_policy> controls
406 ack semantics.
407  
408 =head3 consumer_delete
409  
410 consumer_delete($stream, $consumer, $cb)
411  
412 =head3 consumer_info
413  
414 consumer_info($stream, $consumer, $cb)
415  
416 =head3 consumer_list
417  
418 consumer_list($stream, $cb)
419  
420 =head2 Publishing and fetching
421  
422 =head3 js_publish
423  
424 js_publish($subject, $payload, $cb)
425  
426 Publish with JetStream acknowledgment. Callback: C<($ack, $err)>
427 where C<$ack> is C<{ stream, seq, duplicate }>.
428  
429 =head3 js_publish_h
430  
431 js_publish_h($subject, $headers, $payload, $cb)
432  
433 Like L</js_publish> but sends C<$headers> (a full C<NATS/1.0> header
434 block, e.g. C<"NATS/1.0\r\nNats-Rollup: sub\r\n\r\n">) with the
435 message, waiting for the PubAck on a one-shot reply inbox. Used for
436 rollup publishes where the acknowledged sequence still matters
437 (L<EV::Nats::ObjectStore> metadata). Callback: C<($ack, $err)>.
438  
439 =head3 fetch
440  
441 my $fetch = fetch($stream, $consumer, \%opts, $cb)
442  
443 Pull messages from a pull-mode consumer. Options:
444  
445 =over
446  
447 =item C<batch>
448  
449 Maximum number of messages to fetch (default 1).
450  
451 =item C<expires>
452  
453 Server-side wait time in nanoseconds (default 5_000_000_000 = 5s).
454 Ignored with C<no_wait>.
455  
456 =item C<no_wait>
457  
458 If true, the server answers at once with what is available; a fetch
459 nobody answers ends after C<timeout>.
460  
461 =back
462  
463 Callback: C<(\@messages, $err)>. Each message is a hashref:
464  
465 {
466 subject => 'orders.new',
467 payload => '...',
468 reply => '$JS.ACK....', # for ack/nak/in_progress/term
469 headers => "...", # raw NATS/1.0 header block, or undef
470 }
471  
472 A 404 (no messages) or 408 (expired) status ends the batch; any other
473 status fails the fetch (C<"fetch failed: NATS/1.0 409 Server Shutdown">)
474 and C<-NAK>s the messages received so far. A dropped connection fails it
475 with C<"disconnected">. With C<with_status> the ending status is passed
476 as C<< { code => 409, description => 'Server Shutdown' } >>. An unknown
477 stream or consumer may get no answer at all: the fetch then ends with an
478 empty batch.
479  
480 Returns a handle: C<< $fetch->cancel >> ends the fetch without calling
481 C<$cb>; messages that still arrive for the pull are C<-NAK>ed.
482  
483 =head3 ack
484  
485 ack($msg)
486  
487 =head3 nak
488  
489 nak($msg, [$delay_ns])
490  
491 Redeliver, after C<$delay_ns> nanoseconds if given.
492  
493 =head3 in_progress
494  
495 in_progress($msg)
496  
497 Extend the message's C<ack_wait>.
498  
499 =head3 term
500  
501 term($msg, [$reason])
502  
503 Never redeliver the message.
504  
505 These take a fetched message hashref or its reply subject, and return
506 true once the acknowledgement is sent or queued, or false when it
507 cannot be (C<$@> holds why). They die on a message without a reply
508 subject.
509  
510 =head1 INTERNAL
511  
512 These are exposed for sibling modules (L<EV::Nats::KV>,
513 L<EV::Nats::ObjectStore>) -- not part of the end-user API and subject
514 to change.
515  
516 =head2 decode_json_or_error
517  
518 decode_json_or_error($json)
519  
520 Decode C<$json>. Returns C<($decoded, $error_or_undef)>; the error
521 string already includes a C<"JSON decode error: "> prefix when set.
522 Gates on C<$@> so falsy-but-valid JSON (C<null>, C<0>, C<false>,
523 empty string) is reported as a clean decode rather than a failure.
524  
525 =head2 msg_is_tombstone
526  
527 msg_is_tombstone($msg)
528  
529 True if a C<STREAM.MSG.GET> response message carries a
530 C<KV-Operation: DEL> or C<KV-Operation: PURGE> header. C<$msg> is the
531 decoded C<message> hash from the response. Used by L<EV::Nats::KV>
532 and L<EV::Nats::ObjectStore> to surface deleted/purged entries as
533 clean misses rather than as malformed payloads.
534  
535 =head1 SEE ALSO
536  
537 L<EV::Nats>, L<EV::Nats::KV>, L<EV::Nats::ObjectStore>,
538 L<JetStream API reference|https://docs.nats.io/reference/reference-protocols/nats_api_reference>.
539  
540 =cut
« blib/lib/EV/Nats/ObjectStore.pm ↑ Summary blib/lib/EV/Nats.pm »