@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
@@ -89,6 +89,13 @@ class ClientService {
89
89
  });
90
90
  //synchronously cache the promise (before awaiting)
91
91
  ClientService.instances.set(connectionNS, hotMeshClient);
92
+ //an init that rejects (database unavailable) is not cached for the
93
+ //life of the process; the next call initializes again
94
+ hotMeshClient.catch(() => {
95
+ if (ClientService.instances.get(connectionNS) === hotMeshClient) {
96
+ ClientService.instances.delete(connectionNS);
97
+ }
98
+ });
92
99
  //resolve, activate, and return the client
93
100
  const resolvedClient = await hotMeshClient;
94
101
  if (!readonly) {
@@ -385,9 +392,10 @@ class ClientService {
385
392
  * @private
386
393
  */
387
394
  static async shutdown() {
388
- for (const [_, hotMeshInstance] of ClientService.instances) {
389
- (await hotMeshInstance).stop();
390
- }
395
+ //a cached init that rejected must not stop the others from stopping
396
+ const instances = Array.from(ClientService.instances.values());
397
+ ClientService.instances.clear();
398
+ await Promise.allSettled(instances.map(async (hotMeshInstance) => (await hotMeshInstance).stop()));
391
399
  }
392
400
  }
393
401
  _a = ClientService;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WorkflowHandleService = void 0;
4
+ const health_1 = require("../connector/health");
4
5
  const utils_1 = require("../../modules/utils");
5
6
  const exporter_1 = require("./exporter");
6
7
  /**
@@ -243,7 +244,28 @@ class WorkflowHandleService {
243
244
  async result(config) {
244
245
  const topic = `${this.hotMesh.appId}.executed.${this.workflowId}`;
245
246
  let isResolved = false;
246
- return new Promise(async (resolve, reject) => {
247
+ return new Promise(async (rawResolve, rawReject) => {
248
+ //escalating re-checks: the executed event commits before the status
249
+ //decrement, so a job caught mid-close needs a few quick reads
250
+ const RECHECK_DELAYS_MS = [250, 1000, 5000];
251
+ //a restored database connection re-runs the quick re-checks: a
252
+ //completion NOTIFY sent while the subscription's session was being
253
+ //replaced is gone, and waiting out the steady poll is not needed
254
+ const onRestored = () => {
255
+ if (!isResolved) {
256
+ scheduleRechecks();
257
+ }
258
+ };
259
+ health_1.ConnectionHealth.on('restored', onRestored);
260
+ const release = () => health_1.ConnectionHealth.off('restored', onRestored);
261
+ const resolve = (value) => {
262
+ release();
263
+ rawResolve(value);
264
+ };
265
+ const reject = (error) => {
266
+ release();
267
+ rawReject(error);
268
+ };
247
269
  /**
248
270
  * rejects/resolves the promise based on the `throwOnError`
249
271
  * default behavior is to throw if error
@@ -265,7 +287,16 @@ class WorkflowHandleService {
265
287
  return safeReject(err);
266
288
  }
267
289
  else if (!response) {
268
- const state = await this.hotMesh.getState(`${this.hotMesh.appId}.execute`, this.workflowId);
290
+ let state;
291
+ try {
292
+ state = await this.hotMesh.getState(`${this.hotMesh.appId}.execute`, this.workflowId);
293
+ }
294
+ catch (readError) {
295
+ //the read failed (database unavailable): stay pending so the
296
+ //next check settles the result instead of leaving it hanging
297
+ isResolved = false;
298
+ throw readError;
299
+ }
269
300
  if (state.data?.done && !state.data?.$error) {
270
301
  return resolve(state.data.response);
271
302
  }
@@ -279,37 +310,8 @@ class WorkflowHandleService {
279
310
  }
280
311
  resolve(response);
281
312
  };
282
- //more expensive; fetches the entire job, not just the `status`
283
- if (config?.state) {
284
- const state = await this.hotMesh.getState(`${this.hotMesh.appId}.execute`, this.workflowId);
285
- if (state?.data?.done && !state.data?.$error) {
286
- return complete(state.data.response);
287
- }
288
- else if (state.data?.$error) {
289
- return complete(null, state.data.$error);
290
- }
291
- else if (state.metadata.err) {
292
- return complete(null, JSON.parse(state.metadata.err));
293
- }
294
- }
295
- //subscribe to 'done' topic. Await the registration: the getStatus
296
- //fallback below only covers completions that land BEFORE it reads.
297
- //Unawaited, a job that completes after the status read but before
298
- //the subscription goes active is seen by neither arm and result()
299
- //never settles — hit reliably when a bulk resolve completes many
300
- //workflows in the same instant.
301
- await this.hotMesh.sub(topic, async (_topic, state) => {
302
- this.hotMesh.unsub(topic);
303
- if (state.data.done && !state.data?.$error) {
304
- await complete(state.data?.response);
305
- }
306
- else if (state.data?.$error) {
307
- return complete(null, state.data.$error);
308
- }
309
- else if (state.metadata.err) {
310
- const error = JSON.parse(state.metadata.err);
311
- return await complete(null, error);
312
- }
313
+ const unsubscribe = () => (0, utils_1.detach)(this.hotMesh.unsub(topic), this.hotMesh.engine?.logger, 'durable-result-unsub-error', {
314
+ workflowId: this.workflowId,
313
315
  });
314
316
  //check state in case completed during wiring. One read is not
315
317
  //enough: the executed event commits before the status decrement,
@@ -327,27 +329,85 @@ class WorkflowHandleService {
327
329
  return true;
328
330
  if (status <= 0) {
329
331
  await complete();
330
- this.hotMesh.unsub(topic);
332
+ unsubscribe();
331
333
  return true;
332
334
  }
333
335
  return false;
334
336
  };
335
- if (!(await settleIfComplete())) {
337
+ //a failed check (database unavailable) is a miss, never the end of
338
+ //the wait: the next scheduled check tries again
339
+ const settle = async () => {
340
+ try {
341
+ return await settleIfComplete();
342
+ }
343
+ catch {
344
+ return isResolved;
345
+ }
346
+ };
347
+ function scheduleRechecks() {
348
+ void (async () => {
349
+ for (const delay of RECHECK_DELAYS_MS) {
350
+ await (0, utils_1.sleepFor)(delay);
351
+ if (await settle())
352
+ return;
353
+ }
354
+ })();
355
+ }
356
+ try {
357
+ //more expensive; fetches the entire job, not just the `status`
358
+ if (config?.state) {
359
+ const state = await this.hotMesh.getState(`${this.hotMesh.appId}.execute`, this.workflowId);
360
+ if (state?.data?.done && !state.data?.$error) {
361
+ return complete(state.data.response);
362
+ }
363
+ else if (state.data?.$error) {
364
+ return complete(null, state.data.$error);
365
+ }
366
+ else if (state.metadata.err) {
367
+ return complete(null, JSON.parse(state.metadata.err));
368
+ }
369
+ }
370
+ //subscribe to 'done' topic. Await the registration: the getStatus
371
+ //fallback below only covers completions that land BEFORE it reads.
372
+ //Unawaited, a job that completes after the status read but before
373
+ //the subscription goes active is seen by neither arm and result()
374
+ //never settles — hit reliably when a bulk resolve completes many
375
+ //workflows in the same instant.
376
+ await this.hotMesh.sub(topic, async (_topic, state) => {
377
+ unsubscribe();
378
+ if (state.data.done && !state.data?.$error) {
379
+ await complete(state.data?.response);
380
+ }
381
+ else if (state.data?.$error) {
382
+ return complete(null, state.data.$error);
383
+ }
384
+ else if (state.metadata.err) {
385
+ const error = JSON.parse(state.metadata.err);
386
+ return await complete(null, error);
387
+ }
388
+ });
389
+ }
390
+ catch (setupError) {
391
+ //the wait could not be established; the caller sees the error
392
+ if (!isResolved) {
393
+ isResolved = true;
394
+ reject(setupError);
395
+ }
396
+ return;
397
+ }
398
+ if (!(await settle())) {
336
399
  void (async () => {
337
- const RECHECK_DELAYS_MS = [250, 1000, 5000];
338
400
  for (const delay of RECHECK_DELAYS_MS) {
339
401
  await (0, utils_1.sleepFor)(delay);
340
- if (await settleIfComplete())
402
+ if (await settle())
341
403
  return;
342
404
  }
343
405
  while (!isResolved) {
344
406
  await (0, utils_1.sleepFor)(30000);
345
- if (await settleIfComplete())
407
+ if (await settle())
346
408
  return;
347
409
  }
348
- })().catch(() => {
349
- //the subscription remains the primary completion arm
350
- });
410
+ })();
351
411
  }
352
412
  });
353
413
  }
@@ -486,7 +486,7 @@ class WorkerService {
486
486
  const worker = new WorkerService();
487
487
  worker.activityRunner = await worker.initActivityWorker(config, activityTopic);
488
488
  worker.workflowRunner = await worker.initWorkflowWorker(config, taskQueue, workflowFunctionName, workflowTopic, workflowFunction);
489
- search_1.Search.configureSearchIndex(worker.workflowRunner, config.search);
489
+ (0, utils_1.detach)(search_1.Search.configureSearchIndex(worker.workflowRunner, config.search), worker.workflowRunner?.engine?.logger, 'durable-worker-search-index-error');
490
490
  await WorkerService.activateWorkflow(worker.workflowRunner);
491
491
  // Fire system.worker.{taskQueue}.started post-init (best-effort).
492
492
  if (config.events?.publish) {
@@ -1070,9 +1070,10 @@ class WorkerService {
1070
1070
  * @private
1071
1071
  */
1072
1072
  static async shutdown() {
1073
- for (const [_, hotMeshInstance] of WorkerService.instances) {
1074
- (await hotMeshInstance).stop();
1075
- }
1073
+ //a cached init that rejected must not stop the others from stopping
1074
+ const instances = Array.from(WorkerService.instances.values());
1075
+ WorkerService.instances.clear();
1076
+ await Promise.allSettled(instances.map(async (hotMeshInstance) => (await hotMeshInstance).stop()));
1076
1077
  }
1077
1078
  }
