@imqueue/core 3.2.5 → 3.3.1

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.
@@ -26,13 +26,21 @@ import { IMQMode } from './IMQMode.js';
26
26
  import { ClusterManager } from './ClusterManager.js';
27
27
  export { EventEmitter } from 'node:events';
28
28
  /**
29
- * Represents any JSON-serializable value
29
+ * Any JSON value.
30
+ *
31
+ * @remarks
32
+ * `undefined` is accepted by the type for ergonomics but is not preserved by
33
+ * serialization — `undefined` properties are silently dropped when a message is
34
+ * sent.
30
35
  */
31
36
  export type AnyJson = boolean | number | string | null | undefined | JsonArray | JsonObject;
32
37
  /**
33
38
  * Represents JSON serializable object
34
39
  */
35
40
  export interface JsonObject {
41
+ /**
42
+ * Any string key mapping to any JSON value.
43
+ */
36
44
  [key: string]: AnyJson;
37
45
  }
38
46
  /**
@@ -41,171 +49,239 @@ export interface JsonObject {
41
49
  export interface JsonArray extends Array<AnyJson> {
42
50
  }
43
51
  /**
44
- * Logger interface
52
+ * Minimal logging contract the framework writes diagnostics through. The global
53
+ * `console` satisfies it, and it is the default.
54
+ *
55
+ * Pass an implementation as {@link IMQOptions.logger} to redirect queue output,
56
+ * or a no-op implementation to silence it. The method names match the members of
57
+ * {@link LogLevel}, so a level can be used as a property lookup on a logger.
45
58
  */
46
59
  export interface ILogger {
47
60
  /**
48
- * Log level function
61
+ * Writes a message at the `log` level.
49
62
  *
50
- * @param {...unknown[]} args
63
+ * @param args - values to log
51
64
  */
52
65
  log(...args: unknown[]): void;
53
66
  /**
54
- * Info level function
67
+ * Writes a message at the `info` level.
55
68
  *
56
- * @param {...unknown[]} args
69
+ * @param args - values to log
57
70
  */
58
71
  info(...args: unknown[]): void;
59
72
  /**
60
- * Warning level function
73
+ * Writes a message at the `warn` level.
61
74
  *
62
- * @param {...unknown[]} args
75
+ * @param args - values to log
63
76
  */
64
77
  warn(...args: unknown[]): void;
65
78
  /**
66
- * Error level function
79
+ * Writes a message at the `error` level.
67
80
  *
68
- * @param {...unknown[]} args
81
+ * @param args - values to log
69
82
  */
70
83
  error(...args: unknown[]): void;
71
84
  }
72
85
  /**
73
- * Defines a message format.
86
+ * Internal envelope of a queued message as it is stored in Redis: a generated
87
+ * id, the caller's payload, and the name of the queue that sent it.
74
88
  *
75
- * @type {IMessage}
89
+ * @remarks
90
+ * Consumers never receive this object. The `message` event delivers the payload,
91
+ * the id and the source queue name as three separate arguments.
76
92
  */
77
93
  export interface IMessage {
78
94
  /**
79
- * Message unique identifier
80
- *
81
- * @type {string}
95
+ * Unique identifier assigned to the message when it was sent.
82
96
  */
83
97
  id: string;
84
98
  /**
85
- * Message data. Any JSON-compatible data allowed
86
- *
87
- * @type {JsonObject}
99
+ * The message payload. Must be a JSON object — a bare string, number or
100
+ * array is not a valid message body.
88
101
  */
89
102
  message: JsonObject;
90
103
  /**
91
- * Message source queue name
92
- *
93
- * @type {string}
104
+ * Name of the queue that produced the message.
94
105
  */
95
106
  from: string;
96
107
  /**
97
- * Message delay in milliseconds (for delayed messages). Optional.
108
+ * Intended delay in milliseconds.
98
109
  *
99
- * @type {number}
110
+ * @deprecated Inert, and always absent in practice — the Redis adapter never
111
+ * writes this field and never reads it. Delays are carried in the queue's
112
+ * delayed sorted set, not in the message envelope, so pass the delay to
113
+ * {@link IMessageQueue.send} instead. Scheduled for removal in the next major.
100
114
  */
101
115
  delay?: number;
102
116
  }
