blib/lib/EV/Nats.pm

filter: Statementstmt 89.1% 41 / 46 Branchbran 80.0% 8 / 10 Conditioncond 33.3% 1 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 87.5% 7 / 8 Podpod 100% 2 / 2 totaltotal 83.1% 59 / 71 CC 7 SCAR 11.6
CC
7
Cov
85%
subscribe_max
5.4
creds_file
4.0
CLONE_SKIP
2.0
CRAP 3.2
« blib/lib/EV/Nats/ObjectStore.pm ↑ Summary Nats.xs »
1 package EV::Nats;
2 21 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 21 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 21 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 21 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
7 21 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 21 our $VERSION = '0.09';
9 21 XSLoader::load __PACKAGE__, $VERSION;
10 }
11  
12 21 *pub = \&publish;
13 21 *hpub = \&hpublish;
14 21 *sub = \&subscribe;
15 21 *unsub = \&unsubscribe;
16 21 *req = \&request;
17 21 *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 2 ▶sub subscribe_max {
Subroutine subscribe_max: called CC=4 SCAR=16.9
Pod documented
44 2 my ($self, $subject, $cb, $max_msgs, $queue_group) = @_;
45 2 my $sid = $self->subscribe($subject, $cb, $queue_group);
46 2 ▶ if ($max_msgs && $max_msgs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_msgs and $max_msgs > 0) 2 0 2
Condition33%1/3
$max_msgs and $max_msgs > 0
!ll&&!rl&&r
002
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
47 2 ▶ if (!eval { $self->unsubscribe($sid, $max_msgs); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $self->unsubscribe($sid, $max_msgs); 1 } }) 0 2 2
48 0 my $err = $@;
49 0 eval { $self->unsubscribe($sid) };
50 0 die $err;
51 }
52 }
53 2 $sid;
54 }
55  
56 21 1;
57  
58 =head1 NAME
59  
60 EV::Nats - High-performance asynchronous NATS client using EV
61  
62 =head1 SYNOPSIS
63  
64 use EV;
65 use EV::Nats;
66  
67 my $nats = EV::Nats->new(
68 host => '127.0.0.1',
69 port => 4222,
70 reconnect => 1,
71 on_error => sub { warn "nats: $_[0]\n" },
72 on_connect => sub { warn "connected\n" },
73 );
74  
75 # Subscribe (plain or queue group)
76 my $sid = $nats->subscribe('foo.>', sub {
77 my ($subject, $payload, $reply, $headers) = @_;
78 print "[$subject] $payload\n";
79 });
80 $nats->subscribe('work.>', sub { ... }, 'workers');
81  
82 # Publish (fire-and-forget) and headered publish
83 $nats->publish('foo.bar', 'hello world');
84 $nats->hpublish('foo.bar', "NATS/1.0\r\nX-Trace: 42\r\n\r\n", 'body');
85  
86 # Request / reply
87 $nats->request('service.echo', 'ping', sub {
88 my ($response, $err) = @_;
89 die $err if $err;
90 print "reply: $response\n";
91 }, 5000); # 5s timeout
92  
93 $nats->unsubscribe($sid);
94 EV::run;
95  
96 =head1 DESCRIPTION
97  
98 EV::Nats is an async NATS client that implements the protocol directly
99 in XS on top of L<EV>. There is no external C library dependency.
100  
101 =head2 Protocol
102  
103 Full NATS client protocol (PUB, SUB, UNSUB, MSG, HMSG, PING/PONG),
104 including headered publish/receive, wildcard subjects (C<*>, C<E<gt>>),
105 queue groups, and request/reply with an automatic shared inbox
106 subscription.
107  
108 =head2 Connectivity
109  
110 TCP and Unix-domain sockets; TCP keepalive; connect timeout; auto
111 reconnect with exponential backoff and jitter; subscription and
112 auto-unsub state restored on reconnect; cluster failover from INFO
113 C<connect_urls>; lame-duck-mode (leaf node graceful shutdown) callback;
114 graceful C<drain>.
115  
116 =head2 Auth
117  
118 Token, user/pass, NKey/JWT (Ed25519 via OpenSSL).
119  
120 =head2 TLS
121  
122 Optional, auto-detected at build time. STARTTLS-style upgrade after
123 INFO; full hostname verification (DNS or IP literal) by default;
124 opt-out C<tls_skip_verify>; custom CA via C<tls_ca_file>.
125  
126 =head2 Performance
127  
128 Write coalescing via C<ev_prepare> (one C<write()> per loop
129 iteration); O(1) subscription lookup; per-publish allocation-free
130 fast path; explicit C<batch> mode for tight loops; per-connection
131 stats counters.
132  
133 =head2 Higher-level APIs
134  
135 L<EV::Nats::JetStream>, L<EV::Nats::KV>, L<EV::Nats::ObjectStore>.
136  
137 =head1 METHODS
138  
139 =head2 new
140  
141 new(%options)
142  
143 Create an EV::Nats instance. If C<host> or C<path> is supplied,
144 connection is initiated immediately and the C<on_connect> callback
145 fires once the CONNECT/PONG handshake completes.
146  
147 my $nats = EV::Nats->new(
148 host => '127.0.0.1',
149 port => 4222,
150 reconnect => 1,
151 on_error => sub { warn "nats: $_[0]\n" },
152 on_connect => sub { warn "ready\n" },
153 );
154  
155 =head3 Connection options
156  
157 =over
158  
159 =item host => Str
160  
161 Server hostname (numeric IP recommended; see L</CAVEATS>). When set,
162 connection starts immediately.
163  
164 =item port => Int (default 4222)
165  
166 Server port.
167  
168 =item path => Str
169  
170 Unix-domain socket path. Mutually exclusive with C<host>.
171  
172 =item connect_timeout => Int (ms; 0 = none)
173  
174 How long to wait for the TCP/TLS handshake before giving up.
175  
176 =item keepalive => Int (seconds)
177  
178 If set, enables C<SO_KEEPALIVE> with this idle interval.
179  
180 =item priority => Int (-2 .. +2)
181  
182 L<EV> watcher priority for the I/O watchers on this connection.
183  
184 =item loop => EV::Loop (default C<EV::default_loop>)
185  
186 The L<EV> loop to attach watchers to.
187  
188 =item name => Str
189  
190 Client name advertised in CONNECT.
191  
192 =back
193  
194 =head3 Auth options
195  
196 =over
197  
198 =item user => Str / pass => Str
199  
200 Username/password authentication. JSON-escaped in CONNECT.
201  
202 =item token => Str
203  
204 Token authentication.
205  
206 =item nkey_seed => Str
207  
208 NATS NKey seed (the C<SU...> form). Requires the build to have
209 OpenSSL (C<EV::Nats::HAS_NKEY>). Invalid seeds croak.
210  
211 =item jwt => Str
212  
213 User JWT, paired with C<nkey_seed> for decentralized auth. See also
214 L</creds_file>.
215  
216 =item tls => Bool / tls_ca_file => Str / tls_skip_verify => Bool
217  
218 See L</tls> for details.
219  
220 =back
221  
222 =head3 Protocol options
223  
224 =over
225  
226 =item verbose => Bool (default 0)
227  
228 Request C<+OK> acknowledgments after each command.
229  
230 =item pedantic => Bool (default 0)
231  
232 Server-side strict subject checking.
233  
234 =item echo => Bool (default 1)
235  
236 Receive messages this client itself publishes.
237  
238 =item no_responders => Bool (default 0)
239  
240 Ask the server to send a 503 status reply when a request has no
241 responders, surfaced as the C<"no responders"> error in C<request>.
242  
243 =item inbox_prefix => Str (default C<_INBOX>)
244  
245 Subject prefix for reply inboxes (L</request>, L</new_inbox>), for
246 accounts whose permissions allow replies only under their own prefix.
247 Dot-separated tokens without wildcards, at most 64 bytes.
248  
249 =item ping_interval => Int (ms, default 120000; 0 = disabled)
250  
251 Client-initiated PING interval for keep-alive.
252  
253 =item max_pings_outstanding => Int (default 2)
254  
255 Maximum unacked PINGs before the connection is declared stale.
256  
257 =back
258  
259 =head3 Reconnect options
260  
261 =over
262  
263 =item reconnect => Bool (default 0)
264  
265 Enable automatic reconnection. A failed initial connect is retried the
266 same way, so a client may start before its server.
267  
268 =item reconnect_delay => Int (ms, default 2000)
269  
270 Initial delay between reconnect attempts; subsequent attempts use
271 exponential backoff with jitter, capped by C<max_reconnect_delay>,
272 floored at 100ms.
273  
274 =item max_reconnect_delay => Int (ms, default 30000)
275  
276 Upper bound on the backoff delay.
277  
278 =item max_reconnect_attempts => Int (default 60; 0 = unlimited)
279  
280 Give up after this many consecutive failures.
281  
282 =item reconnect_buf_size => Int (bytes; default 8 MiB; 0 = unlimited)
283  
284 Cap on the writes queued while disconnected (see L</waiting_count>).
285 A publish past the cap croaks instead of queueing.
286  
287 =back
288  
289 Authorization/authentication failures and a refused TLS requirement
290 are fatal: they are reported via C<on_error> and never retried.
291  
292 =head3 Callback options
293  
294 Callbacks fire on the L<EV> loop, except in three narrow cases:
295 C<on_slow_consumer> fires from the sending call, C<on_disconnect>
296 fires from C<disconnect>, and C<on_error> fires inline when
297 C<new>/C<connect> fail before the loop runs.
298  
299 =over
300  
301 =item on_connect => sub { }
302  
303 Called after the CONNECT/PONG handshake completes.
304  
305 =item on_disconnect => sub { }
306  
307 Called when the connection drops, before any auto-reconnect attempt. An
308 attempt that never connects reports through C<on_error> only.
309  
310 =item on_error => sub { my ($err) = @_ }
311  
312 Receives a string. If unset, errors C<croak>.
313  
314 =item on_lame_duck => sub { }
315  
316 Called once when the server signals lame-duck-mode shutdown via
317 INFO C<ldm:true>.
318  
319 =item on_slow_consumer => sub { my ($pending_bytes) = @_ }
320  
321 See L</slow_consumer>.
322  
323 =back
324  
325 =head2 connect
326  
327 connect($host, [$port])
328  
329 Initiate a TCP connection. Port defaults to 4222. Croaks if already
330 connected or in the middle of connecting; otherwise returns
331 immediately, resets the automatic-reconnect attempt budget, and
332 signals completion via C<on_connect>.
333  
334 =head2 connect_unix
335  
336 connect_unix($path)
337  
338 Initiate a Unix-domain-socket connection. Same async semantics as
339 L</connect>.
340  
341 =head2 disconnect
342  
343 Cancel any pending reconnect, drop queued writes, close the socket,
344 and fire C<on_disconnect>. No auto-reconnect is scheduled. For a clean
345 shutdown that flushes pending writes first, see L</drain>.
346  
347 =head2 is_connected
348  
349 True if the CONNECT/PONG handshake has completed and no disconnect
350 or reconnect is in progress.
351  
352 =head2 publish
353  
354 publish($subject, [$payload], [$reply_to])
355  
356 Publish a message. Alias: C<pub>. Croaks on an undef, empty or
357 over-long subject.
358  
359 $nats->publish('foo', 'hello');
360 $nats->publish('foo', 'hello', 'reply.subject');
361  
362 =head2 hpublish
363  
364 hpublish($subject, $headers, [$payload], [$reply_to])
365  
366 Publish with headers. Alias: C<hpub>. Croaks on an undef or empty
367 subject or headers, or headers not starting with C<NATS/1.0>.
368  
369 $nats->hpublish('foo', "NATS/1.0\r\nX-Key: val\r\n\r\n", 'body');
370  
371 =head2 subscribe
372  
373 subscribe($subject, $cb, [$queue_group])
374  
375 Subscribe to a subject. Returns subscription ID. Alias: C<sub>.
376 Croaks on an undef or empty subject, or one with an empty token
377 (C<a..b>).
378  
379 my $sid = $nats->subscribe('foo.*', sub {
380 my ($subject, $payload, $reply, $headers) = @_;
381 });
382  
383 Queue groups are preserved across reconnects.
384  
385 Callback receives:
386  
387 =over
388  
389 =item C<$subject> - actual subject the message was published to
390  
391 =item C<$payload> - message body
392  
393 =item C<$reply> - reply-to subject (undef if none)
394  
395 =item C<$headers> - raw headers string (only for HMSG)
396  
397 =back
398  
399 =head2 subscribe_max
400  
401 subscribe_max($subject, $cb, $max_msgs, [$queue_group])
402  
403 Convenience: L</subscribe> followed by an auto-unsubscribe after
404 C<$max_msgs> messages have been delivered.
405  
406 =head2 unsubscribe
407  
408 unsubscribe($sid, [$max_msgs])
409  
410 Unsubscribe. With C<$max_msgs>, the subscription ends once that many
411 messages have been delivered in total, at once if they already have.
412 The count survives a reconnect. Alias: C<unsub>.
413  
414 =head2 request
415  
416 request($subject, $payload, $cb, [$timeout_ms])
417  
418 Request/reply. Uses automatic inbox subscription. Alias: C<req>.
419 Croaks on an undef or empty subject.
420  
421 $nats->request('service', 'data', sub {
422 my ($response, $err) = @_;
423 die $err if $err;
424 print "got: $response\n";
425 }, 5000);
426  
427 Callback receives C<($response, $error)>. For replies that include
428 NATS message headers (HMSG), a third argument C<$headers> with the
429 raw header block is also passed. Error is set on timeout
430 ("request timeout"), no responders ("no responders"), or a dropped
431 connection ("disconnected"). A request made while reconnecting waits
432 for the connection. A C<$timeout_ms> of 0 disables the timeout; the
433 callback then waits indefinitely.
434  
435 =head2 hrequest
436  
437 hrequest($subject, $headers, $payload, $cb, [$timeout_ms])
438  
439 Like L</request>, with a header block as for L</hpublish>. Alias:
440 C<hreq>.
441  
442 =head2 drain
443  
444 drain([$cb])
445  
446 Graceful shutdown: sends UNSUB for all subscriptions, flushes pending
447 writes with a PING fence, fires C<$cb> when the server confirms with
448 PONG, then disconnects. Messages already on their way are still
449 delivered, and what their callbacks publish is sent before the
450 disconnect. A later L</connect> does not restore the drained
451 subscriptions.
452  
453 C<$cb> receives a single argument: C<undef> on clean drain, or an error
454 string (e.g. C<"disconnected">) if the connection dropped before the
455 PONG arrived. Croaks unless connected. Calling C<drain> again while
456 a drain is in progress croaks if a callback is given, and is
457 otherwise a silent no-op.
458  
459 $nats->drain(sub {
460 my ($err) = @_;
461 die "drain failed: $err" if $err;
462 print "drained, safe to exit\n";
463 });
464  
465 =head2 ping
466  
467 Send PING to server. Croaks unless connected.
468  
469 =head2 flush
470  
471 flush([$cb])
472  
473 Send PING as a write fence; the subsequent PONG guarantees all prior
474 messages were processed by the server. If C<$cb> is given, it is
475 invoked when the PONG arrives. The callback receives a single
476 argument: C<undef> on success, or an error string if the PONG cannot
477 arrive: C<"disconnected"> when the connection (or the attempt the
478 flush waited for) failed, C<"not connected"> when there is no
479 connection and none is being made.
480  
481 While connecting or reconnecting, the PING is sent once the handshake
482 completes, behind the writes queued meanwhile. Without C<$cb>, a flush
483 with no connection and none being made croaks.
484  
485 =head2 creds_file
486  
487 creds_file($path)
488  
489 Read a NATS C<.creds> file and apply the embedded JWT and NKey seed
490 via L</jwt> and L</nkey_seed>. Apply this BEFORE C<connect> so the
491 credentials are available during the CONNECT handshake. Dies if the
492 file is unreadable or missing either the C<USER JWT> or
493 C<USER NKEY SEED> block.
494  
495 =head2 new_inbox
496  
497 Returns a fresh subject suitable for use as a private reply target
498 (C<_INBOX.E<lt>randE<gt>.E<lt>nE<gt>>, under C<inbox_prefix> if set).
499 Each call burns a slot from the same counter that L</request> uses, so
500 manual subscribers must treat the returned subject as opaque.
501  
502 =head2 subscription_count
503  
504 Returns the number of currently-registered subscriptions, including
505 the implicit inbox subscription used by L</request>.
506  
507 =head2 server_info
508  
509 Returns the raw JSON string of the most recent INFO frame received
510 from the server (or C<undef> before the first INFO). Useful for
511 inspecting C<server_id>, C<version>, C<cluster>, C<connect_urls>,
512 etc.
513  
514 =head2 max_payload
515  
516 max_payload([$limit])
517  
518 Server-advertised maximum payload size in bytes. Returns the current
519 value; with an argument, overrides it until the server's next INFO
520 (publishes above this croak locally before reaching the wire). Inbound
521 messages may exceed it, as JetStream replies do, up to 64 MiB.
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, 100-byte payloads
727 (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 (64 in flight) 334K msgs/sec
734  
735 Run C<perl bench/benchmark.pl> for full results. Set C<BENCH_MESSAGES>,
736 C<BENCH_PAYLOAD>, C<BENCH_HOST>, C<BENCH_PORT> to customize.
737  
738 =head1 NATS PROTOCOL
739  
740 This module implements the NATS client protocol directly in XS.
741 The protocol is text-based with CRLF-delimited control lines and
742 binary payloads.
743  
744 Connection flow: server sends INFO, client sends CONNECT + PING,
745 server responds with PONG to confirm. All subscriptions (including
746 queue groups and auto-unsub state) are automatically restored on
747 reconnect.
748  
749 Request/reply uses a single wildcard inbox subscription
750 (C<_INBOX.E<lt>randomE<gt>.*>) for all requests, with unique
751 suffixes per request.
752  
753 =head1 CAVEATS
754  
755 =over
756  
757 =item * DNS resolution via C<getaddrinfo> is blocking. Use numeric IP
758 addresses for latency-sensitive applications.
759  
760 =item * TLS requires OpenSSL headers at build time (auto-detected).
761  
762 =item * NKey auth requires OpenSSL with Ed25519 support (1.1.1+).
763  
764 =item * The module handles all data as bytes. Encode UTF-8 strings before
765 passing them.
766  
767 =item * A die in a callback leaves C<EV::run> once the client has finished
768 handling the event that ran it.
769  
770 =item * Cluster URL discovery (the C<connect_urls> field of INFO) is
771 trusted by default. On failover the client connects to whatever
772 hostnames the previous server advertised, and TLS hostname verification
773 is performed against those names. Use a private CA (C<tls_ca_file>) to
774 restrict which certificates are acceptable, or do not enable C<tls> on
775 public-CA topologies where any holder of a valid cert could redirect
776 clients.
777  
778 =item * Do not use a connection across fork(); create it afterwards
779 instead. The module is not threadsafe, and a connection must be
780 destroyed before the L<EV> loop it was attached to.
781  
782 =back
783  
784 =head1 ENVIRONMENT
785  
786 =over
787  
788 =item TEST_NATS_HOST, TEST_NATS_PORT
789  
790 The live-server tests run only against the server these name; without
791 them they skip.
792  
793 =back
794  
795 =head1 SEE ALSO
796  
797 L<EV::Nats::JetStream>, L<EV::Nats::KV>, L<EV::Nats::ObjectStore>,
798 L<EV>,
799 L<NATS protocol|https://docs.nats.io/reference/reference-protocols/nats-protocol>,
800 L<nats-server|https://github.com/nats-io/nats-server>.
801  
802 =head1 AUTHOR
803  
804 vividsnow
805  
806 =head1 LICENSE
807  
808 This library is free software; you can redistribute it and/or modify it
809 under the same terms as Perl itself.
810  
811 =cut
« blib/lib/EV/Nats/ObjectStore.pm ↑ Summary Nats.xs »