1078
1079
  _a = WorkerService;
@@ -1103,6 +1104,13 @@ WorkerService.getHotMesh = async (workflowTopic, config, options) => {
1103
1104
  },
1104
1105
  });
1105
1106
  WorkerService.instances.set(targetTopic, hotMeshClient);
1107
+ //an init that rejects (database unavailable) is not cached for the
1108
+ //life of the process; the next call initializes again
1109
+ hotMeshClient.catch(() => {
1110
+ if (WorkerService.instances.get(targetTopic) === hotMeshClient) {
1111
+ WorkerService.instances.delete(targetTopic);
1112
+ }
1113
+ });
1106
1114
  await WorkerService.activateWorkflow(await hotMeshClient);
1107
1115
  return hotMeshClient;
1108
1116
  };
@@ -111,6 +111,20 @@ import { ConditionQueueConfig } from '../../../types/hmsh_escalations';
111
111
  * `resolve()` on a batch row remains an admin override that resolves the
112
112
  * whole row with the payload given.
113
113
  *
114
+ * Entries already satisfied before the wait begins go in `filled`, keyed
115
+ * by item key with their `payload`, `at` (from the source of record), and
116
+ * optional `actor`. They start the row with that progress and are
117
+ * delivered with the collection. A `filled` that covers every key throws,
118
+ * so the caller skips the wait.
119
+ *
120
+ * ```typescript
121
+ * await Durable.workflow.condition(signalId, {
122
+ * role: 'assembly',
123
+ * batch: ['cut', 'weld', 'paint'],
124
+ * filled: { cut: { payload: { station: 'cut-1' }, at: cutAt, actor: 'user-7' } },
125
+ * });
126
+ * ```
127
+ *
114
128
  * ## Placement: call escalation-bearing waits from main workflow code
