-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIMessageQueue.ts
More file actions
483 lines (434 loc) · 11.7 KB
/
Copy pathIMessageQueue.ts
File metadata and controls
483 lines (434 loc) · 11.7 KB
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
/*!
* Basic types and interfaces
*
* I'm Queue Software Project
* Copyright (C) 2025 imqueue.com <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* If you want to use this code in a closed source (commercial) project, you can
* purchase a proprietary commercial license. Please contact us at
* <[email protected]> to get commercial licensing options.
*/
import { EventEmitter } from 'events';
import { IMQMode } from './IMQMode';
import { ClusterManager } from './ClusterManager';
export { EventEmitter } from 'events';
/**
* Represents any JSON-serializable value
*/
export type AnyJson =
| boolean
| number
| string
| null
| undefined
| JsonArray
| JsonObject;
/**
* Represents JSON serializable object
*/
export interface JsonObject {
[key: string]: AnyJson;
}
/**
* Represents JSON-serializable array
*/
export interface JsonArray extends Array<AnyJson> {}
/**
* Alias for JsonObject, legacy, outdated, deprecated, try to avoid using.
* Stands here for backward-compatibility only
*
* @deprecated
*/
export type IJson = JsonObject;
/**
* Logger interface
*/
export interface ILogger {
/**
* Log level function
*
* @param {...any[]} args
*/
log(...args: any[]): void;
/**
* Info level function
*
* @param {...any[]} args
*/
info(...args: any[]): void;
/**
* Warning level function
*
* @param {...any[]} args
*/
warn(...args: any[]): void;
/**
* Error level function
*
* @param {...any[]} args
*/
error(...args: any[]): void;
}
/**
* Defines message format.
*
* @type {IMessage}
*/
export interface IMessage {
/**
* Message unique identifier
*
* @type {string}
*/
id: string;
/**
* Message data. Any JSON-compatible data allowed
*
* @type {JsonObject}
*/
message: JsonObject;
/**
* Message source queue name
*
* @type {string}
*/
from: string;
/**
* Message delay in milliseconds (for delayed messages). Optional.
*
* @type {number}
*/
delay?: number;
}
export interface IServerInput {
/**
* Message queue network unique identifier, optional property
*
* @type {string | undefined}
*/
id?: string;
/**
* Message queue network host
*
* @type {string}
*/
host: string;
/**
* Message queue network port
*
* @type {number}
*/
port: number;
}
export interface IMessageQueueConnection extends IMessageQueueAuthConnection {
/**
* Message queue network unique identifier, optional property
*
* @type {string | undefined}
*/
id?: string;
/**
* Message queue network host
*
* @type {string}
*/
host: string;
/**
* Message queue network port
*
* @type {number}
*/
port: number;
}
export interface IMessageQueueAuthConnection {
/**
* Message queue username
*
* @type {string}
*/
username?: string;
/**
* Message queue password
*
* @type {string}
*/
password?: string;
}
/**
* Message queue options
*/
export interface IMQOptions extends Partial<IMessageQueueConnection> {
/**
* Turns on/off cleanup of the message queues
*
* @type {boolean}
*/
cleanup: boolean;
/**
* Defines cleanup pattern for the name of the queue
* which should be removed during cleanup processing
*
* @type {string}
*/
cleanupFilter: string;
/**
* Message queue vendor
*
* @type {string}
*/
vendor?: string;
/**
* Message queue global key prefix (namespace)
*
* @type {string}
*/
prefix?: string;
/**
* Logger defined to be used within message queue in runtime
*
* @type {ILogger}
*/
logger?: ILogger;
/**
* Watcher check delay period. This is used by a queue watcher
* agent to make sure at least one watcher is available for
* queue operations.
*
* @type {number}
*/
watcherCheckDelay?: number;
/**
* A way to serialize message using compression. Will increase
* load to worker process but can decrease network traffic between worker
* and queue host application
*
* @type {boolean}
*/
useGzip?: boolean;
/**
* Enables/disables safe message delivery. When safe message delivery
* is turned on it will use more complex algorithm for message handling
* by a worker process, guaranteeing that if worker fails the message will
* be delivered to another possible worker anyway. In most cases it
* is not required unless it is required by a system design.
*
* @type {boolean}
*/
safeDelivery?: boolean;
/**
* Time-to-live of worker queues (after this time messages are back to
* main queue for handling if worker died). Only works if safeDelivery
* option enabled.
*
* @type {number}
*/
safeDeliveryTtl?: number;
/**
* Queue cluster instances, if MQ should be clustered
*
* @type {IMessageQueueConnection[]}
*/
cluster?: IMessageQueueConnection[];
/**
* Array of cluster managers used to handle cluster operations.
* Any manager implements specific cluster server detection.
*
* @type {ClusterManager[]}
*/
clusterManagers?: ClusterManager[];
/**
* Enables/disables process signal handling (SIGTERM, SIGINT, SIGABRT)
* by the queue. When enabled, the queue frees its watcher lock and
* exits the process on those signals. Disable when the host
* application manages its own shutdown sequence.
*
* @default true
* @type {boolean}
*/
handleSignals?: boolean;
/**
* When enabled, send() resolves only after the message write is
* confirmed by redis (and rejects on write failures). By default
* writes are fire-and-forget for maximum throughput and failures are
* reported through the optional errorHandler argument only.
*
* @default false
* @type {boolean}
*/
awaitWrites?: boolean;
/**
* Enables/disables verbose logging
*
* @default false
* @type {boolean}
*/
verbose?: boolean;
/**
* Enables/disables extended verbose logging. The output may contain
* sensitive information, so use it with caution. Does not work if a verbose
* option is disabled.
*
* @default false
* @type {boolean}
*/
verboseExtended?: boolean;
}
export interface EventMap {
message: [data: any, id: string, from: string];
error: [error: Error, eventName: string];
}
export type IMessageQueueConstructor = new (
name: string,
options?: Partial<IMQOptions>,
mode?: IMQMode,
) => IMessageQueue;
/**
* Generic messaging queue implementation interface
*
* @example
* ~~~typescript
* import { IMessageQueue, EventEmitter } from '@imqueue/core';
* import { randomUUID } from 'crypto';
*
* class SomeMQAdapter implements IMessageQueue extends EventEmitter {
* public async start(): Promise<SomeMQAdapter> {
* // ... implementation goes here
* return this;
* }
* public async stop(): Promise<SomeMQAdapter> {
* // ... implementation goes here
* return this;
* }
* public async send(
* toQueue: string,
* message: JsonObject,
* delay?: number
* ): Promise<string> {
* const messageId = randomUUID();
* // ... implementation goes here
* return messageId;
* }
* public async destroy(): Promise<void> {
* // ... implementation goes here
* }
* public async clear(): Promise<SomeMQAdapter> {
* // ... implementation goes here
* return this;
* }
* }
* ~~~
*/
export interface IMessageQueue extends EventEmitter<EventMap> {
/**
* Message event. Occurs every time queue got a message.
*
* @event IMessageQueue#message
* @type {JsonObject} message - message data
* @type {string} id - message identifier
* @type {string} from - source queue produced the message
*/
/**
* Error event. Occurs every time queue caught an error.
*
* @event IMessageQueue#error
* @type {Error} err - error caught by message queue
* @type {string} code - message queue error code
*/
/**
* Starts the messaging queue.
* Supposed to be an async function.
*
* @returns {Promise<IMessageQueue>}
*/
start(): Promise<IMessageQueue>;
/**
* Stops the queue (should stop to handle queue messages).
* Supposed to be an async function.
*
* @returns {Promise<IMessageQueue>}
*/
stop(): Promise<IMessageQueue>;
/**
* Sends a message to the given queue name with the given data.
* Supposed to be an async function.
*
* @param {string} toQueue - queue name to which a message should be sent to
* @param {JsonObject} message - message data
* @param {number} [delay] - if specified, a message will be handled in the
* target queue after a specified period of time in milliseconds.
* @param {(err: Error) => void} [errorHandler] - callback called only when
* internal error occurs during message send execution.
* @returns {Promise<string>} - message identifier
*/
send(
toQueue: string,
message: JsonObject,
delay?: number,
errorHandler?: (err: Error) => void,
): Promise<string>;
/**
* Creates or uses a subscription channel with the given name and sets
* message handler on data receive
*
* @param {string} channel - channel name
* @param {(data: JsonObject) => any} handler
*/
subscribe(
channel: string,
handler: (data: JsonObject) => any,
): Promise<void>;
/**
* Closes subscription channel
*
* @return {Promise<void>}
*/
unsubscribe(): Promise<void>;
/**
* Publishes data to the current queue channel
*
* If toName specified will publish to pubsub with a different name. This
* can be used to implement broadcasting some messages to other subscribers
* on other pubsub channels. Different names should be in the same namespace
* (same imq prefix)
*
* @param {JsonObject} data - data to publish as channel message
* @param {string} [toName] - different name of the pubsub to publish to
* @return {Promise<void>}
*/
publish(data: JsonObject, toName?: string): Promise<void>;
/**
* Safely destroys the current queue, unregistered all set event
* listeners and connections.
* Supposed to be an async function.
*
* @returns {Promise<void>}
*/
destroy(): Promise<void>;
/**
* Clears queue data in queue host application.
* Supposed to be an async function.
*
* @returns {Promise<IMessageQueue>}
*/
clear(): Promise<IMessageQueue>;
/**
* Retrieves the current count of messages in the queue.
* Supposed to be an async function.
*
* @returns {Promise<number>}
*/
queueLength(): Promise<number>;
}