@hotmeshio/hotmesh 0.28.1 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.28.1",
3
+ "version": "0.29.1",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -52,6 +52,7 @@
52
52
  "test:durable:unknown": "vitest run tests/durable/unknown/postgres.test.ts",
53
53
  "test:durable:escalations": "HMSH_LOGLEVEL=info vitest run tests/durable/escalations",
54
54
  "test:durable:escalations-batch": "HMSH_LOGLEVEL=info vitest run tests/durable/escalations-batch",
55
+ "test:durable:escalations-accumulate": "HMSH_LOGLEVEL=info vitest run tests/durable/escalations-accumulate",
55
56
  "test:durable:exporter": "HMSH_LOGLEVEL=info vitest run tests/durable/exporter",
56
57
  "test:durable:exporter:debug": "EXPORT_DEBUG=1 HMSH_LOGLEVEL=error vitest run tests/durable/basic/postgres.test.ts",
57
58
  "test:durable:codec": "vitest run tests/durable/codec/postgres.test.ts",
@@ -318,10 +318,13 @@ declare class Hook extends Activity {
318
318
  /**
319
319
  * The timeout won the race: transition the wait's escalation row
320
320
  * `pending → expired` so the worklist stops offering work whose workflow
321
- * has already resumed with `false`, and a late resolve fails as
322
- * already-expired instead of delivering a payload into the void. The
323
- * UPDATE is guarded by status='pending' — when the signal won (row
324
- * already resolved) or the wait carried no escalation, it is a no-op.
321
+ * has already resumed, and a late resolve fails as already-expired
322
+ * instead of delivering a payload into the void. The UPDATE is guarded
323
+ * by status='pending'. Returns what the row delivers to the waiter (an
324
+ * accumulator's collection, set as `resolver_payload` in the same
325
+ * UPDATE), and `settledElsewhere` when a row exists but a resolve or
326
+ * cancel already moved it off `pending`, so the caller skips Leg2. With
327
+ * no row (the wait carried no escalation) the timeout proceeds as usual.
325
328
  */
326
329
  private expireEscalationOnTimeout;
327
330
  }
@@ -370,12 +370,16 @@ class Hook extends activity_1.Activity {
370
370
  const row = execResults[execResults.length - 1];
371
371
  if (row?.id) {
372
372
  const ts = new Date().toISOString();
373
- const updatedAt = row.updated_at ? new Date(row.updated_at).toISOString() : ts;
373
+ const updatedAt = row.updated_at
374
+ ? new Date(row.updated_at).toISOString()
375
+ : ts;
374
376
  const publish = (verb, extras) => void Promise.resolve(store.eventsPublish({
375
377
  event_id: `${row.id}:${verb}:${updatedAt}`,
376
378
  type: `system.escalation.${row.id}.${verb}`,
377
379
  ts,
378
- namespace: row.namespace ?? this.engine.namespace ?? this.engine.appId,
380
+ namespace: row.namespace ??
381
+ this.engine.namespace ??
382
+ this.engine.appId,
379
383
  app_id: row.app_id ?? this.engine.appId,
380
384
  workflow_id: row.workflow_id ?? undefined,
381
385
  topic: row.topic ?? undefined,
@@ -385,7 +389,9 @@ class Hook extends activity_1.Activity {
385
389
  span_id: row.span_id ?? undefined,
386
390
  ...extras,
387
391
  data: row,
388
- })).catch(() => { });
392
+ })).catch(() => {
393
+ /* best-effort */
394
+ });
389
395
  publish('created');
390
396
  // A born-assigned row is created AND claimed in the same Leg1
391
397
  // commit — state both, in that order, so hand-off consumers act
@@ -418,7 +424,8 @@ class Hook extends activity_1.Activity {
418
424
  return v;
419
425
  const out = {};
420
426
  for (const [k, val] of Object.entries(v)) {
421
- out[k] = typeof val === 'string' ? pipe_1.Pipe.resolve(val, this.context) : val;
427
+ out[k] =
428
+ typeof val === 'string' ? pipe_1.Pipe.resolve(val, this.context) : val;
422
429
  }
423
430
  return out;
424
431
  };
