blib/lib/EV/Nats.pm

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