@hexok/queue-redis 0.1.0 → 1.0.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.
@@ -1,10 +1,19 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { randomUUID } from 'node:crypto';
2
- import { dispositionOf, Queue, } from '@hexok/queue';
3
+ import { LifecycleError, openRedis, RedisLifecycle, sleep, } from '@hexok/ioredis-lifecycle';
4
+ import { assertMaxDeliveries, deliveryAllowed, dispositionOf, Queue, retryExhausted, } from '@hexok/queue';
3
5
  import { Adapter } from 'hexok';
4
- import { decodeJson, encodeJson, openRedis } from './codec.js';
5
- import { noopSink } from './log-sink.js';
6
+ import { decodeJson, encodeJson } from './codec.js';
6
7
  import { maintainStreams, } from './maintain.js';
7
- import { courtesyPark, parkedError } from './park.js';
8
+ import { courtesyPark, parkedError, } from './park.js';
9
+ import { ackDeleted, releaseConsumer } from './scripts.js';
10
+ const ADAPTER = 'queue';
11
+ const noopSink = {
12
+ debug() { },
13
+ info() { },
14
+ warn() { },
15
+ error() { },
16
+ };
8
17
  function startIdOf(startFrom) {
9
18
  if (startFrom === undefined || startFrom === 'earliest')
10
19
  return '0';
@@ -20,17 +29,87 @@ function isNoGroup(error) {
20
29
  function isBusyGroup(error) {
21
30
  return error instanceof Error && error.message.includes('BUSYGROUP');
22
31
  }
23
- function payloadField(fields) {
32
+ /** Keeps `name` and a string `code`. Drops `command`, `cause`, and any other field that can carry the payload. */
33
+ function scrubbed(error, message) {
34
+ const clean = new Error(message);
35
+ if (!(error instanceof Error))
36
+ return clean;
37
+ clean.name = error.name;
38
+ const code = error.code;
39
+ if (typeof code === 'string')
40
+ return Object.assign(clean, { code });
41
+ return clean;
42
+ }
43
+ function isStreamEntry(entry) {
44
+ return (Array.isArray(entry) &&
45
+ typeof entry[0] === 'string' &&
46
+ Array.isArray(entry[1]));
47
+ }
48
+ function deliveryCountOf(reply, id) {
49
+ if (!Array.isArray(reply))
50
+ return undefined;
51
+ for (const row of reply) {
52
+ if (!Array.isArray(row) || row[0] !== id)
53
+ continue;
54
+ return pendingCount(row[3]);
55
+ }
56
+ return undefined;
57
+ }
58
+ /** A pending-list counter. `0` and unsafe numbers are not a delivery count. */
59
+ function pendingCount(value) {
60
+ const count = typeof value === 'number'
61
+ ? value
62
+ : typeof value === 'string' && value !== ''
63
+ ? Number(value)
64
+ : Number.NaN;
65
+ if (!Number.isSafeInteger(count) || count < 1)
66
+ return undefined;
67
+ return count;
68
+ }
69
+ function exhaustedError(thrown) {
70
+ if (thrown === undefined) {
71
+ return { name: 'Error', message: 'queue: deliveries exhausted' };
72
+ }
73
+ return { ...parkedError(thrown), message: 'queue: deliveries exhausted' };
74
+ }
75
+ function fieldOf(fields, name) {
24
76
  for (let i = 0; i < fields.length - 1; i += 2) {
25
- if (fields[i] === 'payload')
77
+ if (fields[i] === name)
26
78
  return fields[i + 1];
27
79
  }
28
80
  return undefined;
29
81
  }
82
+ async function createGroup(commands, key, group, startId) {
83
+ try {
84
+ await commands.xgroup('CREATE', key, group, startId, 'MKSTREAM');
85
+ }
86
+ catch (error) {
87
+ if (!isBusyGroup(error))
88
+ throw error;
89
+ }
90
+ }
91
+ /** The subscription's read loop and any handlers `XAUTOCLAIM` dispatched. */
92
+ function handlersOf(sub) {
93
+ return Promise.all([sub.done, ...sub.recovering]);
94
+ }
95
+ /** Resolves when `promise` settles or `signal` aborts, whichever is first. It removes its listener either way. */
96
+ function settledOrAborted(promise, signal) {
97
+ if (signal.aborted)
98
+ return Promise.resolve();
99
+ return new Promise((resolve) => {
100
+ const done = () => {
101
+ signal.removeEventListener('abort', done);
102
+ resolve();
103
+ };
104
+ signal.addEventListener('abort', done, { once: true });
105
+ promise.then(done, done);
106
+ });
107
+ }
30
108
  export class RedisQueue extends Adapter(Queue) {
31
109
  #redis;
32
110
  #keyPrefix;
33
111
  #visibilityMs;
112
+ #stopTimeoutMs;
34
113
  #batch;
35
114
  #blockMs;
36
115
  #maxLen;
@@ -39,15 +118,21 @@ export class RedisQueue extends Adapter(Queue) {
39
118
  #decode;
40
119
  #logger;
41
120
  #quarantine;
42
- #commands;
121
+ #lifecycle;
43
122
  #trimTimer;
44
123
  #topics = new Set();
45
124
  #subs = new Map();
125
+ /**
126
+ * The handler call running now. A handler that calls `unsubscribe` on its own subscription, or `stop()`, would otherwise wait for itself until `stopTimeoutMs`.
127
+ * The mark is per call and ends when the handler returns. Work it leaves behind, such as a timer, inherits the context, and must not count as the handler.
128
+ */
129
+ #handling = new AsyncLocalStorage();
46
130
  constructor(config) {
47
131
  super();
48
132
  this.#redis = config.redis;
49
133
  this.#keyPrefix = config.keyPrefix ?? 'hexok:queue:';
50
134
  this.#visibilityMs = config.visibilityMs ?? 30_000;
135
+ this.#stopTimeoutMs = config.stopTimeoutMs ?? 10_000;
51
136
  this.#batch = config.batch ?? 10;
52
137
  this.#blockMs = config.blockMs ?? 1000;
53
138
  this.#maxLen = config.maxLen ?? 10_000;
@@ -56,74 +141,115 @@ export class RedisQueue extends Adapter(Queue) {
56
141
  this.#decode = config.decode ?? decodeJson;
57
142
  this.#logger = config.logger ?? noopSink;
58
143
  this.#quarantine = config.quarantine;
144
+ this.#lifecycle = new RedisLifecycle({
145
+ adapter: ADAPTER,
146
+ stopTimeoutMs: this.#stopTimeoutMs,
147
+ startTimeoutMs: config.startTimeoutMs,
148
+ logger: this.#logger,
149
+ });
59
150
  }
60
- async start() {
61
- if (this.#commands)
62
- return;
63
- this.#commands = openRedis(this.#redis);
64
- this.#trimTimer = setInterval(() => {
65
- void this.#trimAll();
66
- }, 60_000);
151
+ /** `ready` from `start()` until `stop()`, even while Redis is down. Gate traffic on it, not Redis health. */
152
+ get state() {
153
+ return this.#lifecycle.state;
154
+ }
155
+ start() {
156
+ return this.#lifecycle.start(() => ({ commands: openRedis(this.#redis) }), () => {
157
+ this.#trimTimer = setInterval(() => {
158
+ void this.#trimAll();
159
+ }, 60_000);
160
+ });
67
161
  }