@@ -444,8 +451,10 @@ class Hook extends activity_1.Activity {
444
451
  };
445
452
  // Skip the INSERT when no escalation fields resolved — this happens when
446
453
  // the factory waiter runs for a condition() call that had no queueConfig.
447
- if (params.role == null && params.type == null &&
448
- params.priority == null && params.metadata == null &&
454
+ if (params.role == null &&
455
+ params.type == null &&
456
+ params.priority == null &&
457
+ params.metadata == null &&
449
458
  params.assignee == null)
450
459
  return null;
451
460
  const signalKey = await this.deriveEscalationSignalKey();
@@ -516,7 +525,8 @@ class Hook extends activity_1.Activity {
516
525
  // a sibling branch for every activity but its own, so its expected-pipe
517
526
  // resolves against output that does not exist in this flow (which is how
518
527
  // execHook-context waits were writing signal_key-less escalation rows).
519
- return (forTopic.find((rule) => rule.to === this.metadata.aid) ?? forTopic[0]);
528
+ return (forTopic.find((rule) => rule.to === this.metadata.aid) ??
529
+ forTopic[0]);
520
530
  }
521
531
  /**
522
532
  * Register the time hook (sleep) inside the Leg1 transaction.
@@ -678,24 +688,42 @@ class Hook extends activity_1.Activity {
678
688
  error: e.message,
679
689
  });
680
690
  }
681
- await this.expireEscalationOnTimeout();
691
+ const expiry = await this.expireEscalationOnTimeout();
692
+ if (expiry.settledElsewhere) {
693
+ // A resolve or cancel committed first and its wake is already
694
+ // durable; a second Leg2 here would race it.
695
+ this.logger.debug('hook-timeout-settled-elsewhere', {
696
+ jid: jobId,
697
+ aid: this.metadata.aid,
698
+ });
699
+ return;
700
+ }
701
+ if (expiry.delivered !== undefined) {
702
+ // The expired row delivers a collection: it rides the hook data so
703
+ // the waiter's timeout marker carries it to condition().
704
+ this.data = { ...this.data, data: expiry.delivered };
705
+ }
682
706
  }
683
707
  await this.processEvent(stream_1.StreamStatus.SUCCESS, 200, 'hook');
684
708
  }
685
709
  /**
686
710
  * The timeout won the race: transition the wait's escalation row
687
711
  * `pending → expired` so the worklist stops offering work whose workflow
688
- * has already resumed with `false`, and a late resolve fails as
689
- * already-expired instead of delivering a payload into the void. The
690
- * UPDATE is guarded by status='pending' — when the signal won (row
691
- * already resolved) or the wait carried no escalation, it is a no-op.
712
+ * has already resumed, and a late resolve fails as already-expired
713
+ * instead of delivering a payload into the void. The UPDATE is guarded
714
+ * by status='pending'. Returns what the row delivers to the waiter (an
715
+ * accumulator's collection, set as `resolver_payload` in the same
716
+ * UPDATE), and `settledElsewhere` when a row exists but a resolve or
717
+ * cancel already moved it off `pending`, so the caller skips Leg2. With
718
+ * no row (the wait carried no escalation) the timeout proceeds as usual.
692
719
  */
693
720
  async expireEscalationOnTimeout() {
721
+ const proceed = { settledElsewhere: false };
694
722
  if (!this.config.escalation)
695
- return;
723
+ return proceed;
696
724
  const store = this.store;
697
725
  if (typeof store.expireEscalationBySignalKey !== 'function')
698
- return;
726
+ return proceed;
699
727
  // Hydration here is THROWAWAY. getState() REPLACES this.context with
700
728
  // restored job state, which does not carry the per-message dimensional
701
729
  // address (dad) — the stream message is its only carrier for this leg.
@@ -715,10 +743,17 @@ class Hook extends activity_1.Activity {
715
743
  const appId = this.engine.appId;
716
744
  const namespace = this.engine.namespace ?? appId;
717
745
  const signalKey = await this.deriveEscalationSignalKey();
718
- const row = await store.expireEscalationBySignalKey(signalKey, namespace, appId);
746
+ const expiry = await store.expireEscalationBySignalKey(signalKey, namespace, appId);
747
+ const row = expiry && 'entry' in expiry ? expiry.entry : expiry;
748
+ const priorStatus = expiry?.priorStatus ?? null;
749
+ if (!row?.id && priorStatus && priorStatus !== 'pending') {
750
+ return { settledElsewhere: true };
751
+ }
719
752
  if (row?.id && store.eventsPublish) {
720
753
  const ts = new Date().toISOString();
721
- const updatedAt = row.updated_at ? new Date(row.updated_at).toISOString() : ts;
754
+ const updatedAt = row.updated_at
755
+ ? new Date(row.updated_at).toISOString()
756
+ : ts;
722
757
  void Promise.resolve(store.eventsPublish({
723
758
  event_id: `${row.id}:expired:${updatedAt}`,
724
759
  type: `system.escalation.${row.id}.expired`,
@@ -732,14 +767,21 @@ class Hook extends activity_1.Activity {
732
767
  trace_id: row.trace_id ?? undefined,
733
768
  span_id: row.span_id ?? undefined,
734
769
  data: row,
735
- })).catch(() => { });
770
+ })).catch(() => {
771
+ /* best-effort */
772
+ });
736
773
  }
774
+ const delivered = row?.resolver_payload;
775
+ return delivered && typeof delivered === 'object'
776
+ ? { delivered, settledElsewhere: false }
777
+ : proceed;
737
778
  }
