@hotmeshio/hotmesh 0.29.1 → 0.31.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 (65) 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/durable/workflow/condition.d.ts +14 -0
  23. package/build/services/durable/workflow/condition.js +14 -0
  24. package/build/services/engine/completion.js +3 -3
  25. package/build/services/engine/signal.js +3 -3
  26. package/build/services/escalations/batch.d.ts +7 -3
  27. package/build/services/escalations/batch.js +64 -6
  28. package/build/services/escalations/client.d.ts +4 -2
  29. package/build/services/escalations/client.js +4 -2
  30. package/build/services/escalations/fold.d.ts +3 -2
  31. package/build/services/escalations/fold.js +13 -2
  32. package/build/services/escalations/index.d.ts +1 -1
  33. package/build/services/escalations/index.js +2 -1
  34. package/build/services/hotmesh/index.js +17 -4
  35. package/build/services/quorum/index.js +13 -13
  36. package/build/services/router/consumption/index.d.ts +20 -0
  37. package/build/services/router/consumption/index.js +177 -7
  38. package/build/services/store/providers/postgres/kvtransaction.js +8 -1
  39. package/build/services/store/providers/postgres/postgres.d.ts +2 -1
  40. package/build/services/store/providers/postgres/postgres.js +18 -9
  41. package/build/services/stream/index.d.ts +16 -0
  42. package/build/services/stream/index.js +23 -0
  43. package/build/services/stream/providers/postgres/messages.d.ts +7 -0
  44. package/build/services/stream/providers/postgres/messages.js +27 -1
  45. package/build/services/stream/providers/postgres/notifications.d.ts +13 -0
  46. package/build/services/stream/providers/postgres/notifications.js +89 -2
  47. package/build/services/stream/providers/postgres/postgres.d.ts +7 -0
  48. package/build/services/stream/providers/postgres/postgres.js +24 -3
  49. package/build/services/stream/providers/postgres/scout.d.ts +10 -0
  50. package/build/services/stream/providers/postgres/scout.js +38 -4
  51. package/build/services/stream/registry.d.ts +6 -0
  52. package/build/services/stream/registry.js +11 -2
  53. package/build/services/sub/providers/postgres/postgres.d.ts +6 -0
  54. package/build/services/sub/providers/postgres/postgres.js +62 -2
  55. package/build/services/task/index.js +1 -1
  56. package/build/services/worker/credentials.js +5 -0
  57. package/build/services/worker/index.js +5 -5
  58. package/build/types/hmsh_escalations.d.ts +32 -0
  59. package/build/types/hmsh_escalations.js +5 -1
  60. package/build/types/index.d.ts +3 -3
  61. package/build/types/index.js +2 -1
  62. package/build/types/postgres.d.ts +20 -0
  63. package/build/types/provider.d.ts +28 -0
  64. package/index.ts +2 -0
  65. package/package.json +1 -1
@@ -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
@@ -80,6 +80,7 @@ class PostgresStreamService extends index_1.StreamService {
80
80
  this.notificationManager.setupClientNotificationHandler(this);
81
81
  this.notificationManager.startClientFallbackPoller(this.checkForMissedMessages.bind(this));
82
82
  this.scoutManager?.startRouterScoutPoller();
83
+ this.trackBackgroundWork();
83
84
  }
84
85
  }
