@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.js CHANGED
@@ -1590,7 +1590,9 @@ var KNOWN_KINDS = /* @__PURE__ */ new Set([
1590
1590
  "redispatch",
1591
1591
  "waitingFor",
1592
1592
  "republishLifecycle",
1593
- "workflowLifecycle"
1593
+ "workflowLifecycle",
1594
+ "signal",
1595
+ "schedule"
1594
1596
  ]);
1595
1597
  function wireDate(value) {
1596
1598
  if (value === void 0 || value === null) return void 0;
@@ -1809,6 +1811,43 @@ var RunRequestResponder = class {
1809
1811
  }
1810
1812
  };
1811
1813
  }
1814
+ if (body.kind === "schedule") {
1815
+ const { getSchedule, scheduleAction } = this.gateway;
1816
+ if (!getSchedule || !scheduleAction) return unsupported(msg.requestId, body.kind);
1817
+ if (body.action !== "pause" && body.action !== "resume" && body.action !== "trigger") {
1818
+ return badRequest(msg.requestId, `unknown schedule action ${JSON.stringify(body.action)}`);
1819
+ }
1820
+ const schedule = await getSchedule.call(this.gateway, body.id);
1821
+ if (!schedule || schedule.namespace !== msg.tenant) {
1822
+ return {
1823
+ requestId: msg.requestId,
1824
+ result: {
1825
+ ok: false,
1826
+ error: {
1827
+ message: `schedule "${body.id}" not found`,
1828
+ code: "not-found"
1829
+ }
1830
+ }
1831
+ };
1832
+ }
1833
+ return this.answer(msg.requestId, () => scheduleAction.call(this.gateway, body.id, body.action));
1834
+ }
1835
+ if (body.kind === "signal") {
1836
+ const { signal, signalWaiter } = this.gateway;
1837
+ if (!signal || !signalWaiter) return unsupported(msg.requestId, body.kind);
1838
+ const waiterRunId = await signalWaiter.call(this.gateway, body.token);
1839
+ const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;
1840
+ if (!waiter || waiter.namespace !== msg.tenant) {
1841
+ return {
1842
+ requestId: msg.requestId,
1843
+ result: {
1844
+ ok: true,
1845
+ data: null
1846
+ }
1847
+ };
1848
+ }
1849
+ return this.answer(msg.requestId, () => signal.call(this.gateway, body.token, body.payload));
1850
+ }
1812
1851
  if (body.kind === "republishLifecycle" && !this.gateway.republishLifecycle) {
1813
1852
  return unsupported(msg.requestId, body.kind);
1814
1853
  }
@@ -1882,6 +1921,32 @@ var RunRequestResponder = class {
1882
1921
  };
1883
1922
  }
1884
1923
  }