68
- async publish(topic, payload) {
69
- const commands = this.#requireCommands();
162
+ async publish(topic, payload, options = {}) {
163
+ // A state error comes before encoding, so it is never parked.
164
+ this.#lifecycle.assertReady('publish');
165
+ const sensitive = options.sensitive === true;
70
166
  let encoded;
71
167
  try {
72
168
  encoded = this.#encode(payload);
73
169
  }
74
170
  catch (error) {
75
- await this.#parkPublish(topic, payload, error);
76
- throw error;
171
+ await this.#parkPublish(topic, payload, error, {
172
+ sensitive,
173
+ generic: 'queue: encode failed',
174
+ });
175
+ throw sensitive ? scrubbed(error, 'queue: encode failed') : error;
77
176
  }
78
177
  const key = this.#key(topic);
178
+ const fields = ['payload', encoded];
179
+ if (sensitive)
180
+ fields.push('sensitive', '1');
79
181
  let id;
80
182
  try {
81
- const written = await commands.xadd(key, 'MAXLEN', '~', this.#maxLen, '*', 'payload', encoded);
183
+ const written = await this.#lifecycle.run('publish', ({ commands }) => commands.xadd(key, 'MAXLEN', '~', this.#maxLen, '*', ...fields));
82
184
  if (typeof written !== 'string') {
83
185
  throw new Error('queue: XADD did not return an id');
84
186
  }
85
187
  id = written;
86
188
  }
87
189
  catch (error) {
88
- await this.#parkPublish(topic, payload, error);
89
- throw error instanceof Error ? error : new Error('queue: XADD failed');
190
+ await this.#parkPublish(topic, payload, error, {
191
+ sensitive,
192
+ generic: 'queue: XADD failed',
193
+ });
194
+ if (!(error instanceof Error))
195
+ throw new Error('queue: XADD failed');
196
+ // ioredis puts the XADD args, payload included, on `error.command`. A lifecycle error holds no payload and keeps its class.
197
+ throw sensitive && !LifecycleError.is(error)
198
+ ? scrubbed(error, error.message)
199
+ : error;
90
200
  }
91
201
  this.#topics.add(topic);
92
202
  try {
93
203
  await this.#trim(topic);
94
204
  }
95
205
  catch (error) {
96
- this.#logger.error(error instanceof Error ? error : new Error('queue: XTRIM failed'), { topic });
206
+ this.#logFailure(error, 'XTRIM', {
207
+ adapter: ADAPTER,
208
+ connection: 'commands',
209
+ topic,
210
+ });
97
211
  }
