@hotmeshio/hotmesh 0.29.0 → 0.30.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.
Files changed (49) hide show
  1. package/README.md +43 -0
  2. package/build/index.d.ts +2 -1
  3. package/build/index.js +3 -1
  4. package/build/modules/enums.d.ts +35 -0
  5. package/build/modules/enums.js +41 -1
  6. package/build/modules/errors.d.ts +26 -2
  7. package/build/modules/errors.js +82 -1
  8. package/build/modules/utils.d.ts +8 -0
  9. package/build/modules/utils.js +19 -1
  10. package/build/package.json +1 -1
  11. package/build/services/activities/trigger.js +3 -1
  12. package/build/services/connector/health.d.ts +42 -0
  13. package/build/services/connector/health.js +100 -0
  14. package/build/services/connector/index.js +2 -1
  15. package/build/services/connector/providers/postgres-resilient-client.d.ts +95 -0
  16. package/build/services/connector/providers/postgres-resilient-client.js +446 -0
  17. package/build/services/connector/providers/postgres.d.ts +6 -0
  18. package/build/services/connector/providers/postgres.js +72 -14
  19. package/build/services/durable/client.js +11 -3
  20. package/build/services/durable/handle.js +101 -41
  21. package/build/services/durable/worker.js +12 -4
  22. package/build/services/engine/completion.js +3 -3
  23. package/build/services/engine/signal.js +3 -3
  24. package/build/services/hotmesh/index.js +13 -4
  25. package/build/services/quorum/index.js +13 -13
  26. package/build/services/router/consumption/index.d.ts +20 -0
  27. package/build/services/router/consumption/index.js +177 -7
  28. package/build/services/store/providers/postgres/escalation-accumulate.js +5 -1
  29. package/build/services/store/providers/postgres/kvtransaction.js +8 -1
  30. package/build/services/store/providers/postgres/postgres.js +2 -2
  31. package/build/services/stream/index.d.ts +1 -0
  32. package/build/services/stream/providers/postgres/messages.d.ts +7 -0
  33. package/build/services/stream/providers/postgres/messages.js +27 -1
  34. package/build/services/stream/providers/postgres/notifications.d.ts +13 -0
  35. package/build/services/stream/providers/postgres/notifications.js +89 -2
  36. package/build/services/stream/providers/postgres/postgres.d.ts +7 -0
  37. package/build/services/stream/providers/postgres/postgres.js +22 -3
  38. package/build/services/stream/registry.d.ts +6 -0
  39. package/build/services/stream/registry.js +11 -2
  40. package/build/services/sub/providers/postgres/postgres.d.ts +6 -0
  41. package/build/services/sub/providers/postgres/postgres.js +62 -2
  42. package/build/services/task/index.js +1 -1
  43. package/build/services/worker/credentials.js +5 -0
  44. package/build/services/worker/index.js +5 -5
  45. package/build/types/index.d.ts +2 -2
  46. package/build/types/postgres.d.ts +20 -0
  47. package/build/types/provider.d.ts +28 -0
  48. package/index.ts +2 -0
  49. package/package.json +1 -1
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ConsumptionManager = void 0;
4
4
  const utils_1 = require("../../../modules/utils");
5
5
  const errors_1 = require("../../../modules/errors");
6
+ const enums_1 = require("../../../modules/enums");
7
+ const health_1 = require("../../connector/health");
6
8
  const telemetry_1 = require("../telemetry");
7
9
  const config_1 = require("../config");
8
10
  const stream_1 = require("../../../types/stream");