1924
+ /** The run alone (`getRun`, else from its detail), or null when it does not exist. */
1925
+ async runOf(runId) {
1926
+ return this.gateway.getRun ? this.gateway.getRun(runId) : (await this.gateway.getRunDetail(runId))?.run ?? null;
1927
+ }
1928
+ /** `call`'s result as an `ok` reply, or its rejection as an error reply. */
1929
+ async answer(requestId, call) {
1930
+ try {
1931
+ return {
1932
+ requestId,
1933
+ result: {
1934
+ ok: true,
1935
+ data: await call()
1936
+ }
1937
+ };
1938
+ } catch (err) {
1939
+ return {
1940
+ requestId,
1941
+ result: {
1942
+ ok: false,
1943
+ error: {
1944
+ message: err instanceof Error ? err.message : String(err)
1945
+ }
1946
+ }
1947
+ };
1948
+ }
1949
+ }
1885
1950
  /**
1886
1951
  * `detail` scoped to `tenant` (see {@link scopeRunLinks}), with its lifecycle links
1887
1952
  * (`workflowLifecycle`, `lifecycleSubscribers`) narrowed to the subscriptions of `tenant`'s
@@ -3015,6 +3080,27 @@ var StoreRunGateway = class {
3015
3080
  republishLifecycle(target) {
3016
3081
  return this.engine.republishLifecycle(target);
3017
3082
  }
3083
+ /** The persisted schedules (`[]` when the store does not persist them). */
3084
+ async listSchedules(query) {
3085
+ return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];
3086
+ }
3087
+ async getSchedule(id) {
3088
+ if (!this.engine.schedules?.supported) return null;
3089
+ return await this.engine.schedules.get(id) ?? null;
3090
+ }
3091
+ scheduleAction(id, action) {
3092
+ if (action === "pause") return this.engine.schedules.pause(id);
3093
+ if (action === "resume") return this.engine.schedules.resume(id);
3094
+ if (action === "trigger") return this.engine.schedules.trigger(id);
3095
+ return Promise.reject(new Error(`unknown schedule action ${String(action)}`));
3096
+ }
3097
+ signal(token, payload) {
3098
+ return this.engine.signal(token, payload);
3099
+ }
3100
+ async signalWaiter(token) {
3101
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
3102
+ return waiter?.runId ?? null;
3103
+ }
3018
3104
  /**
3019
3105
  * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
3020
3106
  * run that does not exist yet are held until its row shows whose it is.
@@ -4218,8 +4304,268 @@ DurableModule = _ts_decorate13([
4218
4304
  Module({})
4219
4305
  ], DurableModule);
4220
4306
 
4307
+ // src/federated-app-gateway.ts
4308
+ import { WorkflowEngine as WorkflowEngine7 } from "@dudousxd/nestjs-durable-core";
4309
+ var FederatedAppGateway = class {
4310
+ static {
4311
+ __name(this, "FederatedAppGateway");
4312
+ }
4313
+ options;
4314
+ reads;
4315
+ pending = /* @__PURE__ */ new Map();
4316
+ listening = false;
4317
+ timeoutMs;
4318
+ /** Live-tail listeners by run id, fed by ONE subscription to the app's control channel. */
4319
+ tails = /* @__PURE__ */ new Map();
4320
+ tailing = false;
4321
+ constructor(options) {
4322
+ this.options = options;
4323
+ this.reads = new StoreRunGateway(options.store, new WorkflowEngine7({
4324
+ store: options.store
4325
+ }));
4326
+ this.timeoutMs = options.timeoutMs ?? 1e4;
4327
+ }
4328
+ topology() {
4329
+ return {
4330
+ role: "control-plane"
4331
+ };
4332
+ }
4333
+ getRunDetail(runId, options) {
4334
+ return this.reads.getRunDetail(runId, options);
4335
+ }
4336
+ getFanMembers(runId, group, query) {
4337
+ return this.reads.getFanMembers(runId, group, query);
4338
+ }
4339
+ getRun(runId) {
4340
+ return this.reads.getRun(runId);
4341
+ }
4342
+ listRuns(query) {
4343
+ return this.reads.listRuns(query);
4344
+ }
4345
+ runFacets(query) {
4346
+ return this.reads.runFacets(query);
4347
+ }
4348
+ runValueFacets(axis, query, opts) {
4349
+ return this.reads.runValueFacets(axis, query, opts);
4350
+ }
4351
+ waitingFor(runIds) {
4352
+ return this.reads.waitingFor(runIds);
4353
+ }
4354
+ workflowLifecycle(workflow, opts) {
4355
+ return this.reads.workflowLifecycle(workflow, opts);
4356
+ }
4357
+ lifecycleSubscribers(workflow, kind, namespace) {
4358
+ return this.reads.lifecycleSubscribers(workflow, kind, namespace);
4359
+ }
4360
+ /** The app's worker groups, read from its broker (read-only). `[]` when the transport can't. */
4361
+ async workerHealth() {
4362
+ const { transport } = this.options;
4363
+ if (!transport.listWorkerGroups || !transport.groupHealth) return [];
4364
+ const groups = await transport.listWorkerGroups();
4365
+ return Promise.all(groups.map((group) => transport.groupHealth?.(group)));
4366
+ }
4367
+ listSchedules(query) {
4368
+ return this.reads.listSchedules(query);
4369
+ }
4370
+ getSchedule(id) {
4371
+ return this.reads.getSchedule(id);
4372
+ }
4373
+ signalWaiter(token) {
4374
+ return this.reads.signalWaiter(token);
4375
+ }
4376
+ cancel(runId, opts) {
4377
+ return this.onRun(runId, (namespace) => this.request(namespace, opts === void 0 ? {
4378
+ kind: "cancel",
4379
+ runId
4380
+ } : {
4381
+ kind: "cancel",
4382
+ runId,
4383
+ opts
4384
+ }));
4385
+ }
4386
+ retry(runId) {
4387
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4388
+ kind: "retry",
4389
+ runId
4390
+ }));
4391
+ }
4392
+ continue(runId) {
4393
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4394
+ kind: "continue",
4395
+ runId
4396
+ }));
4397
+ }
4398
+ retryWithInput(runId, input) {
4399
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4400
+ kind: "retryWithInput",
4401
+ runId,
4402
+ input
4403
+ }));
4404
+ }
4405
+ redispatchPending(runId) {
4406
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4407
+ kind: "redispatch",
4408
+ runId
4409
+ }));
4410
+ }
4411
+ async republishLifecycle(target) {
4412
+ let namespace;
4413
+ if ("runId" in target) {
4414
+ const run = await this.reads.getRun(target.runId);
4415
+ if (!run) throw new Error(`run ${target.runId} not found`);
4416
+ namespace = run.namespace || "default";
4417
+ } else {
4418
+ namespace = target.namespace;
4419
+ if (namespace === void 0) {
4420
+ throw Object.assign(new Error("republish by workflow needs a namespace on a federated app"), {
4421
+ code: "bad-request"
4422
+ });
4423
+ }
4424
+ }
4425
+ return this.request(namespace, {
4426
+ kind: "republishLifecycle",
4427
+ target
4428
+ });
4429
+ }
4430
+ /**
4431
+ * Pause, resume or trigger one of the app's persisted schedules, executed by the app. A schedule
4432
+ * that does not exist rejects with a `ScheduleNotFoundError`, as the engine's own client does.
4433
+ */
4434
+ async scheduleAction(id, action) {
4435
+ const schedule = await this.reads.getSchedule(id);
4436
+ if (!schedule) throw scheduleNotFound(id);
4437
+ try {
4438
+ return await this.request(schedule.namespace, {
4439
+ kind: "schedule",
4440
+ id,
4441
+ action
4442
+ });
4443
+ } catch (err) {
4444
+ if (err instanceof RunGatewayError && err.code === "not-found") throw scheduleNotFound(id);
4445
+ throw err;
4446
+ }
4447
+ }
4448
+ /**
4449
+ * Deliver `payload` to the app's run waiting on `token`, by the app. Null when no run of the app
4450
+ * waits on it yet: unlike the engine's own `signal`, nothing is buffered for a later wait.
4451
+ */
4452
+ async signal(token, payload) {
4453
+ const runId = await this.reads.signalWaiter(token);
4454
+ if (!runId) return null;
4455
+ return this.onRun(runId, (namespace) => this.request(namespace, {
4456
+ kind: "signal",
4457
+ token,
4458
+ payload
4459
+ }));
4460
+ }
4461
+ /**
4462
+ * The app's live events for `runId`, from the control channel its engines broadcast every event on
4463
+ * (see {@link FederatedAppGatewayOptions.controlPlane}). Nothing when there is none.
4464
+ */
4465
+ subscribe(runId, onEvent) {
4466
+ const control = this.controlPlane();
4467
+ if (!control) return () => void 0;
4468
+ if (!this.tailing) {
4469
+ this.tailing = true;
4470
+ control.onControl((msg) => this.deliver(msg));
4471
+ }
4472
+ let listeners = this.tails.get(runId);
4473
+ if (!listeners) {
4474
+ listeners = /* @__PURE__ */ new Set();
4475
+ this.tails.set(runId, listeners);
4476
+ }
4477
+ listeners.add(onEvent);
4478
+ return () => {
4479
+ const current = this.tails.get(runId);
4480
+ current?.delete(onEvent);
4481
+ if (current?.size === 0) this.tails.delete(runId);
4482
+ };
4483
+ }
4484
+ controlPlane() {
4485
+ if (this.options.controlPlane) return this.options.controlPlane;
4486
+ const candidate = this.options.transport;
4487
+ return typeof candidate.onControl === "function" ? this.options.transport : void 0;
4488
+ }
4489
+ deliver(msg) {
4490
+ if (this.tails.size === 0) return;
4491
+ const events = msg.kind === "event" ? [
4492
+ msg.event
4493
+ ] : msg.kind === "events" ? msg.events : [];
4494
+ for (const event of events) {
4495
+ const listeners = this.tails.get(event.runId);
4496
+ if (!listeners) continue;
4497
+ const live = {
4498
+ ...event,
4499
+ at: new Date(event.at)
4500
+ };
4501
+ for (const listener of listeners) listener(live);
4502
+ }
4503
+ }
4504
+ /** `act` with the namespace of `runId`, or null when the app has no such run. */
4505
+ async onRun(runId, act) {
4506
+ const run = await this.reads.getRun(runId);
4507
+ if (!run) return null;
4508
+ return act(run.namespace || "default");
4509
+ }
4510
+ /** Send `body` to the app as a run request from `namespace`, and wait for its reply. */
4511
+ async request(namespace, body) {
4512
+ const { transport, tenantToken } = this.options;
4513
+ if (!transport.dispatchRunRequest || !transport.onRunReply) {
4514
+ throw new Error("a federated app needs a transport that carries run requests (e.g. BullMQTransport)");
4515
+ }
4516
+ this.listen();
4517
+ const tenant = tenantToken ? await tenantToken(namespace) : namespace;
4518
+ return new Promise((resolve, reject) => {
4519
+ const requestId = globalThis.crypto.randomUUID();
4520
+ const timer = setTimeout(() => {
4521
+ this.pending.delete(requestId);
4522
+ reject(new Error(`the app did not answer ${body.kind} within ${this.timeoutMs}ms`));
4523
+ }, this.timeoutMs);
4524
+ this.pending.set(requestId, {
4525
+ resolve: /* @__PURE__ */ __name((data) => resolve(data), "resolve"),
4526
+ reject,
4527
+ timer
4528
+ });
4529
+ transport.dispatchRunRequest?.({
4530
+ requestId,
4531
+ tenant,
4532
+ body
4533
+ })?.catch((error) => {
4534
+ const entry = this.pending.get(requestId);
4535
+ if (!entry) return;
4536
+ clearTimeout(entry.timer);
4537
+ this.pending.delete(requestId);
4538
+ entry.reject(error instanceof Error ? error : new Error(String(error)));
4539
+ });
4540
+ });
4541
+ }
4542
+ listen() {
4543
+ if (this.listening) return;
4544
+ this.listening = true;
4545
+ this.options.transport.onRunReply?.((reply) => this.handleReply(reply));
4546
+ }
4547
+ handleReply(reply) {
4548
+ const entry = this.pending.get(reply.requestId);
4549
+ if (!entry) return;
4550
+ clearTimeout(entry.timer);
4551
+ this.pending.delete(reply.requestId);
4552
+ if (reply.result.ok) entry.resolve(reply.result.data);
4553
+ else entry.reject(new RunGatewayError(reply.result.error.message, reply.result.error.code));
4554
+ }
4555
+ };
4556
+ function scheduleNotFound(id) {
4557
+ return Object.assign(new Error(`schedule "${id}" not found`), {
4558
+ name: "ScheduleNotFoundError"
4559
+ });
4560
+ }
4561
+ __name(scheduleNotFound, "scheduleNotFound");
4562
+ function federatedAppGateway(options) {
4563
+ return new FederatedAppGateway(options);
4564
+ }
4565
+ __name(federatedAppGateway, "federatedAppGateway");
4566
+
4221
4567
  // 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";