98
212
  return id;
99
213
  }
100
214
  async subscribe(topic, options) {
101
- const commands = this.#requireCommands();
102
- const mapKey = `${topic}\0${options.consumerGroup}`;
103
- if (this.#subs.has(mapKey)) {
104
- throw new Error(`queue: already subscribed to ${topic} group ${options.consumerGroup}`);
105
- }
215
+ const group = options.consumerGroup;
216
+ const mapKey = `${topic}\0${group}`;
217
+ const already = new Error(`queue: already subscribed to ${topic} group ${group}`);
218
+ if (this.#subs.has(mapKey))
219
+ throw already;
220
+ assertMaxDeliveries(options.maxDeliveries);
106
221
  const key = this.#key(topic);
107
222
  const startId = startIdOf(options.startFrom);
108
- await this.#createGroup(commands, key, options.consumerGroup, startId);
109
- const blocking = openRedis(this.#redis);
223
+ await this.#lifecycle.run('subscribe', ({ commands }) => createGroup(commands, key, group, startId));
224
+ if (this.#subs.has(mapKey))
225
+ throw already;
226
+ // Throws `Stopped` when stop() began during the group create, so no connection opens.
227
+ const blocking = this.#lifecycle.attach({
228
+ operation: 'subscribe',
229
+ connection: 'blocking',
230
+ open: () => openRedis(this.#redis),
231
+ fields: { topic, group },
232
+ });
110
233
  let finish = () => { };
111
234
  const done = new Promise((resolve) => {
112
235
  finish = resolve;
113
236
  });
114
237
  const sub = {
115
238
  topic,
116
- group: options.consumerGroup,
239
+ group,
117
240
  key,
118
241
  consumer: `hexok:${process.pid}:${randomUUID()}`,
119
242
  startId,
243
+ maxDeliveries: options.maxDeliveries,
120
244
  onError: options.onError ?? 'retry',
121
245
  handler: options.handler,
122
- aborted: false,
246
+ abort: new AbortController(),
247
+ ack: (command) => this.#lifecycle.run('subscribe', command),
123
248
  inflight: new Set(),
124
249
  blocking,
125
250
  heartbeat: undefined,
126
251
  recovery: undefined,
252
+ recovering: new Set(),
127
253
  done,
128
254
  finish,
129
255
  };
@@ -135,157 +261,166 @@ export class RedisQueue extends Adapter(Queue) {
135
261
  void this.#heartbeat(sub);
136
262
  }, heartbeatMs);
137
263
  sub.recovery = setInterval(() => {
138
- void this.#recover(sub);
264
+ // A slow run would otherwise overlap the next and claim the same entries twice.
265
+ if (sub.recovering.size > 0)
266
+ return;
267
+ const run = this.#recover(sub).finally(() => {
268
+ sub.recovering.delete(run);
269
+ });
270
+ sub.recovering.add(run);
139
271
  }, recoveryMs);
140
272
  void this.#readLoop(sub);
141
273
  }
