@hotmeshio/hotmesh 0.28.1 → 0.29.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.
@@ -33,7 +33,8 @@ const utils_3 = require("./kvtypes/hash/utils");
33
33
  const enums_1 = require("../../../../modules/enums");
34
34
  const cache_1 = require("../../cache");
35
35
  const __1 = require("../..");
36
- const batch_1 = require("../../../escalations/batch");
36
+ const fold_1 = require("../../../escalations/fold");
37
+ const escalation_accumulate_1 = require("./escalation-accumulate");
37
38
  const kvsql_1 = require("./kvsql");
38
39
  const kvtables_1 = require("./kvtables");
39
40
  const time_notify_1 = require("./time-notify");
@@ -1525,9 +1526,9 @@ class PostgresStoreService extends __1.StoreService {
1525
1526
  }
1526
1527
  }
1527
1528
  _escalationInsertParams(params) {
1528
- // A `batch` declaration folds into metadata/envelope so the accumulator
1529
- // shape is present from the row's first visible moment.
1530
- const folded = params.batch ? (0, batch_1.foldBatchConfig)(params) : params;
1529
+ // A `batch` or `accumulate` declaration folds into metadata/envelope so
1530
+ // the accumulator shape is present from the row's first visible moment.
1531
+ const folded = (0, fold_1.foldEscalationConfig)(params);
1531
1532
  const { namespace, appId, signalKey, topic, workflowId, taskQueue, workflowType, type, subtype, entity, description, role, priority, originId, parentId, initiatedBy, createdBy, traceId, spanId, taskId, escalationPayload, metadata, envelope, expiresAt, assignee, durationMinutes, } = folded;
1532
1533
  return [
1533
1534
  namespace ?? 'hmsh',
@@ -1646,8 +1647,12 @@ class PostgresStoreService extends __1.StoreService {
1646
1647
  * Transition a wait's escalation row to `expired` when its resume timer
1647
1648
  * fires first (`condition(signalId, { ..., timeout })`). Guarded by
1648
1649
  * `status = 'pending'`: a signal that won the race already resolved the
1649
- * row and is never touched. Returns the expired row, or null when no
1650
- * pending row carried the key (signal won, or the wait had no escalation).
1650
+ * row and is never touched. An accumulator row (or a batch row with
1651
+ * `partialOnTimeout`) has its `resolver_payload` set to the delivered
1652
+ * collection in the same UPDATE, so row truth and the waiter's value
1653
+ * agree. Returns the expired row plus the row's prior status, so the
1654
+ * caller can tell "a resolve won" (row exists, not pending) from "no
1655
+ * row" (the wait carried no escalation).
1651
1656
  */
1652
1657
  async expireEscalationBySignalKey(signalKey, namespace, appId) {
1653
1658
  const values = [signalKey];
@@ -1660,11 +1665,29 @@ class PostgresStoreService extends __1.StoreService {
1660
1665
  values.push(appId);
1661
1666
  clause += ` AND app_id = $${values.length}`;
1662
1667
  }
1663
- const result = await this.pgClient.query(`UPDATE public.hmsh_escalations
1664
- SET status = 'expired', updated_at = NOW()
1665
- WHERE signal_key = $1${clause} AND status = 'pending'
1666
- RETURNING *`, values);
1667
- return result.rows[0] ?? null;
1668
+ const result = await this.pgClient.query(`
1669
+ WITH target AS MATERIALIZED (
1670
+ SELECT id, status FROM public.hmsh_escalations
1671
+ WHERE signal_key = $1${clause}
1672
+ ORDER BY created_at DESC
1673
+ LIMIT 1 FOR UPDATE
1674
+ ),
1675
+ expired AS (
1676
+ UPDATE public.hmsh_escalations e
1677
+ SET status = 'expired', updated_at = NOW(),
1678
+ resolver_payload = ${(0, escalation_accumulate_1.timeoutPayloadSql)('e')}
1679
+ FROM target
1680
+ WHERE e.id = target.id AND target.status = 'pending'
1681
+ RETURNING e.*
1682
+ )
1683
+ SELECT t.status AS prior_status, row_to_json(x.*) AS entry_json
1684
+ FROM (SELECT * FROM target) t
1685
+ FULL OUTER JOIN (SELECT * FROM expired) x ON x.id = t.id
1686
+ `, values);
1687
+ const row = result.rows[0];
1688
+ if (!row)
1689
+ return { entry: null, priorStatus: null };
1690
+ return { entry: row.entry_json ?? null, priorStatus: row.prior_status ?? null };
1668
1691
  }
1669
1692
  _escalationFilterConditions(params, startIdx = 1) {
1670
1693
  const { namespace, role, roles, type, subtype, entity, status, assignedTo, workflowId, originId, parentId, available, priority, metadata, ids, taskId } = params;
@@ -1906,25 +1929,32 @@ class PostgresStoreService extends __1.StoreService {
1906
1929
  * with no transaction window for unrelated queries to interleave
1907
1930
  * into. Appends the wake params to `params` in place.
1908
1931
  */
1909
- composeEscalationWakeCTE(wakeCommand, params, fromCTE) {
1932
+ composeEscalationWakeCTE(wakeCommand, params, fromCTE, resolution) {
1910
1933
  if (!wakeCommand) {
1911
1934
  return { wakeCTE: '', wakeCount: '0::int AS wake_count' };
1912
1935
  }
1913
1936
  const schemaName = this.kvsql().safeName(this.appId);
1914
1937
  const base = params.length;
1915
1938
  params.push(this.appId, wakeCommand.message, wakeCommand.forSignalKey);
1939
+ //a resolve on an accumulator row delivers the committed collection: the
1940
+ //message's {data,data} slot is rewritten from resolver_payload in SQL
1941
+ let message = `$${base + 2}`;
1942
+ if (resolution) {
1943
+ params.push(resolution.resolutionJson);
1944
+ message = (0, escalation_accumulate_1.resolveWakeMessageSql)(fromCTE, `$${base + 2}`, `$${base + 4}`);
1945
+ }
1916
1946
  return {
1917
1947
  wakeCTE: `,
1918
1948
  wake AS (
1919
1949
  INSERT INTO ${schemaName}.engine_streams (stream_name, message, priority)
1920
- SELECT $${base + 1}, $${base + 2}, 5 FROM ${fromCTE}
1950
+ SELECT $${base + 1}, ${message}, 5 FROM ${fromCTE}
1921
1951
  WHERE ${fromCTE}.signal_key = $${base + 3}
1922
1952
  RETURNING id
1923
1953
  )`,
1924
1954
  wakeCount: '(SELECT COUNT(*) FROM wake)::int AS wake_count',
1925
1955
  };
1926
1956
  }
1927
- async resolveEscalation(params, wakeCommand) {
1957
+ async resolveEscalation(params, wakeCommand, resolutionJson) {
1928
1958
  const { id, namespace, resolverPayload, metadata, assertClaim } = params;
1929
1959
  const payloadJson = resolverPayload ? JSON.stringify(resolverPayload) : null;
1930
1960
  const metaJson = metadata ? JSON.stringify(metadata) : null;
@@ -1946,7 +1976,7 @@ class PostgresStoreService extends __1.StoreService {
1946
1976
  //whose window lapsed under a different assignee all resolve normally.
1947
1977
  sqlParams.push(assertClaim ?? null);
1948
1978
  const claimIdx = sqlParams.length;
1949
- const { wakeCTE, wakeCount } = this.composeEscalationWakeCTE(wakeCommand, sqlParams, 'resolved');
1979
+ const { wakeCTE, wakeCount } = this.composeEscalationWakeCTE(wakeCommand, sqlParams, 'resolved', { resolutionJson: resolutionJson ?? null });
1950
1980
  const result = await this.pgClient.query(`
1951
1981
  WITH target AS MATERIALIZED (
1952
1982
  SELECT id, signal_key, topic, status, assigned_to, assigned_until
@@ -1956,7 +1986,8 @@ class PostgresStoreService extends __1.StoreService {
1956
1986
  ),
1957
1987
  resolved AS (
1958
1988
  UPDATE public.hmsh_escalations e
1959
- SET status = 'resolved', resolved_at = NOW(), resolver_payload = $2,
1989
+ SET status = 'resolved', resolved_at = NOW(),
1990
+ resolver_payload = ${(0, escalation_accumulate_1.resolvePayloadSql)('e', '$2')},
1960
1991
  metadata = CASE WHEN $3::jsonb IS NOT NULL
1961
1992
  THEN COALESCE(e.metadata, '{}'::jsonb) || $3::jsonb
1962
1993
  ELSE e.metadata END,
@@ -2034,7 +2065,7 @@ class PostgresStoreService extends __1.StoreService {
2034
2065
  return null;
2035
2066
  return { id: row.id, signalKey: row.signal_key, topic: row.topic };
2036
2067
  }
2037
- async resolveEscalationByMetadata(params, wakeCommand) {
2068
+ async resolveEscalationByMetadata(params, wakeCommand, resolutionJson) {
2038
2069
  const { key, value, namespace, resolverPayload, roles, metadata } = params;
2039
2070
  const filter = JSON.stringify({ [key]: value });
2040
2071
  const payloadJson = resolverPayload ? JSON.stringify(resolverPayload) : null;
@@ -2043,7 +2074,7 @@ class PostgresStoreService extends __1.StoreService {
2043
2074
  const sqlParams = namespace
2044
2075
  ? [filter, roles ?? null, payloadJson, metaJson, namespace]
2045
2076
  : [filter, roles ?? null, payloadJson, metaJson];
2046
- const { wakeCTE, wakeCount } = this.composeEscalationWakeCTE(wakeCommand, sqlParams, 'resolved');
2077
+ const { wakeCTE, wakeCount } = this.composeEscalationWakeCTE(wakeCommand, sqlParams, 'resolved', { resolutionJson: resolutionJson ?? null });
2047
2078
  const result = await this.pgClient.query(`
2048
2079
  WITH target AS MATERIALIZED (
2049
2080
  SELECT id, signal_key, topic, status FROM public.hmsh_escalations
@@ -2056,7 +2087,8 @@ class PostgresStoreService extends __1.StoreService {
2056
2087
  ),
2057
2088
  resolved AS (
2058
2089
  UPDATE public.hmsh_escalations e
2059
- SET status = 'resolved', resolved_at = NOW(), resolver_payload = $3,
2090
+ SET status = 'resolved', resolved_at = NOW(),
2091
+ resolver_payload = ${(0, escalation_accumulate_1.resolvePayloadSql)('e', '$3')},
2060
2092
  metadata = CASE WHEN $4::jsonb IS NOT NULL
2061
2093
  THEN COALESCE(e.metadata, '{}'::jsonb) || $4::jsonb
2062
2094
  ELSE e.metadata END,
@@ -2296,6 +2328,181 @@ class PostgresStoreService extends __1.StoreService {
2296
2328
  const result = await this.pgClient.query(this._batchItemStatement(targetCTE, 2, 3, 4, 5, wakeCTE, wakeCount), sqlParams);
2297
2329
  return this._mapBatchItemRow(result.rows[0]);
2298
2330
  }
2331
+ _accumulateSelector(sel, label) {
2332
+ const forms = (sel.id ? 1 : 0) + (sel.signalKey ? 1 : 0) + (sel.key !== undefined ? 1 : 0);
2333
+ if (forms !== 1) {
2334
+ throw new Error(`${label} requires exactly one of id, signalKey, or key/value`);
2335
+ }
2336
+ if (sel.id)
2337
+ return { kind: 'id', id: sel.id };
2338
+ if (sel.signalKey)
2339
+ return { kind: 'signalKey', signalKey: sel.signalKey };
2340
+ return { kind: 'metadata', key: sel.key, value: sel.value, roles: sel.roles };
2341
+ }
2342
+ _mapAccumulateRows(rows, assertClaim, wakes) {
2343
+ const primary = rows.find((r) => r.is_primary);
2344
+ const reciprocal = rows.find((r) => !r.is_primary);
2345
+ if (!primary)
2346
+ return { ok: false, outcome: 'not-found' };
2347
+ const side = (row) => {
2348
+ const entry = row.entry_json;
2349
+ const count = Number(entry.metadata?.accumulate_count ?? 0);
2350
+ const max = entry.metadata?.accumulate_max;
2351
+ const remaining = typeof max === 'number' ? Math.max(0, max - count) : null;
2352
+ const wakeIdx = wakes.findIndex((w) => w.command.forSignalKey === row.signal_key);
2353
+ const wakeEnqueued = wakeIdx >= 0 && Number(row.wake_counts?.[wakeIdx] ?? 0) > 0;
2354
+ return { entry, count, remaining, wakeEnqueued };
2355
+ };
2356
+ if (primary.outcome === 'completed' || primary.outcome === 'accepted') {
2357
+ const p = side(primary);
2358
+ const r = reciprocal ? side(reciprocal) : undefined;
2359
+ return {
2360
+ ok: true,
2361
+ outcome: primary.outcome,
2362
+ count: p.count,
2363
+ remaining: p.remaining,
2364
+ entry: p.entry,
2365
+ ...(reciprocal && r
2366
+ ? { reciprocal: { outcome: reciprocal.outcome, count: r.count, remaining: r.remaining, entry: r.entry } }
2367
+ : {}),
2368
+ wake: {
2369
+ primary: { signalKey: primary.signal_key, topic: primary.topic, wakeEnqueued: p.wakeEnqueued },
2370
+ ...(reciprocal && r
2371
+ ? { reciprocal: { signalKey: reciprocal.signal_key, topic: reciprocal.topic, wakeEnqueued: r.wakeEnqueued } }
2372
+ : {}),
2373
+ },
2374
+ };
2375
+ }
2376
+ if (primary.outcome !== 'gated') {
2377
+ if (primary.outcome === 'blocked') {
2378
+ if (primary.prior_status === 'cancelled')
2379
+ return { ok: false, outcome: 'already-cancelled' };
2380
+ if (primary.prior_status === 'expired')
2381
+ return { ok: false, outcome: 'already-expired' };
2382
+ return { ok: false, outcome: 'already-resolved' };
2383
+ }
2384
+ if (primary.outcome === 'claim-blocked') {
2385
+ return {
2386
+ ok: false,
2387
+ outcome: primary.assigned_to === assertClaim ? 'claim-expired' : 'claimed-by-other',
2388
+ };
2389
+ }
2390
+ return { ok: false, outcome: primary.outcome };
2391
+ }
2392
+ //the container was eligible: the reciprocal side blocked the write
2393
+ if (!reciprocal)
2394
+ return { ok: false, outcome: 'reciprocal-not-found' };
2395
+ switch (reciprocal.outcome) {
2396
+ case 'blocked': return { ok: false, outcome: 'reciprocal-terminal' };
2397
+ case 'not-accumulator': return { ok: false, outcome: 'reciprocal-not-accumulator' };
2398
+ case 'duplicate-item': return { ok: false, outcome: 'reciprocal-duplicate' };
2399
+ case 'full': return { ok: false, outcome: 'reciprocal-full' };
2400
+ default: return { ok: false, outcome: 'reciprocal-not-found' };
2401
+ }
2402
+ }
2403
+ /**
2404
+ * Appends one item to an accumulator escalation, and the container's id
2405
+ * to the reciprocal row when one is named, in ONE statement: both rows
2406
+ * locked in id order, both guards evaluated before either write, both
2407
+ * writes or neither. A side reaching `max` (with `resolveAtMax`) resolves
2408
+ * with the ordered collection as `resolver_payload` and its wake commits
2409
+ * in the same statement. See `buildAccumulateStatement`.
2410
+ */
2411
+ async accumulateEscalationItem(params, wakes = []) {
2412
+ const primary = this._accumulateSelector(params, 'accumulateItem');
2413
+ return this._runAccumulate(primary, params, wakes);
2414
+ }
2415
+ /** By-metadata form of `accumulateEscalationItem`, mirroring the
2416
+ * `resolveEscalationByMetadata` selector. No claim assertion. */
2417
+ async accumulateEscalationItemByMetadata(params, wakes = []) {
2418
+ const primary = { kind: 'metadata', key: params.key, value: params.value, roles: params.roles };
2419
+ return this._runAccumulate(primary, { ...params, assertClaim: undefined }, wakes);
2420
+ }
2421
+ async _runAccumulate(primary, params, wakes) {
2422
+ const reciprocal = params.reciprocal ? this._accumulateSelector(params.reciprocal, 'reciprocal') : null;
2423
+ if (reciprocal && JSON.stringify(reciprocal) === JSON.stringify(primary)) {
2424
+ throw new Error('reciprocal must name a different row than the container');
2425
+ }
2426
+ const { sql, values } = (0, escalation_accumulate_1.buildAccumulateStatement)({
2427
+ primary,
2428
+ reciprocal,
2429
+ namespace: params.namespace,
2430
+ itemKey: params.itemKey,
2431
+ payload: params.payload ?? null,
2432
+ reciprocalPayload: params.reciprocal?.payload ?? null,
2433
+ metadata: params.metadata ?? null,
2434
+ actor: params.actor ?? null,
2435
+ assertClaim: params.assertClaim ?? null,
2436
+ wakes,
2437
+ appId: this.appId,
2438
+ schemaName: this.kvsql().safeName(this.appId),
2439
+ });
2440
+ const result = await this.pgClient.query(sql, values);
2441
+ return this._mapAccumulateRows(result.rows, params.assertClaim ?? undefined, wakes);
2442
+ }
2443
+ _mapRemoveRows(rows) {
2444
+ const primary = rows.find((r) => r.is_primary);
2445
+ const reciprocal = rows.find((r) => !r.is_primary);
2446
+ if (!primary)
2447
+ return { ok: false, outcome: 'not-found' };
2448
+ const count = (row) => Number(row.entry_json?.metadata?.accumulate_count ?? 0);
2449
+ if (primary.outcome === 'removed') {
2450
+ return {
2451
+ ok: true,
2452
+ outcome: 'removed',
2453
+ count: count(primary),
2454
+ entry: primary.entry_json,
2455
+ ...(reciprocal ? { reciprocal: { count: count(reciprocal), entry: reciprocal.entry_json } } : {}),
2456
+ };
2457
+ }
2458
+ if (primary.outcome !== 'gated') {
2459
+ if (primary.outcome === 'blocked') {
2460
+ if (primary.prior_status === 'cancelled')
2461
+ return { ok: false, outcome: 'already-cancelled' };
2462
+ if (primary.prior_status === 'expired')
2463
+ return { ok: false, outcome: 'already-expired' };
2464
+ return { ok: false, outcome: 'already-resolved' };
2465
+ }
2466
+ return { ok: false, outcome: primary.outcome };
2467
+ }
2468
+ if (!reciprocal)
2469
+ return { ok: false, outcome: 'reciprocal-not-found' };
2470
+ switch (reciprocal.outcome) {
2471
+ case 'blocked': return { ok: false, outcome: 'reciprocal-terminal' };
2472
+ case 'not-accumulator': return { ok: false, outcome: 'reciprocal-not-accumulator' };
2473
+ case 'item-absent': return { ok: false, outcome: 'reciprocal-absent' };
2474
+ default: return { ok: false, outcome: 'reciprocal-not-found' };
2475
+ }
2476
+ }
2477
+ /**
2478
+ * Removes one held item from an accumulator escalation (and the
2479
+ * container's id from the reciprocal row when named) in ONE guarded
2480
+ * statement. Never wakes the waiter and never changes status. See
2481
+ * `buildRemoveStatement`.
2482
+ */
2483
+ async removeAccumulatedEscalationItem(params) {
2484
+ const primary = this._accumulateSelector(params, 'removeAccumulatedItem');
2485
+ return this._runRemove(primary, params);
2486
+ }
2487
+ /** By-metadata form of `removeAccumulatedEscalationItem`. */
2488
+ async removeAccumulatedEscalationItemByMetadata(params) {
2489
+ const primary = { kind: 'metadata', key: params.key, value: params.value, roles: params.roles };
2490
+ return this._runRemove(primary, params);
2491
+ }
2492
+ async _runRemove(primary, params) {
2493
+ const reciprocal = params.reciprocal ? this._accumulateSelector(params.reciprocal, 'reciprocal') : null;
2494
+ if (reciprocal && JSON.stringify(reciprocal) === JSON.stringify(primary)) {
2495
+ throw new Error('reciprocal must name a different row than the container');
2496
+ }
2497
+ const { sql, values } = (0, escalation_accumulate_1.buildRemoveStatement)({
2498
+ primary,
2499
+ reciprocal,
2500
+ namespace: params.namespace,
2501
+ itemKey: params.itemKey,
2502
+ });
2503
+ const result = await this.pgClient.query(sql, values);
2504
+ return this._mapRemoveRows(result.rows);
2505
+ }
2299
2506
  async cancelEscalation(id, namespace, wakeCommand) {
2300
2507
  //single statement: the cancellation wake is a data-modifying CTE
2301
2508
  //that fires iff the cancel lands AND the row's signal_key matches
@@ -2535,7 +2742,7 @@ class PostgresStoreService extends __1.StoreService {
2535
2742
  * names each blocking row and why. Same durability contract as
2536
2743
  * `resolveEscalation`: each wake commits WITH its row's resolve.
2537
2744
  */
2538
- async resolveAllOrNoneEscalations(params, wakeCommands) {
2745
+ async resolveAllOrNoneEscalations(params, wakeCommands, resolutionJsons) {
2539
2746
  const { items, namespace, metadata, assertAssignee } = params;
2540
2747
  if (!items?.length)
2541
2748
  return { ok: true, entries: [], wakeCount: 0 };
@@ -2558,12 +2765,12 @@ class PostgresStoreService extends __1.StoreService {
2558
2765
  if (wakeCommands?.length) {
2559
2766
  const schemaName = this.kvsql().safeName(this.appId);
2560
2767
  const base = sqlParams.length;
2561
- sqlParams.push(this.appId, wakeCommands.map((w) => w.forSignalKey), wakeCommands.map((w) => w.message));
2768
+ sqlParams.push(this.appId, wakeCommands.map((w) => w.forSignalKey), wakeCommands.map((w) => w.message), wakeCommands.map((_, i) => resolutionJsons?.[i] ?? null));
2562
2769
  wakeCTE = `,
2563
2770
  wake AS (
2564
2771
  INSERT INTO ${schemaName}.engine_streams (stream_name, message, priority)
2565
- SELECT $${base + 1}, w.message, 5
2566
- FROM unnest($${base + 2}::text[], $${base + 3}::text[]) AS w(signal_key, message)
2772
+ SELECT $${base + 1}, ${(0, escalation_accumulate_1.resolveWakeMessageSql)('r', 'w.message', 'w.resolution')}, 5
2773
+ FROM unnest($${base + 2}::text[], $${base + 3}::text[], $${base + 4}::text[]) AS w(signal_key, message, resolution)
2567
2774
  JOIN resolved r ON r.signal_key = w.signal_key
2568
2775
  RETURNING id
2569
2776
  )`;
@@ -2588,7 +2795,7 @@ class PostgresStoreService extends __1.StoreService {
2588
2795
  resolved AS (
2589
2796
  UPDATE public.hmsh_escalations e
2590
2797
  SET status = 'resolved', resolved_at = NOW(),
2591
- resolver_payload = i.payload_text::jsonb,
2798
+ resolver_payload = ${(0, escalation_accumulate_1.resolvePayloadSql)('e', 'i.payload_text')},
2592
2799
  metadata = CASE WHEN $3::jsonb IS NOT NULL
2593
2800
  THEN COALESCE(e.metadata, '{}'::jsonb) || $3::jsonb
2594
2801
  ELSE e.metadata END,
@@ -30,6 +30,24 @@ export interface ConditionQueueConfig {
30
30
  * terminal row for audit.
31
31
  */
32
32
  batch?: string[];
33
+ /**
34
+ * With `batch`, a timeout resumes the wait with the items filled so far
35
+ * plus `$trigger: 'timeout'` instead of `false`. Off by default, so
36
+ * existing batch waiters are unchanged.
37
+ */
38
+ partialOnTimeout?: boolean;
39
+ /**
40
+ * Declares the wait as an open accumulator: items arrive over time via
41
+ * `accumulateItem()` and the collection is delivered on every terminal
42
+ * path except cancel. Resolves with `{ $accumulated, $trigger }` when
43
+ * `max` items are held (`$trigger: 'count'`), when `timeout` fires
44
+ * (`'timeout'`, status `expired`), or on a manual `resolve()`
45
+ * (`'resolve'`, merged with the resolver payload). Folded at creation
46
+ * into `metadata.accumulate_count` / `accumulate_max` / `accumulate_keys`
47
+ * and `envelope.accumulate_items` / `accumulate_config` — one atomic
48
+ * INSERT with the workflow checkpoint. Mutually exclusive with `batch`.
49
+ */
50
+ accumulate?: AccumulateConfig;
33
51
  /**
34
52
  * Born-assigned: writes `assigned_to` in the same atomic INSERT that
35
53
  * creates the row — on the `condition()` path, one commit with the
@@ -324,6 +342,14 @@ export interface CreateEscalationParams {
324
342
  * `signalKey`) accumulate and complete identically; the wake is a no-op.
325
343
  */
326
344
  batch?: string[];
345
+ /** See {@link ConditionQueueConfig.partialOnTimeout}. */
346
+ partialOnTimeout?: boolean;
347
+ /**
348
+ * Declares the row as an open accumulator. See
349
+ * {@link ConditionQueueConfig.accumulate}. Standalone rows (no
350
+ * `signalKey`) accumulate and complete identically; the wake is a no-op.
351
+ */
352
+ accumulate?: AccumulateConfig;
327
353
  }
328
354
  /**
329
355
  * Fields that can be patched on an existing escalation. All fields are
@@ -453,6 +479,205 @@ export declare const ESCALATION_BATCH_FILLED_AT_KEY = "batch_filled_at";
453
479
  * accepted (keys are always parameterized and stored as jsonb text); prefer
454
480
  * URL/query-friendly names (e.g. `u1-L`) for endpoint ergonomics. */
455
481
  export declare const ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = 128;
482
+ /** Envelope key: set by `partialOnTimeout` on a batch row so the expiry
483
+ * statement knows to deliver the filled items with `$trigger: 'timeout'`. */
484
+ export declare const ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = "batch_partial_on_timeout";
485
+ /** Metadata facet: number of items currently held. Recomputed from
486
+ * `accumulate_keys` in every add/remove statement so the two never drift. */
487
+ export declare const ESCALATION_ACCUMULATE_COUNT_KEY = "accumulate_count";
488
+ /** Metadata facet: the count trigger, or `null` when the accumulator is
489
+ * unbounded. `metadata @> '{"accumulate_max": 4}'` finds four-slot rows. */
490
+ export declare const ESCALATION_ACCUMULATE_MAX_KEY = "accumulate_max";
491
+ /** Metadata facet: held item keys (jsonb string array).
492
+ * `metadata @> '{"accumulate_keys":["order-1"]}'` finds the row holding it. */
493
+ export declare const ESCALATION_ACCUMULATE_KEYS_KEY = "accumulate_keys";
494
+ /** Envelope key: the item store, `Record<itemKey, AccumulatedEntry>`. Each
495
+ * entry carries `at` (database clock), optional `payload`, `actor`, and
496
+ * `reciprocalId`. Payloads are plumbing, not facets. */
497
+ export declare const ESCALATION_ACCUMULATE_ITEMS_KEY = "accumulate_items";
498
+ /** Envelope key: the folded declaration (`{ unique, resolveAtMax }`) the
499
+ * add statement reads to decide replacement and completion. */
500
+ export declare const ESCALATION_ACCUMULATE_CONFIG_KEY = "accumulate_config";
501
+ /** Reserved signal-payload key: the ordered collection delivered to the
502
+ * waiter of an accumulator row. */
503
+ export declare const ESCALATION_ACCUMULATED_KEY = "$accumulated";
504
+ /** Reserved signal-payload key: which terminal path delivered the
505
+ * collection (`count` | `timeout` | `resolve`). */
506
+ export declare const ESCALATION_TRIGGER_KEY = "$trigger";
507
+ export interface AccumulateConfig {
508
+ /** Count trigger. Absent means unbounded: only `timeout` or a manual
509
+ * resolve ends the wait. */
510
+ max?: number;
511
+ /** Default `true`: reaching `max` resolves and wakes in the same
512
+ * statement as the completing add. `false` makes `max` a cap only;
513
+ * further adds answer `full` and the wait ends by timeout or resolve. */
514
+ resolveAtMax?: boolean;
515
+ /** Default `true`: a repeated item key answers `duplicate-item`. `false`
516
+ * replaces the entry in place; the count is unchanged. */
517
+ unique?: boolean;
518
+ }
519
+ /** One held item as stored under `envelope.accumulate_items[itemKey]`. */
520
+ export interface AccumulatedEntry<P = Record<string, unknown>> {
521
+ payload?: P;
522
+ /** ISO-8601, stamped by the database clock in the add statement. */
523
+ at: string;
524
+ actor?: string;
525
+ /** The row written in the same statement on the other side of a
526
+ * reciprocal add: the member's id on the container's entry, the
527
+ * container's id on the member's entry. */
528
+ reciprocalId?: string;
529
+ }
530
+ /** One held item as delivered under `$accumulated`. */
531
+ export type AccumulatedItem<P = Record<string, unknown>> = AccumulatedEntry<P> & {
532
+ itemKey: string;
533
+ };
534
+ export type AccumulatorTrigger = 'count' | 'timeout' | 'resolve';
535
+ /**
536
+ * What `condition()` resolves with for an accumulator row on every terminal
537
+ * path except cancel (`null`). `R` is the manual resolver payload, present
538
+ * only when `$trigger` is `'resolve'`.
539
+ */
540
+ export type AccumulatorResult<P = Record<string, unknown>, R extends Record<string, unknown> = Record<string, unknown>> = R & {
541
+ $accumulated: AccumulatedItem<P>[];
542
+ $trigger: AccumulatorTrigger;
543
+ $resolution?: EscalationResolution;
544
+ };
545
+ /** Selector for the second row of a reciprocal add. Exactly one of `id` |
546
+ * `signalKey` | (`key` + `value`). */
547
+ export interface AccumulateReciprocalSelector {
548
+ id?: string;
549
+ signalKey?: string;
550
+ key?: string;
551
+ value?: unknown;
552
+ roles?: string[];
553
+ /** Stored as the reciprocal entry's payload. */
554
+ payload?: Record<string, unknown>;
555
+ }
556
+ /**
557
+ * Outcome of an `accumulateItem()` call.
558
+ * - `completed` — this add reached `max`: the row resolved and the waiter
559
+ * was woken with the collection, in the same statement.
560
+ * - `accepted` — the item landed, the row stays `pending`.
561
+ * - `duplicate-item` — `unique` and the key is already held.
562
+ * - `full` — `max` items held and the key is new (only with
563
+ * `resolveAtMax: false`, or racing a completing add).
564
+ * - `not-accumulator` — the row carries no accumulate declaration.
565
+ * - `reciprocal-*` — the reciprocal row blocked the add; the container
566
+ * row was left untouched.
567
+ * - Remaining values match {@link ResolveEscalationResult} semantics.
568
+ */
569
+ export type AccumulateItemOutcome = 'completed' | 'accepted' | 'duplicate-item' | 'full' | 'not-accumulator' | 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired' | 'claim-expired' | 'claimed-by-other' | 'reciprocal-duplicate' | 'reciprocal-full' | 'reciprocal-terminal' | 'reciprocal-not-accumulator' | 'reciprocal-not-found';
570
+ export interface AccumulateItemParams {
571
+ /** Row selector — exactly one of `id` | `signalKey`. */
572
+ id?: string;
573
+ signalKey?: string;
574
+ namespace?: string;
575
+ /** The key this item is held under. Non-empty, at most
576
+ * {@link ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH} characters. */
577
+ itemKey: string;
578
+ /** Stored as the entry's `payload` and delivered inside `$accumulated`. */
579
+ payload?: Record<string, unknown>;
580
+ /** Merge patch applied to the row's GIN-indexed `metadata` in the same
581
+ * UPDATE. Reserved accumulate keys cannot be overridden. */
582
+ metadata?: Record<string, unknown>;
583
+ /** Recorded on the entry (and the reciprocal entry) as `actor`. */
584
+ actor?: string;
585
+ /** Claim-lock assertion inside the same guarded UPDATE, on the container
586
+ * row only. See {@link ResolveEscalationParams.assertClaim}. */
587
+ assertClaim?: string;
588
+ /** Resolver identity, delivered under `$resolution` with a completing
589
+ * wake. See {@link ResolveEscalationParams.resolvedBy}. */
590
+ resolvedBy?: ResolvedByIdentity;
591
+ /**
592
+ * A second accumulator row written in the same statement, both or
593
+ * neither. The reciprocal row holds the container's id as its item key
594
+ * and each entry points at the other row via `reciprocalId`. A member
595
+ * row declared `accumulate: { max: 1 }` completes and wakes here too.
596
+ */
597
+ reciprocal?: AccumulateReciprocalSelector;
598
+ }
599
+ export interface AccumulateItemByMetadataParams {
600
+ /** Facet selector — mirrors {@link ResolveByMetadataParams}. */
601
+ key: string;
602
+ value: unknown;
603
+ roles?: string[];
604
+ namespace?: string;
605
+ itemKey: string;
606
+ payload?: Record<string, unknown>;
607
+ metadata?: Record<string, unknown>;
608
+ actor?: string;
609
+ resolvedBy?: ResolvedByIdentity;
610
+ reciprocal?: AccumulateReciprocalSelector;
611
+ }
612
+ /** The written side of a reciprocal add. */
613
+ export interface AccumulateReciprocalResult {
614
+ outcome: 'completed' | 'accepted';
615
+ count: number;
616
+ remaining: number | null;
617
+ entry: EscalationEntry;
618
+ }
619
+ /**
620
+ * Result of `accumulateItem()` / `accumulateItemByMetadata()`. On `ok: true`,
621
+ * `count` is the items held after the add, `remaining` is `max - count`
622
+ * (`null` when unbounded), and `entry` is the post-add container row.
623
+ */
624
+ export type AccumulateItemResult = {
625
+ ok: true;
626
+ outcome: 'completed' | 'accepted';
627
+ count: number;
628
+ remaining: number | null;
629
+ entry: EscalationEntry;
630
+ reciprocal?: AccumulateReciprocalResult;
631
+ } | {
632
+ ok: false;
633
+ outcome: Exclude<AccumulateItemOutcome, 'completed' | 'accepted'>;
634
+ };
635
+ export type RemoveAccumulatedItemOutcome = 'removed' | 'item-absent' | 'not-accumulator' | 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired' | 'reciprocal-absent' | 'reciprocal-terminal' | 'reciprocal-not-accumulator' | 'reciprocal-not-found';
636
+ export interface RemoveAccumulatedItemParams {
637
+ /** Row selector — exactly one of `id` | `signalKey`. */
638
+ id?: string;
639
+ signalKey?: string;
640
+ namespace?: string;
641
+ itemKey: string;
642
+ /** Recorded in the lifecycle event only; the entry is gone. */
643
+ actor?: string;
644
+ /** Also remove the container's id from this row, both or neither. */
645
+ reciprocal?: Omit<AccumulateReciprocalSelector, 'payload'>;
646
+ }
647
+ export interface RemoveAccumulatedItemByMetadataParams {
648
+ key: string;
649
+ value: unknown;
650
+ roles?: string[];
651
+ namespace?: string;
652
+ itemKey: string;
653
+ actor?: string;
654
+ reciprocal?: Omit<AccumulateReciprocalSelector, 'payload'>;
655
+ }
656
+ /** Result of `removeAccumulatedItem()`. A removal never wakes the waiter. */
657
+ export type RemoveAccumulatedItemResult = {
658
+ ok: true;
659
+ outcome: 'removed';
660
+ count: number;
661
+ entry: EscalationEntry;
662
+ reciprocal?: {
663
+ count: number;
664
+ entry: EscalationEntry;
665
+ };
666
+ } | {
667
+ ok: false;
668
+ outcome: Exclude<RemoveAccumulatedItemOutcome, 'removed'>;
669
+ };
670
+ /**
671
+ * Result of the timeout path's expiry statement. `entry` is the row that
672
+ * moved `pending → expired` (with `resolver_payload` set when the row
673
+ * delivers a collection), or `null` when no pending row carried the key.
674
+ * `priorStatus` names the row's status before the statement when a row
675
+ * exists, so the caller can tell "a resolve won" from "no row".
676
+ */
677
+ export interface ExpireEscalationResult {
678
+ entry: EscalationEntry | null;
679
+ priorStatus: EscalationEntry['status'] | null;
680
+ }
456
681
  /**
457
682
  * Outcome of a `resolveBatchItem()` call.
458
683
  * - `completed` — this was the LAST item: the row resolved and the waiting
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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_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`. */
@@ -23,3 +23,29 @@ exports.ESCALATION_BATCH_FILLED_AT_KEY = 'batch_filled_at';
23
23
  * accepted (keys are always parameterized and stored as jsonb text); prefer
24
24
  * URL/query-friendly names (e.g. `u1-L`) for endpoint ergonomics. */
25
25
  exports.ESCALATION_BATCH_ITEM_KEY_MAX_LENGTH = 128;
26
+ /** Envelope key: set by `partialOnTimeout` on a batch row so the expiry
27
+ * statement knows to deliver the filled items with `$trigger: 'timeout'`. */
28
+ exports.ESCALATION_BATCH_PARTIAL_ON_TIMEOUT_KEY = 'batch_partial_on_timeout';
29
+ // ─── Open accumulation ────────────────────────────────────────────────────────
30
+ /** Metadata facet: number of items currently held. Recomputed from
31
+ * `accumulate_keys` in every add/remove statement so the two never drift. */
32
+ exports.ESCALATION_ACCUMULATE_COUNT_KEY = 'accumulate_count';
33
+ /** Metadata facet: the count trigger, or `null` when the accumulator is
34
+ * unbounded. `metadata @> '{"accumulate_max": 4}'` finds four-slot rows. */
35
+ exports.ESCALATION_ACCUMULATE_MAX_KEY = 'accumulate_max';
36
+ /** Metadata facet: held item keys (jsonb string array).
37
+ * `metadata @> '{"accumulate_keys":["order-1"]}'` finds the row holding it. */
38
+ exports.ESCALATION_ACCUMULATE_KEYS_KEY = 'accumulate_keys';
39
+ /** Envelope key: the item store, `Record<itemKey, AccumulatedEntry>`. Each
40
+ * entry carries `at` (database clock), optional `payload`, `actor`, and
41
+ * `reciprocalId`. Payloads are plumbing, not facets. */
42
+ exports.ESCALATION_ACCUMULATE_ITEMS_KEY = 'accumulate_items';
43
+ /** Envelope key: the folded declaration (`{ unique, resolveAtMax }`) the
44
+ * add statement reads to decide replacement and completion. */
45
+ exports.ESCALATION_ACCUMULATE_CONFIG_KEY = 'accumulate_config';
46
+ /** Reserved signal-payload key: the ordered collection delivered to the
47
+ * waiter of an accumulator row. */
48
+ exports.ESCALATION_ACCUMULATED_KEY = '$accumulated';
49
+ /** Reserved signal-payload key: which terminal path delivered the
50
+ * collection (`count` | `timeout` | `resolve`). */
51
+ exports.ESCALATION_TRIGGER_KEY = '$trigger';