@dudousxd/nestjs-durable 0.63.0 → 0.65.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
@@ -343,7 +343,7 @@ function attributesOf(workflow, run) {
343
343
  __name(attributesOf, "attributesOf");
344
344
 
345
345
  // src/durable-start-client.ts
346
- import { resolveTenantToken, workflowName } from "@dudousxd/nestjs-durable-core";
346
+ import { acceptingSubscription, resolveConcurrency, resolveTenantToken, toEventSubscription, workflowName } from "@dudousxd/nestjs-durable-core";
347
347
  import { Injectable } from "@nestjs/common";
348
348
 
349
349
  // src/tenancy.ts
@@ -699,95 +699,216 @@ var DurableStartClient = class {
699
699
  options;
700
700
  deps;
701
701
  accessor;
702
+ requests;
702
703
  tenant;
703
704
  tenantToken;
704
- constructor(options, deps, accessor) {
705
+ policies = /* @__PURE__ */ new Map();
706
+ warnedCoalescing = /* @__PURE__ */ new Set();
707
+ constructor(options, deps, accessor, requests) {
705
708
  this.options = options;
706
709
  this.deps = deps;
707
710
  this.accessor = accessor;
711
+ this.requests = requests;
708
712
  this.tenant = options.partition ?? "default";
709
713
  this.tenantToken = resolveTenantTokenSource(options.tenantToken);
710
714
  }
711
- async start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
712
- const name = workflowName(workflow);
713
- const tenant = opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
715
+ /**
716
+ * Apply `policy` to every start of `workflow` from this process (see
717
+ * {@link TenantWorkflowStartPolicy}). Called by `ThinWorkflowRegistrar` at boot.
718
+ */
719
+ declareWorkflow(workflow, policy) {
720
+ this.policies.set(workflow, policy);
721
+ }
722
+ /**
723
+ * The start-run fields a declared policy adds for `input`: it validates the input (throwing), and
724
+ * evaluates the singleton key and the default quota. A per-start `concurrency` wins over the
725
+ * workflow's.
726
+ */
727
+ async applyPolicy(workflow, input, opts) {
728
+ const policy = this.policies.get(workflow);
729
+ if (!policy) return opts?.concurrency !== void 0 ? {
730
+ concurrency: opts.concurrency
731
+ } : {};
732
+ await policy.validateInput?.(input);
733
+ const concurrency = await resolveConcurrency(opts?.concurrency, policy.concurrency, input);
734
+ const singleton = policy.singleton ? {
735
+ key: policy.singleton.key(input),
736
+ ...policy.singleton.limit !== void 0 ? {
737
+ limit: policy.singleton.limit
738
+ } : {},
739
+ ...policy.singleton.maxQueueDepth !== void 0 ? {
740
+ maxQueueDepth: policy.singleton.maxQueueDepth
741
+ } : {}
742
+ } : void 0;
743
+ return {
744
+ ...singleton ? {
745
+ singleton
746
+ } : {},
747
+ ...concurrency ? {
748
+ concurrency
749
+ } : {}
750
+ };
751
+ }
752
+ /** The wire `tenant`: the signed token when configured, else the partition. */
753
+ async wireTenant() {
754
+ return this.tenantToken !== void 0 ? await resolveTenantToken(this.tenantToken) : this.tenant;
755
+ }
756
+ /**
757
+ * The customer tenant a start claims: an explicit `tenantId` (`null` = none), else the request's
758
+ * tenant when tenancy is on.
759
+ */
760
+ claimedTenant(opts) {
761
+ return opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
714
762
  id: opts.tenantId,
715
- kind: opts.tenantKind
763
+ ...opts.tenantKind !== void 0 ? {
764
+ kind: opts.tenantKind
765
+ } : {}
716
766
  } : currentTenant(this.options.tenancy, this.accessor);
767
+ }
768
+ async start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
769
+ const message = await this.startMessage(workflowName(workflow), input, runId, opts);
717
770
  await startRun(this.options.connection, {
718
771
  // The signed token (when configured) rides in the `tenant` field, as on every run request; an
719
772
  // operator with `verifyTenant` derives the run's namespace from it.
720
- tenant: this.tenantToken !== void 0 ? await resolveTenantToken(this.tenantToken) : this.tenant,
721
- workflow: name,
722
- input,
723
- runId,
773
+ tenant: await this.wireTenant(),
774
+ ...message,
724
775
  // Option B: DO NOT pass `namespace` — the start-run queue stays the shared
725
776
  // `durable-start-run` the operator consumes; tenant rides only as message data.
726
777
  ...this.options.prefix !== void 0 ? {
727
778
  prefix: this.options.prefix
728
779
  } : {},
780
+ ...this.deps !== void 0 ? {
781
+ deps: this.deps
782
+ } : {}
783
+ });
784
+ const startAtMs = message.startAt;
785
+ return {
786
+ runId,
787
+ status: startAtMs !== void 0 && Number.isFinite(startAtMs) && startAtMs > Date.now() ? "suspended" : "pending"
788
+ };
789
+ }
790
+ /**
791
+ * The start-run a start of `name` sends (everything but the wire `tenant`): the start options the
792
+ * control plane applies (version pin, priority, delayed start, quota), the singleton key and the
793
+ * customer tenant this run claims. Applies the workflow's declared policy first, so a rejected
794
+ * input throws before anything is published, as `engine.start` does.
795
+ */
796
+ async startMessage(name, input, runId, opts) {
797
+ const tenant = this.claimedTenant(opts);
798
+ const policy = await this.applyPolicy(name, input, opts);
799
+ const startAt = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;
800
+ return {
801
+ workflow: name,
802
+ input,
803
+ runId,
729
804
  ...opts?.tags !== void 0 ? {
730
805
  tags: opts.tags
731
806
  } : {},
732
807
  ...opts?.searchAttributes !== void 0 ? {
733
808
  searchAttributes: opts.searchAttributes
734
809
  } : {},
735
- // The start options the control plane applies (version pin, priority, delayed start, quota).
736
810
  ...opts?.version !== void 0 ? {
737
811
  version: opts.version
738
812
  } : {},
739
813
  ...opts?.priority !== void 0 ? {
740
814
  priority: opts.priority
741
815
  } : {},
742
- ...opts?.startAt !== void 0 ? {
743
- startAt: opts.startAt
816
+ ...startAt !== void 0 ? {
817
+ startAt
818
+ } : {},
819
+ ...policy.concurrency !== void 0 ? {
820
+ concurrency: policy.concurrency
744
821
  } : {},
745
- ...opts?.concurrency !== void 0 ? {
746
- concurrency: opts.concurrency
822
+ ...policy.singleton !== void 0 ? {
823
+ singleton: policy.singleton
747
824
  } : {},
748
825
  ...tenant ? {
749
826
  tenantId: tenant.id,
750
827
  ...tenant.kind !== void 0 ? {
751
828
  tenantKind: tenant.kind
752
829
  } : {}
753
- } : {},
754
- ...this.deps !== void 0 ? {
755
- deps: this.deps
756
830
  } : {}
757
- });
758
- const startAtMs = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;
831
+ };
832
+ }
833
+ /** The control plane's run requests, or a clear error naming what is missing. */
834
+ runRequests(method) {
835
+ const requests = this.requests?.();
836
+ if (!requests) {
837
+ throw new Error(`${method}() on a tenant is sent to the control plane as a run request, which needs \`transport\` on DurableModule.forRoot (the tenant's BullMQTransport).`);
838
+ }
839
+ return requests;
840
+ }
841
+ /**
842
+ * Signal the run of this tenant's partition waiting on `token`, through the control plane.
843
+ * Resolves the resumed run, or null when no run of this partition waits on it: unlike
844
+ * `engine.signal` on a control plane, a tenant's signal is NOT buffered for a wait opened later
845
+ * (another partition's run could open it). Use `signalWithStart` to signal a run that may not wait
846
+ * yet. `opts.id` deduplicates like `engine.signal`.
847
+ */
848
+ async signal(token, payload, opts) {
849
+ return this.runRequests("signal").signal(token, payload, opts);
850
+ }
851
+ async signalWithStart(workflow, input, runId, signal, opts) {
852
+ const requests = this.runRequests("signalWithStart");
853
+ const start = await this.startMessage(workflowName(workflow), input, runId, opts);
854
+ const result = await requests.signalWithStart(start, signal);
759
855
  return {
760
- runId,
761
- status: startAtMs !== void 0 && Number.isFinite(startAtMs) && startAtMs > Date.now() ? "suspended" : "pending"
856
+ runId: result.runId
762
857
  };
763
858
  }
859
+ /**
860
+ * Publish event `name` from this tenant. Starts this app's own `onEvent` subscribers (each one
861
+ * whose `where` accepts the payload, with its `input` mapping) as runs of this partition, by the
862
+ * start path ({@link start}, run id `evt:<id>:<workflow>`), and has the control plane resume the
863
+ * runs of this partition waiting on it (`ctx.waitForEvent`). Resolves how many runs it started or
864
+ * resumed; a subscriber that throws is warned about and skipped. Unlike a control plane's
865
+ * `publishEvent`, an event nobody received is not buffered (there is no `buffer` option), and
866
+ * a subscriber's `debounce`/`batch` is not applied (it starts once per event, with a warning).
867
+ */
868
+ async publishEvent(name, payload, opts) {
869
+ const requests = this.runRequests("publishEvent");
870
+ const eventId = opts?.id ?? globalThis.crypto.randomUUID();
871
+ let started = 0;
872
+ for (const [workflow, policy] of this.policies) {
873
+ try {
874
+ const subscriptions = (policy.onEvent ?? []).map(toEventSubscription).filter((sub) => sub.event === name);
875
+ const { accepted, errors } = acceptingSubscription(subscriptions, payload);
876
+ if (!accepted) {
877
+ if (errors.length > 0) throw errors[0];
878
+ continue;
879
+ }
880
+ if (policy.coalesces && !this.warnedCoalescing.has(workflow)) {
881
+ this.warnedCoalescing.add(workflow);
882
+ console.warn(`[nestjs-durable] ${workflow} debounces/batches its events, which a tenant's publishEvent does not apply: it starts once per event.`);
883
+ }
884
+ const input = accepted.input ? accepted.input(payload) : payload;
885
+ await this.start(workflow, input, `evt:${eventId}:${workflow}`);
886
+ started += 1;
887
+ } catch (error) {
888
+ console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error);
889
+ }
890
+ }
891
+ const resumed = await requests.publishEvent(name, payload, {
892
+ id: eventId
893
+ });
894
+ return started + resumed;
895
+ }
764
896
  cancel(_runId) {
765
897
  return tenantUnsupported("cancel");
766
898
  }
