@burdenoff/be-sdk 2026.1027.1 → 2026.1027.2

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.
Files changed (34) hide show
  1. package/dist/EventQueueFactory-CWHCJP34.js +8 -0
  2. package/dist/{EventQueueFactory-JG7S6HOL.js.map → EventQueueFactory-CWHCJP34.js.map} +1 -1
  3. package/dist/{chunk-JV7XNJP4.js → chunk-5M77HKFT.js} +21 -9
  4. package/dist/chunk-5M77HKFT.js.map +1 -0
  5. package/dist/{chunk-V3N6HDFE.js → chunk-6XZ4ELHR.js} +4 -4
  6. package/dist/{chunk-V3N6HDFE.js.map → chunk-6XZ4ELHR.js.map} +1 -1
  7. package/dist/{chunk-LKCBI6B2.js → chunk-ENEDTQET.js} +2 -2
  8. package/dist/{chunk-LKCBI6B2.js.map → chunk-ENEDTQET.js.map} +1 -1
  9. package/dist/{chunk-PPFJTSHA.js → chunk-JTG6GZTF.js} +3 -3
  10. package/dist/{chunk-PPFJTSHA.js.map → chunk-JTG6GZTF.js.map} +1 -1
  11. package/dist/{chunk-IZZ45AGA.js → chunk-K52ICDCP.js} +3 -3
  12. package/dist/{chunk-IZZ45AGA.js.map → chunk-K52ICDCP.js.map} +1 -1
  13. package/dist/{chunk-KMNSVLDS.js → chunk-NGAGKLAM.js} +3 -3
  14. package/dist/{chunk-KMNSVLDS.js.map → chunk-NGAGKLAM.js.map} +1 -1
  15. package/dist/{chunk-DNULGVN3.js → chunk-SIAOIYHW.js} +472 -88
  16. package/dist/chunk-SIAOIYHW.js.map +1 -0
  17. package/dist/{chunk-HEAQSZBX.js → chunk-TX2GDIWP.js} +41 -28
  18. package/dist/chunk-TX2GDIWP.js.map +1 -0
  19. package/dist/{chunk-Y2ZUUZNU.js → chunk-VSP2QCEW.js} +4 -4
  20. package/dist/{chunk-Y2ZUUZNU.js.map → chunk-VSP2QCEW.js.map} +1 -1
  21. package/dist/event-queue/index.d.ts +1 -1
  22. package/dist/event-queue/index.js +4 -4
  23. package/dist/graph/index.js +6 -6
  24. package/dist/graphql/index.js +2 -2
  25. package/dist/{index-BVXRewdr.d.ts → index-CqNXOs72.d.ts} +29 -0
  26. package/dist/index.d.ts +2 -2
  27. package/dist/index.js +12 -12
  28. package/dist/init/index.js +1 -1
  29. package/dist/prisma/index.js +5 -5
  30. package/package.json +1 -1
  31. package/dist/EventQueueFactory-JG7S6HOL.js +0 -8
  32. package/dist/chunk-DNULGVN3.js.map +0 -1
  33. package/dist/chunk-HEAQSZBX.js.map +0 -1
  34. package/dist/chunk-JV7XNJP4.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { resolveEventStreamsUrl } from './chunk-KS2HQCJR.js';
2
- import { RedisStreamsConnection, isWildcard, streamKey, boundaryOf, dlqKey, registryKey, delayLockKey, delayQueueKey, dedupKey, replyKey, matchSubject } from './chunk-LKCBI6B2.js';
2
+ import { RedisStreamsConnection, isWildcard, streamKey, boundaryOf, dlqKey, registryKey, delayLockKey, delayQueueKey, dedupKey, replyKey, matchSubject } from './chunk-ENEDTQET.js';
3
3
  import { registerDisposable, unregisterDisposable } from './chunk-KO2ZXZ7W.js';
4
4
  import { logger } from './chunk-RU266375.js';
5
5
  import { __name } from './chunk-XE4OXN2W.js';
@@ -70,6 +70,11 @@ __name(extractTraceContext, "extractTraceContext");
70
70
  async function runWithConsumerSpan(subject, fields, handler) {
71
71
  const api = await loadOtelApi();
72
72
  if (!api) return handler();
73
+ let started = false;
74
+ const once = /* @__PURE__ */ __name(() => {
75
+ started = true;
76
+ return handler();
77
+ }, "once");
73
78
  try {
74
79
  const parentCtx = await extractTraceContext(fields);
75
80
  const tracer = api.trace.getTracer("@burdenoff/be-sdk/redis-streams");
@@ -82,14 +87,14 @@ async function runWithConsumerSpan(subject, fields, handler) {
82
87
  }
83
88
  }, parentCtx, async (span) => {
84
89
  try {
85
- const result = await handler();
90
+ const result = await once();
86
91
  span.setStatus({
87
92
  code: 1
88
93
  });
89
94
  span.end();
90
95
  resolve(result);
91
96
  } catch (err) {
92
- span.recordException(err);
97
+ span.recordException(err instanceof Error ? err : new Error(String(err)));
93
98
  span.setStatus({
94
99
  code: 2,
95
100
  message: err instanceof Error ? err.message : String(err)
@@ -99,7 +104,8 @@ async function runWithConsumerSpan(subject, fields, handler) {
99
104
  }
100
105
  });
101
106
  });
102
- } catch {
107
+ } catch (err) {
108
+ if (started) throw err;
103
109
  return handler();
104
110
  }
