@imqueue/core 3.2.4 → 3.3.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.
@@ -23,51 +23,80 @@
23
23
  */
24
24
  import { EventEmitter } from 'node:events';
25
25
  import { type EventMap, type ILogger, type IMessageQueue, type IMessageQueueConnection, IMQMode, type IMQOptions, type IServerInput, type JsonObject, RedisQueue } from './index.js';
26
- interface ClusterServer extends IMessageQueueConnection {
26
+ /**
27
+ * A server registered in a {@link ClusteredRedisQueue}: its address, plus the
28
+ * {@link RedisQueue} instance serving that host.
29
+ *
30
+ * Returned by {@link ClusteredRedisQueue.addServer} so callers can address or
31
+ * inspect one specific host of the cluster.
32
+ */
33
+ export interface ClusterServer extends IMessageQueueConnection {
34
+ /**
35
+ * Queue instance created for this host. Present once the server has been
36
+ * registered; the queue may still be starting.
37
+ */
27
38
  imq?: RedisQueue;
28
39
  }
29
40
  /**
30
- * Class ClusteredRedisQueue
31
- Implements the possibility to scale queues horizontally between several
32
- * redis instances.
41
+ * Scales a single logical queue horizontally across several redis instances.
42
+ * This is what {@link IMQ.create} returns when {@link IMQOptions.cluster} or
43
+ * {@link IMQOptions.clusterManagers} is supplied.
44
+ *
45
+ * @remarks
46
+ * Distribution is asymmetric, and this is the most important thing to know about
47
+ * the class: {@link ClusteredRedisQueue.send} routes each message to exactly
48
+ * one server, chosen by health-aware round-robin that skips instances whose
49
+ * writer connection is not ready. Every other operation — `start`, `stop`,
50
+ * `clear`, `destroy`, `publish`, `subscribe`, `unsubscribe` and `queueLength` —
51
+ * fans out to every server.
52
+ *
53
+ * Every fan-out uses `Promise.all`, so one failing host fails the whole call with
54
+ * no partial-failure reporting and no rollback.
55
+ *
56
+ * The class only `implements` the `EventEmitter` interface rather than extending
57
+ * it, so `instanceof EventEmitter` is false and every emitter method is a
58
+ * delegating shim — see the individual methods for their fan-out semantics, and
59
+ * note in particular that {@link ClusteredRedisQueue.once} is per-server.
33
60
  */
34
61
  export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<EventMap> {
62
+ /**
63
+ * Name of this queue, used as the queue name for every per-host queue in
64
+ * the cluster.
65
+ *
66
+ * @remarks
67
+ * It is read when a server joins, so changing it after construction
68
+ * affects only servers added later — which would silently split the
69
+ * cluster across two queue names. Avoid reassigning it.
70
+ */
35
71
  name: string;
36
72
  /**
37
- * Logger instance associated with this queue instance
73
+ * Logger used for this cluster's own messages, defaulting to
74
+ * {@link IMQOptions.logger} or `console`.
38
75
  *
39
- * @type {ILogger}
76
+ * @remarks
77
+ * Replacing it affects cluster-level logging only — each per-host queue keeps
78
+ * the logger it was constructed with.
40
79
  */
41
80
  logger: ILogger;
42
81
  /**
43
82
  * RedisQueue instances collection
44
- *
45
- * @type {RedisQueue[]}
46
83
  */
47
84
  private imqs;
48
85
  /**
49
86
  * Options associated with this queue instance
50
- *
51
- * @type {IMQOptions}
52
87
  */
53
88
  private readonly options;
54
89
  /**
55
90
  * Part of options without cluster definitions - which are generic for
56
91
  * RedisQueue instances
57
- *
58
- * @type {IMQOptions}
59
92
  */
60
93
  private readonly mqOptions;
61
94
  /**
62
95
  * Cluster servers option definitions
63
- *
64
- * @type {IMessageQueueConnection[]}
65
96
  */
66
97
  private servers;
67
98
  /**
68
99
  * Current queue index (round-robin)
69
- *
70
- * @type {number}
71
100
  */
72
101
  private currentQueue;
73
102
  /**
@@ -76,59 +105,103 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
76
105
  private readonly sendInitTimeout;
77
106
  /**
78
107
  * Total length of RedisQueue instances
79
- *
80
- * @type {number}
81
108
  */
82
109
  private imqLength;
83
110
  /**
84
111
  * Template EventEmitter instance used to replicate queue EventEmitters when
85
112
  * dynamically modifying the cluster
86
- * @type {EventEmitter}
87
- * @private
88
113
  */
89
114
  private readonly templateEmitter;
90
115
  /**
91
116
  * Cluster EventEmitter instance used to notify about changes of
92
117
  * cluster servers
93
- * @type {EventEmitter}
94
- * @private
95
118
  */
96
119
  private readonly clusterEmitter;
97
120
  private state;
98
121
  private initializedClusters;
99
122
  /**
100
- * Class constructor
123
+ * Creates a clustered queue.
124
+ *
125
+ * @param name - queue name, used as the queue name for every per-host queue
126
+ * in the cluster
127
+ * @param options - queue options; must supply {@link IMQOptions.cluster},
128
+ * {@link IMQOptions.clusterManagers}, or both
129
+ * @param _mode - accepted only for {@link IMessageQueueConstructor}
130
+ * signature compatibility and ignored: the underlying queues always
131
+ * run in {@link IMQMode.BOTH}
132
+ * @throws TypeError when neither `cluster` nor a non-empty `clusterManagers`
133
+ * is supplied
101
134
  *
102
- * @param {string} name
103
- * @param {Partial<IMQOptions>} options
104
- * @param {IMQMode} [_mode]
135
+ * @remarks
136
+ * Construction is not inert. One {@link RedisQueue} is created per static
137
+ * cluster entry, and every cluster manager is initialized immediately — so
138
+ * dynamically discovered servers can join before
139
+ * {@link ClusteredRedisQueue.start} is ever called.
140
+ *
141
+ * Cluster entries contribute only `id`, `host` and `port`. All other
142
+ * connection settings, including `username` and `password`, are inherited from
143
+ * the top-level options, so per-server credentials in a cluster entry are
144
+ * ignored.
105
145
  */
106
- constructor(name: string, options?: Partial<IMQOptions>, _mode?: IMQMode);
146
+ constructor(
107
147
  /**
108
- * Starts the messaging queue.
109
- * Supposed to be an async function.
148
+ * Name of this queue, used as the queue name for every per-host queue in
149
+ * the cluster.
110
150
  *
111
- * @returns {Promise<ClusteredRedisQueue>}
151
+ * @remarks
152
+ * It is read when a server joins, so changing it after construction
153
+ * affects only servers added later — which would silently split the
154
+ * cluster across two queue names. Avoid reassigning it.
155
+ */
156
+ name: string, options?: Partial<IMQOptions>, _mode?: IMQMode);
157
+ /**
158
+ * Starts every server's queue concurrently.
159
+ *
160
+ * @returns this queue instance
161
+ *
162
+ * @remarks
163
+ * A failure on any one server rejects this call while the others continue
164
+ * starting, and the cluster stays in the started state — so servers that join
165
+ * afterwards are still started automatically.
166
+ *
167
+ * Always emits one informational log line, regardless of
168
+ * {@link IMQOptions.verbose}.
112
169
  */
113
170
  start(): Promise<ClusteredRedisQueue>;
114
171
  /**
115
- * Stops the queue (should stop handling queue messages).
116
- * Supposed to be an async function.
172
+ * Stops message handling on every server concurrently.
117
173
  *
118
- * @returns {Promise<ClusteredRedisQueue>}
174
+ * @returns this queue instance
175
+ *
176
+ * @remarks
177
+ * Connections are kept and any active subscription is retained, so servers
178
+ * joining afterwards are still subscribed to the remembered channel while
179
+ * remaining stopped. Use {@link ClusteredRedisQueue.destroy} to tear the
180
+ * connections down.
119
181
  */
120
182
  stop(): Promise<ClusteredRedisQueue>;
121
183
  /**
122
- * Sends a message to a given queue name with the given data.
123
- * Supposed to be an async function.
184
+ * Sends a message to one server of the cluster, selected by health-aware
185
+ * round-robin.
186
+ *
187
+ * @param toQueue - queue name to which a message should be sent to
188
+ * @param message - message data
189
+ * @param delay - if specified, a message will be handled in the target queue
190
+ * after a specified period of time in milliseconds
191
+ * @param errorHandler - callback called only when an internal error occurs
192
+ * during message send execution
193
+ * @returns message identifier
194
+ * @throws TypeError propagated from the selected server when it is in
195
+ * {@link IMQMode.WORKER}-only mode
196
+ *
197
+ * @remarks
198
+ * This is the one operation that does not fan out — the message goes to a
199
+ * single server, and not to a stable one.
124
200
  *
125
- * @param {string} toQueue - queue name to which a message should be sent to
126
- * @param {JsonObject} message - message data
127
- * @param {number} [delay] - if specified, a message will be handled in the
128
- target queue after a specified period of time in milliseconds.
129
- * @param {(err: Error) => void} [errorHandler] - callback called only when
130
- internal error occurs during message send execution.
131
- * @returns {Promise<string>} - message identifier
201
+ * When the cluster currently has no servers the send is held until the first
202
+ * server becomes ready, and rejects if none appears within 30 seconds
203
+ * (override with the `IMQ_SEND_INIT_TIMEOUT` environment variable, in
204
+ * milliseconds).
132
205
  */
133
206
  send(toQueue: string, message: JsonObject, delay?: number, errorHandler?: (err: Error) => void): Promise<string>;
134
207
  /**
@@ -136,41 +209,53 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
136
209
  * whose redis connection is currently ready so messages are not routed
137
210
  * to a host that is known to be down. Falls back to the plain
138
211
  * round-robin pick when no instance reports are ready.
139
- *
140
- * @returns {RedisQueue}
141
212
  */
142
213
  private selectQueue;
143
214
  /**
144
215
  * Sends a message once the first cluster server becomes available.
145
216
  * Rejects (rather than hanging forever) if none appears within the
146
217
  * configured timeout and propagates any sent failure.
147
- *
148
- * @returns {Promise<string>}
149
218
  */
150
219
  private sendWhenInitialized;
151
220
  /**
152
- * Safely destroys the current queue, unregistered all set event
153
- * listeners and connections.
154
- * Supposed to be an async function.
221
+ * Destroys every server's queue — closing their connections and removing
222
+ * their event listeners — then unregisters this cluster from all configured
223
+ * cluster managers.
155
224
  *
156
- * @returns {Promise<void>}
225
+ * @remarks
226
+ * Unregistering shuts a manager down entirely once it has no clusters left,
227
+ * which for {@link UDPClusterManager} also terminates its shared UDP worker.
228
+ *
229
+ * The instance must not be reused afterwards: internal routing state is not
230
+ * cleared, so a subsequent {@link ClusteredRedisQueue.send} would silently
231
+ * re-open a connection.
157
232
  */
158
233
  destroy(): Promise<void>;
159
234
  /**
160
- * Clears queue data in queue host application.
161
- * Supposed to be an async function.
235
+ * Deletes this queue's data on every redis host in the cluster,
236
+ * concurrently.
162
237
  *
163
- * @returns {Promise<ClusteredRedisQueue>}
238
+ * @returns this queue instance
164
239
  */
165
240
  clear(): Promise<ClusteredRedisQueue>;
241
+ /**
242
+ * Returns the total number of messages waiting, summed across every redis
243
+ * host in the cluster.
244
+ *
245
+ * @returns sum of the per-host queue lengths
246
+ *
247
+ * @remarks
248
+ * Resolves to `0` when the cluster has no servers, and rejects if any single
249
+ * host cannot be queried. As with {@link RedisQueue.queueLength}, delayed and
250
+ * in-flight messages are not counted.
251
+ */
166
252
  queueLength(): Promise<number>;
167
253
  private verbose;
168
254
  /**
169
255
  * Batch imq action processing on all registered imqs at once
170
256
  *
171
- * @param {string} action
172
- * @param {string} message
173
- * @returns {Promise<this>}
257
+ * @param action -
258
+ * @param message -
174
259
  */
175
260
  private batch;
176
261
  /**
@@ -179,42 +264,252 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
179
264
  * (method chosen by name), so a single contained cast bridges the dynamic
180
265
  * call while the public method signatures below stay fully typed.
181
266
  *
182
- * @template K - EventEmitter method name
183
- * @param {K} method - name of the EventEmitter method to invoke
184
- * @param {any[]} args - arguments to pass to the method
185
- * @returns {unknown[]} - results from each emitter call
267
+ * @typeParam K - EventEmitter method name
268
+ * @param method - name of the EventEmitter method to invoke
269
+ * @param args - arguments to pass to the method
270
+ * @returns results from each emitter call
186
271
  */
187
272
  private applyToEmitters;
273
+ /**
274
+ * Registers a listener on every server's queue and on the internal template
275
+ * used to seed servers that join later.
276
+ *
277
+ * @param args - the arguments `EventEmitter.on` accepts
278
+ * @returns this queue instance
279
+ */
188
280
  on(...args: any[]): this;
281
+ /**
282
+ * Removes a listener from every server's queue and from the internal
283
+ * template.
284
+ *
285
+ * @param args - the arguments `EventEmitter.off` accepts
286
+ * @returns this queue instance
287
+ */
189
288
  off(...args: any[]): this;
289
+ /**
290
+ * Registers a one-shot listener on every server's queue and on the internal
291
+ * template.
292
+ *
293
+ * @param args - the arguments `EventEmitter.once` accepts
294
+ * @returns this queue instance
295
+ *
296
+ * @remarks
297
+ * Because registration is replicated per server, this arms one independent
298
+ * one-shot listener per server — so the callback may run once for each
299
+ * server in the cluster rather than once overall, and more as servers join.
300
+ * Use {@link ClusteredRedisQueue.on} plus explicit de-registration if you
301
+ * need at-most-once semantics.
302
+ */
190
303
  once(...args: any[]): this;
304
+ /**
305
+ * Registers a listener on every server's queue and on the internal template.
306
+ * Alias of {@link ClusteredRedisQueue.on}.
307
+ *
308
+ * @param args - the arguments `EventEmitter.addListener` accepts
309
+ * @returns this queue instance
310
+ */
191
311
  addListener(...args: any[]): this;
312
+ /**
313
+ * Removes a listener from every server's queue and from the internal
314
+ * template. Alias of {@link ClusteredRedisQueue.off}.
315
+ *
316
+ * @param args - the arguments `EventEmitter.removeListener` accepts
317
+ * @returns this queue instance
318
+ */
192
319
  removeListener(...args: any[]): this;
320
+ /**
321
+ * Removes every listener from every server's queue and from the internal
322
+ * template, so servers that join later also start clean.
323
+ *
324
+ * @param args - the arguments `EventEmitter.removeAllListeners` accepts
325
+ * @returns this queue instance
326
+ */
193
327
  removeAllListeners(...args: any[]): this;
328
+ /**
329
+ * Registers a listener at the front of the queue on every server's queue and
330
+ * on the internal template.
331
+ *
332
+ * @param args - the arguments `EventEmitter.prependListener` accepts
333
+ * @returns this queue instance
334
+ */
194
335
  prependListener(...args: any[]): this;
336
+ /**
337
+ * Registers a one-shot listener at the front of the queue on every server's
338
+ * queue and on the internal template.
339
+ *
340
+ * @param args - the arguments `EventEmitter.prependOnceListener` accepts
341
+ * @returns this queue instance
342
+ *
343
+ * @remarks
344
+ * As with {@link ClusteredRedisQueue.once}, the listener is armed per server,
345
+ * so it may fire more than once across the cluster.
346
+ */
195
347
  prependOnceListener(...args: any[]): this;
348
+ /**
349
+ * Sets the maximum listener count on every server's queue and on the internal
350
+ * template.
351
+ *
352
+ * @param args - the arguments `EventEmitter.setMaxListeners` accepts
353
+ * @returns this queue instance
354
+ */
196
355
  setMaxListeners(...args: any[]): this;
356
+ /**
357
+ * Returns the listeners of every server's queue plus the internal template,
358
+ * concatenated.
359
+ *
360
+ * @param args - the arguments `EventEmitter.listeners` accepts
361
+ * @returns the aggregated listeners across the cluster
362
+ *
363
+ * @remarks
364
+ * Because registration is replicated, one listener registered through this
365
+ * class appears once per server plus once for the template — so the array
366
+ * length is a multiple of the logical listener count, not the count itself.
367
+ * Do not compare it against
368
+ * {@link ClusteredRedisQueue.listenerCount}, which reports a single server.
369
+ *
370
+ * The return type is deliberately widened to `any[]`, so Node's per-event
371
+ * listener typing is not available here.
372
+ */
197
373
  listeners(...args: any[]): any[];
374
+ /**
375
+ * Returns the raw listeners of every server's queue plus the internal
376
+ * template, concatenated.
377
+ *
378
+ * @param args - the arguments `EventEmitter.rawListeners` accepts
379
+ * @returns the aggregated raw listeners across the cluster
380
+ *
381
+ * @remarks
382
+ * Aggregated in the same way as {@link ClusteredRedisQueue.listeners}, with
383
+ * the same multiplicity caveat.
384
+ */
198
385
  rawListeners(...args: any[]): any[];
386
+ /**
387
+ * Returns the maximum listener count of the internal template emitter.
388
+ *
389
+ * @returns the template's maximum listener count
390
+ *
391
+ * @remarks
392
+ * Reads the template only — never the underlying per-server queues.
393
+ */
199
394
  getMaxListeners(): number;
395
+ /**
396
+ * Emits an event on every server's queue and on the internal template, so
397
+ * each listener registered through this class runs once per server.
398
+ *
399
+ * @param args - the arguments `EventEmitter.emit` accepts
400
+ * @returns always `true`
401
+ *
402
+ * @remarks
403
+ * The per-emitter results are discarded, so unlike `EventEmitter.emit` the
404
+ * return value does not report whether the event had any listeners — it is
405
+ * `true` even for an empty cluster with no listeners at all.
406
+ */
200
407
  emit(...args: any[]): boolean;
408
+ /**
409
+ * Returns the event names reported by a single representative emitter.
410
+ *
411
+ * @returns the event names from the first server's queue, or from the internal
412
+ * template when the cluster is empty
413
+ *
414
+ * @remarks
415
+ * Like {@link ClusteredRedisQueue.listenerCount}, this does not aggregate
416
+ * across the cluster.
417
+ */
201
418
  eventNames(): (keyof EventMap)[];
419
+ /**
420
+ * Returns the listener count reported by a single representative emitter.
421
+ *
422
+ * @param args - the arguments `EventEmitter.listenerCount` accepts
423
+ * @returns the count from the first server's queue, or from the internal
424
+ * template when the cluster is empty
425
+ *
426
+ * @remarks
427
+ * This deliberately does not aggregate, which makes it inconsistent with
428
+ * {@link ClusteredRedisQueue.listeners}: for a three-server cluster with one
429
+ * registered `message` listener this returns `1` while `listeners('message')`
430
+ * returns four entries.
431
+ */
202
432
  listenerCount(...args: any[]): number;
433
+ /**
434
+ * Publishes the payload on every redis host in the cluster.
435
+ *
436
+ * @param data - payload to publish as a channel message
437
+ * @param toName - optional different pub/sub name to publish to
438
+ * @throws TypeError propagated from any host that has no writer connection
439
+ *
440
+ * @remarks
441
+ * This is the opposite of {@link ClusteredRedisQueue.send}: the same payload
442
+ * goes to all hosts. A subscriber connected to several of them therefore
443
+ * receives one copy per host.
444
+ *
445
+ * Publication is not atomic — if any host has no writer connection the call
446
+ * rejects even though other hosts may already have published. On an empty
447
+ * cluster it resolves without publishing anything, and unlike `send()` it does
448
+ * not wait for a server to appear.
449
+ */
203
450
  publish(data: JsonObject, toName?: string): Promise<void>;
451
+ /**
452
+ * Subscribes the given handler on every redis host in the cluster, and
453
+ * remembers the subscription so servers that join later are subscribed
454
+ * automatically.
455
+ *
456
+ * @param channel - channel name within the queue's prefix namespace
457
+ * @param handler - invoked with the parsed payload of each published message
458
+ * @throws TypeError when a different channel name is supplied while a
459
+ * subscription is already open on the underlying queues
460
+ *
461
+ * @remarks
462
+ * Only one channel per instance is supported. Calling this again with the
463
+ * same channel registers the handler a second time; calling it with a
464
+ * different channel rejects — and the remembered subscription is left
465
+ * pointing at the rejected name, which is what newly joining servers would
466
+ * then use.
467
+ *
468
+ * The handler receives one invocation per host that delivers the message.
469
+ */
204
470
  subscribe(channel: string, handler: (data: JsonObject) => void): Promise<void>;
471
+ /**
472
+ * Unsubscribes from the channel on every redis host and forgets the
473
+ * remembered subscription, so servers joining later are no longer subscribed
474
+ * automatically.
475
+ *
476
+ * @remarks
477
+ * Resolves without effect on an empty cluster.
478
+ */
205
479
  unsubscribe(): Promise<void>;
206
480
  /**
207
- * Adds new servers to the cluster
481
+ * Adds a single server to the cluster and returns its registration record.
482
+ *
483
+ * @param server - address of the server to add
484
+ * @returns the registration record: the resolved `id`, `host` and `port` plus
485
+ * the {@link RedisQueue} instance (`imq`) created for that host, so
486
+ * callers can inspect or address that specific host
208
487
  *
209
- * @param {IServerInput} server
210
- * @returns {void}
488
+ * @remarks
489
+ * Registration is idempotent, and the match rule is broader than an id
490
+ * comparison: a server counts as already present when its `id` matches an
491
+ * existing entry or when its host and port do. Two different ids on the
492
+ * same host and port are therefore treated as one server, and the existing
493
+ * record is returned unchanged without creating a queue.
494
+ *
495
+ * For a genuinely new server this returns as soon as the record is created —
496
+ * starting the queue and re-applying any active subscription happen
497
+ * asynchronously afterwards.
211
498
  */
212
499
  protected addServer(server: IServerInput): ClusterServer;
213
500
  /**
214
- * Removes server from the cluster
501
+ * Removes a server from the cluster, matching by `id` or by host and port.
502
+ *
503
+ * @param server - address of the server to remove
504
+ *
505
+ * @remarks
506
+ * A silent no-op when no server matches. Routing stops using the host
507
+ * immediately, but teardown of its redis connections is started in the
508
+ * background and not awaited: in-flight work on that host is not drained,
509
+ * and teardown errors are only logged.
215
510
  *
216
- * @param {IServerInput} server
217
- * @returns {void}
511
+ * Because the underlying queues are matched by host and port, all entries
512
+ * sharing an address are removed together.
218
513
  */
219
514
  protected removeServer(server: IServerInput): void;
220
515
  private addServerWithQueueInitializing;
@@ -223,4 +518,3 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
223
518
  private findServer;
224
519
  private static matchServers;
225
520
  }
226
- export {};