274
+ /**
275
+ * Ends one subscription the way `stop()` ends them all, within `stopTimeoutMs`.
276
+ * It waits for the subscription's handlers, then removes its consumer when nothing was in flight.
277
+ */
142
278
  async unsubscribe(topic, options) {
143
279
  const mapKey = `${topic}\0${options.consumerGroup}`;
144
280
  const sub = this.#subs.get(mapKey);
145
281
  if (!sub)
146
282
  return;
147
- const idle = sub.inflight.size === 0;
148
- await this.#closeSub(sub, false);
149
- if (idle && sub.inflight.size === 0) {
150
- await this.#releaseConsumer(sub);
283
+ this.#closeSub(sub);
284
+ // Redis can stop answering mid-call, and ioredis would hold the release until it returns.
285
+ const deadline = new AbortController();
286
+ const timer = setTimeout(() => {
287
+ deadline.abort(new Error(`queue: unsubscribe() stopped waiting for Redis after ${this.#stopTimeoutMs}ms. maintain() removes a consumer left behind.`));
288
+ }, this.#stopTimeoutMs);
289
+ const run = (command) => this.#lifecycle.run('unsubscribe', command, { signal: deadline.signal });
290
+ sub.ack = run;
291
+ try {
292
+ if (!this.#calledFrom(sub)) {
293
+ await settledOrAborted(handlersOf(sub), deadline.signal);
294
+ }
295
+ sub.ack = undefined;
296
+ if (deadline.signal.aborted) {
297
+ this.#logger.warn(`queue: unsubscribe() stopped waiting for handlers after ${this.#stopTimeoutMs}ms. The consumer is left for maintain().`, this.#fields(sub, 'commands'));
298
+ }
299
+ else {
300
+ await this.#releaseConsumer(sub, run);
301
+ }
302
+ }
303
+ finally {
304
+ sub.ack = undefined;
305
+ clearTimeout(timer);
151
306
  }
152
- this.#subs.delete(mapKey);
307
+ // stop() and a new subscribe() can run while this waits. Only this subscription's entry is removed.
308
+ if (this.#subs.get(mapKey) === sub)
309
+ this.#subs.delete(mapKey);
153
310
  }
154
311
  async maintain(options = {}) {
155
- const commands = this.#requireCommands();
312
+ this.#lifecycle.assertReady('maintain');
156
313
  return maintainStreams({
157
- commands,
314
+ run: (command) => this.#lifecycle.run('maintain', ({ commands }) => command(commands)),
158
315
  keyPrefix: this.#keyPrefix,
159
316
  retentionMs: this.#retentionMs,
160
317
  options,
161
318
  logger: this.#logger,
162
319
  });
163
320
  }
164
- async stop() {
165
- const idleSubs = [];
166
- for (const sub of this.#subs.values()) {
167
- sub.aborted = true;
168
- this.#clearSubTimers(sub);
169
- if (sub.inflight.size === 0)
170
- idleSubs.push(sub);
171
- }
172
- if (this.#trimTimer) {
321
+ stop() {
322
+ return this.#lifecycle.stop(async ({ run, signal }) => {
173
323
  clearInterval(this.#trimTimer);
174
324
  this.#trimTimer = undefined;
175
- }
176
- for (const sub of this.#subs.values()) {
177
- sub.blocking.disconnect();
178
- }
179
- await Promise.race([
180
- Promise.all([...this.#subs.values()].map((sub) => sub.done)),
181
- new Promise((resolve) => {
182
- setTimeout(resolve, this.#visibilityMs);
183
- }),
184
- ]);
185
- for (const sub of idleSubs) {
186
- if (sub.inflight.size === 0)
187
- await this.#releaseConsumer(sub);
188
- }
189
- for (const sub of this.#subs.values()) {
190
- sub.inflight.clear();
191
- }
192
- const commands = this.#commands;
193
- this.#commands = undefined;
194
- if (commands) {
195
- await commands.quit().catch((error) => {
196
- this.#logger.error(error instanceof Error ? error : new Error('queue: quit failed'));
197
- });
198
- }
199
- for (const sub of this.#subs.values()) {
200
- await sub.blocking.quit().catch(() => undefined);
201
- }
202
- this.#subs.clear();
325
+ const subs = [...this.#subs.values()];
326
+ this.#subs.clear();
327
+ const stopRun = (command) => run('stop', command);
328
+ for (const sub of subs) {
329
+ this.#closeSub(sub);
330
+ // A handler that finishes during a deploy is acked, so its entry is not delivered again.
331
+ sub.ack = stopRun;
332
+ }
333
+ // Handlers finish before consumers are released. `signal` aborts when stop() stops waiting.
334
+ const others = subs.filter((sub) => !this.#calledFrom(sub));
335
+ await settledOrAborted(Promise.all(others.map(handlersOf)), signal);
336
+ for (const sub of subs)
337
+ sub.ack = undefined;
338
+ if (signal.aborted)
339
+ return;
340
+ await Promise.all(subs.map((sub) => this.#releaseConsumer(sub, stopRun)));
341
+ });
203
342
  }
204
- async #releaseConsumer(sub) {
343
+ /**
344
+ * Removes this subscription's consumer with one script that keeps it when it owns a pending entry.
345
+ * A consumer kept that way is left for `XAUTOCLAIM` or `maintain()`.
346
+ */
347
+ async #releaseConsumer(sub, run) {
205
348
  if (sub.inflight.size > 0)
206
349
  return;
207
- const commands = this.#commands;
208
- if (!commands)
209
- return;
210
350
  try {
211
- await commands.xgroup('DELCONSUMER', sub.key, sub.group, sub.consumer);
351
+ await run(async ({ commands }) => {
352
+ // A client that is not ready holds the script in its offline queue until stop() gives up.
353
+ if (commands.status !== 'ready')
354
+ return;
355
+ await releaseConsumer(commands, sub.key, sub.group, sub.consumer);
356
+ });
212
357
  }
213
358
  catch (error) {
214
- this.#logger.error(error instanceof Error ? error : new Error('queue: DELCONSUMER failed'), { topic: sub.topic, group: sub.group });
359
+ this.#logFailure(error, 'consumer release', this.#fields(sub, 'commands'));
215
360
  }
216
361
  }
217
- async #closeSub(sub, wait) {
218
- sub.aborted = true;
219
- this.#clearSubTimers(sub);
220
- sub.blocking.disconnect();
221
- if (wait) {
222
- await Promise.race([
223
- sub.done,
224
- new Promise((resolve) => {
225
- setTimeout(resolve, this.#visibilityMs);
226
- }),
227
- ]);
228
- }
229
- await sub.blocking.quit().catch(() => undefined);
230
- }
231
- #clearSubTimers(sub) {
362
+ /** Aborts the read, clears the timers, and disconnects the blocking client. A `QUIT` after that could wait in the offline queue. */
363
+ #closeSub(sub) {
364
+ sub.abort.abort(new Error('queue: the subscription was closed'));
232
365
  if (sub.heartbeat)
233
366
  clearInterval(sub.heartbeat);
234
367
  if (sub.recovery)
235
368
  clearInterval(sub.recovery);
236
369
  sub.heartbeat = undefined;
237
370
  sub.recovery = undefined;
371
+ this.#lifecycle.detach(sub.blocking);
238
372
  }
239
373
  async #readLoop(sub) {
374
+ const { signal } = sub.abort;
240
375
  let failures = 0;
241
376
  try {
242
- while (!sub.aborted) {
377
+ while (!signal.aborted) {
243
378
  let rows;
244
379
  try {
245
- rows = (await sub.blocking.xreadgroup('GROUP', sub.group, sub.consumer, 'COUNT', this.#batch, 'BLOCK', this.#blockMs, 'STREAMS', sub.key, '>'));
380
+ // `run` adds the abort listener for this one read and removes it when the read settles,
381
+ // so a settled read and its payload are not retained until the subscription aborts.
382
+ // The signal also ends a read on a reconnecting client, which never settles, even after disconnect.
383
+ rows = await this.#lifecycle.run('subscribe', () => sub.blocking.xreadgroup('GROUP', sub.group, sub.consumer, 'COUNT', this.#batch, 'BLOCK', this.#blockMs, 'STREAMS', sub.key, '>'), { signal });
246
384
  failures = 0;
247
385
  }
248
386
  catch (error) {
249
- if (sub.aborted)
387
+ if (signal.aborted || LifecycleError.is(error))
250
388
  break;
251
389
  if (isNoGroup(error)) {
252
- const commands = this.#commands;
253
- if (commands) {
254
- await this.#createGroup(commands, sub.key, sub.group, sub.startId);
255
- }
390
+ if (await this.#restoreGroup(sub))
391
+ continue;
392
+ failures += 1;
393
+ await sleep(backoffMs(failures), signal);
256
394
  continue;
257
395
  }
258
396
  failures += 1;
259
- this.#logger.error(error instanceof Error
260
- ? error
261
- : new Error('queue: XREADGROUP failed'), { topic: sub.topic });
262
- await this.#backoff(failures);
397
+ this.#logFailure(error, 'XREADGROUP', this.#fields(sub, 'blocking'));
398
+ await sleep(backoffMs(failures), signal);
263
399
  continue;
264
400
  }
265
401
  if (!rows)
266
402
  continue;
267
- for (const [, entries] of rows) {
268
- for (const [id, fields] of entries) {
269
- if (sub.aborted)
270
- break;
271
- await this.#dispatch(sub, id, fields);
272
- }
273
- }
403
+ for (const [, entries] of rows)
404
+ await this.#handleBatch(sub, entries);
274
405
  }
275
406
  }
276
407
  finally {
277
408
  sub.finish();
278
409
  }
279
410
  }
280
- async #parkPublish(topic, payload, error) {
411
+ /** A sensitive publish parks `{ sensitive: true }` and a `generic` error that keeps only `name` and `code`. */
412
+ async #parkPublish(topic, payload, error, options) {
281
413
  await courtesyPark(this.#quarantine, {
282
414
  source: 'queue',
283
415
  operation: 'publish',
284
416
  subject: topic,
285
- payload,
286
- error: parkedError(error),
417
+ payload: options.sensitive ? { sensitive: true } : payload,
418
+ error: parkedError(options.sensitive ? scrubbed(error, options.generic) : error),
287
419
  occurredAt: new Date(),
288
- context: { adapter: 'redis' },
420
+ // Redis may have stored it, so a replay from quarantine can duplicate it.
421
+ context: LifecycleError.is(error) && error.code === 'StoppedBeforeReply'
422
+ ? { adapter: 'redis', outcome: 'unknown' }
423
+ : { adapter: 'redis' },
289
424
  }, this.#logger);
290
425
  }
291
426
  async #parkDeliver(sub, id, record) {
@@ -297,16 +432,70 @@ export class RedisQueue extends Adapter(Queue) {
297
432
  error: record.error,
298
433
  occurredAt: new Date(),
299
434
  context: { adapter: 'redis' },
435
+ ...(record.attempts === undefined ? {} : { attempts: record.attempts }),
300
436
  }, this.#logger);
301
437
  }
302
- async #dispatch(sub, id, fields) {
303
- const raw = payloadField(fields);
438
+ /**
439
+ * Every entry of a batch joins the heartbeat when the batch arrives, not when its turn comes.
440
+ * Otherwise an entry waiting behind slow handlers goes idle, and `XAUTOCLAIM`, even this subscription's own, delivers it again.
441
+ */
442
+ async #handleBatch(sub, entries) {
443
+ for (const [id] of entries)
444
+ sub.inflight.add(id);
445
+ const counts = sub.abort.signal.aborted
446
+ ? new Map()
447
+ : await this.#deliveryCounts(sub, entries.map(([id]) => id));
448
+ for (const [id, fields] of entries) {
449
+ if (sub.abort.signal.aborted)
450
+ sub.inflight.delete(id);
451
+ else
452
+ await this.#dispatch(sub, id, fields, counts.get(id));
453
+ }
454
+ }
455
+ /** One `XPENDING` per id. A missing or unusable count is left out of the map. */
456
+ async #deliveryCounts(sub, ids) {
457
+ const counts = new Map();
458
+ if (ids.length === 0)
459
+ return counts;
460
+ let replies;
461
+ try {
462
+ replies = await this.#lifecycle.run('subscribe', ({ commands }) => {
463
+ const pipe = commands.pipeline();
464
+ for (const id of ids)
465
+ pipe.xpending(sub.key, sub.group, id, id, 1);
466
+ return pipe.exec();
467
+ });
468
+ }
469
+ catch (error) {
470
+ this.#logFailure(error, 'XPENDING', this.#fields(sub, 'commands'));
471
+ return counts;
472
+ }
473
+ if (!Array.isArray(replies))
474
+ return counts;
475
+ for (let i = 0; i < ids.length; i += 1) {
476
+ const id = ids[i];
477
+ if (id === undefined)
478
+ continue;
479
+ const item = replies[i];
480
+ if (!Array.isArray(item))
481
+ continue;
482
+ const [failed, reply] = item;
483
+ if (failed)
484
+ continue;
485
+ const count = deliveryCountOf(reply, id);
486
+ if (count !== undefined)
487
+ counts.set(id, count);
488
+ }
489
+ return counts;
490
+ }
491
+ async #dispatch(sub, id, fields, deliveries) {
492
+ const raw = fieldOf(fields, 'payload');
304
493
  if (raw === undefined) {
305
494
  await this.#parkDeliver(sub, id, {
306
495
  payload: { reason: 'missing-payload' },
307
496
  error: { name: 'Error', message: 'queue: missing payload' },
308
497
  });
309
- await this.#settle(sub, id, 'drop', false);
498
+ await this.#settle(sub, id, 'drop');
310
499
  return;
311
500
  }
312
501
  let payload;
@@ -314,114 +503,145 @@ export class RedisQueue extends Adapter(Queue) {
314
503
  payload = this.#decode(raw);
315
504
  }
316
505
  catch (error) {
317
- this.#logger.error(error instanceof Error ? error : new Error('queue: decode failed'), { topic: sub.topic, id });
506
+ // A decode error can quote the raw payload. A sensitive entry gets a generic one.
507
+ const sensitive = fieldOf(fields, 'sensitive') === '1';
508
+ const generic = new Error('queue: decode failed');
509
+ this.#logger.error(!sensitive && error instanceof Error ? error : generic, { adapter: ADAPTER, topic: sub.topic, group: sub.group, id });
318
510
  await this.#parkDeliver(sub, id, {
319
- payload: { reason: 'decode-failed', raw },
320
- error: parkedError(error),
511
+ payload: sensitive
512
+ ? { reason: 'decode-failed', sensitive: true }
513
+ : { reason: 'decode-failed', raw },
514
+ error: parkedError(sensitive ? generic : error),
321
515
  });
322
- await this.#settle(sub, id, 'drop', false);
516
+ await this.#settle(sub, id, 'drop');
517
+ return;
518
+ }
519
+ if (deliveries === undefined) {
520
+ this.#logger.error(new Error('queue: delivery count missing'), {
521
+ adapter: ADAPTER,
522
+ topic: sub.topic,
523
+ group: sub.group,
524
+ id,
525
+ });
526
+ sub.inflight.delete(id);
527
+ return;
528
+ }
529
+ if (!deliveryAllowed(deliveries, sub.maxDeliveries)) {
530
+ await this.#giveUp(sub, id, deliveries, fields, payload);
323
531
  return;
324
532
  }
