-
Notifications
You must be signed in to change notification settings - Fork 47
/
types.ts
2883 lines (2694 loc) · 72.5 KB
/
types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2020-2022 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { NatsError } from "./error.ts";
import type { MsgHdrs } from "./headers.ts";
import type { Authenticator } from "./authenticator.ts";
import { TypedSubscriptionOptions } from "./typedsub.ts";
import { QueuedIterator } from "./queued_iterator.ts";
export const Empty = new Uint8Array(0);
/**
* Events reported by the {@link NatsConnection.status} iterator.
*/
export enum Events {
/** Client disconnected */
Disconnect = "disconnect",
/** Client reconnected */
Reconnect = "reconnect",
/** Client received a cluster update */
Update = "update",
/** Client received a signal telling it that the server is transitioning to Lame Duck Mode */
LDM = "ldm",
/** Client received an async error from the server */
Error = "error",
}
export interface Status {
type: Events | DebugEvents;
data: string | ServersChanged | number;
permissionContext?: { operation: string; subject: string };
}
/**
* Other events that can be reported by the {@link NatsConnection.status} iterator.
* These can usually be safely ignored, as higher-order functionality of the client
* will handle them.
*/
export enum DebugEvents {
Reconnecting = "reconnecting",
PingTimer = "pingTimer",
StaleConnection = "staleConnection",
}
export const DEFAULT_PORT = 4222;
export const DEFAULT_HOST = "127.0.0.1";
// DISCONNECT Parameters, 2 sec wait, 10 tries
export const DEFAULT_RECONNECT_TIME_WAIT = 2 * 1000;
export const DEFAULT_MAX_RECONNECT_ATTEMPTS = 10;
export const DEFAULT_JITTER = 100;
export const DEFAULT_JITTER_TLS = 1000;
// Ping interval
export const DEFAULT_PING_INTERVAL = 2 * 60 * 1000; // 2 minutes
export const DEFAULT_MAX_PING_OUT = 2;
export interface ConnectFn {
(opts: ConnectionOptions): Promise<NatsConnection>;
}
export interface NatsConnection {
/**
* ServerInfo to the currently connected server or undefined
*/
info?: ServerInfo;
/**
* Returns a promise that can be used to monitor if the client closes.
* The promise can resolve an Error if the reason for the close was
* an error. Note that the promise doesn't reject, but rather resolves
* to the error if there was one.
*/
closed(): Promise<void | Error>;
/**
* Close will close the connection to the server. This call will terminate
* all pending requests and subscriptions. The returned promise resolves when
* the connection closes.
*/
close(): Promise<void>;
/**
* Publishes the specified data to the specified subject.
* @param subject
* @param data
* @param options
*/
publish(subject: string, data?: Uint8Array, options?: PublishOptions): void;
/**
* Subscribe expresses interest in the specified subject. The subject may
* have wildcards. Messages are delivered to the {@link SubscriptionOptions.callback}
* if specified. Otherwise, the subscription is an async iterator for {@link Msg}.
*
* @param subject
* @param opts
*/
subscribe(subject: string, opts?: SubscriptionOptions): Subscription;
/**
* Publishes a request with specified data in the specified subject expecting a
* response before {@link RequestOptions.timeout} milliseconds. The api returns a
* Promise that resolves when the first response to the request is received. If
* there are no responders (a subscription) listening on the request subject,
* the request will fail as soon as the server processes it.
*
* @param subject
* @param data
* @param opts
*/
request(
subject: string,
data?: Uint8Array,
opts?: RequestOptions,
): Promise<Msg>;
/**
* Returns a Promise that resolves when the client receives a reply from
* the server. Use of this API is not necessary by clients.
*/
flush(): Promise<void>;
/**
* Initiates a drain on the connection and returns a promise that resolves when the
* drain completes and the connection closes.
*
* Drain is an ordered shutdown of the client. Instead of abruptly closing the client,
* subscriptions are drained, that is messages not yet processed by a subscription are
* handled before the subscription is closed. After subscriptions are drained it is not
* possible to create a new subscription. Then all pending outbound messages are
* sent to the server. Finally, the connection is closed.
*/
drain(): Promise<void>;
/**
* Returns true if the client is closed.
*/
isClosed(): boolean;
/**
* Returns true if the client is draining.
*/
isDraining(): boolean;
/**
* Returns the hostport of the server the client is connected to.
*/
getServer(): string;
/**
* Returns an async iterator of {@link Status} that may be
* useful in understanding when the client looses a connection, or
* reconnects, or receives an update from the cluster among other things.
*
* @return an AsyncIterable<Status>
*/
status(): AsyncIterable<Status>;
/**
* Returns some metrics such as the number of messages and bytes
* sent and recieved by the client.
*/
stats(): Stats;
/**
* Returns a Promise to a {@link JetStreamManager} which allows the client
* to access Streams and Consumers information.
*
* @param opts
*/
jetstreamManager(opts?: JetStreamOptions): Promise<JetStreamManager>;
/**
* Returns a {@link JetStreamClient} which allows publishing messages to
* JetStream or consuming messages from streams.
*
* @param opts
*/
jetstream(opts?: JetStreamOptions): JetStreamClient;
/**
* @return the number of milliseconds it took for a {@link flush}.
*/
rtt(): Promise<number>;
}
/**
* ConnectionOptions does something
*/
export interface ConnectionOptions {
/**
* When the server requires authentication, set an {@link Authenticator}.
* An authenticator is created automatically for username/password and token
* authentication configurations
* if {@link user} and {@link pass} or the {@link token} options are set.
*/
authenticator?: Authenticator;
/**
* When set to `true` the client will print protocol messages that it receives
* or sends to the server.
*/
debug?: boolean;
/**
* Sets the maximum count of ping commands that can be awaiting a response
* before rasing a stale connection status {@link DebugEvents.StaleConnection }
* notification {@link NatsConnection.status} and initiating a reconnect.
*
* @see pingInterval
*/
maxPingOut?: number;
/**
* Sets the maximum count of per-server reconnect attempts before giving up.
* Set to `-1` to never give up.
*
* @default 10
*/
maxReconnectAttempts?: number;
/**
* Sets the client name. When set, the server monitoring pages will display
* this name when referring to this client.
*/
name?: string;
/**
* When set to true, messages published by this client will not match
* this client's subscriptions, so the client is guaranteed to never
* receive self-published messages on a subject that it is listening on.
*/
noEcho?: boolean;
/**
* If set to true, the client will not randomize its server connection list.
*/
noRandomize?: boolean;
/**
* Sets the password for a client connection. Requires that the {@link user}
* option be set. See {@link authenticator}.
*/
pass?: string;
/**
* When set to true, the server may perform additional checks on protocol
* message requests. This option is only useful for NATS client development
* and shouldn't be used, as it affects server performance.
*/
pedantic?: boolean;
/**
* Sets the number of milliseconds between client initiated ping commands.
* See {@link maxPingOut}.
* @default 2 minutes.
*/
pingInterval?: number;
/**
* Sets the port number on the localhost (127.0.0.1) where the nats-server is running.
* This option is mutually exclusive with {@link servers}.
*/
port?: number;
/**
* When set to true, the server will attempt to reconnect so long as
* {@link maxReconnectAttempts} doesn't prevent it.
* @default true
*/
reconnect?: boolean;
/**
* Set a function that dynamically determines the number of milliseconds
* that the client should wait for the next reconnect attempt.
*/
reconnectDelayHandler?: () => number;
/**
* Set the upper bound for a random delay in milliseconds added to
* {@link reconnectTimeWait}.
*
* @default 100 millis
*/
reconnectJitter?: number;
/**
* Set the upper bound for a random delay in milliseconds added to
* {@link reconnectTimeWait}. This only affects TLS connections
*
* @default 1000 millis
*/
reconnectJitterTLS?: number;
/**
* Set the number of millisecods between reconnect attempts.
*
* @default 2000 millis
*/
reconnectTimeWait?: number;
/**
* Set the hostport(s) where the client should attempt to connect.
* This option is mutually exclusive with {@link port}.
*
* @default 127.0.0.1:4222
*/
servers?: Array<string> | string;
/**
* Sets the number of milliseconds the client should wait for a server
* handshake to be established.
*
* @default 20000 millis
*/
timeout?: number;
/**
* When set (can be an empty object), the client requires a secure connection.
* TlsOptions honored depend on the runtime. Consult the specific NATS javascript
* client GitHub repo/documentation. When set to null, the client should fail
* should not connect using TLS. In the case where TLS is available on the server
* a standard connection will be used. If TLS is required, the connection will fail.
*/
tls?: TlsOptions | null;
/**
* Set to a client authentication token. Note that these tokens are
* a specific authentication strategy on the nats-server. This option
* is mutually exclusive of {@link user} and {@link pass}. See {@link authenticator}.
*/
token?: string;
/**
* Sets the username for a client connection. Requires that the {@link pass}
* option be set. See {@link authenticator}.
*/
user?: string;
/**
* When set to true, the server will send response to all server commands.
* This option is only useful for NATS client development and shouldn't
* be used, as it affects server performance.
*/
verbose?: boolean;
/**
* When set to true {@link maxReconnectAttempts} will not trigger until the client
* has established one connection.
*/
waitOnFirstConnect?: boolean;
/**
* When set to true, cluster information gossiped by the nats-server will
* not augment the lists of server(s) known by the client.
*/
ignoreClusterUpdates?: boolean;
/**
* A string prefix (must be a valid subject prefix) prepended to inboxes
* generated by client. This allows a client with limited subject permissions
* to specify a subject where requests can deliver responses.
*/
inboxPrefix?: string;
}
/**
* TlsOptions that can be specified to a client. Note that
* the options are typically runtime specific, so some clients won't support
* them at all. In other cases they will match to the runtime's TLS options.
*
* If no options are specified, but the argument for TlsOptions is an object,
* the client is requesting to only use connections that are secured by TLS.
*/
export interface TlsOptions {
certFile?: string;
cert?: string;
caFile?: string;
ca?: string;
keyFile?: string;
key?: string;
}
/**
* Represents a message delivered by NATS. This interface is used by
* Subscribers.
*/
export interface Msg {
/**
* The subject the message was sent to
*/
subject: string;
/**
* The subscription ID where the message was dispatched.
*/
sid: number;
/**
* A possible subject where the recipient may publish a reply (in the cases
* where the message represents a request).
*/
reply?: string;
/**
* The message's data (or payload)
*/
data: Uint8Array;
/**
* Possible headers that may have been set by the server or the publisher.
*/
headers?: MsgHdrs;
/**
* Convenience to publish a response to the {@link reply} subject in the
* message - this is the same as doing `nc.publish(msg.reply, ...)`.
* @param data
* @param opts
*/
respond(data?: Uint8Array, opts?: PublishOptions): boolean;
}
export interface SubOpts<T> {
/**
* Optional queue name (subscriptions on the same subject that use queues
* are horizontally load balanced when part of the same queue).
*/
queue?: string;
/**
* Optional maximum number of messages to deliver to the subscription
* before it is auto-unsubscribed.
*/
max?: number;
/**
* Optional maximum number of milliseconds before a timer raises an error. This
* useful to monitor a subscription that is expected to yield messages.
* The timer is cancelled when the first message is received by the subscription.
*/
timeout?: number;
/**
* An optional function that will handle messages. Typically, messages
* are processed via an async iterator on the subscription. If this
* option is provided, messages are processed by the specified function.
* @param err
* @param msg
*/
callback?: (err: NatsError | null, msg: T) => void;
}
/**
* Type alias for a SubOpts<Msg>
*/
export type SubscriptionOptions = SubOpts<Msg>;
export interface Base {
subject: string;
callback: (error: NatsError | null, msg: Msg) => void;
received: number;
timeout?: number | null;
max?: number | undefined;
draining: boolean;
}
/**
* ServerInfo represents information from the connected server
*/
export interface ServerInfo {
/**
* True if the server requires authentication
*/
"auth_required"?: boolean;
/**
* Server-assigned client_id
*/
"client_id": number;
/**
* The client's IP as seen by the server
*/
"client_ip"?: string;
cluster?: string;
/**
* Other servers available on the connected cluster
*/
"connect_urls"?: string[];
/**
* Git commit information on the built server binary
*/
"git_commit"?: string;
/**
* Version information on the Go stack used to build the server binary
*/
go: string;
/**
* True if the server supports headers
*/
headers?: boolean;
/**
* Hostname of the connected server
*/
host: string;
/**
* True if the server supports JetStream
*/
jetstream?: boolean;
/**
* True if the server is in Lame Duck Mode
*/
ldm?: boolean;
/**
* Max number of bytes in message that can be sent to the server
*/
"max_payload": number;
/**
* If the server required nkey or JWT authentication the nonce used during authentication.
*/
nonce?: string;
/**
* The port where the server is listening
*/
port: number;
/**
* Version number of the NATS protocol
*/
proto: number;
/**
* The ID of the server
*/
"server_id": string;
/**
* The name of the server
*/
"server_name": string;
/**
* True if TLS is available
*/
"tls_available"?: boolean;
/**
* True if TLS connections are required
*/
"tls_required"?: boolean;
/**
* True if TLS client certificate verification is required
*/
"tls_verify"?: boolean;
/**
* The nats-server version
*/
version: string;
}
export interface Server {
hostname: string;
port: number;
listen: string;
src: string;
tlsName: string;
resolve(
opts: Partial<{ fn: DnsResolveFn; randomize: boolean }>,
): Promise<Server[]>;
}
/**
* ServerChanged records servers in the cluster that were added or deleted.
*/
export interface ServersChanged {
/** list of added servers */
readonly added: string[];
/** list of deleted servers */
readonly deleted: string[];
}
/**
* Basic interface to a Subscription type
*/
export interface Sub<T> extends AsyncIterable<T> {
/** A promise that resolves when the subscription closes */
closed: Promise<void>;
/**
* Stop the subscription from receiving messages. You can optionally
* specify that the subscription should stop after the specified number
* of messages have been received. Note this count is since the lifetime
* of the subscription.
* @param max
*/
unsubscribe(max?: number): void;
/**
* Drain the subscription, closing it after processing all messages
* currently in flight for the client. Returns a promise that resolves
* when the subscription finished draining.
*/
drain(): Promise<void>;
/**
* Returns true if the subscription is draining.
*/
isDraining(): boolean;
/**
* Returns true if the subscription is closed.
*/
isClosed(): boolean;
/**
* @ignore
*/
callback(err: NatsError | null, msg: Msg): void;
/**
* Returns the subject that was used to create the subscription.
*/
getSubject(): string;
/**
* Returns the number of messages received by the subscription.
*/
getReceived(): number;
/**
* Returns the number of messages that have been processed by the subscription.
*/
getProcessed(): number;
/**
* Returns the number of messages that are pending processing. Note that this
* is method is only valid for iterators.
*/
getPending(): number;
/** @ignore */
getID(): number;
/**
* Return the max number of messages before the subscription will unsubscribe.
*/
getMax(): number | undefined;
}
/**
* Type alias for NATS core subscriptions
*/
export type Subscription = Sub<Msg>;
export interface RequestOptions {
/**
* number of milliseconds before the request will timeout.
*/
timeout: number;
/**
* MsgHdrs to include with the request.
*/
headers?: MsgHdrs;
/**
* If true, the request API will create a regular NATS subscription
* to process the response. Otherwise a shared muxed subscriptions is
* used. Requires {@link reply}
*/
noMux?: boolean;
/**
* The subject where the response should be sent to. Requires {@link noMux}
*/
reply?: string;
}
export enum RequestStrategy {
Timer = "timer",
Count = "count",
JitterTimer = "jitterTimer",
SentinelMsg = "sentinelMsg",
}
export interface RequestManyOptions {
strategy: RequestStrategy;
maxWait: number;
headers?: MsgHdrs;
maxMessages?: number;
noMux?: boolean;
}
export interface PublishOptions {
/**
* An optional subject where a response should be sent.
* Note you must have a subscription listening on this subject
* to receive the response.
*/
reply?: string;
/**
* Optional headers to include with the message.
*/
headers?: MsgHdrs;
}
export interface Stats {
/**
* Number of bytes received by the client.
*/
inBytes: number;
/**
* Number of bytes sent by the client.
*/
outBytes: number;
/**
* Number of messages received by the client.
*/
inMsgs: number;
/**
* Number of messages sent by the client.
*/
outMsgs: number;
}
export interface URLParseFn {
(u: string): string;
}
export interface DnsResolveFn {
(h: string): Promise<string[]>;
}
/**
* Options to a JetStream options applied to all JetStream or JetStreamManager requests.
*/
export interface JetStreamOptions {
/**
* Prefix required to interact with JetStream. Must match
* server configuration.
*/
apiPrefix?: string;
/**
* Number of milliseconds to wait for a JetStream API request.
* @default ConnectionOptions.timeout
* @see ConnectionOptions.timeout
*/
timeout?: number;
/**
* Name of the JetStream domain. This value automatically modifies
* the default JetStream apiPrefix.
*/
domain?: string;
}
/**
* The API for interacting with JetStream resources
*/
export interface JetStreamManager {
/**
* JetStream API to interact with Consumers
*/
consumers: ConsumerAPI;
/**
* JetStream API to interact with Streams
*/
streams: StreamAPI;
/**
* Returns JetStreamAccountStats for the current client account.
*/
getAccountInfo(): Promise<JetStreamAccountStats>;
/**
* Returns an async iteartor
*/
advisories(): AsyncIterable<Advisory>;
}
/**
* Options for a JetStream pull subscription which define how long
* the pull request will remain open and limits the amount of data
* that the server could return.
*/
export interface PullOptions {
/**
* Max number of messages to retrieve in a pull.
*/
batch: number;
/**
* If true, the request for messages will end when received by the server
*/
"no_wait": boolean;
/**
* If set, the number of milliseconds to wait for the number of messages
* specified in {@link batch}
*/
expires: number;
/**
* If set, the max number of bytes to receive. The server will limit the
* number of messages in the batch to fit within this setting.
*/
"max_bytes": number;
"idle_heartbeat": number;
}
/**
* The response returned by the JetStream server when a message is added to a stream.
*/
export interface PubAck {
/**
* The name of the stream
*/
stream: string;
/**
* The domain of the JetStream
*/
domain?: string;
/**
* The sequence number of the message as stored in JetStream
*/
seq: number;
/**
* True if the message is a duplicate
*/
duplicate: boolean;
/**
* Acknowledges the PubAck back to the server
*/
ack(): void;
}
/**
* Options for messages published to JetStream
*/
export interface JetStreamPublishOptions {
/**
* A string identifier used to detect duplicate published messages.
* If the msgID is reused within the streams's `duplicate_window`,
* the message will be rejected by the stream, and the {@link PubAck} will
* mark it as a `duplicate`.
*/
msgID: string;
/**
* The number of milliseconds to wait for the PubAck
*/
timeout: number;
// ackWait: Nanos;
/**
* Headers associated with the message. You can create an instance of
* MsgHdrs with the headers() function.
*/
headers: MsgHdrs;
/**
* Set of constraints that when specified are verified by the server.
* If the constraint(s) doesn't match, the server will reject the message.
* These settings allow you to implement deduplication and consistency
* strategies.
*/
expect: Partial<{
/**
* The expected last msgID of the last message received by the stream.
*/
lastMsgID: string;
/**
* The expected stream capturing the message
*/
streamName: string;
/**
* The expected last sequence on the stream.
*/
lastSequence: number;
/**
* The expected last sequence on the stream for a message with this subject
*/
lastSubjectSequence: number;
}>;
}
/**
* A JetStream interface that allows you to request the ConsumerInfo on the backing object.
*/
export interface ConsumerInfoable {
consumerInfo(): Promise<ConsumerInfo>;
}
export interface Closed {
/**
* A promise that when resolves, indicates that the object is closed.
*/
closed: Promise<void>;
}
/**
* The JetStream Subscription object
*/
export type JetStreamSubscription =
& Sub<JsMsg>
& Destroyable
& Closed
& ConsumerInfoable;
export type JetStreamSubscriptionOptions = TypedSubscriptionOptions<JsMsg>;
export interface Pullable {
/**
* Sends a request from the client requesting the server for more messages.
* @param opts
*/
pull(opts?: Partial<PullOptions>): void;
}
export interface Destroyable {
/**
* Destroys a resource on the server. Returns a promise that resolves to true
* whene the operation has been completed
*/
destroy(): Promise<void>;
}
/**
* The JetStream pull subscription object.
*/
export type JetStreamPullSubscription = JetStreamSubscription & Pullable;
/**
* The signature a message handler for a JetStream subscription.
*/
export type JsMsgCallback = (err: NatsError | null, msg: JsMsg | null) => void;
/**
* The interface for creating instances of different JetStream materialized views.
*/
export interface Views {
/**
* Gets or creates a JetStream KV store
* @param name - name for the KV
* @param opts - optional options to configure the KV and stream backing
*/
kv: (name: string, opts?: Partial<KvOptions>) => Promise<KV>;
os: (
name: string,
opts?: Partial<ObjectStoreOptions>,
) => Promise<ObjectStore>;
}
// FIXME: pulls must limit to maxAcksInFlight
/**
* Interface for interacting with JetStream data
*/
export interface JetStreamClient {
/**
* Publishes a message to a stream. If not stream is configured to store the message, the
* request will fail with {@link ErrorCode.NoResponders} error.
*
* @param subj - the subject for the message
* @param data - the message's data
* @param options - the optional message
*/
publish(
subj: string,
data?: Uint8Array,
options?: Partial<JetStreamPublishOptions>,
): Promise<PubAck>;
/**
* Retrieves a single message from JetStream
* @param stream - the name of the stream
* @param consumer - the consumer's durable name (if durable) or name if ephemeral
* @param expires - the number of milliseconds to wait for a message
*/
pull(stream: string, consumer: string, expires?: number): Promise<JsMsg>;
/**
* Similar to pull, but able to configure the number of messages, etc via PullOptions.
* @param stream - the name of the stream
* @param durable - the consumer's durable name (if durable) or name if ephemeral
* @param opts
*/
fetch(
stream: string,
durable: string,
opts?: Partial<PullOptions>,
): QueuedIterator<JsMsg>;
/**
* Creates a pull subscription. A pull subscription relies on the client to request more
* messages from the server. If the consumer doesn't exist, it will be created matching
* the consumer options provided.
*
* It is recommended that a consumer be created first using JetStreamManager APIs and then
* use the bind option to simply attach to the created consumer.
*
* If the filter subject is not specified in the options, the filter will be set to match
* the specified subject.
*
* It is more efficient than {@link fetch} or {@link pull} because
* a single subscription is used between invocations.
*
* @param subject - a subject used to locate the stream
* @param opts
*/
pullSubscribe(
subject: string,
opts: ConsumerOptsBuilder | Partial<ConsumerOpts>,
): Promise<JetStreamPullSubscription>;
/**
* Creates a push subscription. The JetStream server feeds messages to this subscription
* without the client having to request them. The rate at which messages are provided can
* be tuned by the consumer by specifying {@link ConsumerOpts.rate_limit_bps} and/or
* {@link ConsumerOpts.maxAckPending}.
*
* It is recommended that a consumer be created first using JetStreamManager APIs and then
* use the bind option to simply attach to the created consumer.
*
* If the filter subject is not specified in the options, the filter will be set to match
* the specified subject.
*
* @param subject - a subject used to locate the stream
* @param opts
*/
subscribe(
subject: string,
opts: ConsumerOptsBuilder | Partial<ConsumerOpts>,
): Promise<JetStreamSubscription>;