@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.js CHANGED
@@ -5,7 +5,7 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
5
5
  import { readSearchAttributes } from "@dudousxd/nestjs-durable-core";
6
6
 
7
7
  // src/decorators.ts
8
- import { DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, WORKFLOW_NAME_KEY } from "@dudousxd/nestjs-durable-core";
8
+ import { DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, WORKFLOW_NAME_KEY, parseDuration, runCompletedEvent, runFailedEvent } from "@dudousxd/nestjs-durable-core";
9
9
  import "reflect-metadata";
10
10
 
11
11
  // src/origin.ts
@@ -229,24 +229,108 @@ function onErrorCodesOf(method) {
229
229
  __name(onErrorCodesOf, "onErrorCodesOf");
230
230
  var ON_EVENT_METADATA = Symbol("nestjs-durable:on-event");
231
231
  function OnDurableEvent(...events) {
232
+ return (target) => addEventSubscriptions(target, events);
233
+ }
234
+ __name(OnDurableEvent, "OnDurableEvent");
235
+ function OnWorkflowCompleted(workflow, options) {
236
+ return onWorkflowSettled(runCompletedEvent(workflow), options?.where, options);
237
+ }
238
+ __name(OnWorkflowCompleted, "OnWorkflowCompleted");
239
+ function OnWorkflowFailed(workflow, options) {
240
+ const statuses = options?.statuses;
241
+ const where = options?.where;
242
+ const accepts = statuses || where ? (event) => (!statuses || statuses.includes(event.status)) && (!where || where(event)) : void 0;
243
+ return onWorkflowSettled(runFailedEvent(workflow), accepts, options);
244
+ }
245
+ __name(OnWorkflowFailed, "OnWorkflowFailed");
246
+ var ON_EVENT_BATCH_METADATA = Symbol("nestjs-durable:on-event-batch");
247
+ function onWorkflowSettled(event, where, options) {
248
+ const subscription = {
249
+ event,
250
+ where,
251
+ input: options?.input
252
+ };
253
+ const batch = subscriberEventBatch(event, options);
232
254
  return (target) => {
233
- const existing = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
234
- Reflect.defineMetadata(ON_EVENT_METADATA, [
235
- ...existing,
236
- ...events
237
- ], target);
255
+ addEventSubscriptions(target, [
256
+ subscription
257
+ ]);
258
+ if (!batch) return;
259
+ const existing = Reflect.getMetadata(ON_EVENT_BATCH_METADATA, target);
260
+ if (existing && !sameEventBatch(existing, batch)) {
261
+ throw new Error(`${target.name ?? "workflow"}: two lifecycle subscriptions declare different debounce/batch settings; a workflow coalesces all its triggers one way`);
262
+ }
263
+ Reflect.defineMetadata(ON_EVENT_BATCH_METADATA, batch, target);
238
264
  };
239
265
  }
240
- __name(OnDurableEvent, "OnDurableEvent");
266
+ __name(onWorkflowSettled, "onWorkflowSettled");
267
+ function subscriberEventBatch(event, options) {
268
+ if (options?.debounce && options.batch) {
269
+ throw new Error(`${event}: a subscription takes debounce or batch, not both`);
270
+ }
271
+ if (options?.debounce) {
272
+ return {
273
+ mode: "debounce",
274
+ windowMs: parseDuration(options.debounce.windowMs),
275
+ ...options.debounce.key ? {
276
+ key: options.debounce.key
277
+ } : {}
278
+ };
279
+ }
280
+ if (options?.batch) {
281
+ return {
282
+ mode: "batch",
283
+ maxSize: options.batch.maxSize,
284
+ windowMs: parseDuration(options.batch.windowMs),
285
+ ...options.batch.key ? {
286
+ key: options.batch.key
287
+ } : {}
288
+ };
289
+ }
290
+ return void 0;
291
+ }
292
+ __name(subscriberEventBatch, "subscriberEventBatch");
293
+ function sameEventBatch(a, b) {
294
+ 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);
295
+ }
296
+ __name(sameEventBatch, "sameEventBatch");
297
+ function eventBatchOf(meta, target) {
298
+ const declared = meta.debounce ? {
299
+ mode: "debounce",
300
+ windowMs: parseDuration(meta.debounce)
301
+ } : meta.batch ? {
302
+ mode: "batch",
303
+ maxSize: meta.batch.maxSize,
304
+ windowMs: parseDuration(meta.batch.within)
305
+ } : void 0;
306
+ const fromSubscription = Reflect.getMetadata(ON_EVENT_BATCH_METADATA, target);
307
+ if (declared && fromSubscription && !sameEventBatch(declared, fromSubscription)) {
308
+ throw new Error(`workflow ${meta.name}: @Workflow declares ${declared.mode} but a lifecycle subscription declares a different ${fromSubscription.mode}; declare it in one place`);
309
+ }
310
+ return fromSubscription ?? declared;
311
+ }
312
+ __name(eventBatchOf, "eventBatchOf");
313
+ function addEventSubscriptions(target, entries) {
314
+ const existing = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
315
+ Reflect.defineMetadata(ON_EVENT_METADATA, [
316
+ ...existing,
317
+ ...entries
318
+ ], target);
319
+ }
320
+ __name(addEventSubscriptions, "addEventSubscriptions");
241
321
  var OnEvent = OnDurableEvent;
242
322
  function getOnEvents(meta, target) {
243
323
  const fromDecorator = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
324
+ const names = /* @__PURE__ */ new Set();
244
325
  return [
245
- .../* @__PURE__ */ new Set([
246
- ...meta.onEvent ?? [],
247
- ...fromDecorator
248
- ])
249
- ];
326
+ ...meta.onEvent ?? [],
327
+ ...fromDecorator
328
+ ].filter((entry) => {
329
+ if (typeof entry !== "string") return true;
330
+ if (names.has(entry)) return false;
331
+ names.add(entry);
332
+ return true;
333
+ });
250
334
  }