117
+ /**
118
+ * Address of a cluster server, as supplied to the cluster membership operations
119
+ * {@link ICluster.add}, {@link ICluster.remove} and {@link ICluster.find}.
120
+ *
121
+ * @remarks
122
+ * Servers are matched by `id` when both sides carry one, and by host and port
123
+ * otherwise. This is {@link IMessageQueueConnection} without the credentials.
124
+ */
103
125
  export interface IServerInput {
104
126
  /**
105
- * Message queue network unique identifier, optional property
106
- *
107
- * @type {string | undefined}
127
+ * Identifier used to match this server against cluster membership. When
128
+ * omitted, matching falls back to host and port.
108
129
  */
109
130
  id?: string;
110
131
  /**
111
- * Message queue network host
112
- *
113
- * @type {string}
132
+ * Host name or IP address of the server.
114
133
  */
115
134
  host: string;
116
135
  /**
117
- * Message queue network port
118
- *
119
- * @type {number}
136
+ * TCP port the server listens on.
120
137
  */
121
138
  port: number;
122
139
  }
140
+ /**
141
+ * A single queue-host endpoint: where to connect and, optionally, how to
142
+ * authenticate.
143
+ *
144
+ * @remarks
145
+ * Used both as the element type of {@link IMQOptions.cluster} and, through
146
+ * `Partial`, as the connection part of {@link IMQOptions} itself — where it
147
+ * defaults to `localhost:6379` without authentication.
148
+ */
123
149
  export interface IMessageQueueConnection extends IMessageQueueAuthConnection {
124
150
  /**
125
- * Message queue network unique identifier, optional property
126
- *
127
- * @type {string | undefined}
151
+ * Identifier used to match this endpoint against cluster membership.
152
+ * Meaningful on `cluster` entries only, not at the top level of
153
+ * {@link IMQOptions}.
128
154
  */
129
155
  id?: string;
130
156
  /**
131
- * Message queue network host
132
- *
133
- * @type {string}
157
+ * Host name or IP address of the queue host. Defaults to `localhost`.
134
158
  */
135
159
  host: string;
136
160
  /**
137
- * Message queue network port
138
- *
139
- * @type {number}
161
+ * TCP port of the queue host. Defaults to `6379`.
140
162
  */
141
163
  port: number;
142
164
  }
165
+ /**
166
+ * Optional credentials for a queue host, forwarded to the Redis client as
167
+ * `username` and `password`.
168
+ *
169
+ * Supply both for a Redis ACL user, or just `password` for a `requirepass`-only
170
+ * server. Omit both to connect unauthenticated, which is the default.
171
+ */
143
172
  export interface IMessageQueueAuthConnection {
144
173
  /**
145
- * Message queue username
146
- *
147
- * @type {string}
174
+ * Redis ACL user name. Omit for a server that only uses `requirepass`.
148
175
  */
149
176
  username?: string;
150
177
  /**
151
- * Message queue password
152
- *
153
- * @type {string}
178
+ * Password for the queue host.
154
179
  */
155
180
  password?: string;
156
181
  }
157
182
  /**
158
- * Message queue options
183
+ * Options accepted by every queue implementation.
184
+ *
185
+ * Anything omitted falls back to {@link DEFAULT_IMQ_OPTIONS} — `localhost:6379`,
186
+ * prefix `imq`, cleanup off, safe delivery off, gzip off, a 5000 ms watcher check
187
+ * and safe-delivery TTL, and signal handling on.
188
+ *
189
+ * @remarks
190
+ * Only `cleanup` and `cleanupFilter` are required by the type, even though every
191
+ * constructor and {@link IMQ.create} accepts a `Partial<IMQOptions>` — prefer
192
+ * `Partial<IMQOptions>` when declaring option literals.
193
+ *
194
+ * The inherited `id` is meaningful only on {@link IMQOptions.cluster} entries;
195
+ * the queue itself never reads it.
159
196
  */
