UNPKG

17.9 kBTypeScriptView Raw
1/*
2 * Copyright 2013-2021 The NATS Authors
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15export declare function connect(
16 opts?: ConnectionOptions,
17): Promise<NatsConnection>;
18
19export declare const Empty: Uint8Array;
20export declare enum Events {
21 Disconnect = "disconnect",
22 Reconnect = "reconnect",
23 Update = "update",
24 LDM = "ldm",
25 Error = "error"
26}
27export interface Status {
28 type: Events | DebugEvents;
29 data: string | ServersChanged | number;
30}
31export declare enum DebugEvents {
32 Reconnecting = "reconnecting",
33 PingTimer = "pingTimer",
34 StaleConnection = "staleConnection"
35}
36
37export interface NatsConnection {
38 info?: ServerInfo;
39 closed(): Promise<void | Error>;
40 close(): Promise<void>;
41 publish(subject: string, data?: Uint8Array, options?: PublishOptions): void;
42 subscribe(subject: string, opts?: SubscriptionOptions): Subscription;
43 request(subject: string, data?: Uint8Array, opts?: RequestOptions): Promise<Msg>;
44 flush(): Promise<void>;
45 drain(): Promise<void>;
46 isClosed(): boolean;
47 isDraining(): boolean;
48 getServer(): string;
49 status(): AsyncIterable<Status>;
50 stats(): Stats;
51 jetstreamManager(opts?: JetStreamOptions): Promise<JetStreamManager>;
52 jetstream(opts?: JetStreamOptions): JetStreamClient;
53}
54export interface ConnectionOptions {
55 authenticator?: Authenticator;
56 debug?: boolean;
57 ignoreClusterUpdates?: boolean;
58 inboxPrefix?: string;
59 maxPingOut?: number;
60 maxReconnectAttempts?: number;
61 name?: string;
62 noEcho?: boolean;
63 noRandomize?: boolean;
64 pass?: string;
65 pedantic?: boolean;
66 pingInterval?: number;
67 port?: number;
68 reconnect?: boolean;
69 reconnectDelayHandler?: () => number;
70 reconnectJitter?: number;
71 reconnectJitterTLS?: number;
72 reconnectTimeWait?: number;
73 servers?: Array<string> | string;
74 timeout?: number;
75 tls?: TlsOptions;
76 token?: string;
77 user?: string;
78 verbose?: boolean;
79 waitOnFirstConnect?: boolean;
80}
81export interface TlsOptions {
82 certFile?: string;
83 cert?: string;
84 caFile?: string;
85 ca?: string;
86 keyFile?: string;
87 key?: string;
88}
89export interface Msg {
90 subject: string;
91 sid: number;
92 reply?: string;
93 data: Uint8Array;
94 headers?: MsgHdrs;
95 respond(data?: Uint8Array, opts?: PublishOptions): boolean;
96}
97export interface SubOpts<T> {
98 queue?: string;
99 max?: number;
100 timeout?: number;
101 callback?: (err: NatsError | null, msg: T) => void;
102}
103export declare type SubscriptionOptions = SubOpts<Msg>;
104
105export interface ServerInfo {
106 "auth_required"?: boolean;
107 "client_id": number;
108 "client_ip"?: string;
109 "connect_urls"?: string[];
110 "git_commit"?: string;
111 go: string;
112 headers?: boolean;
113 host: string;
114 jetstream?: boolean;
115 ldm?: boolean;
116 "max_payload": number;
117 nonce?: string;
118 port: number;
119 proto: number;
120 "server_id": string;
121 "server_name": string;
122 "tls_available"?: boolean;
123 "tls_required"?: boolean;
124 "tls_verify"?: boolean;
125 version: string;
126}
127
128export interface ServersChanged {
129 readonly added: string[];
130 readonly deleted: string[];
131}
132export interface Sub<T> extends AsyncIterable<T> {
133 unsubscribe(max?: number): void;
134 drain(): Promise<void>;
135 isDraining(): boolean;
136 isClosed(): boolean;
137 callback(err: NatsError | null, msg: Msg): void;
138 getSubject(): string;
139 getReceived(): number;
140 getProcessed(): number;
141 getPending(): number;
142 getID(): number;
143 getMax(): number | undefined;
144}
145export declare type Subscription = Sub<Msg>;
146export interface RequestOptions {
147 timeout: number;
148 headers?: MsgHdrs;
149 noMux?: boolean;
150 reply?: string;
151}
152export interface PublishOptions {
153 reply?: string;
154 headers?: MsgHdrs;
155}
156
157export interface MsgHdrs extends Iterable<[string, string[]]> {
158 hasError: boolean;
159 status: string;
160 code: number;
161 get(k: string): string;
162 set(k: string, v: string): void;
163 append(k: string, v: string): void;
164 has(k: string): boolean;
165 values(k: string): string[];
166 delete(k: string): void;
167}
168export declare function headers(): MsgHdrs;
169
170export declare function createInbox(prefix?: string): string;
171
172export interface Authenticator {
173 (nonce?: string): Auth;
174}
175
176export declare type NoAuth = void;
177export interface TokenAuth {
178 auth_token: string;
179}
180export interface UserPass {
181 user: string;
182 pass?: string;
183}
184export interface NKeyAuth {
185 nkey: string;
186 sig: string;
187}
188export interface JwtAuth {
189 jwt: string;
190 nkey?: string;
191 sig?: string;
192}
193declare type Auth = NoAuth | TokenAuth | UserPass | NKeyAuth | JwtAuth;
194
195export declare function noAuthFn(): Authenticator;
196
197export declare function nkeyAuthenticator(
198 seed?: Uint8Array | (() => Uint8Array),
199): Authenticator;
200
201export declare function jwtAuthenticator(
202 ajwt: string | (() => string),
203 seed?: Uint8Array | (() => Uint8Array),
204): Authenticator;
205
206export declare function credsAuthenticator(creds: Uint8Array): Authenticator;
207
208export declare enum ErrorCode {
209 ApiError = "BAD API",
210 BadAuthentication = "BAD_AUTHENTICATION",
211 BadCreds = "BAD_CREDS",
212 BadHeader = "BAD_HEADER",
213 BadJson = "BAD_JSON",
214 BadPayload = "BAD_PAYLOAD",
215 BadSubject = "BAD_SUBJECT",
216 Cancelled = "CANCELLED",
217 ConnectionClosed = "CONNECTION_CLOSED",
218 ConnectionDraining = "CONNECTION_DRAINING",
219 ConnectionRefused = "CONNECTION_REFUSED",
220 ConnectionTimeout = "CONNECTION_TIMEOUT",
221 Disconnect = "DISCONNECT",
222 InvalidOption = "INVALID_OPTION",
223 InvalidPayload = "INVALID_PAYLOAD",
224 MaxPayloadExceeded = "MAX_PAYLOAD_EXCEEDED",
225 NoResponders = "503",
226 NotFunction = "NOT_FUNC",
227 RequestError = "REQUEST_ERROR",
228 ServerOptionNotAvailable = "SERVER_OPT_NA",
229 SubClosed = "SUB_CLOSED",
230 SubDraining = "SUB_DRAINING",
231 Timeout = "TIMEOUT",
232 Tls = "TLS",
233 Unknown = "UNKNOWN_ERROR",
234 WssRequired = "WSS_REQUIRED",
235 JetStreamInvalidAck = "JESTREAM_INVALID_ACK",
236 JetStream404NoMessages = "404",
237 JetStream408RequestTimeout = "408",
238 JetStream409MaxAckPendingExceeded = "409",
239 JetStreamNotEnabled = "503",
240 AuthorizationViolation = "AUTHORIZATION_VIOLATION",
241 AuthenticationExpired = "AUTHENTICATION_EXPIRED",
242 ProtocolError = "NATS_PROTOCOL_ERR",
243 PermissionsViolation = "PERMISSIONS_VIOLATION",
244}
245
246export declare interface NatsError extends Error {
247 name: string;
248 message: string;
249 code: string;
250 chainedError?: Error;
251}
252
253export interface Stats {
254 inBytes: number;
255 outBytes: number;
256 inMsgs: number;
257 outMsgs: number;
258}
259
260export interface Codec<T> {
261 encode(d: T): Uint8Array;
262 decode(a: Uint8Array): T;
263}
264export declare function StringCodec(): Codec<string>;
265export declare function JSONCodec<T = unknown>(): Codec<T>;
266
267export interface JetStreamOptions {
268 apiPrefix?: string;
269 timeout?: number;
270}
271export interface JetStreamManager {
272 consumers: ConsumerAPI;
273 streams: StreamAPI;
274 getAccountInfo(): Promise<JetStreamAccountStats>;
275 advisories(): AsyncIterable<Advisory>;
276}
277export interface PullOptions {
278 batch: number;
279 "no_wait": boolean;
280 expires: number;
281}
282export interface PubAck {
283 stream: string;
284 seq: number;
285 duplicate: boolean;
286 ack(): void;
287}
288export interface JetStreamPublishOptions {
289 msgID: string;
290 timeout: number;
291 ackWait: Nanos;
292 expect: Partial<{
293 lastMsgID: string;
294 streamName: string;
295 lastSequence: number;
296 }>;
297}
298export interface ConsumerInfoable {
299 consumerInfo(): Promise<ConsumerInfo>;
300}
301export interface Closed {
302 closed: Promise<void>;
303}
304export declare type JetStreamSubscription = Sub<JsMsg> & Destroyable & Closed & ConsumerInfoable;
305export declare type JetStreamSubscriptionOptions = TypedSubscriptionOptions<JsMsg>;
306export interface Pullable {
307 pull(opts?: Partial<PullOptions>): void;
308}
309export interface Destroyable {
310 destroy(): Promise<void>;
311}
312
313export interface Dispatcher<T> {
314 push(v: T): void;
315}
316export interface QueuedIterator<T> extends Dispatcher<T> {
317 [Symbol.asyncIterator](): AsyncIterator<T>;
318 stop(err?: Error): void;
319 getProcessed(): number;
320 getPending(): number;
321 getReceived(): number;
322}
323
324export declare type JetStreamPullSubscription = JetStreamSubscription & Pullable;
325export declare type JsMsgCallback = (err: NatsError | null, msg: JsMsg | null) => void;
326export interface JetStreamClient {
327 publish(subj: string, data?: Uint8Array, options?: Partial<JetStreamPublishOptions>): Promise<PubAck>;
328 pull(stream: string, durable: string): Promise<JsMsg>;
329 fetch(stream: string, durable: string, opts?: Partial<PullOptions>): QueuedIterator<JsMsg>;
330 pullSubscribe(subject: string, opts: ConsumerOptsBuilder | Partial<ConsumerOpts>): Promise<JetStreamPullSubscription>;
331 subscribe(subject: string, opts: ConsumerOptsBuilder | Partial<ConsumerOpts>): Promise<JetStreamSubscription>;
332}
333export interface ConsumerOpts {
334 config: Partial<ConsumerConfig>;
335 mack: boolean;
336 subQueue: string;
337 stream: string;
338 callbackFn?: JsMsgCallback;
339 name?: string;
340 max?: number;
341 debug?: boolean;
342}
343export declare function consumerOpts(): ConsumerOptsBuilder;
344
345export interface ConsumerOptsBuilder {
346 deliverTo(subject: string): void;
347 manualAck(): void;
348 durable(name: string): void;
349 deliverAll(): void;
350 deliverLast(): void;
351 deliverNew(): void;
352 startSequence(seq: number): void;
353 startTime(time: Date | Nanos): void;
354 ackNone(): void;
355 ackAll(): void;
356 ackExplicit(): void;
357 maxDeliver(max: number): void;
358 maxAckPending(max: number): void;
359 maxWaiting(max: number): void;
360 maxMessages(max: number): void;
361 callback(fn: JsMsgCallback): void;
362}
363export interface Lister<T> {
364 next(): Promise<T[]>;
365}
366export interface ConsumerAPI {
367 info(stream: string, consumer: string): Promise<ConsumerInfo>;
368 add(stream: string, cfg: Partial<ConsumerConfig>): Promise<ConsumerInfo>;
369 delete(stream: string, consumer: string): Promise<boolean>;
370 list(stream: string): Lister<ConsumerInfo>;
371}
372export interface StreamAPI {
373 info(stream: string): Promise<StreamInfo>;
374 add(cfg: Partial<StreamConfig>): Promise<StreamInfo>;
375 update(cfg: StreamConfig): Promise<StreamInfo>;
376 purge(stream: string): Promise<PurgeResponse>;
377 delete(stream: string): Promise<boolean>;
378 list(): Lister<StreamInfo>;
379 deleteMessage(stream: string, seq: number): Promise<boolean>;
380 getMessage(stream: string, seq: number): Promise<StoredMsg>;
381 find(subject: string): Promise<string>;
382}
383export interface JsMsg {
384 redelivered: boolean;
385 info: DeliveryInfo;
386 seq: number;
387 headers: MsgHdrs | undefined;
388 data: Uint8Array;
389 subject: string;
390 sid: number;
391 ack(): void;
392 nak(): void;
393 working(): void;
394 term(): void;
395 ackAck(): Promise<boolean>;
396}
397export interface DeliveryInfo {
398 stream: string;
399 consumer: string;
400 redeliveryCount: number;
401 streamSequence: number;
402 deliverySequence: number;
403 timestampNanos: number;
404 pending: number;
405 redelivered: boolean;
406}
407export interface StoredMsg {
408 subject: string;
409 seq: number;
410 header: MsgHdrs;
411 data: Uint8Array;
412 time: Date;
413}
414export interface Advisory {
415 kind: AdvisoryKind;
416 data: unknown;
417}
418export declare enum AdvisoryKind {
419 API = "api_audit",
420 StreamAction = "stream_action",
421 ConsumerAction = "consumer_action",
422 SnapshotCreate = "snapshot_create",
423 SnapshotComplete = "snapshot_complete",
424 RestoreCreate = "restore_create",
425 RestoreComplete = "restore_complete",
426 MaxDeliver = "max_deliver",
427 Terminated = "terminated",
428 Ack = "consumer_ack",
429 StreamLeaderElected = "stream_leader_elected",
430 StreamQuorumLost = "stream_quorum_lost",
431 ConsumerLeaderElected = "consumer_leader_elected",
432 ConsumerQuorumLost = "consumer_quorum_lost"
433}
434export declare type Nanos = number;
435export interface ApiError {
436 code: number;
437 description: string;
438}
439export interface ApiResponse {
440 type: string;
441 error?: ApiError;
442}
443export interface ApiPaged {
444 total: number;
445 offset: number;
446 limit: number;
447}
448export interface ApiPagedRequest {
449 offset: number;
450}
451export interface StreamInfo {
452 config: StreamConfig;
453 created: number;
454 state: StreamState;
455 cluster?: ClusterInfo;
456 mirror?: StreamSourceInfo;
457 sources?: StreamSourceInfo[];
458}
459export interface StreamConfig {
460 name: string;
461 subjects?: string[];
462 retention: RetentionPolicy;
463 "max_consumers": number;
464 "max_msgs": number;
465 "max_bytes": number;
466 discard?: DiscardPolicy;
467 "max_age": number;
468 "max_msg_size"?: number;
469 storage: StorageType;
470 "num_replicas": number;
471 "no_ack"?: boolean;
472 "template_owner"?: string;
473 "duplicate_window"?: number;
474 placement?: Placement;
475 mirror?: StreamSource;
476 sources?: StreamSource[];
477}
478export interface StreamSource {
479 name: string;
480 "opt_start_seq": number;
481 "opt_start_time": string;
482 "filter_subject": string;
483}
484export interface Placement {
485 cluster: string;
486 tags: string[];
487}
488export declare enum RetentionPolicy {
489 Limits = "limits",
490 Interest = "interest",
491 Workqueue = "workqueue"
492}
493export declare enum DiscardPolicy {
494 Old = "old",
495 New = "new"
496}
497export declare enum StorageType {
498 File = "file",
499 Memory = "memory"
500}
501export declare enum DeliverPolicy {
502 All = "all",
503 Last = "last",
504 New = "new",
505 StartSequence = "by_start_sequence",
506 StartTime = "by_start_time"
507}
508export declare enum AckPolicy {
509 None = "none",
510 All = "all",
511 Explicit = "explicit",
512 NotSet = ""
513}
514export declare enum ReplayPolicy {
515 Instant = "instant",
516 Original = "original"
517}
518export interface StreamState {
519 messages: number;
520 bytes: number;
521 "first_seq": number;
522 "first_ts": number;
523 "last_seq": number;
524 "last_ts": string;
525 deleted: number[];
526 lost: LostStreamData;
527 "consumer_count": number;
528}
529export interface LostStreamData {
530 msgs: number;
531 bytes: number;
532}
533export interface ClusterInfo {
534 name?: string;
535 leader?: string;
536 replicas?: PeerInfo[];
537}
538export interface PeerInfo {
539 name: string;
540 current: boolean;
541 offline: boolean;
542 active: Nanos;
543 lag: number;
544}
545export interface StreamSourceInfo {
546 name: string;
547 lag: number;
548 active: Nanos;
549 error?: ApiError;
550}
551export interface PurgeResponse extends Success {
552 purged: number;
553}
554export interface CreateConsumerRequest {
555 "stream_name": string;
556 config: Partial<ConsumerConfig>;
557}
558export interface StreamMsgResponse extends ApiResponse {
559 message: {
560 subject: string;
561 seq: number;
562 data: string;
563 hdrs: string;
564 time: string;
565 };
566}
567export interface SequencePair {
568 "consumer_seq": number;
569 "stream_seq": number;
570}
571export interface ConsumerInfo {
572 "stream_name": string;
573 name: string;
574 created: number;
575 config: ConsumerConfig;
576 delivered: SequencePair;
577 "ack_floor": SequencePair;
578 "num_ack_pending": number;
579 "num_redelivered": number;
580 "num_waiting": number;
581 "num_pending": number;
582 cluster?: ClusterInfo;
583}
584export interface ConsumerListResponse extends ApiResponse, ApiPaged {
585 consumers: ConsumerInfo[];
586}
587export interface StreamListResponse extends ApiResponse, ApiPaged {
588 streams: StreamInfo[];
589}
590export interface Success {
591 success: boolean;
592}
593export declare type SuccessResponse = ApiResponse & Success;
594export interface MsgRequest {
595 seq: number;
596}
597export interface MsgDeleteRequest extends MsgRequest {
598 "no_erase"?: boolean;
599}
600export interface JetStreamAccountStats {
601 memory: number;
602 storage: number;
603 streams: number;
604 consumers: number;
605 api: JetStreamApiStats;
606 limits: AccountLimits;
607}
608export interface JetStreamApiStats {
609 total: number;
610 errors: number;
611}
612export interface AccountInfoResponse extends ApiResponse, JetStreamAccountStats {
613}
614export interface AccountLimits {
615 "max_memory": number;
616 "max_storage": number;
617 "max_streams": number;
618 "max_consumers": number;
619}
620export interface ConsumerConfig {
621 name: string;
622 "durable_name"?: string;
623 "deliver_subject"?: string;
624 "deliver_policy": DeliverPolicy;
625 "opt_start_seq"?: number;
626 "opt_start_time"?: string;
627 "ack_policy": AckPolicy;
628 "ack_wait"?: number;
629 "max_deliver"?: number;
630 "filter_subject"?: string;
631 "replay_policy": ReplayPolicy;
632 "rate_limit_bps"?: number;
633 "sample_freq"?: string;
634 "max_waiting"?: number;
635 "max_ack_pending"?: number;
636}
637export interface Consumer {
638 "stream_name": string;
639 config: ConsumerConfig;
640}
641export interface StreamNames {
642 streams: string[];
643}
644export interface StreamNameBySubject {
645 subject: string;
646}
647export interface NextRequest {
648 expires: number;
649 batch: number;
650 "no_wait": boolean;
651}
652
653export declare type MsgAdapter<T> = (
654 err: NatsError | null,
655 msg: Msg,
656) => [NatsError | null, T | null];
657/**
658 * Callback presented to the user with the converted type
659 */
660export declare type TypedCallback<T> = (
661 err: NatsError | null,
662 msg: T | null,
663) => void;
664export interface TypedSubscriptionOptions<T> extends SubOpts<T> {
665 adapter: MsgAdapter<T>;
666 callback?: TypedCallback<T>;
667 dispatchedFn?: DispatchedFn<T>;
668 cleanupFn?: (sub: Subscription, info?: unknown) => void;
669}
670
671export declare type DispatchedFn<T> = (data: T | null) => void;