767
899
  deleteRun(_runId) {
768
900
  return tenantUnsupported("deleteRun");
769
901
  }
770
- // — everything below rejects: a tenant worker holds no store/driver, only the start channel. —
771
- // The remaining WorkflowEngine surface WorkflowService delegates to (resume/waitForRun/signal/
772
- // signalWithStart/publishEvent) all need the store or driver a tenant does not have. A tenant only
773
- // ever calls `start`; these exist so a mistaken call fails with a CLEAR, named tenant error instead
774
- // of a cryptic `this.engine.X is not a function` — the facade is honest about what it cannot do.
775
- // Params mirror the WorkflowEngine surface being faced; every method rejects without reading them.
902
+ // — everything below rejects: a tenant worker holds no store/driver. —
903
+ // `resume`/`waitForRun` need the store or driver a tenant does not have. They exist so a mistaken
904
+ // call fails with a CLEAR, named tenant error instead of a cryptic `this.engine.X is not a
905
+ // function`. Params mirror the WorkflowEngine surface; every method rejects without reading them.
776
906
  resume(_runId) {
777
907
  return tenantUnsupported("resume");
778
908
  }
779
909
  waitForRun(_runId, _opts) {
780
910
  return tenantUnsupported("waitForRun");
781
911
  }
782
- signal(_token, _payload) {
783
- return tenantUnsupported("signal");
784
- }
785
- signalWithStart(_workflow, _input, _runId, _signal, _opts) {
786
- return tenantUnsupported("signalWithStart");
787
- }
788
- publishEvent(_name, _payload, _opts) {
789
- return tenantUnsupported("publishEvent");
790
- }
791
912
  };