115
129
  *
116
130
  * The resolve/signal delivery pipeline routes to the main flow's waiter.
@@ -117,6 +117,20 @@ const didRun_1 = require("./didRun");
117
117
  * `resolve()` on a batch row remains an admin override that resolves the
118
118
  * whole row with the payload given.
119
119
  *
120
+ * Entries already satisfied before the wait begins go in `filled`, keyed
121
+ * by item key with their `payload`, `at` (from the source of record), and
122
+ * optional `actor`. They start the row with that progress and are
123
+ * delivered with the collection. A `filled` that covers every key throws,
124
+ * so the caller skips the wait.
125
+ *
126
+ * ```typescript
127
+ * await Durable.workflow.condition(signalId, {
128
+ * role: 'assembly',
129
+ * batch: ['cut', 'weld', 'paint'],
130
+ * filled: { cut: { payload: { station: 'cut-1' }, at: cutAt, actor: 'user-7' } },
131
+ * });
132
+ * ```
133
+ *
120
134
  * ## Placement: call escalation-bearing waits from main workflow code
121
135
  *
122
136
  * The resolve/signal delivery pipeline routes to the main flow's waiter.
@@ -126,8 +126,8 @@ async function runJobCompletionTasks(instance, context, options = {}, transactio
126
126
  await publishPermanentSubscribers(instance, context, jobOutput, options.emit, transaction);
127
127
  }
