This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
natsClient.ts
336 lines (298 loc) · 9.62 KB
/
natsClient.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
// This file is part of the @egomobile/nats distribution.
// Copyright (c) Next.e.GO Mobile SE, Aachen, Germany (https://e-go-mobile.com/)
//
// @egomobile/nats is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, version 3.
//
// @egomobile/nats is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { ConnectionOptions, connect as connectToNats, NatsConnection } from "nats";
import type { GetterOrValue, Nilable } from "../internal";
import { EventEmitter } from "node:events";
import { INatsPublisherOptions, NatsPublisher } from "./natsPublisher";
import { INatsConsumerOptions, NatsConsumer } from "./natsConsumer";
/**
* Options for `NatsClient.createConsumer()` method.
*/
export type CreateNatsConsumerOptions = Omit<INatsConsumerOptions, "client">;
/**
* Options for `NatsClient.createPublisher()` method.
*/
export type CreateNatsPublisherOptions = Omit<INatsPublisherOptions, "client">;
/**
* Options for `NatsClient.exitOnClode()` method.
*/
export interface IExitOnCloseNatsOptions {
/**
* The custom exit code.
*
* @default `2`.
*/
exitCode?: Nilable<string>;
}
/**
* Options for `NatsClient` class.
*/
export interface INatsClientOptions {
/**
* A custom `AbortController`.
*/
abortController?: Nilable<AbortController>;
/**
* Custom connection options or the function that receives it.
*/
connectionOptions?: Nilable<GetterOrValue<ConnectionOptions>>;
/**
* Is in mock mode or not.
*/
isMock?: Nilable<boolean>;
/**
* Name of the connection.
*/
name: string;
}
/**
* A NATS client.
*
* @example
* ```
* import { NatsClient } from "@egomobile/nats"
*
* interface IFooMessage {
* bar: number;
* }
*
* // creates and opens an instance to a NATS
* // server using `NATS_URL`, `NATS_USER` and `NATS_PASSWORD`
* // environment variables
* const client = NatsClient.open({
* "name": process.env.POD_NAME!.trim()
* })
*
* const consumer = client.createConsumer<IFooMessage>("foo-stream-name")
* consumer.subscribe()
*
* const publisher = client.createPublisher<IFooMessage>("foo-stream-name")
* await publisher.publish({
* "bar": 42
* })
* ```
*/
export class NatsClient extends EventEmitter {
readonly #abortController: AbortController;
#connection: Nilable<NatsConnection>;
readonly #getConnectionOptions: () => Promise<ConnectionOptions>;
/**
* Initializes a new instance of that class.
*
* @param {Nilable<INatsClientOptions>} [options] Custom options.
*/
constructor(public readonly options: INatsClientOptions) {
super();
if (options?.connectionOptions) {
if (typeof options.connectionOptions === "function") {
const getConnectionOptions = options.connectionOptions;
this.#getConnectionOptions = async () => {
return Promise.resolve(getConnectionOptions());
};
}
else if (typeof options.connectionOptions === "object") {
const connectionOptions = options.connectionOptions;
this.#getConnectionOptions = async () => {
return connectionOptions;
};
}
else {
throw new TypeError("options.connectionOptions needs to be of type object or function");
}
}
else {
// default
this.#getConnectionOptions = async () => {
return {
"servers": process.env.NATS_URL?.split("\n"),
"user": process.env.NATS_USER?.trim(),
"pass": process.env.NATS_PASSWORD?.trim()
};
};
}
this.#abortController = options?.abortController ?? new AbortController();
}
/**
* Closes the connection.
*
* @returns {Promise<boolean>} The promise that indicates if operation was successful or not.
*/
async close(): Promise<boolean> {
const currentConnection = this.#connection;
if (currentConnection && !currentConnection.isClosed()) {
await currentConnection!.close();
this.#connection = null;
return true;
}
return false;
}
/**
* Connects to a NATS instance.
*
* @returns {Promise<NatsConnection>} The promise with the new connection.
*/
async connect(): Promise<NatsConnection> {
if (this.isEnabled) {
throw new Error("there is already an open connection");
}
const newConnection = await connectToNats(
await this.#getConnectionOptions()
);
this.#connection = newConnection;
return newConnection;
}
/**
* Gets the underlying `NatsConnection`, if open.
*
* @returns {Nilable<NatsConnection>} The connection instance, if available.
*/
get connection(): Nilable<NatsConnection> {
return this.#connection;
}
/**
* Creates a new consumer instance based on this client.
*
* @param {CreateNatsConsumerOptions} options The options.
* @param {string} streamName The name of the stream.
*
* @returns {NatsConsumer<T>} The consumer.
*/
createConsumer<T>(streamName: string): NatsConsumer<T>;
createConsumer<T>(options: CreateNatsConsumerOptions): NatsConsumer<T>;
createConsumer<T>(optionsOrStreamName: string | CreateNatsConsumerOptions): NatsConsumer<T> {
let options: CreateNatsConsumerOptions;
if (typeof optionsOrStreamName === "string") {
options = {
"streamName": optionsOrStreamName
};
}
else {
options = optionsOrStreamName;
}
return new NatsConsumer({
...options,
"client": this,
"abortController": options.abortController ?? this.#abortController
});
}
/**
* Creates a new publisher instance based on this client.
*
* @param {CreateNatsPublisherOptions} options The options.
* @param {string} streamName The name of the stream.
*
* @returns {NatsPublisher<T>} The publisher.
*/
createPublisher<T>(streamName: string): NatsPublisher<T>;
createPublisher<T>(options: CreateNatsPublisherOptions): NatsPublisher<T>;
createPublisher<T>(optionsOrStreamName: string | CreateNatsPublisherOptions): NatsPublisher<T> {
let options: CreateNatsPublisherOptions;
if (typeof optionsOrStreamName === "string") {
options = {
"streamName": optionsOrStreamName
};
}
else {
options = optionsOrStreamName;
}
return new NatsPublisher({
...options,
"client": this
});
}
/**
* Registers system wide events to close process
* and/or `NatsConnection`.
*
* @param {Nilable<IExitOnCloseNatsOptions>} options The options.
*
* @returns {this} This instance.
*/
exitOnClose(options?: Nilable<IExitOnCloseNatsOptions>): this {
const exitCode = options?.exitCode ?? 2;
if (typeof exitCode !== "number") {
throw new TypeError("options.exitCode must be of a number");
}
// close process, if connection to NATS
// is terminated
this.connection!.closed().then(() => {
process.exit(exitCode);
});
// try to close connection, if process closes
process.once("exit", () => {
return this.#tryClose();
});
process.once("SIGINT", () => {
return this.#tryClose();
});
process.once("SIGUSR1", () => {
return this.#tryClose();
});
process.once("SIGUSR2", () => {
return this.#tryClose();
});
process.once("uncaughtException", (error) => {
process.exitCode = exitCode;
console.error("[ERROR]", "@egomobile/nats", error);
this.#tryClose();
});
return this;
}
/**
* Gets if the connection is enabled / open or not.
*
* @returns {boolean} Connection is open or not.
*/
get isEnabled(): boolean {
return !!this.#connection && !this.#connection.isClosed();
}
/**
* Gets if client is in mock mode or not.
*
* @returns {boolean} Is in mock mode or not.
*/
get isMock(): boolean {
return !!this.options.isMock;
}
/**
* Creates a new `NatsClient` instance and opens a connection.
*
* @param {INatsClientOptions} options The options.
*
* @returns {Promise<NatsClient>} The promise with the new client instance.
*/
static async open(options: INatsClientOptions): Promise<NatsClient> {
const newClient = new this(options);
await newClient.connect();
return newClient;
}
/**
* Shorthand for `options.name`.
*
* @returns {string} The client name.
*/
get name(): string {
return this.options.name;
}
async #tryClose() {
this.#abortController.abort();
try {
await this.connection?.close();
}
catch (error) {
console.warn("[WARN]", "@egomobile/nats", error);
}
}
}