@dudousxd/nestjs-durable 0.61.0 → 0.63.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
@@ -732,6 +732,19 @@ var DurableStartClient = class {
732
732
  ...opts?.searchAttributes !== void 0 ? {
733
733
  searchAttributes: opts.searchAttributes
734
734
  } : {},
735
+ // The start options the control plane applies (version pin, priority, delayed start, quota).
736
+ ...opts?.version !== void 0 ? {
737
+ version: opts.version
738
+ } : {},
739
+ ...opts?.priority !== void 0 ? {
740
+ priority: opts.priority
741
+ } : {},
742
+ ...opts?.startAt !== void 0 ? {
743
+ startAt: opts.startAt
744
+ } : {},
745
+ ...opts?.concurrency !== void 0 ? {
746
+ concurrency: opts.concurrency
747
+ } : {},
735
748
  ...tenant ? {
736
749
  tenantId: tenant.id,
737
750
  ...tenant.kind !== void 0 ? {
@@ -742,9 +755,10 @@ var DurableStartClient = class {
742
755
  deps: this.deps
743
756
  } : {}
744
757
  });
758
+ const startAtMs = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;
745
759
  return {
746
760
  runId,
747
- status: "pending"
761
+ status: startAtMs !== void 0 && Number.isFinite(startAtMs) && startAtMs > Date.now() ? "suspended" : "pending"
748
762
  };
749
763
  }