128
128
  else {
129
- publishOneTimeSubscribers(instance, context, jobOutput, options.emit);
130
- publishPermanentSubscribers(instance, context, jobOutput, options.emit);
129
+ (0, utils_1.detach)(publishOneTimeSubscribers(instance, context, jobOutput, options.emit), instance.logger, 'engine-publish-onetime-subscribers-error');
130
+ (0, utils_1.detach)(publishPermanentSubscribers(instance, context, jobOutput, options.emit), instance.logger, 'engine-publish-permanent-subscribers-error');
131
131
  }
132
132
  }
133
133
  if (!options.emit) {
@@ -135,7 +135,7 @@ async function runJobCompletionTasks(instance, context, options = {}, transactio
135
135
  await instance.taskService.registerJobForCleanup(context.metadata.jid, resolveExpires(context, options), options, transaction);
136
136
  }
137
137
  else {
138
- instance.taskService.registerJobForCleanup(context.metadata.jid, resolveExpires(context, options), options);
138
+ (0, utils_1.detach)(instance.taskService.registerJobForCleanup(context.metadata.jid, resolveExpires(context, options), options), instance.logger, 'engine-register-cleanup-error');
139
139
  }
140
140
  }
141
141
  return msgId;
@@ -81,7 +81,7 @@ async function signalAll(instance, hookTopic, data, keyResolver, queryFacets = [
81
81
  keyResolver.scrub || false,
82
82
  JSON.stringify(data),
83
83
  ].join(key_1.VALSEP)));
84
- instance.subscribe.publish(key_1.KeyType.QUORUM, { type: 'work', originator: instance.guid }, instance.appId);
84
+ (0, utils_1.detach)(instance.subscribe.publish(key_1.KeyType.QUORUM, { type: 'work', originator: instance.guid }, instance.appId), instance.logger, 'engine-signal-work-publish-error');
85
85
  }
86
86
  return workItems;
87
87
  }
