@imqueue/core 3.4.1 → 3.4.3
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/AGENTS.md +17 -5
- package/CHANGELOG.md +108 -0
- package/README.md +75 -0
- package/index.d.ts +7 -0
- package/index.js +7 -0
- package/package.json +2 -2
- package/src/ClusterManager.d.ts +5 -0
- package/src/ClusterManager.js +5 -0
- package/src/ClusteredRedisQueue.d.ts +62 -0
- package/src/ClusteredRedisQueue.js +62 -0
- package/src/IMessageQueue.d.ts +103 -46
- package/src/RedisQueue.d.ts +196 -42
- package/src/RedisQueue.js +297 -71
- package/src/UDPClusterManager.d.ts +35 -0
- package/src/UDPClusterManager.js +35 -0
- package/src/UDPWorker.d.ts +134 -1
- package/src/UDPWorker.js +140 -1
- package/src/helpers/copyEventEmitter.d.ts +21 -0
- package/src/helpers/copyEventEmitter.js +21 -0
- package/CLAUDE.md +0 -2
package/src/RedisQueue.js
CHANGED
|
@@ -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:
|
|
142
|
+
safeDeliveryTtl: 300000,
|
|
125
143
|
useGzip: false,
|
|
126
144
|
watcherCheckDelay: 5000,
|
|
127
145
|
handleSignals: true,
|
|
@@ -309,6 +327,8 @@ let RedisQueue = (() => {
|
|
|
309
327
|
* removing their keys.
|
|
310
328
|
*/
|
|
311
329
|
lastConnectedKeys = [];
|
|
330
|
+
/** Lease owners seen connected on the previous sweep (one sweep of grace) */
|
|
331
|
+
lastOwners = new Set();
|
|
312
332
|
/**
|
|
313
333
|
* True while this instance holds a reference to the shared writer
|
|
314
334
|
*/
|
|
@@ -317,7 +337,18 @@ let RedisQueue = (() => {
|
|
|
317
337
|
* Internal per-channel reconnection state
|
|
318
338
|
*/
|
|
319
339
|
reconnectTimers = {};
|
|
340
|
+
/**
|
|
341
|
+
* Consecutive failed reconnection attempts per channel, which is what the
|
|
342
|
+
* backoff delay is computed from. Reset once a channel connects again.
|
|
343
|
+
*/
|
|
320
344
|
reconnectAttempts = {};
|
|
345
|
+
/**
|
|
346
|
+
* Channels with a reconnection already in progress.
|
|
347
|
+
*
|
|
348
|
+
* @remarks
|
|
349
|
+
* A guard, not a status: several `close` events can arrive for one channel,
|
|
350
|
+
* and without this each would start its own reconnection loop.
|
|
351
|
+
*/
|
|
321
352
|
reconnecting = {};
|
|
322
353
|
/**
|
|
323
354
|
* The `host:port` address of the redis server this queue talks to.
|
|
@@ -357,13 +388,18 @@ let RedisQueue = (() => {
|
|
|
357
388
|
/**
|
|
358
389
|
* Serializes a given data object into string
|
|
359
390
|
*
|
|
360
|
-
* @param data -
|
|
391
|
+
* @param data - the value to serialize; must be JSON-serializable
|
|
392
|
+
* @returns the wire representation, gzipped when
|
|
393
|
+
* {@link IMQOptions.useGzip} is on
|
|
361
394
|
*/
|
|
362
395
|
pack;
|
|
363
396
|
/**
|
|
364
397
|
* Deserialize string data into an object
|
|
365
398
|
*
|
|
366
|
-
* @param data -
|
|
399
|
+
* @param data - the wire representation, as produced by `pack`
|
|
400
|
+
* @returns the deserialized value
|
|
401
|
+
* @throws when the payload is malformed, or was packed with a different
|
|
402
|
+
* {@link IMQOptions.useGzip} setting
|
|
367
403
|
*/
|
|
368
404
|
unpack;
|
|
369
405
|
/**
|
|
@@ -394,7 +430,16 @@ let RedisQueue = (() => {
|
|
|
394
430
|
* Assign it before {@link RedisQueue.start} — a running reader keeps
|
|
395
431
|
* consuming the key it was started with.
|
|
396
432
|
*/
|
|
397
|
-
name, options,
|
|
433
|
+
name, options,
|
|
434
|
+
/**
|
|
435
|
+
* Whether this handle publishes, consumes, or both.
|
|
436
|
+
*
|
|
437
|
+
* @remarks
|
|
438
|
+
* Fixed at construction: it decides which connections `start()` opens,
|
|
439
|
+
* so a publisher never opens a reader and cannot consume even by
|
|
440
|
+
* accident.
|
|
441
|
+
*/
|
|
442
|
+
mode = IMQMode.BOTH) {
|
|
398
443
|
super();
|
|
399
444
|
this.name = name;
|
|
400
445
|
this.mode = mode;
|
|
@@ -407,6 +452,15 @@ let RedisQueue = (() => {
|
|
|
407
452
|
}
|
|
408
453
|
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
454
|
}
|
|
455
|
+
/**
|
|
456
|
+
* Writes a diagnostic line, but only under {@link IMQOptions.verbose}.
|
|
457
|
+
*
|
|
458
|
+
* @param message - the line to write, tagged with this queue's name
|
|
459
|
+
*
|
|
460
|
+
* @remarks
|
|
461
|
+
* For tracing the queue's own lifecycle. Anything a user must see whether
|
|
462
|
+
* or not verbose is on goes through `logLine` instead.
|
|
463
|
+
*/
|
|
410
464
|
verbose(message) {
|
|
411
465
|
if (this.options.verbose) {
|
|
412
466
|
this.logger.info(`[IMQ-CORE][${this.name}]: ${message}`);
|
|
@@ -508,8 +562,8 @@ let RedisQueue = (() => {
|
|
|
508
562
|
* Attaches a subscription message handler to a given channel
|
|
509
563
|
* connection
|
|
510
564
|
*
|
|
511
|
-
* @param chan -
|
|
512
|
-
* @param handler -
|
|
565
|
+
* @param chan - the pub/sub channel to deliver messages from
|
|
566
|
+
* @param handler - called with the decoded payload of each message
|
|
513
567
|
*/
|
|
514
568
|
attachSubscriptionHandler(chan, handler) {
|
|
515
569
|
const fcn = `${this.options.prefix}:${this.subscriptionName}`;
|
|
@@ -926,9 +980,11 @@ let RedisQueue = (() => {
|
|
|
926
980
|
* and silently discarded.
|
|
927
981
|
*
|
|
928
982
|
* With `clearData` set, only the main and delayed keys are removed: messages
|
|
929
|
-
* currently
|
|
930
|
-
* not, and the watcher
|
|
931
|
-
*
|
|
983
|
+
* currently checked out to a worker key under
|
|
984
|
+
* {@link IMQOptions.safeDelivery} are not, and the watcher returns them to
|
|
985
|
+
* the queue once their worker is gone or their
|
|
986
|
+
* {@link IMQOptions.safeDeliveryTtl} is spent — so messages can reappear
|
|
987
|
+
* after a clearing destroy.
|
|
932
988
|
*
|
|
933
989
|
* Never rejects; unlock and clear failures are logged.
|
|
934
990
|
*/
|
|
@@ -960,9 +1016,10 @@ let RedisQueue = (() => {
|
|
|
960
1016
|
* @remarks
|
|
961
1017
|
* A no-op that resolves successfully when the queue has no writer connection.
|
|
962
1018
|
* In-flight messages held in worker keys under
|
|
963
|
-
* {@link IMQOptions.safeDelivery} are not removed and
|
|
964
|
-
*
|
|
965
|
-
*
|
|
1019
|
+
* {@link IMQOptions.safeDelivery} are not removed, and the watcher returns
|
|
1020
|
+
* them to the queue once their worker is gone or their
|
|
1021
|
+
* {@link IMQOptions.safeDeliveryTtl} is spent — so this does not guarantee
|
|
1022
|
+
* the queue stays empty. Errors are logged rather than thrown, so success cannot be
|
|
966
1023
|
* inferred from a resolved promise.
|
|
967
1024
|
*/
|
|
968
1025
|
async clear() {
|
|
@@ -990,11 +1047,14 @@ let RedisQueue = (() => {
|
|
|
990
1047
|
* @returns count of messages waiting to be consumed
|
|
991
1048
|
*
|
|
992
1049
|
* @remarks
|
|
993
|
-
* Delayed messages that are not yet due, and messages currently
|
|
994
|
-
* worker under {@link IMQOptions.safeDelivery}, are not counted — so
|
|
995
|
-
* is not the amount of outstanding work.
|
|
996
|
-
*
|
|
997
|
-
*
|
|
1050
|
+
* Delayed messages that are not yet due, and messages currently checked out
|
|
1051
|
+
* to a worker under {@link IMQOptions.safeDelivery}, are not counted — so
|
|
1052
|
+
* this is not the amount of outstanding work. Under safe delivery a message
|
|
1053
|
+
* is checked out for as long as its handler runs, so on a busy queue the
|
|
1054
|
+
* shortfall is roughly everything in flight, not a rounding error.
|
|
1055
|
+
*
|
|
1056
|
+
* Returns `0` when the queue has no writer connection, which makes
|
|
1057
|
+
* "disconnected" indistinguishable from "empty"; it never throws.
|
|
998
1058
|
*/
|
|
999
1059
|
async queueLength() {
|
|
1000
1060
|
if (!this.writer) {
|
|
@@ -1053,7 +1113,8 @@ let RedisQueue = (() => {
|
|
|
1053
1113
|
/**
|
|
1054
1114
|
* Returns the connection currently bound to the given channel, if any.
|
|
1055
1115
|
*
|
|
1056
|
-
* @param channel -
|
|
1116
|
+
* @param channel - which of the queue's connections to look up
|
|
1117
|
+
* @returns the connection, or `undefined` when that channel is not open
|
|
1057
1118
|
*/
|
|
1058
1119
|
connectionOf(channel) {
|
|
1059
1120
|
switch (channel) {
|
|
@@ -1070,8 +1131,8 @@ let RedisQueue = (() => {
|
|
|
1070
1131
|
/**
|
|
1071
1132
|
* Binds the given connection to the given channel.
|
|
1072
1133
|
*
|
|
1073
|
-
* @param channel -
|
|
1074
|
-
* @param conn -
|
|
1134
|
+
* @param channel - which of the queue's connections to bind
|
|
1135
|
+
* @param conn - the client to bind, or `undefined` to unbind it
|
|
1075
1136
|
*/
|
|
1076
1137
|
bindConnection(channel, conn) {
|
|
1077
1138
|
switch (channel) {
|
|
@@ -1192,8 +1253,9 @@ let RedisQueue = (() => {
|
|
|
1192
1253
|
/**
|
|
1193
1254
|
* Establishes a given connection channel by its name
|
|
1194
1255
|
*
|
|
1195
|
-
* @param channel -
|
|
1196
|
-
* @param options -
|
|
1256
|
+
* @param channel - which of the queue's connections to open
|
|
1257
|
+
* @param options - connection options; falls back to this queue's own
|
|
1258
|
+
* @returns the ready client
|
|
1197
1259
|
*/
|
|
1198
1260
|
async connect(channel, options) {
|
|
1199
1261
|
this.verbose(`Connecting to ${channel} channel...`);
|
|
@@ -1252,7 +1314,7 @@ let RedisQueue = (() => {
|
|
|
1252
1314
|
* Schedules custom reconnection for a given channel with capped
|
|
1253
1315
|
* exponential backoff
|
|
1254
1316
|
*
|
|
1255
|
-
* @param channel -
|
|
1317
|
+
* @param channel - which of the queue's connections to reconnect
|
|
1256
1318
|
*/
|
|
1257
1319
|
scheduleReconnect(channel) {
|
|
1258
1320
|
if (this.destroyed || this.reconnecting[channel]) {
|
|
@@ -1274,7 +1336,7 @@ let RedisQueue = (() => {
|
|
|
1274
1336
|
* rescheduling itself on failure. Errors are handled internally, so the
|
|
1275
1337
|
* scheduled timer never produces an unhandled rejection.
|
|
1276
1338
|
*
|
|
1277
|
-
* @param channel -
|
|
1339
|
+
* @param channel - which of the queue's connections to reconnect
|
|
1278
1340
|
*/
|
|
1279
1341
|
async reconnectNow(channel) {
|
|
1280
1342
|
if (this.destroyed) {
|
|
@@ -1321,9 +1383,12 @@ let RedisQueue = (() => {
|
|
|
1321
1383
|
/**
|
|
1322
1384
|
* Generates channel name
|
|
1323
1385
|
*
|
|
1324
|
-
* @param contextName -
|
|
1325
|
-
* @param prefix -
|
|
1326
|
-
* @param name -
|
|
1386
|
+
* @param contextName - the queue name the connection belongs to
|
|
1387
|
+
* @param prefix - the key prefix this queue works under
|
|
1388
|
+
* @param name - which of the queue's connections this is
|
|
1389
|
+
* @returns the name registered with the broker, ending in this process's
|
|
1390
|
+
* pid and host — which is what makes a connection, and so a lease
|
|
1391
|
+
* owner, identifiable in `CLIENT LIST`
|
|
1327
1392
|
*/
|
|
1328
1393
|
getChannelName(contextName, prefix, name) {
|
|
1329
1394
|
const uniqueSuffix = `pid:${process.pid}:host:${hostname()}`;
|
|
@@ -1332,7 +1397,8 @@ let RedisQueue = (() => {
|
|
|
1332
1397
|
/**
|
|
1333
1398
|
* Builds and returns connection error handler
|
|
1334
1399
|
*
|
|
1335
|
-
* @param channel -
|
|
1400
|
+
* @param channel - which of the queue's connections the handler is for
|
|
1401
|
+
* @returns the handler to attach to that connection's `error` event
|
|
1336
1402
|
*/
|
|
1337
1403
|
onErrorHandler(channel) {
|
|
1338
1404
|
return (error) => {
|
|
@@ -1351,7 +1417,8 @@ let RedisQueue = (() => {
|
|
|
1351
1417
|
/**
|
|
1352
1418
|
* Builds and returns redis connection close handler
|
|
1353
1419
|
*
|
|
1354
|
-
* @param channel -
|
|
1420
|
+
* @param channel - which of the queue's connections the handler is for
|
|
1421
|
+
* @returns the handler to attach to that connection's `close` event
|
|
1355
1422
|
*/
|
|
1356
1423
|
onCloseHandler(channel) {
|
|
1357
1424
|
this.verbose(`Redis ${channel} is closing...`);
|
|
@@ -1364,23 +1431,41 @@ let RedisQueue = (() => {
|
|
|
1364
1431
|
};
|
|
1365
1432
|
}
|
|
1366
1433
|
/**
|
|
1367
|
-
*
|
|
1434
|
+
* Unpacks one raw queue message and hands it to the `message` listeners.
|
|
1435
|
+
*
|
|
1436
|
+
* @param msg - the `[queue key, packed message]` pair as read off redis
|
|
1437
|
+
* @returns the promises the listeners returned, empty when none did
|
|
1368
1438
|
*
|
|
1369
|
-
* @
|
|
1439
|
+
* @remarks
|
|
1440
|
+
* The return value is how the caller learns when the listeners are actually
|
|
1441
|
+
* finished, which is what {@link RedisQueue.readSafe} needs in order to know
|
|
1442
|
+
* when a message's lease may be dropped. `emit()` discards what a listener
|
|
1443
|
+
* returns, so the listeners are invoked directly; raw listeners are used so
|
|
1444
|
+
* a `once` listener still removes itself and still yields its value, exactly
|
|
1445
|
+
* as `emit()` would have arranged.
|
|
1446
|
+
*
|
|
1447
|
+
* A listener throwing synchronously propagates, as it does through `emit()`.
|
|
1448
|
+
* An unreadable message dispatches nothing and reports nothing pending.
|
|
1370
1449
|
*/
|
|
1371
1450
|
process(msg) {
|
|
1372
1451
|
const [queue, data] = msg;
|
|
1452
|
+
const pending = [];
|
|
1373
1453
|
if (!queue || queue !== this.key) {
|
|
1374
|
-
return
|
|
1454
|
+
return pending;
|
|
1375
1455
|
}
|
|
1376
1456
|
try {
|
|
1377
1457
|
const { id, message, from } = this.unpack(data);
|
|
1378
|
-
this.
|
|
1458
|
+
for (const listener of this.rawListeners('message')) {
|
|
1459
|
+
const result = listener.call(this, message, id, from);
|
|
1460
|
+
if (typeof result?.then === 'function') {
|
|
1461
|
+
pending.push(result);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1379
1464
|
}
|
|
1380
1465
|
catch (err) {
|
|
1381
1466
|
this.emitError('OnMessage', 'process error - message is invalid', err);
|
|
1382
1467
|
}
|
|
1383
|
-
return
|
|
1468
|
+
return pending;
|
|
1384
1469
|
}
|
|
1385
1470
|
/**
|
|
1386
1471
|
* Returns the number of established watcher connections on redis
|
|
@@ -1397,9 +1482,9 @@ let RedisQueue = (() => {
|
|
|
1397
1482
|
return list.split(/\r?\n/).filter(client => rx.test(client)).length;
|
|
1398
1483
|
}
|
|
1399
1484
|
/**
|
|
1400
|
-
*
|
|
1485
|
+
* Moves messages whose delay has elapsed onto their queue.
|
|
1401
1486
|
*
|
|
1402
|
-
* @param key -
|
|
1487
|
+
* @param key - the queue key whose `:delayed` companion to drain
|
|
1403
1488
|
*/
|
|
1404
1489
|
async processDelayed(key) {
|
|
1405
1490
|
try {
|
|
@@ -1426,16 +1511,22 @@ let RedisQueue = (() => {
|
|
|
1426
1511
|
}
|
|
1427
1512
|
}
|
|
1428
1513
|
/**
|
|
1429
|
-
*
|
|
1514
|
+
* Sweeps for leases whose worker is not coming back and returns their
|
|
1515
|
+
* messages to the queue.
|
|
1516
|
+
*
|
|
1517
|
+
* @param clients - raw `CLIENT LIST` output for this tick, or `undefined`
|
|
1518
|
+
* when it could not be read, in which case liveness is unknown and a
|
|
1519
|
+
* lease is left to its budget rather than guessed at
|
|
1430
1520
|
*/
|
|
1431
|
-
async processWatch() {
|
|
1521
|
+
async processWatch(clients) {
|
|
1522
|
+
const owners = clients === undefined ? undefined : this.connectedOwners(clients);
|
|
1432
1523
|
const now = Date.now();
|
|
1433
1524
|
let cursor = '0';
|
|
1434
1525
|
while (true) {
|
|
1435
1526
|
try {
|
|
1436
1527
|
const [next, keys] = await this.writer.scan(cursor, 'MATCH', `${this.options.prefix}:*:worker:*`, 'COUNT', SCAN_COUNT);
|
|
1437
1528
|
cursor = next;
|
|
1438
|
-
await this.processKeys(keys, now);
|
|
1529
|
+
await this.processKeys(keys, now, owners);
|
|
1439
1530
|
if (cursor === '0') {
|
|
1440
1531
|
return;
|
|
1441
1532
|
}
|
|
@@ -1454,12 +1545,50 @@ let RedisQueue = (() => {
|
|
|
1454
1545
|
}
|
|
1455
1546
|
}
|
|
1456
1547
|
/**
|
|
1457
|
-
*
|
|
1548
|
+
* Decides whether one worker key has been abandoned.
|
|
1549
|
+
*
|
|
1550
|
+
* @param key - the worker key
|
|
1551
|
+
* @param now - the timestamp this sweep started at
|
|
1552
|
+
* @param owners - processes currently connected, or `undefined` when the
|
|
1553
|
+
* client list could not be read
|
|
1554
|
+
* @returns whether this key's message should go back on the queue
|
|
1458
1555
|
*
|
|
1459
|
-
* @
|
|
1460
|
-
*
|
|
1556
|
+
* @remarks
|
|
1557
|
+
* Which scheme applies is read off the key itself rather than off this
|
|
1558
|
+
* queue's options, because the sweeper serves every queue sharing the
|
|
1559
|
+
* prefix and they need not be configured alike.
|
|
1560
|
+
*
|
|
1561
|
+
* A key naming its owner is abandoned on either of two counts, because
|
|
1562
|
+
* there are two ways to lose a message. The owner having left the broker's
|
|
1563
|
+
* client list catches the process dying — the common case, detected as fast
|
|
1564
|
+
* as the socket closes and needing nothing renewed to keep a live lease
|
|
1565
|
+
* alive. The deadline catches what liveness cannot see: a worker that is up,
|
|
1566
|
+
* connected and serving other messages while one handler has wedged on this
|
|
1567
|
+
* one. The budget is honoured even when liveness is unknown, since an
|
|
1568
|
+
* exhausted budget is exhausted either way.
|
|
1569
|
+
*
|
|
1570
|
+
* A key with no owner was written by 3.x, before leases named one. Its
|
|
1571
|
+
* deadline is the whole story, exactly as it was then, so a rolling upgrade
|
|
1572
|
+
* does not strand it.
|
|
1461
1573
|
*/
|
|
1462
|
-
|
|
1574
|
+
isAbandoned(key, now, owners) {
|
|
1575
|
+
const owner = RX_LEASE_OWNER.exec(key);
|
|
1576
|
+
const expired = Number(key.split(':').pop()) < now;
|
|
1577
|
+
if (!owner) {
|
|
1578
|
+
return expired;
|
|
1579
|
+
}
|
|
1580
|
+
return expired || (owners ? !owners.has(owner[1]) : false);
|
|
1581
|
+
}
|
|
1582
|
+
/**
|
|
1583
|
+
* Returns the messages of abandoned leases to their queues.
|
|
1584
|
+
*
|
|
1585
|
+
* @param keys - worker keys from one page of the sweep's `SCAN`
|
|
1586
|
+
* @param now - the timestamp the sweep started at, so every key in a pass
|
|
1587
|
+
* is judged against the same instant
|
|
1588
|
+
* @param owners - processes currently connected, or `undefined` when the
|
|
1589
|
+
* client list could not be read
|
|
1590
|
+
*/
|
|
1591
|
+
async processKeys(keys, now, owners) {
|
|
1463
1592
|
if (!keys.length) {
|
|
1464
1593
|
return;
|
|
1465
1594
|
}
|
|
@@ -1469,14 +1598,11 @@ let RedisQueue = (() => {
|
|
|
1469
1598
|
.join(', ')}`);
|
|
1470
1599
|
try {
|
|
1471
1600
|
for (const key of keys) {
|
|
1472
|
-
|
|
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) {
|
|
1601
|
+
if (!this.isAbandoned(key, now, owners)) {
|
|
1478
1602
|
continue;
|
|
1479
1603
|
}
|
|
1604
|
+
const kp = key.split(':');
|
|
1605
|
+
kp.pop();
|
|
1480
1606
|
const target = `${kp.shift()}:${kp.shift()}`;
|
|
1481
1607
|
const moved = await this.writer.lmove(key, target, 'RIGHT', 'LEFT');
|
|
1482
1608
|
// a non-empty result means a message whose lease expired is being
|
|
@@ -1512,9 +1638,10 @@ let RedisQueue = (() => {
|
|
|
1512
1638
|
}
|
|
1513
1639
|
}
|
|
1514
1640
|
/**
|
|
1515
|
-
*
|
|
1641
|
+
* Handles one keyspace notification from the watcher subscription.
|
|
1516
1642
|
*
|
|
1517
|
-
* @param args -
|
|
1643
|
+
* @param args - the `pmessage` arguments; only the last, the expired key,
|
|
1644
|
+
* is used, and only when it is a delayed message's ttl marker
|
|
1518
1645
|
*/
|
|
1519
1646
|
async onWatchMessage(...args) {
|
|
1520
1647
|
try {
|
|
@@ -1617,7 +1744,15 @@ let RedisQueue = (() => {
|
|
|
1617
1744
|
.catch((err) => this.verbose(`Error subscribing to watcher channel: ${err}`));
|
|
1618
1745
|
// watch for expired unhandled safe queues
|
|
1619
1746
|
if (!this.safeCheckInterval && this.options.safeDeliveryTtl != null) {
|
|
1620
|
-
|
|
1747
|
+
// the sweep is watcher maintenance, so it runs on the watcher's own
|
|
1748
|
+
// cadence rather than on the processing budget: how long a message
|
|
1749
|
+
// may be worked on and how often we look for abandoned ones are
|
|
1750
|
+
// different questions, and tying them would make a crashed worker's
|
|
1751
|
+
// message wait out a budget meant for a live one. Falls back to the
|
|
1752
|
+
// budget only when the watcher check is switched off outright
|
|
1753
|
+
this.safeCheckInterval = setInterval(this.runSafeCheck.bind(this), Number(this.options.watcherCheckDelay) > 0
|
|
1754
|
+
? Number(this.options.watcherCheckDelay)
|
|
1755
|
+
: Number(this.options.safeDeliveryTtl));
|
|
1621
1756
|
// maintenance timer must not keep the process alive on its own
|
|
1622
1757
|
this.safeCheckInterval.unref();
|
|
1623
1758
|
}
|
|
@@ -1641,15 +1776,78 @@ let RedisQueue = (() => {
|
|
|
1641
1776
|
this.cleanSafeCheckInterval();
|
|
1642
1777
|
return;
|
|
1643
1778
|
}
|
|
1779
|
+
// one CLIENT LIST for the tick. The cleanup pass has always needed it
|
|
1780
|
+
// and lease recovery needs the same answer, so asking twice would be
|
|
1781
|
+
// the only redis traffic this design could add - and it does not.
|
|
1782
|
+
// `undefined` means it could not be read, which is emphatically not
|
|
1783
|
+
// "nobody is connected": both consumers treat it as unknown and do
|
|
1784
|
+
// nothing rather than reclaiming or deleting
|
|
1785
|
+
const clients = this.options.cleanup || this.options.safeDelivery
|
|
1786
|
+
? await this.readClients()
|
|
1787
|
+
: undefined;
|
|
1644
1788
|
if (this.options.safeDelivery) {
|
|
1645
|
-
await this.processWatch();
|
|
1789
|
+
await this.processWatch(clients);
|
|
1646
1790
|
}
|
|
1647
|
-
await this.processCleanup();
|
|
1791
|
+
await this.processCleanup(clients);
|
|
1648
1792
|
}
|
|
1649
1793
|
/**
|
|
1650
|
-
*
|
|
1794
|
+
* Reads the broker's client list.
|
|
1795
|
+
*
|
|
1796
|
+
* @returns the raw `CLIENT LIST` output, or `undefined` when it could not
|
|
1797
|
+
* be read
|
|
1798
|
+
*
|
|
1799
|
+
* @remarks
|
|
1800
|
+
* A failure must not read as "nobody is connected" — that would reclaim
|
|
1801
|
+
* every lease in flight and delete every key in the prefix — so it is
|
|
1802
|
+
* reported as unknown rather than as an empty list.
|
|
1651
1803
|
*/
|
|
1652
|
-
async
|
|
1804
|
+
async readClients() {
|
|
1805
|
+
try {
|
|
1806
|
+
return (await this.writer.client('LIST')).toString();
|
|
1807
|
+
}
|
|
1808
|
+
catch (err) {
|
|
1809
|
+
this.logLine('warn', `client list read failed, code ${errorCode(err)}`);
|
|
1810
|
+
return undefined;
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
/**
|
|
1814
|
+
* Extracts the processes currently connected to the broker, as the owner
|
|
1815
|
+
* tokens stamped into worker keys.
|
|
1816
|
+
*
|
|
1817
|
+
* @param clients - raw `CLIENT LIST` output
|
|
1818
|
+
* @returns owners seen connected now, plus those seen on the previous sweep
|
|
1819
|
+
*
|
|
1820
|
+
* @remarks
|
|
1821
|
+
* Previous-sweep owners are included deliberately, mirroring the grace the
|
|
1822
|
+
* cleanup pass already gives reconnecting clients: a worker riding out a
|
|
1823
|
+
* reconnect backoff briefly leaves the client list, and reclaiming its
|
|
1824
|
+
* leases then would re-deliver work that is still running. One sweep of
|
|
1825
|
+
* grace costs one sweep of recovery latency and removes that whole class of
|
|
1826
|
+
* duplicate.
|
|
1827
|
+
*/
|
|
1828
|
+
connectedOwners(clients) {
|
|
1829
|
+
const seen = new Set();
|
|
1830
|
+
for (const name of clients.match(RX_CLIENT_NAME) || []) {
|
|
1831
|
+
const owner = RX_CLIENT_OWNER.exec(name);
|
|
1832
|
+
if (owner) {
|
|
1833
|
+
seen.add(owner[1]);
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
const owners = new Set([...seen, ...this.lastOwners]);
|
|
1837
|
+
this.lastOwners = seen;
|
|
1838
|
+
return owners;
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Removes keys left behind by clients that are no longer connected.
|
|
1842
|
+
*
|
|
1843
|
+
* @param clients - raw `CLIENT LIST` output for this tick, so the list is
|
|
1844
|
+
* read once per sweep. Called on its own, this reads its own; a read
|
|
1845
|
+
* that fails throws into the catch below and deletes nothing,
|
|
1846
|
+
* because treating an unreadable list as "no client owns anything"
|
|
1847
|
+
* would delete every key in the prefix
|
|
1848
|
+
* @returns this queue instance, or `undefined` when cleanup is disabled
|
|
1849
|
+
*/
|
|
1850
|
+
async processCleanup(clients) {
|
|
1653
1851
|
this.verbose('Cleaning up orphaned keys...');
|
|
1654
1852
|
try {
|
|
1655
1853
|
if (!this.options.cleanup) {
|
|
@@ -1659,8 +1857,9 @@ let RedisQueue = (() => {
|
|
|
1659
1857
|
':' +
|
|
1660
1858
|
escapeRegExp(this.options.cleanupFilter || '*').replace(/\\\*/g, '.*'), 'i');
|
|
1661
1859
|
this.verbose(`Cleaning up keys matching ${filter}`);
|
|
1662
|
-
const
|
|
1663
|
-
|
|
1860
|
+
const list = clients ??
|
|
1861
|
+
(await this.writer.client('LIST')).toString();
|
|
1862
|
+
const connectedKeys = (list.match(RX_CLIENT_NAME) || [])
|
|
1664
1863
|
.filter((name) => RX_CLIENT_TEST.test(name) && filter.test(name))
|
|
1665
1864
|
.map((name) => name.replace(/^name=/, '').replace(RX_CLIENT_CLEAN, ''))
|
|
1666
1865
|
.filter((name, i, a) => a.indexOf(name) === i);
|
|
@@ -1741,6 +1940,22 @@ let RedisQueue = (() => {
|
|
|
1741
1940
|
this.emitError('OnReadUnsafe', 'unsafe reader failed', err);
|
|
1742
1941
|
}
|
|
1743
1942
|
}
|
|
1943
|
+
/**
|
|
1944
|
+
* Ends one lease, dropping the worker key and with it the message.
|
|
1945
|
+
*
|
|
1946
|
+
* @param workerKey - the key holding the message
|
|
1947
|
+
*
|
|
1948
|
+
* @remarks
|
|
1949
|
+
* Idempotent, and never throws: an undeleted worker key is re-queued by the
|
|
1950
|
+
* watcher later, which is one of the causes a handler can be given for a
|
|
1951
|
+
* duplicate. The key itself is never logged, as it carries the queue name
|
|
1952
|
+
* and the lease id.
|
|
1953
|
+
*/
|
|
1954
|
+
releaseLease(workerKey) {
|
|
1955
|
+
this.writer
|
|
1956
|
+
?.del(workerKey)
|
|
1957
|
+
.catch((err) => this.logLine('warn', `OnReadSafe: del error, queue ${this.name}, code ${errorCode(err)}`));
|
|
1958
|
+
}
|
|
1744
1959
|
/**
|
|
1745
1960
|
* Reliable but slow method of message handling by message queue.
|
|
1746
1961
|
*
|
|
@@ -1753,13 +1968,14 @@ let RedisQueue = (() => {
|
|
|
1753
1968
|
const key = this.key;
|
|
1754
1969
|
// blocking timeout in seconds, at most half of the lease ttl, so
|
|
1755
1970
|
// a claimed message always has at least half the ttl remaining
|
|
1756
|
-
const timeout = Math.max(0.1, Number(this.options.safeDeliveryTtl) /
|
|
1971
|
+
const timeout = Math.max(0.1, Math.min(Number(this.options.safeDeliveryTtl) / 2, READ_MAX_BLOCK) /
|
|
1972
|
+
1000);
|
|
1757
1973
|
while (true) {
|
|
1758
1974
|
if (!this.reader || !this.writer || this.destroyed) {
|
|
1759
1975
|
break;
|
|
1760
1976
|
}
|
|
1761
1977
|
const expire = Date.now() + Number(this.options.safeDeliveryTtl);
|
|
1762
|
-
const workerKey = `${key}:worker:${randomUUID()}:${expire}`;
|
|
1978
|
+
const workerKey = `${key}:worker:${randomUUID()}:${OWNER}:${expire}`;
|
|
1763
1979
|
let msg;
|
|
1764
1980
|
try {
|
|
1765
1981
|
msg = await this.reader.blmove(this.key, workerKey, 'RIGHT', 'LEFT', timeout);
|
|
@@ -1796,16 +2012,25 @@ let RedisQueue = (() => {
|
|
|
1796
2012
|
continue;
|
|
1797
2013
|
}
|
|
1798
2014
|
try {
|
|
1799
|
-
this.process([key, msg]);
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
2015
|
+
const pending = this.process([key, msg]);
|
|
2016
|
+
if (pending.length) {
|
|
2017
|
+
// the listeners are still working: the message stays in
|
|
2018
|
+
// its worker key, so a worker that dies now leaves it to
|
|
2019
|
+
// be re-queued instead of taking it down. Settled, not
|
|
2020
|
+
// fulfilled - a handler that threw has had its turn, and
|
|
2021
|
+
// re-delivering on a rejection would retry forever
|
|
2022
|
+
void Promise.allSettled(pending).then(() => this.releaseLease(workerKey));
|
|
2023
|
+
}
|
|
2024
|
+
else {
|
|
2025
|
+
// nothing asynchronous was started, so the listeners are
|
|
2026
|
+
// already done - all a synchronous handler can offer
|
|
2027
|
+
this.releaseLease(workerKey);
|
|
2028
|
+
}
|
|
1806
2029
|
}
|
|
1807
2030
|
catch (err) {
|
|
1808
|
-
// a single message failure must never kill the read loop
|
|
2031
|
+
// a single message failure must never kill the read loop, and
|
|
2032
|
+
// must not strand its lease either
|
|
2033
|
+
this.releaseLease(workerKey);
|
|
1809
2034
|
this.emitError('OnReadSafe', 'safe reader failed', err);
|
|
1810
2035
|
}
|
|
1811
2036
|
}
|
|
@@ -1854,9 +2079,10 @@ let RedisQueue = (() => {
|
|
|
1854
2079
|
/**
|
|
1855
2080
|
* Emits error
|
|
1856
2081
|
*
|
|
1857
|
-
* @param eventName -
|
|
1858
|
-
*
|
|
1859
|
-
* @param
|
|
2082
|
+
* @param eventName - the internal routine that caught it, used as a
|
|
2083
|
+
* diagnostic label such as `OnMessage` or `OnReadSafe`
|
|
2084
|
+
* @param message - human-readable context for the log line
|
|
2085
|
+
* @param err - the caught value, wrapped when it is not an `Error`
|
|
1860
2086
|
*/
|
|
1861
2087
|
emitError(eventName, message, err) {
|
|
1862
2088
|
const error = err instanceof Error ? err : new Error(String(err));
|