325
- sub.inflight.add(id);
326
533
  let thrown = false;
534
+ let thrownError;
327
535
  let returned;
328
536
  try {
329
- returned = await sub.handler({ id, topic: sub.topic, payload });
537
+ const call = { sub, active: true };
538
+ try {
539
+ returned = await this.#handling.run(call, () => sub.handler({ id, topic: sub.topic, payload, deliveries }));
540
+ }
541
+ finally {
542
+ call.active = false;
543
+ }
330
544
  }
331
545
  catch (error) {
332
546
  thrown = true;
547
+ thrownError = error;
333
548
  returned = undefined;
334
- this.#logger.error(error instanceof Error ? error : new Error('queue: handler failed'), { topic: sub.topic, id });
549
+ this.#logger.error(error instanceof Error ? error : new Error('queue: handler failed'), { adapter: ADAPTER, topic: sub.topic, group: sub.group, id });
335
550
  }
336
551
  const disposition = dispositionOf(returned, thrown, sub.onError);
337
- await this.#settle(sub, id, disposition, true);
338
- }
339
- async #settle(sub, id, disposition, tracked) {
340
- if (sub.aborted) {
341
- if (tracked)
342
- sub.inflight.delete(id);
343
- return;
344
- }
345
- if (disposition === 'retry') {
346
- if (tracked)
347
- sub.inflight.delete(id);
552
+ if (disposition === 'retry' &&
553
+ retryExhausted(deliveries, sub.maxDeliveries)) {
554
+ await this.#giveUp(sub, id, deliveries, fields, payload, thrownError);
348
555
  return;
349
556
  }
350
- const commands = this.#commands;
351
- if (!commands || sub.aborted) {
352
- if (tracked)
353
- sub.inflight.delete(id);
557
+ await this.#settle(sub, id, disposition);
558
+ }
559
+ /** Logs, parks when a sink is set, then acknowledges. A failed park still acknowledges. */
560
+ async #giveUp(sub, id, deliveries, fields, payload, thrown) {
561
+ this.#logger.error(new Error('queue: deliveries exhausted'), {
562
+ adapter: ADAPTER,
563
+ topic: sub.topic,
564
+ group: sub.group,
565
+ id,
566
+ deliveries,
567
+ });
568
+ const sensitive = fieldOf(fields, 'sensitive') === '1';
569
+ await this.#parkDeliver(sub, id, {
570
+ payload: sensitive
571
+ ? { reason: 'deliveries-exhausted', sensitive: true }
572
+ : { reason: 'deliveries-exhausted', payload },
573
+ error: exhaustedError(thrown),
574
+ attempts: deliveries,
575
+ });
576
+ await this.#settle(sub, id, 'ack');
577
+ }
578
+ /** Once `unsubscribe` or `stop()` stops waiting, a handler that returns does not `XACK`. Its entry stays pending for another consumer. */
579
+ async #settle(sub, id, disposition) {
580
+ const ack = sub.ack;
581
+ if (ack === undefined || disposition === 'retry') {
582
+ sub.inflight.delete(id);
354
583
  return;
355
584
  }