@@ -91,11 +91,11 @@ async function signalAll(instance, hookTopic, data, keyResolver, queryFacets = [
91
91
  }
92
92
  exports.signalAll = signalAll;
93
93
  async function processWebHooks(instance, signalFn) {
94
- instance.taskService.processWebHooks(signalFn);
94
+ (0, utils_1.detach)(instance.taskService.processWebHooks(signalFn), instance.logger, 'engine-process-webhooks-error');
95
95
  }
96
96
  exports.processWebHooks = processWebHooks;
97
97
  async function processTimeHooks(instance, hookTimeFn) {
98
- instance.taskService.processTimeHooks(hookTimeFn);
98
+ (0, utils_1.detach)(instance.taskService.processTimeHooks(hookTimeFn), instance.logger, 'engine-process-timehooks-error');
99
99
  }
100
100
  exports.processTimeHooks = processTimeHooks;
101
101
  async function throttle(instance, delayInMillis) {
@@ -1,10 +1,13 @@
1
- import { AccumulateConfig } from '../../types/hmsh_escalations';
1
+ import { AccumulateConfig, BatchFilledEntry } from '../../types/hmsh_escalations';
2
2
  /**
3
3
  * Folds a `batch` declaration into the escalation's storage shape:
4
4
  * queryable facets in `metadata` (`batch_pending`, `batch_count`,
5
5
  * `batch_keys`) and the payload accumulator in `envelope`
6
6
  * (`batch_items: {}`). `partialOnTimeout` is stored beside the items so
7
- * the expiry statement delivers the filled items instead of `false`. Pure
7
+ * the expiry statement delivers the filled items instead of `false`.
8
+ * `filled` entries start satisfied: they are left out of `batch_pending`
9
+ * and written into `batch_items`, `batch_filled_at`, and (when an entry
10
+ * names an actor) `batch_filled_by`. Pure
8
11
  * and deterministic — safe on the replayed `condition()` path. Throws
9
12
  * synchronously on an invalid declaration so a bad batch never reaches a
10
13
  * durable write.
@@ -12,7 +15,8 @@ import { AccumulateConfig } from '../../types/hmsh_escalations';
12
15
  export declare function foldBatchConfig<T extends {
13
16
  batch?: string[];
14
17
  partialOnTimeout?: boolean;
18
+ filled?: Record<string, BatchFilledEntry>;
15
19
  accumulate?: AccumulateConfig;
16
20
  metadata?: Record<string, unknown>;
17
21
  envelope?: Record<string, unknown>;
18
- }>(config: T): Omit<T, 'batch' | 'partialOnTimeout'>;
22
+ }>(config: T): Omit<T, 'batch' | 'partialOnTimeout' | 'filled'>;
@@ -10,24 +10,78 @@ const RESERVED_METADATA_KEYS = new Set([
10
10
  const RESERVED_ENVELOPE_KEYS = new Set([
11
11
  hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY,
12
12
  hmsh_escalations_1.ESCALATION_BATCH_FILLED_AT_KEY,
13
+ hmsh_escalations_1.ESCALATION_BATCH_FILLED_BY_KEY,
13
14
  hmsh_escalations_1.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY,
14
15
  ]);
16
+ /**
17
+ * Validates `filled` against the declared keys and splits it into the
18
+ * envelope maps. Pure: `at` is normalized from the caller's value, never
19
+ * read from a clock.
20
+ */
21
+ function foldFilledEntries(batch, filled) {
22
+ const folded = {
23
+ pending: [...batch],
24
+ items: {},
25
+ filledAt: {},
26
+ filledBy: {},
27
+ };
28
+ if (filled === undefined)
29
+ return folded;
30
+ if (!filled || typeof filled !== 'object' || Array.isArray(filled)) {
31
+ throw new Error('filled must be an object keyed by batch item key');
32
+ }
33
+ for (const [key, entry] of Object.entries(filled)) {
34
+ if (!batch.includes(key)) {
35
+ throw new Error(`filled key '${key}' is not declared in batch`);
36
+ }
37
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
38
+ throw new Error(`filled['${key}'] must be an object`);
39
+ }
40
+ const { payload, at, actor } = entry;
41
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
42
+ throw new Error(`filled['${key}'].payload must be an object`);
43
+ }
44
+ const time = typeof at === 'string' ? Date.parse(at) : NaN;
45
+ if (Number.isNaN(time)) {
46
+ throw new Error(`filled['${key}'].at must be an ISO-8601 timestamp`);
47
+ }
48
+ if (actor !== undefined &&
49
+ (typeof actor !== 'string' || actor.length === 0)) {
50
+ throw new Error(`filled['${key}'].actor must be a non-empty string`);
51
+ }
52
+ folded.items[key] = payload;
53
+ folded.filledAt[key] = new Date(time).toISOString();
54
+ if (actor !== undefined)
55
+ folded.filledBy[key] = actor;
56
+ }
57
+ folded.pending = batch.filter((key) => !(key in folded.items));
58
+ if (folded.pending.length === 0) {
59
+ throw new Error('filled satisfies every batch key; there is nothing to wait for');
60
+ }
61
+ return folded;
62
+ }
15
63
  /**
16
64
  * Folds a `batch` declaration into the escalation's storage shape:
17
65
  * queryable facets in `metadata` (`batch_pending`, `batch_count`,
18
66
  * `batch_keys`) and the payload accumulator in `envelope`
19
67
  * (`batch_items: {}`). `partialOnTimeout` is stored beside the items so
20
- * the expiry statement delivers the filled items instead of `false`. Pure
68
+ * the expiry statement delivers the filled items instead of `false`.
69
+ * `filled` entries start satisfied: they are left out of `batch_pending`
70
+ * and written into `batch_items`, `batch_filled_at`, and (when an entry
71
+ * names an actor) `batch_filled_by`. Pure
21
72
  * and deterministic — safe on the replayed `condition()` path. Throws
22
73
  * synchronously on an invalid declaration so a bad batch never reaches a
23
74
  * durable write.
24
75
  */