105
111
  }
@@ -155,6 +161,109 @@ function messageSettlement(transport) {
155
161
  }
156
162
  __name(messageSettlement, "messageSettlement");
157
163
 
164
+ // src/event-queue/implementations/dispatch-limiter.ts
165
+ function resolveConcurrency(value, label = "concurrency") {
166
+ if (value === void 0) return 1;
167
+ if (!Number.isInteger(value) || value < 1) {
168
+ throw new Error(`[event-queue] ${label} must be a positive integer, got ${String(value)}`);
169
+ }
170
+ return value;
171
+ }
172
+ __name(resolveConcurrency, "resolveConcurrency");
173
+ function resolveDrainTimeout(value, fallbackMs) {
174
+ if (value === void 0) return fallbackMs;
175
+ if (!Number.isFinite(value) || value < 0) {
176
+ throw new Error(`[event-queue] drainTimeoutMs must be a non-negative number, got ${String(value)}`);
177
+ }
178
+ return value;
179
+ }
180
+ __name(resolveDrainTimeout, "resolveDrainTimeout");
181
+ var DispatchLimiter = class {
182
+ static {
183
+ __name(this, "DispatchLimiter");
184
+ }
185
+ concurrency;
186
+ active = 0;
187
+ waiters = [];
188
+ running = /* @__PURE__ */ new Set();
189
+ constructor(concurrency) {
190
+ this.concurrency = concurrency;
191
+ resolveConcurrency(concurrency);
192
+ }
193
+ /** Slots not currently held. */
194
+ get freeSlots() {
195
+ return this.concurrency - this.active;
196
+ }
197
+ /** Handlers started through {@link run} that have not settled yet. */
198
+ get inFlight() {
199
+ return this.running.size;
200
+ }
201
+ /** Waits for a slot and takes it. Waiters are served in FIFO order. */
202
+ acquire() {
203
+ if (this.active < this.concurrency) {
204
+ this.active++;
205
+ return Promise.resolve();
206
+ }
207
+ return new Promise((resolve) => {
208
+ this.waiters.push(() => {
209
+ this.active++;
210
+ resolve();
211
+ });
212
+ });
213
+ }
214
+ /** Takes a slot only if one is free right now. */
215
+ tryAcquire() {
216
+ if (this.active >= this.concurrency) return false;
217
+ this.active++;
218
+ return true;
219
+ }
220
+ /** Returns a slot taken with {@link acquire} or {@link tryAcquire} that was not passed to {@link run}. */
221
+ release() {
222
+ if (this.active === 0) return;
223
+ this.active--;
224
+ const next = this.waiters.shift();
225
+ next?.();
226
+ }
227
+ /**
228
+ * Runs `task` on a slot the caller already holds and releases the slot when
229
+ * the task settles. The task must handle its own errors; a rejection is
230
+ * swallowed here so one failure never affects its siblings.
231
+ */
232
+ run(task) {
233
+ const promise = Promise.resolve().then(task).catch(() => void 0).finally(() => {
234
+ this.running.delete(promise);
235
+ this.release();
236
+ });
237
+ this.running.add(promise);
238
+ }
239
+ /**
240
+ * Waits for every running task, at most `timeoutMs`. Resolves `true` when
241
+ * everything settled in time and `false` on timeout (the tasks keep running).
242
+ */
243
+ async drain(timeoutMs) {
244
+ if (this.running.size === 0) return true;
245
+ let timer;
246
+ const timedOut = new Promise((resolve) => {
247
+ timer = setTimeout(() => resolve(false), timeoutMs);
248
+ timer.unref?.();
249
+ });
250
+ const settled = (async () => {
251
+ while (this.running.size > 0) await Promise.allSettled([
252
+ ...this.running
253
+ ]);
254
+ return true;
255
+ })();
256
+ try {
257
+ return await Promise.race([
258
+ settled,
259
+ timedOut
260
+ ]);
261
+ } finally {
262
+ if (timer) clearTimeout(timer);
263
+ }
264
+ }
265
+ };
266
+
158
267
  // src/event-queue/implementations/redis-streams/RedisStreamsEventConsumer.ts
