@dudousxd/nestjs-durable 0.61.0 → 0.62.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
@@ -38,19 +38,20 @@ __export(src_exports, {
38
38
  DURABLE_WORKER_RUNNERS: () => DURABLE_WORKER_RUNNERS,
39
39
  DURABLE_WORKER_RUNTIME: () => DURABLE_WORKER_RUNTIME,
40
40
  DeadLetter: () => DeadLetter,
41
- DuplicateDurableCopyError: () => import_nestjs_durable_core20.DuplicateDurableCopyError,
41
+ DuplicateDurableCopyError: () => import_nestjs_durable_core21.DuplicateDurableCopyError,
42
42
  DurableModule: () => DurableModule,
43
43
  DurableStartClient: () => DurableStartClient,
44
44
  ENTITY_METADATA: () => ENTITY_METADATA,
45
45
  ENTITY_ON_METADATA: () => ENTITY_ON_METADATA,
46
46
  Entity: () => Entity,
47
47
  EntityService: () => EntityService,
48
+ FederatedAppGateway: () => FederatedAppGateway,
48
49
  IN_APP_RUN_REDIS_WORKER: () => IN_APP_RUN_REDIS_WORKER,
49
50
  IN_APP_WORKER_BINDING: () => IN_APP_WORKER_BINDING,
50
51
  IN_APP_WORKER_RUNNERS: () => IN_APP_WORKER_RUNNERS,
51
52
  IN_APP_WORKER_RUNTIME: () => IN_APP_WORKER_RUNTIME,
52
53
  InAppWorkerBootstrap: () => InAppWorkerBootstrap,
53
- LIFECYCLE_PENDING_TAG: () => import_nestjs_durable_core20.LIFECYCLE_PENDING_TAG,
54
+ LIFECYCLE_PENDING_TAG: () => import_nestjs_durable_core21.LIFECYCLE_PENDING_TAG,
54
55
  ON_ERROR_METADATA: () => ON_ERROR_METADATA,
55
56
  ON_EVENT_BATCH_METADATA: () => ON_EVENT_BATCH_METADATA,
56
57
  ON_EVENT_METADATA: () => ON_EVENT_METADATA,
@@ -62,7 +63,7 @@ __export(src_exports, {
62
63
  ProxyRunGateway: () => ProxyRunGateway,
63
64
  RUN_GATEWAY: () => RUN_GATEWAY,
64
65
  RUN_REDIS_WORKER: () => RUN_REDIS_WORKER,
65
- RunGateway: () => import_nestjs_durable_core20.RunGateway,
66
+ RunGateway: () => import_nestjs_durable_core21.RunGateway,
66
67
  RunGatewayError: () => RunGatewayError,
67
68
  RunRequestResponder: () => RunRequestResponder,
68
69
  STEP_INTERCEPTOR_METADATA: () => STEP_INTERCEPTOR_METADATA,
@@ -77,34 +78,35 @@ __export(src_exports, {
77
78
  UNSUPPORTED_RUN_REQUEST: () => UNSUPPORTED_RUN_REQUEST,
78
79
  WORKFLOW_METADATA: () => WORKFLOW_METADATA,
79
80
  Workflow: () => Workflow,
80
- WorkflowEngine: () => import_nestjs_durable_core20.WorkflowEngine,
81
+ WorkflowEngine: () => import_nestjs_durable_core21.WorkflowEngine,
81
82
  WorkflowService: () => WorkflowService,
82
83
  attributesOf: () => attributesOf,
83
84
  entityConfigFor: () => entityConfigFor,
84
85
  eventBatchOf: () => eventBatchOf,
86
+ federatedAppGateway: () => federatedAppGateway,
85
87
  getDurableStepMeta: () => getDurableStepMeta,
86
88
  getEntityMeta: () => getEntityMeta,
87
89
  getOnEvents: () => getOnEvents,
88
90
  getWorkflowMeta: () => getWorkflowMeta,
89
- hmacTenantVerifier: () => import_nestjs_durable_core20.hmacTenantVerifier,
91
+ hmacTenantVerifier: () => import_nestjs_durable_core21.hmacTenantVerifier,
90
92
  inAppWorkerProviders: () => inAppWorkerProviders,
91
93
  isDeadLetterHandler: () => isDeadLetterHandler,
92
94
  isDrivingOperator: () => isDrivingOperator,
93
95
  isOperatorRole: () => isOperatorRole,
94
96
  isStepInterceptor: () => isStepInterceptor,
95
- lifecycleRunId: () => import_nestjs_durable_core20.lifecycleRunId,
96
- lifecycleSourceOf: () => import_nestjs_durable_core20.lifecycleSourceOf,
97
+ lifecycleRunId: () => import_nestjs_durable_core21.lifecycleRunId,
98
+ lifecycleSourceOf: () => import_nestjs_durable_core21.lifecycleSourceOf,
97
99
  onErrorCodesOf: () => onErrorCodesOf,
98
- prevCronFireMs: () => import_nestjs_durable_core20.prevCronFireMs,
99
- readSearchAttributes: () => import_nestjs_durable_core20.readSearchAttributes,
100
- runCompletedEvent: () => import_nestjs_durable_core20.runCompletedEvent,
101
- runFailedEvent: () => import_nestjs_durable_core20.runFailedEvent,
102
- runSchedules: () => import_nestjs_durable_core20.runSchedules,
103
- scheduleRunIdAt: () => import_nestjs_durable_core20.scheduleRunIdAt,
104
- scheduledRunId: () => import_nestjs_durable_core20.scheduledRunId,
105
- signTenantToken: () => import_nestjs_durable_core20.signTenantToken,
100
+ prevCronFireMs: () => import_nestjs_durable_core21.prevCronFireMs,
101
+ readSearchAttributes: () => import_nestjs_durable_core21.readSearchAttributes,
102
+ runCompletedEvent: () => import_nestjs_durable_core21.runCompletedEvent,
103
+ runFailedEvent: () => import_nestjs_durable_core21.runFailedEvent,
104
+ runSchedules: () => import_nestjs_durable_core21.runSchedules,
105
+ scheduleRunIdAt: () => import_nestjs_durable_core21.scheduleRunIdAt,
106
+ scheduledRunId: () => import_nestjs_durable_core21.scheduledRunId,
107
+ signTenantToken: () => import_nestjs_durable_core21.signTenantToken,
106
108
  thinWorkerProviders: () => thinWorkerProviders,
107
- triggeredRunsOf: () => import_nestjs_durable_core20.triggeredRunsOf,
109
+ triggeredRunsOf: () => import_nestjs_durable_core21.triggeredRunsOf,
108
110
  unavailableRunGateway: () => unavailableRunGateway
109
111
  });
110
112
  module.exports = __toCommonJS(src_exports);
@@ -1698,7 +1700,9 @@ var KNOWN_KINDS = /* @__PURE__ */ new Set([
1698
1700
  "redispatch",
1699
1701
  "waitingFor",
1700
1702
  "republishLifecycle",
1701
- "workflowLifecycle"
1703
+ "workflowLifecycle",
1704
+ "signal",
1705
+ "schedule"
1702
1706
  ]);
1703
1707
  function wireDate(value) {
1704
1708
  if (value === void 0 || value === null) return void 0;
@@ -1917,6 +1921,43 @@ var RunRequestResponder = class {
1917
1921
  }
1918
1922
  };
1919
1923
  }
1924
+ if (body.kind === "schedule") {
1925
+ const { getSchedule, scheduleAction } = this.gateway;
1926
+ if (!getSchedule || !scheduleAction) return unsupported(msg.requestId, body.kind);
1927
+ if (body.action !== "pause" && body.action !== "resume" && body.action !== "trigger") {
1928
+ return badRequest(msg.requestId, `unknown schedule action ${JSON.stringify(body.action)}`);
1929
+ }
1930
+ const schedule = await getSchedule.call(this.gateway, body.id);
1931
+ if (!schedule || schedule.namespace !== msg.tenant) {
1932
+ return {
1933
+ requestId: msg.requestId,
1934
+ result: {
1935
+ ok: false,
1936
+ error: {
1937
+ message: `schedule "${body.id}" not found`,
1938
+ code: "not-found"
1939
+ }
1940
+ }
1941
+ };
1942
+ }
1943
+ return this.answer(msg.requestId, () => scheduleAction.call(this.gateway, body.id, body.action));
1944
+ }
1945
+ if (body.kind === "signal") {
1946
+ const { signal, signalWaiter } = this.gateway;
1947
+ if (!signal || !signalWaiter) return unsupported(msg.requestId, body.kind);
1948
+ const waiterRunId = await signalWaiter.call(this.gateway, body.token);
1949
+ const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;
1950
+ if (!waiter || waiter.namespace !== msg.tenant) {
1951
+ return {
1952
+ requestId: msg.requestId,
1953
+ result: {
1954
+ ok: true,
1955
+ data: null
1956
+ }
1957
+ };
1958
+ }
1959
+ return this.answer(msg.requestId, () => signal.call(this.gateway, body.token, body.payload));
1960
+ }
1920
1961
  if (body.kind === "republishLifecycle" && !this.gateway.republishLifecycle) {
1921
1962
  return unsupported(msg.requestId, body.kind);
1922
1963
  }
@@ -1990,6 +2031,32 @@ var RunRequestResponder = class {
1990
2031
  };
1991
2032
  }
1992
2033
  }
2034
+ /** The run alone (`getRun`, else from its detail), or null when it does not exist. */
2035
+ async runOf(runId) {
2036
+ return this.gateway.getRun ? this.gateway.getRun(runId) : (await this.gateway.getRunDetail(runId))?.run ?? null;
2037
+ }
2038
+ /** `call`'s result as an `ok` reply, or its rejection as an error reply. */
2039
+ async answer(requestId, call) {
2040
+ try {
2041
+ return {
2042
+ requestId,
2043
+ result: {
2044
+ ok: true,
2045
+ data: await call()
2046
+ }
2047
+ };
2048
+ } catch (err) {
2049
+ return {
2050
+ requestId,
2051
+ result: {
2052
+ ok: false,
2053
+ error: {
2054
+ message: err instanceof Error ? err.message : String(err)
2055
+ }
2056
+ }
2057
+ };
2058
+ }
2059
+ }
1993
2060
  /**
1994
2061
  * `detail` scoped to `tenant` (see {@link scopeRunLinks}), with its lifecycle links
1995
2062
  * (`workflowLifecycle`, `lifecycleSubscribers`) narrowed to the subscriptions of `tenant`'s
@@ -3123,6 +3190,27 @@ var StoreRunGateway = class {
3123
3190
  republishLifecycle(target) {
3124
3191
  return this.engine.republishLifecycle(target);
3125
3192
  }
3193
+ /** The persisted schedules (`[]` when the store does not persist them). */
3194
+ async listSchedules(query) {
3195
+ return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];
3196
+ }
3197
+ async getSchedule(id) {
3198
+ if (!this.engine.schedules?.supported) return null;
3199
+ return await this.engine.schedules.get(id) ?? null;
3200
+ }
3201
+ scheduleAction(id, action) {
3202
+ if (action === "pause") return this.engine.schedules.pause(id);
3203
+ if (action === "resume") return this.engine.schedules.resume(id);
3204
+ if (action === "trigger") return this.engine.schedules.trigger(id);
3205
+ return Promise.reject(new Error(`unknown schedule action ${String(action)}`));
3206
+ }
3207
+ signal(token, payload) {
3208
+ return this.engine.signal(token, payload);
3209
+ }
3210
+ async signalWaiter(token) {
3211
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
3212
+ return waiter?.runId ?? null;
3213
+ }
3126
3214
  /**
3127
3215
  * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
3128
3216
  * run that does not exist yet are held until its row shows whose it is.
@@ -4326,8 +4414,268 @@ DurableModule = _ts_decorate13([
4326
4414
  (0, import_common13.Module)({})
4327
4415
  ], DurableModule);
4328
4416
 
4329
- // src/index.ts
4417
+ // src/federated-app-gateway.ts
4330
4418
  var import_nestjs_durable_core20 = require("@dudousxd/nestjs-durable-core");
4419
+ var FederatedAppGateway = class {
4420
+ static {
4421
+ __name(this, "FederatedAppGateway");
4422
+ }
4423
+ options;
4424
+ reads;
4425
+ pending = /* @__PURE__ */ new Map();
4426
+ listening = false;
4427
+ timeoutMs;
4428
+ /** Live-tail listeners by run id, fed by ONE subscription to the app's control channel. */
4429
+ tails = /* @__PURE__ */ new Map();
4430
+ tailing = false;
4431
+ constructor(options) {
4432
+ this.options = options;
4433
+ this.reads = new StoreRunGateway(options.store, new import_nestjs_durable_core20.WorkflowEngine({
4434
+ store: options.store
4435
+ }));
4436
+ this.timeoutMs = options.timeoutMs ?? 1e4;
4437
+ }
4438
+ topology() {
4439
+ return {
4440
+ role: "control-plane"
4441
+ };
4442
+ }
4443
+ getRunDetail(runId, options) {
4444
+ return this.reads.getRunDetail(runId, options);
4445
+ }
4446
+ getFanMembers(runId, group, query) {
4447
+ return this.reads.getFanMembers(runId, group, query);
4448
+ }
4449
+ getRun(runId) {
4450
+ return this.reads.getRun(runId);
4451
+ }
4452
+ listRuns(query) {
4453
+ return this.reads.listRuns(query);
4454
+ }
4455
+ runFacets(query) {
4456
+ return this.reads.runFacets(query);
4457
+ }
4458
+ runValueFacets(axis, query, opts) {
4459
+ return this.reads.runValueFacets(axis, query, opts);
4460
+ }
4461
+ waitingFor(runIds) {
4462
+ return this.reads.waitingFor(runIds);
4463
+ }
4464
+ workflowLifecycle(workflow, opts) {
4465
+ return this.reads.workflowLifecycle(workflow, opts);
4466
+ }
4467
+ lifecycleSubscribers(workflow, kind, namespace) {
4468
+ return this.reads.lifecycleSubscribers(workflow, kind, namespace);
4469
+ }
4470
+ /** The app's worker groups, read from its broker (read-only). `[]` when the transport can't. */
4471
+ async workerHealth() {
4472
+ const { transport } = this.options;
4473
+ if (!transport.listWorkerGroups || !transport.groupHealth) return [];
4474
+ const groups = await transport.listWorkerGroups();
4475
+ return Promise.all(groups.map((group) => transport.groupHealth?.(group)));
4476
+ }
4477
+ listSchedules(query) {
4478
+ return this.reads.listSchedules(query);
4479
+ }
4480
+ getSchedule(id) {
4481
+ return this.reads.getSchedule(id);
4482
+ }
4483
+ signalWaiter(token) {
4484
+ return this.reads.signalWaiter(token);
4485
+ }
4486
+ cancel(runId, opts) {
4487
+ return this.onRun(runId, (namespace) => this.request(namespace, opts === void 0 ? {
4488
+ kind: "cancel",
4489
+ runId
4490
+ } : {
4491
+ kind: "cancel",
4492
+ runId,
4493
+ opts
4494
+ }));
4495
+ }
4496
+ retry(runId) {
4497
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4498
+ kind: "retry",
4499
+ runId
4500
+ }));
4501
+ }
4502
+ continue(runId) {
4503
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4504
+ kind: "continue",
4505
+ runId
4506
+ }));
4507
+ }
4508
+ retryWithInput(runId, input) {
4509
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4510
+ kind: "retryWithInput",
4511
+ runId,
4512
+ input
4513
+ }));
4514
+ }
4515
+ redispatchPending(runId) {
4516
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4517
+ kind: "redispatch",
4518
+ runId
4519
+ }));
4520
+ }
4521
+ async republishLifecycle(target) {
4522
+ let namespace;
4523
+ if ("runId" in target) {
4524
+ const run = await this.reads.getRun(target.runId);
4525
+ if (!run) throw new Error(`run ${target.runId} not found`);
4526
+ namespace = run.namespace || "default";
4527
+ } else {
4528
+ namespace = target.namespace;
4529
+ if (namespace === void 0) {
4530
+ throw Object.assign(new Error("republish by workflow needs a namespace on a federated app"), {
4531
+ code: "bad-request"
4532
+ });
4533
+ }
4534
+ }
4535
+ return this.request(namespace, {
4536
+ kind: "republishLifecycle",
4537
+ target
4538
+ });
4539
+ }
4540
+ /**
4541
+ * Pause, resume or trigger one of the app's persisted schedules, executed by the app. A schedule
4542
+ * that does not exist rejects with a `ScheduleNotFoundError`, as the engine's own client does.
4543
+ */
4544
+ async scheduleAction(id, action) {
4545
+ const schedule = await this.reads.getSchedule(id);
4546
+ if (!schedule) throw scheduleNotFound(id);
4547
+ try {
4548
+ return await this.request(schedule.namespace, {
4549
+ kind: "schedule",
4550
+ id,
4551
+ action
4552
+ });
4553
+ } catch (err) {
4554
+ if (err instanceof RunGatewayError && err.code === "not-found") throw scheduleNotFound(id);
4555
+ throw err;
4556
+ }
4557
+ }
4558
+ /**
4559
+ * Deliver `payload` to the app's run waiting on `token`, by the app. Null when no run of the app
4560
+ * waits on it yet: unlike the engine's own `signal`, nothing is buffered for a later wait.
4561
+ */
4562
+ async signal(token, payload) {
4563
+ const runId = await this.reads.signalWaiter(token);
4564
+ if (!runId) return null;
4565
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4566
+ kind: "signal",
4567
+ token,
4568
+ payload
4569
+ }));
4570
+ }
4571
+ /**
4572
+ * The app's live events for `runId`, from the control channel its engines broadcast every event on
4573
+ * (see {@link FederatedAppGatewayOptions.controlPlane}). Nothing when there is none.
4574
+ */
4575
+ subscribe(runId, onEvent) {
4576
+ const control = this.controlPlane();
4577
+ if (!control) return () => void 0;
4578
+ if (!this.tailing) {
4579
+ this.tailing = true;
4580
+ control.onControl((msg) => this.deliver(msg));
4581
+ }
4582
+ let listeners = this.tails.get(runId);
4583
+ if (!listeners) {
4584
+ listeners = /* @__PURE__ */ new Set();
4585
+ this.tails.set(runId, listeners);
4586
+ }
4587
+ listeners.add(onEvent);
4588
+ return () => {
4589
+ const current = this.tails.get(runId);
4590
+ current?.delete(onEvent);
4591
+ if (current?.size === 0) this.tails.delete(runId);
4592
+ };
4593
+ }
4594
+ controlPlane() {
4595
+ if (this.options.controlPlane) return this.options.controlPlane;
4596
+ const candidate = this.options.transport;
4597
+ return typeof candidate.onControl === "function" ? this.options.transport : void 0;
4598
+ }
4599
+ deliver(msg) {
4600
+ if (this.tails.size === 0) return;
4601
+ const events = msg.kind === "event" ? [
4602
+ msg.event
4603
+ ] : msg.kind === "events" ? msg.events : [];
4604
+ for (const event of events) {
4605
+ const listeners = this.tails.get(event.runId);
4606
+ if (!listeners) continue;
4607
+ const live = {
4608
+ ...event,
4609
+ at: new Date(event.at)
4610
+ };
4611
+ for (const listener of listeners) listener(live);
4612
+ }
4613
+ }
4614
+ /** `act` with the namespace of `runId`, or null when the app has no such run. */
4615
+ async onRun(runId, act) {
4616
+ const run = await this.reads.getRun(runId);
4617
+ if (!run) return null;
4618
+ return act(run.namespace || "default");
4619
+ }
4620
+ /** Send `body` to the app as a run request from `namespace`, and wait for its reply. */
4621
+ async request(namespace, body) {
4622
+ const { transport, tenantToken } = this.options;
4623
+ if (!transport.dispatchRunRequest || !transport.onRunReply) {
4624
+ throw new Error("a federated app needs a transport that carries run requests (e.g. BullMQTransport)");
4625
+ }
4626
+ this.listen();
4627
+ const tenant = tenantToken ? await tenantToken(namespace) : namespace;
4628
+ return new Promise((resolve, reject) => {
4629
+ const requestId = globalThis.crypto.randomUUID();
4630
+ const timer = setTimeout(() => {
4631
+ this.pending.delete(requestId);
4632
+ reject(new Error(`the app did not answer ${body.kind} within ${this.timeoutMs}ms`));
4633
+ }, this.timeoutMs);
4634
+ this.pending.set(requestId, {
4635
+ resolve: /* @__PURE__ */ __name((data) => resolve(data), "resolve"),
4636
+ reject,
4637
+ timer
4638
+ });
4639
+ transport.dispatchRunRequest?.({
4640
+ requestId,
4641
+ tenant,
4642
+ body
4643
+ })?.catch((error) => {
4644
+ const entry = this.pending.get(requestId);
4645
+ if (!entry) return;
4646
+ clearTimeout(entry.timer);
4647
+ this.pending.delete(requestId);
4648
+ entry.reject(error instanceof Error ? error : new Error(String(error)));
4649
+ });
4650
+ });
4651
+ }
4652
+ listen() {
4653
+ if (this.listening) return;
4654
+ this.listening = true;
4655
+ this.options.transport.onRunReply?.((reply) => this.handleReply(reply));
4656
+ }
4657
+ handleReply(reply) {
4658
+ const entry = this.pending.get(reply.requestId);
4659
+ if (!entry) return;
4660
+ clearTimeout(entry.timer);
4661
+ this.pending.delete(reply.requestId);
4662
+ if (reply.result.ok) entry.resolve(reply.result.data);
4663
+ else entry.reject(new RunGatewayError(reply.result.error.message, reply.result.error.code));
4664
+ }
4665
+ };
4666
+ function scheduleNotFound(id) {
4667
+ return Object.assign(new Error(`schedule "${id}" not found`), {
4668
+ name: "ScheduleNotFoundError"
4669
+ });
4670
+ }
4671
+ __name(scheduleNotFound, "scheduleNotFound");
4672
+ function federatedAppGateway(options) {
4673
+ return new FederatedAppGateway(options);
4674
+ }
4675
+ __name(federatedAppGateway, "federatedAppGateway");
4676
+
4677
+ // src/index.ts
4678
+ var import_nestjs_durable_core21 = require("@dudousxd/nestjs-durable-core");
4331
4679
  // Annotate the CommonJS export names for ESM import in node:
4332
4680
  0 && (module.exports = {
4333
4681
  BAD_RUN_REQUEST,
@@ -4344,6 +4692,7 @@ var import_nestjs_durable_core20 = require("@dudousxd/nestjs-durable-core");
4344
4692
  ENTITY_ON_METADATA,
4345
4693
  Entity,
4346
4694
  EntityService,
4695
+ FederatedAppGateway,
4347
4696
  IN_APP_RUN_REDIS_WORKER,
4348
4697
  IN_APP_WORKER_BINDING,
4349
4698
  IN_APP_WORKER_RUNNERS,
@@ -4381,6 +4730,7 @@ var import_nestjs_durable_core20 = require("@dudousxd/nestjs-durable-core");
4381
4730
  attributesOf,
4382
4731
  entityConfigFor,
4383
4732
  eventBatchOf,
4733
+ federatedAppGateway,
4384
4734
  getDurableStepMeta,
4385
4735
  getEntityMeta,
4386
4736
  getOnEvents,