750
764
  cancel(_runId) {
@@ -790,7 +804,7 @@ function tenantUnsupported(method) {
790
804
  __name(tenantUnsupported, "tenantUnsupported");
791
805
 
792
806
  // src/durable-worker.module.ts
793
- import { DURABLE_OPTIONS_CANONICAL } from "@dudousxd/nestjs-durable-core";
807
+ import { DURABLE_OPTIONS_CANONICAL, WorkflowEngine, bindWorkflowClass } from "@dudousxd/nestjs-durable-core";
794
808
  import { Inject, Injectable as Injectable2 } from "@nestjs/common";
795
809
  import { DiscoveryService, MetadataScanner } from "@nestjs/core";
796
810
 
@@ -1029,28 +1043,38 @@ var ThinWorkflowRegistrar = class {
1029
1043
  metadataScanner;
1030
1044
  runtime;
1031
1045
  options;
1032
- constructor(discovery, metadataScanner, runtime, options) {
1046
+ starter;
1047
+ constructor(discovery, metadataScanner, runtime, options, starter) {
1033
1048
  this.discovery = discovery;
1034
1049
  this.metadataScanner = metadataScanner;
1035
1050
  this.runtime = runtime;
1036
1051
  this.options = options;
1052
+ this.starter = starter;
1037
1053
  }
1038
1054
  onModuleInit() {
1039
1055
  const runtime = this.runtime;
1040
1056
  if (runtime === null || !isPureThinWorker(this.options)) return;
1041
- scanWorkflows(this.discovery, (meta, instance, origin) => registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin));
1057
+ const starter = this.starter;
1058
+ scanWorkflows(this.discovery, (meta, instance, origin) => {
1059
+ registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin);
1060
+ bindWorkflowClass(instance.constructor, {
1061
+ start: /* @__PURE__ */ __name((name, input, runId, opts) => starter.start(name, input, runId, opts), "start")
1062
+ });
1063
+ });
1042
1064
  }
1043
1065
  };
1044
1066
  ThinWorkflowRegistrar = _ts_decorate2([
1045
1067
  Injectable2(),
1046
1068
  _ts_param(2, Inject(DURABLE_WORKER_RUNTIME)),
1047
1069
  _ts_param(3, Inject(DURABLE_OPTIONS_CANONICAL)),
1070
+ _ts_param(4, Inject(WorkflowEngine)),
1048
1071
  _ts_metadata2("design:type", Function),
1049
1072
  _ts_metadata2("design:paramtypes", [
1050
1073
  typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
1051
1074
  typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
1052
1075
  Object,
1053
- typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions
1076
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
1077
+ typeof WorkflowStartClient === "undefined" ? Object : WorkflowStartClient
1054
1078
  ])
1055
1079
  ], ThinWorkflowRegistrar);
1056
1080
  var ThinStepRegistrar = class {
@@ -1231,7 +1255,7 @@ function unavailableRunGateway() {
1231
1255
  __name(unavailableRunGateway, "unavailableRunGateway");
1232
1256
 
1233
1257
  // src/durable.module.ts
1234
- import { DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL8, RunGateway as RunGateway2, STATE_STORE, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL4, TRANSPORT, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL3, WorkflowEngine as WorkflowEngine6, sealDurableCopies, useDurableExecution } from "@dudousxd/nestjs-durable-core";
1258
+ import { DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL8, RunGateway as RunGateway2, STATE_STORE, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL4, TRANSPORT, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL3, WorkflowEngine as WorkflowEngine7, sealDurableCopies, useDurableExecution } from "@dudousxd/nestjs-durable-core";
1235
1259
  import { Inject as Inject9, Injectable as Injectable13, Module } from "@nestjs/common";
1236
1260
  import { DiscoveryModule, ModuleRef as ModuleRef2 } from "@nestjs/core";
1237
1261
 
@@ -1316,7 +1340,7 @@ DurableStepRegistrar = _ts_decorate3([
1316
1340
  ], DurableStepRegistrar);
1317
1341
 
1318
1342
  // src/entity.ts
1319
- import { WorkflowEngine } from "@dudousxd/nestjs-durable-core";
1343
+ import { WorkflowEngine as WorkflowEngine2 } from "@dudousxd/nestjs-durable-core";
1320
1344
  import { Injectable as Injectable4 } from "@nestjs/common";
1321
1345
  import "reflect-metadata";
1322
1346
  function _ts_decorate4(decorators, target, key, desc) {
@@ -1399,7 +1423,7 @@ EntityService = _ts_decorate4([
1399
1423
  Injectable4(),
1400
1424
  _ts_metadata4("design:type", Function),
1401
1425
  _ts_metadata4("design:paramtypes", [
1402
- typeof WorkflowEngine === "undefined" ? Object : WorkflowEngine
1426
+ typeof WorkflowEngine2 === "undefined" ? Object : WorkflowEngine2
1403
1427
  ])
1404
1428
  ], EntityService);
1405
1429
 
@@ -1590,7 +1614,9 @@ var KNOWN_KINDS = /* @__PURE__ */ new Set([
1590
1614
  "redispatch",
1591
1615
  "waitingFor",
1592
1616
  "republishLifecycle",
1593
- "workflowLifecycle"
1617
+ "workflowLifecycle",
1618
+ "signal",
1619
+ "schedule"
1594
1620
  ]);
1595
1621
  function wireDate(value) {
1596
1622
  if (value === void 0 || value === null) return void 0;
@@ -1809,6 +1835,43 @@ var RunRequestResponder = class {
1809
1835
  }
1810
1836
  };
1811
1837
  }
1838
+ if (body.kind === "schedule") {
1839
+ const { getSchedule, scheduleAction } = this.gateway;
1840
+ if (!getSchedule || !scheduleAction) return unsupported(msg.requestId, body.kind);
1841
+ if (body.action !== "pause" && body.action !== "resume" && body.action !== "trigger") {
1842
+ return badRequest(msg.requestId, `unknown schedule action ${JSON.stringify(body.action)}`);
1843
+ }
1844
+ const schedule = await getSchedule.call(this.gateway, body.id);
1845
+ if (!schedule || schedule.namespace !== msg.tenant) {
1846
+ return {
1847
+ requestId: msg.requestId,
1848
+ result: {
1849
+ ok: false,
1850
+ error: {
1851
+ message: `schedule "${body.id}" not found`,
1852
+ code: "not-found"
1853
+ }
1854
+ }
1855
+ };
1856
+ }
1857
+ return this.answer(msg.requestId, () => scheduleAction.call(this.gateway, body.id, body.action));
1858
+ }
1859
+ if (body.kind === "signal") {
1860
+ const { signal, signalWaiter } = this.gateway;
1861
+ if (!signal || !signalWaiter) return unsupported(msg.requestId, body.kind);
1862
+ const waiterRunId = await signalWaiter.call(this.gateway, body.token);
1863
+ const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;
1864
+ if (!waiter || waiter.namespace !== msg.tenant) {
1865
+ return {
1866
+ requestId: msg.requestId,
1867
+ result: {
1868
+ ok: true,
1869
+ data: null
1870
+ }
1871
+ };
1872
+ }
1873
+ return this.answer(msg.requestId, () => signal.call(this.gateway, body.token, body.payload));
1874
+ }
1812
1875
  if (body.kind === "republishLifecycle" && !this.gateway.republishLifecycle) {
1813
1876
  return unsupported(msg.requestId, body.kind);
1814
1877
  }
@@ -1882,6 +1945,32 @@ var RunRequestResponder = class {
1882
1945
  };
1883
1946
  }
1884
1947
  }
1948
+ /** The run alone (`getRun`, else from its detail), or null when it does not exist. */
1949
+ async runOf(runId) {
1950
+ return this.gateway.getRun ? this.gateway.getRun(runId) : (await this.gateway.getRunDetail(runId))?.run ?? null;
1951
+ }
1952
+ /** `call`'s result as an `ok` reply, or its rejection as an error reply. */
1953
+ async answer(requestId, call) {
1954
+ try {
1955
+ return {
1956
+ requestId,
1957
+ result: {
1958
+ ok: true,
1959
+ data: await call()
1960
+ }
1961
+ };
1962
+ } catch (err) {
1963
+ return {
1964
+ requestId,
1965
+ result: {
1966
+ ok: false,
1967
+ error: {
1968
+ message: err instanceof Error ? err.message : String(err)
1969
+ }
1970
+ }
1971
+ };
1972
+ }
1973
+ }
1885
1974
  /**
1886
1975
  * `detail` scoped to `tenant` (see {@link scopeRunLinks}), with its lifecycle links
1887
1976
  * (`workflowLifecycle`, `lifecycleSubscribers`) narrowed to the subscriptions of `tenant`'s
@@ -2669,7 +2758,7 @@ RetentionPoller = _ts_decorate8([
2669
2758
  ], RetentionPoller);
2670
2759
 
2671
2760
  // src/store-run-gateway.ts
2672
- 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";
2761
+ import { LIFECYCLE_REGISTRY_WORKFLOW, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL2, SUMMARY_CHILD_LIMIT as SUMMARY_CHILD_LIMIT2, WorkflowEngine as WorkflowEngine3, 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";
2673
2762
  import { Inject as Inject6, Injectable as Injectable9 } from "@nestjs/common";
2674
2763
  function _ts_decorate9(decorators, target, key, desc) {
2675
2764
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -3015,6 +3104,27 @@ var StoreRunGateway = class {
3015
3104
  republishLifecycle(target) {
3016
3105
  return this.engine.republishLifecycle(target);
3017
3106
  }
3107
+ /** The persisted schedules (`[]` when the store does not persist them). */
3108
+ async listSchedules(query) {
3109
+ return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];
3110
+ }
3111
+ async getSchedule(id) {
3112
+ if (!this.engine.schedules?.supported) return null;
3113
+ return await this.engine.schedules.get(id) ?? null;
3114
+ }
3115
+ scheduleAction(id, action) {
3116
+ if (action === "pause") return this.engine.schedules.pause(id);
3117
+ if (action === "resume") return this.engine.schedules.resume(id);
3118
+ if (action === "trigger") return this.engine.schedules.trigger(id);
3119
+ return Promise.reject(new Error(`unknown schedule action ${String(action)}`));
3120
+ }
3121
+ signal(token, payload) {
3122
+ return this.engine.signal(token, payload);
3123
+ }
3124
+ async signalWaiter(token) {
3125
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
3126
+ return waiter?.runId ?? null;
3127
+ }
3018
3128
  /**
3019
3129
  * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
3020
3130
  * run that does not exist yet are held until its row shows whose it is.
@@ -3061,7 +3171,7 @@ StoreRunGateway = _ts_decorate9([
3061
3171
  _ts_metadata9("design:type", Function),
3062
3172
  _ts_metadata9("design:paramtypes", [
3063
3173
  typeof StateStore === "undefined" ? Object : StateStore,
3064
- typeof WorkflowEngine2 === "undefined" ? Object : WorkflowEngine2
3174
+ typeof WorkflowEngine3 === "undefined" ? Object : WorkflowEngine3
3065
3175
  ])
3066
3176
  ], StoreRunGateway);
3067
3177
 
@@ -3108,7 +3218,7 @@ var TenantEventRepublisher = class {
3108
3218
 
3109
3219
  // src/timer-poller.ts
3110
3220
  import * as durableCore from "@dudousxd/nestjs-durable-core";
3111
- import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL6, WorkflowEngine as WorkflowEngine3, runSchedules, workflowName as workflowName3 } from "@dudousxd/nestjs-durable-core";
3221
+ import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL6, WorkflowEngine as WorkflowEngine4, runSchedules, workflowName as workflowName3 } from "@dudousxd/nestjs-durable-core";
3112
3222
  import { Inject as Inject7, Injectable as Injectable10, Optional as Optional3 } from "@nestjs/common";
3113
3223
  function _ts_decorate10(decorators, target, key, desc) {
3114
3224
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -3368,7 +3478,7 @@ TimerPoller = _ts_decorate10([
3368
3478
  _ts_param7(2, Optional3()),
3369
3479
  _ts_metadata10("design:type", Function),
3370
3480
  _ts_metadata10("design:paramtypes", [
3371
- typeof WorkflowEngine3 === "undefined" ? Object : WorkflowEngine3,
3481
+ typeof WorkflowEngine4 === "undefined" ? Object : WorkflowEngine4,
3372
3482
  typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3373
3483
  typeof SweepLeases === "undefined" ? Object : SweepLeases
3374
3484
  ])
@@ -3380,7 +3490,7 @@ var CONTEXT_ACCESSOR = Symbol.for("@dudousxd/nestjs-context:accessor");
3380
3490
  var RUN_GATEWAY = RunGateway;
3381
3491
 
3382
3492
  // src/workflow.registrar.ts
3383
- import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL7, RemoteWorkflowExecutor, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL3, WorkflowEngine as WorkflowEngine4, bindWorkflowClass, sanitizeQueueToken, tenantGroup, workflowName as workflowName4 } from "@dudousxd/nestjs-durable-core";
3493
+ import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL7, RemoteWorkflowExecutor, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL3, WorkflowEngine as WorkflowEngine5, bindWorkflowClass as bindWorkflowClass2, sanitizeQueueToken, tenantGroup, workflowName as workflowName4 } from "@dudousxd/nestjs-durable-core";
3384
3494
  import { Inject as Inject8, Injectable as Injectable11 } from "@nestjs/common";
3385
3495
  import { DiscoveryService as DiscoveryService4, MetadataScanner as MetadataScanner4 } from "@nestjs/core";
3386
3496
 
@@ -3525,7 +3635,7 @@ var WorkflowRegistrar = class {
3525
3635
  executor: new RemoteWorkflowExecutor(this.inAppWorker.transport, meta.name, this.inAppWorker.partition)
3526
3636
  } : {}
3527
3637
  });
3528
- bindWorkflowClass(workflowCtor, {
3638
+ bindWorkflowClass2(workflowCtor, {
3529
3639
  start: /* @__PURE__ */ __name((name, input, runId, opts) => this.engine.start(name, input, runId, opts), "start"),