738
779
  catch (e) {
739
780
  this.logger.debug('hook-timeout-escalation-expire', {
740
781
  topic: this.config.hook?.topic,
741
782
  error: e.message,
742
783
  });
784
+ return proceed;
743
785
  }
744
786
  finally {
745
787
  this.context = dispatchContext;
@@ -1,4 +1,4 @@
1
- declare const APP_VERSION = "18";
1
+ declare const APP_VERSION = "19";
2
2
  declare const APP_ID = "durable";
3
3
  /**
4
4
  * returns a new durable workflow schema
@@ -6,10 +6,10 @@ exports.APP_ID = exports.APP_VERSION = exports.getWorkflowYAML = void 0;
6
6
  // schema upgrade and hot-swap to it (see WorkerService.activateWorkflow and
7
7
  // ClientService.deployAndActivate). Changing the YAML without a bump leaves
8
8
  // every already-deployed database on the old schema forever. Numeric string —
9
- // compared with `Number()` for ordering. (v18: assign-at-creation — the
10
- // escalation blocks forward queueConfig.assignee/durationMinutes so a
11
- // condition() row is born assigned in the Leg1 commit.)
12
- const APP_VERSION = '18';
9
+ // compared with `Number()` for ordering. (v19: the timeout markers carry
10
+ // `data`, so an accumulator row delivers its collection to condition()
11
+ // when the timer wins; a plain timeout still resumes with false.)
12
+ const APP_VERSION = '19';
13
13
  exports.APP_VERSION = APP_VERSION;
14
14
  const APP_ID = 'durable';
15
15
  exports.APP_ID = APP_ID;
@@ -423,7 +423,7 @@ const getWorkflowYAML = (app, version) => {
423
423
  - [type, wait, data, '{$self.hook.data}', ac, '{$self.output.metadata.ac}', au, '{$self.output.metadata.au}']
424
424
  - ['{@object.create}']
425
425
  - '@pipe':
426
- - [timedOut, true, ac, '{$self.output.metadata.ac}', au, '{$self.output.metadata.au}']
426
+ - [timedOut, true, data, '{$self.hook.data.data}', ac, '{$self.output.metadata.ac}', au, '{$self.output.metadata.au}']
427
427
  - ['{@object.create}']
428
428
  - ['{@conditional.ternary}']
429
429
  - ['{@object.create}']
@@ -1240,7 +1240,7 @@ const getWorkflowYAML = (app, version) => {
1240
1240
  - [type, wait, data, '{$self.hook.data}', ac, '{$self.output.metadata.ac}', au, '{$self.output.metadata.au}']
1241
1241
  - ['{@object.create}']
1242
1242
  - '@pipe':
1243
- - [timedOut, true, ac, '{$self.output.metadata.ac}', au, '{$self.output.metadata.au}']
1243
+ - [timedOut, true, data, '{$self.hook.data.data}', ac, '{$self.output.metadata.ac}', au, '{$self.output.metadata.au}']
1244
1244
  - ['{@object.create}']
1245
1245
  - ['{@conditional.ternary}']
1246
1246
  - ['{@object.create}']
@@ -2013,7 +2013,7 @@ const getWorkflowYAML = (app, version) => {
2013
2013
  - [type, wait, data, '{$self.hook.data}', ac, '{$job.metadata.jc}', au, '{$self.output.metadata.au}']
2014
2014
  - ['{@object.create}']
2015
2015
  - '@pipe':
2016
- - [type, wait, timedOut, true, ac, '{$self.output.metadata.ac}', au, '{$self.output.metadata.au}']
2016
+ - [type, wait, timedOut, true, data, '{$self.hook.data.data}', ac, '{$self.output.metadata.ac}', au, '{$self.output.metadata.au}']
2017
2017
  - ['{@object.create}']
2018
2018
  - ['{@conditional.ternary}']
2019
2019
  - ['{@object.create}']
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.condition = void 0;
4
+ const fold_1 = require("../../escalations/fold");
4
5
  const common_1 = require("./common");
5
6
  const cancellationScope_1 = require("./cancellationScope");
6
7
  const didRun_1 = require("./didRun");
7
- const batch_1 = require("../../escalations/batch");
8
8
  /**
9
9
  * Pauses the workflow until a signal with the given `signalId` is received.
10
10
  * The workflow suspends durably — it survives process restarts and will
@@ -178,12 +178,16 @@ async function condition(signalId, timeoutOrConfig) {
178
178
  // A string arg is a bare timeout; a config object may carry its own
179
179
  // `timeout` field — the engine's waiter block accepts duration and
180
180
  // queueConfig together (one wait: escalation row + resume timer).
181
- // A `batch` declaration folds into metadata/envelope here, before the
182
- // interruption message is built, so the accumulator shape rides the
183
- // same Leg1-atomic INSERT as every other config field.
184
- const rawConfig = timeoutOrConfig && typeof timeoutOrConfig === 'object' ? timeoutOrConfig : undefined;
185
- const queueConfig = rawConfig?.batch ? (0, batch_1.foldBatchConfig)(rawConfig) : rawConfig;
186
- const timeout = typeof timeoutOrConfig === 'string' ? timeoutOrConfig : queueConfig?.timeout;
181
+ // A `batch` or `accumulate` declaration folds into metadata/envelope
182
+ // here, before the interruption message is built, so the accumulator
183
+ // shape rides the same Leg1-atomic INSERT as every other config field.
184
+ const rawConfig = timeoutOrConfig && typeof timeoutOrConfig === 'object'
185
+ ? timeoutOrConfig
186
+ : undefined;
187
+ const queueConfig = rawConfig ? (0, fold_1.foldEscalationConfig)(rawConfig) : rawConfig;
188
+ const timeout = typeof timeoutOrConfig === 'string'
189
+ ? timeoutOrConfig
190
+ : queueConfig?.timeout;
187
191
  const [didRunAlready, execIndex, result] = await (0, didRun_1.didRun)('wait');
188
192
  (0, cancellationScope_1.checkCancellation)();
189
193
  if (didRunAlready) {
@@ -200,14 +204,19 @@ async function condition(signalId, timeoutOrConfig) {
200
204
  });
201
205
  }
202
206
  }
203
- // If the condition timed out (timeout won the race), return false
207
+ // The timeout won the race. An accumulator row (or a batch row with
208
+ // `partialOnTimeout`) delivers its collection through the marker's
209
+ // `data`; every other wait resumes with false.
204
210
  if (result?.timedOut) {
205
- return false;
211
+ const delivered = result.data;
212
+ return delivered === undefined || delivered === null ? false : delivered;
206
213
  }
207
214
  const signalData = result.data?.data;
208
215
  // If the escalation was cancelled via cancel(), the signal carries this marker.
209
216
  // Return null so the workflow can distinguish cancellation from a real resolution.
210
- if (signalData && typeof signalData === 'object' && signalData.__escalation_cancelled === true) {
217
+ if (signalData &&
218
+ typeof signalData === 'object' &&
219
+ signalData.__escalation_cancelled === true) {
211
220
  return null;
212
221
  }
213
222
  return signalData;
@@ -0,0 +1,30 @@
1
+ import { AccumulateConfig } from '../../types/hmsh_escalations';
2
+ export declare const ACCUMULATE_RESERVED_METADATA_KEYS: ReadonlySet<string>;
3
+ export declare const ACCUMULATE_RESERVED_ENVELOPE_KEYS: ReadonlySet<string>;
4
+ /** The stored form of an `accumulate` declaration (`envelope.accumulate_config`). */
5
+ export interface StoredAccumulateConfig {
6
+ unique: boolean;
7
+ resolveAtMax: boolean;
8
+ }
9
+ /**
10
+ * Validates an item key for the accumulate ops: a non-empty string within
11
+ * the shared item-key length limit. Throws synchronously so a bad key never
12
+ * reaches a statement.
13
+ */
14
+ export declare function assertAccumulateItemKey(itemKey: unknown): asserts itemKey is string;
15
+ /**
16
+ * Folds an `accumulate` declaration into the escalation's storage shape:
17
+ * queryable facets in `metadata` (`accumulate_count: 0`, `accumulate_max`,
18
+ * `accumulate_keys: []`) and the item store plus stored options in
19
+ * `envelope` (`accumulate_items: {}`, `accumulate_config`). Pure and
20
+ * deterministic, so it is safe on the replayed `condition()` path. Throws
21
+ * synchronously on an invalid declaration so a bad accumulator never
22
+ * reaches a durable write.
23
+ */
24
+ export declare function foldAccumulateConfig<T extends {
25
+ accumulate?: AccumulateConfig;
26
+ batch?: string[];
27
+ partialOnTimeout?: boolean;
28
+ metadata?: Record<string, unknown>;
29
+ envelope?: Record<string, unknown>;
30
+ }>(config: T): Omit<T, 'accumulate' | 'partialOnTimeout'>;
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.foldAccumulateConfig = exports.assertAccumulateItemKey = exports.ACCUMULATE_RESERVED_ENVELOPE_KEYS = exports.ACCUMULATE_RESERVED_METADATA_KEYS = void 0;
4
+ const hmsh_escalations_1 = require("../../types/hmsh_escalations");
5
+ exports.ACCUMULATE_RESERVED_METADATA_KEYS = new Set([
6
+ hmsh_escalations_1.ESCALATION_ACCUMULATE_COUNT_KEY,
7
+ hmsh_escalations_1.ESCALATION_ACCUMULATE_MAX_KEY,
8
+ hmsh_escalations_1.ESCALATION_ACCUMULATE_KEYS_KEY,
9
+ ]);
10
+ exports.ACCUMULATE_RESERVED_ENVELOPE_KEYS = new Set([
11
+ hmsh_escalations_1.ESCALATION_ACCUMULATE_ITEMS_KEY,
12
+ hmsh_escalations_1.ESCALATION_ACCUMULATE_CONFIG_KEY,
13
+ ]);
14
+ /**
15
+ * Validates an item key for the accumulate ops: a non-empty string within
16
+ * the shared item-key length limit. Throws synchronously so a bad key never
17
+ * reaches a statement.
18
+ */
19
+ function assertAccumulateItemKey(itemKey) {
20
+ if (typeof itemKey !== 'string' || itemKey.length === 0) {
21
+ throw new Error('itemKey must be a non-empty string');
22
+ }
23
+ if (itemKey.length > hmsh_escalations_1.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH) {
24
+ throw new Error(`itemKey must be at most ${hmsh_escalations_1.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH} characters: '${itemKey.slice(0, 32)}…'`);
25
+ }
26
+ }
27
+ exports.assertAccumulateItemKey = assertAccumulateItemKey;
28
+ /**
29
+ * Folds an `accumulate` declaration into the escalation's storage shape:
30
+ * queryable facets in `metadata` (`accumulate_count: 0`, `accumulate_max`,
31
+ * `accumulate_keys: []`) and the item store plus stored options in
32
+ * `envelope` (`accumulate_items: {}`, `accumulate_config`). Pure and
33
+ * deterministic, so it is safe on the replayed `condition()` path. Throws
34
+ * synchronously on an invalid declaration so a bad accumulator never
35
+ * reaches a durable write.
36
+ */
37
+ function foldAccumulateConfig(config) {
38
+ const { accumulate, partialOnTimeout, ...rest } = config;
39
+ if (!accumulate)
40
+ return rest;
41
+ if (typeof accumulate !== 'object' || Array.isArray(accumulate)) {
42
+ throw new Error('accumulate must be an object');
43
+ }
44
+ if (rest.batch) {
45
+ throw new Error('accumulate and batch are mutually exclusive');
46
+ }
47
+ if (partialOnTimeout !== undefined) {
48
+ throw new Error('partialOnTimeout applies to batch only; an accumulator always delivers on timeout');
49
+ }
50
+ const { max, resolveAtMax = true, unique = true } = accumulate;
51
+ if (max !== undefined && (!Number.isInteger(max) || max < 1)) {
52
+ throw new Error('accumulate.max must be a positive integer');
53
+ }
54
+ if (typeof resolveAtMax !== 'boolean') {
55
+ throw new Error('accumulate.resolveAtMax must be a boolean');
56
+ }
57
+ if (typeof unique !== 'boolean') {
58
+ throw new Error('accumulate.unique must be a boolean');
59
+ }
60
+ for (const reserved of exports.ACCUMULATE_RESERVED_METADATA_KEYS) {
61
+ if (rest.metadata && reserved in rest.metadata) {
62
+ throw new Error(`metadata key '${reserved}' is reserved for accumulate state`);
63
+ }
64
+ }
65
+ for (const reserved of exports.ACCUMULATE_RESERVED_ENVELOPE_KEYS) {
66
+ if (rest.envelope && reserved in rest.envelope) {
67
+ throw new Error(`envelope key '${reserved}' is reserved for accumulate state`);
68
+ }
69
+ }
70
+ const stored = { unique, resolveAtMax };
71
+ return {
72
+ ...rest,
73
+ metadata: {
74
+ ...(rest.metadata ?? {}),
75
+ [hmsh_escalations_1.ESCALATION_ACCUMULATE_COUNT_KEY]: 0,
76
+ [hmsh_escalations_1.ESCALATION_ACCUMULATE_MAX_KEY]: max ?? null,
77
+ [hmsh_escalations_1.ESCALATION_ACCUMULATE_KEYS_KEY]: [],
78
+ },
79
+ envelope: {
80
+ ...(rest.envelope ?? {}),
81
+ [hmsh_escalations_1.ESCALATION_ACCUMULATE_ITEMS_KEY]: {},
82
+ [hmsh_escalations_1.ESCALATION_ACCUMULATE_CONFIG_KEY]: stored,
83
+ },
84
+ };
85
+ }
86
+ exports.foldAccumulateConfig = foldAccumulateConfig;
@@ -1,13 +1,18 @@
1
+ import { AccumulateConfig } from '../../types/hmsh_escalations';
1
2
  /**
2
3
  * Folds a `batch` declaration into the escalation's storage shape:
3
4
  * queryable facets in `metadata` (`batch_pending`, `batch_count`,
4
5
  * `batch_keys`) and the payload accumulator in `envelope`
5
- * (`batch_items: {}`). Pure and deterministic — safe on the replayed
6
- * `condition()` path. Throws synchronously on an invalid declaration so
7
- * a bad batch never reaches a durable write.
6
+ * (`batch_items: {}`). `partialOnTimeout` is stored beside the items so
7
+ * the expiry statement delivers the filled items instead of `false`. Pure
8
+ * and deterministic — safe on the replayed `condition()` path. Throws
9
+ * synchronously on an invalid declaration so a bad batch never reaches a
10
+ * durable write.
8
11
  */
9
12
  export declare function foldBatchConfig<T extends {
10
13
  batch?: string[];
14
+ partialOnTimeout?: boolean;
15
+ accumulate?: AccumulateConfig;
11
16
  metadata?: Record<string, unknown>;
12
17
  envelope?: Record<string, unknown>;
13
- }>(config: T): Omit<T, 'batch'>;
18
+ }>(config: T): Omit<T, 'batch' | 'partialOnTimeout'>;
@@ -10,19 +10,32 @@ 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_PARTIAL_ON_TIMEOUT_KEY,
13
14
  ]);