792
913
  DurableStartClient = _ts_decorate([
793
914
  Injectable(),
@@ -795,7 +916,8 @@ DurableStartClient = _ts_decorate([
795
916
  _ts_metadata("design:paramtypes", [
796
917
  typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
797
918
  typeof StartRunDeps === "undefined" ? Object : StartRunDeps,
798
- typeof ContextAccessor === "undefined" ? Object : ContextAccessor
919
+ typeof ContextAccessor === "undefined" ? Object : ContextAccessor,
920
+ Function
799
921
  ])
800
922
  ], DurableStartClient);
801
923
  function tenantUnsupported(method) {
@@ -804,8 +926,8 @@ function tenantUnsupported(method) {
804
926
  __name(tenantUnsupported, "tenantUnsupported");
805
927
 
806
928
  // src/durable-worker.module.ts
807
- import { DURABLE_OPTIONS_CANONICAL, WorkflowEngine, bindWorkflowClass } from "@dudousxd/nestjs-durable-core";
808
- import { Inject, Injectable as Injectable2 } from "@nestjs/common";
929
+ import { DURABLE_OPTIONS_CANONICAL, WorkflowEngine as WorkflowEngine2, bindWorkflowClass, resolveTenantToken as resolveTenantToken2, workflowName as workflowName3 } from "@dudousxd/nestjs-durable-core";
930
+ import { Inject, Injectable as Injectable3 } from "@nestjs/common";
809
931
  import { DiscoveryService, MetadataScanner } from "@nestjs/core";
810
932
 
811
933
  // src/schema-parse.ts
@@ -916,6 +1038,97 @@ function scanSteps(discovery, scanner, register) {
916
1038
  }
917
1039
  __name(scanSteps, "scanSteps");
918
1040
 
1041
+ // src/entity.ts
1042
+ import { WorkflowEngine } from "@dudousxd/nestjs-durable-core";
1043
+ import { Injectable as Injectable2 } from "@nestjs/common";
1044
+ import "reflect-metadata";
1045
+ function _ts_decorate2(decorators, target, key, desc) {
1046
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1047
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1048
+ r = Reflect.decorate(decorators, target, key, desc);
1049
+ } else {
1050
+ for (var i = decorators.length - 1; i >= 0; i--) {
1051
+ if (d = decorators[i]) {
1052
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1053
+ }
1054
+ }
1055
+ }
1056
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1057
+ }
1058
+ __name(_ts_decorate2, "_ts_decorate");
1059
+ function _ts_metadata2(metadataKey, metadataValue) {
1060
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1061
+ return Reflect.metadata(metadataKey, metadataValue);
1062
+ }
1063
+ }
1064
+ __name(_ts_metadata2, "_ts_metadata");
1065
+ var ENTITY_METADATA = Symbol("nestjs-durable:entity");
1066
+ var ENTITY_ON_METADATA = Symbol("nestjs-durable:entity-on");
1067
+ function Entity(options) {
1068
+ return (target) => {
1069
+ Reflect.defineMetadata(ENTITY_METADATA, options, target);
1070
+ };
1071
+ }
1072
+ __name(Entity, "Entity");
1073
+ function On(op) {
1074
+ return (target, propertyKey) => {
1075
+ const ctor = target.constructor;
1076
+ const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1077
+ ops.set(op, propertyKey);
1078
+ Reflect.defineMetadata(ENTITY_ON_METADATA, ops, ctor);
1079
+ };
1080
+ }
1081
+ __name(On, "On");
1082
+ function getEntityMeta(target) {
1083
+ return Reflect.getMetadata(ENTITY_METADATA, target);
1084
+ }
1085
+ __name(getEntityMeta, "getEntityMeta");
1086
+ function entityConfigFor(ctor) {
1087
+ const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1088
+ const Cls = ctor;
1089
+ const handlers = {};
1090
+ for (const [op, method] of ops) {
1091
+ handlers[op] = (state, arg) => {
1092
+ Object.setPrototypeOf(state, Cls.prototype);
1093
+ const fn = state[method];
1094
+ if (typeof fn !== "function") throw new Error(`entity handler "${method}" is not a method`);
1095
+ return fn.call(state, arg);
1096
+ };
1097
+ }
1098
+ return {
1099
+ initialState: /* @__PURE__ */ __name(() => new Cls(), "initialState"),
1100
+ handlers
1101
+ };
1102
+ }
1103
+ __name(entityConfigFor, "entityConfigFor");
1104
+ var EntityService = class {
1105
+ static {
1106
+ __name(this, "EntityService");
1107
+ }
1108
+ engine;
1109
+ constructor(engine) {
1110
+ this.engine = engine;
1111
+ }
1112
+ /** Send an operation to an entity (fire-and-forget; ordered + exactly-once per key). */
1113
+ signal(name, key, op, arg) {
1114
+ return this.engine.signalEntity(name, key, op, arg);
1115
+ }
1116
+ /** Read an entity's current durable state (or undefined if it has none yet). */
1117
+ getState(name, key) {
1118
+ return this.engine.getEntityState(name, key);
1119
+ }
1120
+ };
1121
+ EntityService = _ts_decorate2([
1122
+ Injectable2(),
1123
+ _ts_metadata2("design:type", Function),
1124
+ _ts_metadata2("design:paramtypes", [
1125
+ typeof WorkflowEngine === "undefined" ? Object : WorkflowEngine
1126
+ ])
1127
+ ], EntityService);
1128
+
1129
+ // src/runtime-registration.ts
1130
+ import { parseDuration as parseDuration2 } from "@dudousxd/nestjs-durable-core";
1131
+
919
1132
  // src/on-error-handlers.ts
920
1133
  import { workflowName as workflowName2 } from "@dudousxd/nestjs-durable-core";
921
1134
  function onErrorHandlersOf(meta, instance, scanner) {
@@ -967,7 +1180,7 @@ function workflowIo(meta) {
967
1180
  __name(workflowIo, "workflowIo");
968
1181
 
969
1182
  // src/runtime-registration.ts
970
- function registerOnRuntime(runtime, scanner, meta, instance, origin) {
1183
+ function registerOnRuntime(runtime, scanner, meta, instance, origin, deadLetter) {
971
1184
  const { handlers, routes } = onErrorHandlersOf(meta, instance, scanner);
972
1185
  const announced = {
973
1186
  version: meta.version,
@@ -995,14 +1208,61 @@ function registerOnRuntime(runtime, scanner, meta, instance, origin) {
995
1208
  } : {},
996
1209
  ...subscribes.length > 0 ? {
997
1210
  subscribes
1211
+ } : {},
1212
+ ...announcedOptions(meta),
1213
+ ...deadLetter !== void 0 ? {
1214
+ deadLetter
998
1215
  } : {}
999
1216
  });
1000
1217
  for (const [name, fn] of handlers) runtime.registerWorkflow(name, fn, announced);
1001
1218
  }
1002
1219
  __name(registerOnRuntime, "registerOnRuntime");
1220
+ function announcedOptions(meta) {
1221
+ const options = {};
1222
+ if (meta.tags !== void 0 && meta.tags.length > 0) options.tags = [
1223
+ ...meta.tags
1224
+ ];
1225
+ if (meta.executionTimeout !== void 0) {
1226
+ options.executionTimeoutMs = parseDuration2(meta.executionTimeout);
1227
+ }
1228
+ if (meta.singleton !== void 0) {
1229
+ options.singleton = {
1230
+ ...meta.singleton.limit !== void 0 ? {
1231
+ limit: meta.singleton.limit
1232
+ } : {},
1233
+ ...meta.singleton.maxQueueDepth !== void 0 ? {
1234
+ maxQueueDepth: meta.singleton.maxQueueDepth
1235
+ } : {}
1236
+ };
1237
+ }
1238
+ return Object.keys(options).length > 0 ? {
1239
+ options
1240
+ } : {};
1241
+ }
1242
+ __name(announcedOptions, "announcedOptions");
1243
+
1244
+ // src/step-interceptor.ts
1245
+ import "reflect-metadata";
1246
+ var STEP_INTERCEPTOR_METADATA = Symbol("nestjs-durable:step-interceptor");
1247
+ function StepInterceptor() {
1248
+ return (target) => {
1249
+ Reflect.defineMetadata(STEP_INTERCEPTOR_METADATA, true, target);
1250
+ };
1251
+ }
1252
+ __name(StepInterceptor, "StepInterceptor");
1253
+ function isStepInterceptor(target) {
1254
+ return Reflect.getMetadata(STEP_INTERCEPTOR_METADATA, target) === true;
1255
+ }
1256
+ __name(isStepInterceptor, "isStepInterceptor");
1257
+
1258
+ // src/tokens.ts
1259
+ import { RunGateway } from "@dudousxd/nestjs-durable-core";
1260
+ var CONTEXT_ACCESSOR = Symbol.for("@dudousxd/nestjs-context:accessor");
1261
+ var TENANT_AUTH = Symbol("nestjs-durable:tenant-auth");
1262
+ var RUN_GATEWAY = RunGateway;
1003
1263
 
1004
1264
  // src/durable-worker.module.ts
1005
- function _ts_decorate2(decorators, target, key, desc) {
1265
+ function _ts_decorate3(decorators, target, key, desc) {
1006
1266
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1007
1267
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1008
1268
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1015,19 +1275,29 @@ function _ts_decorate2(decorators, target, key, desc) {
1015
1275
  }
1016
1276
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1017
1277
  }
1018
- __name(_ts_decorate2, "_ts_decorate");
1019
- function _ts_metadata2(metadataKey, metadataValue) {
1278
+ __name(_ts_decorate3, "_ts_decorate");
1279
+ function _ts_metadata3(metadataKey, metadataValue) {
1020
1280
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1021
1281
  return Reflect.metadata(metadataKey, metadataValue);
1022
1282
  }
1023
1283
  }
1024
- __name(_ts_metadata2, "_ts_metadata");
1284
+ __name(_ts_metadata3, "_ts_metadata");
1025
1285
  function _ts_param(paramIndex, decorator) {
1026
1286
  return function(target, key) {
1027
1287
  decorator(target, key, paramIndex);
1028
1288
  };
1029
1289
  }
1030
1290
  __name(_ts_param, "_ts_param");
1291
+ function deadLetterHandlerOf(instance, scanner) {
1292
+ for (const name of scanner.getAllMethodNames(Object.getPrototypeOf(instance))) {
1293
+ const method = instance[name];
1294
+ if (typeof method === "function" && isDeadLetterHandler(method)) {
1295
+ return (ctx, input) => method.call(instance, ctx, input);
1296
+ }
1297
+ }
1298
+ return void 0;
1299
+ }
1300
+ __name(deadLetterHandlerOf, "deadLetterHandlerOf");
1031
1301
  var RUN_REDIS_WORKER = Symbol("nestjs-durable:run-redis-worker");
1032
1302
  var DURABLE_WORKER_RUNTIME = Symbol("nestjs-durable:worker-runtime");
1033
1303
  var DURABLE_WORKER_RUNNERS = Symbol("nestjs-durable:worker-runners");
@@ -1055,21 +1325,78 @@ var ThinWorkflowRegistrar = class {
1055
1325
  const runtime = this.runtime;
1056
1326
  if (runtime === null || !isPureThinWorker(this.options)) return;
1057
1327
  const starter = this.starter;
1328
+ this.assertNoEntities();
1329
+ this.useInterceptors(runtime);
1330
+ const fallback = this.options.deadLetterWorkflow ? workflowName3(this.options.deadLetterWorkflow) : void 0;
1058
1331
  scanWorkflows(this.discovery, (meta, instance, origin) => {
1059
- registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin);
1332
+ const inline = deadLetterHandlerOf(instance, this.metadataScanner);
1333
+ if (inline && meta.deadLetterWorkflow) {
1334
+ throw new Error(`@Workflow ${meta.name} declares both an inline @DeadLetter() method and a deadLetterWorkflow option. Use one: the inline handler, or the reference.`);
1335
+ }
1336
+ const deadLetter = inline ? `${meta.name}.dlq` : meta.deadLetterWorkflow ? workflowName3(meta.deadLetterWorkflow) : fallback;
1337
+ registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin, deadLetter);
1338
+ if (inline) {
1339
+ runtime.registerWorkflow(`${meta.name}.dlq`, inline, {
1340
+ version: meta.version,
1341
+ ...origin !== void 0 ? {
1342
+ origin
1343
+ } : {}
1344
+ });
1345
+ }
1346
+ const declare = starter.declareWorkflow;
1347
+ if (typeof declare === "function") {
1348
+ const policy = {
1349
+ validateInput: workflowIo(meta).validateAtStart,
1350
+ singleton: meta.singleton,
1351
+ concurrency: meta.concurrency,
1352
+ onEvent: getOnEvents(meta, instance.constructor),
1353
+ coalesces: eventBatchOf(meta, instance.constructor) !== void 0
1354
+ };
1355
+ declare.call(starter, meta.name, policy);
1356
+ }
1060
1357
  bindWorkflowClass(instance.constructor, {
1061
1358
  start: /* @__PURE__ */ __name((name, input, runId, opts) => starter.start(name, input, runId, opts), "start")
1062
1359
  });
1063
1360
  });
1064
1361
  }
1362
+ /**
1363
+ * `@Entity` providers are refused on a tenant, at boot: an entity's state is a run on the store
1364
+ * and its `@On` handlers run inside the engine that owns that store (`EntityService` and
1365
+ * `ctx.callEntity`/`signalEntity` read and serialize it there). A tenant has no store and no
1366
+ * engine, so an entity declared here would never run. Declare it on the control plane.
1367
+ */
1368
+ assertNoEntities() {
1369
+ const entities = this.discovery.getProviders().map((w) => w.instance).filter((i) => !!i && typeof i === "object" && !!getEntityMeta(i.constructor)).map((i) => getEntityMeta(i.constructor)?.name);
1370
+ if (entities.length === 0) return;
1371
+ throw new Error(`@Entity ${entities.join(", ")} cannot be declared on a DurableModule tenant (connection, no store): an entity's state and handlers live in the engine that owns the store. Declare it on the control plane.`);
1372
+ }
1373
+ /**
1374
+ * `@StepInterceptor()` providers wrap every step this tenant runs (each `ctx.step` its workers
1375
+ * execute), as `engine.use` does on an engine. A `@durable-worker` too old to take interceptors
1376
+ * says so instead of dropping them silently.
1377
+ */
1378
+ useInterceptors(runtime) {
1379
+ for (const wrapper of this.discovery.getProviders()) {
1380
+ const instance = wrapper.instance;
1381
+ if (!instance || typeof instance !== "object" || !isStepInterceptor(instance.constructor)) {
1382
+ continue;
1383
+ }
1384
+ const interceptor = instance;
1385
+ if (typeof runtime.use !== "function") {
1386
+ console.warn(`[nestjs-durable] @StepInterceptor ${instance.constructor.name} is not applied: this @dudousxd/durable-worker predates step interceptors on a tenant; upgrade it.`);
1387
+ continue;
1388
+ }
1389
+ runtime.use((invocation, next) => interceptor.intercept(invocation, next));
1390
+ }
1391
+ }
1065
1392
  };
1066
- ThinWorkflowRegistrar = _ts_decorate2([
1067
- Injectable2(),
1393
+ ThinWorkflowRegistrar = _ts_decorate3([
1394
+ Injectable3(),
1068
1395
  _ts_param(2, Inject(DURABLE_WORKER_RUNTIME)),
1069
1396
  _ts_param(3, Inject(DURABLE_OPTIONS_CANONICAL)),
1070
- _ts_param(4, Inject(WorkflowEngine)),
1071
- _ts_metadata2("design:type", Function),
1072
- _ts_metadata2("design:paramtypes", [
1397
+ _ts_param(4, Inject(WorkflowEngine2)),
1398
+ _ts_metadata3("design:type", Function),
1399
+ _ts_metadata3("design:paramtypes", [
1073
1400
  typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
1074
1401
  typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
1075
1402
  Object,
@@ -1097,12 +1424,12 @@ var ThinStepRegistrar = class {
1097
1424
  scanSteps(this.discovery, this.metadataScanner, (meta, handler) => runtime.registerStep(meta.name, handler));
1098
1425
  }
1099
1426
  };
1100
- ThinStepRegistrar = _ts_decorate2([
1101
- Injectable2(),
1427
+ ThinStepRegistrar = _ts_decorate3([
1428
+ Injectable3(),
1102
1429
  _ts_param(2, Inject(DURABLE_WORKER_RUNTIME)),
1103
1430
  _ts_param(3, Inject(DURABLE_OPTIONS_CANONICAL)),
1104
- _ts_metadata2("design:type", Function),
1105
- _ts_metadata2("design:paramtypes", [
1431
+ _ts_metadata3("design:type", Function),
1432
+ _ts_metadata3("design:paramtypes", [
1106
1433
  typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
1107
1434
  typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
1108
1435
  Object,
@@ -1117,18 +1444,25 @@ var ThinWorkerBootstrap = class {
1117
1444
  options;
1118
1445
  runRedisWorker;
1119
1446
  runnersSink;
1447
+ auth;
1120
1448
  runners = [];
1121
- constructor(runtime, options, runRedisWorker2, runnersSink) {
1449
+ constructor(runtime, options, runRedisWorker2, runnersSink, auth) {
1122
1450
  this.runtime = runtime;
1123
1451
  this.options = options;
1124
1452
  this.runRedisWorker = runRedisWorker2;
1125
1453
  this.runnersSink = runnersSink;
1454
+ this.auth = auth;
1126
1455
  }
1127
1456
  async onApplicationBootstrap() {
1128
1457
  const options = this.options;
1129
1458
  const runtime = this.runtime;
1130
1459
  if (runtime === null || !isPureThinWorker(options) || options.connection === void 0) return;
1131
- if (options.consumers === false) return;
1460
+ if (options.consumers === false) {
1461
+ if ((options.schedules?.length ?? 0) > 0) {
1462
+ console.warn("[nestjs-durable] `schedules` on a tenant with `consumers: false` are not announced: a tenant announces its schedules on its worker descriptor, so declare them on the processes that run its workers.");
1463
+ }
1464
+ return;
1465
+ }
1132
1466
  const handle = await this.runRedisWorker({
1133
1467
  runtime,
1134
1468
  connection: options.connection,
@@ -1143,7 +1477,10 @@ var ThinWorkerBootstrap = class {
1143
1477
  } : {},
1144
1478
  ...options.concurrency !== void 0 ? {
1145
1479
  concurrency: options.concurrency
1146
- } : {}
1480
+ } : {},
1481
+ // Announce the app's schedules (an empty list too) so the control plane adopts, updates and
1482
+ // withdraws them: a tenant has no store to fire them from.
1483
+ ...await tenantScheduleAnnouncement(options, this.auth.tenantToken)
1147
1484
  });
1148
1485
  this.runners.push(handle);
1149
1486
  this.runnersSink.push(handle);
@@ -1152,20 +1489,65 @@ var ThinWorkerBootstrap = class {
1152
1489
  await Promise.allSettled(this.runners.map((h) => h.close()));
1153
1490
  }
1154
1491
  };
1155
- ThinWorkerBootstrap = _ts_decorate2([
1156
- Injectable2(),
1492
+ ThinWorkerBootstrap = _ts_decorate3([
1493
+ Injectable3(),
1157
1494
  _ts_param(0, Inject(DURABLE_WORKER_RUNTIME)),
1158
1495
  _ts_param(1, Inject(DURABLE_OPTIONS_CANONICAL)),
1159
1496
  _ts_param(2, Inject(RUN_REDIS_WORKER)),
1160
1497
  _ts_param(3, Inject(DURABLE_WORKER_RUNNERS)),
1161
- _ts_metadata2("design:type", Function),
1162
- _ts_metadata2("design:paramtypes", [
1498
+ _ts_param(4, Inject(TENANT_AUTH)),
1499
+ _ts_metadata3("design:type", Function),
1500
+ _ts_metadata3("design:paramtypes", [
1163
1501
  Object,
1164
1502
  typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
1165
1503
  typeof RunRedisWorkerFn === "undefined" ? Object : RunRedisWorkerFn,
1166
- Array
1504
+ Array,
1505
+ typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
1167
1506
  ])
1168
1507
  ], ThinWorkerBootstrap);
1508
+ async function tenantScheduleAnnouncement(options, tenantToken) {
1509
+ let tenant;
1510
+ try {
1511
+ tenant = tenantToken !== void 0 ? await resolveTenantToken2(tenantToken) : options.partition ?? "default";
1512
+ } catch (error) {
1513
+ console.warn(`[nestjs-durable] this worker announces no schedules: its tenantToken failed (${error instanceof Error ? error.message : String(error)})`);
1514
+ return {};
1515
+ }
1516
+ return {
1517
+ schedules: {
1518
+ tenant,
1519
+ items: (options.schedules ?? []).map(announcedSchedule)
1520
+ }
1521
+ };
1522
+ }
1523
+ __name(tenantScheduleAnnouncement, "tenantScheduleAnnouncement");
1524
+ function announcedSchedule(s) {
1525
+ const item = {
1526
+ key: s.key,
1527
+ workflow: workflowName3(s.workflow)
1528
+ };
1529
+ if (s.input !== void 0) item.input = s.input;
1530
+ if (s.everyMs !== void 0) item.everyMs = s.everyMs;
1531
+ if (s.cron !== void 0) item.cron = s.cron;
1532
+ if (s.timezone !== void 0) item.timezone = s.timezone;
1533
+ if (s.paused === true) item.paused = true;
1534
+ if (s.overlap !== void 0) item.overlap = s.overlap;
1535
+ if (s.jitter !== void 0 && s.jitter > 0) item.jitterMs = s.jitter;
1536
+ const singleton = typeof s.workflow === "function" ? getWorkflowMeta(s.workflow)?.singleton : void 0;
1537
+ if (singleton) {
1538
+ item.singleton = {
1539
+ key: singleton.key(s.input),
1540
+ ...singleton.limit !== void 0 ? {
1541
+ limit: singleton.limit
1542
+ } : {},
1543
+ ...singleton.maxQueueDepth !== void 0 ? {
1544
+ maxQueueDepth: singleton.maxQueueDepth
1545
+ } : {}
1546
+ };
1547
+ }
1548
+ return item;
1549
+ }
1550
+ __name(announcedSchedule, "announcedSchedule");
1169
1551
  function thinWorkerProviders() {
1170
1552
  return [
1171
1553
  {
@@ -1261,7 +1643,7 @@ import { DiscoveryModule, ModuleRef as ModuleRef2 } from "@nestjs/core";
1261
1643
 
1262
1644
  // src/durable-step.registrar.ts
1263
1645
  import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL2, TRANSPORT_CANONICAL } from "@dudousxd/nestjs-durable-core";
1264
- import { Inject as Inject2, Injectable as Injectable3 } from "@nestjs/common";
1646
+ import { Inject as Inject2, Injectable as Injectable4 } from "@nestjs/common";
1265
1647
  import { DiscoveryService as DiscoveryService2, MetadataScanner as MetadataScanner2 } from "@nestjs/core";
1266
1648
 
1267
1649
  // src/role.ts
@@ -1275,7 +1657,7 @@ function isDrivingOperator(options) {
1275
1657
  __name(isDrivingOperator, "isDrivingOperator");
1276
1658
 
1277
1659
  // src/durable-step.registrar.ts
1278
- function _ts_decorate3(decorators, target, key, desc) {
1660
+ function _ts_decorate4(decorators, target, key, desc) {
1279
1661
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1280
1662
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1281
1663
  r = Reflect.decorate(decorators, target, key, desc);
@@ -1288,13 +1670,13 @@ function _ts_decorate3(decorators, target, key, desc) {
1288
1670
  }
1289
1671
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1290
1672
  }
1291
- __name(_ts_decorate3, "_ts_decorate");
1292
- function _ts_metadata3(metadataKey, metadataValue) {
1673
+ __name(_ts_decorate4, "_ts_decorate");
1674
+ function _ts_metadata4(metadataKey, metadataValue) {
1293
1675
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1294
1676
  return Reflect.metadata(metadataKey, metadataValue);
1295
1677
  }
1296
1678
  }
1297
- __name(_ts_metadata3, "_ts_metadata");
1679
+ __name(_ts_metadata4, "_ts_metadata");
1298
1680
  function _ts_param2(paramIndex, decorator) {
1299
1681
  return function(target, key) {
1300
1682
  decorator(target, key, paramIndex);
@@ -1326,12 +1708,12 @@ var DurableStepRegistrar = class {
1326
1708
  scanSteps(this.discovery, this.metadataScanner, (meta, handler) => transport.handle(meta.name, handler, this.options.partition));
1327
1709
  }
1328
1710
  };
1329
- DurableStepRegistrar = _ts_decorate3([
1330
- Injectable3(),
1711
+ DurableStepRegistrar = _ts_decorate4([
1712
+ Injectable4(),
1331
1713
  _ts_param2(2, Inject2(TRANSPORT_CANONICAL)),
1332
1714
  _ts_param2(3, Inject2(DURABLE_OPTIONS_CANONICAL2)),
1333
- _ts_metadata3("design:type", Function),
1334
- _ts_metadata3("design:paramtypes", [
1715
+ _ts_metadata4("design:type", Function),
1716
+ _ts_metadata4("design:paramtypes", [
1335
1717
  typeof DiscoveryService2 === "undefined" ? Object : DiscoveryService2,
1336
1718
  typeof MetadataScanner2 === "undefined" ? Object : MetadataScanner2,
1337
1719
  Object,
@@ -1339,94 +1721,6 @@ DurableStepRegistrar = _ts_decorate3([
1339
1721
  ])
1340
1722
  ], DurableStepRegistrar);
1341
1723
 
1342
- // src/entity.ts
1343
- import { WorkflowEngine as WorkflowEngine2 } from "@dudousxd/nestjs-durable-core";
1344
- import { Injectable as Injectable4 } from "@nestjs/common";
1345
- import "reflect-metadata";
1346
- function _ts_decorate4(decorators, target, key, desc) {
1347
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1348
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1349
- r = Reflect.decorate(decorators, target, key, desc);
1350
- } else {
1351
- for (var i = decorators.length - 1; i >= 0; i--) {
1352
- if (d = decorators[i]) {
1353
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1354
- }
1355
- }
1356
- }
1357
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1358
- }
1359
- __name(_ts_decorate4, "_ts_decorate");
1360
- function _ts_metadata4(metadataKey, metadataValue) {
1361
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1362
- return Reflect.metadata(metadataKey, metadataValue);
1363
- }
1364
- }
1365
- __name(_ts_metadata4, "_ts_metadata");
1366
- var ENTITY_METADATA = Symbol("nestjs-durable:entity");
1367
- var ENTITY_ON_METADATA = Symbol("nestjs-durable:entity-on");
1368
- function Entity(options) {
1369
- return (target) => {
1370
- Reflect.defineMetadata(ENTITY_METADATA, options, target);
1371
- };
1372
- }
1373
- __name(Entity, "Entity");
1374
- function On(op) {
1375
- return (target, propertyKey) => {
1376
- const ctor = target.constructor;
1377
- const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1378
- ops.set(op, propertyKey);
1379
- Reflect.defineMetadata(ENTITY_ON_METADATA, ops, ctor);
1380
- };
1381
- }
1382
- __name(On, "On");
1383
- function getEntityMeta(target) {
1384
- return Reflect.getMetadata(ENTITY_METADATA, target);
1385
- }
1386
- __name(getEntityMeta, "getEntityMeta");
1387
- function entityConfigFor(ctor) {
1388
- const ops = Reflect.getMetadata(ENTITY_ON_METADATA, ctor) ?? /* @__PURE__ */ new Map();
1389
- const Cls = ctor;
1390
- const handlers = {};
1391
- for (const [op, method] of ops) {
1392
- handlers[op] = (state, arg) => {
1393
- Object.setPrototypeOf(state, Cls.prototype);
1394
- const fn = state[method];
1395
- if (typeof fn !== "function") throw new Error(`entity handler "${method}" is not a method`);
1396
- return fn.call(state, arg);
1397
- };
1398
- }
1399
- return {
1400
- initialState: /* @__PURE__ */ __name(() => new Cls(), "initialState"),
1401
- handlers
1402
- };
1403
- }
1404
- __name(entityConfigFor, "entityConfigFor");
1405
- var EntityService = class {
1406
- static {
1407
- __name(this, "EntityService");
1408
- }
1409
- engine;
1410
- constructor(engine) {
1411
- this.engine = engine;
1412
- }
1413
- /** Send an operation to an entity (fire-and-forget; ordered + exactly-once per key). */
1414
- signal(name, key, op, arg) {
1415
- return this.engine.signalEntity(name, key, op, arg);
1416
- }
1417
- /** Read an entity's current durable state (or undefined if it has none yet). */
1418
- getState(name, key) {
1419
- return this.engine.getEntityState(name, key);
1420
- }
1421
- };
1422
- EntityService = _ts_decorate4([
1423
- Injectable4(),
1424
- _ts_metadata4("design:type", Function),
1425
- _ts_metadata4("design:paramtypes", [
1426
- typeof WorkflowEngine2 === "undefined" ? Object : WorkflowEngine2
1427
- ])
1428
- ], EntityService);
1429
-
1430
1724
  // src/in-app-worker.ts
1431
1725
  import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL3, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL2 } from "@dudousxd/nestjs-durable-core";
1432
1726
  import { Inject as Inject3, Injectable as Injectable5 } from "@nestjs/common";
@@ -1591,11 +1885,11 @@ function inAppWorkerProviders() {
1591
1885
  __name(inAppWorkerProviders, "inAppWorkerProviders");
1592
1886
 
1593
1887
  // src/proxy-run-gateway.ts
1594
- import { SUMMARY_CHILD_LIMIT, childIdsOf, pageFan, resolveTenantToken as resolveTenantToken2, scopeTenantQuery, summarizeTimeline, tenantVisible } from "@dudousxd/nestjs-durable-core";
1888
+ import { SUMMARY_CHILD_LIMIT, childIdsOf, pageFan, resolveTenantToken as resolveTenantToken3, scopeTenantQuery, summarizeTimeline, tenantVisible } from "@dudousxd/nestjs-durable-core";
1595
1889
  import { Injectable as Injectable6 } from "@nestjs/common";
1596
1890
 
1597
1891
  // src/run-request-responder.ts
1598
- import { lifecycleKindOf, resolveWireTenant } from "@dudousxd/nestjs-durable-core";
1892
+ import { grantsClientTenant, lifecycleKindOf, verifyWireTenant } from "@dudousxd/nestjs-durable-core";
1599
1893
  var UNSUPPORTED_RUN_REQUEST = "unsupported-request";
1600
1894
  var BAD_RUN_REQUEST = "bad-request";
1601
1895
  var TENANT_REPUBLISH_MAX_LIMIT = 1e3;
@@ -1616,7 +1910,9 @@ var KNOWN_KINDS = /* @__PURE__ */ new Set([
1616
1910
  "republishLifecycle",
1617
1911
  "workflowLifecycle",
1618
1912
  "signal",
1619
- "schedule"
1913
+ "schedule",
1914
+ "signalWithStart",
1915
+ "publishEvent"
1620
1916
  ]);
1621
1917
  function wireDate(value) {
1622
1918
  if (value === void 0 || value === null) return void 0;
@@ -1692,7 +1988,8 @@ var RunRequestResponder = class {
1692
1988
  });
1693
1989
  }
1694
1990
  async handle(wire) {
1695
- const tenant = await resolveWireTenant(wire.tenant, this.verifyTenant);
1991
+ const verified = await verifyWireTenant(wire.tenant, this.verifyTenant);
1992
+ const tenant = verified?.tenant ?? null;
1696
1993
  if (tenant === null) {
1697
1994
  return {
1698
1995
  requestId: wire.requestId,
@@ -1870,7 +2167,18 @@ var RunRequestResponder = class {
1870
2167
  }
1871
2168
  };
1872
2169
  }
1873
- return this.answer(msg.requestId, () => signal.call(this.gateway, body.token, body.payload));
2170
+ return this.answer(msg.requestId, () => body.opts === void 0 ? signal.call(this.gateway, body.token, body.payload) : signal.call(this.gateway, body.token, body.payload, body.opts));
2171
+ }
2172
+ if (body.kind === "signalWithStart") {
2173
+ return this.signalWithStart(msg.requestId, body, msg.tenant, verified);
2174
+ }
2175
+ if (body.kind === "publishEvent") {
2176
+ const { publishEventForTenant } = this.gateway;
2177
+ if (!publishEventForTenant) return unsupported(msg.requestId, body.kind);
2178
+ if (typeof body.name !== "string" || body.name === "") {
2179
+ return badRequest(msg.requestId, "publishEvent needs an event name");
2180
+ }
2181
+ return this.answer(msg.requestId, () => publishEventForTenant.call(this.gateway, body.name, body.payload, msg.tenant));
1874
2182
  }
1875
2183
  if (body.kind === "republishLifecycle" && !this.gateway.republishLifecycle) {
1876
2184
  return unsupported(msg.requestId, body.kind);
@@ -1945,6 +2253,50 @@ var RunRequestResponder = class {
1945
2253
  };
1946
2254
  }
1947
2255
  }
2256
+ /**
2257
+ * A tenant's `signalWithStart`: the run it names must be the requester's when it exists, and so
2258
+ * must a run already waiting on the token; anything else is refused `cross-tenant` before the
2259
+ * gateway is called. The run is started in the requester's namespace (a customer tenant it claims
2260
+ * is kept only when its verified token grants it, as for a start-run).
2261
+ */
2262
+ async signalWithStart(requestId, body, tenant, verified) {
2263
+ const { signalWithStartForTenant, signalWaiter } = this.gateway;
2264
+ if (!signalWithStartForTenant) return unsupported(requestId, body.kind);
2265
+ const start = body.start;
2266
+ if (!start || typeof start.runId !== "string" || start.runId === "" || typeof start.workflow !== "string" || start.workflow === "" || typeof body.signal?.token !== "string" || body.signal.token === "") {
2267
+ return badRequest(requestId, "signalWithStart needs a workflow, a run id and a signal token");
2268
+ }
2269
+ const crossTenant = {
2270
+ requestId,
2271
+ result: {
2272
+ ok: false,
2273
+ error: {
2274
+ message: "run belongs to another tenant",
2275
+ code: "cross-tenant"
2276
+ }
2277
+ }
2278
+ };
2279
+ const existing = await this.runOf(start.runId);
2280
+ if (existing && existing.namespace !== tenant) return crossTenant;
2281
+ const waiterRunId = signalWaiter ? await signalWaiter.call(this.gateway, body.signal.token) : null;
2282
+ const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;
2283
+ if (waiter && waiter.namespace !== tenant) return crossTenant;
2284
+ const claim = start.tenantId !== void 0 ? grantsClientTenant(verified, start.tenantId) ? {
2285
+ tenantId: start.tenantId,
2286
+ ...start.tenantKind !== void 0 ? {
2287
+ tenantKind: start.tenantKind
2288
+ } : {}
2289
+ } : {
2290
+ tenantId: null
2291
+ } : {};
2292
+ return this.answer(requestId, () => signalWithStartForTenant.call(this.gateway, {
2293
+ ...start,
2294
+ tenant
2295
+ }, tenant, claim, {
2296
+ token: body.signal.token,
2297
+ payload: body.signal.payload
2298
+ }));
2299
+ }
1948
2300
  /** The run alone (`getRun`, else from its detail), or null when it does not exist. */
1949
2301
  async runOf(runId) {
1950
2302
  return this.gateway.getRun ? this.gateway.getRun(runId) : (await this.gateway.getRunDetail(runId))?.run ?? null;
@@ -2113,6 +2465,10 @@ var RunGatewayError = class extends Error {
2113
2465
  this.code = code;
2114
2466
  }
2115
2467
  };
2468
+ function unsupportedVerb(kind) {
2469
+ return new RunGatewayError(`${kind} is not supported by this server: the control plane is older than this tenant`, UNSUPPORTED_RUN_REQUEST);
2470
+ }
2471
+ __name(unsupportedVerb, "unsupportedVerb");
2116
2472
  var UnsupportedRunRequestError = class UnsupportedRunRequestError2 extends RunGatewayError {
2117
2473
  static {
2118
2474
  __name(this, "UnsupportedRunRequestError");
@@ -2204,7 +2560,7 @@ var ProxyRunGateway = class {
2204
2560
  request(body) {
2205
2561
  const source = this.tenantToken;
2206
2562
  if (typeof source !== "function") return this.send(source ?? this.tenant, body);
2207
- return resolveTenantToken2(source).then((tenant) => this.send(tenant, body));
2563
+ return resolveTenantToken3(source).then((tenant) => this.send(tenant, body));
2208
2564
  }
2209
2565
  send(tenant, body) {
2210
2566
  return new Promise((resolve, reject) => {
@@ -2418,7 +2774,7 @@ var ProxyRunGateway = class {
2418
2774
  * {@link RunGatewayError} with code {@link UNSUPPORTED_RUN_REQUEST}.
2419
2775
  */
2420
2776
  async requestNewVerb(body) {
2421
- 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");
2777
+ const notSupported = /* @__PURE__ */ __name(() => unsupportedVerb(body.kind), "notSupported");
2422
2778
  if (this.knownUnsupported(body.kind)) throw notSupported();
2423
2779
  let data;
2424
2780
  try {
@@ -2430,6 +2786,62 @@ var ProxyRunGateway = class {
2430
2786
  this.unsupportedUntil.set(body.kind, Date.now() + this.capabilityTtlMs);
2431
2787
  throw notSupported();
2432
2788
  }
2789
+ /**
2790
+ * Signal the run of this tenant's namespace waiting on `token` (`engine.signal`). Resolves null
2791
+ * when no run of this namespace waits on it: the control plane does NOT buffer a tenant's signal
2792
+ * for a wait opened later (another namespace's run could open it). A control plane that predates
2793
+ * the verb fails it with an {@link UNSUPPORTED_RUN_REQUEST} error.
2794
+ */
2795
+ async signal(token, payload, opts) {
2796
+ if (this.knownUnsupported("signal")) throw unsupportedVerb("signal");
2797
+ let data;
2798
+ try {
2799
+ data = await this.request(opts === void 0 ? {
2800
+ kind: "signal",
2801
+ token,
2802
+ payload
2803
+ } : {
2804
+ kind: "signal",
2805
+ token,
2806
+ payload,
2807
+ opts
2808
+ });
2809
+ } catch (err) {
2810
+ if (!isUnsupported(err)) throw err;
2811
+ }
2812
+ if (data !== void 0) return data;
2813
+ this.unsupportedUntil.set("signal", Date.now() + this.capabilityTtlMs);
2814
+ throw unsupportedVerb("signal");
2815
+ }
2816
+ /**
2817
+ * `engine.signalWithStart` for this tenant: the control plane starts `start` in this tenant's
2818
+ * namespace unless its run exists, then signals it (buffered until the run waits, when the token
2819
+ * names the run id). See the responder for the authorization rule.
2820
+ */
2821
+ signalWithStart(start, signal) {
2822
+ return this.requestNewVerb({
2823
+ kind: "signalWithStart",
2824
+ start,
2825
+ signal
2826
+ });
2827
+ }
2828
+ /**
2829
+ * Resume the runs of this tenant's namespace waiting on event `name` (`ctx.waitForEvent`).
2830
+ * Resolves how many it resumed. The tenant's own `onEvent` subscribers are started by the caller
2831
+ * (`DurableStartClient.publishEvent`), not here.
2832
+ */
2833
+ publishEvent(name, payload, opts) {
2834
+ return this.requestNewVerb({
2835
+ kind: "publishEvent",
2836
+ name,
2837
+ payload,
2838
+ ...opts?.id !== void 0 ? {
2839
+ opts: {
2840
+ id: opts.id
2841
+ }
2842
+ } : {}
2843
+ });
2844
+ }
2433
2845
  subscribe(runId, onEvent) {
2434
2846
  const unsubscribe = this.transport.onTenantEvent?.(this.tenant, (evt) => {
2435
2847
  if (evt.event.runId === runId) onEvent(evt.event);
@@ -2452,7 +2864,7 @@ ProxyRunGateway = _ts_decorate6([
2452
2864
  ], ProxyRunGateway);
2453
2865
 
2454
2866
  // src/retention-poller.ts
2455
- import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL5, STATE_STORE_CANONICAL, TERMINAL_RUN_STATUSES, parseDuration as parseDuration2 } from "@dudousxd/nestjs-durable-core";
2867
+ import { DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL5, STATE_STORE_CANONICAL, TERMINAL_RUN_STATUSES, parseDuration as parseDuration3 } from "@dudousxd/nestjs-durable-core";
2456
2868
  import { Inject as Inject5, Injectable as Injectable8, Optional as Optional2 } from "@nestjs/common";
2457
2869
 
2458
2870
  // src/settle-within.ts
@@ -2625,7 +3037,7 @@ function validateRetention(retention) {
2625
3037
  if (policy.maxAge == null && policy.maxCount == null) {
2626
3038
  throw new Error("durable retention: each policy must set maxAge and/or maxCount");
2627
3039
  }
2628
- if (policy.maxAge != null) parseDuration2(policy.maxAge);
3040
+ if (policy.maxAge != null) parseDuration3(policy.maxAge);
2629
3041
  for (const status of policy.statuses) {
2630
3042
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
2631
3043
  throw new Error(`durable retention: status "${status}" is not terminal; only ${TERMINAL_RUN_STATUSES.join(", ")} can be pruned`);
@@ -2682,7 +3094,7 @@ var RetentionPoller = class {
2682
3094
  return;
2683
3095
  }
2684
3096
  void this.sweep();
2685
- const intervalMs = retention.sweepInterval != null ? parseDuration2(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
3097
+ const intervalMs = retention.sweepInterval != null ? parseDuration3(retention.sweepInterval) : DEFAULT_SWEEP_INTERVAL_MS;
2686
3098
  if (intervalMs > 0) {
2687
3099
  this.timer = setInterval(() => void this.sweep(), intervalMs);
2688
3100
  this.timer.unref?.();
@@ -3118,8 +3530,14 @@ var StoreRunGateway = class {
3118
3530
  if (action === "trigger") return this.engine.schedules.trigger(id);
3119
3531
  return Promise.reject(new Error(`unknown schedule action ${String(action)}`));
3120
3532
  }
3121
- signal(token, payload) {
3122
- return this.engine.signal(token, payload);
3533
+ signal(token, payload, opts) {
3534
+ return this.engine.signal(token, payload, opts);
3535
+ }
3536
+ signalWithStartForTenant(start, namespace, clientTenant, signal) {
3537
+ return this.engine.signalWithStartForTenant(start, namespace, clientTenant, signal);
3538
+ }
3539
+ publishEventForTenant(name, payload, namespace) {
3540
+ return this.engine.publishEventForTenant(name, payload, namespace);
3123
3541
  }
3124
3542
  async signalWaiter(token) {
3125
3543
  const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
@@ -3218,7 +3636,7 @@ var TenantEventRepublisher = class {
3218
3636
 
3219
3637
  // src/timer-poller.ts
3220
3638
  import * as durableCore 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";
3639
+ import { ANNOUNCED_SCHEDULE_TAG, DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL6, WorkflowEngine as WorkflowEngine4, runSchedules, workflowName as workflowName4 } from "@dudousxd/nestjs-durable-core";
3222
3640
  import { Inject as Inject7, Injectable as Injectable10, Optional as Optional3 } from "@nestjs/common";
3223
3641
  function _ts_decorate10(decorators, target, key, desc) {
3224
3642
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -3269,13 +3687,15 @@ var TimerPoller = class {
3269
3687
  endWait;
3270
3688
  /** When the owed-lifecycle listing last succeeded (see {@link owedSweepDue}). */
3271
3689
  owedSweptAt;
3690
+ /** When the tenant schedule announcements were last reconciled (see {@link announcedSchedules}). */
3691
+ announcedSyncedAt;
3272
3692
  constructor(engine, options, leases = new SweepLeases()) {
3273
3693
  this.engine = engine;
3274
3694
  this.options = options;
3275
3695
  this.leases = leases;
3276
3696
  }
3277
3697
  async onApplicationBootstrap() {
3278
- for (const s of this.options.schedules ?? []) workflowName3(s.workflow);
3698
+ for (const s of this.options.schedules ?? []) workflowName4(s.workflow);
3279
3699
  if (!isDrivingOperator(this.options)) return;
3280
3700
  this.engine.consumeRuns?.();
3281
3701
  this.unsubscribeEnqueued = this.engine.onEnqueued((runId) => {
@@ -3358,7 +3778,8 @@ var TimerPoller = class {
3358
3778
  try {
3359
3779
  const now = Date.now();
3360
3780
  const stored = await this.engine.nextDueAt(now + wait, {
3361
- persistedSchedules: this.options.persistedSchedules === true
3781
+ persistedSchedules: this.options.persistedSchedules === true,
3782
+ announcedSchedules: this.announcedSchedules() !== void 0
3362
3783
  });
3363
3784
  const schedules = this.options.schedules;
3364
3785
  const scheduled = schedules && schedules.length > 0 && nextScheduleFireAt2 ? nextScheduleFireAt2(this.engine, schedules, now) : void 0;
@@ -3375,6 +3796,22 @@ var TimerPoller = class {
3375
3796
  }
3376
3797
  }
3377
3798
  /**
3799
+ * The tenant schedule adoption settings when it is on (see
3800
+ * {@link DurableModuleOptions.announcedSchedules}), else undefined: off by option, on a core
3801
+ * without it, or on a store that does not persist schedules.
3802
+ */
3803
+ announcedSchedules() {
3804
+ const option = this.options.announcedSchedules;
3805
+ if (option === false) return void 0;
3806
+ if (typeof this.engine.syncAnnouncedSchedules !== "function") return void 0;
3807
+ if (this.engine.schedules?.supported !== true) return void 0;
3808
+ const settings = typeof option === "object" ? option : {};
3809
+ return {
3810
+ syncMs: settings.syncMs ?? 15e3,
3811
+ graceMs: settings.graceMs
3812
+ };
3813
+ }
3814
+ /**
3378
3815
  * Whether this poll lists the owed lifecycle runs: until a sweep that listed them succeeded, then
3379
3816
  * once per `owedLifecycleSweepMs` (a clock that went back lists them again).
3380
3817
  */
@@ -3457,8 +3894,27 @@ var TimerPoller = class {
3457
3894
  if (schedules && schedules.length > 0) {
3458
3895
  note(await this.sweep("schedules", () => runSchedules(this.engine, schedules, Date.now())));
3459
3896
  }
3897
+ const announced = this.announcedSchedules();
3898
+ if (announced) {
3899
+ const at = Date.now();
3900
+ const last = this.announcedSyncedAt;
3901
+ if (last === void 0 || at < last || at - last >= announced.syncMs) {
3902
+ await this.sweep("announcedSchedules", () => this.leases.run("announced-schedules", async () => {
3903
+ await this.engine.syncAnnouncedSchedules({
3904
+ ...announced.graceMs !== void 0 ? {
3905
+ graceMs: announced.graceMs
3906
+ } : {}
3907
+ });
3908
+ this.announcedSyncedAt = at;
3909
+ }));
3910
+ }
3911
+ }
3460
3912
  if (this.options.persistedSchedules) {
3461
3913
  note(await this.sweep("persistedSchedules", () => this.engine.schedules.tick()));
3914
+ } else if (announced) {
3915
+ note(await this.sweep("announcedScheduleFires", () => this.engine.schedules.tick(Date.now(), {
3916
+ tag: ANNOUNCED_SCHEDULE_TAG
3917
+ })));
3462
3918
  }
3463
3919
  return worked;
3464
3920
  }
@@ -3484,31 +3940,10 @@ TimerPoller = _ts_decorate10([
3484
3940
  ])
3485
3941
  ], TimerPoller);
3486
3942
 
3487
- // src/tokens.ts
3488
- import { RunGateway } from "@dudousxd/nestjs-durable-core";
3489
- var CONTEXT_ACCESSOR = Symbol.for("@dudousxd/nestjs-context:accessor");
3490
- var RUN_GATEWAY = RunGateway;
3491
-
3492
3943
  // src/workflow.registrar.ts
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";
3944
+ 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 workflowName5 } from "@dudousxd/nestjs-durable-core";
3494
3945
  import { Inject as Inject8, Injectable as Injectable11 } from "@nestjs/common";
3495
3946
  import { DiscoveryService as DiscoveryService4, MetadataScanner as MetadataScanner4 } from "@nestjs/core";
3496
-
3497
- // src/step-interceptor.ts
3498
- import "reflect-metadata";
3499
- var STEP_INTERCEPTOR_METADATA = Symbol("nestjs-durable:step-interceptor");
3500
- function StepInterceptor() {
3501
- return (target) => {
3502
- Reflect.defineMetadata(STEP_INTERCEPTOR_METADATA, true, target);
3503
- };
3504
- }
3505
- __name(StepInterceptor, "StepInterceptor");
3506
- function isStepInterceptor(target) {
3507
- return Reflect.getMetadata(STEP_INTERCEPTOR_METADATA, target) === true;
3508
- }
3509
- __name(isStepInterceptor, "isStepInterceptor");
3510
-
3511
- // src/workflow.registrar.ts
3512
3947
  function _ts_decorate11(decorators, target, key, desc) {
3513
3948
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3514
3949
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -3650,7 +4085,7 @@ var WorkflowRegistrar = class {
3650
4085
  });
3651
4086
  deadLetterByWorkflow.set(meta.name, dlqName);
3652
4087
  } else if (meta.deadLetterWorkflow) {
3653
- deadLetterByWorkflow.set(meta.name, workflowName4(meta.deadLetterWorkflow));
4088
+ deadLetterByWorkflow.set(meta.name, workflowName5(meta.deadLetterWorkflow));
3654
4089
  }
3655
4090
  });
3656
4091
  this.reportUnattributed(unattributed);
@@ -3698,28 +4133,36 @@ var WorkflowRegistrar = class {
3698
4133
  * a `dlq:<runId>` id, so re-recovery never double-dispatches.
3699
4134
  */
3700
4135
  installDeadLetterRouting(byWorkflow) {
3701
- const fallback = this.options.deadLetterWorkflow ? workflowName4(this.options.deadLetterWorkflow) : void 0;
4136
+ const fallback = this.options.deadLetterWorkflow ? workflowName5(this.options.deadLetterWorkflow) : void 0;
3702
4137
  if (byWorkflow.size === 0 && !fallback) return;
3703
4138
  this.engine.onDead((run) => {
3704
- const target = byWorkflow.get(run.workflow) ?? fallback;
3705
- if (!target) return;
3706
- void this.engine.start(
3707
- target,
3708
- {
3709
- deadRunId: run.id,
3710
- workflow: run.workflow,
3711
- input: run.input,
3712
- error: run.error
3713
- },
3714
- `dlq:${run.id}`,
3715
- // Route the dead-letter handler to the dead run's OWN tenant so an operator dispatches it to
3716
- // that tenant's worker group (`target@<tenant>`), not the bare group.
3717
- {
3718
- namespace: run.namespace
3719
- }
3720
- ).catch(() => void 0);
4139
+ void this.routeDead(run, byWorkflow, fallback).catch(() => void 0);
3721
4140
  });
3722
4141
  }
4142
+ /** {@link installDeadLetterRouting}'s routing of one dead run. */
4143
+ async routeDead(run, byWorkflow, fallback) {
4144
+ let target = byWorkflow.get(run.workflow);
4145
+ if (!target && fallback) {
4146
+ if (await this.engine.announcedDeadLetter?.(run).catch(() => void 0)) return;
4147
+ target = fallback;
4148
+ }
4149
+ if (!target) return;
4150
+ await this.engine.start(
4151
+ target,
4152
+ {
4153
+ deadRunId: run.id,
4154
+ workflow: run.workflow,
4155
+ input: run.input,
4156
+ error: run.error
4157
+ },
4158
+ `dlq:${run.id}`,
4159
+ // Route the dead-letter handler to the dead run's OWN tenant so an operator dispatches it to
4160
+ // that tenant's worker group (`target@<tenant>`), not the bare group.
4161
+ {
4162
+ namespace: run.namespace
4163
+ }
4164
+ ).catch(() => void 0);
4165
+ }
3723
4166
  };
3724
4167
  WorkflowRegistrar = _ts_decorate11([
3725
4168
  Injectable11(),
@@ -4007,7 +4450,6 @@ function resolveTopologyPreset(options) {
4007
4450
  };
4008
4451
  }
4009
4452
  __name(resolveTopologyPreset, "resolveTopologyPreset");
4010
- var TENANT_AUTH = Symbol("nestjs-durable:tenant-auth");
4011
4453
  var RunGatewayBootstrap = class RunGatewayBootstrap2 {
4012
4454
  static {
4013
4455
  __name(this, "RunGatewayBootstrap");
@@ -4192,12 +4634,29 @@ var DurableModule = class _DurableModule {
4192
4634
  provide: WorkflowEngine7,
4193
4635
  useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef, auth) => {
4194
4636
  if (options.store === void 0) {
4195
- return new DurableStartClient({
4196
- ...options,
4197
- ...auth.tenantToken !== void 0 ? {
4198
- tenantToken: auth.tenantToken
4199
- } : {}
4200
- }, void 0, resolveAccessor(moduleRef));
4637
+ return new DurableStartClient(
4638
+ {
4639
+ ...options,
4640
+ ...auth.tenantToken !== void 0 ? {
4641
+ tenantToken: auth.tenantToken
4642
+ } : {}
4643
+ },
4644
+ void 0,
4645
+ resolveAccessor(moduleRef),
4646
+ // `signal`/`signalWithStart`/`publishEvent` go to the control plane as run requests,
4647
+ // over the one `ProxyRunGateway` bound under `RunGateway` (it owns the reply
4648
+ // subscription). Resolved lazily: that gateway is built after this facade.
4649
+ () => {
4650
+ try {
4651
+ const gateway = moduleRef.get(RunGateway2, {
4652
+ strict: false
4653
+ });
4654
+ return gateway instanceof ProxyRunGateway ? gateway : void 0;
4655
+ } catch {
4656
+ return void 0;
4657
+ }
4658
+ }
4659
+ );
4201
4660
  }
4202
4661
  if (!store) {
4203
4662
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
@@ -4630,6 +5089,7 @@ export {
4630
5089
  Step,
4631
5090
  StepInterceptor,
4632
5091
  StoreRunGateway,
5092
+ TENANT_AUTH,
4633
5093
  TENANT_REPUBLISH_MAX_LIMIT,
4634
5094
  TenantEventRepublisher,
4635
5095
  ThinStepRegistrar,
@@ -4665,6 +5125,7 @@ export {
4665
5125
  scheduleRunIdAt,
4666
5126
  scheduledRunId,
4667
5127
  signTenantToken,
5128
+ tenantScheduleAnnouncement,
4668
5129
  thinWorkerProviders,
4669
5130
  triggeredRunsOf,
4670
5131
  unavailableRunGateway