159
268
  var DEFAULT_BLOCK_MS = 5e3;
160
269
  var DEFAULT_BATCH = 10;
@@ -162,7 +271,43 @@ var REGISTRY_REFRESH_MS = 1e4;
162
271
  var DEFAULT_ACK_WAIT_MS = 3e4;
163
272
  var DEFAULT_MAX_DELIVER = 3;
164
273
  var SWEEP_INTERVAL_MS = 15e3;
274
+ var SWEEP_BATCH = 50;
275
+ var HEARTBEAT_MIN_INTERVAL_MS = 250;
276
+ var HEARTBEAT_CHUNK = 100;
165
277
  var DELAYQ_INTERVAL_MS = 1e3;
278
+ function parsePendingRows(reply) {
279
+ if (!Array.isArray(reply)) return [];
280
+ const rows = [];
281
+ for (const row of reply) {
282
+ if (!Array.isArray(row)) continue;
283
+ const id = row[0];
284
+ const deliveries = Number(row[3]);
285
+ if (typeof id !== "string" || !Number.isFinite(deliveries)) continue;
286
+ rows.push({
287
+ id,
288
+ deliveries
289
+ });
290
+ }
291
+ return rows;
292
+ }
293
+ __name(parsePendingRows, "parsePendingRows");
294
+ function parseClaimedEntries(reply) {
295
+ const out = /* @__PURE__ */ new Map();
296
+ if (!Array.isArray(reply)) return out;
297
+ for (const entry of reply) {
298
+ if (!Array.isArray(entry)) continue;
299
+ const id = entry[0];
300
+ const fields = entry[1];
301
+ if (typeof id !== "string" || !Array.isArray(fields)) continue;
302
+ out.set(id, fields.filter((f) => typeof f === "string"));
303
+ }
304
+ return out;
305
+ }
306
+ __name(parseClaimedEntries, "parseClaimedEntries");
307
+ function errorMessage(err) {
308
+ return err instanceof Error ? err.message : String(err);
309
+ }
310
+ __name(errorMessage, "errorMessage");
166
311
  var RedisStreamsSubscription = class RedisStreamsSubscription2 {
167
312
  static {
168
313
  __name(this, "RedisStreamsSubscription");
@@ -221,13 +366,25 @@ var RedisStreamsEventConsumer = class {
221
366
  group;
222
367
  maxDeliver;
223
368
  ackWaitMs;
369
+ /** XREADGROUP COUNT for serial subscriptions (historical name; not a concurrency limit). */
224
370
  maxConcurrent;
371
+ concurrency;
372
+ drainTimeoutMs;
225
373
  consumedCount = 0;
226
374
  failedCount = 0;
227
375
  lastActivity = null;
228
376
  stopped = false;
229
377
  sweepTimer = null;
230
378
  delayqTimer = null;
379
+ heartbeatTimer = null;
380
+ /** stream -> the subscription loop consuming it (used to re-dispatch reclaimed entries). */
381
+ workers = /* @__PURE__ */ new Map();
382
+ /** Every stream loop a subscription started, for drain and cleanup. */
383
+ subWorkers = /* @__PURE__ */ new Map();
384
+ /** stream -> ids read by this process and not yet settled by their handler. */
385
+ held = /* @__PURE__ */ new Map();
386
+ /** Blocking clients per subscription, closed on unsubscribe to abort a pending XREADGROUP BLOCK. */
387
+ blockingClients = /* @__PURE__ */ new Map();
231
388
  settlements = /* @__PURE__ */ new Map();
232
389
  retainedSerializedFieldsBytes = 0;
233
390
  knownStreams = /* @__PURE__ */ new Map();
@@ -246,6 +403,8 @@ var RedisStreamsEventConsumer = class {
246
403
  this.maxDeliver = config.maxDeliver ?? DEFAULT_MAX_DELIVER;
247
404
  this.ackWaitMs = config.ackWait ? Math.max(1e3, Math.round(config.ackWait / 1e6)) : DEFAULT_ACK_WAIT_MS;
248
405
  this.maxConcurrent = config.maxConcurrent ?? 5;
406
+ this.concurrency = resolveConcurrency(config.concurrency);
407
+ this.drainTimeoutMs = resolveDrainTimeout(config.drainTimeoutMs, this.ackWaitMs);
249
408
  this.shutdownName = `redis-streams-consumer:${config.name ?? this.group}`;
250
409
  registerDisposable(this);
251
410
  }
@@ -273,13 +432,29 @@ var RedisStreamsEventConsumer = class {
273
432
  t.unref?.();
274
433
  this.delayqTimer = t;
275
434
  }
435
+ if (!this.heartbeatTimer) {
436
+ const t = setInterval(() => {
437
+ void this.heartbeat().catch(() => void 0);
438
+ }, Math.max(HEARTBEAT_MIN_INTERVAL_MS, Math.floor(this.ackWaitMs / 2)));
439
+ t.unref?.();
440
+ this.heartbeatTimer = t;
441
+ }
276
442
  }
443
+ /**
444
+ * Stops reading, waits for in-flight handlers (bounded by `drainTimeoutMs`)
445
+ * so they can still ack, then closes the connection. The heartbeat keeps
446
+ * running during the drain so live entries are not reclaimed meanwhile.
447
+ */
277
448
  async disconnect() {
278
449
  unregisterDisposable(this);
279
450
  this.stopped = true;
280
451
  if (this.sweepTimer) clearInterval(this.sweepTimer);
281
452
  if (this.delayqTimer) clearInterval(this.delayqTimer);
453
+ this.sweepTimer = null;
454
+ this.delayqTimer = null;
282
455
  await this.unsubscribeAll();
456
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
457
+ this.heartbeatTimer = null;
283
458
  await this.connection.disconnect();
284
459
  }
285
460
  isConnected() {
@@ -332,8 +507,14 @@ var RedisStreamsEventConsumer = class {
332
507
  }
333
508
  async subscribe(opts) {
334
509
  await this.connect();
510
+ const concurrency = resolveConcurrency(opts.options?.concurrency ?? this.concurrency);
511
+ const drainTimeoutMs = resolveDrainTimeout(opts.options?.drainTimeoutMs, this.drainTimeoutMs);
512
+ const limiter = /* @__PURE__ */ __name(() => new DispatchLimiter(concurrency), "limiter");
335
513
  const sub = new RedisStreamsSubscription(opts.subject, async () => {
336
514
  this.subscriptions = this.subscriptions.filter((s) => s !== sub);
515
+ this.abortReads(sub);
516
+ await this.drainSubscription(sub, opts.subject, drainTimeoutMs);
517
+ this.releaseStreams(sub);
337
518
  });
338
519
  this.subscriptions.push(sub);
339
520
  const startId = this.resolveStartId(opts.options?.deliverPolicy);
@@ -353,7 +534,7 @@ var RedisStreamsEventConsumer = class {
353
534
  await evt.ack();
354
535
  }
355
536
  } : handlerFn;
356
- this.spawnLoop(sub, stream, opts.subject, filteredHandler);
537
+ this.spawnLoop(sub, stream, opts.subject, filteredHandler, limiter());
357
538
  return sub;
358
539
  }
359
540
  if (!wildcard) {
@@ -362,7 +543,7 @@ var RedisStreamsEventConsumer = class {
362
543
  });
363
544
  await this.ensureGroup(stream, startId);
364
545
  this.knownStreams.set(stream, opts.subject);
365
- this.spawnLoop(sub, stream, opts.subject, handlerFn);
546
+ this.spawnLoop(sub, stream, opts.subject, handlerFn, limiter());
366
547
  } else {
367
548
  const boundary = boundaryOf(opts.subject);
368
549
  const refresh = /* @__PURE__ */ __name(async () => {
@@ -376,7 +557,7 @@ var RedisStreamsEventConsumer = class {
376
557
  if (this.knownStreams.has(stream)) continue;
377
558
  await this.ensureGroup(stream, startId);
378
559
  this.knownStreams.set(stream, s);
379
- this.spawnLoop(sub, stream, s, handlerFn);
560
+ this.spawnLoop(sub, stream, s, handlerFn, limiter());
380
561
  }
381
562
  }, "refresh");
382
563
  await refresh();
@@ -421,11 +602,9 @@ var RedisStreamsEventConsumer = class {
421
602
  return out;
422
603
  }
423
604
  async unsubscribeAll() {
424
- for (const sub of [
605
+ await Promise.all([
425
606
  ...this.subscriptions
426
- ]) {
427
- await sub.unsubscribe();
428
- }
607
+ ].map((sub) => sub.unsubscribe()));
429
608
  this.subscriptions = [];
430
609
  this.subscriptionLoops.clear();
431
610
  }
@@ -502,68 +681,201 @@ var RedisStreamsEventConsumer = class {
502
681
  }
503
682
  }
504
683
  }