160
197
  export interface IMQOptions extends Partial<IMessageQueueConnection> {
161
198
  /**
162
- * Turns on/off cleanup of the message queues
199
+ * Turns on/off the watcher's periodic removal of orphaned keys. Defaults to
200
+ * `false`.
163
201
  *
164
- * @type {boolean}
202
+ * @remarks
203
+ * This is a destructive sweep. Only the instance holding the watcher lock
204
+ * performs it, on the {@link IMQOptions.safeDeliveryTtl} interval, and it
205
+ * deletes every key under `<prefix>:<cleanupFilter>` that does not belong to
206
+ * a currently connected imq client — with one sweep of grace for clients seen
207
+ * during the previous sweep. That means it will delete messages queued for a
208
+ * consumer that is not running, so enable it only where queue names map
209
+ * one-to-one onto live processes.
165
210
  */
166
211
  cleanup: boolean;
167
212
  /**
168
- * Cleanup pattern for queue names that should be removed during cleanup
213
+ * Redis glob pattern, appended to the prefix as `<prefix>:<cleanupFilter>`,
214
+ * selecting which keys the cleanup sweep considers. Defaults to `'*'` —
215
+ * every key in the namespace.
169
216
  *
170
- * @type {string}
217
+ * @remarks
218
+ * This matches Redis key names, not queue names. The same pattern is also
219
+ * matched against connection names when deciding which keys belong to live
220
+ * clients. Used only when {@link IMQOptions.cleanup} is enabled.
171
221
  */
172
222
  cleanupFilter: string;
173
223
  /**
174
- * Message queue vendor
224
+ * Queue adapter vendor name. Defaults to `'Redis'`, which is the only
225
+ * supported value.
175
226
  *
176
- * @type {string}
227
+ * @remarks
228
+ * Honoured only by {@link IMQ.create}, which throws a `TypeError` for any
229
+ * other value. Ignored when a queue class is instantiated directly, because
230
+ * {@link DEFAULT_IMQ_OPTIONS} carries no `vendor` key.
177
231
  */
178
232
  vendor?: string;
179
233
  /**
180
- * Message queue global key prefix (namespace)
234
+ * Global key namespace for everything this queue writes. Defaults to `'imq'`.
181
235
  *
182
- * @type {string}
236
+ * @remarks
237
+ * The prefix scopes more than the queue keys: it also scopes the delayed set,
238
+ * the pub/sub channel names, and the watcher election lock
239
+ * `<prefix>:watch:lock`. All queues sharing a prefix on the same Redis host
240
+ * therefore elect exactly one watcher between them, and
241
+ * {@link IMessageQueue.publish} can only reach names inside the same prefix.
242
+ * Use distinct prefixes to isolate unrelated applications on a shared Redis.
183
243
  */
184
244
  prefix?: string;
185
245
  /**
186
- * Logger instance to use for message queue logging at runtime
246
+ * Logger used for queue diagnostics. Defaults to `console`.
187
247
  *
188
- * @type {ILogger}
248
+ * @remarks
249
+ * Connection lifecycle messages and all internal errors are written here
250
+ * regardless of {@link IMQOptions.verbose} — only verbose messages are gated
251
+ * by it. Pass a no-op {@link ILogger} to silence the queue entirely.
189
252
  */
190
253
  logger?: ILogger;
191
254
  /**
192
- * Delay period (in milliseconds) between watcher availability checks.
193
- * Used to ensure at least one watcher is available for queue operations.
255
+ * Interval in milliseconds of the periodic watcher check. Defaults to 5000.
194
256
  *
195
- * @type {number}
257
+ * @remarks
258
+ * Each tick re-elects a watcher owner if none exists and, on
259
+ * worker-capable instances, releases due delayed messages — acting as the
260
+ * fallback when Redis keyspace notifications are unavailable. That makes this
261
+ * value the worst-case extra latency for a delayed message. Setting it to `0`
262
+ * disables both behaviours.
196
263
  */
197
264
  watcherCheckDelay?: number;
198
265
  /**
199
266
  * Enable message compression for serialization. Increases a worker CPU load
200
- * but decreases network traffic between workers and the queue host.
267
+ * but decreases network traffic between workers and the queue host. Defaults
268
+ * to `false`.
201
269
  *
202
- * @type {boolean}
270
+ * @remarks
271
+ * Must be set identically on every producer and consumer of a queue: a
272
+ * mismatch makes deserialization fail, which emits an `error` event with the
273
+ * event name `OnMessage` and drops the message — permanently, even under
274
+ * {@link IMQOptions.safeDelivery}, because the worker key is released
275
+ * immediately afterwards.
276
+ *
277
+ * Applies to queue messages only. {@link IMessageQueue.publish} and
278
+ * {@link IMessageQueue.subscribe} payloads are always plain JSON.
203
279
  */
204
280
  useGzip?: boolean;
205
281
  /**
206
282
  * Enable guaranteed message delivery. When enabled, reading a message
207
283
  * moves it atomically out of the queue into a worker-owned key instead of
208
- * popping it outright, so a worker that dies *before* it starts on a
284
+ * popping it outright, so a worker that dies before it even starts on a
209
285
  * message leaves that message behind for the watcher to re-queue rather
210
286
  * than taking it down with the process.
211
287
  *
@@ -216,8 +292,7 @@ export interface IMQOptions extends Partial<IMessageQueueConnection> {
216
292
  * in-flight work before exit is up to the application. Delivery is
217
293
  * at-least-once in either mode, so handlers should be idempotent.
218
294
  *
219
- * @default false
220
- * @type {boolean}
295
+ * @defaultValue false
221
296
  */
222
297
  safeDelivery?: boolean;
223
298
  /**
@@ -231,24 +306,46 @@ export interface IMQOptions extends Partial<IMessageQueueConnection> {
231
306
  * deadline. The key is released when the message is dispatched, so a slow
232
307
  * handler is neither interrupted nor re-queued for taking too long, and
233
308
  * raising this value extends no protection over long-running work — tune it
234
- * for how quickly an abandoned message should come back. Only effective
235
- * when safeDelivery is enabled.
309
+ * for how quickly an abandoned message should come back.
310
+ *
311
+ * @defaultValue 5000
236
312
  *
237
- * @default 5000
238
- * @type {number}
313
+ * @remarks
314
+ * This value applies whether or not {@link IMQOptions.safeDelivery} is on:
315
+ * it always sets the period of the watcher's maintenance sweep, which also
316
+ * drives the {@link IMQOptions.cleanup} pass. Setting it to `null` or
317
+ * `undefined` disables that interval altogether, so neither lease recovery
318
+ * nor cleanup runs.
319
+ *
320
+ * In safe-delivery mode it additionally sets the reader's blocking-pop
321
+ * timeout to half the TTL, with a 100 ms floor, after which the reader
322
+ * regenerates the lease and blocks again. Very small values therefore
323
+ * increase Redis round-trips without further reducing latency.
239
324
  */
240
325
  safeDeliveryTtl?: number;
241
326
  /**
242
- * Queue cluster instances, if MQ should be clustered
327
+ * Redis servers to spread this queue across. Supplying this — or
328
+ * {@link IMQOptions.clusterManagers} — makes {@link IMQ.create} return a
329
+ * {@link ClusteredRedisQueue}.
330
+ *
331
+ * @remarks
332
+ * Each entry carries its own host, port and optional `id` used for
333
+ * cluster-membership matching. Sends are distributed across the servers by
334
+ * health-aware round-robin, preferring ones whose connection is ready.
243
335
  *
244
- * @type {IMessageQueueConnection[]}
336
+ * Note that per-entry `username` and `password` are currently ignored — the
337
+ * underlying queues authenticate with the top-level credentials.
245
338
  */
246
339
  cluster?: IMessageQueueConnection[];
247
340
  /**
248
- * Array of cluster managers used to handle cluster operations.
249
- * Any manager implements specific cluster server detection.
341
+ * Cluster managers that discover and maintain cluster servers dynamically.
342
+ * Supplying this — or {@link IMQOptions.cluster} — makes {@link IMQ.create}
343
+ * return a {@link ClusteredRedisQueue}.
250
344
  *
251
- * @type {ClusterManager[]}
345
+ * @remarks
346
+ * Each manager implements its own server-detection mechanism;
347
+ * {@link UDPClusterManager} discovers members from UDP broadcasts. Implement
348
+ * {@link ClusterManager} to add your own.
252
349
  */
253
350
  clusterManagers?: ClusterManager[];
254
351
  /**
@@ -258,41 +355,101 @@ export interface IMQOptions extends Partial<IMessageQueueConnection> {
258
355
  * to finish, so drain those yourself if work in progress must not be lost.
259
356
  * Disable if the host application manages shutdown.
260
357
  *
261
- * @default true
262
- * @type {boolean}
358
+ * @defaultValue true
359
+ *
360
+ * @remarks
361
+ * The handlers are installed once per process, by the first started queue
362
+ * that does not disable them, and they release the watcher locks of every
363
+ * started queue in the process before calling `process.exit(0)` — forced
364
+ * after `IMQ_SHUTDOWN_TIMEOUT` milliseconds, with exit code 1 if a lock could
365
+ * not be released. Because they are process-wide, disabling this on one
366
+ * instance does not prevent exit when another instance leaves it enabled.
263
367
  */
264
368
  handleSignals?: boolean;
265
369
  /**
266
- * Enables/disables verbose logging
370
+ * Enables/disables verbose logging.
371
+ *
372
+ * @defaultValue false
267
373
  *
268
- * @default false
269
- * @type {boolean}
374
+ * @remarks
375
+ * Only informational tracing is gated by this. Connection lifecycle messages
376
+ * and internal errors are always written to {@link IMQOptions.logger}.
270
377
  */
271
378
  verbose?: boolean;
272
379
  /**
273
- * Enables/disables extended verbose logging. The output may contain
274
- * sensitive information, so use it with caution. Does not work if a verbose
275
- * option is disabled.
380
+ * Enables/disables extended verbose logging.
276
381
  *
277
- * @default false
278
- * @type {boolean}
382
+ * @deprecated Never implemented — no code path reads this option, so setting
383
+ * it produces no additional output whatsoever. Use {@link IMQOptions.verbose}
384
+ * instead. Scheduled for removal in the next major.
279
385
  */
280
386
  verboseExtended?: boolean;
281
387
  }
