@imqueue/core 3.4.2 → 3.5.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.
package/src/RedisQueue.js CHANGED
@@ -59,7 +59,7 @@ import { EventEmitter } from 'node:events';
59
59
  import { randomUUID } from 'node:crypto';
60
60
  import { hostname } from 'node:os';
61
61
  import { IMQMode, profile, } from './index.js';
62
- import { buildOptions, escapeRegExp, randomInt, pack, sha1, unpack, envInt, errorCode, LOG_MAX_KEYS, } from './helpers/index.js';
62
+ import { buildOptions, escapeRegExp, randomInt, pack, sha1, unpack, envInt, envTls, tlsFingerprint, errorCode, LOG_MAX_KEYS, } from './helpers/index.js';
63
63
  import Redis from './redis.js';
64
64
  const RX_CLIENT_NAME = /name=(\S+)/g;
65
65
  const RX_CLIENT_TEST = /:(reader|writer|watcher)/;
@@ -70,6 +70,24 @@ const RECONNECT_BASE_DELAY = 1000;
70
70
  const RECONNECT_MAX_DELAY = 30000;
71
71
  /** SCAN batch size used while sweeping keys */
72
72
  const SCAN_COUNT = '1000';
73
+ /**
74
+ * This process, as it appears inside every connection name this queue registers
75
+ * with the broker (see `getChannelName`). Stamped into each worker key so the
76
+ * watcher can ask the broker whether a lease's owner is still alive instead of
77
+ * asking a clock whether time has run out.
78
+ */
79
+ const OWNER = `pid:${process.pid}:host:${hostname()}`;
80
+ /** Matches the owner inside a worker key, which ends with its deadline */
81
+ const RX_LEASE_OWNER = /:(pid:\d+:host:[^:]+):\d+$/;
82
+ /** Matches the owner inside a `name=` entry of `CLIENT LIST` */
83
+ const RX_CLIENT_OWNER = /(pid:\d+:host:\S+)$/;
84
+ /**
85
+ * Upper bound (ms) on the reader's blocking pop. A lease deadline is stamped
86
+ * before the pop that fills the key, so a message is born having already spent
87
+ * whatever the pop waited; capping it keeps that negligible against a budget of
88
+ * minutes.
89
+ */
90
+ const READ_MAX_BLOCK = 5000;
73
91
  /** Redis config parameter holding the keyspace-notification flags */
74
92
  const NOTIFY_EVENTS_PARAM = 'notify-keyspace-events';
75
93
  /**
@@ -121,7 +139,7 @@ export const DEFAULT_IMQ_OPTIONS = {
121
139
  logger: console,
122
140
  prefix: 'imq',
123
141
  safeDelivery: false,
124
- safeDeliveryTtl: 5000,
142
+ safeDeliveryTtl: 300000,
125
143
  useGzip: false,
126
144
  watcherCheckDelay: 5000,
127
145
  handleSignals: true,
@@ -160,11 +178,12 @@ const IMQ_REDIS_MAX_LISTENERS_LIMIT = envInt('IMQ_REDIS_MAX_LISTENERS_LIMIT', 10
160
178
  * @remarks
161
179
  * Connection model: the reader is per instance and exists only in
162
180
  * {@link IMQMode.BOTH} or {@link IMQMode.WORKER} mode, while the writer and
163
- * watcher connections are shared per `host:port` across every queue in the
164
- * process and reference-counted. Exactly one queue per key prefix is elected as
165
- * the watcher through a `<prefix>:watch:lock` key, and that owner also releases
166
- * delayed messages, recovers abandoned safe-delivery hand-offs and — when
167
- * {@link IMQOptions.cleanup} is on — prunes orphaned keys.
181
+ * watcher connections are shared per `host:port` — and per TLS configuration —
182
+ * across every queue in the process and reference-counted. Exactly one queue
183
+ * per key prefix is elected as the watcher through a `<prefix>:watch:lock` key,
184
+ * and that owner also releases delayed messages, recovers abandoned
185
+ * safe-delivery hand-offs and — when {@link IMQOptions.cleanup} is on — prunes
186
+ * orphaned keys.
168
187
  *
169
188
  * Lifecycle: {@link RedisQueue.start} is required before consuming or
170
189
  * publishing, while {@link RedisQueue.send} starts the queue lazily.
@@ -309,6 +328,8 @@ let RedisQueue = (() => {
309
328
  * removing their keys.
310
329
  */
311
330
  lastConnectedKeys = [];
331
+ /** Lease owners seen connected on the previous sweep (one sweep of grace) */
332
+ lastOwners = new Set();
312
333
  /**
313
334
  * True while this instance holds a reference to the shared writer
314
335
  */