@@ -19,6 +21,11 @@ class ConsumptionManager {
19
21
  set hasReachedMaxBackoff(v) { this.router.hasReachedMaxBackoff = v; }
20
22
  constructor(stream, logger, throttleManager, errorHandler, lifecycleManager, reclaimDelay, reclaimCount, appId, role, router, retry, duressManager) {
21
23
  this.messagesSinceLastEval = 0;
24
+ //streams with a pending redelivery wake (one schedule per stream)
25
+ this.redeliveryWakes = new Set();
26
+ //messages deferred during an outage, released when a connection returns
27
+ this.deferredReservations = new Map();
28
+ this.releaseArmed = false;
22
29
  // Adaptive consumption pressure — scales reservation timeout AND batch
23
30
  // size based on stream depth. Under load: timeout grows (prevents
24
31
  // duplicate re-reservation) and batch size shrinks (reduces in-memory
@@ -419,6 +426,19 @@ class ConsumptionManager {
419
426
  }
420
427
  catch (error) {
421
428
  if (this.lifecycleManager.getShouldConsume() &&
429
+ error instanceof errors_1.HotMeshConnectionError) {
430
+ //the connection is reconnecting: resume within one reconnect ceiling
431
+ this.logger.warn(`router-stream-connection-unavailable`, {
432
+ stream,
433
+ group,
434
+ consumer,
435
+ error: error.message,
436
+ });
437
+ this.errorCount++;
438
+ const timeout = Math.min(1000 * 2 ** Math.min(this.errorCount, 10), Math.max(enums_1.HMSH_PG_RECONNECT_MAX_MS, 1000));
439
+ setTimeout(consume.bind(this), timeout);
440
+ }
441
+ else if (this.lifecycleManager.getShouldConsume() &&
422
442
  process.env.NODE_ENV !== 'test') {
423
443
  this.logger.error(`router-stream-error`, {
424
444
  error,
@@ -434,6 +454,97 @@ class ConsumptionManager {
434
454
  };
435
455
  consume.call(this);
436
456
  }
457
+ /**
458
+ * Record a message this consumer deferred because the connection was
459
+ * unavailable. The reservation is released as soon as a connection is
460
+ * restored, so the message is redelivered at once; the timed wake below
461
+ * remains the fallback when a release is not possible.
462
+ */
463
+ deferForRedelivery(stream, id, consumer) {
464
+ this.scheduleRedeliveryWake(stream);
465
+ if (!consumer || typeof this.stream.releaseReservations !== 'function') {
466
+ return;
467
+ }
468
+ const key = `${stream}|${consumer}`;
469
+ let entry = this.deferredReservations.get(key);
470
+ if (!entry) {
471
+ entry = { stream, consumer, ids: new Set() };
472
+ this.deferredReservations.set(key, entry);
473
+ }
474
+ entry.ids.add(id);
475
+ this.armDeferredRelease();
476
+ }
477
+ armDeferredRelease() {
478
+ if (this.releaseArmed) {
479
+ return;
480
+ }
481
+ this.releaseArmed = true;
482
+ health_1.ConnectionHealth.once('restored', () => {
483
+ this.releaseArmed = false;
484
+ return this.releaseDeferred();
485
+ });
486
+ }
487
+ async releaseDeferred() {
488
+ const batches = Array.from(this.deferredReservations.values());
489
+ this.deferredReservations.clear();
490
+ for (const batch of batches) {
491
+ const ids = Array.from(batch.ids);
492
+ try {
493
+ const released = await this.stream.releaseReservations(batch.stream, ids, batch.consumer);
494
+ this.logger.info('stream-deferred-released', {
495
+ stream: batch.stream,
496
+ consumer: batch.consumer,
497
+ requested: ids.length,
498
+ released,
499
+ });
500
+ }
501
+ catch (error) {
502
+ //the stream's own connection is not back yet: keep the batch for
503
+ //the next restore (the timed wake still covers it)
504
+ const key = `${batch.stream}|${batch.consumer}`;
505
+ const pending = this.deferredReservations.get(key);
506
+ if (pending) {
507
+ ids.forEach((id) => pending.ids.add(id));
508
+ }
509
+ else {
510
+ this.deferredReservations.set(key, batch);
511
+ }
512
+ this.armDeferredRelease();
513
+ this.logger.warn('stream-deferred-release-error', {
514
+ stream: batch.stream,
515
+ consumer: batch.consumer,
516
+ error: error?.message,
517
+ });
518
+ }
519
+ }
520
+ }
521
+ /**
522
+ * A message left unacked because the connection was unavailable is
523
+ * redelivered once its reservation lapses, but only when a consumer
524
+ * next fetches. Wake the stream's consumers just after the lapse (and
525
+ * twice more, in case the database is still away) instead of waiting
526
+ * for the fallback poller. One schedule per stream at a time.
527
+ */
528
+ scheduleRedeliveryWake(stream) {
529
+ const streamService = this.stream;
530
+ if (typeof streamService.scheduleStreamNotify !== 'function' ||
531
+ this.redeliveryWakes.has(stream)) {
532
+ return;
533
+ }
534
+ this.redeliveryWakes.add(stream);
535
+ //a message becomes claimable once the longest reservation window lapses
536
+ const windowMs = Math.max(Number(streamService.reservationTimeout) || 0, this.adaptiveReservationTimeout + ConsumptionManager.LEASE_BUFFER_S) * 1000;
537
+ const delays = [
538
+ windowMs + 1000,
539
+ windowMs * 2 + 1000,
540
+ windowMs * 4 + 1000,
541
+ ];
542
+ for (const delay of delays) {
543
+ streamService.scheduleStreamNotify(stream, delay);
544
+ }
545
+ const release = setTimeout(() => this.redeliveryWakes.delete(stream), delays[delays.length - 1]);
546
+ release.unref?.();
547
+ }
437
548
  /**
438
549
  * Whether reservation heartbeats are available: the provider must
439
550
  * implement extendReservation and advertise the capability.
@@ -589,6 +700,26 @@ class ConsumptionManager {
589
700
  }
590
701
  catch (err) {
591
702
  const category = (0, errors_1.classifyError)(err);
703
+ if (category === errors_1.ErrorCategory.UNAVAILABLE) {
704
+ // The HotMesh database connection is unavailable. Do NOT ack and
705
+ // do NOT publish an error response: the message stays reserved and
706
+ // is redelivered once the connection returns, without spending
707
+ // the retry budget on an outage.
708
+ this.logger.warn('stream-connection-unavailable', {
709
+ category,
710
+ group,
711
+ stream,
712
+ id,
713
+ topic: input.metadata?.topic,
714
+ activityId: input.metadata?.aid,
715
+ jobId: input.metadata?.jid,
716
+ error: err?.message,
717
+ });
718
+ telemetry.setStreamErrorFromException(err);
719
+ telemetry.endStreamSpan();
720
+ this.deferForRedelivery(stream, id, consumer);
721
+ return; // NO ack — redelivered after the connection returns
722
+ }
592
723
  if (err instanceof errors_1.LeaseExpiredError) {
593
724
  // FATAL: lease expired — do NOT ack. The message remains in the
594
725
  // stream for a reclaimant to pick up cleanly. Any partial writes
@@ -646,6 +777,7 @@ class ConsumptionManager {
646
777
  }
647
778
  }
648
779
  }
780
+ let skipAck = false;
649
781
  try {
650
782
  // When the ENGINE encounters an infrastructure error (schema not found,
651
783
  // subscription missing — code 598), the message is permanently unprocessable.
@@ -667,16 +799,49 @@ class ConsumptionManager {
667
799
  }
668
800
  }
669
801
  catch (publishErr) {
670
- // If publishResponse fails, still ack the message to prevent
671
- // infinite reprocessing. Log the error for debugging.
672
- this.logger.error(`stream-publish-response-error`, {
673
- category: (0, errors_1.classifyError)(publishErr),
674
- group, stream, id, error: publishErr,
675
- });
802
+ if ((0, errors_1.isConnectionError)(publishErr)) {
803
+ // The response was not written because the connection is gone.
804
+ // Acking now would lose it; leave the message for redelivery.
805
+ skipAck = true;
806
+ this.deferForRedelivery(stream, id, consumer);
807
+ this.logger.warn(`stream-publish-response-deferred`, {
808
+ category: errors_1.ErrorCategory.UNAVAILABLE,
809
+ group,
810
+ stream,
811
+ id,
812
+ error: publishErr?.message,
813
+ });
814
+ }
815
+ else {
816
+ // If publishResponse fails, still ack the message to prevent
817
+ // infinite reprocessing. Log the error for debugging.
818
+ this.logger.error(`stream-publish-response-error`, {
819
+ category: (0, errors_1.classifyError)(publishErr),
820
+ group,
821
+ stream,
822
+ id,
823
+ error: publishErr,
824
+ });
825
+ }
676
826
  this.errorCount++;
677
827
  }
678
828
  finally {
679
- await this.ackAndDelete(stream, group, id);
829
+ if (!skipAck) {
830
+ try {
831
+ await this.ackAndDelete(stream, group, id);
832
+ }
833
+ catch (ackErr) {
834
+ // An unacked message is redelivered; never let the ack reject
835
+ // the consumer loop.
836
+ this.logger.warn(`stream-ack-deferred`, {
837
+ category: (0, errors_1.classifyError)(ackErr),
838
+ group,
839
+ stream,
840
+ id,
841
+ error: ackErr?.message,
842
+ });
843
+ }
844
+ }
680
845
  telemetry.endStreamSpan();
681
846
  this.logger.debug(`stream-read-one-end`, { group, stream, id });
682
847
  }
@@ -687,6 +852,11 @@ class ConsumptionManager {
687
852
  output = await callback(input);
688
853
  }
689
854
  catch (error) {
855
+ if (error instanceof errors_1.HotMeshConnectionError) {
856
+ //an outage is not the callback's failure; consumeOne leaves the
857
+ //message for redelivery instead of structuring an error response
858
+ throw error;
859
+ }
690
860
  this.logger.error(`stream-call-function-error`, {
691
861
  category: (0, errors_1.classifyError)(error),
692
862
  error,
@@ -103,13 +103,17 @@ function pickCte(name, selector, namespace, p) {
103
103
  case 'signalKey':
104
104
  return `${name} AS MATERIALIZED (SELECT e.id ${from} WHERE e.signal_key = ${p.add(selector.signalKey)}${ns} LIMIT 1)`;
105
105
  case 'metadata': {
106
+ // The facet names a container: only a pending row carrying the
107
+ // accumulator declaration qualifies, so a release or remediation row
108
+ // sharing the facet (or a closed older generation) is never picked.
106
109
  const filter = p.add(JSON.stringify({ [selector.key]: selector.value }));
107
110
  const roles = p.add(selector.roles ?? null);
108
111
  return `${name} AS MATERIALIZED (
109
112
  SELECT e.id ${from}
110
113
  WHERE e.metadata @> ${filter}::jsonb
114
+ AND e.metadata ? '${COUNT}'
111
115
  AND (${roles}::text[] IS NULL OR e.role = ANY(${roles}::text[]))
112
- AND e.status IN ('pending', 'cancelled')${ns}
116
+ AND e.status = 'pending'${ns}
113
117
  ORDER BY e.priority ASC, e.created_at ASC
114
118
  LIMIT 1)`;
115
119
  }
@@ -263,7 +263,14 @@ class KVTransaction {
263
263
  commandTypes: this.commands.map(c => c.returnType),
264
264
  commandSqlPreviews: this.commands.map(c => c.sql.substring(0, 80)),
265
265
  });
266
- await client.query('ROLLBACK');
266
+ //a ROLLBACK on a lost session fails too; the original error is the one
267
+ //the caller needs (the server already rolled the session back)
268
+ try {
269
+ await client.query('ROLLBACK');
270
+ }
271
+ catch {
272
+ //nothing to roll back
273
+ }
267
274
  throw err;
268
275
  }
269
276
  }
@@ -1002,8 +1002,8 @@ class PostgresStoreService extends __1.StoreService {
1002
1002
  if (didRemove) {
1003
1003
  if (scrub) {
1004
1004
  //indexes can be designed to be self-cleaning; `engine.hookAll` exposes this option
1005
- this.kvsql().del(processedKey);
1006
- this.kvsql().del(key.split(':').slice(0, 5).join(':'));
1005
+ (0, utils_1.detach)(this.kvsql().del(processedKey), this.logger, 'store-scrub-error');
1006
+ (0, utils_1.detach)(this.kvsql().del(key.split(':').slice(0, 5).join(':')), this.logger, 'store-scrub-error');
1007
1007
  }
1008
1008
  else {
1009
1009
  await this.kvsql().rename(processedKey, key);
@@ -73,6 +73,7 @@ export declare abstract class StreamService<ClientProvider extends ProviderClien
73
73
  deadLetterMessages?(streamName: string, groupName: string, messageIds: string[]): Promise<number>;
74
74
  expireJobMessages?(jid: string): Promise<number>;
75
75
  extendReservation?(streamName: string, messageId: string, consumerName: string): Promise<number>;
76
+ releaseReservations?(streamName: string, messageIds: string[], consumerName: string): Promise<number>;
76
77
  stopNotificationConsumer?(streamName: string, groupName: string): Promise<void>;
77
78
  cleanup?(): Promise<void>;
78
79
  }
@@ -44,6 +44,13 @@ export declare function expireJobMessages(client: PostgresClientType & ProviderC
44
44
  * stale consumer can abandon its execution.
45
45
  */
46
46
  export declare function extendReservation(client: PostgresClientType & ProviderClient, tableName: string, streamName: string, messageId: string, consumerName: string, logger: ILogger): Promise<number>;
47
+ /**
48
+ * Release reservations the consumer still holds so the messages are
49
+ * redelivered immediately. Scoped to the owning consumer and to live
50
+ * rows: a message another consumer reclaimed, or one already acked or
51
+ * expired, is left alone.
52
+ */
53
+ export declare function releaseReservations(client: PostgresClientType & ProviderClient, tableName: string, streamName: string, messageIds: string[], consumerName: string, logger: ILogger): Promise<number>;
47
54
  /**
48
55
  * Fetch messages from the stream with optional exponential backoff.
49
56
  * Uses SKIP LOCKED for high-concurrency consumption.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.retryMessages = exports.deadLetterMessages = exports.ackAndDelete = exports.deleteMessages = exports.acknowledgeMessages = exports.fetchMessages = exports.extendReservation = exports.expireJobMessages = exports.buildPublishSQL = exports.publishMessages = exports.getMessagePriority = void 0;
3
+ exports.retryMessages = exports.deadLetterMessages = exports.ackAndDelete = exports.deleteMessages = exports.acknowledgeMessages = exports.fetchMessages = exports.releaseReservations = exports.extendReservation = exports.expireJobMessages = exports.buildPublishSQL = exports.publishMessages = exports.getMessagePriority = void 0;
4
4
  const enums_1 = require("../../../../modules/enums");
5
5
  const utils_1 = require("../../../../modules/utils");
6
6
  const stream_1 = require("../../../../types/stream");
@@ -255,6 +255,32 @@ async function extendReservation(client, tableName, streamName, messageId, consu
255
255
  }
256
256
  }
257
257
  exports.extendReservation = extendReservation;
258
+ /**
259
+ * Release reservations the consumer still holds so the messages are
260
+ * redelivered immediately. Scoped to the owning consumer and to live
261
+ * rows: a message another consumer reclaimed, or one already acked or
262
+ * expired, is left alone.
263
+ */
264
+ async function releaseReservations(client, tableName, streamName, messageIds, consumerName, logger) {
265
+ if (messageIds.length === 0) {
266
+ return 0;
267
+ }
268
+ try {
269
+ const res = await client.query(`UPDATE ${tableName}
270
+ SET reserved_at = NULL, reserved_by = NULL
271
+ WHERE stream_name = $1 AND id = ANY($2::bigint[])
272
+ AND reserved_by = $3 AND expired_at IS NULL`, [streamName, messageIds.map((id) => parseInt(id, 10)), consumerName]);
273
+ return res.rowCount ?? 0;
274
+ }
275
+ catch (error) {
276
+ logger.error(`postgres-stream-release-error-${streamName}`, {
277
+ messageIds,
278
+ error,
279
+ });
280
+ throw error;
281
+ }
282
+ }
283
+ exports.releaseReservations = releaseReservations;
258
284
  /**
259
285
  * Delivery liveness guard. Scoped to messages that are REDELIVERIES
260
286
  * (a prior reservation lapsed) or RETRIES (retry_attempt > 0) — zombie
@@ -17,6 +17,7 @@ export declare class NotificationManager<TService> {
17
17
  private static clientNotificationConsumers;
18
18
  private static clientNotificationHandlers;
19
19
  private static clientFallbackPollers;
20
+ private static relistenClients;
20
21
  private instanceNotificationConsumers;
21
22
  private notificationHandlerBound;
22
23
  constructor(client: PostgresClientType & ProviderClient, getTableName: () => string, getFallbackInterval: () => number, logger: ILogger);
@@ -24,6 +25,12 @@ export declare class NotificationManager<TService> {
24
25
  * Set up notification handler for this client (once per client).
25
26
  */
26
27
  setupClientNotificationHandler(serviceInstance: TService): void;
28
+ /**
29
+ * Re-issue LISTEN for every stream channel with a consumer on this
30
+ * client, then wake each listening consumer. Failures are logged; the
31
+ * fallback poller and the next reconnect cover what remains.
32
+ */
33
+ private static relisten;
27
34
  /**
28
35
  * Start fallback poller for missed notifications (once per client).
29
36
  */
@@ -55,6 +62,12 @@ export declare class NotificationManager<TService> {
55
62
  */
56
63
  private getConsumerKey;
57
64
  }
65
+ /**
66
+ * Hand a batch to a consumer's callback. The callback is async in
67
+ * practice; its rejection is logged here and never becomes an unhandled
68
+ * rejection. Unacked messages are redelivered by the stream.
69
+ */
70
+ export declare function deliver(consumer: NotificationConsumer, messages: StreamMessage[], logger: ILogger): void;
58
71
  /**
59
72
  * Get configuration values for notification settings.
60
73
  */
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getNotificationTimeout = exports.getFallbackInterval = exports.NotificationManager = void 0;
3
+ exports.getNotificationTimeout = exports.getFallbackInterval = exports.deliver = exports.NotificationManager = void 0;
4
4
  const enums_1 = require("../../../../modules/enums");
5
5
  const kvtables_1 = require("./kvtables");
6
6
  /**
@@ -32,6 +32,66 @@ class NotificationManager {
32
32
  }
33
33
  this.client.on('notification', this.notificationHandlerBound);
34
34
  NotificationManager.clientNotificationHandlers.set(this.client, true);
35
+ // A resilient client replaces its session after a loss; LISTEN is
36
+ // session state, so channels are re-armed and every consumer fetches
37
+ // at once (NOTIFYs sent while the session was down are gone)
38
+ const client = this.client;
39
+ if (!NotificationManager.relistenClients.has(client)) {
40
+ NotificationManager.relistenClients.add(client);
41
+ client.on('reconnected', () => {
42
+ void NotificationManager.relisten(client, this.logger);
43
+ });
44
+ }
45
+ }
46
+ /**
47
+ * Re-issue LISTEN for every stream channel with a consumer on this
48
+ * client, then wake each listening consumer. Failures are logged; the
49
+ * fallback poller and the next reconnect cover what remains.
50
+ */
51
+ static async relisten(client, logger) {
52
+ const consumersByKey = NotificationManager.clientNotificationConsumers.get(client);
53
+ if (!consumersByKey) {
54
+ return;
55
+ }
56
+ let armed = 0;
57
+ for (const [consumerKey, instanceMap] of consumersByKey.entries()) {
58
+ const consumers = Array.from(instanceMap.values());
59
+ const anyConsumer = consumers[0];
60
+ if (!anyConsumer) {
61
+ continue;
62
+ }
63
+ const separator = consumerKey.lastIndexOf(':');
64
+ const resolvedStreamName = consumerKey.substring(0, separator);
65
+ const isEngine = consumerKey.substring(separator + 1) === 'ENGINE';
66
+ const channelName = (0, kvtables_1.getNotificationChannelName)(resolvedStreamName, isEngine);
67
+ const serviceAny = anyConsumer.serviceInstance;
68
+ try {
69
+ if (serviceAny?.securedMode && serviceAny?.safeName) {
70
+ const schema = serviceAny.safeName(serviceAny.appId);
71
+ await client.query(`SELECT ${schema}.worker_listen($1)`, [
72
+ resolvedStreamName,
73
+ ]);
74
+ }
75
+ else {
76
+ await client.query(`LISTEN "${channelName}"`);
77
+ }
78
+ armed++;
79
+ }
80
+ catch (error) {
81
+ logger.warn('postgres-stream-relisten-error', { channelName, error });
82
+ continue;
83
+ }
84
+ for (const consumer of consumers) {
85
+ if (consumer.isListening &&
86
+ consumer.serviceInstance?.fetchAndDeliverMessages) {
87
+ consumer.serviceInstance.fetchAndDeliverMessages(consumer);
88
+ }
89
+ }
90
+ }
91
+ logger.info('postgres-stream-relisten', {
92
+ channels: consumersByKey.size,
93
+ armed,
94
+ });
35
95
  }
36
96
  /**
37
97
  * Start fallback poller for missed notifications (once per client).
@@ -90,7 +150,7 @@ class NotificationManager {
90
150
  groupName: consumer.groupName,
91
151
  messageCount: messages.length,
92
152
  });
93
- consumer.callback(messages);
153
+ deliver(consumer, messages, this.logger);
94
154
  }
95
155
  consumer.lastFallbackCheck = now;
96
156
  }
@@ -372,7 +432,34 @@ class NotificationManager {
372
432
  NotificationManager.clientNotificationConsumers = new Map();
373
433
  NotificationManager.clientNotificationHandlers = new Map();
374
434
  NotificationManager.clientFallbackPollers = new Map();
435
+ // Clients whose 'reconnected' event re-arms LISTEN (armed once per client)
436
+ NotificationManager.relistenClients = new WeakSet();
375
437
  exports.NotificationManager = NotificationManager;
438
+ /**
439
+ * Hand a batch to a consumer's callback. The callback is async in
440
+ * practice; its rejection is logged here and never becomes an unhandled
441
+ * rejection. Unacked messages are redelivered by the stream.
442
+ */
443
+ function deliver(consumer, messages, logger) {
444
+ try {
445
+ const settled = consumer.callback(messages);
446
+ if (settled && typeof settled.catch === 'function') {
447
+ settled.catch((error) => logger.error('postgres-stream-consumer-callback-error', {
448
+ streamName: consumer.streamName,
449
+ groupName: consumer.groupName,
450
+ error,
451
+ }));
452
+ }
453
+ }
454
+ catch (error) {
455
+ logger.error('postgres-stream-consumer-callback-error', {
456
+ streamName: consumer.streamName,
457
+ groupName: consumer.groupName,
458
+ error,
459
+ });
460
+ }
461
+ }
462
+ exports.deliver = deliver;
376
463
  /**
377
464
  * Get configuration values for notification settings.
378
465
  */
@@ -99,6 +99,13 @@ declare class PostgresStreamService extends StreamService<PostgresClientType & P
99
99
  * is no longer this consumer's to hold (reclaimed, acked, or expired).
100
100
  */
101
101
  extendReservation(streamName: string, messageId: string, consumerName: string): Promise<number>;
102
+ /**
103
+ * Release reservations this consumer holds but deferred (the connection
104
+ * was unavailable), then wake the stream's consumers so the messages are
105
+ * redelivered at once. Secured workers cannot update the stream table;
106
+ * their messages are redelivered when the reservation lapses.
107
+ */
108
+ releaseReservations(streamName: string, messageIds: string[], consumerName: string): Promise<number>;
102
109
  /**
103
110
  * Soft-deletes every live stream row that belongs to a job, across the
104
111
  * worker and engine stream tables. Called by the engine when a job is
@@ -110,7 +110,7 @@ class PostgresStreamService extends index_1.StreamService {
110
110
  consumer.fetchPending = false;
111
111
  const messages = await this.fetchMessages(consumer.streamName, consumer.groupName, consumer.consumerName, { batchSize, reservationTimeout: this.reservationTimeout, enableBackoff: false, maxRetries: 1 });
112
112
  if (messages.length > 0) {
113
- consumer.callback(messages);
113
+ (0, notifications_1.deliver)(consumer, messages, this.logger);
114
114
  }
115
115
  // Boolean() rather than === true: fetchPending is mutated by the
116
116
  // notification handler across the await, which TS narrowing misses
@@ -221,7 +221,7 @@ class PostgresStreamService extends index_1.StreamService {
221
221
  stream_name: target.streamName,
222
222
  table_type: target.isEngine ? 'engine' : 'worker',
223
223
  });
224
- setTimeout(async () => {
224
+ const timer = setTimeout(async () => {
225
225
  try {
226
226
  await this.streamClient.query(`SELECT pg_notify($1, $2)`, [channelName, payload]);
227
227
  }
@@ -229,6 +229,8 @@ class PostgresStreamService extends index_1.StreamService {
229
229
  // Best-effort; the scout fallback will pick it up
230
230
  }
231
231
  }, delayMs);
232
+ //a pending wake never holds a finished process open
233
+ timer.unref?.();
232
234
  }
233
235
  _publishMessages(streamName, messages, options) {
234
236
  const target = this.resolveStreamTarget(streamName);
@@ -267,7 +269,7 @@ class PostgresStreamService extends index_1.StreamService {
267
269
  fetchDuration: Date.now() - fetchStart,
268
270
  });
269
271
  if (initialMessages.length > 0) {
270
- callback(initialMessages);
272
+ (0, notifications_1.deliver)({ streamName, groupName, callback }, initialMessages, this.logger);
271
273
  }
272
274
  }
273
275
  catch (error) {
@@ -308,6 +310,23 @@ class PostgresStreamService extends index_1.StreamService {
308
310
  const target = this.resolveStreamTarget(streamName);
309
311
  return Messages.extendReservation(this.streamClient, target.tableName, target.streamName, messageId, consumerName, this.logger);
310
312
  }
313
+ /**
314
+ * Release reservations this consumer holds but deferred (the connection
315
+ * was unavailable), then wake the stream's consumers so the messages are
316
+ * redelivered at once. Secured workers cannot update the stream table;
317
+ * their messages are redelivered when the reservation lapses.
318
+ */
319
+ async releaseReservations(streamName, messageIds, consumerName) {
320
+ if (this.securedMode) {
321
+ return 0;
322
+ }
323
+ const target = this.resolveStreamTarget(streamName);
324
+ const released = await Messages.releaseReservations(this.streamClient, target.tableName, target.streamName, messageIds, consumerName, this.logger);
325
+ if (released > 0) {
326
+ this.scheduleStreamNotify(streamName, 0);
327
+ }
328
+ return released;
329
+ }
311
330
  /**
312
331
  * Soft-deletes every live stream row that belongs to a job, across the
313
332
  * worker and engine stream tables. Called by the engine when a job is
@@ -62,6 +62,12 @@ declare class StreamConsumerRegistry {
62
62
  static getEngineCounts(namespace: string, appId: string): {
63
63
  [key: string]: number;
64
64
  };
65
+ /**
66
+ * Forget every registered consumer without stopping them. Used after
67
+ * the routers were already stopped process-wide, so a later init in the
68
+ * same process creates live consumers instead of reusing stopped ones.
69
+ */
70
+ static clear(): void;
65
71
  /**
66
72
  * Stop all consumers and clear the registry.
67
73
  */
@@ -51,7 +51,7 @@ class StreamConsumerRegistry {
51
51
  appId,
52
52
  topic: taskQueue,
53
53
  });
54
- router.consumeMessages(streamKey, 'WORKER', guid, dispatchCallback);
54
+ (0, utils_1.detach)(router.consumeMessages(streamKey, 'WORKER', guid, dispatchCallback), logger, 'stream-consumer-registry-worker-start-error', { taskQueue });
55
55
  }
56
56
  }
57
57
  // Register the callback for this workflow name
@@ -93,7 +93,7 @@ class StreamConsumerRegistry {
93
93
  throttle,
94
94
  }, stream, logger);
95
95
  entry.routers.push(router);
96
- router.consumeMessages(streamKey, 'ENGINE', consumerGuid, dispatchCallback);
96
+ (0, utils_1.detach)(router.consumeMessages(streamKey, 'ENGINE', consumerGuid, dispatchCallback), logger, 'stream-consumer-registry-engine-start-error', { appId });
97
97
  }
