@horizon-republic/nestjs-jetstream 2.5.1 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -5
- package/dist/index.cjs +620 -307
- package/dist/index.d.cts +239 -62
- package/dist/index.d.ts +239 -62
- package/dist/index.js +621 -317
- package/package.json +7 -7
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ModuleMetadata, FactoryProvider, Type, Logger, OnApplicationShutdown, DynamicModule } from '@nestjs/common';
|
|
2
|
-
import { MsgHdrs, StreamConfig, ConsumerConfig, DeliverPolicy, ReplayPolicy, ConnectionOptions, NatsConnection, Status, JetStreamManager, ConsumerInfo, JsMsg, Msg } from 'nats';
|
|
2
|
+
import { MsgHdrs, StreamConfig, ConsumerConfig, ConsumeOptions, DeliverPolicy, ReplayPolicy, ConnectionOptions, NatsConnection, Status, JetStreamManager, JetStreamClient, ConsumerInfo, JsMsg, Msg } from 'nats';
|
|
3
3
|
import { MessageHandler, Server, CustomTransportStrategy, ClientProxy, ReadPacket, WritePacket, BaseRpcContext } from '@nestjs/microservices';
|
|
4
4
|
import { Observable } from 'rxjs';
|
|
5
5
|
|
|
@@ -31,6 +31,11 @@ interface Codec {
|
|
|
31
31
|
decode(data: Uint8Array): unknown;
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
/** Discriminates the kind of message routed through the transport. */
|
|
35
|
+
declare enum MessageKind {
|
|
36
|
+
Event = "event",
|
|
37
|
+
Rpc = "rpc"
|
|
38
|
+
}
|
|
34
39
|
declare enum TransportEvent {
|
|
35
40
|
Connect = "connect",
|
|
36
41
|
Disconnect = "disconnect",
|
|
@@ -71,7 +76,7 @@ interface TransportHooks {
|
|
|
71
76
|
/** Fired when an RPC handler exceeds its timeout. */
|
|
72
77
|
[TransportEvent.RpcTimeout](subject: string, correlationId: string): void;
|
|
73
78
|
/** Fired after a message is successfully routed to its handler. */
|
|
74
|
-
[TransportEvent.MessageRouted](subject: string, kind:
|
|
79
|
+
[TransportEvent.MessageRouted](subject: string, kind: MessageKind): void;
|
|
75
80
|
/** Fired at the start of the graceful shutdown sequence. */
|
|
76
81
|
[TransportEvent.ShutdownStart](): void;
|
|
77
82
|
/** Fired after graceful shutdown completes. */
|
|
@@ -101,6 +106,16 @@ interface DeadLetterInfo {
|
|
|
101
106
|
timestamp: string;
|
|
102
107
|
}
|
|
103
108
|
|
|
109
|
+
/** Health status returned by the JetStream health indicator. */
|
|
110
|
+
interface JetstreamHealthStatus {
|
|
111
|
+
/** Whether the NATS connection is alive. */
|
|
112
|
+
connected: boolean;
|
|
113
|
+
/** NATS server URL, or `null` if not connected. */
|
|
114
|
+
server: string | null;
|
|
115
|
+
/** Round-trip latency in ms, or `null` if disconnected. */
|
|
116
|
+
latency: number | null;
|
|
117
|
+
}
|
|
118
|
+
|
|
104
119
|
/**
|
|
105
120
|
* RPC transport configuration.
|
|
106
121
|
*
|
|
@@ -123,11 +138,50 @@ type RpcConfig = {
|
|
|
123
138
|
stream?: Partial<StreamConfig>;
|
|
124
139
|
/** Raw NATS ConsumerConfig overrides for the command consumer. */
|
|
125
140
|
consumer?: Partial<ConsumerConfig>;
|
|
141
|
+
/** Options passed to the nats.js `consumer.consume()` call for the command consumer. */
|
|
142
|
+
consume?: Partial<ConsumeOptions>;
|
|
143
|
+
/** Maximum number of concurrent RPC handler executions. */
|
|
144
|
+
concurrency?: number;
|
|
145
|
+
/**
|
|
146
|
+
* Auto-extend ack deadline via `msg.working()` during RPC handler execution.
|
|
147
|
+
* The RPC handler timeout (`setTimeout` + `msg.term()`) still acts as the hard cap.
|
|
148
|
+
*/
|
|
149
|
+
ackExtension?: boolean | number;
|
|
126
150
|
};
|
|
127
151
|
/** Overrides for JetStream stream and consumer configuration. */
|
|
128
152
|
interface StreamConsumerOverrides {
|
|
129
153
|
stream?: Partial<StreamConfig>;
|
|
130
154
|
consumer?: Partial<ConsumerConfig>;
|
|
155
|
+
/**
|
|
156
|
+
* Options passed to the nats.js `consumer.consume()` call.
|
|
157
|
+
* Controls prefetch buffer size, idle heartbeat interval, and auto-refill thresholds.
|
|
158
|
+
*
|
|
159
|
+
* nats.js supports two consumption modes (message-based and byte-based).
|
|
160
|
+
* Do not mix `max_bytes`/`threshold_bytes` with `threshold_messages` —
|
|
161
|
+
* use one mode or the other.
|
|
162
|
+
*
|
|
163
|
+
* @see https://github.com/nats-io/nats.js — ConsumeOptions
|
|
164
|
+
*/
|
|
165
|
+
consume?: Partial<ConsumeOptions>;
|
|
166
|
+
/**
|
|
167
|
+
* Maximum number of concurrent handler executions (RxJS `mergeMap` limit).
|
|
168
|
+
*
|
|
169
|
+
* Default: `undefined` (unlimited — naturally bounded by `max_ack_pending`).
|
|
170
|
+
* Set this to protect downstream systems from overload.
|
|
171
|
+
*
|
|
172
|
+
* **Important:** if `concurrency < max_ack_pending`, messages buffer in RxJS
|
|
173
|
+
* while their NATS ack timer ticks. Increase `ack_wait` proportionally to
|
|
174
|
+
* prevent unnecessary redeliveries.
|
|
175
|
+
*/
|
|
176
|
+
concurrency?: number;
|
|
177
|
+
/**
|
|
178
|
+
* Auto-extend the NATS ack deadline via `msg.working()` during handler execution.
|
|
179
|
+
*
|
|
180
|
+
* - `false` (default): disabled — NATS redelivers after `ack_wait` if not acked.
|
|
181
|
+
* - `true`: auto-extend at `ack_wait / 2` interval (calculated from consumer config).
|
|
182
|
+
* - `number`: explicit extension interval in milliseconds.
|
|
183
|
+
*/
|
|
184
|
+
ackExtension?: boolean | number;
|
|
131
185
|
}
|
|
132
186
|
/**
|
|
133
187
|
* Configuration for ordered event consumers.
|
|
@@ -281,12 +335,17 @@ type JetstreamModuleAsyncOptions = {
|
|
|
281
335
|
/**
|
|
282
336
|
* Identifies a JetStream stream/consumer kind.
|
|
283
337
|
*
|
|
284
|
-
* - `
|
|
285
|
-
* - `
|
|
286
|
-
* - `
|
|
287
|
-
* - `
|
|
338
|
+
* - `Event` — Workqueue events (at-least-once delivery to one consumer).
|
|
339
|
+
* - `Command` — RPC commands (JetStream mode only).
|
|
340
|
+
* - `Broadcast` — Broadcast events (fan-out to all consumers).
|
|
341
|
+
* - `Ordered` — Ordered events (strict sequential delivery, Limits retention).
|
|
288
342
|
*/
|
|
289
|
-
|
|
343
|
+
declare enum StreamKind {
|
|
344
|
+
Event = "ev",
|
|
345
|
+
Command = "cmd",
|
|
346
|
+
Broadcast = "broadcast",
|
|
347
|
+
Ordered = "ordered"
|
|
348
|
+
}
|
|
290
349
|
|
|
291
350
|
/** @internal Grouped pattern lists by stream kind, used for stream/consumer setup. */
|
|
292
351
|
interface PatternsByKind {
|
|
@@ -299,6 +358,33 @@ interface PatternsByKind {
|
|
|
299
358
|
/** Ordered event patterns (strict sequential delivery). */
|
|
300
359
|
ordered: string[];
|
|
301
360
|
}
|
|
361
|
+
/** Options for configuring event/broadcast processing behavior. */
|
|
362
|
+
interface EventProcessingConfig {
|
|
363
|
+
events?: {
|
|
364
|
+
concurrency?: number;
|
|
365
|
+
ackExtension?: boolean | number;
|
|
366
|
+
};
|
|
367
|
+
broadcast?: {
|
|
368
|
+
concurrency?: number;
|
|
369
|
+
ackExtension?: boolean | number;
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
/** Options for dead letter queue handling. */
|
|
373
|
+
interface DeadLetterConfig {
|
|
374
|
+
/**
|
|
375
|
+
* Map of stream name -> max_deliver value.
|
|
376
|
+
* Used to detect when a message from a given stream has exhausted all delivery attempts.
|
|
377
|
+
*/
|
|
378
|
+
maxDeliverByStream: Map<string, number>;
|
|
379
|
+
/** Async callback invoked when a message exhausts all deliveries. */
|
|
380
|
+
onDeadLetter(info: DeadLetterInfo): Promise<void>;
|
|
381
|
+
}
|
|
382
|
+
/** Options for configuring RPC processing behavior. */
|
|
383
|
+
interface RpcRouterOptions {
|
|
384
|
+
timeout?: number;
|
|
385
|
+
concurrency?: number;
|
|
386
|
+
ackExtension?: boolean | number;
|
|
387
|
+
}
|
|
302
388
|
|
|
303
389
|
/**
|
|
304
390
|
* Central event bus for transport lifecycle notifications.
|
|
@@ -330,6 +416,12 @@ declare class EventBus {
|
|
|
330
416
|
* @param args - Arguments matching the hook signature for this event.
|
|
331
417
|
*/
|
|
332
418
|
emit<K extends keyof TransportHooks>(event: K, ...args: Parameters<TransportHooks[K]>): void;
|
|
419
|
+
/**
|
|
420
|
+
* Hot-path optimized emit for MessageRouted events.
|
|
421
|
+
* Avoids rest/spread overhead of the generic `emit()`.
|
|
422
|
+
*/
|
|
423
|
+
emitMessageRouted(subject: string, kind: MessageKind): void;
|
|
424
|
+
private callHook;
|
|
333
425
|
}
|
|
334
426
|
|
|
335
427
|
/**
|
|
@@ -352,6 +444,7 @@ declare class ConnectionProvider {
|
|
|
352
444
|
private readonly logger;
|
|
353
445
|
private connection;
|
|
354
446
|
private connectionPromise;
|
|
447
|
+
private jsClient;
|
|
355
448
|
private jsmInstance;
|
|
356
449
|
private jsmPromise;
|
|
357
450
|
constructor(options: JetstreamModuleOptions, eventBus: EventBus);
|
|
@@ -367,6 +460,16 @@ declare class ConnectionProvider {
|
|
|
367
460
|
* @returns The JetStreamManager for stream/consumer administration.
|
|
368
461
|
*/
|
|
369
462
|
getJetStreamManager(): Promise<JetStreamManager>;
|
|
463
|
+
/**
|
|
464
|
+
* Get a cached JetStream client.
|
|
465
|
+
*
|
|
466
|
+
* Invalidated automatically on reconnect and shutdown so consumers always
|
|
467
|
+
* operate against the live connection.
|
|
468
|
+
*
|
|
469
|
+
* @returns The cached JetStreamClient.
|
|
470
|
+
* @throws Error if the connection has not been established yet.
|
|
471
|
+
*/
|
|
472
|
+
getJetStreamClient(): JetStreamClient;
|
|
370
473
|
/** Direct access to the raw NATS connection, or `null` if not yet connected. */
|
|
371
474
|
get unwrap(): NatsConnection | null;
|
|
372
475
|
/**
|
|
@@ -393,6 +496,11 @@ declare class PatternRegistry {
|
|
|
393
496
|
private readonly options;
|
|
394
497
|
private readonly logger;
|
|
395
498
|
private readonly registry;
|
|
499
|
+
private cachedPatterns;
|
|
500
|
+
private _hasEvents;
|
|
501
|
+
private _hasCommands;
|
|
502
|
+
private _hasBroadcasts;
|
|
503
|
+
private _hasOrdered;
|
|
396
504
|
constructor(options: JetstreamModuleOptions);
|
|
397
505
|
/**
|
|
398
506
|
* Register all handlers from the NestJS strategy.
|
|
@@ -404,21 +512,17 @@ declare class PatternRegistry {
|
|
|
404
512
|
getHandler(subject: string): MessageHandler | null;
|
|
405
513
|
/** Get all registered broadcast patterns (for consumer filter_subject setup). */
|
|
406
514
|
getBroadcastPatterns(): string[];
|
|
407
|
-
/** Check if any broadcast handlers are registered. */
|
|
408
515
|
hasBroadcastHandlers(): boolean;
|
|
409
|
-
/** Check if any RPC (command) handlers are registered. */
|
|
410
516
|
hasRpcHandlers(): boolean;
|
|
411
|
-
/** Check if any workqueue event handlers are registered. */
|
|
412
517
|
hasEventHandlers(): boolean;
|
|
413
|
-
/** Check if any ordered event handlers are registered. */
|
|
414
518
|
hasOrderedHandlers(): boolean;
|
|
415
519
|
/** Get fully-qualified NATS subjects for ordered handlers. */
|
|
416
520
|
getOrderedSubjects(): string[];
|
|
417
|
-
/** Get patterns grouped by kind. */
|
|
521
|
+
/** Get patterns grouped by kind (cached after registration). */
|
|
418
522
|
getPatternsByKind(): PatternsByKind;
|
|
419
523
|
/** Normalize a full NATS subject back to the user-facing pattern. */
|
|
420
524
|
normalizeSubject(subject: string): string;
|
|
421
|
-
|
|
525
|
+
private buildPatternsByKind;
|
|
422
526
|
private logSummary;
|
|
423
527
|
}
|
|
424
528
|
|
|
@@ -485,16 +589,6 @@ declare class StreamProvider {
|
|
|
485
589
|
private getOverrides;
|
|
486
590
|
}
|
|
487
591
|
|
|
488
|
-
/** Options for dead letter queue handling. */
|
|
489
|
-
interface DeadLetterConfig {
|
|
490
|
-
/**
|
|
491
|
-
* Map of stream name -> max_deliver value.
|
|
492
|
-
* Used to detect when a message from a given stream has exhausted all delivery attempts.
|
|
493
|
-
*/
|
|
494
|
-
maxDeliverByStream: Map<string, number>;
|
|
495
|
-
/** Async callback invoked when a message exhausts all deliveries. */
|
|
496
|
-
onDeadLetter(info: DeadLetterInfo): Promise<void>;
|
|
497
|
-
}
|
|
498
592
|
/**
|
|
499
593
|
* Routes incoming event messages (workqueue, broadcast, and ordered) to NestJS handlers.
|
|
500
594
|
*
|
|
@@ -511,9 +605,11 @@ declare class EventRouter {
|
|
|
511
605
|
private readonly codec;
|
|
512
606
|
private readonly eventBus;
|
|
513
607
|
private readonly deadLetterConfig?;
|
|
608
|
+
private readonly processingConfig?;
|
|
609
|
+
private readonly ackWaitMap?;
|
|
514
610
|
private readonly logger;
|
|
515
611
|
private readonly subscriptions;
|
|
516
|
-
constructor(messageProvider: MessageProvider, patternRegistry: PatternRegistry, codec: Codec, eventBus: EventBus, deadLetterConfig?: DeadLetterConfig | undefined);
|
|
612
|
+
constructor(messageProvider: MessageProvider, patternRegistry: PatternRegistry, codec: Codec, eventBus: EventBus, deadLetterConfig?: DeadLetterConfig | undefined, processingConfig?: EventProcessingConfig | undefined, ackWaitMap?: Map<StreamKind, number> | undefined);
|
|
517
613
|
/**
|
|
518
614
|
* Update the max_deliver thresholds from actual NATS consumer configs.
|
|
519
615
|
* Called after consumers are ensured so the DLQ map reflects reality.
|
|
@@ -525,12 +621,16 @@ declare class EventRouter {
|
|
|
525
621
|
destroy(): void;
|
|
526
622
|
/** Subscribe to a message stream and route each message. */
|
|
527
623
|
private subscribeToStream;
|
|
528
|
-
|
|
529
|
-
private
|
|
624
|
+
private getConcurrency;
|
|
625
|
+
private getAckExtensionConfig;
|
|
626
|
+
/** Handle a single event message with error isolation. */
|
|
627
|
+
private handleSafe;
|
|
628
|
+
/** Handle an ordered message with error isolation. */
|
|
629
|
+
private handleOrderedSafe;
|
|
630
|
+
/** Resolve handler, decode payload, and build context. Returns null on failure. */
|
|
631
|
+
private decodeMessage;
|
|
530
632
|
/** Execute handler, then ack on success or nak/dead-letter on failure. */
|
|
531
633
|
private executeHandler;
|
|
532
|
-
/** Handle an ordered message: decode -> execute handler -> no ack/nak. */
|
|
533
|
-
private handleOrdered;
|
|
534
634
|
/** Check if the message has exhausted all delivery attempts. */
|
|
535
635
|
private isDeadLetter;
|
|
536
636
|
/** Handle a dead letter: invoke callback, then term or nak based on result. */
|
|
@@ -555,16 +655,23 @@ declare class RpcRouter {
|
|
|
555
655
|
private readonly connection;
|
|
556
656
|
private readonly codec;
|
|
557
657
|
private readonly eventBus;
|
|
658
|
+
private readonly rpcOptions?;
|
|
659
|
+
private readonly ackWaitMap?;
|
|
558
660
|
private readonly logger;
|
|
559
661
|
private readonly timeout;
|
|
662
|
+
private readonly concurrency;
|
|
663
|
+
private resolvedAckExtensionInterval;
|
|
560
664
|
private subscription;
|
|
561
|
-
|
|
665
|
+
private cachedNc;
|
|
666
|
+
constructor(messageProvider: MessageProvider, patternRegistry: PatternRegistry, connection: ConnectionProvider, codec: Codec, eventBus: EventBus, rpcOptions?: RpcRouterOptions | undefined, ackWaitMap?: Map<StreamKind, number> | undefined);
|
|
667
|
+
/** Lazily resolve the ack extension interval (needs ackWaitMap populated at runtime). */
|
|
668
|
+
private get ackExtensionInterval();
|
|
562
669
|
/** Start routing command messages to handlers. */
|
|
563
|
-
start(): void
|
|
670
|
+
start(): Promise<void>;
|
|
564
671
|
/** Stop routing and unsubscribe. */
|
|
565
672
|
destroy(): void;
|
|
566
|
-
/** Handle a single RPC command message. */
|
|
567
|
-
private
|
|
673
|
+
/** Handle a single RPC command message with error isolation. */
|
|
674
|
+
private handleSafe;
|
|
568
675
|
/** Execute handler, publish response, settle message. */
|
|
569
676
|
private executeHandler;
|
|
570
677
|
}
|
|
@@ -612,6 +719,7 @@ declare class ConsumerProvider {
|
|
|
612
719
|
declare class MessageProvider {
|
|
613
720
|
private readonly connection;
|
|
614
721
|
private readonly eventBus;
|
|
722
|
+
private readonly consumeOptionsMap;
|
|
615
723
|
private readonly logger;
|
|
616
724
|
private readonly activeIterators;
|
|
617
725
|
private orderedReadyResolve;
|
|
@@ -621,7 +729,7 @@ declare class MessageProvider {
|
|
|
621
729
|
private commandMessages$;
|
|
622
730
|
private broadcastMessages$;
|
|
623
731
|
private orderedMessages$;
|
|
624
|
-
constructor(connection: ConnectionProvider, eventBus: EventBus);
|
|
732
|
+
constructor(connection: ConnectionProvider, eventBus: EventBus, consumeOptionsMap?: Map<StreamKind, Partial<ConsumeOptions>>);
|
|
625
733
|
/** Observable stream of workqueue event messages. */
|
|
626
734
|
get events$(): Observable<JsMsg>;
|
|
627
735
|
/** Observable stream of RPC command messages (jetstream mode). */
|
|
@@ -645,6 +753,7 @@ declare class MessageProvider {
|
|
|
645
753
|
*
|
|
646
754
|
* @param streamName - JetStream stream to consume from.
|
|
647
755
|
* @param filterSubjects - NATS subjects to filter on.
|
|
756
|
+
* @param orderedConfig - Optional overrides for ordered consumer options.
|
|
648
757
|
*/
|
|
649
758
|
startOrdered(streamName: string, filterSubjects: string[], orderedConfig?: OrderedEventOverrides): Promise<void>;
|
|
650
759
|
/** Stop all consumer flows and reinitialize subjects for potential restart. */
|
|
@@ -655,8 +764,12 @@ declare class MessageProvider {
|
|
|
655
764
|
private consumeOnce;
|
|
656
765
|
/** Get the target subject for a consumer kind. */
|
|
657
766
|
private getTargetSubject;
|
|
767
|
+
/** Monitor heartbeats and restart the consumer iterator on prolonged silence. */
|
|
768
|
+
private monitorConsumerHealth;
|
|
658
769
|
/** Create a self-healing ordered consumer flow. */
|
|
659
770
|
private createOrderedFlow;
|
|
771
|
+
/** Shared self-healing flow: defer -> retry with exponential backoff on error/completion. */
|
|
772
|
+
private createSelfHealingFlow;
|
|
660
773
|
/** Single iteration: create ordered consumer -> iterate messages. */
|
|
661
774
|
private consumeOrderedOnce;
|
|
662
775
|
}
|
|
@@ -682,10 +795,11 @@ declare class JetstreamStrategy extends Server implements CustomTransportStrateg
|
|
|
682
795
|
private readonly eventRouter;
|
|
683
796
|
private readonly rpcRouter;
|
|
684
797
|
private readonly coreRpcServer;
|
|
798
|
+
private readonly ackWaitMap;
|
|
685
799
|
readonly transportId: symbol;
|
|
686
800
|
private readonly listeners;
|
|
687
801
|
private started;
|
|
688
|
-
constructor(options: JetstreamModuleOptions, connection: ConnectionProvider, patternRegistry: PatternRegistry, streamProvider: StreamProvider, consumerProvider: ConsumerProvider, messageProvider: MessageProvider, eventRouter: EventRouter, rpcRouter: RpcRouter, coreRpcServer: CoreRpcServer);
|
|
802
|
+
constructor(options: JetstreamModuleOptions, connection: ConnectionProvider, patternRegistry: PatternRegistry, streamProvider: StreamProvider, consumerProvider: ConsumerProvider, messageProvider: MessageProvider, eventRouter: EventRouter, rpcRouter: RpcRouter, coreRpcServer: CoreRpcServer, ackWaitMap?: Map<StreamKind, number>);
|
|
689
803
|
/**
|
|
690
804
|
* Start the transport: register handlers, create infrastructure, begin consumption.
|
|
691
805
|
*
|
|
@@ -709,16 +823,18 @@ declare class JetstreamStrategy extends Server implements CustomTransportStrateg
|
|
|
709
823
|
unwrap<T>(): T;
|
|
710
824
|
/** Access the pattern registry (for module-level introspection). */
|
|
711
825
|
getPatternRegistry(): PatternRegistry;
|
|
712
|
-
/** Determine which
|
|
713
|
-
private
|
|
714
|
-
/**
|
|
715
|
-
private
|
|
826
|
+
/** Determine which streams and durable consumers are needed. */
|
|
827
|
+
private resolveRequiredKinds;
|
|
828
|
+
/** Populate the shared ack_wait map from actual NATS consumer configs. */
|
|
829
|
+
private populateAckWaitMap;
|
|
716
830
|
/** Build max_deliver map from actual NATS consumer configs (not options). */
|
|
717
831
|
private buildMaxDeliverMap;
|
|
718
|
-
private isCoreRpcMode;
|
|
719
|
-
private isJetStreamRpcMode;
|
|
720
832
|
}
|
|
721
833
|
|
|
834
|
+
/** Minimal interface for anything that can be stopped during shutdown. */
|
|
835
|
+
interface Stoppable {
|
|
836
|
+
close(): void;
|
|
837
|
+
}
|
|
722
838
|
/**
|
|
723
839
|
* Orchestrates graceful transport shutdown.
|
|
724
840
|
*
|
|
@@ -738,9 +854,9 @@ declare class ShutdownManager {
|
|
|
738
854
|
/**
|
|
739
855
|
* Execute the full shutdown sequence.
|
|
740
856
|
*
|
|
741
|
-
* @param strategy Optional
|
|
857
|
+
* @param strategy Optional stoppable to close (stops consumers and subscriptions).
|
|
742
858
|
*/
|
|
743
|
-
shutdown(strategy?:
|
|
859
|
+
shutdown(strategy?: Stoppable): Promise<void>;
|
|
744
860
|
}
|
|
745
861
|
|
|
746
862
|
/**
|
|
@@ -841,6 +957,8 @@ declare class JetstreamClient extends ClientProxy {
|
|
|
841
957
|
private readonly logger;
|
|
842
958
|
/** Target service name this client sends messages to. */
|
|
843
959
|
private readonly targetName;
|
|
960
|
+
/** Pre-cached caller name derived from rootOptions.name, computed once in constructor. */
|
|
961
|
+
private readonly callerName;
|
|
844
962
|
/** Shared inbox for JetStream-mode RPC responses. */
|
|
845
963
|
private inbox;
|
|
846
964
|
private inboxSubscription;
|
|
@@ -900,8 +1018,6 @@ declare class JetstreamClient extends ClientProxy {
|
|
|
900
1018
|
private buildHeaders;
|
|
901
1019
|
/** Extract data, headers, and timeout from raw packet data or JetstreamRecord. */
|
|
902
1020
|
private extractRecordData;
|
|
903
|
-
private isCoreRpcMode;
|
|
904
|
-
private isJetStreamRpcMode;
|
|
905
1021
|
private getRpcTimeout;
|
|
906
1022
|
}
|
|
907
1023
|
|
|
@@ -1032,19 +1148,33 @@ type NatsMessage = JsMsg | Msg;
|
|
|
1032
1148
|
* Execution context for RPC and event handlers.
|
|
1033
1149
|
*
|
|
1034
1150
|
* Provides convenient accessors for the NATS message, subject,
|
|
1035
|
-
* and
|
|
1151
|
+
* headers, and JetStream metadata without needing to interact
|
|
1152
|
+
* with the raw message directly.
|
|
1153
|
+
*
|
|
1154
|
+
* Handlers can also control message settlement via {@link retry}
|
|
1155
|
+
* and {@link terminate} instead of throwing errors.
|
|
1036
1156
|
*
|
|
1037
1157
|
* @example
|
|
1038
1158
|
* ```typescript
|
|
1039
|
-
* @
|
|
1040
|
-
*
|
|
1041
|
-
*
|
|
1042
|
-
*
|
|
1043
|
-
*
|
|
1159
|
+
* @EventPattern('order.process')
|
|
1160
|
+
* async handle(@Payload() data: OrderDto, @Ctx() ctx: RpcContext) {
|
|
1161
|
+
* if (ctx.getDeliveryCount()! >= 3) {
|
|
1162
|
+
* ctx.terminate('Max business retries exceeded');
|
|
1163
|
+
* return;
|
|
1164
|
+
* }
|
|
1165
|
+
* if (!this.isReady()) {
|
|
1166
|
+
* ctx.retry({ delay: 5000 });
|
|
1167
|
+
* return;
|
|
1168
|
+
* }
|
|
1169
|
+
* await this.process(data);
|
|
1044
1170
|
* }
|
|
1045
1171
|
* ```
|
|
1046
1172
|
*/
|
|
1047
1173
|
declare class RpcContext extends BaseRpcContext<[NatsMessage]> {
|
|
1174
|
+
private _shouldRetry;
|
|
1175
|
+
private _retryDelay;
|
|
1176
|
+
private _shouldTerminate;
|
|
1177
|
+
private _terminateReason;
|
|
1048
1178
|
/**
|
|
1049
1179
|
* Get the underlying NATS message.
|
|
1050
1180
|
*
|
|
@@ -1071,19 +1201,52 @@ declare class RpcContext extends BaseRpcContext<[NatsMessage]> {
|
|
|
1071
1201
|
isJetStream(): this is RpcContext & {
|
|
1072
1202
|
getMessage(): JsMsg;
|
|
1073
1203
|
};
|
|
1204
|
+
/** How many times this message has been delivered. */
|
|
1205
|
+
getDeliveryCount(): number | undefined;
|
|
1206
|
+
/** The JetStream stream this message belongs to. */
|
|
1207
|
+
getStream(): string | undefined;
|
|
1208
|
+
/** The stream sequence number. */
|
|
1209
|
+
getSequence(): number | undefined;
|
|
1210
|
+
/** The message timestamp as a `Date` (derived from `info.timestampNanos`). */
|
|
1211
|
+
getTimestamp(): Date | undefined;
|
|
1212
|
+
/** The name of the service that published this message (from `x-caller-name` header). */
|
|
1213
|
+
getCallerName(): string | undefined;
|
|
1214
|
+
/**
|
|
1215
|
+
* Signal the transport to retry (nak) this message instead of acknowledging it.
|
|
1216
|
+
*
|
|
1217
|
+
* Use for business-level retries without throwing errors.
|
|
1218
|
+
* Only affects JetStream event handlers (workqueue/broadcast).
|
|
1219
|
+
*
|
|
1220
|
+
* @param opts - Optional delay in ms before redelivery.
|
|
1221
|
+
* @throws Error if {@link terminate} was already called.
|
|
1222
|
+
*/
|
|
1223
|
+
retry(opts?: {
|
|
1224
|
+
delayMs?: number;
|
|
1225
|
+
}): void;
|
|
1226
|
+
/**
|
|
1227
|
+
* Signal the transport to permanently reject (term) this message.
|
|
1228
|
+
*
|
|
1229
|
+
* Use when a message is no longer relevant and should not be retried or sent to DLQ.
|
|
1230
|
+
* Only affects JetStream event handlers (workqueue/broadcast).
|
|
1231
|
+
*
|
|
1232
|
+
* @param reason - Optional reason for termination (logged by NATS).
|
|
1233
|
+
* @throws Error if {@link retry} was already called.
|
|
1234
|
+
*/
|
|
1235
|
+
terminate(reason?: string): void;
|
|
1236
|
+
/** Narrow to JsMsg or return null for Core messages. Used by metadata getters. */
|
|
1237
|
+
private asJetStream;
|
|
1238
|
+
/** Ensure the message is JetStream — settlement actions are not available for Core NATS. */
|
|
1239
|
+
private assertJetStream;
|
|
1240
|
+
/** @internal */
|
|
1241
|
+
get shouldRetry(): boolean;
|
|
1242
|
+
/** @internal */
|
|
1243
|
+
get retryDelay(): number | undefined;
|
|
1244
|
+
/** @internal */
|
|
1245
|
+
get shouldTerminate(): boolean;
|
|
1246
|
+
/** @internal */
|
|
1247
|
+
get terminateReason(): string | undefined;
|
|
1074
1248
|
}
|
|
1075
1249
|
|
|
1076
|
-
/**
|
|
1077
|
-
* Health status returned by {@link JetstreamHealthIndicator.check}.
|
|
1078
|
-
*/
|
|
1079
|
-
interface JetstreamHealthStatus {
|
|
1080
|
-
/** Whether the NATS connection is alive. */
|
|
1081
|
-
connected: boolean;
|
|
1082
|
-
/** NATS server URL, or `null` if not connected. */
|
|
1083
|
-
server: string | null;
|
|
1084
|
-
/** Round-trip latency in ms, or `null` if disconnected. */
|
|
1085
|
-
latency: number | null;
|
|
1086
|
-
}
|
|
1087
1250
|
/**
|
|
1088
1251
|
* Health indicator result compatible with @nestjs/terminus.
|
|
1089
1252
|
*
|
|
@@ -1184,5 +1347,19 @@ declare enum JetstreamHeader {
|
|
|
1184
1347
|
/** Set to `'true'` on error responses so the client can distinguish success from failure. */
|
|
1185
1348
|
Error = "x-error"
|
|
1186
1349
|
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Prefixes used in event patterns to route to specific stream types.
|
|
1352
|
+
* Applied by the user when emitting events (e.g. `client.emit('broadcast:config.updated', data)`).
|
|
1353
|
+
*/
|
|
1354
|
+
declare enum PatternPrefix {
|
|
1355
|
+
/** Route to the shared broadcast stream. */
|
|
1356
|
+
Broadcast = "broadcast:",
|
|
1357
|
+
/** Route to the ordered stream. */
|
|
1358
|
+
Ordered = "ordered:"
|
|
1359
|
+
}
|
|
1360
|
+
/** Check if the RPC config specifies JetStream mode. */
|
|
1361
|
+
declare const isJetStreamRpcMode: (rpc: RpcConfig | undefined) => boolean;
|
|
1362
|
+
/** Check if the RPC config specifies Core mode (default). */
|
|
1363
|
+
declare const isCoreRpcMode: (rpc: RpcConfig | undefined) => boolean;
|
|
1187
1364
|
|
|
1188
|
-
export { type Codec, type DeadLetterInfo, EventBus, JETSTREAM_CODEC, JETSTREAM_CONNECTION, JETSTREAM_EVENT_BUS, JETSTREAM_OPTIONS, JetstreamClient, type JetstreamFeatureOptions, JetstreamHeader, JetstreamHealthIndicator, type JetstreamHealthStatus, JetstreamModule, type JetstreamModuleAsyncOptions, type JetstreamModuleOptions, JetstreamRecord, JetstreamRecordBuilder, JetstreamStrategy, JsonCodec, type OrderedEventOverrides, type RpcConfig, RpcContext, type StreamConsumerOverrides, TransportEvent, type TransportHooks, getClientToken, toNanos };
|
|
1365
|
+
export { type Codec, type DeadLetterInfo, EventBus, JETSTREAM_CODEC, JETSTREAM_CONNECTION, JETSTREAM_EVENT_BUS, JETSTREAM_OPTIONS, JetstreamClient, type JetstreamFeatureOptions, JetstreamHeader, JetstreamHealthIndicator, type JetstreamHealthStatus, JetstreamModule, type JetstreamModuleAsyncOptions, type JetstreamModuleOptions, JetstreamRecord, JetstreamRecordBuilder, JetstreamStrategy, JsonCodec, MessageKind, type OrderedEventOverrides, PatternPrefix, type RpcConfig, RpcContext, type StreamConsumerOverrides, StreamKind, TransportEvent, type TransportHooks, getClientToken, isCoreRpcMode, isJetStreamRpcMode, toNanos };
|