@@ -317,20 +338,51 @@ let RedisQueue = (() => {
317
338
  * Internal per-channel reconnection state
318
339
  */
319
340
  reconnectTimers = {};
341
+ /**
342
+ * Consecutive failed reconnection attempts per channel, which is what the
343
+ * backoff delay is computed from. Reset once a channel connects again.
344
+ */
320
345
  reconnectAttempts = {};
346
+ /**
347
+ * Channels with a reconnection already in progress.
348
+ *
349
+ * @remarks
350
+ * A guard, not a status: several `close` events can arrive for one channel,
351
+ * and without this each would start its own reconnection loop.
352
+ */
321
353
  reconnecting = {};
322
354
  /**
323
355
  * The `host:port` address of the redis server this queue talks to.
324
356
  *
325
357
  * @remarks
326
358
  * This is not an instance identifier. It is deliberately shared by every
327
- * queue in the process that targets the same server, and is the key under
328
- * which the writer and watcher connections (and the writer reference count)
329
- * are stored. It includes neither the key prefix nor the credentials, so two
330
- * queues differing only in those share the same underlying connections — the
331
- * first one created wins.
359
+ * queue in the process that targets the same server, and it is what
360
+ * identifies that server in logs. It includes neither the key prefix nor
361
+ * the credentials.
362
+ *
363
+ * It is no longer the whole of the connection pool key — see
364
+ * {@link RedisQueue.poolKey} — because connections differing in their
365
+ * transport security must not be shared.
332
366
  */
333
367
  redisKey;
368
+ /**
369
+ * Key under which the shared writer and watcher connections, and the writer
370
+ * reference count, are stored.
371
+ *
372
+ * @remarks
373
+ * This is {@link RedisQueue.redisKey} for a plaintext connection, and that
374
+ * address plus a fingerprint of {@link IMQOptions.tls} for an encrypted
375
+ * one. Two queues reaching one server under equal TLS configurations
376
+ * therefore still share a connection, while queues that differ in their
377
+ * trust anchors, client certificate or verification callbacks get separate
378
+ * ones — a queue asking for TLS can never be handed a plaintext socket
379
+ * another queue opened first, nor the reverse.
380
+ *
381
+ * The prefix and the credentials remain outside the key, so queues
382
+ * differing only in those still share a connection and the first one
383
+ * created still wins.
384
+ */
385
+ poolKey;
334
386
  /**
335
387
  * Lua scripts for redis
336
388
  */
@@ -357,13 +409,18 @@ let RedisQueue = (() => {
357
409
  /**
358
410
  * Serializes a given data object into string
359
411
  *
360
- * @param data -
412
+ * @param data - the value to serialize; must be JSON-serializable
413
+ * @returns the wire representation, gzipped when
414
+ * {@link IMQOptions.useGzip} is on
361
415
  */
362
416
  pack;
363
417
  /**
364
418
  * Deserialize string data into an object
365
419
  *
366
- * @param data -
420
+ * @param data - the wire representation, as produced by `pack`
421
+ * @returns the deserialized value
422
+ * @throws when the payload is malformed, or was packed with a different
423
+ * {@link IMQOptions.useGzip} setting
367
424
  */
368
425
  unpack;
369
426
  /**
@@ -394,19 +451,58 @@ let RedisQueue = (() => {
394
451
  * Assign it before {@link RedisQueue.start} — a running reader keeps
395
452
  * consuming the key it was started with.
396
453
  */
397
- name, options, mode = IMQMode.BOTH) {
454
+ name, options,
455
+ /**
456
+ * Whether this handle publishes, consumes, or both.
457
+ *
458
+ * @remarks
459
+ * Fixed at construction: it decides which connections `start()` opens,
460
+ * so a publisher never opens a reader and cannot consume even by
461
+ * accident.
462
+ */
463
+ mode = IMQMode.BOTH) {
398
464
  super();
399
465
  this.name = name;
400
466
  this.mode = mode;
401
467
  this.options = buildOptions(DEFAULT_IMQ_OPTIONS, options);
468
+ if (this.options.tls === undefined) {
469
+ // an unreadable CA or client key throws out of here rather than
470
+ // yielding a queue that would quietly talk to the broker in clear
471
+ const fromEnv = envTls();
472
+ if (fromEnv !== undefined) {
473
+ // assigned only when the environment actually asks for TLS, so
474
+ // that a queue nobody configured for it carries no `tls` key at
475
+ // all and `options` keeps exactly the shape it always had
476
+ this.options.tls = fromEnv;
477
+ }
478
+ }
402
479
  this.pack = this.options.useGzip ? pack : JSON.stringify;
403
480
  this.unpack = this.options.useGzip ? unpack : JSON.parse;
404
481
  this.redisKey = `${this.options.host}:${this.options.port}`;
482
+ this.poolKey = this.options.tls
483
+ ? `${this.redisKey}#${tlsFingerprint(this.options.tls)}`
484
+ : this.redisKey;
485
+ if (this.options.tls &&
486
+ this.options.tls !== true &&
487
+ this.options.tls.rejectUnauthorized === false) {
488
+ this.logger.warn('%s: TLS certificate verification is disabled for redis host' +
489
+ ' %s — the connection is encrypted but the server is not' +
490
+ ' authenticated, so it is open to interception', this.name, this.redisKey);
491
+ }
405
492
  for (const script of Object.keys(this.scripts)) {
406
493
  this.scripts[script].checksum = sha1(this.scripts[script].code);
407
494
  }
408
495
  this.verbose(`Initializing queue on ${this.options.host}:${this.options.port} with prefix ${this.options.prefix} and safeDelivery = ${this.options.safeDelivery}, and safeDeliveryTtl = ${this.options.safeDeliveryTtl}, and watcherCheckDelay = ${this.options.watcherCheckDelay}, and useGzip = ${this.options.useGzip}`);
409
496
  }
497
+ /**
498
+ * Writes a diagnostic line, but only under {@link IMQOptions.verbose}.
499
+ *
500
+ * @param message - the line to write, tagged with this queue's name
501
+ *
502
+ * @remarks
503
+ * For tracing the queue's own lifecycle. Anything a user must see whether
504
+ * or not verbose is on goes through `logLine` instead.
505
+ */
410
506
  verbose(message) {
411
507
  if (this.options.verbose) {
412
508
  this.logger.info(`[IMQ-CORE][${this.name}]: ${message}`);
@@ -508,8 +604,8 @@ let RedisQueue = (() => {
508
604
  * Attaches a subscription message handler to a given channel
509
605
  * connection
510
606
  *
511
- * @param chan -
512
- * @param handler -
607
+ * @param chan - the pub/sub channel to deliver messages from
608
+ * @param handler - called with the decoded payload of each message
513
609
  */
514
610
  attachSubscriptionHandler(chan, handler) {
515
611
  const fcn = `${this.options.prefix}:${this.subscriptionName}`;
@@ -668,8 +764,8 @@ let RedisQueue = (() => {
668
764
  RedisQueue.bindSignals();
669
765
  }
670
766
  if (!this.writerAcquired) {
671
- RedisQueue.writerRefs[this.redisKey] =
672
- (RedisQueue.writerRefs[this.redisKey] || 0) + 1;
767
+ RedisQueue.writerRefs[this.poolKey] =
768
+ (RedisQueue.writerRefs[this.poolKey] || 0) + 1;
673
769
  this.writerAcquired = true;
674
770
  }
675
771
  await this.initWatcher();
@@ -926,9 +1022,11 @@ let RedisQueue = (() => {
926
1022
  * and silently discarded.
927
1023
  *
928
1024
  * With `clearData` set, only the main and delayed keys are removed: messages
929
- * currently leased to a worker key under {@link IMQOptions.safeDelivery} are
930
- * not, and the watcher will re-queue them once their lease expires — so
931
- * messages can reappear after a clearing destroy.
1025
+ * currently checked out to a worker key under
1026
+ * {@link IMQOptions.safeDelivery} are not, and the watcher returns them to
1027
+ * the queue once their worker is gone or their
1028
+ * {@link IMQOptions.safeDeliveryTtl} is spent — so messages can reappear
1029
+ * after a clearing destroy.
932
1030
  *
933
1031
  * Never rejects; unlock and clear failures are logged.
934
1032
  */
@@ -960,9 +1058,10 @@ let RedisQueue = (() => {
960
1058
  * @remarks
961
1059
  * A no-op that resolves successfully when the queue has no writer connection.
962
1060
  * In-flight messages held in worker keys under
963
- * {@link IMQOptions.safeDelivery} are not removed and may be re-queued by the
964
- * watcher after their lease expires, so this does not guarantee the queue
965
- * stays empty. Errors are logged rather than thrown, so success cannot be
1061
+ * {@link IMQOptions.safeDelivery} are not removed, and the watcher returns
1062
+ * them to the queue once their worker is gone or their
1063
+ * {@link IMQOptions.safeDeliveryTtl} is spent — so this does not guarantee
1064
+ * the queue stays empty. Errors are logged rather than thrown, so success cannot be
966
1065
  * inferred from a resolved promise.
967
1066
  */
968
1067
  async clear() {
@@ -990,11 +1089,14 @@ let RedisQueue = (() => {
990
1089
  * @returns count of messages waiting to be consumed
991
1090
  *
992
1091
  * @remarks
993
- * Delayed messages that are not yet due, and messages currently leased to a
994
- * worker under {@link IMQOptions.safeDelivery}, are not counted — so this
995
- * is not the amount of outstanding work. Returns `0` when the queue has no
996
- * writer connection, which makes "disconnected" indistinguishable from
997
- * "empty"; it never throws.
1092
+ * Delayed messages that are not yet due, and messages currently checked out
1093
+ * to a worker under {@link IMQOptions.safeDelivery}, are not counted — so
1094
+ * this is not the amount of outstanding work. Under safe delivery a message
1095
+ * is checked out for as long as its handler runs, so on a busy queue the
1096
+ * shortfall is roughly everything in flight, not a rounding error.
1097
+ *
1098
+ * Returns `0` when the queue has no writer connection, which makes
1099
+ * "disconnected" indistinguishable from "empty"; it never throws.
998
1100
  */
999
1101
  async queueLength() {
1000
1102
  if (!this.writer) {
@@ -1022,38 +1124,40 @@ let RedisQueue = (() => {
1022
1124
  * Used for health-aware routing in the clustered queue.
1023
1125
  *
1024
1126
  * @remarks
1025
- * The writer connection is shared per `host:port` within the process, so this
1026
- * reflects the health of that server connection rather than of this instance
1027
- * alone — every queue pointing at the same server reports the same value.
1127
+ * The writer connection is shared per `host:port` and TLS configuration
1128
+ * within the process, so this reflects the health of that server connection
1129
+ * rather than of this instance alone — every queue pointing at the same
1130
+ * server the same way reports the same value.
1028
1131
  */
1029
1132
  get available() {
1030
1133
  return !this.writer || this.writer.status === 'ready';
1031
1134
  }
1032
1135
  /**
1033
1136
  * Writer connection associated with this queue instance. Shared by every
1034
- * queue in the process that targets the same `host:port`.
1137
+ * queue in the process that targets the same {@link RedisQueue.poolKey}.
1035
1138
  */
1036
1139
  get writer() {
1037
- return RedisQueue.writers[this.redisKey];
1140
+ return RedisQueue.writers[this.poolKey];
1038
1141
  }
1039
1142
  set writer(conn) {
1040
- RedisQueue.writers[this.redisKey] = conn;
1143
+ RedisQueue.writers[this.poolKey] = conn;
1041
1144
  }
1042
1145
  /**
1043
1146
  * Watcher connection associated with this queue instance. Shared by every
1044
- * queue in the process that targets the same `host:port`; at most one queue
1045
- * per prefix is the elected watcher owner.
1147
+ * queue in the process that targets the same {@link RedisQueue.poolKey}; at
1148
+ * most one queue per prefix is the elected watcher owner.
1046
1149
  */
1047
1150
  get watcher() {
1048
- return RedisQueue.watchers[this.redisKey];
1151
+ return RedisQueue.watchers[this.poolKey];
1049
1152
  }
1050
1153
  set watcher(conn) {
1051
- RedisQueue.watchers[this.redisKey] = conn;
1154
+ RedisQueue.watchers[this.poolKey] = conn;
1052
1155
  }
1053
1156
  /**
1054
1157
  * Returns the connection currently bound to the given channel, if any.
1055
1158
  *
1056
- * @param channel -
1159
+ * @param channel - which of the queue's connections to look up
1160
+ * @returns the connection, or `undefined` when that channel is not open
1057
1161
  */
1058
1162
  connectionOf(channel) {
1059
1163
  switch (channel) {
@@ -1070,8 +1174,8 @@ let RedisQueue = (() => {
1070
1174
  /**
1071
1175
  * Binds the given connection to the given channel.
1072
1176
  *
1073
- * @param channel -
1074
- * @param conn -
1177
+ * @param channel - which of the queue's connections to bind
1178
+ * @param conn - the client to bind, or `undefined` to unbind it
1075
1179
  */
1076
1180
  bindConnection(channel, conn) {
1077
1181
  switch (channel) {
@@ -1114,7 +1218,7 @@ let RedisQueue = (() => {
1114
1218
  if (this.watcher) {
1115
1219
  this.verbose('Destroying watcher...');
1116
1220
  this.destroyChannel('watcher');
1117
- delete RedisQueue.watchers[this.redisKey];
1221
+ delete RedisQueue.watchers[this.poolKey];
1118
1222
  this.verbose('Watcher destroyed!');
1119
1223
  }
1120
1224
  }
@@ -1124,8 +1228,8 @@ let RedisQueue = (() => {
1124
1228
  destroyWriter(release = true) {
1125
1229
  if (release && this.writerAcquired) {
1126
1230
  this.writerAcquired = false;
1127
- RedisQueue.writerRefs[this.redisKey] = Math.max(0, (RedisQueue.writerRefs[this.redisKey] || 1) - 1);
1128
- if (RedisQueue.writerRefs[this.redisKey] > 0) {
1231
+ RedisQueue.writerRefs[this.poolKey] = Math.max(0, (RedisQueue.writerRefs[this.poolKey] || 1) - 1);
1232
+ if (RedisQueue.writerRefs[this.poolKey] > 0) {
1129
1233
  // the shared writer connection is still used by other
1130
1234
  // queue instances within this process
1131
1235
  this.verbose('Writer is still in use, skipping destroy...');
@@ -1135,10 +1239,34 @@ let RedisQueue = (() => {
1135
1239
  if (this.writer) {
1136
1240
  this.verbose('Destroying writer...');
1137
1241
  this.destroyChannel('writer');
1138
- delete RedisQueue.writers[this.redisKey];
1242
+ delete RedisQueue.writers[this.poolKey];
1139
1243
  this.verbose('Writer destroyed!');
1140
1244
  }
1141
1245
  }
1246
+ /**
1247
+ * Installs a durable `error` listener on a connection's socket.
1248
+ *
1249
+ * @param client - the connection whose socket to guard
1250
+ *
1251
+ * @remarks
1252
+ * The redis client guards the socket with a one-shot listener, which the
1253
+ * first failure consumes. A socket that goes on to report a second one -
1254
+ * a rejected TLS handshake is answered by an alert that arrives after the
1255
+ * failure that caused it - then reaches a socket with nothing attached,
1256
+ * and an unhandled `error` takes the process down. Nothing is left to act
1257
+ * on it by then, so it is swallowed.
1258
+ *
1259
+ * Idempotent: connections are marked once guarded, so repeated failures on
1260
+ * one socket do not accumulate listeners.
1261
+ */
1262
+ guardSocket(client) {
1263
+ const stream = client.stream;
1264
+ if (!stream || client.__guarded__) {
1265
+ return;
1266
+ }
1267
+ client.__guarded__ = true;
1268
+ stream.on('error', () => undefined);
1269
+ }
1142
1270
  /**
1143
1271
  * Destroys any channel
1144
1272
  */
@@ -1148,7 +1276,15 @@ let RedisQueue = (() => {
1148
1276
  return;
1149
1277
  }
1150
1278
  try {
1279
+ this.guardSocket(client);
1151
1280
  client.removeAllListeners();
1281
+ // removing the listeners leaves the client with no `error` handler
1282
+ // while the teardown below still writes to it. On a socket that has
1283
+ // already failed - a TLS handshake the peer rejected, most
1284
+ // obviously - that write raises an error an EventEmitter with no
1285
+ // listener rethrows, taking the process down as it is shutting the
1286
+ // connection cleanly. Nothing is left to report it to, so swallow.
1287
+ client.on('error', () => undefined);
1152
1288
  let disconnected = false;
1153
1289
  const forceDisconnect = () => {
1154
1290
  if (disconnected) {
@@ -1192,8 +1328,9 @@ let RedisQueue = (() => {
1192
1328
  /**
1193
1329
  * Establishes a given connection channel by its name
1194
1330
  *
1195
- * @param channel -
1196
- * @param options -
1331
+ * @param channel - which of the queue's connections to open
1332
+ * @param options - connection options; falls back to this queue's own
1333
+ * @returns the ready client
1197
1334
  */
1198
1335
  async connect(channel, options) {
1199
1336
  this.verbose(`Connecting to ${channel} channel...`);
@@ -1206,6 +1343,13 @@ let RedisQueue = (() => {
1206
1343
  host: options.host || 'localhost',
1207
1344
  username: options.username,
1208
1345
  password: options.password,
1346
+ // spread conditionally: the literal stays closed on purpose, so
1347
+ // that nothing a caller passes can override the retry strategy,
1348
+ // the offline queue or the lazy connect this queue's reconnection
1349
+ // logic is built on
1350
+ ...(options.tls
1351
+ ? { tls: options.tls === true ? {} : options.tls }
1352
+ : {}),
1209
1353
  connectionName: this.getChannelName(this.name, options.prefix || '', channel),
1210
1354
  retryStrategy: noRetryStrategy,
1211
1355
  autoResubscribe: true,
@@ -1252,7 +1396,7 @@ let RedisQueue = (() => {
1252
1396
  * Schedules custom reconnection for a given channel with capped
1253
1397
  * exponential backoff
1254
1398
  *
1255
- * @param channel -
1399
+ * @param channel - which of the queue's connections to reconnect
1256
1400
  */
1257
1401
  scheduleReconnect(channel) {
1258
1402
  if (this.destroyed || this.reconnecting[channel]) {
@@ -1274,7 +1418,7 @@ let RedisQueue = (() => {
1274
1418
  * rescheduling itself on failure. Errors are handled internally, so the
1275
1419
  * scheduled timer never produces an unhandled rejection.
1276
1420
  *
1277
- * @param channel -
1421
+ * @param channel - which of the queue's connections to reconnect
1278
1422
  */
1279
1423
  async reconnectNow(channel) {
1280
1424
  if (this.destroyed) {
@@ -1321,9 +1465,12 @@ let RedisQueue = (() => {
1321
1465
  /**
1322
1466
  * Generates channel name
1323
1467
  *
1324
- * @param contextName -
1325
- * @param prefix -
1326
- * @param name -
1468
+ * @param contextName - the queue name the connection belongs to
1469
+ * @param prefix - the key prefix this queue works under
1470
+ * @param name - which of the queue's connections this is
1471
+ * @returns the name registered with the broker, ending in this process's
1472
+ * pid and host — which is what makes a connection, and so a lease
1473
+ * owner, identifiable in `CLIENT LIST`
1327
1474
  */
1328
1475
  getChannelName(contextName, prefix, name) {
1329
1476
  const uniqueSuffix = `pid:${process.pid}:host:${hostname()}`;
@@ -1332,11 +1479,18 @@ let RedisQueue = (() => {
1332
1479
  /**
1333
1480
  * Builds and returns connection error handler
1334
1481
  *
1335
- * @param channel -
1482
+ * @param channel - which of the queue's connections the handler is for
1483
+ * @returns the handler to attach to that connection's `error` event
1336
1484
  */
1337
1485
  onErrorHandler(channel) {
1338
1486
  return (error) => {
1339
1487
  this.verbose(`Redis Error: ${error}`);
1488
+ // the failure that brings a socket down is rarely the last thing
1489
+ // it reports, and the client's own guard is spent by this one
1490
+ const failed = this.connectionOf(channel);
1491
+ if (failed) {
1492
+ this.guardSocket(failed);
1493
+ }
1340
1494
  if (this.destroyed) {
1341
1495
  return;
1342
1496
  }
@@ -1351,7 +1505,8 @@ let RedisQueue = (() => {
1351
1505
  /**
1352
1506
  * Builds and returns redis connection close handler
1353
1507
  *
1354
- * @param channel -
1508
+ * @param channel - which of the queue's connections the handler is for
1509
+ * @returns the handler to attach to that connection's `close` event
1355
1510
  */
1356
1511
  onCloseHandler(channel) {
1357
1512
  this.verbose(`Redis ${channel} is closing...`);
@@ -1364,23 +1519,41 @@ let RedisQueue = (() => {
1364
1519
  };
1365
1520
  }
1366
1521
  /**
1367
- * Processes given redis-queue message
1522
+ * Unpacks one raw queue message and hands it to the `message` listeners.
1523
+ *
1524
+ * @param msg - the `[queue key, packed message]` pair as read off redis
1525
+ * @returns the promises the listeners returned, empty when none did
1526
+ *
1527
+ * @remarks
1528
+ * The return value is how the caller learns when the listeners are actually
1529
+ * finished, which is what {@link RedisQueue.readSafe} needs in order to know
1530
+ * when a message's lease may be dropped. `emit()` discards what a listener
1531
+ * returns, so the listeners are invoked directly; raw listeners are used so
1532
+ * a `once` listener still removes itself and still yields its value, exactly
1533
+ * as `emit()` would have arranged.
1368
1534
  *
1369
- * @param msg -
1535
+ * A listener throwing synchronously propagates, as it does through `emit()`.
1536
+ * An unreadable message dispatches nothing and reports nothing pending.
1370
1537
  */
1371
1538
  process(msg) {
1372
1539
  const [queue, data] = msg;
1540
+ const pending = [];
1373
1541
  if (!queue || queue !== this.key) {
1374
- return this;
1542
+ return pending;
1375
1543
  }
1376
1544
  try {
1377
1545
  const { id, message, from } = this.unpack(data);
1378
- this.emit('message', message, id, from);
1546
+ for (const listener of this.rawListeners('message')) {
1547
+ const result = listener.call(this, message, id, from);
1548
+ if (typeof result?.then === 'function') {
1549
+ pending.push(result);
1550
+ }
1551
+ }
1379
1552
  }
1380
1553
  catch (err) {
1381
1554
  this.emitError('OnMessage', 'process error - message is invalid', err);
1382
1555
  }
1383
- return this;
1556
+ return pending;
1384
1557
  }
1385
1558
  /**
1386
1559
  * Returns the number of established watcher connections on redis
@@ -1397,9 +1570,9 @@ let RedisQueue = (() => {
1397
1570
  return list.split(/\r?\n/).filter(client => rx.test(client)).length;
1398
1571
  }
1399
1572
  /**
1400
- * Processes delayed a message by its given redis key
1573
+ * Moves messages whose delay has elapsed onto their queue.
1401
1574
  *
1402
- * @param key -
1575
+ * @param key - the queue key whose `:delayed` companion to drain
1403
1576
  */
1404
1577
  async processDelayed(key) {
1405
1578
  try {
@@ -1426,16 +1599,22 @@ let RedisQueue = (() => {
1426
1599
  }
1427
1600
  }
1428
1601
  /**
1429
- * Watch routine
1602
+ * Sweeps for leases whose worker is not coming back and returns their
1603
+ * messages to the queue.
1604
+ *
1605
+ * @param clients - raw `CLIENT LIST` output for this tick, or `undefined`
1606
+ * when it could not be read, in which case liveness is unknown and a
1607
+ * lease is left to its budget rather than guessed at
1430
1608
  */
1431
- async processWatch() {
1609
+ async processWatch(clients) {
1610
+ const owners = clients === undefined ? undefined : this.connectedOwners(clients);
1432
1611
  const now = Date.now();
1433
1612
  let cursor = '0';
1434
1613
  while (true) {
1435
1614
  try {
1436
1615
  const [next, keys] = await this.writer.scan(cursor, 'MATCH', `${this.options.prefix}:*:worker:*`, 'COUNT', SCAN_COUNT);
1437
1616
  cursor = next;
1438
- await this.processKeys(keys, now);
1617
+ await this.processKeys(keys, now, owners);
1439
1618
  if (cursor === '0') {
1440
1619
  return;
1441
1620
  }
@@ -1454,12 +1633,50 @@ let RedisQueue = (() => {
1454
1633
  }
1455
1634
  }
1456
1635
  /**
1457
- * Process given keys from a message queue
1636
+ * Decides whether one worker key has been abandoned.
1637
+ *
1638
+ * @param key - the worker key
1639
+ * @param now - the timestamp this sweep started at
1640
+ * @param owners - processes currently connected, or `undefined` when the
1641
+ * client list could not be read
1642
+ * @returns whether this key's message should go back on the queue
1458
1643
  *
1459
- * @param keys -
1460
- * @param now -
1644
+ * @remarks
1645
+ * Which scheme applies is read off the key itself rather than off this
1646
+ * queue's options, because the sweeper serves every queue sharing the
1647
+ * prefix and they need not be configured alike.
1648
+ *
1649
+ * A key naming its owner is abandoned on either of two counts, because
1650
+ * there are two ways to lose a message. The owner having left the broker's
1651
+ * client list catches the process dying — the common case, detected as fast
1652
+ * as the socket closes and needing nothing renewed to keep a live lease
1653
+ * alive. The deadline catches what liveness cannot see: a worker that is up,
1654
+ * connected and serving other messages while one handler has wedged on this
1655
+ * one. The budget is honoured even when liveness is unknown, since an
1656
+ * exhausted budget is exhausted either way.
1657
+ *
1658
+ * A key with no owner was written by 3.x, before leases named one. Its
1659
+ * deadline is the whole story, exactly as it was then, so a rolling upgrade
1660
+ * does not strand it.
1461
1661
  */
1462
- async processKeys(keys, now) {
1662
+ isAbandoned(key, now, owners) {
1663
+ const owner = RX_LEASE_OWNER.exec(key);
1664
+ const expired = Number(key.split(':').pop()) < now;
1665
+ if (!owner) {
1666
+ return expired;
1667
+ }
1668
+ return expired || (owners ? !owners.has(owner[1]) : false);
1669
+ }
1670
+ /**
1671
+ * Returns the messages of abandoned leases to their queues.
1672
+ *
1673
+ * @param keys - worker keys from one page of the sweep's `SCAN`
1674
+ * @param now - the timestamp the sweep started at, so every key in a pass
1675
+ * is judged against the same instant
1676
+ * @param owners - processes currently connected, or `undefined` when the
1677
+ * client list could not be read
1678
+ */
1679
+ async processKeys(keys, now, owners) {
1463
1680
  if (!keys.length) {
1464
1681
  return;
1465
1682
  }
@@ -1469,14 +1686,11 @@ let RedisQueue = (() => {
1469
1686
  .join(', ')}`);
1470
1687
  try {
1471
1688
  for (const key of keys) {
1472
- const kp = key.split(':');
1473
- // the last key segment is the worker's lease deadline: only
1474
- // re-queue messages of workers whose lease has expired (the
1475
- // worker died mid-processing); fresh leases belong to live
1476
- // workers and must not be touched
1477
- if (Number(kp.pop()) >= now) {
1689
+ if (!this.isAbandoned(key, now, owners)) {
1478
1690
  continue;
1479
1691
  }
1692
+ const kp = key.split(':');
1693
+ kp.pop();
1480
1694
  const target = `${kp.shift()}:${kp.shift()}`;
1481
1695
  const moved = await this.writer.lmove(key, target, 'RIGHT', 'LEFT');
1482
1696
  // a non-empty result means a message whose lease expired is being
@@ -1512,9 +1726,10 @@ let RedisQueue = (() => {
1512
1726
  }
1513
1727
  }
1514
1728
  /**
1515
- * Watch message processor
1729
+ * Handles one keyspace notification from the watcher subscription.
1516
1730
  *
1517
- * @param args -
1731
+ * @param args - the `pmessage` arguments; only the last, the expired key,
1732
+ * is used, and only when it is a delayed message's ttl marker
1518
1733
  */
1519
1734
  async onWatchMessage(...args) {
1520
1735
  try {
@@ -1617,7 +1832,15 @@ let RedisQueue = (() => {
1617
1832
  .catch((err) => this.verbose(`Error subscribing to watcher channel: ${err}`));
1618
1833
  // watch for expired unhandled safe queues
1619
1834
  if (!this.safeCheckInterval && this.options.safeDeliveryTtl != null) {
1620
- this.safeCheckInterval = setInterval(this.runSafeCheck.bind(this), this.options.safeDeliveryTtl);
1835
+ // the sweep is watcher maintenance, so it runs on the watcher's own
1836
+ // cadence rather than on the processing budget: how long a message
1837
+ // may be worked on and how often we look for abandoned ones are
1838
+ // different questions, and tying them would make a crashed worker's
1839
+ // message wait out a budget meant for a live one. Falls back to the
1840
+ // budget only when the watcher check is switched off outright
1841
+ this.safeCheckInterval = setInterval(this.runSafeCheck.bind(this), Number(this.options.watcherCheckDelay) > 0
1842
+ ? Number(this.options.watcherCheckDelay)
1843
+ : Number(this.options.safeDeliveryTtl));
1621
1844
  // maintenance timer must not keep the process alive on its own
1622
1845
  this.safeCheckInterval.unref();
1623
1846
  }
@@ -1641,15 +1864,78 @@ let RedisQueue = (() => {
1641
1864
  this.cleanSafeCheckInterval();
1642
1865
  return;
1643
1866
  }
1867
+ // one CLIENT LIST for the tick. The cleanup pass has always needed it
1868
+ // and lease recovery needs the same answer, so asking twice would be
1869
+ // the only redis traffic this design could add - and it does not.
1870
+ // `undefined` means it could not be read, which is emphatically not
1871
+ // "nobody is connected": both consumers treat it as unknown and do
1872
+ // nothing rather than reclaiming or deleting
1873
+ const clients = this.options.cleanup || this.options.safeDelivery
1874
+ ? await this.readClients()
1875
+ : undefined;
1644
1876
  if (this.options.safeDelivery) {
1645
- await this.processWatch();
1877
+ await this.processWatch(clients);
1646
1878
  }
1647
- await this.processCleanup();
1879
+ await this.processCleanup(clients);
1648
1880
  }
1649
1881
  /**
1650
- * Cleans up orphaned keys from redis
1882
+ * Reads the broker's client list.
1883
+ *
1884
+ * @returns the raw `CLIENT LIST` output, or `undefined` when it could not
1885
+ * be read
1886
+ *
1887
+ * @remarks
1888
+ * A failure must not read as "nobody is connected" — that would reclaim
1889
+ * every lease in flight and delete every key in the prefix — so it is
1890
+ * reported as unknown rather than as an empty list.
1651
1891
  */
1652
- async processCleanup() {
1892
+ async readClients() {
1893
+ try {
1894
+ return (await this.writer.client('LIST')).toString();
1895
+ }
1896
+ catch (err) {
1897
+ this.logLine('warn', `client list read failed, code ${errorCode(err)}`);
1898
+ return undefined;
1899
+ }
1900
+ }
1901
+ /**
1902
+ * Extracts the processes currently connected to the broker, as the owner
1903
+ * tokens stamped into worker keys.
1904
+ *
1905
+ * @param clients - raw `CLIENT LIST` output
1906
+ * @returns owners seen connected now, plus those seen on the previous sweep
1907
+ *
1908
+ * @remarks
1909
+ * Previous-sweep owners are included deliberately, mirroring the grace the
1910
+ * cleanup pass already gives reconnecting clients: a worker riding out a
1911
+ * reconnect backoff briefly leaves the client list, and reclaiming its
1912
+ * leases then would re-deliver work that is still running. One sweep of
1913
+ * grace costs one sweep of recovery latency and removes that whole class of
1914
+ * duplicate.
1915
+ */
1916
+ connectedOwners(clients) {
1917
+ const seen = new Set();
1918
+ for (const name of clients.match(RX_CLIENT_NAME) || []) {
1919
+ const owner = RX_CLIENT_OWNER.exec(name);
1920
+ if (owner) {
1921
+ seen.add(owner[1]);
1922
+ }
1923
+ }
1924
+ const owners = new Set([...seen, ...this.lastOwners]);
1925
+ this.lastOwners = seen;
1926
+ return owners;
1927
+ }
1928
+ /**
1929
+ * Removes keys left behind by clients that are no longer connected.
1930
+ *
1931
+ * @param clients - raw `CLIENT LIST` output for this tick, so the list is
1932
+ * read once per sweep. Called on its own, this reads its own; a read
1933
+ * that fails throws into the catch below and deletes nothing,
1934
+ * because treating an unreadable list as "no client owns anything"
1935
+ * would delete every key in the prefix
1936
+ * @returns this queue instance, or `undefined` when cleanup is disabled
1937
+ */
1938
+ async processCleanup(clients) {
1653
1939
  this.verbose('Cleaning up orphaned keys...');
1654
1940
  try {
1655
1941
  if (!this.options.cleanup) {
@@ -1659,8 +1945,9 @@ let RedisQueue = (() => {
1659
1945
  ':' +
1660
1946
  escapeRegExp(this.options.cleanupFilter || '*').replace(/\\\*/g, '.*'), 'i');
1661
1947
  this.verbose(`Cleaning up keys matching ${filter}`);
1662
- const clients = (await this.writer.client('LIST')).toString() || '';
1663
- const connectedKeys = (clients.match(RX_CLIENT_NAME) || [])
1948
+ const list = clients ??
1949
+ (await this.writer.client('LIST')).toString();
1950
+ const connectedKeys = (list.match(RX_CLIENT_NAME) || [])
1664
1951
  .filter((name) => RX_CLIENT_TEST.test(name) && filter.test(name))
1665
1952
  .map((name) => name.replace(/^name=/, '').replace(RX_CLIENT_CLEAN, ''))
1666
1953
  .filter((name, i, a) => a.indexOf(name) === i);
@@ -1741,6 +2028,22 @@ let RedisQueue = (() => {
1741
2028
  this.emitError('OnReadUnsafe', 'unsafe reader failed', err);
1742
2029
  }
1743
2030
  }
2031
+ /**
2032
+ * Ends one lease, dropping the worker key and with it the message.
2033
+ *
2034
+ * @param workerKey - the key holding the message
2035
+ *
2036
+ * @remarks
2037
+ * Idempotent, and never throws: an undeleted worker key is re-queued by the
2038
+ * watcher later, which is one of the causes a handler can be given for a
2039
+ * duplicate. The key itself is never logged, as it carries the queue name
2040
+ * and the lease id.
2041
+ */
2042
+ releaseLease(workerKey) {
2043
+ this.writer
2044
+ ?.del(workerKey)
2045
+ .catch((err) => this.logLine('warn', `OnReadSafe: del error, queue ${this.name}, code ${errorCode(err)}`));
2046
+ }
1744
2047
  /**
1745
2048
  * Reliable but slow method of message handling by message queue.
1746
2049
  *
@@ -1753,13 +2056,14 @@ let RedisQueue = (() => {
1753
2056
  const key = this.key;
1754
2057
  // blocking timeout in seconds, at most half of the lease ttl, so
1755
2058
  // a claimed message always has at least half the ttl remaining
1756
- const timeout = Math.max(0.1, Number(this.options.safeDeliveryTtl) / 2000);
2059
+ const timeout = Math.max(0.1, Math.min(Number(this.options.safeDeliveryTtl) / 2, READ_MAX_BLOCK) /
2060
+ 1000);
1757
2061
  while (true) {
1758
2062
  if (!this.reader || !this.writer || this.destroyed) {
1759
2063
  break;
1760
2064
  }
1761
2065
  const expire = Date.now() + Number(this.options.safeDeliveryTtl);
1762
- const workerKey = `${key}:worker:${randomUUID()}:${expire}`;
2066
+ const workerKey = `${key}:worker:${randomUUID()}:${OWNER}:${expire}`;
1763
2067
  let msg;
1764
2068
  try {
1765
2069
  msg = await this.reader.blmove(this.key, workerKey, 'RIGHT', 'LEFT', timeout);
@@ -1796,16 +2100,25 @@ let RedisQueue = (() => {
1796
2100
  continue;
1797
2101
  }
1798
2102
  try {
1799
- this.process([key, msg]);
1800
- this.writer.del(workerKey).catch((err) =>
1801
- // an undeleted worker key is re-queued by the watcher
1802
- // later, which is the other cause of a duplicate. The
1803
- // key itself is never logged: it carries the client
1804
- // queue name, the lease uuid and its deadline
1805
- this.logLine('warn', `OnReadSafe: del error, queue ${this.name}, code ${errorCode(err)}`));
2103
+ const pending = this.process([key, msg]);
2104
+ if (pending.length) {
2105
+ // the listeners are still working: the message stays in
2106
+ // its worker key, so a worker that dies now leaves it to
2107
+ // be re-queued instead of taking it down. Settled, not
2108
+ // fulfilled - a handler that threw has had its turn, and
2109
+ // re-delivering on a rejection would retry forever
2110
+ void Promise.allSettled(pending).then(() => this.releaseLease(workerKey));
2111
+ }
2112
+ else {
2113
+ // nothing asynchronous was started, so the listeners are
2114
+ // already done - all a synchronous handler can offer
2115
+ this.releaseLease(workerKey);
2116
+ }
1806
2117
  }
1807
2118
  catch (err) {
1808
- // a single message failure must never kill the read loop
2119
+ // a single message failure must never kill the read loop, and
2120
+ // must not strand its lease either
2121
+ this.releaseLease(workerKey);
1809
2122
  this.emitError('OnReadSafe', 'safe reader failed', err);
1810
2123
  }
1811
2124
  }
@@ -1854,9 +2167,10 @@ let RedisQueue = (() => {
1854
2167
  /**
1855
2168
  * Emits error
1856
2169
  *
1857
- * @param eventName -
1858
- * @param message -
1859
- * @param err -
2170
+ * @param eventName - the internal routine that caught it, used as a
2171
+ * diagnostic label such as `OnMessage` or `OnReadSafe`
2172
+ * @param message - human-readable context for the log line
2173
+ * @param err - the caught value, wrapped when it is not an `Error`
1860
2174
  */
1861
2175
  emitError(eventName, message, err) {
1862
2176
  const error = err instanceof Error ? err : new Error(String(err));