14
15
  /**
15
16
  * Folds a `batch` declaration into the escalation's storage shape:
16
17
  * queryable facets in `metadata` (`batch_pending`, `batch_count`,
17
18
  * `batch_keys`) and the payload accumulator in `envelope`
18
- * (`batch_items: {}`). Pure and deterministic — safe on the replayed
19
- * `condition()` path. Throws synchronously on an invalid declaration so
20
- * a bad batch never reaches a durable write.
19
+ * (`batch_items: {}`). `partialOnTimeout` is stored beside the items so
20
+ * the expiry statement delivers the filled items instead of `false`. Pure
21
+ * and deterministic — safe on the replayed `condition()` path. Throws
22
+ * synchronously on an invalid declaration so a bad batch never reaches a
23
+ * durable write.
21
24
  */
22
25
  function foldBatchConfig(config) {
23
- const { batch, ...rest } = config;
24
- if (!batch)
26
+ const { batch, partialOnTimeout, ...rest } = config;
27
+ if (!batch) {
28
+ if (partialOnTimeout !== undefined) {
29
+ throw new Error('partialOnTimeout requires a batch declaration');
30
+ }
25
31
  return rest;
32
+ }
33
+ if (rest.accumulate) {
34
+ throw new Error('accumulate and batch are mutually exclusive');
35
+ }
36
+ if (partialOnTimeout !== undefined && typeof partialOnTimeout !== 'boolean') {
37
+ throw new Error('partialOnTimeout must be a boolean');
38
+ }
26
39
  if (!Array.isArray(batch) || batch.length === 0) {
27
40
  throw new Error('batch must be a non-empty array of item keys');
28
41
  }
@@ -61,6 +74,9 @@ function foldBatchConfig(config) {
61
74
  ...(rest.envelope ?? {}),
62
75
  [hmsh_escalations_1.ESCALATION_BATCH_ITEMS_KEY]: {},
63
76
  [hmsh_escalations_1.ESCALATION_BATCH_FILLED_AT_KEY]: {},
77
+ ...(partialOnTimeout
78
+ ? { [hmsh_escalations_1.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY]: true }
79
+ : {}),
64
80
  },
65
81
  };
