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