388
+ /**
389
+ * Typed event map for a queue's `EventEmitter` base, giving compile-time
390
+ * signatures for the only two events a queue emits.
391
+ *
392
+ * @remarks
393
+ * The map is closed, so `emit`/`on` with any other event name is a type error —
394
+ * there is no `connect`, `close`, `ready` or `drain` event on a queue.
395
+ */
282
396
  export interface EventMap {
397
+ /**
398
+ * Emitted for every message consumed from the queue, with the payload, the
399
+ * message id, and the name of the queue that sent it.
400
+ */
283
401
  message: [data: JsonObject, id: string, from: string];
402
+ /**
403
+ * Emitted for background failures, with the error and the name of the
404
+ * internal routine that caught it — a diagnostic label such as `OnMessage`,
405
+ * `OnReadSafe` or `OnWatch`, not an error code.
406
+ *
407
+ * @remarks
408
+ * Emitted only when at least one `error` listener is attached; otherwise the
409
+ * error is logged and swallowed so a background routine cannot crash the
410
+ * process. Errors are always written to {@link IMQOptions.logger} as well,
411
+ * and emission is informational — the queue keeps running.
412
+ */
284
413
  error: [error: Error, eventName: string];
285
414
  }
415
+ /**
416
+ * Constructor contract every queue adapter must satisfy: it takes the queue
417
+ * name, optional partial options and an optional {@link IMQMode}, and yields an
418
+ * {@link IMessageQueue}.
419
+ *
420
+ * {@link IMQ.create} resolves an adapter of this shape from the registered
421
+ * vendor adapters and instantiates it.
422
+ *
423
+ * @remarks
424
+ * The built-in adapters are registered through an explicit cast rather than
425
+ * structural assignment, so do not expect a clean assignment from a concrete
426
+ * queue class to this type.
427
+ */
286
428
  export type IMessageQueueConstructor = new (name: string, options?: Partial<IMQOptions>, mode?: IMQMode) => IMessageQueue;