66
82
  }
@@ -1,7 +1,7 @@
1
1
  import { HotMesh } from '../hotmesh';
2
2
  import { EventsConfig } from '../../types/system_events';
3
3
  import { Connection } from '../../types/durable';
4
- import { EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, StatsEscalationsParams, EscalationStats, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, EscalateToRoleParams, MigrateEscalationParams, ClaimManyParams, EscalateManyToRoleParams, UpdateManyPriorityParams, ResolveManyParams, ResolveAllOrNoneParams, ResolveAllOrNoneResult, PruneEscalationsParams, PruneEscalationsResult, ClaimManyByQueryParams, ResolveBatchItemParams, ResolveBatchItemByMetadataParams, ResolveBatchItemResult } from '../../types/hmsh_escalations';
4
+ import { EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, StatsEscalationsParams, EscalationStats, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, EscalateToRoleParams, MigrateEscalationParams, ClaimManyParams, EscalateManyToRoleParams, UpdateManyPriorityParams, ResolveManyParams, ResolveAllOrNoneParams, ResolveAllOrNoneResult, PruneEscalationsParams, PruneEscalationsResult, ClaimManyByQueryParams, ResolveBatchItemParams, ResolveBatchItemByMetadataParams, ResolveBatchItemResult, AccumulateItemParams, AccumulateItemByMetadataParams, AccumulateItemResult, RemoveAccumulatedItemParams, RemoveAccumulatedItemByMetadataParams, RemoveAccumulatedItemResult } from '../../types/hmsh_escalations';
5
5
  /**
6
6
  * Reserved signal-payload key carrying resolution provenance
7
7
  * (`EscalationResolution`) to the waiting workflow. The `$` prefix marks the
@@ -248,6 +248,68 @@ export declare class EscalationClientService {
248
248
  * for the fill contract.
249
249
  */