356
585
  try {
357
- await commands.xack(sub.key, sub.group, id);
586
+ await ack(({ commands }) => commands.xack(sub.key, sub.group, id));
358
587
  }
359
588
  catch (error) {
360
- if (!sub.aborted) {
361
- this.#logger.error(error instanceof Error ? error : new Error('queue: XACK failed'), { topic: sub.topic, id });
362
- }
589
+ this.#logFailure(error, 'XACK', {
590
+ ...this.#fields(sub, 'commands'),
591
+ id,
592
+ });
363
593
  }
364
- if (tracked)
365
- sub.inflight.delete(id);
594
+ sub.inflight.delete(id);
366
595
  }
367
596
  async #heartbeat(sub) {
368
- if (sub.aborted)
597
+ if (sub.abort.signal.aborted)
369
598
  return;
370
599
  const ids = [...sub.inflight];
371
600
  if (ids.length === 0)
372
601
  return;
373
- const commands = this.#commands;
374
- if (!commands || sub.aborted)
375
- return;
376
602
  try {
377
- await commands.xclaim(sub.key, sub.group, sub.consumer, 0, ...ids, 'JUSTID');
603
+ await this.#lifecycle.run('subscribe', ({ commands }) => commands.xclaim(sub.key, sub.group, sub.consumer, 0, ...ids, 'JUSTID'));
378
604
  }