98
98
  if (enums_1.HMSH_ENGINE_CONCURRENCY > 1) {
99
99
  logger.info('stream-consumer-registry-engine-parallel', {
@@ -215,6 +215,15 @@ class StreamConsumerRegistry {
215
215
  }
216
216
  return merged;
217
217
  }
218
+ /**
219
+ * Forget every registered consumer without stopping them. Used after
220
+ * the routers were already stopped process-wide, so a later init in the
221
+ * same process creates live consumers instead of reusing stopped ones.
222
+ */
223
+ static clear() {
224
+ StreamConsumerRegistry.workerConsumers.clear();
225
+ StreamConsumerRegistry.engineConsumers.clear();
226
+ }
218
227
  /**
219
228
  * Stop all consumers and clear the registry.
220
229
  */
@@ -7,11 +7,17 @@ import { PostgresClientType } from '../../../../types/postgres';
7
7
  declare class PostgresSubService extends SubService<PostgresClientType & ProviderClient> {
8
8
  private static clientSubscriptions;
9
9
  private static clientHandlers;
10
+ private static relistenClients;
10
11
  private instanceSubscriptions;
11
12
  private instanceId;
12
13
  constructor(eventClient: PostgresClientType & ProviderClient, storeClient?: PostgresClientType & ProviderClient);
13
14
  init(namespace: string, appId: string, engineId: string, logger: ILogger): Promise<void>;
14
15
  private setupNotificationHandler;
16
+ /**
17
+ * Re-issue LISTEN for every channel subscribed on a client. A failure
18
+ * leaves the channel for the next reconnect; nothing is thrown.
19
+ */
20
+ private static relisten;
15
21
  transact(): ProviderTransaction;
16
22
  mintKey(type: KeyType, params: KeyStoreParams): string;
17
23
  mintSafeKey(type: KeyType, params: KeyStoreParams): [string, string];