287
429
  /**
288
- * Generic messaging queue implementation interface
430
+ * Contract every messaging queue implementation fulfils. Implement it to add a
431
+ * transport of your own, or program against it to stay adapter-agnostic.
432
+ *
433
+ * A queue is an `EventEmitter` typed by {@link EventMap}, so it emits exactly two
434
+ * events: `message`, with the payload, the message id and the sending queue's
435
+ * name; and `error`, with the error and the name of the internal routine that
436
+ * caught it. The `error` event fires only when a listener is attached — attach one
437
+ * if background failures must be observed.
289
438
  *
290
439
  * @example
291
- * ~~~typescript
292
- * import { IMessageQueue, EventEmitter } from '@imqueue/core';
440
+ * Implementing an adapter:
441
+ * ```typescript
442
+ * import {
443
+ * type IMessageQueue,
444
+ * type EventMap,
445
+ * type JsonObject,
446
+ * EventEmitter,
447
+ * } from '@imqueue/core';
293
448
  * import { randomUUID } from 'node:crypto';
294
449
  *
295
- * class SomeMQAdapter extends EventEmitter implements IMessageQueue {
450
+ * class SomeMQAdapter extends EventEmitter<EventMap>
451
+ * implements IMessageQueue
452
+ * {
296
453
  * public async start(): Promise<SomeMQAdapter> {
297
454
  * // ... implementation goes here
298
455
  * return this;
@@ -310,68 +467,130 @@ export type IMessageQueueConstructor = new (name: string, options?: Partial<IMQO
310
467
  * // ... implementation goes here
311
468
  * return messageId;
312
469
  * }
313
- * public async destroy(): Promise<void> {
470
+ * public async subscribe(
471
+ * channel: string,
472
+ * handler: (data: JsonObject) => void,
473
+ * ): Promise<void> {
474
+ * // ... implementation goes here
475
+ * }
476
+ * public async unsubscribe(): Promise<void> {
477
+ * // ... implementation goes here
478
+ * }
479
+ * public async publish(
480
+ * data: JsonObject,
481
+ * toName?: string,
482
+ * ): Promise<void> {
483
+ * // ... implementation goes here
484
+ * }
485
+ * public async queueLength(): Promise<number> {
314
486
  * // ... implementation goes here
487
+ * return 0;
315
488
  * }
316
489
  * public async clear(): Promise<SomeMQAdapter> {
317
490
  * // ... implementation goes here
318
491
  * return this;
319
492
  * }
493
+ * public async destroy(): Promise<void> {
494
+ * // ... implementation goes here
495
+ * }
320
496
  * }
321
- * ~~~
497
+ * ```
322
498
  */