379
605
  catch (error) {
380
- this.#logger.error(error instanceof Error ? error : new Error('queue: XCLAIM failed'), { topic: sub.topic });
606
+ this.#logFailure(error, 'XCLAIM', this.#fields(sub, 'commands'));
381
607
  }
382
608
  }
383
609
  async #recover(sub) {
384
- if (sub.aborted)
385
- return;
386
- const commands = this.#commands;
387
- if (!commands)
610
+ if (sub.abort.signal.aborted)
388
611
  return;
389
612
  try {
390
- const claimed = (await commands.xautoclaim(sub.key, sub.group, sub.consumer, this.#visibilityMs, '0-0', 'COUNT', this.#batch));
391
- const entries = claimed[1] ?? [];
392
- for (const [id, fields] of entries) {
393
- if (sub.aborted)
394
- return;
395
- if (sub.inflight.has(id))
396
- continue;
397
- await this.#dispatch(sub, id, fields);
613
+ const reply = await this.#lifecycle.run('subscribe', ({ commands }) => commands.xautoclaim(sub.key, sub.group, sub.consumer, this.#visibilityMs, '0-0', 'COUNT', this.#batch));
614
+ // Redis 7 lists deleted ids as a third element and drops them itself. Redis 6.2 returns each as `nil` and keeps it pending.
615
+ const claimed = Array.isArray(reply[1]) ? reply[1] : [];
616
+ const entries = claimed.filter(isStreamEntry);
617
+ if (entries.length < claimed.length) {
618
+ await this.#lifecycle.run('subscribe', ({ commands }) => ackDeleted(commands, sub.key, sub.group, sub.consumer));
398
619
  }
620
+ await this.#handleBatch(sub, entries.filter(([id]) => !sub.inflight.has(id)));
399
621
  }
400
622
  catch (error) {
401
- if (sub.aborted)
402
- return;
403
- if (isNoGroup(error)) {
404
- await this.#createGroup(commands, sub.key, sub.group, sub.startId);
623
+ if (isNoGroup(error) && !sub.abort.signal.aborted) {
624
+ await this.#restoreGroup(sub);
405
625
  return;
406
626
  }
407
- this.#logger.error(error instanceof Error ? error : new Error('queue: XAUTOCLAIM failed'), { topic: sub.topic });
627
+ this.#logFailure(error, 'XAUTOCLAIM', this.#fields(sub, 'commands'));
408
628
  }
409
629
  }
410
- async #createGroup(commands, key, group, startId) {
630
+ /** Recreates a group deleted under a running subscription. Logs a failure and returns false, unless the queue is stopping. */
631
+ async #restoreGroup(sub) {
411
632
  try {
412
- await commands.xgroup('CREATE', key, group, startId, 'MKSTREAM');
633
+ await this.#lifecycle.run('subscribe', ({ commands }) => createGroup(commands, sub.key, sub.group, sub.startId));
634
+ return true;
413
635
  }
414
636
  catch (error) {
415
- if (!isBusyGroup(error))
416
- throw error;
637
+ this.#logFailure(error, 'XGROUP CREATE', this.#fields(sub, 'commands'));
638
+ // After stop(), the read loop sees the abort and ends.
639
+ return LifecycleError.is(error);
417
640
  }
418
641
  }
419
642
  async #trim(topic) {
420
- const commands = this.#commands;
421
- if (!commands)
422
- return;
423
643
  const minId = `${Date.now() - this.#retentionMs}-0`;
424
- await commands.xtrim(this.#key(topic), 'MINID', '~', minId);
644
+ await this.#lifecycle.run('publish', ({ commands }) => commands.xtrim(this.#key(topic), 'MINID', '~', minId));
425
645
  }
426
646
  async #trimAll() {
427
647
  for (const topic of this.#topics) {
@@ -429,24 +649,41 @@ export class RedisQueue extends Adapter(Queue) {
429
649
  await this.#trim(topic);
430
650
  }
431
651
  catch (error) {
432
- this.#logger.error(error instanceof Error ? error : new Error('queue: age trim failed'), { topic });
652
+ this.#logFailure(error, 'XTRIM', {
653
+ adapter: ADAPTER,
654
+ connection: 'commands',
655
+ topic,
656
+ });
433
657
  }
434
658
  }
