@dudousxd/nestjs-durable 0.52.7 → 0.54.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.
package/dist/index.cjs CHANGED
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  // src/index.ts
32
32
  var index_exports = {};
33
33
  __export(index_exports, {
34
+ BAD_RUN_REQUEST: () => BAD_RUN_REQUEST,
34
35
  CONTEXT_ACCESSOR: () => CONTEXT_ACCESSOR,
35
36
  DEAD_LETTER_METADATA: () => DEAD_LETTER_METADATA,
36
37
  DURABLE_STEP_METADATA: () => DURABLE_STEP_METADATA,
@@ -49,12 +50,16 @@ __export(index_exports, {
49
50
  IN_APP_WORKER_RUNNERS: () => IN_APP_WORKER_RUNNERS,
50
51
  IN_APP_WORKER_RUNTIME: () => IN_APP_WORKER_RUNTIME,
51
52
  InAppWorkerBootstrap: () => InAppWorkerBootstrap,
53
+ LIFECYCLE_PENDING_TAG: () => import_nestjs_durable_core19.LIFECYCLE_PENDING_TAG,
52
54
  ON_ERROR_METADATA: () => ON_ERROR_METADATA,
55
+ ON_EVENT_BATCH_METADATA: () => ON_EVENT_BATCH_METADATA,
53
56
  ON_EVENT_METADATA: () => ON_EVENT_METADATA,
54
57
  On: () => On,
55
58
  OnDurableEvent: () => OnDurableEvent,
56
59
  OnError: () => OnError,
57
60
  OnEvent: () => OnEvent,
61
+ OnWorkflowCompleted: () => OnWorkflowCompleted,
62
+ OnWorkflowFailed: () => OnWorkflowFailed,
58
63
  ProxyRunGateway: () => ProxyRunGateway,
59
64
  RUN_GATEWAY: () => RUN_GATEWAY,
60
65
  RUN_REDIS_WORKER: () => RUN_REDIS_WORKER,
@@ -65,6 +70,7 @@ __export(index_exports, {
65
70
  Step: () => Step,
66
71
  StepInterceptor: () => StepInterceptor,
67
72
  StoreRunGateway: () => StoreRunGateway,
73
+ TENANT_REPUBLISH_MAX_LIMIT: () => TENANT_REPUBLISH_MAX_LIMIT,
68
74
  TenantEventRepublisher: () => TenantEventRepublisher,
69
75
  ThinStepRegistrar: () => ThinStepRegistrar,
70
76
  ThinWorkerBootstrap: () => ThinWorkerBootstrap,
@@ -76,6 +82,7 @@ __export(index_exports, {
76
82
  WorkflowService: () => WorkflowService,
77
83
  attributesOf: () => attributesOf,
78
84
  entityConfigFor: () => entityConfigFor,
85
+ eventBatchOf: () => eventBatchOf,
79
86
  getDurableStepMeta: () => getDurableStepMeta,
80
87
  getEntityMeta: () => getEntityMeta,
81
88
  getOnEvents: () => getOnEvents,
@@ -86,14 +93,19 @@ __export(index_exports, {
86
93
  isDrivingOperator: () => isDrivingOperator,
87
94
  isOperatorRole: () => isOperatorRole,
88
95
  isStepInterceptor: () => isStepInterceptor,
96
+ lifecycleRunId: () => import_nestjs_durable_core19.lifecycleRunId,
97
+ lifecycleSourceOf: () => import_nestjs_durable_core19.lifecycleSourceOf,
89
98
  onErrorCodesOf: () => onErrorCodesOf,
90
99
  prevCronFireMs: () => import_nestjs_durable_core19.prevCronFireMs,
91
100
  readSearchAttributes: () => import_nestjs_durable_core19.readSearchAttributes,
101
+ runCompletedEvent: () => import_nestjs_durable_core19.runCompletedEvent,
102
+ runFailedEvent: () => import_nestjs_durable_core19.runFailedEvent,
92
103
  runSchedules: () => import_nestjs_durable_core19.runSchedules,
93
104
  scheduleRunIdAt: () => import_nestjs_durable_core19.scheduleRunIdAt,
94
105
  scheduledRunId: () => import_nestjs_durable_core19.scheduledRunId,
95
106
  signTenantToken: () => import_nestjs_durable_core19.signTenantToken,
96
107
  thinWorkerProviders: () => thinWorkerProviders,
108
+ triggeredRunsOf: () => import_nestjs_durable_core19.triggeredRunsOf,
97
109
  unavailableRunGateway: () => unavailableRunGateway
98
110
  });
99
111
  module.exports = __toCommonJS(index_exports);
@@ -326,24 +338,108 @@ function onErrorCodesOf(method) {
326
338
  __name(onErrorCodesOf, "onErrorCodesOf");
327
339
  var ON_EVENT_METADATA = Symbol("nestjs-durable:on-event");
328
340
  function OnDurableEvent(...events) {
341
+ return (target) => addEventSubscriptions(target, events);
342
+ }
343
+ __name(OnDurableEvent, "OnDurableEvent");
344
+ function OnWorkflowCompleted(workflow, options) {
345
+ return onWorkflowSettled((0, import_nestjs_durable_core.runCompletedEvent)(workflow), options?.where, options);
346
+ }
347
+ __name(OnWorkflowCompleted, "OnWorkflowCompleted");
348
+ function OnWorkflowFailed(workflow, options) {
349
+ const statuses = options?.statuses;
350
+ const where = options?.where;
351
+ const accepts = statuses || where ? (event) => (!statuses || statuses.includes(event.status)) && (!where || where(event)) : void 0;
352
+ return onWorkflowSettled((0, import_nestjs_durable_core.runFailedEvent)(workflow), accepts, options);
353
+ }
354
+ __name(OnWorkflowFailed, "OnWorkflowFailed");
355
+ var ON_EVENT_BATCH_METADATA = Symbol("nestjs-durable:on-event-batch");
356
+ function onWorkflowSettled(event, where, options) {
357
+ const subscription = {
358
+ event,
359
+ where,
360
+ input: options?.input
361
+ };
362
+ const batch = subscriberEventBatch(event, options);
329
363
  return (target) => {
330
- const existing = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
331
- Reflect.defineMetadata(ON_EVENT_METADATA, [
332
- ...existing,
333
- ...events
334
- ], target);
364
+ addEventSubscriptions(target, [
365
+ subscription
366
+ ]);
367
+ if (!batch) return;
368
+ const existing = Reflect.getMetadata(ON_EVENT_BATCH_METADATA, target);
369
+ if (existing && !sameEventBatch(existing, batch)) {
370
+ throw new Error(`${target.name ?? "workflow"}: two lifecycle subscriptions declare different debounce/batch settings; a workflow coalesces all its triggers one way`);
371
+ }
372
+ Reflect.defineMetadata(ON_EVENT_BATCH_METADATA, batch, target);
335
373
  };
336
374
  }
337
- __name(OnDurableEvent, "OnDurableEvent");
375
+ __name(onWorkflowSettled, "onWorkflowSettled");
376
+ function subscriberEventBatch(event, options) {
377
+ if (options?.debounce && options.batch) {
378
+ throw new Error(`${event}: a subscription takes debounce or batch, not both`);
379
+ }
380
+ if (options?.debounce) {
381
+ return {
382
+ mode: "debounce",
383
+ windowMs: (0, import_nestjs_durable_core.parseDuration)(options.debounce.windowMs),
384
+ ...options.debounce.key ? {
385
+ key: options.debounce.key
386
+ } : {}
387
+ };
388
+ }
389
+ if (options?.batch) {
390
+ return {
391
+ mode: "batch",
392
+ maxSize: options.batch.maxSize,
393
+ windowMs: (0, import_nestjs_durable_core.parseDuration)(options.batch.windowMs),
394
+ ...options.batch.key ? {
395
+ key: options.batch.key
396
+ } : {}
397
+ };
398
+ }
399
+ return void 0;
400
+ }
401
+ __name(subscriberEventBatch, "subscriberEventBatch");
402
+ function sameEventBatch(a, b) {
403
+ return a.mode === b.mode && a.windowMs === b.windowMs && a.key?.toString() === b.key?.toString() && (a.mode !== "batch" || b.mode !== "batch" || a.maxSize === b.maxSize);
404
+ }
405
+ __name(sameEventBatch, "sameEventBatch");
406
+ function eventBatchOf(meta, target) {
407
+ const declared = meta.debounce ? {
408
+ mode: "debounce",
409
+ windowMs: (0, import_nestjs_durable_core.parseDuration)(meta.debounce)
410
+ } : meta.batch ? {
411
+ mode: "batch",
412
+ maxSize: meta.batch.maxSize,
413
+ windowMs: (0, import_nestjs_durable_core.parseDuration)(meta.batch.within)
414
+ } : void 0;
415
+ const fromSubscription = Reflect.getMetadata(ON_EVENT_BATCH_METADATA, target);
416
+ if (declared && fromSubscription && !sameEventBatch(declared, fromSubscription)) {
417
+ throw new Error(`workflow ${meta.name}: @Workflow declares ${declared.mode} but a lifecycle subscription declares a different ${fromSubscription.mode}; declare it in one place`);
418
+ }
419
+ return fromSubscription ?? declared;
420
+ }
421
+ __name(eventBatchOf, "eventBatchOf");
422
+ function addEventSubscriptions(target, entries) {
423
+ const existing = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
424
+ Reflect.defineMetadata(ON_EVENT_METADATA, [
425
+ ...existing,
426
+ ...entries
427
+ ], target);
428
+ }
429
+ __name(addEventSubscriptions, "addEventSubscriptions");
338
430
  var OnEvent = OnDurableEvent;
339
431
  function getOnEvents(meta, target) {
340
432
  const fromDecorator = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
433
+ const names = /* @__PURE__ */ new Set();
341
434
  return [
342
- .../* @__PURE__ */ new Set([
343
- ...meta.onEvent ?? [],
344
- ...fromDecorator
345
- ])
346
- ];
435
+ ...meta.onEvent ?? [],
436
+ ...fromDecorator
437
+ ].filter((entry) => {
438
+ if (typeof entry !== "string") return true;
439
+ if (names.has(entry)) return false;
440
+ names.add(entry);
441
+ return true;
442
+ });
347
443
  }
348
444
  __name(getOnEvents, "getOnEvents");
349
445
 
@@ -659,6 +755,9 @@ function registerOnRuntime(runtime, scanner, meta, instance, origin) {
659
755
  } : {}
660
756
  };
661
757
  const body = workflowIo(meta).wrap((ctx, input) => instance.run(ctx, input));
758
+ const subscribes = [
759
+ ...new Set(getOnEvents(meta, instance.constructor).map((entry) => typeof entry === "string" ? entry : entry.event))
760
+ ];
662
761
  runtime.registerWorkflow(meta.name, body, {
663
762
  ...announced,
664
763
  ...meta.requires !== void 0 ? {
@@ -672,6 +771,9 @@ function registerOnRuntime(runtime, scanner, meta, instance, origin) {
672
771
  code,
673
772
  workflow
674
773
  })
774
+ } : {},
775
+ ...subscribes.length > 0 ? {
776
+ subscribes
675
777
  } : {}
676
778
  });
677
779
  for (const [name, fn] of handlers) runtime.registerWorkflow(name, fn, announced);
@@ -1264,6 +1366,8 @@ var import_common6 = require("@nestjs/common");
1264
1366
  // src/run-request-responder.ts
1265
1367
  var import_nestjs_durable_core10 = require("@dudousxd/nestjs-durable-core");
1266
1368
  var UNSUPPORTED_RUN_REQUEST = "unsupported-request";
1369
+ var BAD_RUN_REQUEST = "bad-request";
1370
+ var TENANT_REPUBLISH_MAX_LIMIT = 1e3;
1267
1371
  var KNOWN_KINDS = /* @__PURE__ */ new Set([
1268
1372
  "getRunDetail",
1269
1373
  "getFanMembers",
@@ -1277,8 +1381,47 @@ var KNOWN_KINDS = /* @__PURE__ */ new Set([
1277
1381
  "continue",
1278
1382
  "retryWithInput",
1279
1383
  "redispatch",
1280
- "waitingFor"
1384
+ "waitingFor",
1385
+ "republishLifecycle",
1386
+ "workflowLifecycle"
1281
1387
  ]);
1388
+ function wireDate(value) {
1389
+ if (value === void 0 || value === null) return void 0;
1390
+ const date = value instanceof Date ? value : new Date(value);
1391
+ if (Number.isNaN(date.getTime())) throw new Error(`invalid date ${String(value)}`);
1392
+ return date;
1393
+ }
1394
+ __name(wireDate, "wireDate");
1395
+ function scopeRunLinks(detail, tenant) {
1396
+ const own = /* @__PURE__ */ __name((link) => link.namespace === tenant, "own");
1397
+ const bare = /* @__PURE__ */ __name((link) => {
1398
+ if (own(link)) return link;
1399
+ const { status: _status, namespace: _namespace, ...rest2 } = link;
1400
+ return rest2;
1401
+ }, "bare");
1402
+ const awaitedBy = detail.awaitedBy?.filter(own);
1403
+ const { awaitedBy: _awaitedBy, ...rest } = detail;
1404
+ const source = detail.triggeredBy;
1405
+ return {
1406
+ ...rest,
1407
+ ...source ? {
1408
+ triggeredBy: own(source) ? source : {
1409
+ runId: source.runId,
1410
+ kind: source.kind
1411
+ }
1412
+ } : {},
1413
+ ...awaitedBy && awaitedBy.length > 0 ? {
1414
+ awaitedBy
1415
+ } : {},
1416
+ ...detail.waitsFor ? {
1417
+ waitsFor: detail.waitsFor.map(bare)
1418
+ } : {},
1419
+ ...detail.lifecycleDeliveries ? {
1420
+ lifecycleDeliveries: detail.lifecycleDeliveries.map(bare)
1421
+ } : {}
1422
+ };
1423
+ }
1424
+ __name(scopeRunLinks, "scopeRunLinks");
1282
1425
  var RunRequestResponder = class {
1283
1426
  static {
1284
1427
  __name(this, "RunRequestResponder");
@@ -1334,18 +1477,7 @@ var RunRequestResponder = class {
1334
1477
  tenant
1335
1478
  };
1336
1479
  const { body } = msg;
1337
- if (!KNOWN_KINDS.has(body.kind)) {
1338
- return {
1339
- requestId: msg.requestId,
1340
- result: {
1341
- ok: false,
1342
- error: {
1343
- message: `the control plane does not support the ${String(body.kind)} run request`,
1344
- code: UNSUPPORTED_RUN_REQUEST
1345
- }
1346
- }
1347
- };
1348
- }
1480
+ if (!KNOWN_KINDS.has(body.kind)) return unsupported(msg.requestId, String(body.kind));
1349
1481
  if (body.kind === "listRuns") {
1350
1482
  const data = await this.gateway.listRuns({
1351
1483
  ...body.query,
@@ -1396,12 +1528,65 @@ var RunRequestResponder = class {
1396
1528
  }
1397
1529
  };
1398
1530
  }
1531
+ if (body.kind === "workflowLifecycle") {
1532
+ if (!this.gateway.workflowLifecycle) return unsupported(msg.requestId, body.kind);
1533
+ const data = await this.gateway.workflowLifecycle(body.workflow, {
1534
+ namespace: msg.tenant
1535
+ });
1536
+ return {
1537
+ requestId: msg.requestId,
1538
+ result: {
1539
+ ok: true,
1540
+ data
1541
+ }
1542
+ };
1543
+ }
1544
+ if (body.kind === "republishLifecycle" && !("runId" in body.target)) {
1545
+ if (!this.gateway.republishLifecycle) return unsupported(msg.requestId, body.kind);
1546
+ const { since, until, limit, ...rest } = body.target;
1547
+ if (limit !== void 0 && (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1)) {
1548
+ return badRequest(msg.requestId, `limit must be a positive integer, got ${JSON.stringify(limit)}`);
1549
+ }
1550
+ const refused = await this.refuseSubscriber(rest.workflow, rest.kind, rest.subscriber, msg.tenant);
1551
+ if (refused) return badRequest(msg.requestId, refused);
1552
+ const target = {
1553
+ ...rest,
1554
+ namespace: msg.tenant,
1555
+ limit: Math.min(limit ?? TENANT_REPUBLISH_MAX_LIMIT, TENANT_REPUBLISH_MAX_LIMIT),
1556
+ ...since !== void 0 ? {
1557
+ since: wireDate(since)
1558
+ } : {},
1559
+ ...until !== void 0 ? {
1560
+ until: wireDate(until)
1561
+ } : {}
1562
+ };
1563
+ try {
1564
+ const data = await this.gateway.republishLifecycle(target);
1565
+ return {
1566
+ requestId: msg.requestId,
1567
+ result: {
1568
+ ok: true,
1569
+ data
1570
+ }
1571
+ };
1572
+ } catch (err) {
1573
+ return {
1574
+ requestId: msg.requestId,
1575
+ result: {
1576
+ ok: false,
1577
+ error: {
1578
+ message: err instanceof Error ? err.message : String(err)
1579
+ }
1580
+ }
1581
+ };
1582
+ }
1583
+ }
1399
1584
  if (body.kind === "waitingFor") {
1400
1585
  const all = await this.gateway.waitingFor(body.runIds);
1401
- const owned = await Promise.all(Object.entries(all).map(async ([runId, waiting]) => {
1402
- const owner = this.gateway.getRun ? await this.gateway.getRun(runId) : (await this.gateway.getRunDetail(runId))?.run;
1586
+ const owned = await Promise.all(Object.entries(all).map(async ([runId2, waiting]) => {
1587
+ const owner = this.gateway.getRun ? await this.gateway.getRun(runId2) : (await this.gateway.getRunDetail(runId2))?.run;
1403
1588
  return owner && owner.namespace === msg.tenant ? [
1404
- runId,
1589
+ runId2,
1405
1590
  waiting
1406
1591
  ] : void 0;
1407
1592
  }));
@@ -1417,8 +1602,12 @@ var RunRequestResponder = class {
1417
1602
  }
1418
1603
  };
1419
1604
  }
1420
- const detail = body.kind === "getRunDetail" || !this.gateway.getRun ? await this.gateway.getRunDetail(body.runId, body.kind === "getRunDetail" ? body.options : void 0) : void 0;
1421
- const run = detail !== void 0 ? detail?.run ?? null : await this.gateway.getRun?.(body.runId);
1605
+ if (body.kind === "republishLifecycle" && !this.gateway.republishLifecycle) {
1606
+ return unsupported(msg.requestId, body.kind);
1607
+ }
1608
+ const runId = runIdOf(body);
1609
+ const detail = body.kind === "getRunDetail" || !this.gateway.getRun ? await this.gateway.getRunDetail(runId, body.kind === "getRunDetail" ? body.options : void 0) : void 0;
1610
+ const run = detail !== void 0 ? detail?.run ?? null : await this.gateway.getRun?.(runId);
1422
1611
  if (run && run.namespace !== msg.tenant) {
1423
1612
  return {
1424
1613
  requestId: msg.requestId,
@@ -1432,11 +1621,12 @@ var RunRequestResponder = class {
1432
1621
  };
1433
1622
  }
1434
1623
  if (body.kind === "getRunDetail") {
1624
+ const data = detail ? await this.scopeLifecycle(detail, msg.tenant) : detail;
1435
1625
  return {
1436
1626
  requestId: msg.requestId,
1437
1627
  result: {
1438
1628
  ok: true,
1439
- data: detail
1629
+ data
1440
1630
  }
1441
1631
  };
1442
1632
  }
@@ -1459,6 +1649,11 @@ var RunRequestResponder = class {
1459
1649
  }
1460
1650
  };
1461
1651
  }
1652
+ if (body.kind === "republishLifecycle" && "runId" in body.target && run) {
1653
+ const kind = (0, import_nestjs_durable_core10.lifecycleKindOf)(run.status);
1654
+ const refused = kind ? await this.refuseSubscriber(run.workflow, kind, body.target.subscriber, msg.tenant) : void 0;
1655
+ if (refused) return badRequest(msg.requestId, refused);
1656
+ }
1462
1657
  try {
1463
1658
  const data = await this.callVerb(body);
1464
1659
  return {
@@ -1480,8 +1675,71 @@ var RunRequestResponder = class {
1480
1675
  };
1481
1676
  }
1482
1677
  }
1678
+ /**
1679
+ * `detail` scoped to `tenant` (see {@link scopeRunLinks}), with its lifecycle links
1680
+ * (`workflowLifecycle`, `lifecycleSubscribers`) narrowed to the subscriptions of `tenant`'s
1681
+ * namespace, as the `workflowLifecycle` verb answers them.
1682
+ */
1683
+ async scopeLifecycle(input, tenant) {
1684
+ const detail = scopeRunLinks(input, tenant);
1685
+ if (detail.workflowLifecycle === void 0 && detail.lifecycleSubscribers === void 0) {
1686
+ return detail;
1687
+ }
1688
+ const { workflowLifecycle: _links, lifecycleSubscribers: _subscribers, ...rest } = detail;
1689
+ const links = await this.gateway.workflowLifecycle?.(detail.run.workflow, {
1690
+ namespace: tenant
1691
+ });
1692
+ if (!links) return rest;
1693
+ const kind = (0, import_nestjs_durable_core10.lifecycleKindOf)(detail.run.status);
1694
+ const subscribers = kind ? [
1695
+ ...new Set(links.startsOnSettle.filter((l) => l.kind === kind).map((l) => l.workflow))
1696
+ ] : [];
1697
+ const linked = links.startsOnSettle.length > 0 || links.startedBy.length > 0;
1698
+ return {
1699
+ ...rest,
1700
+ ...subscribers.length > 0 ? {
1701
+ lifecycleSubscribers: subscribers
1702
+ } : {},
1703
+ ...linked ? {
1704
+ workflowLifecycle: links
1705
+ } : {}
1706
+ };
1707
+ }
1708
+ /**
1709
+ * Why a tenant republish naming `subscriber` is refused, or undefined when it may go ahead: the
1710
+ * subscriber must be owed the event of `workflow` settling (as `kind`, when given) by a run of
1711
+ * the tenant's namespace (the gateway's `lifecycleSubscribers`, else the tenant's
1712
+ * `workflowLifecycle` links), so a tenant cannot have the event owed to an arbitrary name. Without
1713
+ * `subscriber` there is nothing to check.
1714
+ */
1715
+ async refuseSubscriber(workflow, kind, subscriber, tenant) {
1716
+ if (subscriber === void 0) return void 0;
1717
+ const kinds = kind ? [
1718
+ kind
1719
+ ] : [
1720
+ "completed",
1721
+ "failed"
1722
+ ];
1723
+ let subscribes = false;
1724
+ if (this.gateway.lifecycleSubscribers) {
1725
+ for (const k of kinds) {
1726
+ const subscribers = await this.gateway.lifecycleSubscribers(workflow, k, tenant);
1727
+ subscribes ||= subscribers.includes(subscriber);
1728
+ }
1729
+ } else {
1730
+ const links = await this.gateway.workflowLifecycle?.(workflow, {
1731
+ namespace: tenant
1732
+ });
1733
+ subscribes = links?.startsOnSettle.some((link) => link.workflow === subscriber && kinds.includes(link.kind)) ?? false;
1734
+ }
1735
+ if (subscribes) return void 0;
1736
+ const events = kind ? `run.${kind}:${workflow}` : `run.completed:${workflow} or run.failed:${workflow}`;
1737
+ return `subscriber ${subscriber} does not subscribe to ${events} in namespace ${tenant}`;
1738
+ }
1483
1739
  callVerb(body) {
1484
1740
  switch (body.kind) {
1741
+ case "republishLifecycle":
1742
+ return this.gateway.republishLifecycle?.(body.target) ?? Promise.reject(new Error("republishLifecycle is not supported"));
1485
1743
  case "cancel":
1486
1744
  return this.gateway.cancel(body.runId, body.opts);
1487
1745
  case "retry":
@@ -1495,6 +1753,37 @@ var RunRequestResponder = class {
1495
1753
  }
1496
1754
  }
1497
1755
  };
1756
+ function runIdOf(body) {
1757
+ if (body.kind !== "republishLifecycle") return body.runId;
1758
+ return "runId" in body.target ? body.target.runId : "";
1759
+ }
1760
+ __name(runIdOf, "runIdOf");
1761
+ function badRequest(requestId, message) {
1762
+ return {
1763
+ requestId,
1764
+ result: {
1765
+ ok: false,
1766
+ error: {
1767
+ message,
1768
+ code: BAD_RUN_REQUEST
1769
+ }
1770
+ }
1771
+ };
1772
+ }
1773
+ __name(badRequest, "badRequest");
1774
+ function unsupported(requestId, kind) {
1775
+ return {
1776
+ requestId,
1777
+ result: {
1778
+ ok: false,
1779
+ error: {
1780
+ message: `the control plane does not support the ${kind} run request`,
1781
+ code: UNSUPPORTED_RUN_REQUEST
1782
+ }
1783
+ }
1784
+ };
1785
+ }
1786
+ __name(unsupported, "unsupported");
1498
1787
 
1499
1788
  // src/proxy-run-gateway.ts
1500
1789
  function _ts_decorate6(decorators, target, key, desc) {
@@ -1760,6 +2049,42 @@ var ProxyRunGateway = class {
1760
2049
  runId
1761
2050
  });
1762
2051
  }
2052
+ /**
2053
+ * Republished on the control plane: a one-run target is checked against this tenant like
2054
+ * `retry`, a by-workflow one is read over this tenant's namespace only. A control plane too old to
2055
+ * know the verb fails it with an {@link UNSUPPORTED_RUN_REQUEST} error rather than a timeout.
2056
+ */
2057
+ republishLifecycle(target) {
2058
+ return this.requestNewVerb({
2059
+ kind: "republishLifecycle",
2060
+ target
2061
+ });
2062
+ }
2063
+ /** Answered by the control plane's engine; same version-skew error as {@link republishLifecycle}. */
2064
+ workflowLifecycle(workflow) {
2065
+ return this.requestNewVerb({
2066
+ kind: "workflowLifecycle",
2067
+ workflow
2068
+ });
2069
+ }
2070
+ /**
2071
+ * A verb with no fallback on an older control plane: its unsupported-request error, or the empty
2072
+ * `ok: true` reply the oldest responders send for an unknown verb, becomes a
2073
+ * {@link RunGatewayError} with code {@link UNSUPPORTED_RUN_REQUEST}.
2074
+ */
2075
+ async requestNewVerb(body) {
2076
+ const notSupported = /* @__PURE__ */ __name(() => new RunGatewayError(`${body.kind} is not supported by this server: the control plane is older than this tenant`, UNSUPPORTED_RUN_REQUEST), "notSupported");
2077
+ if (this.knownUnsupported(body.kind)) throw notSupported();
2078
+ let data;
2079
+ try {
2080
+ data = await this.request(body);
2081
+ } catch (err) {
2082
+ if (!isUnsupported(err)) throw err;
2083
+ }
2084
+ if (data !== void 0 && data !== null) return data;
2085
+ this.unsupportedUntil.set(body.kind, Date.now() + this.capabilityTtlMs);
2086
+ throw notSupported();
2087
+ }
1763
2088
  subscribe(runId, onEvent) {
1764
2089
  const unsubscribe = this.transport.onTenantEvent?.(this.tenant, (evt) => {
1765
2090
  if (evt.event.runId === runId) onEvent(evt.event);
@@ -2001,6 +2326,33 @@ function _ts_param5(paramIndex, decorator) {
2001
2326
  };
2002
2327
  }
2003
2328
  __name(_ts_param5, "_ts_param");
2329
+ function detailExtras(links) {
2330
+ const { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy } = links;
2331
+ if (!lifecycleSubscribers && !lifecycleDeliveries && !waitsFor && !awaitedBy && !triggeredBy) {
2332
+ return void 0;
2333
+ }
2334
+ return {
2335
+ lifecycleSubscribers,
2336
+ lifecycleDeliveries,
2337
+ waitsFor,
2338
+ awaitedBy,
2339
+ triggeredBy
2340
+ };
2341
+ }
2342
+ __name(detailExtras, "detailExtras");
2343
+ function withoutRegistry(query) {
2344
+ if (query.workflow === import_nestjs_durable_core13.LIFECYCLE_REGISTRY_WORKFLOW || query.workflows?.includes(import_nestjs_durable_core13.LIFECYCLE_REGISTRY_WORKFLOW)) {
2345
+ return query;
2346
+ }
2347
+ return {
2348
+ ...query,
2349
+ excludeWorkflows: [
2350
+ ...query.excludeWorkflows ?? [],
2351
+ import_nestjs_durable_core13.LIFECYCLE_REGISTRY_WORKFLOW
2352
+ ]
2353
+ };
2354
+ }
2355
+ __name(withoutRegistry, "withoutRegistry");
2004
2356
  var StoreRunGateway = class {
2005
2357
  static {
2006
2358
  __name(this, "StoreRunGateway");
@@ -2019,6 +2371,7 @@ var StoreRunGateway = class {
2019
2371
  async getRunDetail(runId, options) {
2020
2372
  const run = await this.store.getRun(runId);
2021
2373
  if (!run) return null;
2374
+ const links = await this.lifecycleLinks(run);
2022
2375
  const over = options?.summarizeFansOver;
2023
2376
  if (over === void 0) {
2024
2377
  const [timeline2, children] = await Promise.all([
@@ -2028,12 +2381,13 @@ var StoreRunGateway = class {
2028
2381
  return {
2029
2382
  run,
2030
2383
  timeline: timeline2,
2031
- children
2384
+ children,
2385
+ ...links
2032
2386
  };
2033
2387
  }
2034
2388
  if ((0, import_nestjs_durable_core13.aggregatesCheckpoints)(this.store)) {
2035
2389
  const stats = await this.store.checkpointStats(runId);
2036
- const etag = (0, import_nestjs_durable_core13.runDetailEtag)(run, stats, over);
2390
+ const etag = (0, import_nestjs_durable_core13.extendEtag)((0, import_nestjs_durable_core13.runDetailEtag)(run, stats, over), detailExtras(links));
2037
2391
  if ((0, import_nestjs_durable_core13.etagMatches)(options?.ifNoneMatch, etag)) {
2038
2392
  return {
2039
2393
  run,
@@ -2046,7 +2400,8 @@ var StoreRunGateway = class {
2046
2400
  return {
2047
2401
  run,
2048
2402
  ...await (0, import_nestjs_durable_core13.summarizeRunFromStore)(this.store, runId, over, stats),
2049
- etag
2403
+ etag,
2404
+ ...links
2050
2405
  };
2051
2406
  }
2052
2407
  const full = await this.store.listCheckpoints(runId);
@@ -2057,9 +2412,108 @@ var StoreRunGateway = class {
2057
2412
  timeline,
2058
2413
  children: ids.slice(0, import_nestjs_durable_core13.SUMMARY_CHILD_LIMIT),
2059
2414
  fans,
2060
- childCount: ids.length
2415
+ childCount: ids.length,
2416
+ ...links
2061
2417
  };
2062
2418
  }
2419
+ /**
2420
+ * What a run detail reads beyond the run row and its checkpoints: what this run's settling
2421
+ * started, the subscribers its lifecycle event goes to (of its namespace) and where it stands for
2422
+ * each, what started it, its workflow's lifecycle links, and the `ctx.waitForRun` waits on either
2423
+ * side of it with the other run's status. A few reads per detail: the run's own waiters while it
2424
+ * is suspended, the waiters on it (one prefix read), and one batched read of every linked run.
2425
+ */
2426
+ async lifecycleLinks(run) {
2427
+ const triggered = await this.engine.triggeredRuns(run);
2428
+ const source = (0, import_nestjs_durable_core13.lifecycleSourceOf)(run);
2429
+ const kind = (0, import_nestjs_durable_core13.lifecycleKindOf)(run.status);
2430
+ const subscribers = kind ? await this.engine.lifecycleSubscribers(run.workflow, kind, run.namespace || "default") : [];
2431
+ const workflowLifecycle = await this.engine.workflowLifecycle(run.workflow);
2432
+ const linked = workflowLifecycle.startsOnSettle.length > 0 || workflowLifecycle.startedBy.length > 0;
2433
+ const deliveries = kind ? (0, import_nestjs_durable_core13.lifecycleDeliveriesOf)(run, {
2434
+ subscribers,
2435
+ live: new Set(subscribers),
2436
+ coalesced: this.engine.coalescedSubscribers(run)
2437
+ }) : [];
2438
+ const [own, onIt] = await Promise.all([
2439
+ run.status === "suspended" ? (0, import_nestjs_durable_core13.listSignalWaitersOfRuns)(this.store, [
2440
+ run.id
2441
+ ]) : [],
2442
+ run.workflow.startsWith("__") ? [] : this.store.listSignalWaiters((0, import_nestjs_durable_core13.runWaitPrefix)(run.id))
2443
+ ]);
2444
+ const waitsFor = own.flatMap((w) => {
2445
+ const target = (0, import_nestjs_durable_core13.runWaitTargetOf)(w);
2446
+ return target !== void 0 ? [
2447
+ {
2448
+ runId: target,
2449
+ seq: w.seq
2450
+ }
2451
+ ] : [];
2452
+ });
2453
+ const awaitedBy = onIt.filter((w) => (0, import_nestjs_durable_core13.runWaitTargetOf)(w) === run.id).map((w) => ({
2454
+ runId: w.runId,
2455
+ seq: w.seq
2456
+ }));
2457
+ const started = deliveries.flatMap((d) => d.state === "started" && d.runId !== void 0 ? [
2458
+ d.runId
2459
+ ] : []);
2460
+ const { runs } = await (0, import_nestjs_durable_core13.readRunsByIds)(this.store, [
2461
+ ...source ? [
2462
+ source.runId
2463
+ ] : [],
2464
+ ...started,
2465
+ ...waitsFor.map((l) => l.runId),
2466
+ ...awaitedBy.map((l) => l.runId)
2467
+ ]);
2468
+ const withRun = /* @__PURE__ */ __name((link) => {
2469
+ const other = link.runId !== void 0 ? runs.get(link.runId) : void 0;
2470
+ return other ? {
2471
+ ...link,
2472
+ status: other.status,
2473
+ namespace: other.namespace
2474
+ } : link;
2475
+ }, "withRun");
2476
+ const sourceRun = source ? runs.get(source.runId) : void 0;
2477
+ const traceId = (0, import_nestjs_durable_core13.traceIdOfTraceparent)((0, import_nestjs_durable_core13.lifecycleTraceparentOf)(sourceRun?.tags));
2478
+ return {
2479
+ ...triggered.length > 0 ? {
2480
+ triggered
2481
+ } : {},
2482
+ ...source ? {
2483
+ triggeredBy: {
2484
+ ...source,
2485
+ ...sourceRun ? {
2486
+ status: sourceRun.status,
2487
+ namespace: sourceRun.namespace
2488
+ } : {},
2489
+ ...traceId ? {
2490
+ traceId
2491
+ } : {}
2492
+ }
2493
+ } : {},
2494
+ ...subscribers.length > 0 ? {
2495
+ lifecycleSubscribers: subscribers
2496
+ } : {},
2497
+ ...linked ? {
2498
+ workflowLifecycle
2499
+ } : {},
2500
+ ...deliveries.length > 0 ? {
2501
+ lifecycleDeliveries: deliveries.map((d) => d.state === "started" ? withRun(d) : d)
2502
+ } : {},
2503
+ ...waitsFor.length > 0 ? {
2504
+ waitsFor: waitsFor.map(withRun)
2505
+ } : {},
2506
+ ...awaitedBy.length > 0 ? {
2507
+ awaitedBy: awaitedBy.map(withRun)
2508
+ } : {}
2509
+ };
2510
+ }
2511
+ workflowLifecycle(workflow, opts) {
2512
+ return this.engine.workflowLifecycle(workflow, opts);
2513
+ }
2514
+ lifecycleSubscribers(workflow, kind, namespace) {
2515
+ return this.engine.lifecycleSubscribers(workflow, kind, namespace);
2516
+ }
2063
2517
  getRun(runId) {
2064
2518
  return this.store.getRun(runId);
2065
2519
  }
@@ -2086,7 +2540,7 @@ var StoreRunGateway = class {
2086
2540
  return (0, import_nestjs_durable_core13.pageFan)(await this.store.listCheckpoints(runId), group, query);
2087
2541
  }
2088
2542
  async listRuns(query) {
2089
- const runs = await this.store.listRuns(query);
2543
+ const runs = await this.store.listRuns(withoutRegistry(query));
2090
2544
  const waiterByRun = (0, import_nestjs_durable_core13.indexWaitersByRun)(await (0, import_nestjs_durable_core13.listSignalWaitersOfRuns)(this.store, runs.filter((run) => run.status === "suspended").map((run) => run.id)));
2091
2545
  return runs.map((run) => {
2092
2546
  const waiting = (0, import_nestjs_durable_core13.resolveRunWaiting)(run, waiterByRun);
@@ -2103,8 +2557,9 @@ var StoreRunGateway = class {
2103
2557
  * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
2104
2558
  */
2105
2559
  async runFacets(query) {
2106
- if (this.store.runFacets) return this.store.runFacets(query);
2107
- const runs = await this.store.listRuns(query);
2560
+ const scoped = withoutRegistry(query);
2561
+ if (this.store.runFacets) return this.store.runFacets(scoped);
2562
+ const runs = await this.store.listRuns(scoped);
2108
2563
  return (0, import_nestjs_durable_core13.mergeRunFacetRows)(runs.map((r) => ({
2109
2564
  status: r.status,
2110
2565
  origin: r.origin,
@@ -2119,7 +2574,7 @@ var StoreRunGateway = class {
2119
2574
  * still works without it.
2120
2575
  */
2121
2576
  async runValueFacets(axis, query, opts) {
2122
- return this.store.runValueFacets?.(axis, query, opts) ?? [];
2577
+ return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
2123
2578
  }
2124
2579
  /**
2125
2580
  * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
@@ -2172,6 +2627,9 @@ var StoreRunGateway = class {
2172
2627
  redispatchPending(runId) {
2173
2628
  return this.engine.redispatchPending(runId);
2174
2629
  }
2630
+ republishLifecycle(target) {
2631
+ return this.engine.republishLifecycle(target);
2632
+ }
2175
2633
  subscribe(runId, onEvent) {
2176
2634
  return this.engine.subscribe((event) => {
2177
2635
  if (event.runId === runId) onEvent(event);
@@ -2346,6 +2804,7 @@ var TimerPoller = class {
2346
2804
  await this.sweep("sweepTimeouts", () => this.engine.sweepTimeouts());
2347
2805
  await this.sweep("sweepStalled", async () => this.engine.sweepStalled?.());
2348
2806
  await this.sweep("sweepBufferedSignals", async () => this.engine.sweepBufferedSignals?.());
2807
+ await this.sweep("sweepLifecycleEvents", async () => this.engine.sweepLifecycleEvents?.());
2349
2808
  const schedules = this.options.schedules;
2350
2809
  if (schedules && schedules.length > 0) {
2351
2810
  await this.sweep("schedules", () => (0, import_nestjs_durable_core14.runSchedules)(this.engine, schedules, Date.now()));
@@ -2488,15 +2947,8 @@ var WorkflowRegistrar = class {
2488
2947
  if (origin === void 0) unattributed.push(meta.name);
2489
2948
  const io = workflowIo(meta);
2490
2949
  const body = io.wrap((ctx, input) => workflow.run(ctx, input));
2491
- const eventBatch = meta.debounce ? {
2492
- mode: "debounce",
2493
- windowMs: (0, import_nestjs_durable_core16.parseDuration)(meta.debounce)
2494
- } : meta.batch ? {
2495
- mode: "batch",
2496
- maxSize: meta.batch.maxSize,
2497
- windowMs: (0, import_nestjs_durable_core16.parseDuration)(meta.batch.within)
2498
- } : void 0;
2499
2950
  const workflowCtor = workflow.constructor;
2951
+ const eventBatch = eventBatchOf(meta, workflowCtor);
2500
2952
  const onError = onErrorHandlersOf(meta, workflow, this.metadataScanner);
2501
2953
  for (const [name, fn] of onError.handlers) {
2502
2954
  this.engine.register(name, meta.version, fn, {
@@ -2702,6 +3154,22 @@ var WorkflowService = class {
2702
3154
  publishEvent(name, payload, opts) {
2703
3155
  return this.engine.publishEvent(name, payload, opts);
2704
3156
  }
3157
+ /**
3158
+ * The runs started by `runId` settling, through `@OnWorkflowCompleted` / `@OnWorkflowFailed` (or
3159
+ * an `onEvent` on `runCompletedEvent(...)`). Only subscribers registered on this engine are
3160
+ * considered. For the reverse link, `lifecycleSourceOf(run)` reads it from the run itself.
3161
+ */
3162
+ triggeredRuns(runId) {
3163
+ return this.engine.triggeredRuns(runId);
3164
+ }
3165
+ /**
3166
+ * Publish settled runs' lifecycle events again: to a subscriber registered after they settled, or
3167
+ * one restricted by `subscriber`. Subscribers already started for a run are not started again.
3168
+ * See `WorkflowEngine.republishLifecycle`.
3169
+ */
3170
+ republishLifecycle(target) {
3171
+ return this.engine.republishLifecycle(target);
3172
+ }
2705
3173
  };
2706
3174
  WorkflowService = _ts_decorate11([
2707
3175
  (0, import_common11.Injectable)(),
@@ -3048,6 +3516,7 @@ var DurableModule = class _DurableModule {
3048
3516
  leaseMs: options.leaseMs,
3049
3517
  admission: options.admission,
3050
3518
  maxRecoveryAttempts: options.maxRecoveryAttempts,
3519
+ unregisteredWorkflowGraceMs: options.unregisteredWorkflowGraceMs,
3051
3520
  remoteAdvanceSilenceMs: options.remoteAdvanceSilenceMs,
3052
3521
  remoteRedispatchMs: options.remoteRedispatchMs,
3053
3522
  remoteRedispatchMax: options.remoteRedispatchMax,
@@ -3143,6 +3612,7 @@ DurableModule = _ts_decorate12([
3143
3612
  var import_nestjs_durable_core19 = require("@dudousxd/nestjs-durable-core");
3144
3613
  // Annotate the CommonJS export names for ESM import in node:
3145
3614
  0 && (module.exports = {
3615
+ BAD_RUN_REQUEST,
3146
3616
  CONTEXT_ACCESSOR,
3147
3617
  DEAD_LETTER_METADATA,
3148
3618
  DURABLE_STEP_METADATA,
@@ -3161,12 +3631,16 @@ var import_nestjs_durable_core19 = require("@dudousxd/nestjs-durable-core");
3161
3631
  IN_APP_WORKER_RUNNERS,
3162
3632
  IN_APP_WORKER_RUNTIME,
3163
3633
  InAppWorkerBootstrap,
3634
+ LIFECYCLE_PENDING_TAG,
3164
3635
  ON_ERROR_METADATA,
3636
+ ON_EVENT_BATCH_METADATA,
3165
3637
  ON_EVENT_METADATA,
3166
3638
  On,
3167
3639
  OnDurableEvent,
3168
3640
  OnError,
3169
3641
  OnEvent,
3642
+ OnWorkflowCompleted,
3643
+ OnWorkflowFailed,
3170
3644
  ProxyRunGateway,
3171
3645
  RUN_GATEWAY,
3172
3646
  RUN_REDIS_WORKER,
@@ -3177,6 +3651,7 @@ var import_nestjs_durable_core19 = require("@dudousxd/nestjs-durable-core");
3177
3651
  Step,
3178
3652
  StepInterceptor,
3179
3653
  StoreRunGateway,
3654
+ TENANT_REPUBLISH_MAX_LIMIT,
3180
3655
  TenantEventRepublisher,
3181
3656
  ThinStepRegistrar,
3182
3657
  ThinWorkerBootstrap,
@@ -3188,6 +3663,7 @@ var import_nestjs_durable_core19 = require("@dudousxd/nestjs-durable-core");
3188
3663
  WorkflowService,
3189
3664
  attributesOf,
3190
3665
  entityConfigFor,
3666
+ eventBatchOf,
3191
3667
  getDurableStepMeta,
3192
3668
  getEntityMeta,
3193
3669
  getOnEvents,
@@ -3198,14 +3674,19 @@ var import_nestjs_durable_core19 = require("@dudousxd/nestjs-durable-core");
3198
3674
  isDrivingOperator,
3199
3675
  isOperatorRole,
3200
3676
  isStepInterceptor,
3677
+ lifecycleRunId,
3678
+ lifecycleSourceOf,
3201
3679
  onErrorCodesOf,
3202
3680
  prevCronFireMs,
3203
3681
  readSearchAttributes,
3682
+ runCompletedEvent,
3683
+ runFailedEvent,
3204
3684
  runSchedules,
3205
3685
  scheduleRunIdAt,
3206
3686
  scheduledRunId,
3207
3687
  signTenantToken,
3208
3688
  thinWorkerProviders,
3689
+ triggeredRunsOf,
3209
3690
  unavailableRunGateway
3210
3691
  });
3211
3692
  //# sourceMappingURL=index.cjs.map