250
250
  resolveBatchItemByMetadata(params: ResolveBatchItemByMetadataParams, namespace?: string): Promise<ResolveBatchItemResult>;
251
+ private _previewAccumulateRow;
252
+ /**
253
+ * Pre-builds one side's wake with a placeholder payload; the store
254
+ * rewrites the `{data,data}` slot from the committed collection inside
255
+ * the add statement, so a completing side's wake commits WITH the add.
256
+ */
257
+ private _accumulateWake;
258
+ private _assertAccumulatePatch;
259
+ /**
260
+ * Shared post-statement handling for both add forms: post-commit wake
261
+ * fallback per completed side (the committed `resolver_payload` is the
262
+ * recovery record) and lifecycle events (`accumulated` on an interim
263
+ * add, `resolved` on completion) for the container and the reciprocal.
264
+ */
265
+ private _settleAccumulateResult;
266
+ private _accumulateWakes;
267
+ /**
268
+ * Adds ONE item to an accumulator escalation (a wait created with
269
+ * `condition(signalId, { accumulate: {...} })` or a standalone `create()`
270
+ * with `accumulate`). One atomic statement: the entry lands under
271
+ * `envelope.accumulate_items[itemKey]` with a database-clock `at`, the
272
+ * `accumulate_keys` / `accumulate_count` facets recompute, and, when the
273
+ * add reaches `max` with `resolveAtMax`, the row resolves with the
274
+ * ordered collection (`{ $accumulated, $trigger: 'count' }`) as its
275
+ * `resolver_payload` and the waiting workflow's wake commits WITH the
276
+ * add. The caller that completes the row learns it from
277
+ * `outcome: 'completed'`.
278
+ *
279
+ * Pass `reciprocal` to write a second accumulator row in the same
280
+ * statement, both or neither: the reciprocal holds the container's id as
281
+ * its item key, each entry carries the other row's id as `reciprocalId`,
282
+ * and a member row declared `accumulate: { max: 1 }` completes and wakes
283
+ * here too. A blocked reciprocal leaves the container untouched and
284
+ * answers `reciprocal-*`.
285
+ *
286
+ * Adds are claim-agnostic by default; pass `assertClaim` for the same
287
+ * claim-lock assertion as `resolve()` on the container row. Pass
288
+ * `metadata` to merge an outcome patch into the container's GIN-indexed
289
+ * metadata in the same UPDATE (reserved accumulate keys are rejected).
290
+ * A repeated key answers `duplicate-item` without touching the row
291
+ * unless the accumulator was declared `unique: false`, which replaces
292
+ * the entry in place.
293
+ */
294
+ accumulateItem(params: AccumulateItemParams, namespace?: string): Promise<AccumulateItemResult>;
295
+ /**
296
+ * Add selecting the container by metadata facet: the highest priority
297
+ * pending row whose `metadata` contains the key/value, mirroring
298
+ * `resolveByMetadata()`'s selector. See {@link accumulateItem} for the
299
+ * add contract.
300
+ */
301
+ accumulateItemByMetadata(params: AccumulateItemByMetadataParams, namespace?: string): Promise<AccumulateItemResult>;
302
+ private _settleRemoveResult;
303
+ /**
304
+ * Removes ONE held item from a pending accumulator escalation in one
305
+ * guarded statement: the entry leaves `accumulate_items`, the facets
306
+ * recompute, the row stays `pending`, and the waiter is never woken.
307
+ * Pass `reciprocal` to also remove the container's id from that row,
308
+ * both or neither. A key that is not held answers `item-absent`.
309
+ */
310
+ removeAccumulatedItem(params: RemoveAccumulatedItemParams, namespace?: string): Promise<RemoveAccumulatedItemResult>;
311
+ /** Removal selecting the container by metadata facet. See {@link removeAccumulatedItem}. */
312
+ removeAccumulatedItemByMetadata(params: RemoveAccumulatedItemByMetadataParams, namespace?: string): Promise<RemoveAccumulatedItemResult>;
251
313
  /**
252
314
  * Full-fidelity migration: inserts an escalation row preserving the original
253
315
  * UUID and lifecycle state. Returns `null` on duplicate (idempotent).