505
- spawnLoop(sub, stream, subject, handler) {
506
- const loop = /* @__PURE__ */ __name(async () => {
507
- const client = await this.connection.makeBlockingClient();
684
+ heldFor(stream) {
685
+ let ids = this.held.get(stream);
686
+ if (!ids) {
687
+ ids = /* @__PURE__ */ new Set();
688
+ this.held.set(stream, ids);
689
+ }
690
+ return ids;
691
+ }
692
+ /** Closes the subscription's blocking clients so a pending XREADGROUP BLOCK returns now. */
693
+ abortReads(sub) {
694
+ for (const client of this.blockingClients.get(sub) ?? []) {
508
695
  try {
509
- while (!this.stopped && sub.isActive()) {
510
- let raw = null;
511
- try {
512
- raw = await client.xreadgroup("GROUP", this.group, this.consumerName, "COUNT", this.maxConcurrent, "BLOCK", DEFAULT_BLOCK_MS, "STREAMS", stream, ">");
513
- } catch (err) {
514
- const msg = err instanceof Error ? err.message : String(err);
515
- if (msg.includes("NOGROUP")) {
516
- await this.ensureGroup(stream, "$");
517
- continue;
518
- }
519
- logger.warn("[RedisStreamsEventConsumer] read error", {
520
- stream,
521
- error: msg
522
- });
523
- await new Promise((res) => setTimeout(res, 1e3));
524
- continue;
525
- }
526
- if (!raw) continue;
527
- for (const [, entries] of raw) {
528
- for (const [id, rawFields] of entries) {
529
- sub.recordReceived();
530
- this.consumedCount++;
531
- this.lastActivity = /* @__PURE__ */ new Date();
532
- const parsed = this.parseEntry(stream, id, rawFields);
533
- const evt = this.toAcknowledgeable(stream, id, parsed);
534
- try {
535
- await runWithConsumerSpan(subject, parsed.fields, () => handler(evt));
536
- sub.recordProcessed();
537
- } catch (err) {
538
- sub.recordFailed();
539
- this.failedCount++;
540
- logger.error("[RedisStreamsEventConsumer] handler error", {
541
- subject,
542
- id,
543
- error: err instanceof Error ? err.message : String(err)
544
- });
545
- try {
546
- await evt.nak();
547
- } catch {
548
- }
549
- }
550
- }
551
- }
552
- }
553
- } finally {
554
- try {
555
- client.disconnect();
556
- } catch {
557
- }
696
+ client.disconnect();
697
+ } catch {
558
698
  }
559
- }, "loop");
560
- void loop().catch((err) => {
699
+ }
700
+ }
701
+ /** Waits for the in-flight handlers of every stream loop of `sub`, at most `timeoutMs` in total. */
702
+ async drainSubscription(sub, subject, timeoutMs) {
703
+ const limiters = (this.subWorkers.get(sub) ?? []).map(({ worker }) => worker.limiter);
704
+ const results = await Promise.all(limiters.map((l) => l.drain(timeoutMs)));
705
+ if (results.every(Boolean)) return;
706
+ logger.warn("[RedisStreamsEventConsumer] drain timed out; unfinished entries stay pending for reclaim", {
707
+ subject,
708
+ inFlight: limiters.reduce((sum, l) => sum + l.inFlight, 0),
709
+ drainTimeoutMs: timeoutMs
710
+ });
711
+ }
712
+ /** Forgets the streams a finished subscription consumed so the sweep and heartbeat stop touching them. */
713
+ releaseStreams(sub) {
714
+ for (const { stream, worker } of this.subWorkers.get(sub) ?? []) {
715
+ if (this.workers.get(stream) !== worker) continue;
716
+ this.workers.delete(stream);
717
+ this.knownStreams.delete(stream);
718
+ this.held.delete(stream);
719
+ }
720
+ this.subWorkers.delete(sub);
721
+ this.blockingClients.delete(sub);
722
+ }
723
+ spawnLoop(sub, stream, subject, handler, limiter) {
724
+ const worker = {
725
+ sub,
726
+ subject,
727
+ handler,
728
+ limiter,
729
+ queued: 0
730
+ };
731
+ this.workers.set(stream, worker);
732
+ const started = this.subWorkers.get(sub) ?? [];
733
+ started.push({
734
+ stream,
735
+ worker
736
+ });
737
+ this.subWorkers.set(sub, started);
738
+ void this.runLoop(stream, worker).catch((err) => {
561
739
  logger.error("[RedisStreamsEventConsumer] loop crashed", {
562
740
  stream,
563
- error: err instanceof Error ? err.message : String(err)
741
+ error: errorMessage(err)
564
742
  });
565
743
  });
566
744
  }
745
+ isRunning(worker) {
746
+ return !this.stopped && worker.sub.isActive();
747
+ }
748
+ async runLoop(stream, worker) {
749
+ const client = await this.connection.makeBlockingClient();
750
+ let clients = this.blockingClients.get(worker.sub);
751
+ if (!clients) {
752
+ clients = /* @__PURE__ */ new Set();
753
+ this.blockingClients.set(worker.sub, clients);
754
+ }
755
+ clients.add(client);
756
+ try {
757
+ while (this.isRunning(worker)) {
758
+ await worker.limiter.acquire();
759
+ if (!this.isRunning(worker)) {
760
+ worker.limiter.release();
761
+ break;
762
+ }
763
+ const entries = await this.readBatch(client, stream, worker);
764
+ if (entries.length === 0) {
765
+ worker.limiter.release();
766
+ continue;
767
+ }
768
+ await this.dispatchBatch(stream, worker, entries);
769
+ }
770
+ } finally {
771
+ clients.delete(client);
772
+ try {
773
+ client.disconnect();
774
+ } catch {
775
+ }
776
+ }
777
+ }
778
+ /**
779
+ * One XREADGROUP. A serial subscription reads `maxConcurrent` (the batch
780
+ * size); a parallel one reads only as many entries as it has slots for.
781
+ * Read errors are logged and yield an empty batch.
782
+ */
783
+ async readBatch(client, stream, worker) {
784
+ const { limiter } = worker;
785
+ const count = limiter.concurrency === 1 ? this.maxConcurrent : 1 + limiter.freeSlots;
786
+ try {
787
+ const raw = await client.xreadgroup("GROUP", this.group, this.consumerName, "COUNT", count, "BLOCK", DEFAULT_BLOCK_MS, "STREAMS", stream, ">");
788
+ return (raw ?? []).flatMap(([, batch]) => batch);
789
+ } catch (err) {
790
+ if (!this.isRunning(worker)) return [];
791
+ const msg = errorMessage(err);
792
+ if (msg.includes("NOGROUP")) {
793
+ await this.ensureGroup(stream, "$");
794
+ return [];
795
+ }
796
+ logger.warn("[RedisStreamsEventConsumer] read error", {
797
+ stream,
798
+ error: msg
799
+ });
800
+ await new Promise((res) => setTimeout(res, 1e3));
801
+ return [];
802
+ }
803
+ }
804
+ /**
805
+ * Starts each entry of a batch on its own slot, in stream order. The caller
806
+ * already holds the slot for the first entry. Every entry is held (and so
807
+ * heartbeated) from the moment it is read until its handler settles.
808
+ */
809
+ async dispatchBatch(stream, worker, entries) {
810
+ const { limiter } = worker;
811
+ const held = this.heldFor(stream);
812
+ for (const [id] of entries) held.add(id);
813
+ for (let index = 0; index < entries.length; index++) {
814
+ if (index > 0) await limiter.acquire();
815
+ if (!this.isRunning(worker)) {
816
+ limiter.release();
817
+ for (const [rest] of entries.slice(index)) held.delete(rest);
818
+ return;
819
+ }
820
+ const [id, rawFields] = entries[index] ?? [
821
+ "",
822
+ []
823
+ ];
824
+ limiter.run(() => this.dispatchEntry(worker.sub, stream, worker.subject, worker.handler, id, rawFields, 1).finally(() => held.delete(id)));
825
+ }
826
+ }
827
+ /** Runs one entry's handler. Never rejects: a throw is logged and the entry nak'd (left pending). */
828
+ async dispatchEntry(sub, stream, subject, handler, id, rawFields, deliveryCount) {
829
+ sub.recordReceived();
830
+ this.consumedCount++;
831
+ this.lastActivity = /* @__PURE__ */ new Date();
832
+ let evt = null;
833
+ let fields = {};
834
+ try {
835
+ const parsed = this.parseEntry(stream, id, rawFields);
836
+ parsed.deliveryCount = deliveryCount;
837
+ fields = parsed.fields;
838
+ evt = this.toAcknowledgeable(stream, id, parsed);
839
+ const event = evt;
840
+ await runWithConsumerSpan(subject, fields, () => handler(event));
841
+ sub.recordProcessed();
842
+ } catch (err) {
843
+ sub.recordFailed();
844
+ this.failedCount++;
845
+ logger.error("[RedisStreamsEventConsumer] handler error", {
846
+ subject,
847
+ id,
848
+ error: errorMessage(err)
849
+ });
850
+ if (evt) {
851
+ try {
852
+ await evt.nak();
853
+ } catch {
854
+ }
855
+ }
856
+ }
857
+ }
858
+ /** Resets the idle time of every held entry without bumping its delivery count. */
859
+ async heartbeat() {
860
+ if (this.held.size === 0) return;
861
+ const client = this.connection.getClient();
862
+ for (const [stream, ids] of this.held) {
863
+ if (ids.size === 0) continue;
864
+ const list = [
865
+ ...ids
866
+ ];
867
+ try {
868
+ for (let i = 0; i < list.length; i += HEARTBEAT_CHUNK) {
869
+ await client.xclaim(stream, this.group, this.consumerName, 0, ...list.slice(i, i + HEARTBEAT_CHUNK), "JUSTID");
870
+ }
871
+ } catch (err) {
872
+ logger.debug("[RedisStreamsEventConsumer] heartbeat error", {
873
+ stream,
874
+ error: errorMessage(err)
875
+ });
876
+ }
877
+ }
878
+ }
567
879
  parseEntry(stream, id, rawFields) {
568
880
  const fields = {};
569
881
  for (let i = 0; i + 1 < rawFields.length; i += 2) {
@@ -659,30 +971,18 @@ var RedisStreamsEventConsumer = class {
659
971
  this.retainedSerializedFieldsBytes += serializedFieldsBytes;
660
972
  return actions;
661
973
  }
974
+ /**
975
+ * Reclaims entries idle longer than ackWait that this process is not
976
+ * handling. Within maxDeliver they are re-dispatched through the stream's
977
+ * bounded dispatcher; past it they are dead-lettered.
978
+ */
662
979
  async sweepPending() {
663
980
  if (this.stopped || this.knownStreams.size === 0) return;
664
- const client = this.connection.getClient();
665
981
  for (const [stream] of this.knownStreams) {
666
982
  try {
667
- const claimed = await client.xautoclaim(stream, this.group, this.consumerName, this.ackWaitMs, "0", "COUNT", 50);
668
- if (!claimed) continue;
669
- const entries = claimed[1] ?? [];
670
- for (const [id, rawFields] of entries) {
671
- const pending = await client.xpending(stream, this.group, "IDLE", 0, "-", "+", 1, this.consumerName);
672
- const deliveryCount = Array.isArray(pending) && pending[0] ? pending[0][3] : 1;
673
- if (deliveryCount > this.maxDeliver) {
674
- const parsed = this.parseEntry(stream, id, rawFields);
675
- parsed.deliveryCount = deliveryCount;
676
- await this.settlement(stream, id, parsed, this.group).term("max-deliver-exceeded");
677
- logger.warn("[RedisStreamsEventConsumer] message moved to DLQ", {
678
- stream,
679
- id,
680
- deliveryCount
681
- });
682
- }
683
- }
983
+ await this.sweepStream(stream);
684
984
  } catch (err) {
685
- const msg = err instanceof Error ? err.message : String(err);
985
+ const msg = errorMessage(err);
686
986
  if (msg.includes("NOGROUP")) continue;
687
987
  logger.debug("[RedisStreamsEventConsumer] sweep iteration error", {
688
988
  stream,
@@ -691,6 +991,80 @@ var RedisStreamsEventConsumer = class {
691
991
  }
692
992
  }
693
993
  }
994
+ async sweepStream(stream) {
995
+ const client = this.connection.getClient();
996
+ const rows = parsePendingRows(await client.xpending(stream, this.group, "IDLE", this.ackWaitMs, "-", "+", SWEEP_BATCH));
997
+ const worker = this.workers.get(stream);
998
+ const live = worker && this.isRunning(worker) ? worker : void 0;
999
+ const picked = this.pickReclaimable(stream, rows, live);
1000
+ if (picked.length === 0) return;
1001
+ const claimed = parseClaimedEntries(await client.xclaim(stream, this.group, this.consumerName, this.ackWaitMs, ...picked.map((r) => r.id)));
1002
+ for (const row of picked) {
1003
+ const rawFields = claimed.get(row.id);
1004
+ if (!rawFields) continue;
1005
+ const deliveryCount = row.deliveries + 1;
1006
+ if (deliveryCount > this.maxDeliver) await this.deadLetter(stream, row.id, rawFields, deliveryCount);
1007
+ else if (live) this.redispatch(stream, live, row.id, rawFields, deliveryCount);
1008
+ }
1009
+ }
1010
+ /**
1011
+ * Chooses which idle entries to claim: never one this process is handling;
1012
+ * every one past maxDeliver (to dead-letter it); and, within maxDeliver, no
1013
+ * more than the live dispatcher can run alongside what it already runs, so
1014
+ * a replica never hoards reclaimed work it cannot start soon.
1015
+ */
1016
+ pickReclaimable(stream, rows, live) {
1017
+ const held = this.held.get(stream);
1018
+ let budget = live ? live.limiter.concurrency - live.limiter.inFlight - live.queued : 0;
1019
+ const picked = [];
1020
+ for (const row of rows) {
1021
+ if (held?.has(row.id)) continue;
1022
+ if (row.deliveries + 1 > this.maxDeliver) {
1023
+ picked.push(row);
1024
+ } else if (budget > 0) {
1025
+ budget--;
1026
+ picked.push(row);
1027
+ }
1028
+ }
1029
+ return picked;
1030
+ }
1031
+ async deadLetter(stream, id, rawFields, deliveryCount) {
1032
+ const parsed = this.parseEntry(stream, id, rawFields);
1033
+ parsed.deliveryCount = deliveryCount;
1034
+ try {
1035
+ await this.settlement(stream, id, parsed, this.group).term("max-deliver-exceeded");
1036
+ logger.warn("[RedisStreamsEventConsumer] message moved to DLQ", {
1037
+ stream,
1038
+ id,
1039
+ deliveryCount
1040
+ });
1041
+ } catch (err) {
1042
+ logger.debug("[RedisStreamsEventConsumer] dead-letter failed; retried on next sweep", {
1043
+ stream,
1044
+ id,
1045
+ error: errorMessage(err)
1046
+ });
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Runs a reclaimed entry on the stream's dispatcher. It is held (and so
1051
+ * heartbeated) while it waits for a slot; if the subscription stops first
1052
+ * it is left pending for another replica.
1053
+ */
1054
+ redispatch(stream, worker, id, rawFields, deliveryCount) {
1055
+ const held = this.heldFor(stream);
1056
+ held.add(id);
1057
+ worker.queued++;
1058
+ void worker.limiter.acquire().then(() => {
1059
+ worker.queued--;
1060
+ if (!this.isRunning(worker)) {
1061
+ worker.limiter.release();
1062
+ held.delete(id);
1063
+ return;
1064
+ }
1065
+ worker.limiter.run(() => this.dispatchEntry(worker.sub, stream, worker.subject, worker.handler, id, rawFields, deliveryCount).finally(() => held.delete(id)));
1066
+ });
1067
+ }
694
1068
  async drainDelayQueues() {
695
1069
  if (this.stopped || this.knownStreams.size === 0) return;
696
1070
  const client = this.connection.getClient();
@@ -927,6 +1301,12 @@ function streamsUrlFromEnv() {
927
1301
  return resolveEventStreamsUrl() ?? DEFAULT_STREAMS_URL;
928
1302
  }
929
1303
  __name(streamsUrlFromEnv, "streamsUrlFromEnv");
1304
+ function optionalIntEnv(name) {
1305
+ const raw = process.env[name];
1306
+ if (raw === void 0 || raw.trim() === "") return void 0;
1307
+ return Number(raw.trim());
1308
+ }
1309
+ __name(optionalIntEnv, "optionalIntEnv");
930
1310
  function resolveQueueType() {
931
1311
  return QueueType.REDIS_STREAMS;
932
1312
  }
@@ -1009,6 +1389,8 @@ var EventQueueFactory = class _EventQueueFactory {
1009
1389
  stream,
1010
1390
  consumer,
1011
1391
  maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
1392
+ concurrency: optionalIntEnv("QUEUE_CONCURRENCY"),
1393
+ drainTimeoutMs: optionalIntEnv("QUEUE_DRAIN_TIMEOUT_MS"),
1012
1394
  maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
1013
1395
  ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
1014
1396
  });
@@ -1043,12 +1425,14 @@ var EventQueueFactory = class _EventQueueFactory {
1043
1425
  stream,
1044
1426
  consumer,
1045
1427
  maxConcurrent: process.env["QUEUE_MAX_CONCURRENT"] ? parseInt(process.env["QUEUE_MAX_CONCURRENT"], 10) : 5,
1428
+ concurrency: optionalIntEnv("QUEUE_CONCURRENCY"),
1429
+ drainTimeoutMs: optionalIntEnv("QUEUE_DRAIN_TIMEOUT_MS"),
1046
1430
  maxDeliver: process.env["QUEUE_MAX_DELIVER"] ? parseInt(process.env["QUEUE_MAX_DELIVER"], 10) : 3,
1047
1431
  ackWait: process.env["QUEUE_ACK_WAIT"] ? parseInt(process.env["QUEUE_ACK_WAIT"], 10) * 1e9 : 3e10
1048
1432
  });
1049
1433
  }
1050
1434
  };
1051
1435
 
1052
- export { EventQueueFactory, QueueType, RedisStreamsEventConsumer, RedisStreamsEventPublisher, resolveQueueType, safeStringify };
1053
- //# sourceMappingURL=chunk-DNULGVN3.js.map
1054
- //# sourceMappingURL=chunk-DNULGVN3.js.map
1436
+ export { DispatchLimiter, EventQueueFactory, QueueType, RedisStreamsEventConsumer, RedisStreamsEventPublisher, resolveConcurrency, resolveDrainTimeout, resolveQueueType, safeStringify };
1437
+ //# sourceMappingURL=chunk-SIAOIYHW.js.map
1438
+ //# sourceMappingURL=chunk-SIAOIYHW.js.map