25
76
  function foldBatchConfig(config) {
26
- const { batch, partialOnTimeout, ...rest } = config;
77
+ const { batch, partialOnTimeout, filled, ...rest } = config;
27
78
  if (!batch) {
28
79
  if (partialOnTimeout !== undefined) {
29
80
  throw new Error('partialOnTimeout requires a batch declaration');
30
81
  }
82
+ if (filled !== undefined) {
83
+ throw new Error('filled requires a batch declaration');
84
+ }
31
85
  return rest;
32
86
  }
33
87
  if (rest.accumulate) {
@@ -62,18 +116,22 @@ function foldBatchConfig(config) {
62
116
  throw new Error(`envelope key '${reserved}' is reserved for batch state`);
63
117
  }
64
118
  }
119
+ const fills = foldFilledEntries(batch, filled);
65
120
  return {
66
121
  ...rest,
67
122
  metadata: {
68
123
  ...(rest.metadata ?? {}),
69
- [hmsh_escalations_1.ESCALATION_BATCH_PENDING_KEY]: [...batch],
70
- [hmsh_escalations_1.ESCALATION_BATCH_COUNT_KEY]: batch.length,
124
+ [hmsh_escalations_1.ESCALATION_BATCH_PENDING_KEY]: fills.pending,
125
+ [hmsh_escalations_1.ESCALATION_BATCH_COUNT_KEY]: fills.pending.length,
71
126
  [hmsh_escalations_1.ESCALATION_BATCH_KEYS_KEY]: [...batch],
72
127
  },
73
128
  envelope: {
74
129
  ...(rest.envelope ?? {}),
75
- [hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY]: {},
76
- [hmsh_escalations_1.ESCALATION_BATCH_FILLED_AT_KEY]: {},
130
+ [hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY]: fills.items,
131
+ [hmsh_escalations_1.ESCALATION_BATCH_FILLED_AT_KEY]: fills.filledAt,
132
+ ...(Object.keys(fills.filledBy).length
133
+ ? { [hmsh_escalations_1.ESCALATION_BATCH_FILLED_BY_KEY]: fills.filledBy }
134
+ : {}),
77
135
  ...(partialOnTimeout
78
136
  ? { [hmsh_escalations_1.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY]: true }
79
137
  : {}),
@@ -233,8 +233,10 @@ export declare class EscalationClientService {
233
233
  * from multiple principals. Pass `assertClaim` to opt into the same
234
234
  * claim-lock assertion as `resolve()`. Pass `metadata` to merge an outcome
235
235
  * patch into the row's GIN-indexed metadata in the same UPDATE (reserved
236
- * batch keys cannot be overridden). Pass `resolvedBy` on submissions to
237
- * deliver `$resolution` provenance with the completing item's signal.
236
+ * batch keys cannot be overridden). Pass `actor` to record who filled
237
+ * the item under `envelope.batch_filled_by[itemKey]` in the same UPDATE.
238
+ * Pass `resolvedBy` on submissions to deliver `$resolution` provenance
239
+ * with the completing item's signal.
238
240
  *
239
241
  * A duplicate submission of an already-filled key returns
240
242
  * `outcome: 'duplicate-item'` without touching the row — safe under
@@ -530,8 +530,10 @@ class EscalationClientService {
530
530
  * from multiple principals. Pass `assertClaim` to opt into the same
531
531
  * claim-lock assertion as `resolve()`. Pass `metadata` to merge an outcome
532
532
  * patch into the row's GIN-indexed metadata in the same UPDATE (reserved
533
- * batch keys cannot be overridden). Pass `resolvedBy` on submissions to
534
- * deliver `$resolution` provenance with the completing item's signal.
533
+ * batch keys cannot be overridden). Pass `actor` to record who filled
534
+ * the item under `envelope.batch_filled_by[itemKey]` in the same UPDATE.
535
+ * Pass `resolvedBy` on submissions to deliver `$resolution` provenance
536
+ * with the completing item's signal.
535
537
  *
536
538
  * A duplicate submission of an already-filled key returns
537
539
  * `outcome: 'duplicate-item'` without touching the row — safe under
@@ -1,7 +1,8 @@
1
- import { AccumulateConfig } from '../../types/hmsh_escalations';
1
+ import { AccumulateConfig, BatchFilledEntry } from '../../types/hmsh_escalations';
2
2
  type Foldable = {
3
3
  batch?: string[];
4
4
  partialOnTimeout?: boolean;
5
+ filled?: Record<string, BatchFilledEntry>;
5
6
  accumulate?: AccumulateConfig;
6
7
  metadata?: Record<string, unknown>;
7
8
  envelope?: Record<string, unknown>;
@@ -12,5 +13,5 @@ type Foldable = {
12
13
  * config through untouched. The single entry point for both the
13
14
  * `condition()` path and standalone `create()`.
14
15
  */
15
- export declare function foldEscalationConfig<T extends Foldable>(config: T): Omit<T, 'batch' | 'partialOnTimeout' | 'accumulate'>;
16
+ export declare function foldEscalationConfig<T extends Foldable>(config: T): Omit<T, 'batch' | 'partialOnTimeout' | 'filled' | 'accumulate'>;
16
17
  export {};
@@ -10,19 +10,30 @@ const batch_1 = require("./batch");
10
10
  * `condition()` path and standalone `create()`.
11
11
  */
12
12
  function foldEscalationConfig(config) {
13
- const { batch, partialOnTimeout, accumulate, ...rest } = config;
13
+ const { batch, partialOnTimeout, filled, accumulate, ...rest } = config;
14
14
  if (batch) {
15
15
  if (accumulate) {
16
16
  throw new Error('accumulate and batch are mutually exclusive');
17
17
  }
18
- return (0, batch_1.foldBatchConfig)({ ...rest, batch, partialOnTimeout });
18
+ return (0, batch_1.foldBatchConfig)({
19
+ ...rest,
20
+ batch,
21
+ partialOnTimeout,
22
+ filled,
23
+ });
19
24
  }
20
25
  if (accumulate) {
26
+ if (filled !== undefined) {
27
+ throw new Error('filled applies to batch only');
28
+ }
21
29
  return (0, accumulate_1.foldAccumulateConfig)({ ...rest, accumulate });
22
30
  }
23
31
  if (partialOnTimeout !== undefined) {
24
32
  throw new Error('partialOnTimeout requires a batch declaration');
25
33
  }
34
+ if (filled !== undefined) {
35
+ throw new Error('filled requires a batch declaration');
36
+ }
26
37
  return rest;
27
38
  }
28
39
  exports.foldEscalationConfig = foldEscalationConfig;
@@ -68,4 +68,4 @@ export { ESCALATION_RESOLUTION_KEY } from './client';
68
68
  export { foldBatchConfig } from './batch';
69
69
  export { foldAccumulateConfig, assertAccumulateItemKey } from './accumulate';
70
70
  export { foldEscalationConfig } from './fold';
71
- export { 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, 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 '../../types/hmsh_escalations';
71
+ export { 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, 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 '../../types/hmsh_escalations';
@@ -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_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_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 = exports.foldEscalationConfig = exports.assertAccumulateItemKey = exports.foldAccumulateConfig = exports.foldBatchConfig = exports.ESCALATION_RESOLUTION_KEY = exports.EscalationClientService = exports.Escalations = 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_ITEM_KEY_MAX_LENGTH = exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = 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 = exports.foldEscalationConfig = exports.assertAccumulateItemKey = exports.foldAccumulateConfig = exports.foldBatchConfig = exports.ESCALATION_RESOLUTION_KEY = exports.EscalationClientService = exports.Escalations = void 0;
4
4
  const utils_1 = require("../../modules/utils");
5
5
  const client_1 = require("./client");
6
6
  Object.defineProperty(exports, "EscalationClientService", { enumerable: true, get: function () { return client_1.EscalationClientService; } });
@@ -84,6 +84,7 @@ Object.defineProperty(exports, "ESCALATION_BATCH_COUNT_KEY", { enumerable: true,
84
84
  Object.defineProperty(exports, "ESCALATION_BATCH_KEYS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_KEYS_KEY; } });
85
85
  Object.defineProperty(exports, "ESCALATION_BATCH_ITEMS_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY; } });
86
86
  Object.defineProperty(exports, "ESCALATION_BATCH_FILLED_AT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_FILLED_AT_KEY; } });
87
+ Object.defineProperty(exports, "ESCALATION_BATCH_FILLED_BY_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_FILLED_BY_KEY; } });
87
88
  Object.defineProperty(exports, "ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY; } });
88
89
  Object.defineProperty(exports, "ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH; } });
89
90
  Object.defineProperty(exports, "ESCALATION_ACCUMULATE_COUNT_KEY", { enumerable: true, get: function () { return hmsh_escalations_1.ESCALATION_ACCUMULATE_COUNT_KEY; } });
@@ -28,6 +28,8 @@ const utils_1 = require("../../modules/utils");
28
28
  const factory_1 = require("../connector/factory");
29
29
  const logger_1 = require("../logger");
30
30
  const router_1 = require("../router");
31
+ const stream_1 = require("../stream");
32
+ const registry_1 = require("../stream/registry");
31
33
  // Submodules
32
34
  const Validation = __importStar(require("./validation"));
33
35
  const Init = __importStar(require("./init"));
@@ -193,13 +195,13 @@ class HotMesh {
193
195
  const quorum = instance.quorum;
194
196
  const engineGuid = instance.guid;
195
197
  instance.engine.router.setDuressCallback((snapshot) => {
196
- quorum.pub({
198
+ (0, utils_1.detach)(quorum.pub({
197
199
  type: 'duress',
198
200
  originator: engineGuid,
199
201
  duress_score_ms: snapshot.score_ms,
200
202
  throttle_ms: snapshot.throttle_ms,
201
203
  level: snapshot.level,
202
- });
204
+ }), instance.logger, 'hotmesh-duress-publish-error');
203
205
  });
204
206
  }
205
207
  await Init.doWork(instance, config, instance.logger);
@@ -500,8 +502,19 @@ class HotMesh {
500
502
  static async stop() {
501
503
  if (!this.disconnecting) {
502
504
  this.disconnecting = true;
503
- await router_1.Router.stopConsuming();
504
- await factory_1.ConnectorService.disconnectAll();
505
+ try {
506
+ await router_1.Router.stopConsuming();
507
+ //streams outside a consuming router (extra engines, clients,
508
+ //readonly routers) stop their pollers before the disconnect
509
+ await stream_1.StreamService.stopAll();
510
+ //the stopped consumers are forgotten so a later init in this
511
+ //process starts live ones instead of reusing stopped routers
512
+ registry_1.StreamConsumerRegistry.clear();
513
+ await factory_1.ConnectorService.disconnectAll();
514
+ }
515
+ finally {
516
+ this.disconnecting = false;
517
+ }
505
518
  }
506
519
  }
507
520
  /**