85
86
  isNotificationsEnabled() {
@@ -110,7 +111,7 @@ class PostgresStreamService extends index_1.StreamService {
110
111
  consumer.fetchPending = false;
111
112
  const messages = await this.fetchMessages(consumer.streamName, consumer.groupName, consumer.consumerName, { batchSize, reservationTimeout: this.reservationTimeout, enableBackoff: false, maxRetries: 1 });
112
113
  if (messages.length > 0) {
113
- consumer.callback(messages);
114
+ (0, notifications_1.deliver)(consumer, messages, this.logger);
114
115
  }
115
116
  // Boolean() rather than === true: fetchPending is mutated by the
116
117
  // notification handler across the await, which TS narrowing misses
@@ -221,7 +222,7 @@ class PostgresStreamService extends index_1.StreamService {
221
222
  stream_name: target.streamName,
222
223
  table_type: target.isEngine ? 'engine' : 'worker',
223
224
  });
224
- setTimeout(async () => {
225
+ const timer = setTimeout(async () => {
225
226
  try {
226
227
  await this.streamClient.query(`SELECT pg_notify($1, $2)`, [channelName, payload]);
227
228
  }
@@ -229,6 +230,8 @@ class PostgresStreamService extends index_1.StreamService {
229
230
  // Best-effort; the scout fallback will pick it up
230
231
  }
231
232
  }, delayMs);
233
+ //a pending wake never holds a finished process open
234
+ timer.unref?.();
232
235
  }
233
236
  _publishMessages(streamName, messages, options) {
234
237
  const target = this.resolveStreamTarget(streamName);
@@ -267,7 +270,7 @@ class PostgresStreamService extends index_1.StreamService {
267
270
  fetchDuration: Date.now() - fetchStart,
268
271
  });
269
272
  if (initialMessages.length > 0) {
270
- callback(initialMessages);
273
+ (0, notifications_1.deliver)({ streamName, groupName, callback }, initialMessages, this.logger);
271
274
  }
272
275
  }
273
276
  catch (error) {
@@ -308,6 +311,23 @@ class PostgresStreamService extends index_1.StreamService {
308
311
  const target = this.resolveStreamTarget(streamName);
309
312
  return Messages.extendReservation(this.streamClient, target.tableName, target.streamName, messageId, consumerName, this.logger);
310
313
  }
314
+ /**
315
+ * Release reservations this consumer holds but deferred (the connection
316
+ * was unavailable), then wake the stream's consumers so the messages are
317
+ * redelivered at once. Secured workers cannot update the stream table;
318
+ * their messages are redelivered when the reservation lapses.
319
+ */
320
+ async releaseReservations(streamName, messageIds, consumerName) {
321
+ if (this.securedMode) {
322
+ return 0;
323
+ }
324
+ const target = this.resolveStreamTarget(streamName);
325
+ const released = await Messages.releaseReservations(this.streamClient, target.tableName, target.streamName, messageIds, consumerName, this.logger);
326
+ if (released > 0) {
327
+ this.scheduleStreamNotify(streamName, 0);
328
+ }
329
+ return released;
330
+ }
311
331
  /**
312
332
  * Soft-deletes every live stream row that belongs to a job, across the
313
333
  * worker and engine stream tables. Called by the engine when a job is
@@ -396,6 +416,7 @@ class PostgresStreamService extends index_1.StreamService {
396
416
  };
397
417
  }
398
418
  async cleanup() {
419
+ this.untrackBackgroundWork();
399
420
  if (this.scoutManager) {
400
421
  await this.scoutManager.stopRouterScoutPoller();
401
422
  }
@@ -15,6 +15,8 @@ export declare class ScoutManager {
15
15
  private logger;
16
16
  private isScout;
17
17
  private shouldStopScout;
18
+ private roleResetTimer;
19
+ private pause;
18
20
  private pollCount;
19
21
  private totalNotifications;
20
22
  private scoutStartTime;
@@ -36,6 +38,14 @@ export declare class ScoutManager {
36
38
  * Main polling loop for the router scout.
37
39
  */
38
40
  private pollForVisibleMessagesLoop;
41
+ /**
42
+ * A loop pause that `stopRouterScoutPoller()` ends early, so a stopped
43
+ * scout leaves no timer behind.
44
+ */
45
+ private pauseFor;
46
+ private endPause;
47
+ /** True once `stopRouterScoutPoller()` has run. */
48
+ isStopped(): boolean;
39
49
  /**
40
50
  * Poll for visible messages and trigger notifications for any found.
41
51
  */
@@ -17,6 +17,8 @@ class ScoutManager {
17
17
  this.logger = logger;
18
18
  this.isScout = false;
19
19
  this.shouldStopScout = false;
20
+ this.roleResetTimer = null;
21
+ this.pause = null;
20
22
  // Polling metrics
21
23
  this.pollCount = 0;
22
24
  this.totalNotifications = 0;
@@ -42,6 +44,11 @@ class ScoutManager {
42
44
  */
43
45
  async stopRouterScoutPoller() {
44
46
  this.shouldStopScout = true;
47
+ if (this.roleResetTimer) {
48
+ clearTimeout(this.roleResetTimer);
49
+ this.roleResetTimer = null;
50
+ }
51
+ this.endPause();
45
52
  if (this.isScout) {
46
53
  await this.releaseScoutRole('router');
47
54
  this.isScout = false;
@@ -62,7 +69,8 @@ class ScoutManager {
62
69
  this.logger.debug('postgres-stream-router-scout-role-acquired', {
63
70
  appId: this.appId,
64
71
  });
65
- setTimeout(() => {
72
+ this.roleResetTimer = setTimeout(() => {
73
+ this.roleResetTimer = null;
66
74
  this.isScout = false;
67
75
  this.scoutStartTime = null;
68
76
  }, enums_1.HMSH_ROUTER_SCOUT_INTERVAL_SECONDS * 1000);
@@ -81,19 +89,45 @@ class ScoutManager {
81
89
  // We're the scout - poll for visible messages frequently
82
90
  await this.pollForVisibleMessages();
83
91
  // Sleep for the short polling interval
84
- await (0, utils_1.sleepFor)(this.getRouterScoutInterval());
92
+ await this.pauseFor(this.getRouterScoutInterval());
85
93
  }
86
94
  else {
87
95
  // Not the scout - sleep longer before trying to acquire role again
88
- await (0, utils_1.sleepFor)(enums_1.HMSH_ROUTER_SCOUT_INTERVAL_SECONDS * 1000);
96
+ await this.pauseFor(enums_1.HMSH_ROUTER_SCOUT_INTERVAL_SECONDS * 1000);
89
97
  }
90
98
  }
91
99
  catch (error) {
92
100
  this.logger.error('postgres-stream-router-scout-loop-error', { error });
93
- await (0, utils_1.sleepFor)(1000); // Brief pause on error
101
+ await this.pauseFor(1000); // Brief pause on error
94
102
  }
95
103
  }
96
104
  }
105
+ /**
106
+ * A loop pause that `stopRouterScoutPoller()` ends early, so a stopped
107
+ * scout leaves no timer behind.
108
+ */
109
+ pauseFor(ms) {
110
+ if (this.shouldStopScout)
111
+ return Promise.resolve();
112
+ return new Promise((resolve) => {
113
+ const timer = setTimeout(() => {
114
+ this.pause = null;
115
+ resolve();
116
+ }, ms);
117
+ this.pause = { timer, resolve };
118
+ });
119
+ }
120
+ endPause() {
121
+ if (!this.pause)
122
+ return;
123
+ clearTimeout(this.pause.timer);
124
+ this.pause.resolve();
125
+ this.pause = null;
126
+ }
127
+ /** True once `stopRouterScoutPoller()` has run. */
128
+ isStopped() {
129
+ return this.shouldStopScout;
130
+ }
97
131
  /**
98
132
  * Poll for visible messages and trigger notifications for any found.
99
133
  */
@@ -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];
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.PostgresSubService = void 0;
7
7
  const crypto_1 = __importDefault(require("crypto"));
8
8
  const enums_1 = require("../../../../modules/enums");
9
+ const errors_1 = require("../../../../modules/errors");
9
10
  const key_1 = require("../../../../modules/key");
10
11
  const index_1 = require("../../index");
11
12
  class PostgresSubService extends index_1.SubService {
@@ -43,7 +44,12 @@ class PostgresSubService extends index_1.SubService {
43
44
  // Call all callbacks
44
45
  callbackArray.forEach(([callbackKey, callback], index) => {
45
46
  try {
46
- callback(msg.channel, payload);
47
+ //async subscribers settle here; a rejection is logged, never unhandled
48
+ const settled = callback(msg.channel, payload);
49
+ if (settled &&
50
+ typeof settled.catch === 'function') {
51
+ settled.catch((err) => this.logger?.error(`Error in subscription callback for ${msg.channel}:`, err));
52
+ }
47
53
  }
48
54
  catch (err) {
49
55
  this.logger?.error(`Error in subscription callback for ${msg.channel}:`, err);
@@ -55,9 +61,37 @@ class PostgresSubService extends index_1.SubService {
55
61
  }
56
62
  }
57
63
  });
64
+ // A resilient client replaces its session after a loss; LISTEN is
65
+ // session state, so every channel is re-armed on the new session
66
+ const eventClient = this.eventClient;
67
+ if (typeof eventClient.on === 'function' &&
68
+ !PostgresSubService.relistenClients.has(eventClient)) {
69
+ PostgresSubService.relistenClients.add(eventClient);
70
+ eventClient.on('reconnected', () => {
71
+ void PostgresSubService.relisten(eventClient, this.logger);
72
+ });
73
+ }
58
74
  // Mark this client as having a notification handler
59
75
  PostgresSubService.clientHandlers.set(this.eventClient, true);
60
76
  }
77
+ /**
78
+ * Re-issue LISTEN for every channel subscribed on a client. A failure
79
+ * leaves the channel for the next reconnect; nothing is thrown.
80
+ */
81
+ static async relisten(client, logger) {
82
+ const channels = Array.from(PostgresSubService.clientSubscriptions.get(client)?.keys() ?? []);
83
+ let armed = 0;
84
+ for (const channel of channels) {
85
+ try {
86
+ await client.query(`LISTEN "${channel}"`);
87
+ armed++;
88
+ }
89
+ catch (error) {
90
+ logger?.warn('postgres-sub-relisten-error', { channel, error });
91
+ }
92
+ }
93
+ logger?.info('postgres-sub-relisten', { channels: channels.length, armed });
94
+ }
61
95
  transact() {
62
96
  throw new Error('Transactions are not supported in lightweight pub/sub');
63
97
  }
@@ -99,7 +133,22 @@ class PostgresSubService extends index_1.SubService {
99
133
  callbacks = new Map();
100
134
  clientSubscriptions.set(safeKey, callbacks);
101
135
  // Start listening to the safe topic (only once per channel across all instances)
102
- await this.eventClient.query(`LISTEN "${safeKey}"`);
136
+ try {
137
+ await this.eventClient.query(`LISTEN "${safeKey}"`);
138
+ }
139
+ catch (err) {
140
+ if (!(0, errors_1.isConnectionError)(err)) {
141
+ clientSubscriptions.delete(safeKey);
142
+ throw err;
143
+ }
144
+ //the session is being replaced: the channel stays registered and
145
+ //the reconnect re-arms it, so the subscriber is not lost
146
+ this.logger?.warn('postgres-subscribe-deferred', {
147
+ originalKey,
148
+ safeKey,
149
+ error: err?.message,
150
+ });
151
+ }
103
152
  }
104
153
  // Generate unique callback key to avoid overwrites
105
154
  const callbackKey = `${this.instanceId}-${Date.now()}-${Math.random()}`;
@@ -247,6 +296,15 @@ class PostgresSubService extends index_1.SubService {
247
296
  return true;
248
297
  }
249
298
  catch (err) {
299
+ // Pub/sub is best effort: an outage drops the message, never the caller
300
+ if ((0, errors_1.isConnectionError)(err)) {
301
+ this.logger?.warn('postgres-publish-failed-connection-unavailable', {
302
+ originalKey,
303
+ safeKey,
304
+ error: err?.message,
305
+ });
306
+ return false;
307
+ }
250
308
  // Handle gracefully if client was closed during operation
251
309
  if (err?.message?.includes('closed') || err?.message?.includes('queryable')) {
252
310
  this.logger?.debug('postgres-publish-failed-closed-client', {
@@ -271,3 +329,5 @@ exports.PostgresSubService = PostgresSubService;
271
329
  // Static maps to manage subscriptions across all instances sharing the same client
272
330
  PostgresSubService.clientSubscriptions = new Map();
273
331
  PostgresSubService.clientHandlers = new Map();
332
+ // Clients whose 'reconnected' event re-arms LISTEN (armed once per client)
333
+ PostgresSubService.relistenClients = new WeakSet();
@@ -24,7 +24,7 @@ class TaskService {
24
24
  else {
25
25
  await this.store.deleteProcessedTaskQueue(workItemKey, sourceKey, destinationKey, scrub === 'true');
26
26
  }
27
- setImmediate(() => this.processWebHooks(hookEventCallback));
27
+ setImmediate(() => (0, utils_1.detach)(this.processWebHooks(hookEventCallback), this.logger, 'task-process-webhooks-error'));
28
28
  }
29
29
  }
30
30
  async enqueueWorkItems(keys) {
@@ -21,6 +21,11 @@ async function createAdminClient(connection) {
21
21
  const ClientClass = config.class;
22
22
  const options = config.options;
23
23
  const client = new ClientClass(options);
24
+ //a lost socket fails the pending admin query; the 'error' event itself
25
+ //must never go unhandled (that ends the process)
26
+ if (typeof client.on === 'function') {
27
+ client.on('error', () => undefined);
28
+ }
24
29
  await client.connect();
25
30
  return client;
26
31
  }
@@ -129,16 +129,16 @@ class WorkerService {
129
129
  if (message.type === 'throttle') {
130
130
  if (message.topic !== null) {
131
131
  //undefined allows passthrough
132
- self.throttle(message.throttle);
132
+ (0, utils_1.detach)(self.throttle(message.throttle), self.logger, 'worker-throttle-error');
133
133
  }
134
134
  }
135
135
  else if (message.type === 'ping') {
136
- self.sayPong(self.appId, self.guid, message.originator, message.details);
136
+ (0, utils_1.detach)(self.sayPong(self.appId, self.guid, message.originator, message.details), self.logger, 'worker-pong-error');
137
137
  }
138
138
  else if (message.type === 'rollcall') {
139
139
  if (message.topic !== null) {
140
140
  //undefined allows passthrough
141
- self.doRollCall(message);
141
+ (0, utils_1.detach)(self.doRollCall(message), self.logger, 'worker-rollcall-error');
142
142
  }
143
143
  }
144
144
  };
@@ -203,12 +203,12 @@ class WorkerService {
203
203
  signature: signature ? this.callback.toString() : undefined,
204
204
  };
205
205
  }
206
- this.subscribe.publish(key_1.KeyType.QUORUM, {
206
+ (0, utils_1.detach)(this.subscribe.publish(key_1.KeyType.QUORUM, {
207
207
  type: 'pong',
208
208
  guid,
209
209
  originator,
210
210
  profile,
211
- }, appId);
211
+ }, appId), this.logger, 'worker-pong-publish-error');
212
212
  }
213
213
  /**
214
214
  * @private
@@ -36,6 +36,18 @@ export interface ConditionQueueConfig {
36
36
  * existing batch waiters are unchanged.
37
37
  */
38
38
  partialOnTimeout?: boolean;
39
+ /**
40
+ * With `batch`, entries already satisfied when the row is created (for
41
+ * example, received before the wait began). Each key must be declared in
42
+ * `batch`; at least one key must remain open. The entries are folded into
43
+ * the same creation INSERT: `batch_pending` / `batch_count` start without
44
+ * them, and `batch_items` / `batch_filled_at` / `batch_filled_by` hold
45
+ * their payload, time, and actor, so progress and completion count them
46
+ * and the completing signal delivers them with the rest. Pure input:
47
+ * `at` comes from the source of record, never a fresh clock in the
48
+ * workflow, so the replayed `condition()` folds the same row.
49
+ */
50
+ filled?: Record<string, BatchFilledEntry>;
39
51
  /**
40
52
  * Declares the wait as an open accumulator: items arrive over time via
41
53
  * `accumulateItem()` and the collection is delivered on every terminal
@@ -344,6 +356,8 @@ export interface CreateEscalationParams {
344
356
  batch?: string[];
345
357
  /** See {@link ConditionQueueConfig.partialOnTimeout}. */
346
358
  partialOnTimeout?: boolean;
359
+ /** See {@link ConditionQueueConfig.filled}. */
360
+ filled?: Record<string, BatchFilledEntry>;
347
361
  /**
348
362
  * Declares the row as an open accumulator. See
349
363
  * {@link ConditionQueueConfig.accumulate}. Standalone rows (no
@@ -475,6 +489,19 @@ export declare const ESCALATION_BATCH_ITEMS_KEY = "batch_items";
475
489
  * stamped by the DATABASE clock inside the same guarded fill statement —
476
490
  * row truth, not caller clocks. The attempt timeline for free. */
477
491
  export declare const ESCALATION_BATCH_FILLED_AT_KEY = "batch_filled_at";
492
+ /** Envelope key: per-item actors (`Record<itemKey, string>`), written by a
493
+ * fill that names an `actor` and by `filled` entries that carry one. Absent
494
+ * until the first attributed fill. */
495
+ export declare const ESCALATION_BATCH_FILLED_BY_KEY = "batch_filled_by";
496
+ /** One batch entry satisfied at creation. See {@link ConditionQueueConfig.filled}. */
497
+ export interface BatchFilledEntry<P = Record<string, unknown>> {
498
+ /** Stored under `envelope.batch_items[itemKey]`, delivered with the collection. */
499
+ payload: P;
500
+ /** ISO-8601: when the entry was satisfied, from the source of record. */
501
+ at: string;
502
+ /** Stored under `envelope.batch_filled_by[itemKey]`. */
503
+ actor?: string;
504
+ }
478
505
  /** Item keys are non-empty strings up to this length. Any characters are
479
506
  * accepted (keys are always parameterized and stored as jsonb text); prefer
480
507
  * URL/query-friendly names (e.g. `u1-L`) for endpoint ergonomics. */
@@ -707,6 +734,9 @@ export interface ResolveBatchItemParams {
707
734
  * claim-agnostic without it (multiple contributors are the norm). See
708
735
  * {@link ResolveEscalationParams.assertClaim}. */
709
736
  assertClaim?: string;
737
+ /** Recorded under `envelope.batch_filled_by[itemKey]` in the same
738
+ * statement as the fill. */
739
+ actor?: string;
710
740
  /** Resolver identity. Delivered under `$resolution` ONLY on the completing
711
741
  * item's signal. See {@link ResolveEscalationParams.resolvedBy}. */
712
742
  resolvedBy?: ResolvedByIdentity;
@@ -722,6 +752,8 @@ export interface ResolveBatchItemByMetadataParams {
722
752
  /** Merge patch for the matched row's `metadata` — distinct from the
723
753
  * `key`/`value` selector. */
724
754
  metadata?: Record<string, unknown>;
755
+ /** See {@link ResolveBatchItemParams.actor}. */
756
+ actor?: string;
725
757
  resolvedBy?: ResolvedByIdentity;
726
758
  }
727
759
  /**
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ESCALATION_TRIGGER_KEY = exports.ESCALATION_ACCUMULATED_KEY = exports.ESCALATION_ACCUMULATE_CONFIG_KEY = exports.ESCALATION_ACCUMULATE_ITEMS_KEY = exports.ESCALATION_ACCUMULATE_KEYS_KEY = exports.ESCALATION_ACCUMULATE_MAX_KEY = exports.ESCALATION_ACCUMULATE_COUNT_KEY = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_FILLED_AT_KEY = exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = void 0;
3
+ exports.ESCALATION_TRIGGER_KEY = exports.ESCALATION_ACCUMULATED_KEY = exports.ESCALATION_ACCUMULATE_CONFIG_KEY = exports.ESCALATION_ACCUMULATE_ITEMS_KEY = exports.ESCALATION_ACCUMULATE_KEYS_KEY = exports.ESCALATION_ACCUMULATE_MAX_KEY = exports.ESCALATION_ACCUMULATE_COUNT_KEY = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_FILLED_BY_KEY = exports.ESCALATION_BATCH_FILLED_AT_KEY = exports.ESCALATION_BATCH_ITEMS_KEY = exports.ESCALATION_BATCH_KEYS_KEY = exports.ESCALATION_BATCH_COUNT_KEY = exports.ESCALATION_BATCH_PENDING_KEY = void 0;
4
4
  // ─── Batch accumulation ───────────────────────────────────────────────────────
5
5
  /** Metadata facet: item keys still awaiting submission (jsonb string array).
6
6
  * `metadata @> '{"batch_pending":["x"]}'` finds rows still missing item `x`. */
@@ -19,6 +19,10 @@ exports.ESCALATION_BATCH_ITEMS_KEY = 'batch_items';
19
19
  * stamped by the DATABASE clock inside the same guarded fill statement —
20
20
  * row truth, not caller clocks. The attempt timeline for free. */
21
21
  exports.ESCALATION_BATCH_FILLED_AT_KEY = 'batch_filled_at';
22
+ /** Envelope key: per-item actors (`Record<itemKey, string>`), written by a
23
+ * fill that names an `actor` and by `filled` entries that carry one. Absent
24
+ * until the first attributed fill. */
25
+ exports.ESCALATION_BATCH_FILLED_BY_KEY = 'batch_filled_by';
22
26
  /** Item keys are non-empty strings up to this length. Any characters are
23
27
  * accepted (keys are always parameterized and stored as jsonb text); prefer
24
28
  * URL/query-friendly names (e.g. `u1-L`) for endpoint ergonomics. */
@@ -14,9 +14,9 @@ export { ILogger, LogLevel } from './logger';
14
14
  export { ExtensionType, JobCompletionOptions, JobData, JobsData, JobInterruptOptions, JobMetadata, JobOutput, JobState, JobStatus, PartialJobState, } from './job';
15
15
  export { MappingStatements } from './map';
16
16
  export { Pipe, PipeContext, PipeItem, PipeItems, PipeObject, ReduceObject, } from './pipe';
17
- export { ProviderClass, ProviderClient, ProviderConfig, ProviderTransaction, Providers, TransactionResultList, ProviderNativeClient, ProviderOptions, } from './provider';
17
+ export { ProviderClass, ProviderClient, ProviderConfig, ProviderTransaction, Providers, TransactionResultList, ProviderNativeClient, ProviderOptions, ConnectionHealthEvent, ConnectionHealthSnapshot, ConnectionLostEvent, ConnectionRestoredEvent, } from './provider';
18
18
  export { VirtualConnectParams, VirtualContext, VirtualExecParams, VirtualCronParams, VirtualExecOptions, VirtualCronOptions, VirtualInterruptOptions, VirtualInterruptParams, VirtualFlushParams, } from './virtual';
19
- export { PostgresClassType, PostgresClientOptions, PostgresClientType, PostgresConsumerGroup, PostgresPendingMessage, PostgresPoolClientType, PostgresQueryConfigType, PostgresQueryResultType, PostgresStreamMessage, PostgresStreamOptions, PostgresTransaction, } from './postgres';
19
+ export { PostgresClassType, PostgresClientOptions, PostgresClientType, PostgresConsumerGroup, PostgresPendingMessage, PostgresPoolClientType, PostgresQueryConfigType, PostgresQueryResultType, PostgresReconnectedEvent, PostgresStreamMessage, PostgresStreamOptions, PostgresTransaction, } from './postgres';
20
20
  export { ActivateMessage, CronMessage, JobMessage, JobMessageCallback, PingMessage, PongMessage, QuorumMessage, QuorumMessageCallback, QuorumProfile, RollCallMessage, RollCallOptions, SubscriptionCallback, SubscriptionOptions, SystemHealth, ThrottleMessage, ThrottleOptions, WorkMessage, } from './quorum';
21
21
  export { NatsAckPolicy, NatsAckPolicyExplicitType, NatsClassType, NatsClientType, NatsClientOptions, NatsConsumerConfigType, NatsJetStreamManager, NatsConnection, NatsJetStreamType, NatsConnectionOptions, NatsConsumerConfig, NatsConsumerInfo, NatsConsumerManager, NatsDeliveryInfo, NatsJetStreamOptions, NatsError, NatsErrorType, NatsJetStreamClient, NatsJsMsg, NatsMessageType, NatsMsgExpect, NatsPubAck, NatsPubAckType, NatsPublishOptions, NatsRetentionPolicy, NatsRetentionPolicyWorkqueueType, NatsSequenceInfo, NatsStorageMemoryType, NatsStorageType, NatsStreamConfig, NatsStreamInfo, NatsStreamManager, NatsStreamConfigType, NatsStreamInfoType, NatsStreamOptions, NatsStreamState, NatsTransaction, } from './nats';
22
22
  export { JSONSchema, StringAnyType, StringScalarType, StringStringType, SymbolMap, SymbolMaps, SymbolRanges, Symbols, SymbolSets, } from './serializer';
@@ -25,5 +25,5 @@ export { ReclaimedMessageType, RetryPolicy, RouterConfig, StreamCode, StreamConf
25
25
  export { context, Context, Counter, Meter, metrics, propagation, SpanContext, Span, SpanStatus, SpanStatusCode, SpanKind, trace, Tracer, ValueType, } from './telemetry';
26
26
  export { WorkListTaskType } from './task';
27
27
  export { TransitionMatch, TransitionRule, Transitions } from './transition';
28
- export { ConditionQueueConfig, EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, ResolveAllOrNoneItem, ResolveAllOrNoneParams, ResolveAllOrNoneBlockReason, ResolveAllOrNoneResult, EscalateToRoleParams, MigrateEscalationParams, EscalationResolution, ResolvedByIdentity, ClaimManyQuerySelector, ClaimManyByQueryParams, BatchItemOutcome, ResolveBatchItemParams, ResolveBatchItemByMetadataParams, ResolveBatchItemResult, ESCALATION_BATCH_PENDING_KEY, ESCALATION_BATCH_COUNT_KEY, ESCALATION_BATCH_KEYS_KEY, ESCALATION_BATCH_ITEMS_KEY, ESCALATION_BATCH_FILLED_AT_KEY, ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY, ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH, AccumulateConfig, AccumulatedEntry, AccumulatedItem, AccumulatorTrigger, AccumulatorResult, AccumulateReciprocalSelector, AccumulateItemOutcome, AccumulateItemParams, AccumulateItemByMetadataParams, AccumulateReciprocalResult, AccumulateItemResult, RemoveAccumulatedItemOutcome, RemoveAccumulatedItemParams, RemoveAccumulatedItemByMetadataParams, RemoveAccumulatedItemResult, ExpireEscalationResult, ESCALATION_ACCUMULATE_COUNT_KEY, ESCALATION_ACCUMULATE_MAX_KEY, ESCALATION_ACCUMULATE_KEYS_KEY, ESCALATION_ACCUMULATE_ITEMS_KEY, ESCALATION_ACCUMULATE_CONFIG_KEY, ESCALATION_ACCUMULATED_KEY, ESCALATION_TRIGGER_KEY, } from './hmsh_escalations';
28
+ export { ConditionQueueConfig, EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, ResolveAllOrNoneItem, ResolveAllOrNoneParams, ResolveAllOrNoneBlockReason, ResolveAllOrNoneResult, EscalateToRoleParams, MigrateEscalationParams, EscalationResolution, ResolvedByIdentity, ClaimManyQuerySelector, ClaimManyByQueryParams, BatchItemOutcome, ResolveBatchItemParams, ResolveBatchItemByMetadataParams, ResolveBatchItemResult, ESCALATION_BATCH_PENDING_KEY, ESCALATION_BATCH_COUNT_KEY, ESCALATION_BATCH_KEYS_KEY, ESCALATION_BATCH_ITEMS_KEY, ESCALATION_BATCH_FILLED_AT_KEY, ESCALATION_BATCH_FILLED_BY_KEY, ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY, ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH, BatchFilledEntry, AccumulateConfig, AccumulatedEntry, AccumulatedItem, AccumulatorTrigger, AccumulatorResult, AccumulateReciprocalSelector, AccumulateItemOutcome, AccumulateItemParams, AccumulateItemByMetadataParams, AccumulateReciprocalResult, AccumulateItemResult, RemoveAccumulatedItemOutcome, RemoveAccumulatedItemParams, RemoveAccumulatedItemByMetadataParams, RemoveAccumulatedItemResult, ExpireEscalationResult, ESCALATION_ACCUMULATE_COUNT_KEY, ESCALATION_ACCUMULATE_MAX_KEY, ESCALATION_ACCUMULATE_KEYS_KEY, ESCALATION_ACCUMULATE_ITEMS_KEY, ESCALATION_ACCUMULATE_CONFIG_KEY, ESCALATION_ACCUMULATED_KEY, ESCALATION_TRIGGER_KEY, } from './hmsh_escalations';
29
29
  export { EscalationVerb, EngineVerb, WorkerVerb, SystemEvent, EventsConfig } from './system_events';