blib/lib/EV/Nats.pm

filter: Statementstmt 93.4% 43 / 46 Branchbran 75.0% 9 / 12 Conditioncond 33.3% 1 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 87.5% 7 / 8 Podpod 100% 2 / 2 totaltotal 84.9% 62 / 73 CC 8 SCAR 12.7
CC
8
Cov
87%
subscribe_max
6.1
creds_file
4.0
CLONE_SKIP
2.0
CRAP 3.6
« blib/lib/EV/Nats/JetStream.pm ↑ Summary Nats.xs »
1 package EV::Nats;
2 22 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 22 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 22 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 22 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
7 22 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 22 our $VERSION = '0.07';
9 22 XSLoader::load __PACKAGE__, $VERSION;
10 }
11  
12 22 *pub = \&publish;
13 22 *hpub = \&hpublish;
14 22 *sub = \&subscribe;
15 22 *unsub = \&unsubscribe;
16 22 *req = \&request;
17 22 *hreq = \&hrequest;
18  
19 # Threads would clone the raw C pointer into the child, aliasing one
20 # connection from two interpreters; leave the child with undef instead.
21 0 ▶sub CLONE_SKIP { 1 }
Subroutine CLONE_SKIP: not called CC=1 SCAR=6.9
22  
23 6 ▶sub creds_file {
Subroutine creds_file: called CC=4 SCAR=13.9
Pod documented
24 6 my ($self, $path) = @_;
25 6 ▶ open my $fh, '<', $path or die "cannot open creds file $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or die "cannot open creds file ${path}: $!" 5 1 6
26 5 my $content = do { local $/; <$fh> };
27 5 close $fh;
28  
29 # NATS .creds is two PEM-style blocks. Require both BEGIN+END markers.
30 5 my ($jwt) = $content =~
31 /-----BEGIN\s+NATS\s+USER\s+JWT-----\r?\n\s*(\S+)\s*\r?\n-+END\s+NATS\s+USER\s+JWT-+/;
32 5 my ($seed) = $content =~
33 /-----BEGIN\s+USER\s+NKEY\s+SEED-----\r?\n\s*(\S+)\s*\r?\n-+END\s+USER\s+NKEY\s+SEED-+/;
34  
35 5 ▶ die "$path: missing NATS USER JWT block\n" unless defined $jwt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $jwt 2 3 5
36 3 ▶ die "$path: missing USER NKEY SEED block\n" unless defined $seed;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $seed 1 2 3
37  
38 2 $self->jwt($jwt);
39 2 $self->nkey_seed($seed);
40 2 $self;
41 }
42  
43 1 ▶sub subscribe_max {
Subroutine subscribe_max: called CC=5 SCAR=18.0
Pod documented
44 1 my ($self, $subject, $cb, $max_msgs, $queue_group) = @_;
45 1 ▶ my $sid = defined $queue_group
Branch: 1 branch
BranchTrueFalseTotal
defined $queue_group ? : 0 1 1
46 ? $self->subscribe($subject, $cb, $queue_group)
47 : $self->subscribe($subject, $cb);
48 1 ▶ if ($max_msgs && $max_msgs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_msgs and $max_msgs > 0) 1 0 1
Condition33%1/3
$max_msgs and $max_msgs > 0
!ll&&!rl&&r
001
MC/DC0%0/2
$max_msgs and $max_msgs > 0
$max_msgs $max_msgs > 0
Truth table33%1/3
A and B
A= $max_msgsB= $max_msgs > 0
ABresult
0X0
100
111
49 0 ▶ if (!eval { $self->unsubscribe($sid, $max_msgs); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $self->unsubscribe($sid, $max_msgs); 1 } }) 1 0 1
50 1 my $err = $@;
51 1 eval { $self->unsubscribe($sid) };
52 1 die $err;
53 }
54 }
55 0 $sid;
56 }
57  
58 22 1;
59  
60 =head1 NAME
61  
62 EV::Nats - High-performance asynchronous NATS client using EV
63  
64 =head1 SYNOPSIS
65  
66 use EV;
67 use EV::Nats;
68  
69 my $nats = EV::Nats->new(
70 host => '127.0.0.1',
71 port => 4222,
72 reconnect => 1,
73 on_error => sub { warn "nats: $_[0]\n" },
74 on_connect => sub { warn "connected\n" },
75 );
76  
77 # Subscribe (plain or queue group)
78 my $sid = $nats->subscribe('foo.>', sub {
79 my ($subject, $payload, $reply, $headers) = @_;
80 print "[$subject] $payload\n";
81 });
82 $nats->subscribe('work.>', sub { ... }, 'workers');
83  
84 # Publish (fire-and-forget) and headered publish
85 $nats->publish('foo.bar', 'hello world');
86 $nats->hpublish('foo.bar', "NATS/1.0\r\nX-Trace: 42\r\n\r\n", 'body');
87  
88 # Request / reply
89 $nats->request('service.echo', 'ping', sub {
90 my ($response, $err) = @_;
91 die $err if $err;
92 print "reply: $response\n";
93 }, 5000); # 5s timeout
94  
95 $nats->unsubscribe($sid);
96 EV::run;
97  
98 =head1 DESCRIPTION
99  
100 EV::Nats is an async NATS client that implements the protocol directly
101 in XS on top of L<EV>. There is no external C library dependency.
102  
103 =head2 Protocol
104  
105 Full NATS client protocol (PUB, SUB, UNSUB, MSG, HMSG, PING/PONG),
106 including headered publish/receive, wildcard subjects (C<*>, C<E<gt>>),
107 queue groups, and request/reply with an automatic shared inbox
108 subscription.
109  
110 =head2 Connectivity
111  
112 TCP and Unix-domain sockets; TCP keepalive; connect timeout; auto
113 reconnect with exponential backoff and jitter; subscription and
114 auto-unsub state restored on reconnect; cluster failover from INFO
115 C<connect_urls>; lame-duck-mode (leaf node graceful shutdown) callback;
116 graceful C<drain>.
117  
118 =head2 Auth
119  
120 Token, user/pass, NKey/JWT (Ed25519 via OpenSSL).
121  
122 =head2 TLS
123  
124 Optional, auto-detected at build time. STARTTLS-style upgrade after
125 INFO; full hostname verification (DNS or IP literal) by default;
126 opt-out C<tls_skip_verify>; custom CA via C<tls_ca_file>.
127  
128 =head2 Performance
129  
130 Write coalescing via C<ev_prepare> (one C<write()> per loop
131 iteration); O(1) subscription lookup; per-publish allocation-free
132 fast path; explicit C<batch> mode for tight loops; per-connection
133 stats counters.
134  
135 =head2 Higher-level APIs
136  
137 L<EV::Nats::JetStream>, L<EV::Nats::KV>, L<EV::Nats::ObjectStore>.
138  
139 B<Note:> DNS resolution via C<getaddrinfo> is blocking. Use numeric IP
140 addresses for latency-sensitive applications.
141  
142 =head1 METHODS
143  
144 =head2 new
145  
146 new(%options)
147  
148 Create an EV::Nats instance. If C<host> or C<path> is supplied,
149 connection is initiated immediately and the C<on_connect> callback
150 fires once the CONNECT/PONG handshake completes.
151  
152 my $nats = EV::Nats->new(
153 host => '127.0.0.1',
154 port => 4222,
155 reconnect => 1,
156 on_error => sub { warn "nats: $_[0]\n" },
157 on_connect => sub { warn "ready\n" },
158 );
159  
160 =head3 Connection options
161  
162 =over
163  
164 =item host => Str
165  
166 Server hostname (numeric IP recommended; see L</CAVEATS>). When set,
167 connection starts immediately.
168  
169 =item port => Int (default 4222)
170  
171 Server port.
172  
173 =item path => Str
174  
175 Unix-domain socket path. Mutually exclusive with C<host>.
176  
177 =item connect_timeout => Int (ms; 0 = none)
178  
179 How long to wait for the TCP/TLS handshake before giving up.
180  
181 =item keepalive => Int (seconds)
182  
183 If set, enables C<SO_KEEPALIVE> with this idle interval.
184  
185 =item priority => Int (-2 .. +2)
186  
187 L<EV> watcher priority for the I/O watchers on this connection.
188  
189 =item loop => EV::Loop (default C<EV::default_loop>)
190  
191 The L<EV> loop to attach watchers to.
192  
193 =item name => Str
194  
195 Client name advertised in CONNECT.
196  
197 =back
198  
199 =head3 Auth options
200  
201 =over
202  
203 =item user => Str / pass => Str
204  
205 Username/password authentication. JSON-escaped in CONNECT.
206  
207 =item token => Str
208  
209 Token authentication.
210  
211 =item nkey_seed => Str
212  
213 NATS NKey seed (the C<SU...> form). Requires the build to have
214 OpenSSL (C<EV::Nats::HAS_NKEY>). Invalid seeds croak.
215  
216 =item jwt => Str
217  
218 User JWT, paired with C<nkey_seed> for decentralized auth. See also
219 L</creds_file>.
220  
221 =item tls => Bool / tls_ca_file => Str / tls_skip_verify => Bool
222  
223 See L</tls> for details.
224  
225 =back
226  
227 =head3 Protocol options
228  
229 =over
230  
231 =item verbose => Bool (default 0)
232  
233 Request C<+OK> acknowledgments after each command.
234  
235 =item pedantic => Bool (default 0)
236  
237 Server-side strict subject checking.
238  
239 =item echo => Bool (default 1)
240  
241 Receive messages this client itself publishes.
242  
243 =item no_responders => Bool (default 0)
244  
245 Ask the server to send a 503 status reply when a request has no
246 responders, surfaced as the C<"no responders"> error in C<request>.
247  
248 =item inbox_prefix => Str (default C<_INBOX>)
249  
250 Subject prefix for reply inboxes (L</request>, L</new_inbox>), for
251 accounts whose permissions allow replies only under their own prefix.
252 Dot-separated tokens without wildcards, at most 64 bytes.
253  
254 =item ping_interval => Int (ms, default 120000; 0 = disabled)
255  
256 Client-initiated PING interval for keep-alive.
257  
258 =item max_pings_outstanding => Int (default 2)
259  
260 Maximum unacked PINGs before the connection is declared stale.
261  
262 =back
263  
264 =head3 Reconnect options
265  
266 =over
267  
268 =item reconnect => Bool (default 0)
269  
270 Enable automatic reconnection.
271  
272 =item reconnect_delay => Int (ms, default 2000)
273  
274 Initial delay between reconnect attempts; subsequent attempts use
275 exponential backoff with jitter, capped by C<max_reconnect_delay>,
276 floored at 100ms.
277  
278 =item max_reconnect_delay => Int (ms, default 30000)
279  
280 Upper bound on the backoff delay.
281  
282 =item max_reconnect_attempts => Int (default 60; 0 = unlimited)
283  
284 Give up after this many consecutive failures.
285  
286 =item reconnect_buf_size => Int (bytes; default 8 MiB; 0 = unlimited)
287  
288 Cap on the writes queued while disconnected (see L</waiting_count>).
289 A publish past the cap croaks instead of queueing.
290  
291 =back
292  
293 Authorization/authentication failures and a refused TLS requirement
294 are fatal: they are reported via C<on_error> and never retried.
295  
296 =head3 Callback options
297  
298 Callbacks fire on the L<EV> loop, except in three narrow cases:
299 C<on_slow_consumer> fires from the sending call, C<on_disconnect>
300 fires from C<disconnect>, and C<on_error> fires inline when
301 C<new>/C<connect> fail before the loop runs.
302  
303 =over
304  
305 =item on_connect => sub { }
306  
307 Called after the CONNECT/PONG handshake completes.
308  
309 =item on_disconnect => sub { }
310  
311 Called when the connection drops, before any auto-reconnect attempt.
312  
313 =item on_error => sub { my ($err) = @_ }
314  
315 Receives a string. If unset, errors C<croak>.
316  
317 =item on_lame_duck => sub { }
318  
319 Called once when the server signals lame-duck-mode shutdown via
320 INFO C<ldm:true>.
321  
322 =item on_slow_consumer => sub { my ($pending_bytes) = @_ }
323  
324 See L</slow_consumer>.
325  
326 =back
327  
328 =head2 connect
329  
330 connect($host, [$port])
331  
332 Initiate a TCP connection. Port defaults to 4222. Croaks if already
333 connected or in the middle of connecting; otherwise returns
334 immediately, resets the automatic-reconnect attempt budget, and
335 signals completion via C<on_connect>.
336  
337 =head2 connect_unix
338  
339 connect_unix($path)
340  
341 Initiate a Unix-domain-socket connection. Same async semantics as
342 L</connect>.
343  
344 =head2 disconnect
345  
346 Cancel any pending reconnect, drop queued writes, close the socket,
347 and fire C<on_disconnect>. C<intentional_disconnect> is set so no
348 auto-reconnect is scheduled. For a clean shutdown that flushes
349 pending writes first, see L</drain>.
350  
351 =head2 is_connected
352  
353 True if the CONNECT/PONG handshake has completed and no disconnect
354 or reconnect is in progress.
355  
356 =head2 publish
357  
358 publish($subject, [$payload], [$reply_to])
359  
360 Publish a message. Alias: C<pub>. Croaks on an undef or empty
361 subject.
362  
363 $nats->publish('foo', 'hello');
364 $nats->publish('foo', 'hello', 'reply.subject');
365  
366 =head2 hpublish
367  
368 hpublish($subject, $headers, [$payload], [$reply_to])
369  
370 Publish with headers. Alias: C<hpub>. Croaks on an undef or empty
371 subject or headers, or headers not starting with C<NATS/1.0>.
372  
373 $nats->hpublish('foo', "NATS/1.0\r\nX-Key: val\r\n\r\n", 'body');
374  
375 =head2 subscribe
376  
377 subscribe($subject, $cb, [$queue_group])
378  
379 Subscribe to a subject. Returns subscription ID. Alias: C<sub>.
380 Croaks on an undef or empty subject.
381  
382 my $sid = $nats->subscribe('foo.*', sub {
383 my ($subject, $payload, $reply, $headers) = @_;
384 });
385  
386 Queue groups are preserved across reconnects.
387  
388 Callback receives:
389  
390 =over
391  
392 =item C<$subject> - actual subject the message was published to
393  
394 =item C<$payload> - message body
395  
396 =item C<$reply> - reply-to subject (undef if none)
397  
398 =item C<$headers> - raw headers string (only for HMSG)
399  
400 =back
401  
402 =head2 subscribe_max
403  
404 subscribe_max($subject, $cb, $max_msgs, [$queue_group])
405  
406 Convenience: L</subscribe> followed by an auto-unsubscribe after
407 C<$max_msgs> messages have been delivered.
408  
409 =head2 unsubscribe
410  
411 unsubscribe($sid, [$max_msgs])
412  
413 Unsubscribe. With C<$max_msgs>, the server is told to deliver that
414 many more messages and then drop the subscription. The auto-unsub
415 state is restored on reconnect (so the partial count survives a
416 disconnect). Alias: C<unsub>.
417  
418 =head2 request
419  
420 request($subject, $payload, $cb, [$timeout_ms])
421  
422 Request/reply. Uses automatic inbox subscription. Alias: C<req>.
423 Croaks on an undef or empty subject.
424  
425 $nats->request('service', 'data', sub {
426 my ($response, $err) = @_;
427 die $err if $err;
428 print "got: $response\n";
429 }, 5000);
430  
431 Callback receives C<($response, $error)>. For replies that include
432 NATS message headers (HMSG), a third argument C<$headers> with the
433 raw header block is also passed. Error is set on timeout
434 ("request timeout"), no responders ("no responders"), or a dropped
435 connection ("disconnected"). A C<$timeout_ms> of 0 disables the
436 timeout; the callback then waits indefinitely.
437  
438 =head2 hrequest
439  
440 hrequest($subject, $headers, $payload, $cb, [$timeout_ms])
441  
442 Like L</request>, with a header block as for L</hpublish>. Alias:
443 C<hreq>.
444  
445 =head2 drain
446  
447 drain([$cb])
448  
449 Graceful shutdown: sends UNSUB for all subscriptions, flushes pending
450 writes with a PING fence, fires C<$cb> when the server confirms with
451 PONG, then disconnects. No new messages will be received after drain
452 is initiated.
453  
454 C<$cb> receives a single argument: C<undef> on clean drain, or an error
455 string (e.g. C<"disconnected">) if the connection dropped before the
456 PONG arrived. Croaks unless connected. Calling C<drain> again while
457 a drain is in progress croaks if a callback is given, and is
458 otherwise a silent no-op.
459  
460 $nats->drain(sub {
461 my ($err) = @_;
462 die "drain failed: $err" if $err;
463 print "drained, safe to exit\n";
464 });
465  
466 =head2 ping
467  
468 Send PING to server. Croaks unless connected.
469  
470 =head2 flush
471  
472 flush([$cb])
473  
474 Send PING as a write fence; the subsequent PONG guarantees all prior
475 messages were processed by the server. If C<$cb> is given, it is
476 invoked when the PONG arrives. The callback receives a single
477 argument: C<undef> on success, or an error string if the PONG cannot
478 arrive: C<"disconnected"> when the connection (or the attempt the
479 flush waited for) failed, C<"not connected"> when there is no
480 connection and none is being made.
481  
482 While connecting or reconnecting, the PING is sent once the handshake
483 completes, behind the writes queued meanwhile. Without C<$cb>, a flush
484 with no connection and none being made croaks.
485  
486 =head2 creds_file
487  
488 creds_file($path)
489  
490 Read a NATS C<.creds> file and apply the embedded JWT and NKey seed
491 via L</jwt> and L</nkey_seed>. Apply this BEFORE C<connect> so the
492 credentials are available during the CONNECT handshake. Dies if the
493 file is unreadable or missing either the C<USER JWT> or
494 C<USER NKEY SEED> block.
495  
496 =head2 new_inbox
497  
498 Returns a fresh subject suitable for use as a private reply target
499 (C<_INBOX.E<lt>randE<gt>.E<lt>nE<gt>>, under C<inbox_prefix> if set).
500 Each call burns a slot from the same counter that L</request> uses, so
501 manual subscribers must treat the returned subject as opaque.
502  
503 =head2 subscription_count
504  
505 Returns the number of currently-registered subscriptions, including
506 the implicit inbox subscription used by L</request>.
507  
508 =head2 server_info
509  
510 Returns the raw JSON string of the most recent INFO frame received
511 from the server (or C<undef> before the first INFO). Useful for
512 inspecting C<server_id>, C<version>, C<cluster>, C<connect_urls>,
513 etc.
514  
515 =head2 max_payload
516  
517 max_payload([$limit])
518  
519 Server-advertised maximum payload size in bytes. Returns the current
520 value; with an argument, overrides it (publishes above this croak
521 locally before reaching the wire).
522  
523 =head2 waiting_count
524  
525 Number of writes queued locally during connect or reconnect (i.e.
526 C<publish>/C<request> calls made while the connection is not yet
527 ready). They flush when the handshake completes. Queueing past
528 L</reconnect_buf_size> croaks.
529  
530 =head2 skip_waiting
531  
532 Drop all queued writes without sending them. Useful before
533 C<disconnect> if reconnect is enabled and you don't want stale
534 publishes replayed.
535  
536 =head2 reconnect
537  
538 reconnect($enable, [$delay_ms], [$max_attempts])
539  
540 Configure reconnection. C<$delay_ms> and C<$max_attempts> are only
541 written when supplied; omitted args leave the existing value unchanged.
542 Passing a false C<$enable> also cancels a pending reconnect attempt.
543  
544 =head2 reconnect_enabled
545  
546 Returns true if reconnect is enabled.
547  
548 =head2 reconnect_buf_size
549  
550 reconnect_buf_size([$bytes])
551  
552 Get/set the cap on writes queued while disconnected (default 8 MiB;
553 0 disables the cap). May also be passed to L</new>. A publish that
554 would exceed the cap croaks with C<"reconnect buffer full"> instead
555 of queueing.
556  
557 =head2 connect_timeout
558  
559 connect_timeout([$ms])
560  
561 Get/set connect timeout. Read at the start of each connect attempt.
562  
563 =head2 ping_interval
564  
565 ping_interval([$ms])
566  
567 Get/set PING interval. Takes effect immediately on a live
568 connection, including disabling (0) a running timer.
569  
570 =head2 max_pings_outstanding
571  
572 max_pings_outstanding([$num])
573  
574 Get/set max outstanding PINGs. 0 disables the staleness check.
575  
576 =head2 priority
577  
578 priority([$num])
579  
580 Get/set EV watcher priority (-2 .. +2; anything else croaks).
581 Applies to watchers created by the next (re)connect.
582  
583 =head2 keepalive
584  
585 keepalive([$seconds])
586  
587 Get/set TCP keepalive. Applies to sockets created by the next
588 (re)connect.
589  
590 =head2 batch
591  
592 batch($coderef)
593  
594 Batch multiple publishes into a single write. Suppresses per-publish
595 write scheduling; all buffered data is flushed after the coderef returns.
596  
597 $nats->batch(sub {
598 $nats->publish("foo.$_", "msg-$_") for 1..1000;
599 });
600  
601 =head2 slow_consumer
602  
603 slow_consumer($bytes_threshold, [$cb])
604  
605 Enable slow consumer detection. When the write buffer exceeds
606 C<$bytes_threshold> bytes, C<$cb> is called with the current buffer size.
607 A threshold of 0 disables detection. Unlike other callbacks, this one
608 fires synchronously from the call whose write crosses the threshold,
609 once per crossing: it re-arms after the buffer drains back below it.
610 The threshold and callback may also be passed to L</new> as
611 C<slow_consumer_bytes> and C<on_slow_consumer>.
612  
613 $nats->slow_consumer(1024*1024, sub {
614 my ($pending_bytes) = @_;
615 warn "slow consumer: ${pending_bytes}B pending\n";
616 });
617  
618 =head2 on_lame_duck
619  
620 on_lame_duck([$cb])
621  
622 Get/set the lame-duck callback. Fires once when the server signals
623 shutdown (leaf node, rolling restart) via INFO C<ldm:true>. Use this
624 to migrate work to another server before the grace period elapses.
625  
626 =head2 nkey_seed
627  
628 nkey_seed($seed)
629  
630 Set the NKey seed (the C<SU...> base32-encoded form) for Ed25519
631 authentication. Requires the build to have OpenSSL (see
632 L</EV::Nats::HAS_NKEY>). The server nonce from INFO is automatically
633 signed during CONNECT. May also be passed to L</new> as
634 C<nkey_seed =E<gt> ...>. Set before connecting; a change takes
635 effect on the next (re)connect.
636  
637 =head2 jwt
638  
639 jwt($token)
640  
641 Set the user JWT. Combine with L</nkey_seed> for NATS decentralized
642 auth. May also be passed to L</new>. See L</creds_file> for the
643 common case of loading both from a C<.creds> file. Set before
644 connecting; a change takes effect on the next (re)connect.
645  
646 =head2 nkey_generate_user_seed
647  
648 EV::Nats->nkey_generate_user_seed
649  
650 Class method. Returns a fresh, valid NATS User NKey seed (the
651 C<SU...> form). Useful for tests and provisioning scripts that
652 don't have the C<nk> CLI available. Requires C<HAS_NKEY>; croaks
653 otherwise.
654  
655 =head2 nkey_public_from_seed
656  
657 EV::Nats->nkey_public_from_seed($seed)
658  
659 Class method. Derives the matching public key (the C<U...> form)
660 from a User NKey seed. Croaks on an invalid seed. Pair with
661 L</nkey_generate_user_seed> to provision the server with the public
662 key while the client keeps the seed.
663  
664 =head2 tls
665  
666 tls($enable, [$ca_file], [$skip_verify])
667  
668 Configure TLS. Requires OpenSSL at build time (see
669 L</EV::Nats::HAS_TLS>).
670  
671 $nats->tls(1); # system CA
672 $nats->tls(1, '/path/to/ca.pem'); # custom CA
673 $nats->tls(1, undef, 1); # skip verification
674  
675 When verification is enabled (the default), the server certificate's
676 SAN must match the host passed to L</connect>. May also be passed to
677 L</new> as C<tls =E<gt> 1, tls_ca_file =E<gt> $path>. Takes effect on
678 the next (re)connect.
679  
680 =head2 stats
681  
682 Returns a hash of connection counters:
683  
684 my %s = $nats->stats;
685 # ( msgs_in, msgs_out, bytes_in, bytes_out )
686  
687 Outbound counters record accepted writes; messages still queued when
688 the connection drops are counted but never sent.
689  
690 =head2 reset_stats
691  
692 Zero all counters returned by L</stats>.
693  
694 =head2 on_error
695  
696 on_error([$cb])
697  
698 =head2 on_connect
699  
700 on_connect([$cb])
701  
702 =head2 on_disconnect
703  
704 on_disconnect([$cb])
705  
706 Get/set the corresponding callback at runtime. With no argument,
707 returns the current value (or C<undef>). With an argument, replaces
708 it; pass C<undef> to clear.
709  
710 =head1 BUILD-TIME FEATURES
711  
712 =over
713  
714 =item C<EV::Nats::HAS_TLS>
715  
716 True if compiled with OpenSSL (TLS supported).
717  
718 =item C<EV::Nats::HAS_NKEY>
719  
720 True if NKey/JWT signing is available (also requires OpenSSL).
721  
722 =back
723  
724 =head1 BENCHMARKS
725  
726 Measured on Linux with TCP loopback, Perl 5.40, nats-server 2.12,
727 100-byte payloads (C<bench/benchmark.pl>):
728  
729 100K msgs 200K msgs
730 PUB fire-and-forget 4.7M 5.0M msgs/sec
731 PUB + SUB (loopback) 1.8M 1.6M msgs/sec
732 PUB + SUB (8B payload) 2.2M 1.9M msgs/sec
733 REQ/REP (pipelined, 64) 334K msgs/sec
734  
735 Connected-path publish appends directly to the write buffer with no
736 per-message allocation. Write coalescing via C<ev_prepare> batches
737 all publishes per event-loop iteration into a single C<write()> syscall.
738  
739 Run C<perl bench/benchmark.pl> for full results. Set C<BENCH_MESSAGES>,
740 C<BENCH_PAYLOAD>, C<BENCH_HOST>, C<BENCH_PORT> to customize.
741  
742 =head1 NATS PROTOCOL
743  
744 This module implements the NATS client protocol directly in XS.
745 The protocol is text-based with CRLF-delimited control lines and
746 binary payloads.
747  
748 Connection flow: server sends INFO, client sends CONNECT + PING,
749 server responds with PONG to confirm. All subscriptions (including
750 queue groups and auto-unsub state) are automatically restored on
751 reconnect.
752  
753 Request/reply uses a single wildcard inbox subscription
754 (C<_INBOX.E<lt>randomE<gt>.*>) for all requests, with unique
755 suffixes per request.
756  
757 =head1 CAVEATS
758  
759 =over
760  
761 =item * DNS resolution via C<getaddrinfo> is blocking. Use numeric IP
762 addresses for latency-sensitive applications.
763  
764  
765 =item * TLS requires OpenSSL headers at build time (auto-detected).
766  
767 =item * NKey auth requires OpenSSL with Ed25519 support (1.1.1+).
768  
769 =item * The module handles all data as bytes. Encode UTF-8 strings before
770 passing them.
771  
772 =item * Cluster URL discovery (the C<connect_urls> field of INFO) is
773 trusted by default. On failover the client connects to whatever
774 hostnames the previous server advertised, and TLS hostname verification
775 is performed against those names. Use a private CA (C<tls_ca_file>) to
776 restrict which certificates are acceptable, or do not enable C<tls> on
777 public-CA topologies where any holder of a valid cert could redirect
778 clients.
779  
780 =item * Do not use a connection across fork(); create it afterwards
781 instead. The module is not threadsafe, and a connection must be
782 destroyed before the L<EV> loop it was attached to.
783  
784 =back
785  
786 =head1 ENVIRONMENT
787  
788 =over
789  
790 =item TEST_NATS_HOST, TEST_NATS_PORT
791  
792 Set these to run the test suite against a NATS server
793 (default: 127.0.0.1:4222).
794  
795 =back
796  
797 =head1 SEE ALSO
798  
799 L<EV::Nats::JetStream>, L<EV::Nats::KV>, L<EV::Nats::ObjectStore>,
800 L<EV>,
801 L<NATS protocol|https://docs.nats.io/reference/reference-protocols/nats-protocol>,
802 L<nats-server|https://github.com/nats-io/nats-server>.
803  
804 =head1 AUTHOR
805  
806 vividsnow
807  
808 =head1 LICENSE
809  
810 This library is free software; you can redistribute it and/or modify it
811 under the same terms as Perl itself.
812  
813 =cut
« blib/lib/EV/Nats/JetStream.pm ↑ Summary Nats.xs »