251
335
  __name(getOnEvents, "getOnEvents");
252
336
 
@@ -562,6 +646,9 @@ function registerOnRuntime(runtime, scanner, meta, instance, origin) {
562
646
  } : {}
563
647
  };
564
648
  const body = workflowIo(meta).wrap((ctx, input) => instance.run(ctx, input));
649
+ const subscribes = [
650
+ ...new Set(getOnEvents(meta, instance.constructor).map((entry) => typeof entry === "string" ? entry : entry.event))
651
+ ];
565
652
  runtime.registerWorkflow(meta.name, body, {
566
653
  ...announced,
567
654
  ...meta.requires !== void 0 ? {
@@ -575,6 +662,9 @@ function registerOnRuntime(runtime, scanner, meta, instance, origin) {
575
662
  code,
576
663
  workflow
577
664
  })
665
+ } : {},
666
+ ...subscribes.length > 0 ? {
667
+ subscribes
578
668
  } : {}
579
669
  });
580
670
  for (const [name, fn] of handlers) runtime.registerWorkflow(name, fn, announced);
@@ -1165,8 +1255,10 @@ import { SUMMARY_CHILD_LIMIT, childIdsOf, pageFan, resolveTenantToken as resolve
1165
1255
  import { Injectable as Injectable6 } from "@nestjs/common";
1166
1256
 
1167
1257
  // src/run-request-responder.ts
1168
- import { resolveWireTenant } from "@dudousxd/nestjs-durable-core";
1258
+ import { lifecycleKindOf, resolveWireTenant } from "@dudousxd/nestjs-durable-core";
1169
1259
  var UNSUPPORTED_RUN_REQUEST = "unsupported-request";
1260
+ var BAD_RUN_REQUEST = "bad-request";
1261
+ var TENANT_REPUBLISH_MAX_LIMIT = 1e3;
1170
1262
  var KNOWN_KINDS = /* @__PURE__ */ new Set([
1171
1263
  "getRunDetail",
1172
1264
  "getFanMembers",
@@ -1180,8 +1272,47 @@ var KNOWN_KINDS = /* @__PURE__ */ new Set([
1180
1272
  "continue",
1181
1273
  "retryWithInput",
1182
1274
  "redispatch",
1183
- "waitingFor"
1275
+ "waitingFor",
1276
+ "republishLifecycle",
1277
+ "workflowLifecycle"
1184
1278
  ]);
1279
+ function wireDate(value) {
1280
+ if (value === void 0 || value === null) return void 0;
1281
+ const date = value instanceof Date ? value : new Date(value);
1282
+ if (Number.isNaN(date.getTime())) throw new Error(`invalid date ${String(value)}`);
1283
+ return date;
1284
+ }
1285
+ __name(wireDate, "wireDate");
1286
+ function scopeRunLinks(detail, tenant) {
1287
+ const own = /* @__PURE__ */ __name((link) => link.namespace === tenant, "own");
1288
+ const bare = /* @__PURE__ */ __name((link) => {
1289
+ if (own(link)) return link;
1290
+ const { status: _status, namespace: _namespace, ...rest2 } = link;
1291
+ return rest2;
1292
+ }, "bare");
1293
+ const awaitedBy = detail.awaitedBy?.filter(own);
1294
+ const { awaitedBy: _awaitedBy, ...rest } = detail;
1295
+ const source = detail.triggeredBy;
1296
+ return {
1297
+ ...rest,
1298
+ ...source ? {
1299
+ triggeredBy: own(source) ? source : {
1300
+ runId: source.runId,
1301
+ kind: source.kind
1302
+ }
1303
+ } : {},
1304
+ ...awaitedBy && awaitedBy.length > 0 ? {
1305
+ awaitedBy
1306
+ } : {},
1307
+ ...detail.waitsFor ? {
1308
+ waitsFor: detail.waitsFor.map(bare)
1309
+ } : {},
1310
+ ...detail.lifecycleDeliveries ? {
1311
+ lifecycleDeliveries: detail.lifecycleDeliveries.map(bare)
1312
+ } : {}
1313
+ };
1314
+ }
1315
+ __name(scopeRunLinks, "scopeRunLinks");
1185
1316
  var RunRequestResponder = class {
1186
1317
  static {
1187
1318
  __name(this, "RunRequestResponder");
@@ -1237,18 +1368,7 @@ var RunRequestResponder = class {
1237
1368
  tenant
1238
1369
  };
1239
1370
  const { body } = msg;
1240
- if (!KNOWN_KINDS.has(body.kind)) {
1241
- return {
1242
- requestId: msg.requestId,
1243
- result: {
1244
- ok: false,
1245
- error: {
1246
- message: `the control plane does not support the ${String(body.kind)} run request`,
1247
- code: UNSUPPORTED_RUN_REQUEST
1248
- }
1249
- }
1250
- };
1251
- }
1371
+ if (!KNOWN_KINDS.has(body.kind)) return unsupported(msg.requestId, String(body.kind));
1252
1372
  if (body.kind === "listRuns") {
1253
1373
  const data = await this.gateway.listRuns({
1254
1374
  ...body.query,
@@ -1299,12 +1419,65 @@ var RunRequestResponder = class {
1299
1419
  }
1300
1420
  };
1301
1421
  }
1422
+ if (body.kind === "workflowLifecycle") {
1423
+ if (!this.gateway.workflowLifecycle) return unsupported(msg.requestId, body.kind);
1424
+ const data = await this.gateway.workflowLifecycle(body.workflow, {
1425
+ namespace: msg.tenant
1426
+ });
1427
+ return {
1428
+ requestId: msg.requestId,
1429
+ result: {
1430
+ ok: true,
1431
+ data
1432
+ }
1433
+ };
1434
+ }
1435
+ if (body.kind === "republishLifecycle" && !("runId" in body.target)) {
1436
+ if (!this.gateway.republishLifecycle) return unsupported(msg.requestId, body.kind);
1437
+ const { since, until, limit, ...rest } = body.target;
1438
+ if (limit !== void 0 && (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1)) {
1439
+ return badRequest(msg.requestId, `limit must be a positive integer, got ${JSON.stringify(limit)}`);
1440
+ }
1441
+ const refused = await this.refuseSubscriber(rest.workflow, rest.kind, rest.subscriber, msg.tenant);
1442
+ if (refused) return badRequest(msg.requestId, refused);
1443
+ const target = {
1444
+ ...rest,
1445
+ namespace: msg.tenant,
1446
+ limit: Math.min(limit ?? TENANT_REPUBLISH_MAX_LIMIT, TENANT_REPUBLISH_MAX_LIMIT),
1447
+ ...since !== void 0 ? {
1448
+ since: wireDate(since)
1449
+ } : {},
1450
+ ...until !== void 0 ? {
1451
+ until: wireDate(until)
1452
+ } : {}
1453
+ };
1454
+ try {
1455
+ const data = await this.gateway.republishLifecycle(target);
1456
+ return {
1457
+ requestId: msg.requestId,
1458
+ result: {
1459
+ ok: true,
1460
+ data
1461
+ }
1462
+ };
1463
+ } catch (err) {
1464
+ return {
1465
+ requestId: msg.requestId,
1466
+ result: {
1467
+ ok: false,
1468
+ error: {
1469
+ message: err instanceof Error ? err.message : String(err)
1470
+ }
1471
+ }
1472
+ };
1473
+ }
1474
+ }
1302
1475
  if (body.kind === "waitingFor") {
1303
1476
  const all = await this.gateway.waitingFor(body.runIds);
1304
- const owned = await Promise.all(Object.entries(all).map(async ([runId, waiting]) => {
1305
- const owner = this.gateway.getRun ? await this.gateway.getRun(runId) : (await this.gateway.getRunDetail(runId))?.run;
1477
+ const owned = await Promise.all(Object.entries(all).map(async ([runId2, waiting]) => {
1478
+ const owner = this.gateway.getRun ? await this.gateway.getRun(runId2) : (await this.gateway.getRunDetail(runId2))?.run;
1306
1479
  return owner && owner.namespace === msg.tenant ? [
1307
- runId,
1480
+ runId2,
1308
1481
  waiting
1309
1482
  ] : void 0;
1310
1483
  }));
@@ -1320,8 +1493,12 @@ var RunRequestResponder = class {
1320
1493
  }
1321
1494
  };
1322
1495
  }
1323
- const detail = body.kind === "getRunDetail" || !this.gateway.getRun ? await this.gateway.getRunDetail(body.runId, body.kind === "getRunDetail" ? body.options : void 0) : void 0;
1324
- const run = detail !== void 0 ? detail?.run ?? null : await this.gateway.getRun?.(body.runId);
1496
+ if (body.kind === "republishLifecycle" && !this.gateway.republishLifecycle) {
1497
+ return unsupported(msg.requestId, body.kind);
1498
+ }
1499
+ const runId = runIdOf(body);
1500
+ const detail = body.kind === "getRunDetail" || !this.gateway.getRun ? await this.gateway.getRunDetail(runId, body.kind === "getRunDetail" ? body.options : void 0) : void 0;
1501
+ const run = detail !== void 0 ? detail?.run ?? null : await this.gateway.getRun?.(runId);
1325
1502
  if (run && run.namespace !== msg.tenant) {
1326
1503
  return {
1327
1504
  requestId: msg.requestId,
@@ -1335,11 +1512,12 @@ var RunRequestResponder = class {
1335
1512
  };
1336
1513
  }
1337
1514
  if (body.kind === "getRunDetail") {
1515
+ const data = detail ? await this.scopeLifecycle(detail, msg.tenant) : detail;
1338
1516
  return {
1339
1517
  requestId: msg.requestId,
1340
1518
  result: {
1341
1519
  ok: true,
1342
- data: detail
1520
+ data
1343
1521
  }
1344
1522
  };
1345
1523
  }
@@ -1362,6 +1540,11 @@ var RunRequestResponder = class {
1362
1540
  }
1363
1541
  };
1364
1542
  }
1543
+ if (body.kind === "republishLifecycle" && "runId" in body.target && run) {
1544
+ const kind = lifecycleKindOf(run.status);
1545
+ const refused = kind ? await this.refuseSubscriber(run.workflow, kind, body.target.subscriber, msg.tenant) : void 0;
1546
+ if (refused) return badRequest(msg.requestId, refused);
1547
+ }
1365
1548
  try {
1366
1549
  const data = await this.callVerb(body);
1367
1550
  return {
@@ -1383,8 +1566,71 @@ var RunRequestResponder = class {
1383
1566
  };
1384
1567
  }
1385
1568
  }
1569
+ /**
1570
+ * `detail` scoped to `tenant` (see {@link scopeRunLinks}), with its lifecycle links
1571
+ * (`workflowLifecycle`, `lifecycleSubscribers`) narrowed to the subscriptions of `tenant`'s
1572
+ * namespace, as the `workflowLifecycle` verb answers them.
1573
+ */
1574
+ async scopeLifecycle(input, tenant) {
1575
+ const detail = scopeRunLinks(input, tenant);
1576
+ if (detail.workflowLifecycle === void 0 && detail.lifecycleSubscribers === void 0) {
1577
+ return detail;
1578
+ }
1579
+ const { workflowLifecycle: _links, lifecycleSubscribers: _subscribers, ...rest } = detail;
1580
+ const links = await this.gateway.workflowLifecycle?.(detail.run.workflow, {
1581
+ namespace: tenant
1582
+ });
1583
+ if (!links) return rest;
1584
+ const kind = lifecycleKindOf(detail.run.status);
1585
+ const subscribers = kind ? [
1586
+ ...new Set(links.startsOnSettle.filter((l) => l.kind === kind).map((l) => l.workflow))
1587
+ ] : [];
1588
+ const linked = links.startsOnSettle.length > 0 || links.startedBy.length > 0;
1589
+ return {
1590
+ ...rest,
1591
+ ...subscribers.length > 0 ? {
1592
+ lifecycleSubscribers: subscribers
1593
+ } : {},
1594
+ ...linked ? {
1595
+ workflowLifecycle: links
1596
+ } : {}
1597
+ };
1598
+ }
1599
+ /**
1600
+ * Why a tenant republish naming `subscriber` is refused, or undefined when it may go ahead: the
1601
+ * subscriber must be owed the event of `workflow` settling (as `kind`, when given) by a run of
1602
+ * the tenant's namespace (the gateway's `lifecycleSubscribers`, else the tenant's
1603
+ * `workflowLifecycle` links), so a tenant cannot have the event owed to an arbitrary name. Without
1604
+ * `subscriber` there is nothing to check.
1605
+ */
1606
+ async refuseSubscriber(workflow, kind, subscriber, tenant) {
1607
+ if (subscriber === void 0) return void 0;
1608
+ const kinds = kind ? [
1609
+ kind
1610
+ ] : [
1611
+ "completed",
1612
+ "failed"
1613
+ ];
1614
+ let subscribes = false;
1615
+ if (this.gateway.lifecycleSubscribers) {
1616
+ for (const k of kinds) {
1617
+ const subscribers = await this.gateway.lifecycleSubscribers(workflow, k, tenant);
1618
+ subscribes ||= subscribers.includes(subscriber);
1619
+ }
1620
+ } else {
1621
+ const links = await this.gateway.workflowLifecycle?.(workflow, {
1622
+ namespace: tenant
1623
+ });
1624
+ subscribes = links?.startsOnSettle.some((link) => link.workflow === subscriber && kinds.includes(link.kind)) ?? false;
1625
+ }
1626
+ if (subscribes) return void 0;
1627
+ const events = kind ? `run.${kind}:${workflow}` : `run.completed:${workflow} or run.failed:${workflow}`;
1628
+ return `subscriber ${subscriber} does not subscribe to ${events} in namespace ${tenant}`;
1629
+ }
1386
1630
  callVerb(body) {
1387
1631
  switch (body.kind) {
1632
+ case "republishLifecycle":
1633
+ return this.gateway.republishLifecycle?.(body.target) ?? Promise.reject(new Error("republishLifecycle is not supported"));
1388
1634
  case "cancel":
1389
1635
  return this.gateway.cancel(body.runId, body.opts);
1390
1636
  case "retry":
@@ -1398,6 +1644,37 @@ var RunRequestResponder = class {
1398
1644
  }
1399
1645
  }
1400
1646
  };
1647
+ function runIdOf(body) {
1648
+ if (body.kind !== "republishLifecycle") return body.runId;
1649
+ return "runId" in body.target ? body.target.runId : "";
1650
+ }
1651
+ __name(runIdOf, "runIdOf");
1652
+ function badRequest(requestId, message) {
1653
+ return {
1654
+ requestId,
1655
+ result: {
1656
+ ok: false,
1657
+ error: {
1658
+ message,
1659
+ code: BAD_RUN_REQUEST
1660
+ }
1661
+ }
1662
+ };
1663
+ }
1664
+ __name(badRequest, "badRequest");
1665
+ function unsupported(requestId, kind) {
1666
+ return {
1667
+ requestId,
1668
+ result: {
1669
+ ok: false,
1670
+ error: {
1671
+ message: `the control plane does not support the ${kind} run request`,
1672
+ code: UNSUPPORTED_RUN_REQUEST
1673
+ }
1674
+ }
1675
+ };
1676
+ }
1677
+ __name(unsupported, "unsupported");
1401
1678
 
1402
1679
  // src/proxy-run-gateway.ts
1403
1680
  function _ts_decorate6(decorators, target, key, desc) {
@@ -1663,6 +1940,42 @@ var ProxyRunGateway = class {
1663
1940
  runId
1664
1941
  });
1665
1942
  }
1943
+ /**
1944
+ * Republished on the control plane: a one-run target is checked against this tenant like
1945
+ * `retry`, a by-workflow one is read over this tenant's namespace only. A control plane too old to
1946
+ * know the verb fails it with an {@link UNSUPPORTED_RUN_REQUEST} error rather than a timeout.
1947
+ */
1948
+ republishLifecycle(target) {
1949
+ return this.requestNewVerb({
1950
+ kind: "republishLifecycle",
1951
+ target
1952
+ });
1953
+ }
1954
+ /** Answered by the control plane's engine; same version-skew error as {@link republishLifecycle}. */
1955
+ workflowLifecycle(workflow) {
1956
+ return this.requestNewVerb({
1957
+ kind: "workflowLifecycle",
1958
+ workflow
1959
+ });
1960
+ }
1961
+ /**
1962
+ * A verb with no fallback on an older control plane: its unsupported-request error, or the empty
1963
+ * `ok: true` reply the oldest responders send for an unknown verb, becomes a
1964
+ * {@link RunGatewayError} with code {@link UNSUPPORTED_RUN_REQUEST}.
1965
+ */
1966
+ async requestNewVerb(body) {
1967
+ 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");
1968
+ if (this.knownUnsupported(body.kind)) throw notSupported();
1969
+ let data;
1970
+ try {
1971
+ data = await this.request(body);
1972
+ } catch (err) {
1973
+ if (!isUnsupported(err)) throw err;
1974
+ }
1975
+ if (data !== void 0 && data !== null) return data;
1976
+ this.unsupportedUntil.set(body.kind, Date.now() + this.capabilityTtlMs);
1977
+ throw notSupported();
1978
+ }
1666
1979
  subscribe(runId, onEvent) {
1667
1980
  const unsubscribe = this.transport.onTenantEvent?.(this.tenant, (evt) => {
1668
1981
  if (evt.event.runId === runId) onEvent(evt.event);
@@ -1684,7 +1997,7 @@ ProxyRunGateway = _ts_decorate6([
1684
1997
  ], ProxyRunGateway);
1685
1998
 
1686
1999
  // src/retention-poller.ts
1687
- import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL4, STATE_STORE_CANONICAL, TERMINAL_RUN_STATUSES, parseDuration } from "@dudousxd/nestjs-durable-core";
2000
+ import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL4, STATE_STORE_CANONICAL, TERMINAL_RUN_STATUSES, parseDuration as parseDuration2 } from "@dudousxd/nestjs-durable-core";
1688
2001
  import { Inject as Inject4, Injectable as Injectable7 } from "@nestjs/common";
1689
2002
 
1690
2003
  // src/settle-within.ts
@@ -1750,7 +2063,7 @@ function validateRetention(retention) {
1750
2063
  if (policy.maxAge == null && policy.maxCount == null) {
1751
2064
  throw new Error("durable retention: each policy must set maxAge and/or maxCount");
1752
2065
  }
1753
- if (policy.maxAge != null) parseDuration(policy.maxAge);
2066
+ if (policy.maxAge != null) parseDuration2(policy.maxAge);
1754
2067
  for (const status of policy.statuses) {
1755
2068
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
1756
2069
  throw new Error(`durable retention: status "${status}" is not terminal; only ${TERMINAL_RUN_STATUSES.join(", ")} can be pruned`);
@@ -1805,7 +2118,7 @@ var RetentionPoller = class {
1805
2118
  return;
1806
2119
  }
1807
2120
  void this.sweep();
1808
- const intervalMs = retention.sweepInterval != null ? parseDuration(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
2121
+ const intervalMs = retention.sweepInterval != null ? parseDuration2(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
1809
2122
  if (intervalMs > 0) {
1810
2123
  this.timer = setInterval(() => void this.sweep(), intervalMs);
1811
2124
  this.timer.unref?.();
@@ -1876,7 +2189,7 @@ RetentionPoller = _ts_decorate7([
1876
2189
  ], RetentionPoller);
1877
2190
 
1878
2191
  // src/store-run-gateway.ts
1879
- import { STATE_STORE_CANONICAL as STATE_STORE_CANONICAL2, SUMMARY_CHILD_LIMIT as SUMMARY_CHILD_LIMIT2, WorkflowEngine as WorkflowEngine2, aggregatesCheckpoints, childIdsOf as childIdsOf2, etagMatches, fanPageEtag, indexWaitersByRun, listSignalWaitersOfRuns, mergeRunFacetRows, pageFan as pageFan2, pageFanFromStore, resolveRunWaiting, runDetailEtag, summarizeRunFromStore, summarizeTimeline as summarizeTimeline2 } from "@dudousxd/nestjs-durable-core";
2192
+ import { LIFECYCLE_REGISTRY_WORKFLOW, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL2, SUMMARY_CHILD_LIMIT as SUMMARY_CHILD_LIMIT2, WorkflowEngine as WorkflowEngine2, aggregatesCheckpoints, childIdsOf as childIdsOf2, etagMatches, extendEtag, fanPageEtag, indexWaitersByRun, lifecycleDeliveriesOf, lifecycleKindOf as lifecycleKindOf2, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, mergeRunFacetRows, pageFan as pageFan2, pageFanFromStore, readRunsByIds, resolveRunWaiting, runDetailEtag, runWaitPrefix, runWaitTargetOf, summarizeRunFromStore, summarizeTimeline as summarizeTimeline2, traceIdOfTraceparent } from "@dudousxd/nestjs-durable-core";
1880
2193
  import { Inject as Inject5, Injectable as Injectable8 } from "@nestjs/common";
1881
2194
  function _ts_decorate8(decorators, target, key, desc) {
1882
2195
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -1904,6 +2217,33 @@ function _ts_param5(paramIndex, decorator) {
1904
2217
  };
1905
2218
  }
1906
2219
  __name(_ts_param5, "_ts_param");
2220
+ function detailExtras(links) {
2221
+ const { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy } = links;
2222
+ if (!lifecycleSubscribers && !lifecycleDeliveries && !waitsFor && !awaitedBy && !triggeredBy) {
2223
+ return void 0;
2224
+ }
2225
+ return {
2226
+ lifecycleSubscribers,
2227
+ lifecycleDeliveries,
2228
+ waitsFor,
2229
+ awaitedBy,
2230
+ triggeredBy
2231
+ };
2232
+ }
2233
+ __name(detailExtras, "detailExtras");
2234
+ function withoutRegistry(query) {
2235
+ if (query.workflow === LIFECYCLE_REGISTRY_WORKFLOW || query.workflows?.includes(LIFECYCLE_REGISTRY_WORKFLOW)) {
2236
+ return query;
2237
+ }
2238
+ return {
2239
+ ...query,
2240
+ excludeWorkflows: [
2241
+ ...query.excludeWorkflows ?? [],
2242
+ LIFECYCLE_REGISTRY_WORKFLOW
2243
+ ]
2244
+ };
2245
+ }
2246
+ __name(withoutRegistry, "withoutRegistry");
1907
2247
  var StoreRunGateway = class {
1908
2248
  static {
1909
2249
  __name(this, "StoreRunGateway");
@@ -1922,6 +2262,7 @@ var StoreRunGateway = class {
1922
2262
  async getRunDetail(runId, options) {
1923
2263
  const run = await this.store.getRun(runId);
1924
2264
  if (!run) return null;
2265
+ const links = await this.lifecycleLinks(run);
1925
2266
  const over = options?.summarizeFansOver;
1926
2267
  if (over === void 0) {
1927
2268
  const [timeline2, children] = await Promise.all([
@@ -1931,12 +2272,13 @@ var StoreRunGateway = class {
1931
2272
  return {
1932
2273
  run,
1933
2274
  timeline: timeline2,
1934
- children
2275
+ children,
2276
+ ...links
1935
2277
  };
1936
2278
  }
1937
2279
  if (aggregatesCheckpoints(this.store)) {
1938
2280
  const stats = await this.store.checkpointStats(runId);
1939
- const etag = runDetailEtag(run, stats, over);
2281
+ const etag = extendEtag(runDetailEtag(run, stats, over), detailExtras(links));
1940
2282
  if (etagMatches(options?.ifNoneMatch, etag)) {
1941
2283
  return {
1942
2284
  run,
@@ -1949,7 +2291,8 @@ var StoreRunGateway = class {
1949
2291
  return {
1950
2292
  run,
1951
2293
  ...await summarizeRunFromStore(this.store, runId, over, stats),
1952
- etag
2294
+ etag,
2295
+ ...links
1953
2296
  };
1954
2297
  }
1955
2298
  const full = await this.store.listCheckpoints(runId);
@@ -1960,9 +2303,108 @@ var StoreRunGateway = class {
1960
2303
  timeline,
1961
2304
  children: ids.slice(0, SUMMARY_CHILD_LIMIT2),
1962
2305
  fans,
1963
- childCount: ids.length
2306
+ childCount: ids.length,
2307
+ ...links
1964
2308
  };
1965
2309
  }
2310
+ /**
2311
+ * What a run detail reads beyond the run row and its checkpoints: what this run's settling
2312
+ * started, the subscribers its lifecycle event goes to (of its namespace) and where it stands for
2313
+ * each, what started it, its workflow's lifecycle links, and the `ctx.waitForRun` waits on either
2314
+ * side of it with the other run's status. A few reads per detail: the run's own waiters while it
2315
+ * is suspended, the waiters on it (one prefix read), and one batched read of every linked run.
2316
+ */
2317
+ async lifecycleLinks(run) {
2318
+ const triggered = await this.engine.triggeredRuns(run);
2319
+ const source = lifecycleSourceOf(run);
2320
+ const kind = lifecycleKindOf2(run.status);
2321
+ const subscribers = kind ? await this.engine.lifecycleSubscribers(run.workflow, kind, run.namespace || "default") : [];
2322
+ const workflowLifecycle = await this.engine.workflowLifecycle(run.workflow);
2323
+ const linked = workflowLifecycle.startsOnSettle.length > 0 || workflowLifecycle.startedBy.length > 0;
2324
+ const deliveries = kind ? lifecycleDeliveriesOf(run, {
2325
+ subscribers,
2326
+ live: new Set(subscribers),
2327
+ coalesced: this.engine.coalescedSubscribers(run)
2328
+ }) : [];
2329
+ const [own, onIt] = await Promise.all([
2330
+ run.status === "suspended" ? listSignalWaitersOfRuns(this.store, [
2331
+ run.id
2332
+ ]) : [],
2333
+ run.workflow.startsWith("__") ? [] : this.store.listSignalWaiters(runWaitPrefix(run.id))
2334
+ ]);
2335
+ const waitsFor = own.flatMap((w) => {
2336
+ const target = runWaitTargetOf(w);
2337
+ return target !== void 0 ? [
2338
+ {
2339
+ runId: target,
2340
+ seq: w.seq
2341
+ }
2342
+ ] : [];
2343
+ });
2344
+ const awaitedBy = onIt.filter((w) => runWaitTargetOf(w) === run.id).map((w) => ({
2345
+ runId: w.runId,
2346
+ seq: w.seq
2347
+ }));
2348
+ const started = deliveries.flatMap((d) => d.state === "started" && d.runId !== void 0 ? [
2349
+ d.runId
2350
+ ] : []);
2351
+ const { runs } = await readRunsByIds(this.store, [
2352
+ ...source ? [
2353
+ source.runId
2354
+ ] : [],
2355
+ ...started,
2356
+ ...waitsFor.map((l) => l.runId),
2357
+ ...awaitedBy.map((l) => l.runId)
2358
+ ]);
2359
+ const withRun = /* @__PURE__ */ __name((link) => {
2360
+ const other = link.runId !== void 0 ? runs.get(link.runId) : void 0;
2361
+ return other ? {
2362
+ ...link,
2363
+ status: other.status,
2364
+ namespace: other.namespace
2365
+ } : link;
2366
+ }, "withRun");
2367
+ const sourceRun = source ? runs.get(source.runId) : void 0;
2368
+ const traceId = traceIdOfTraceparent(lifecycleTraceparentOf(sourceRun?.tags));
2369
+ return {
2370
+ ...triggered.length > 0 ? {
2371
+ triggered
2372
+ } : {},
2373
+ ...source ? {
2374
+ triggeredBy: {
2375
+ ...source,
2376
+ ...sourceRun ? {
2377
+ status: sourceRun.status,
2378
+ namespace: sourceRun.namespace
2379
+ } : {},
2380
+ ...traceId ? {
2381
+ traceId
2382
+ } : {}
2383
+ }
2384
+ } : {},
2385
+ ...subscribers.length > 0 ? {
2386
+ lifecycleSubscribers: subscribers
2387
+ } : {},
2388
+ ...linked ? {
2389
+ workflowLifecycle
2390
+ } : {},
2391
+ ...deliveries.length > 0 ? {
2392
+ lifecycleDeliveries: deliveries.map((d) => d.state === "started" ? withRun(d) : d)
2393
+ } : {},
2394
+ ...waitsFor.length > 0 ? {
2395
+ waitsFor: waitsFor.map(withRun)
2396
+ } : {},
2397
+ ...awaitedBy.length > 0 ? {
2398
+ awaitedBy: awaitedBy.map(withRun)
2399
+ } : {}
2400
+ };
2401
+ }
2402
+ workflowLifecycle(workflow, opts) {
2403
+ return this.engine.workflowLifecycle(workflow, opts);
2404
+ }
2405
+ lifecycleSubscribers(workflow, kind, namespace) {
2406
+ return this.engine.lifecycleSubscribers(workflow, kind, namespace);
2407
+ }
1966
2408
  getRun(runId) {
1967
2409
  return this.store.getRun(runId);
1968
2410
  }
@@ -1989,7 +2431,7 @@ var StoreRunGateway = class {
1989
2431
  return pageFan2(await this.store.listCheckpoints(runId), group, query);
1990
2432
  }
1991
2433
  async listRuns(query) {
1992
- const runs = await this.store.listRuns(query);
2434
+ const runs = await this.store.listRuns(withoutRegistry(query));
1993
2435
  const waiterByRun = indexWaitersByRun(await listSignalWaitersOfRuns(this.store, runs.filter((run) => run.status === "suspended").map((run) => run.id)));
1994
2436
  return runs.map((run) => {
1995
2437
  const waiting = resolveRunWaiting(run, waiterByRun);
@@ -2006,8 +2448,9 @@ var StoreRunGateway = class {
2006
2448
  * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
2007
2449
  */
2008
2450
  async runFacets(query) {
2009
- if (this.store.runFacets) return this.store.runFacets(query);
2010
- const runs = await this.store.listRuns(query);
2451
+ const scoped = withoutRegistry(query);
2452
+ if (this.store.runFacets) return this.store.runFacets(scoped);
2453
+ const runs = await this.store.listRuns(scoped);
2011
2454
  return mergeRunFacetRows(runs.map((r) => ({
2012
2455
  status: r.status,
2013
2456
  origin: r.origin,
@@ -2022,7 +2465,7 @@ var StoreRunGateway = class {
2022
2465
  * still works without it.
2023
2466
  */
2024
2467
  async runValueFacets(axis, query, opts) {
2025
- return this.store.runValueFacets?.(axis, query, opts) ?? [];
2468
+ return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
2026
2469
  }
2027
2470
  /**
2028
2471
  * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
@@ -2075,6 +2518,9 @@ var StoreRunGateway = class {
2075
2518
  redispatchPending(runId) {
2076
2519
  return this.engine.redispatchPending(runId);
2077
2520
  }
2521
+ republishLifecycle(target) {
2522
+ return this.engine.republishLifecycle(target);
2523
+ }
2078
2524
  subscribe(runId, onEvent) {
2079
2525
  return this.engine.subscribe((event) => {
2080
2526
  if (event.runId === runId) onEvent(event);
@@ -2249,6 +2695,7 @@ var TimerPoller = class {
2249
2695
  await this.sweep("sweepTimeouts", () => this.engine.sweepTimeouts());
2250
2696
  await this.sweep("sweepStalled", async () => this.engine.sweepStalled?.());
2251
2697
  await this.sweep("sweepBufferedSignals", async () => this.engine.sweepBufferedSignals?.());
2698
+ await this.sweep("sweepLifecycleEvents", async () => this.engine.sweepLifecycleEvents?.());
2252
2699
  const schedules = this.options.schedules;
2253
2700
  if (schedules && schedules.length > 0) {
2254
2701
  await this.sweep("schedules", () => runSchedules(this.engine, schedules, Date.now()));
@@ -2283,7 +2730,7 @@ var CONTEXT_ACCESSOR = Symbol.for("@dudousxd/nestjs-context:accessor");
2283
2730
  var RUN_GATEWAY = RunGateway;
2284
2731
 
2285
2732
  // src/workflow.registrar.ts
2286
- import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL6, RemoteWorkflowExecutor, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL3, WorkflowEngine as WorkflowEngine4, bindWorkflowClass, parseDuration as parseDuration2, sanitizeQueueToken, tenantGroup, workflowName as workflowName4 } from "@dudousxd/nestjs-durable-core";
2733
+ import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL6, RemoteWorkflowExecutor, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL3, WorkflowEngine as WorkflowEngine4, bindWorkflowClass, sanitizeQueueToken, tenantGroup, workflowName as workflowName4 } from "@dudousxd/nestjs-durable-core";
2287
2734
  import { Inject as Inject7, Injectable as Injectable10 } from "@nestjs/common";
2288
2735
  import { DiscoveryService as DiscoveryService4, MetadataScanner as MetadataScanner4 } from "@nestjs/core";
2289
2736
 
@@ -2391,15 +2838,8 @@ var WorkflowRegistrar = class {
2391
2838
  if (origin === void 0) unattributed.push(meta.name);
2392
2839
  const io = workflowIo(meta);
2393
2840
  const body = io.wrap((ctx, input) => workflow.run(ctx, input));
2394
- const eventBatch = meta.debounce ? {
2395
- mode: "debounce",
2396
- windowMs: parseDuration2(meta.debounce)
2397
- } : meta.batch ? {
2398
- mode: "batch",
2399
- maxSize: meta.batch.maxSize,
2400
- windowMs: parseDuration2(meta.batch.within)
2401
- } : void 0;
2402
2841
  const workflowCtor = workflow.constructor;
2842
+ const eventBatch = eventBatchOf(meta, workflowCtor);
2403
2843
  const onError = onErrorHandlersOf(meta, workflow, this.metadataScanner);
2404
2844
  for (const [name, fn] of onError.handlers) {
2405
2845
  this.engine.register(name, meta.version, fn, {
@@ -2605,6 +3045,22 @@ var WorkflowService = class {
2605
3045
  publishEvent(name, payload, opts) {
2606
3046
  return this.engine.publishEvent(name, payload, opts);
2607
3047
  }
3048
+ /**
3049
+ * The runs started by `runId` settling, through `@OnWorkflowCompleted` / `@OnWorkflowFailed` (or
3050
+ * an `onEvent` on `runCompletedEvent(...)`). Only subscribers registered on this engine are
3051
+ * considered. For the reverse link, `lifecycleSourceOf(run)` reads it from the run itself.
3052
+ */
3053
+ triggeredRuns(runId) {
3054
+ return this.engine.triggeredRuns(runId);
3055
+ }
3056
+ /**
3057
+ * Publish settled runs' lifecycle events again: to a subscriber registered after they settled, or
3058
+ * one restricted by `subscriber`. Subscribers already started for a run are not started again.
3059
+ * See `WorkflowEngine.republishLifecycle`.
3060
+ */
3061
+ republishLifecycle(target) {
3062
+ return this.engine.republishLifecycle(target);
3063
+ }
2608
3064
  };
2609
3065
  WorkflowService = _ts_decorate11([
2610
3066
  Injectable11(),
@@ -2951,6 +3407,7 @@ var DurableModule = class _DurableModule {
2951
3407
  leaseMs: options.leaseMs,
2952
3408
  admission: options.admission,
2953
3409
  maxRecoveryAttempts: options.maxRecoveryAttempts,
3410
+ unregisteredWorkflowGraceMs: options.unregisteredWorkflowGraceMs,
2954
3411
  remoteAdvanceSilenceMs: options.remoteAdvanceSilenceMs,
2955
3412
  remoteRedispatchMs: options.remoteRedispatchMs,
2956
3413
  remoteRedispatchMax: options.remoteRedispatchMax,
@@ -3043,8 +3500,9 @@ DurableModule = _ts_decorate12([
3043
3500
  ], DurableModule);
3044
3501
 
3045
3502
  // src/index.ts
3046
- import { hmacTenantVerifier, prevCronFireMs, readSearchAttributes as readSearchAttributes2, RunGateway as RunGateway3, runSchedules as runSchedules2, scheduledRunId, scheduleRunIdAt, signTenantToken, WorkflowEngine as WorkflowEngine7 } from "@dudousxd/nestjs-durable-core";
3503
+ import { hmacTenantVerifier, LIFECYCLE_PENDING_TAG, lifecycleRunId, lifecycleSourceOf as lifecycleSourceOf2, prevCronFireMs, readSearchAttributes as readSearchAttributes2, RunGateway as RunGateway3, runCompletedEvent as runCompletedEvent2, runFailedEvent as runFailedEvent2, runSchedules as runSchedules2, scheduledRunId, scheduleRunIdAt, signTenantToken, triggeredRunsOf, WorkflowEngine as WorkflowEngine7 } from "@dudousxd/nestjs-durable-core";
3047
3504
  export {
3505
+ BAD_RUN_REQUEST,
3048
3506
  CONTEXT_ACCESSOR,
3049
3507
  DEAD_LETTER_METADATA,
3050
3508
  DURABLE_STEP_METADATA,
@@ -3063,12 +3521,16 @@ export {
3063
3521
  IN_APP_WORKER_RUNNERS,
3064
3522
  IN_APP_WORKER_RUNTIME,
3065
3523
  InAppWorkerBootstrap,
3524
+ LIFECYCLE_PENDING_TAG,
3066
3525
  ON_ERROR_METADATA,
3526
+ ON_EVENT_BATCH_METADATA,
3067
3527
  ON_EVENT_METADATA,
3068
3528
  On,
3069
3529
  OnDurableEvent,
3070
3530
  OnError,
3071
3531
  OnEvent,
3532
+ OnWorkflowCompleted,
3533
+ OnWorkflowFailed,
3072
3534
  ProxyRunGateway,
3073
3535
  RUN_GATEWAY,
3074
3536
  RUN_REDIS_WORKER,
@@ -3079,6 +3541,7 @@ export {
3079
3541
  Step,
3080
3542
  StepInterceptor,
3081
3543
  StoreRunGateway,
3544
+ TENANT_REPUBLISH_MAX_LIMIT,
3082
3545
  TenantEventRepublisher,
3083
3546
  ThinStepRegistrar,
3084
3547
  ThinWorkerBootstrap,
@@ -3090,6 +3553,7 @@ export {
3090
3553
  WorkflowService,
3091
3554
  attributesOf,
3092
3555
  entityConfigFor,
3556
+ eventBatchOf,
3093
3557
  getDurableStepMeta,
3094
3558
  getEntityMeta,
3095
3559
  getOnEvents,
@@ -3100,14 +3564,19 @@ export {
3100
3564
  isDrivingOperator,
3101
3565
  isOperatorRole,
3102
3566
  isStepInterceptor,
3567
+ lifecycleRunId,
3568
+ lifecycleSourceOf2 as lifecycleSourceOf,
3103
3569
  onErrorCodesOf,
3104
3570
  prevCronFireMs,
3105
3571
  readSearchAttributes2 as readSearchAttributes,
3572
+ runCompletedEvent2 as runCompletedEvent,
3573
+ runFailedEvent2 as runFailedEvent,
3106
3574
  runSchedules2 as runSchedules,
3107
3575
  scheduleRunIdAt,
3108
3576
  scheduledRunId,
3109
3577
  signTenantToken,
3110
3578
  thinWorkerProviders,
3579
+ triggeredRunsOf,
3111
3580
  unavailableRunGateway
3112
3581
  };
3113
3582
  //# sourceMappingURL=index.js.map