435
659
  }
436
- async #backoff(failures) {
437
- const ms = Math.min(1000 * failures, 5000);
438
- await new Promise((resolve) => {
439
- setTimeout(resolve, ms);
440
- });
660
+ /**
661
+ * Logs a failed background command. Redis may have run one that `stop()` cut short, so `StoppedBeforeReply` goes to `warn`.
662
+ * `NotStarted`, `Starting`, and `Stopped` mean the queue was not running, which is not a failure.
663
+ */
664
+ #logFailure(error, command, fields) {
665
+ if (LifecycleError.is(error)) {
666
+ if (error.code === 'StoppedBeforeReply') {
667
+ this.#logger.warn(`queue: stop() stopped waiting before Redis replied to the ${command}. Redis may or may not have run it.`, { ...fields, code: error.code });
668
+ }
669
+ return;
670
+ }
671
+ this.#logger.error(error instanceof Error ? error : new Error(`queue: ${command} failed`), fields);
672
+ }
673
+ #fields(sub, connection) {
674
+ return { adapter: ADAPTER, connection, topic: sub.topic, group: sub.group };
675
+ }
676
+ /** Whether a handler of `sub` is the caller and has not yet returned. */
677
+ #calledFrom(sub) {
678
+ const call = this.#handling.getStore();
679
+ return call?.active === true && call.sub === sub;
441
680
  }
442
681
  #key(topic) {
443
682
  return `${this.#keyPrefix}${topic}`;
444
683
  }
445
- #requireCommands() {
446
- if (!this.#commands) {
447
- throw new Error('queue: start() was not called');
448
- }
449
- return this.#commands;
450
- }
684
+ }
685
+ /** Waits longer after each failed read, up to 5 seconds. */
686
+ function backoffMs(failures) {
687
+ return Math.min(1000 * failures, 5000);
451
688
  }
452
689
  //# sourceMappingURL=redis-queue.js.map