4568
+ 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 WorkflowEngine8 } from "@dudousxd/nestjs-durable-core";
4223
4569
  export {
4224
4570
  BAD_RUN_REQUEST,
4225
4571
  CONTEXT_ACCESSOR,
@@ -4235,6 +4581,7 @@ export {
4235
4581
  ENTITY_ON_METADATA,
4236
4582
  Entity,
4237
4583
  EntityService,
4584
+ FederatedAppGateway,
4238
4585
  IN_APP_RUN_REDIS_WORKER,
4239
4586
  IN_APP_WORKER_BINDING,
4240
4587
  IN_APP_WORKER_RUNNERS,
@@ -4267,11 +4614,12 @@ export {
4267
4614
  UNSUPPORTED_RUN_REQUEST,
4268
4615
  WORKFLOW_METADATA,
4269
4616
  Workflow,
4270
- WorkflowEngine7 as WorkflowEngine,
4617
+ WorkflowEngine8 as WorkflowEngine,
4271
4618
  WorkflowService,
4272
4619
  attributesOf,
4273
4620
  entityConfigFor,
4274
4621
  eventBatchOf,
4622
+ federatedAppGateway,
4275
4623
  getDurableStepMeta,
4276
4624
  getEntityMeta,
4277
4625
  getOnEvents,