323
499
  export interface IMessageQueue extends EventEmitter<EventMap> {
324
500
  /**
325
- * Message event. Occurs every time the queue receives a message.
501
+ * Starts the queue: opens its connections, joins watcher election and begins
502
+ * consuming, so `message` events start arriving.
326
503
  *
327
- * @event IMessageQueue#message
328
- * @type {JsonObject} message - message data
329
- * @type {string} id - message identifier
330
- * @type {string} from - source queue that produced the message
331
- */
332
- /**
333
- * Error event. Occurs every time the queue encounters an error.
504
+ * @returns this queue instance
505
+ * @throws TypeError when the queue was constructed without a name
334
506
  *
335
- * @event IMessageQueue#error
336
- * @type {Error} err - error caught by the message queue
337
- * @type {string} code - message queue error code
338
- */
339
- /**
340
- * Starts the messaging queue.
507
+ * @remarks
508
+ * A no-op when the queue is already started, and it may be called again
509
+ * after {@link IMessageQueue.stop}. A reader is opened only in
510
+ * {@link IMQMode.BOTH} or {@link IMQMode.WORKER} mode, so a publisher-only
511
+ * queue never emits `message`. Unless
512
+ * {@link IMQOptions.handleSignals} is disabled, this also installs
513
+ * process-wide signal handlers.
341
514
  *
342
- * @returns {Promise<IMessageQueue>}
515
+ * Required before {@link IMessageQueue.publish};
516
+ * {@link IMessageQueue.send} starts the queue implicitly.
343
517
  */
344
518
  start(): Promise<IMessageQueue>;
345
519
  /**
346
- * Stops the queue from handling messages.
520
+ * Stops consuming, so no further `message` events fire.
521
+ *
522
+ * @returns this queue instance
347
523
  *
348
- * @returns {Promise<IMessageQueue>}
524
+ * @remarks
525
+ * Only the reader is torn down. The writer connection, the watcher lock and
526
+ * the watcher/maintenance timers all stay active, and
527
+ * {@link IMessageQueue.send} and {@link IMessageQueue.publish} keep working —
528
+ * call {@link IMessageQueue.destroy} to release those. Safe to call when not
529
+ * started, and {@link IMessageQueue.start} may be called again afterwards.
349
530
  */
350
531
  stop(): Promise<IMessageQueue>;
351
532
  /**
352
533
  * Sends a message to the specified queue with the given data.
353
534
  *
354
- * @param {string} toQueue - name of the destination queue
355
- * @param {JsonObject} message - message data to send
356
- * @param {number} [delay] - if specified, the message will be handled in
357
- * the target queue after the specified delay in milliseconds
358
- * @param {(err: Error) => void} [errorHandler] - callback invoked only
359
- * when an internal error occurs during message send execution
360
- * @returns {Promise<string>} - the message identifier
535
+ * @param toQueue - name of the destination queue
536
+ * @param message - message data to send
537
+ * @param delay - if specified, the message becomes available in the target
538
+ * queue only after this many milliseconds. This is a minimum, not a
539
+ * schedule: the message is released by the watcher, either on a Redis
540
+ * expired-key notification or on the next
541
+ * {@link IMQOptions.watcherCheckDelay} poll, so availability may lag
542
+ * by up to that interval. A delay of `0` or `undefined` sends
543
+ * immediately.
544
+ * @param errorHandler - callback invoked only when an internal error occurs
545
+ * during message send execution
546
+ * @returns the identifier assigned to the message
547
+ * @throws TypeError when the queue is in {@link IMQMode.WORKER}-only mode, or
548
+ * when a writer connection cannot be established
549
+ *
550
+ * @remarks
551
+ * The returned promise resolves as soon as the write has been dispatched —
552
+ * before the queue host confirms it, and long before the message is
553
+ * consumed. The identifier is generated locally, so it is available even if
554
+ * the write later fails. A resolved promise is therefore not evidence that
555
+ * the message was enqueued: supply `errorHandler` to observe write failures,
556
+ * which never reject.
557
+ *
558
+ * Starts the queue implicitly when it has not been started yet. Delivery is
559
+ * at-least-once, so handlers must be idempotent.
361
560
  */
362
561
  send(toQueue: string, message: JsonObject, delay?: number, errorHandler?: (err: Error) => void): Promise<string>;
363
562
  /**
364
- * Creates or uses a subscription channel with the given name and sets
365
- * message handler on data receive
563
+ * Subscribes to the pub/sub channel with the given name and registers a
564
+ * handler for the data it delivers. The effective channel is
565
+ * `<prefix>:<channel>`.
366
566
  *
367
- * @param {string} channel - channel name
368
- * @param {(data: JsonObject) => void} handler
567
+ * @param channel - channel name within the queue's prefix namespace
568
+ * @param handler - invoked with the parsed payload of each published message
569
+ * @throws TypeError when no channel name is given, or when a different
570
+ * channel name is supplied while a subscription is already open — an
571
+ * instance supports exactly one channel until
572
+ * {@link IMessageQueue.unsubscribe} resets it
573
+ *
574
+ * @remarks
575
+ * Calling this repeatedly with the same channel name adds another handler
576
+ * rather than replacing the existing one, and all of them are invoked. The
577
+ * subscription uses its own connection, so it does not require
578
+ * {@link IMessageQueue.start}, and it is re-established automatically after a
579
+ * reconnect.
580
+ *
581
+ * Payloads are always plain JSON — {@link IMQOptions.useGzip} does not apply
582
+ * to pub/sub. Delivery is fire-and-forget: messages published while nobody is
583
+ * subscribed are lost, unlike queued messages.
369
584
  */
370
585
  subscribe(channel: string, handler: (data: JsonObject) => void): Promise<void>;
371
586
  /**
372
- * Closes the subscription channel
587
+ * Closes the subscription channel and drops every handler registered through
588
+ * {@link IMessageQueue.subscribe}, resetting the instance so a later
589
+ * subscription may use a different channel name.
373
590
  *
374
- * @returns {Promise<void>}
591
+ * @remarks
592
+ * A no-op when no subscription exists, and it never rejects — teardown
593
+ * failures are only logged. There is no way to remove an individual handler.
375
594
  */
376
595
  unsubscribe(): Promise<void>;
377
596
  /**
@@ -381,29 +600,63 @@ export interface IMessageQueue extends EventEmitter<EventMap> {
381
600
  * can be used to broadcast messages to other subscribers on different pubsub
382
601
  * channels. Different names must be in the same namespace (same imq prefix).
383
602
  *
384
- * @param {JsonObject} data - data to publish as a channel message
385
- * @param {string} [toName] - optional different pubsub name to publish to
386
- * @returns {Promise<void>}
603
+ * @param data - data to publish as a channel message
604
+ * @param toName - optional different pubsub name to publish to
605
+ * @throws TypeError when the queue has no writer connection
606
+ *
607
+ * @remarks
608
+ * Unlike {@link IMessageQueue.send}, this does not start the queue
609
+ * implicitly — {@link IMessageQueue.start} must have completed first. The
610
+ * payload is always plain JSON ({@link IMQOptions.useGzip} does not apply),
611
+ * and pub/sub delivery is not persisted, so subscribers that are not
612
+ * connected at publish time never receive the message.
387
613
  */
388
614
  publish(data: JsonObject, toName?: string): Promise<void>;
389
615
  /**
390
- * Safely destroys the current queue, unregistering all event listeners
391
- * and closing connections.
616
+ * Releases this queue handle: removes all event listeners, stops the
617
+ * maintenance timers, releases the watcher lock if held, disconnects the
618
+ * reader, and drops this instance's reference to the shared writer.
619
+ *
620
+ * @remarks
621
+ * The writer connection is shared per `host:port` within the process and
622
+ * stays open while other started instances still reference it.
392
623
  *
393
- * @returns {Promise<void>}
624
+ * Queue data is deliberately left intact, so destroying one handle never
625
+ * discards messages still pending for other producers or consumers. Note that
626
+ * removing all listeners also discards the caller's `message` and `error`
627
+ * handlers, while {@link IMessageQueue.start} can revive the instance — so
628
+ * re-register them if you restart it.
394
629
  */
395
630
  destroy(): Promise<void>;
396
631
  /**
397
- * Clears all queue data from the queue host application.
632
+ * Deletes this queue's pending messages — both the main list and the delayed
633
+ * set for `<prefix>:<name>`.
398
634
  *
399
- * @returns {Promise<IMessageQueue>}
635
+ * @returns this queue instance
636
+ *
637
+ * @remarks
638
+ * Other queues in the namespace, the watcher lock, and messages currently
639
+ * leased to a worker under {@link IMQOptions.safeDelivery} are all untouched —
640
+ * a leased message can be re-queued by the watcher once its lease expires, so
641
+ * this does not guarantee the queue stays empty.
642
+ *
643
+ * It never rejects: with no writer connection it silently does nothing, and
644
+ * host failures are logged rather than raised, so success cannot be inferred
645
+ * from a resolved promise.
400
646
  */
401
647
  clear(): Promise<IMessageQueue>;
402
648
  /**
403
- * Retrieves the current count of messages in the queue.
404
- * Supposed to be an async function.
649
+ * Returns the number of messages currently waiting in this queue's main list.
650
+ *
651
+ * @returns count of messages waiting to be consumed
652
+ *
653
+ * @remarks
654
+ * Delayed messages that are not yet due, and messages currently leased to a
655
+ * worker under {@link IMQOptions.safeDelivery}, are not counted — so this
656
+ * is not the amount of outstanding work.
405
657
  *
406
- * @returns {Promise<number>}
658
+ * Returns `0` when the queue has no writer connection, which makes
659
+ * "disconnected" indistinguishable from "empty".
407
660
  */
408
661
  queueLength(): Promise<number>;
409
662
  }