3530
3640
  waitForRun: /* @__PURE__ */ __name((runId, opts) => this.engine.waitForRun(runId, opts), "waitForRun")
3531
3641
  });
@@ -3620,7 +3730,7 @@ WorkflowRegistrar = _ts_decorate11([
3620
3730
  _ts_metadata11("design:paramtypes", [
3621
3731
  typeof DiscoveryService4 === "undefined" ? Object : DiscoveryService4,
3622
3732
  typeof MetadataScanner4 === "undefined" ? Object : MetadataScanner4,
3623
- typeof WorkflowEngine4 === "undefined" ? Object : WorkflowEngine4,
3733
+ typeof WorkflowEngine5 === "undefined" ? Object : WorkflowEngine5,
3624
3734
  Object,
3625
3735
  typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3626
3736
  Object
@@ -3629,7 +3739,7 @@ WorkflowRegistrar = _ts_decorate11([
3629
3739
 
3630
3740
  // src/workflow.service.ts
3631
3741
  import { randomUUID } from "node:crypto";
3632
- import { WorkflowEngine as WorkflowEngine5 } from "@dudousxd/nestjs-durable-core";
3742
+ import { WorkflowEngine as WorkflowEngine6 } from "@dudousxd/nestjs-durable-core";
3633
3743
  import { Injectable as Injectable12 } from "@nestjs/common";
3634
3744
  function _ts_decorate12(decorators, target, key, desc) {
3635
3745
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -3720,7 +3830,7 @@ WorkflowService = _ts_decorate12([
3720
3830
  Injectable12(),
3721
3831
  _ts_metadata12("design:type", Function),
3722
3832
  _ts_metadata12("design:paramtypes", [
3723
- typeof WorkflowEngine5 === "undefined" ? Object : WorkflowEngine5
3833
+ typeof WorkflowEngine6 === "undefined" ? Object : WorkflowEngine6
3724
3834
  ])
3725
3835
  ], WorkflowService);
3726
3836
 
@@ -3956,7 +4066,7 @@ RunGatewayBootstrap = _ts_decorate13([
3956
4066
  _ts_param9(5, Inject9(TENANT_AUTH)),
3957
4067
  _ts_metadata13("design:type", Function),
3958
4068
  _ts_metadata13("design:paramtypes", [
3959
- typeof WorkflowEngine6 === "undefined" ? Object : WorkflowEngine6,
4069
+ typeof WorkflowEngine7 === "undefined" ? Object : WorkflowEngine7,
3960
4070
  Object,
3961
4071
  typeof RunGateway2 === "undefined" ? Object : RunGateway2,
3962
4072
  Object,
@@ -4079,7 +4189,7 @@ var DurableModule = class _DurableModule {
4079
4189
  // Shared token, bound EXACTLY once: a real engine for the operator role, or a store-less
4080
4190
  // `DurableStartClient` facade for a thin worker (no `store`) — either way, `WorkflowService`
4081
4191
  // and app code call `engine.start(...)` unchanged.
4082
- provide: WorkflowEngine6,
4192
+ provide: WorkflowEngine7,
4083
4193
  useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef, auth) => {
4084
4194
  if (options.store === void 0) {
4085
4195
  return new DurableStartClient({
@@ -4106,7 +4216,7 @@ var DurableModule = class _DurableModule {
4106
4216
  if (t) deferTransportConsumers(t);
4107
4217
  }
4108
4218
  }
4109
- const engine = new WorkflowEngine6({
4219
+ const engine = new WorkflowEngine7({
4110
4220
  store,
4111
4221
  transport: transport ?? void 0,
4112
4222
  transports: options.transports,
@@ -4186,7 +4296,7 @@ var DurableModule = class _DurableModule {
4186
4296
  inject: [
4187
4297
  DURABLE_OPTIONS_CANONICAL8,
4188
4298
  STATE_STORE_CANONICAL4,
4189
- WorkflowEngine6,
4299
+ WorkflowEngine7,
4190
4300
  TENANT_AUTH,
4191
4301
  ModuleRef2
4192
4302
  ]
@@ -4203,7 +4313,7 @@ var DurableModule = class _DurableModule {
4203
4313
  exports: [
4204
4314
  WorkflowService,
4205
4315
  EntityService,
4206
- WorkflowEngine6,
4316
+ WorkflowEngine7,
4207
4317
  STATE_STORE,
4208
4318
  STATE_STORE_CANONICAL4,
4209
4319
  TRANSPORT,
@@ -4218,8 +4328,268 @@ DurableModule = _ts_decorate13([
4218
4328
  Module({})
4219
4329
  ], DurableModule);
4220
4330
 
4331
+ // src/federated-app-gateway.ts
4332
+ import { WorkflowEngine as WorkflowEngine8 } from "@dudousxd/nestjs-durable-core";
4333
+ var FederatedAppGateway = class {
4334
+ static {
4335
+ __name(this, "FederatedAppGateway");
4336
+ }
4337
+ options;
4338
+ reads;
4339
+ pending = /* @__PURE__ */ new Map();
4340
+ listening = false;
4341
+ timeoutMs;
4342
+ /** Live-tail listeners by run id, fed by ONE subscription to the app's control channel. */
4343
+ tails = /* @__PURE__ */ new Map();
4344
+ tailing = false;
4345
+ constructor(options) {
4346
+ this.options = options;
4347
+ this.reads = new StoreRunGateway(options.store, new WorkflowEngine8({
4348
+ store: options.store
4349
+ }));
4350
+ this.timeoutMs = options.timeoutMs ?? 1e4;
4351
+ }
4352
+ topology() {
4353
+ return {
4354
+ role: "control-plane"
4355
+ };
4356
+ }
4357
+ getRunDetail(runId, options) {
4358
+ return this.reads.getRunDetail(runId, options);
4359
+ }
4360
+ getFanMembers(runId, group, query) {
4361
+ return this.reads.getFanMembers(runId, group, query);
4362
+ }
4363
+ getRun(runId) {
4364
+ return this.reads.getRun(runId);
4365
+ }
4366
+ listRuns(query) {
4367
+ return this.reads.listRuns(query);
4368
+ }
4369
+ runFacets(query) {
4370
+ return this.reads.runFacets(query);
4371
+ }
4372
+ runValueFacets(axis, query, opts) {
4373
+ return this.reads.runValueFacets(axis, query, opts);
4374
+ }
4375
+ waitingFor(runIds) {
4376
+ return this.reads.waitingFor(runIds);
4377
+ }
4378
+ workflowLifecycle(workflow, opts) {
4379
+ return this.reads.workflowLifecycle(workflow, opts);
4380
+ }
4381
+ lifecycleSubscribers(workflow, kind, namespace) {
4382
+ return this.reads.lifecycleSubscribers(workflow, kind, namespace);
4383
+ }
4384
+ /** The app's worker groups, read from its broker (read-only). `[]` when the transport can't. */
4385
+ async workerHealth() {
4386
+ const { transport } = this.options;
4387
+ if (!transport.listWorkerGroups || !transport.groupHealth) return [];
4388
+ const groups = await transport.listWorkerGroups();
4389
+ return Promise.all(groups.map((group) => transport.groupHealth?.(group)));
4390
+ }
4391
+ listSchedules(query) {
4392
+ return this.reads.listSchedules(query);
4393
+ }
4394
+ getSchedule(id) {
4395
+ return this.reads.getSchedule(id);
4396
+ }
4397
+ signalWaiter(token) {
4398
+ return this.reads.signalWaiter(token);
4399
+ }
4400
+ cancel(runId, opts) {
4401
+ return this.onRun(runId, (namespace) => this.request(namespace, opts === void 0 ? {
4402
+ kind: "cancel",
4403
+ runId
4404
+ } : {
4405
+ kind: "cancel",
4406
+ runId,
4407
+ opts
4408
+ }));
4409
+ }
4410
+ retry(runId) {
4411
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4412
+ kind: "retry",
4413
+ runId
4414
+ }));
4415
+ }
4416
+ continue(runId) {
4417
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4418
+ kind: "continue",
4419
+ runId
4420
+ }));
4421
+ }
4422
+ retryWithInput(runId, input) {
4423
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4424
+ kind: "retryWithInput",
4425
+ runId,
4426
+ input
4427
+ }));
4428
+ }
4429
+ redispatchPending(runId) {
4430
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4431
+ kind: "redispatch",
4432
+ runId
4433
+ }));
4434
+ }
4435
+ async republishLifecycle(target) {
4436
+ let namespace;
4437
+ if ("runId" in target) {
4438
+ const run = await this.reads.getRun(target.runId);
4439
+ if (!run) throw new Error(`run ${target.runId} not found`);
4440
+ namespace = run.namespace || "default";
4441
+ } else {
4442
+ namespace = target.namespace;
4443
+ if (namespace === void 0) {
4444
+ throw Object.assign(new Error("republish by workflow needs a namespace on a federated app"), {
4445
+ code: "bad-request"
4446
+ });
4447
+ }
4448
+ }
4449
+ return this.request(namespace, {
4450
+ kind: "republishLifecycle",
4451
+ target
4452
+ });
4453
+ }
4454
+ /**
4455
+ * Pause, resume or trigger one of the app's persisted schedules, executed by the app. A schedule
4456
+ * that does not exist rejects with a `ScheduleNotFoundError`, as the engine's own client does.
4457
+ */
4458
+ async scheduleAction(id, action) {
4459
+ const schedule = await this.reads.getSchedule(id);
4460
+ if (!schedule) throw scheduleNotFound(id);
4461
+ try {
4462
+ return await this.request(schedule.namespace, {
4463
+ kind: "schedule",
4464
+ id,
4465
+ action
4466
+ });
4467
+ } catch (err) {
4468
+ if (err instanceof RunGatewayError && err.code === "not-found") throw scheduleNotFound(id);
4469
+ throw err;
4470
+ }
4471
+ }
4472
+ /**
4473
+ * Deliver `payload` to the app's run waiting on `token`, by the app. Null when no run of the app
4474
+ * waits on it yet: unlike the engine's own `signal`, nothing is buffered for a later wait.
4475
+ */
4476
+ async signal(token, payload) {
4477
+ const runId = await this.reads.signalWaiter(token);
4478
+ if (!runId) return null;
4479
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4480
+ kind: "signal",
4481
+ token,
4482
+ payload
4483
+ }));
4484
+ }
4485
+ /**
4486
+ * The app's live events for `runId`, from the control channel its engines broadcast every event on
4487
+ * (see {@link FederatedAppGatewayOptions.controlPlane}). Nothing when there is none.
4488
+ */
4489
+ subscribe(runId, onEvent) {
4490
+ const control = this.controlPlane();
4491
+ if (!control) return () => void 0;
4492
+ if (!this.tailing) {
4493
+ this.tailing = true;
4494
+ control.onControl((msg) => this.deliver(msg));
4495
+ }
4496
+ let listeners = this.tails.get(runId);
4497
+ if (!listeners) {
4498
+ listeners = /* @__PURE__ */ new Set();
4499
+ this.tails.set(runId, listeners);
4500
+ }
4501
+ listeners.add(onEvent);
4502
+ return () => {
4503
+ const current = this.tails.get(runId);
4504
+ current?.delete(onEvent);
4505
+ if (current?.size === 0) this.tails.delete(runId);
4506
+ };
4507
+ }
4508
+ controlPlane() {
4509
+ if (this.options.controlPlane) return this.options.controlPlane;
4510
+ const candidate = this.options.transport;
4511
+ return typeof candidate.onControl === "function" ? this.options.transport : void 0;
4512
+ }
4513
+ deliver(msg) {
4514
+ if (this.tails.size === 0) return;
4515
+ const events = msg.kind === "event" ? [
4516
+ msg.event
4517
+ ] : msg.kind === "events" ? msg.events : [];
4518
+ for (const event of events) {
4519
+ const listeners = this.tails.get(event.runId);
4520
+ if (!listeners) continue;
4521
+ const live = {
4522
+ ...event,
4523
+ at: new Date(event.at)
4524
+ };
4525
+ for (const listener of listeners) listener(live);
4526
+ }
4527
+ }
4528
+ /** `act` with the namespace of `runId`, or null when the app has no such run. */
4529
+ async onRun(runId, act) {
4530
+ const run = await this.reads.getRun(runId);
4531
+ if (!run) return null;
4532
+ return act(run.namespace || "default");
4533
+ }
4534
+ /** Send `body` to the app as a run request from `namespace`, and wait for its reply. */
4535
+ async request(namespace, body) {
4536
+ const { transport, tenantToken } = this.options;
4537
+ if (!transport.dispatchRunRequest || !transport.onRunReply) {
4538
+ throw new Error("a federated app needs a transport that carries run requests (e.g. BullMQTransport)");
4539
+ }
4540
+ this.listen();
4541
+ const tenant = tenantToken ? await tenantToken(namespace) : namespace;
4542
+ return new Promise((resolve, reject) => {
4543
+ const requestId = globalThis.crypto.randomUUID();
4544
+ const timer = setTimeout(() => {
4545
+ this.pending.delete(requestId);
4546
+ reject(new Error(`the app did not answer ${body.kind} within ${this.timeoutMs}ms`));
4547
+ }, this.timeoutMs);
4548
+ this.pending.set(requestId, {
4549
+ resolve: /* @__PURE__ */ __name((data) => resolve(data), "resolve"),
4550
+ reject,
4551
+ timer
4552
+ });
4553
+ transport.dispatchRunRequest?.({
4554
+ requestId,
4555
+ tenant,
4556
+ body
4557
+ })?.catch((error) => {
4558
+ const entry = this.pending.get(requestId);
4559
+ if (!entry) return;
4560
+ clearTimeout(entry.timer);
4561
+ this.pending.delete(requestId);
4562
+ entry.reject(error instanceof Error ? error : new Error(String(error)));
4563
+ });
4564
+ });
4565
+ }
4566
+ listen() {
4567
+ if (this.listening) return;
4568
+ this.listening = true;
4569
+ this.options.transport.onRunReply?.((reply) => this.handleReply(reply));
4570
+ }
4571
+ handleReply(reply) {
4572
+ const entry = this.pending.get(reply.requestId);
4573
+ if (!entry) return;
4574
+ clearTimeout(entry.timer);
4575
+ this.pending.delete(reply.requestId);
4576
+ if (reply.result.ok) entry.resolve(reply.result.data);
4577
+ else entry.reject(new RunGatewayError(reply.result.error.message, reply.result.error.code));
4578
+ }
4579
+ };
4580
+ function scheduleNotFound(id) {
4581
+ return Object.assign(new Error(`schedule "${id}" not found`), {
4582
+ name: "ScheduleNotFoundError"
4583
+ });
4584
+ }
4585
+ __name(scheduleNotFound, "scheduleNotFound");
4586
+ function federatedAppGateway(options) {
4587
+ return new FederatedAppGateway(options);
4588
+ }
4589
+ __name(federatedAppGateway, "federatedAppGateway");
4590
+
4221
4591
  // src/index.ts
4222
- import { DuplicateDurableCopyError, 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";
4592
+ import { DuplicateDurableCopyError, 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 WorkflowEngine9 } from "@dudousxd/nestjs-durable-core";
4223
4593
  export {
4224
4594
  BAD_RUN_REQUEST,
4225
4595
  CONTEXT_ACCESSOR,
@@ -4235,6 +4605,7 @@ export {
4235
4605
  ENTITY_ON_METADATA,
4236
4606
  Entity,
4237
4607
  EntityService,
4608
+ FederatedAppGateway,
4238
4609
  IN_APP_RUN_REDIS_WORKER,
4239
4610
  IN_APP_WORKER_BINDING,
4240
4611
  IN_APP_WORKER_RUNNERS,
@@ -4267,11 +4638,12 @@ export {
4267
4638
  UNSUPPORTED_RUN_REQUEST,
4268
4639
  WORKFLOW_METADATA,
4269
4640
  Workflow,
4270
- WorkflowEngine7 as WorkflowEngine,
4641
+ WorkflowEngine9 as WorkflowEngine,
4271
4642
  WorkflowService,
4272
4643
  attributesOf,
4273
4644
  entityConfigFor,
4274
4645
  eventBatchOf,
4646
+ federatedAppGateway,
4275
4647
  getDurableStepMeta,
4276
4648
  getEntityMeta,
4277
4649
  getOnEvents,