@dudousxd/nestjs-durable-core 0.88.0 → 0.90.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
@@ -771,7 +771,7 @@ var TERMINAL_RUN_STATUSES = [
771
771
  ];
772
772
  function isNonEmptyRunScope(scope) {
773
773
  if (!scope) return false;
774
- return scope.workflow !== void 0 || scope.workflows !== void 0 || scope.tag !== void 0 || scope.tags !== void 0 || scope.namespace !== void 0 || scope.namespaces !== void 0 || scope.attributes !== void 0 && scope.attributes.length > 0;
774
+ return scope.workflow !== void 0 || scope.workflows !== void 0 || scope.tag !== void 0 || scope.tags !== void 0 || scope.namespace !== void 0 || scope.namespaces !== void 0 || scope.tenantId !== void 0 || scope.tenantIds !== void 0 || scope.attributes !== void 0 && scope.attributes.length > 0;
775
775
  }
776
776
  __name(isNonEmptyRunScope, "isNonEmptyRunScope");
777
777
  var PARENT_CLOSE_TAG_PREFIX = "parent-close:";
@@ -844,6 +844,31 @@ function acceptingSubscription(subscriptions, payload) {
844
844
  };
845
845
  }
846
846
  __name(acceptingSubscription, "acceptingSubscription");
847
+ var BUFFERED_EVENT_TENANTS = "__durableEventTenants";
848
+ function scopeBufferedEvent(payload, tenantIds) {
849
+ return tenantIds === void 0 ? payload : {
850
+ [BUFFERED_EVENT_TENANTS]: tenantIds,
851
+ payload
852
+ };
853
+ }
854
+ __name(scopeBufferedEvent, "scopeBufferedEvent");
855
+ function readBufferedEvent(stored) {
856
+ if (stored !== null && typeof stored === "object" && Array.isArray(stored[BUFFERED_EVENT_TENANTS]) && Object.keys(stored).length === 2 && "payload" in stored) {
857
+ const scoped = stored;
858
+ return {
859
+ payload: scoped.payload,
860
+ tenantIds: scoped[BUFFERED_EVENT_TENANTS]
861
+ };
862
+ }
863
+ return {
864
+ payload: stored
865
+ };
866
+ }
867
+ __name(readBufferedEvent, "readBufferedEvent");
868
+ function bufferedEventReaches(tenantIds, tenantId) {
869
+ return tenantIds === void 0 || tenantIds.includes(tenantId ?? null);
870
+ }
871
+ __name(bufferedEventReaches, "bufferedEventReaches");
847
872
 
848
873
  // src/lifecycle-events.ts
849
874
  function runCompletedEvent(workflow) {
@@ -1633,7 +1658,8 @@ async function runStepHandler(task, handler) {
1633
1658
  workflow: void 0,
1634
1659
  name: task.name,
1635
1660
  seq: task.seq,
1636
- attempt: task.attempt
1661
+ attempt: task.attempt,
1662
+ context: task.context
1637
1663
  },
1638
1664
  // Outside any ambient workflow ctx: an in-process transport runs the handler on the parent
1639
1665
  // body's async path, but a handler is not the body (see `runOutsideWorkflowCtx`).
@@ -1974,10 +2000,14 @@ var Entities = class {
1974
2000
  };
1975
2001
 
1976
2002
  // src/event-accumulators.ts
1977
- function accumulatorRunId(target, key) {
1978
- if (key === void 0) return `__evtacc__:${target}`;
1979
- const escaped = encodeURIComponent(key).replace(/[~!'()*.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
1980
- return `__evtacc__:${target}:${escaped}`;
2003
+ function escapeIdPart(value) {
2004
+ return encodeURIComponent(value).replace(/[~!'()*.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
2005
+ }
2006
+ __name(escapeIdPart, "escapeIdPart");
2007
+ function accumulatorRunId(target, key, tenant) {
2008
+ const base = tenant === void 0 ? "__evtacc__" : `__evtacc__@${escapeIdPart(tenant)}`;
2009
+ if (key === void 0) return `${base}:${target}`;
2010
+ return `${base}:${target}:${escapeIdPart(key)}`;
1981
2011
  }
1982
2012
  __name(accumulatorRunId, "accumulatorRunId");
1983
2013
  var ACCUMULATOR_SEEN_MAX = 1e3;
@@ -2022,7 +2052,7 @@ var SeenEvents = class SeenEvents2 {
2022
2052
  } : rest;
2023
2053
  }
2024
2054
  };
2025
- var accToken = /* @__PURE__ */ __name((input) => accumulatorRunId(input.target, input.key), "accToken");
2055
+ var accToken = /* @__PURE__ */ __name((input) => accumulatorRunId(input.target, input.key, input.tenant), "accToken");
2026
2056
  var EventAccumulators = class {
2027
2057
  static {
2028
2058
  __name(this, "EventAccumulators");
@@ -2041,8 +2071,12 @@ var EventAccumulators = class {
2041
2071
  * Route an `onEvent` payload into its target's debounce/batch accumulator: the target's one, or
2042
2072
  * with a `key`, the one for `String(config.key(payload))`. A `key` that throws rejects the route.
2043
2073
  * With `id`, the accumulator counts the event once however many times it is routed.
2074
+ *
2075
+ * `tenant` is the tenant the event belongs to when tenancy is on: a tenant gets its own
2076
+ * accumulator, stamped with it (so its target runs are too); `null` routes into the shared one,
2077
+ * stamped with no tenant. Undefined (tenancy off) starts the accumulator as before.
2044
2078
  */
2045
- route(target, config, payload, id) {
2079
+ route(target, config, payload, id, tenant) {
2046
2080
  const input = {
2047
2081
  target,
2048
2082
  windowMs: config.windowMs,
@@ -2051,6 +2085,9 @@ var EventAccumulators = class {
2051
2085
  } : {},
2052
2086
  ...config.key ? {
2053
2087
  key: String(config.key(payload))
2088
+ } : {},
2089
+ ...tenant ? {
2090
+ tenant: tenant.id
2054
2091
  } : {}
2055
2092
  };
2056
2093
  const workflow = config.mode === "debounce" ? "__evt_debounce" : "__evt_batch";
@@ -2060,10 +2097,18 @@ var EventAccumulators = class {
2060
2097
  id,
2061
2098
  payload
2062
2099
  };
2100
+ const opts = tenant === void 0 ? void 0 : tenant === null ? {
2101
+ tenantId: null
2102
+ } : {
2103
+ tenantId: tenant.id,
2104
+ ...tenant.kind !== void 0 ? {
2105
+ tenantKind: tenant.kind
2106
+ } : {}
2107
+ };
2063
2108
  return this.host.signalWithStart(workflow, input, token, {
2064
2109
  token,
2065
2110
  payload: signal
2066
- });
2111
+ }, opts);
2067
2112
  }
2068
2113
  /** Fire the target with the LAST payload once events have been quiet for `windowMs`. */
2069
2114
  async debounce(ctx, input) {
@@ -3551,6 +3596,78 @@ function remember(memo, key, runId) {
3551
3596
  }
3552
3597
  __name(remember, "remember");
3553
3598
 
3599
+ // src/tenancy.ts
3600
+ function tenantVisible(row, filter) {
3601
+ const id = row.tenantId ?? null;
3602
+ switch (filter.mode) {
3603
+ case "system":
3604
+ case "all":
3605
+ return true;
3606
+ case "tenantless":
3607
+ return id === null;
3608
+ case "tenant":
3609
+ return id === filter.tenantId || id === null && filter.nullRows === "shared";
3610
+ }
3611
+ }
3612
+ __name(tenantVisible, "tenantVisible");
3613
+ function tenantIdsFor(filter) {
3614
+ switch (filter.mode) {
3615
+ case "system":
3616
+ case "all":
3617
+ return void 0;
3618
+ case "tenantless":
3619
+ return [
3620
+ null
3621
+ ];
3622
+ case "tenant":
3623
+ return filter.nullRows === "shared" ? [
3624
+ filter.tenantId,
3625
+ null
3626
+ ] : [
3627
+ filter.tenantId
3628
+ ];
3629
+ }
3630
+ }
3631
+ __name(tenantIdsFor, "tenantIdsFor");
3632
+ function scopeTenantQuery(query, filter) {
3633
+ const allowed = tenantIdsFor(filter);
3634
+ if (allowed === void 0) return query;
3635
+ const tenantIds = query.tenantIds ? query.tenantIds.filter((id) => allowed.includes(id)) : allowed;
3636
+ return {
3637
+ ...query,
3638
+ tenantIds
3639
+ };
3640
+ }
3641
+ __name(scopeTenantQuery, "scopeTenantQuery");
3642
+ function rowTenant(row) {
3643
+ if (row.tenantId == null) return void 0;
3644
+ return row.tenantKind != null ? {
3645
+ id: row.tenantId,
3646
+ kind: row.tenantKind
3647
+ } : {
3648
+ id: row.tenantId
3649
+ };
3650
+ }
3651
+ __name(rowTenant, "rowTenant");
3652
+ function inheritTenant(row) {
3653
+ return row.tenantId == null ? {
3654
+ tenantId: null
3655
+ } : {
3656
+ tenantId: row.tenantId,
3657
+ ...row.tenantKind != null ? {
3658
+ tenantKind: row.tenantKind
3659
+ } : {}
3660
+ };
3661
+ }
3662
+ __name(inheritTenant, "inheritTenant");
3663
+ function matchesTenantPredicates(row, query) {
3664
+ const id = row.tenantId ?? null;
3665
+ if (query.tenantId !== void 0 && id !== query.tenantId) return false;
3666
+ if (query.tenantIds !== void 0 && !query.tenantIds.includes(id)) return false;
3667
+ return true;
3668
+ }
3669
+ __name(matchesTenantPredicates, "matchesTenantPredicates");
3670
+
3554
3671
  // src/schedules.ts
3555
3672
  var ScheduleAlreadyExistsError = class extends Error {
3556
3673
  static {
@@ -3608,6 +3725,16 @@ var ScheduleClient = class {
3608
3725
  listSchedules: /* @__PURE__ */ __name((q) => s.listSchedules.call(s, q), "listSchedules")
3609
3726
  };
3610
3727
  }
3728
+ filter() {
3729
+ return this.host.tenantFilter?.() ?? {
3730
+ mode: "system"
3731
+ };
3732
+ }
3733
+ /** The schedule `id` if it exists and the caller may see it (tenancy), else null. */
3734
+ async visible(id) {
3735
+ const record = await this.requireStore().getSchedule(id);
3736
+ return record && tenantVisible(record, this.filter()) ? record : null;
3737
+ }
3611
3738
  /** Create a schedule. Throws {@link ScheduleAlreadyExistsError} if the id is taken. */
3612
3739
  async create(opts) {
3613
3740
  const store = this.requireStore();
@@ -3621,19 +3748,24 @@ var ScheduleClient = class {
3621
3748
  */
3622
3749
  async upsert(opts) {
3623
3750
  const store = this.requireStore();
3624
- return this.write(opts, await store.getSchedule(opts.id));
3751
+ const existing = await store.getSchedule(opts.id);
3752
+ if (existing && !tenantVisible(existing, this.filter())) {
3753
+ throw new ScheduleAlreadyExistsError(opts.id);
3754
+ }
3755
+ return this.write(opts, existing);
3625
3756
  }
3626
- /** The schedule `id`, or null. */
3757
+ /** The schedule `id`, or null (also null for another tenant's schedule). */
3627
3758
  async get(id) {
3628
- const record = await this.requireStore().getSchedule(id);
3759
+ const record = await this.visible(id);
3629
3760
  return record ? describe(record) : null;
3630
3761
  }
3631
- /** Schedules matching `query`, soonest-due first. */
3762
+ /** Schedules matching `query` (and visible to the caller's tenant), soonest-due first. */
3632
3763
  async list(query = {}) {
3633
- return (await this.requireStore().listSchedules(query)).map(describe);
3764
+ return (await this.requireStore().listSchedules(scopeTenantQuery(query, this.filter()))).map(describe);
3634
3765
  }
3635
3766
  /** Delete the schedule. Runs it already started are left alone. Returns whether it existed. */
3636
- delete(id) {
3767
+ async delete(id) {
3768
+ if (!await this.visible(id)) return false;
3637
3769
  return this.requireStore().deleteSchedule(id);
3638
3770
  }
3639
3771
  /** Stop firing until {@link resume}. `note` records why (shown by `get`/`list`). */
@@ -3768,10 +3900,34 @@ var ScheduleClient = class {
3768
3900
  return !!prev && !TERMINAL_RUN_STATUSES.includes(prev.status);
3769
3901
  }
3770
3902
  async mustGet(id) {
3771
- const record = await this.requireStore().getSchedule(id);
3903
+ const record = await this.visible(id);
3772
3904
  if (!record) throw new ScheduleNotFoundError(id);
3773
3905
  return record;
3774
3906
  }
3907
+ /** Explicit `opts.tenantId` → the existing schedule's tenant (upsert) → the context tenant → none. */
3908
+ scheduleTenant(opts, existing) {
3909
+ let tenant;
3910
+ if (opts.tenantId !== void 0) {
3911
+ tenant = opts.tenantId === null ? void 0 : {
3912
+ id: opts.tenantId,
3913
+ kind: opts.tenantKind
3914
+ };
3915
+ } else if (existing) {
3916
+ tenant = existing.tenantId == null ? void 0 : {
3917
+ id: existing.tenantId,
3918
+ kind: existing.tenantKind ?? void 0
3919
+ };
3920
+ } else {
3921
+ tenant = this.host.tenant?.();
3922
+ }
3923
+ if (!tenant) return {};
3924
+ return tenant.kind !== void 0 ? {
3925
+ tenantId: tenant.id,
3926
+ tenantKind: tenant.kind
3927
+ } : {
3928
+ tenantId: tenant.id
3929
+ };
3930
+ }
3775
3931
  async write(opts, existing) {
3776
3932
  const store = this.requireStore();
3777
3933
  const spec = toSpec(opts);
@@ -3790,6 +3946,7 @@ var ScheduleClient = class {
3790
3946
  ...existing?.state ?? {},
3791
3947
  window
3792
3948
  }),
3949
+ ...this.scheduleTenant(opts, existing),
3793
3950
  createdAt: existing?.createdAt ?? new Date(now),
3794
3951
  updatedAt: new Date(now)
3795
3952
  };
@@ -3872,7 +4029,10 @@ function startOptions(record) {
3872
4029
  namespace: record.namespace,
3873
4030
  searchAttributes: spec.searchAttributes,
3874
4031
  priority: spec.priority,
3875
- concurrency: spec.concurrency
4032
+ concurrency: spec.concurrency,
4033
+ // Every fire belongs to the schedule's customer (or explicitly to none), never to whichever
4034
+ // poller or request happened to fire it.
4035
+ ...inheritTenant(record)
3876
4036
  });
3877
4037
  }
3878
4038
  __name(startOptions, "startOptions");
@@ -3902,6 +4062,8 @@ function describe(record) {
3902
4062
  lastRunId: state.lastRunId,
3903
4063
  fires: state.fires ?? 0,
3904
4064
  lastError: state.lastError,
4065
+ tenantId: record.tenantId ?? void 0,
4066
+ tenantKind: record.tenantKind ?? void 0,
3905
4067
  createdAt: record.createdAt,
3906
4068
  updatedAt: record.updatedAt
3907
4069
  });
@@ -5255,8 +5417,14 @@ function createWorkflowCtx(host, runId, compensations, workflow = "", searchAttr
5255
5417
  }, "consumeBuffered");
5256
5418
  const consumeBufferedEvent = /* @__PURE__ */ __name(async (name, match, token, seq) => {
5257
5419
  const candidates = await store.listBufferedEvents(name, EVENT_BUFFER_SCAN_LIMIT);
5420
+ let runTenantId;
5258
5421
  for (const candidate of candidates) {
5259
- if (!eventMatches(candidate.payload, match ?? {})) continue;
5422
+ const { payload, tenantIds } = readBufferedEvent(candidate.payload);
5423
+ if (!eventMatches(payload, match ?? {})) continue;
5424
+ if (tenantIds !== void 0) {
5425
+ runTenantId ??= store.getRun(runId).then((run) => run?.tenantId ?? null);
5426
+ if (!bufferedEventReaches(tenantIds, await runTenantId)) continue;
5427
+ }
5260
5428
  if (!await store.removeBufferedEvent(candidate.id)) continue;
5261
5429
  await store.removeSignalWaiter({
5262
5430
  token,
@@ -5268,10 +5436,10 @@ function createWorkflowCtx(host, runId, compensations, workflow = "", searchAttr
5268
5436
  seq,
5269
5437
  name: `signal:${token}`,
5270
5438
  kind: "signal",
5271
- output: candidate.payload
5439
+ output: payload
5272
5440
  }));
5273
5441
  return {
5274
- value: candidate.payload
5442
+ value: payload
5275
5443
  };
5276
5444
  }
5277
5445
  return null;
@@ -6436,6 +6604,8 @@ var WorkflowEngine = class _WorkflowEngine {
6436
6604
  context;
6437
6605
  /** Establish the originating context ambiently around a local step body (see {@link WorkflowEngineDeps.rehydrate}). Default passthrough. */
6438
6606
  rehydrate;
6607
+ /** Tenancy seam (see {@link WorkflowEngineDeps.tenancy}); undefined = off. */
6608
+ tenancy;
6439
6609
  compensationRetries;
6440
6610
  /** Persist a `running` checkpoint at the start of a local step body (see {@link WorkflowEngineDeps.trackStepStart}). */
6441
6611
  trackStepStart;
@@ -6453,6 +6623,10 @@ var WorkflowEngine = class _WorkflowEngine {
6453
6623
  workflows = /* @__PURE__ */ new Map();
6454
6624
  /** The newest registered version per workflow name — used to `start` new runs. */
6455
6625
  latest = /* @__PURE__ */ new Map();
6626
+ /** Workflows this instance starts but never runs, keyed `name@version` (like {@link workflows}), so every version stays startable. See {@link registerStartOnly}. */
6627
+ startOnly = /* @__PURE__ */ new Map();
6628
+ /** The latest start-only registration per name, for unpinned starts (like {@link latest}). */
6629
+ startOnlyLatest = /* @__PURE__ */ new Map();
6456
6630
  /** Event name → subscribing workflow name → that workflow's subscriptions to it. See `onEvent`. */
6457
6631
  eventTriggers = /* @__PURE__ */ new Map();
6458
6632
  /** Durable-entity subsystem (registers the `__entity` runner; see `registerEntity`). */
@@ -6641,6 +6815,7 @@ var WorkflowEngine = class _WorkflowEngine {
6641
6815
  this.traceparent = deps.traceparent;
6642
6816
  this.context = deps.context;
6643
6817
  this.rehydrate = deps.rehydrate ?? ((_carrier, fn) => fn());
6818
+ this.tenancy = deps.tenancy;
6644
6819
  this.compensationRetries = Math.max(1, deps.compensationRetries ?? 1);
6645
6820
  this.trackStepStart = deps.trackStepStart ?? true;
6646
6821
  this.localWork = new BoundedRunner(LOCAL_RUN_CONCURRENCY);
@@ -6670,7 +6845,9 @@ var WorkflowEngine = class _WorkflowEngine {
6670
6845
  this.schedules = new ScheduleClient(this.store, {
6671
6846
  start: /* @__PURE__ */ __name((workflow, input, runId, opts) => this.start(workflow, input, runId, opts), "start"),
6672
6847
  getRun: /* @__PURE__ */ __name((runId) => this.store.getRun(runId), "getRun"),
6673
- isDraining: /* @__PURE__ */ __name(() => this.draining, "isDraining")
6848
+ isDraining: /* @__PURE__ */ __name(() => this.draining, "isDraining"),
6849
+ tenant: /* @__PURE__ */ __name(() => this.tenancy?.current(), "tenant"),
6850
+ tenantFilter: /* @__PURE__ */ __name(() => this.tenantFilter(), "tenantFilter")
6674
6851
  }, {
6675
6852
  namespace: this.namespace,
6676
6853
  clock: this.clock
@@ -6774,7 +6951,18 @@ var WorkflowEngine = class _WorkflowEngine {
6774
6951
  }
6775
6952
  }
6776
6953
  });
6777
- this.accumulators = new EventAccumulators(this);
6954
+ this.accumulators = new EventAccumulators({
6955
+ register: /* @__PURE__ */ __name((name, version, fn, opts) => this.register(name, version, fn, opts), "register"),
6956
+ // The engine picks the accumulator's tenant itself, so its signal is the engine's own
6957
+ // delivery: not subject to the publisher's tenancy filter.
6958
+ signalWithStart: /* @__PURE__ */ __name(async (workflow, input, runId, signal, opts) => {
6959
+ await this.start(workflow, input, runId, opts);
6960
+ await this.signalUnchecked(signal.token, signal.payload);
6961
+ return {
6962
+ runId
6963
+ };
6964
+ }, "signalWithStart")
6965
+ });
6778
6966
  this.entities = new Entities(this, {
6779
6967
  bufferSignal: /* @__PURE__ */ __name((token, payload) => this.store.bufferSignal(token, payload), "bufferSignal"),
6780
6968
  wakeWaiter: /* @__PURE__ */ __name((token, payload) => this.wakeSignalWaiter(token, payload), "wakeWaiter"),
@@ -6973,7 +7161,7 @@ var WorkflowEngine = class _WorkflowEngine {
6973
7161
  if (!this.isRegisteredHere(run) && !await this.canResolveWorkflow(run)) {
6974
7162
  const result = await this.settleUnregistered(run, nowMs);
6975
7163
  if (result) settled?.set(run.id, result);
6976
- else if (result === void 0) this.logUnregisteredSkip(run);
7164
+ else if (result === void 0 && !this.isStartOnlyHere(run)) this.logUnregisteredSkip(run);
6977
7165
  continue;
6978
7166
  }
6979
7167
  try {
@@ -7119,6 +7307,34 @@ var WorkflowEngine = class _WorkflowEngine {
7119
7307
  }
7120
7308
  }
7121
7309
  /**
7310
+ * Let {@link start} create runs of `name@version` on this instance without registering a body here:
7311
+ * the run is stored and left for an instance that {@link register}ed the workflow, and this one
7312
+ * never executes it. For a process that only emits work (an API pod) while workers run it.
7313
+ *
7314
+ * Runs this instance picks up anyway (a driving poll, the run queue) are released for another
7315
+ * instance without a log line, and dead-lettered after `unregisteredWorkflowGraceMs` like any run
7316
+ * whose workflow nobody registered. A {@link register} of the same name on this instance wins.
7317
+ */
7318
+ registerStartOnly(name, version, opts) {
7319
+ const entry = {
7320
+ name,
7321
+ version,
7322
+ fn: /* @__PURE__ */ __name(() => {
7323
+ throw new Error(`workflow ${name} is start-only on this instance \u2014 it has no body here`);
7324
+ }, "fn"),
7325
+ tags: opts?.tags,
7326
+ validateInput: opts?.validateInput,
7327
+ origin: opts?.origin
7328
+ };
7329
+ this.startOnly.set(versionKey(name, version), entry);
7330
+ const current = this.startOnlyLatest.get(name);
7331
+ if (!current || isNewerVersion(version, current.version)) this.startOnlyLatest.set(name, entry);
7332
+ }
7333
+ /** Whether `run` is of a workflow this instance only starts (see {@link registerStartOnly}). */
7334
+ isStartOnlyHere(run) {
7335
+ return !this.isRegisteredHere(run) && this.startOnly.has(versionKey(run.workflow, run.workflowVersion));
7336
+ }
7337
+ /**
7122
7338
  * The retained in-process body for `name@version`, for an IN-APP worker that consumes this engine's
7123
7339
  * own group to SERVE a group-served `register(..., { group, executor })` workflow (uniform dispatch):
7124
7340
  * the worker fetches the body by name when it picks up the dispatched {@link WorkflowTask}, replays
@@ -7222,15 +7438,19 @@ var WorkflowEngine = class _WorkflowEngine {
7222
7438
  * time from {@link context} — the SAME reader stamped on dispatched remote tasks — so a local step
7223
7439
  * sees the live tenant / user / trace ids ambiently (via the {@link rehydrate} bridge). Default
7224
7440
  * `rehydrate` is a passthrough, so this is byte-identical to a bare body call when unwired.
7441
+ *
7442
+ * The run row's tenant is re-applied INSIDE the rehydrated context: an app carrier (a custom
7443
+ * `serialize`/`deserialize`) may not carry the tenant, and its deserializer would otherwise replace
7444
+ * the tenant the turn was started with. Local steps always see the row's tenant.
7225
7445
  */
7226
- interceptStep(invocation, body) {
7446
+ interceptStep(invocation, body, tenant) {
7227
7447
  const carrier = this.context?.();
7228
7448
  const run = /* @__PURE__ */ __name(() => {
7229
7449
  if (this.interceptors.length === 0) return body();
7230
7450
  const chain = this.interceptors.reduceRight((next, interceptor) => () => interceptor(invocation, next), body);
7231
7451
  return chain();
7232
7452
  }, "run");
7233
- return this.rehydrate(carrier, run);
7453
+ return this.rehydrate(carrier, () => tenant ? this.inRunTenant(tenant, run) : run());
7234
7454
  }
7235
7455
  /**
7236
7456
  * Be notified when a run is cancelled — on ANY instance, via the transport control plane. A
@@ -7421,9 +7641,12 @@ var WorkflowEngine = class _WorkflowEngine {
7421
7641
  * an announcement carries no `where` or `input`. `routeIdOf` names the event for a subscriber's
7422
7642
  * debounce/batch accumulator, which counts an id once. Returns the subscribers reached, with the
7423
7643
  * run each started (none when the payload went into its debounce/batch accumulator), and the ones
7424
- * that could not be started, with why.
7644
+ * that could not be started, with why. `batchTenant` is the tenant whose debounce/batch accumulator
7645
+ * the payload goes into (see {@link EventAccumulators.route}). `runTenant`, when set, is the tenant
7646
+ * every directly started subscriber run gets (a lifecycle event: the settled run's), instead of the
7647
+ * context's at publish time (which may be none, e.g. the background retry pass).
7425
7648
  */
7426
- async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf) {
7649
+ async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf, batchTenant, runTenant) {
7427
7650
  const reached = [];
7428
7651
  const failed = [];
7429
7652
  for (const [workflow, subscriptions] of this.eventTriggers.get(name) ?? []) {
@@ -7440,13 +7663,13 @@ var WorkflowEngine = class _WorkflowEngine {
7440
7663
  const input = accepted.input ? accepted.input(payload) : payload;
7441
7664
  const batch = this.latest.get(workflow)?.eventBatch;
7442
7665
  if (batch) {
7443
- await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow));
7666
+ await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow), batchTenant);
7444
7667
  reached.push({
7445
7668
  workflow
7446
7669
  });
7447
7670
  } else {
7448
7671
  const runId = runIdOf(workflow);
7449
- await this.start(workflow, input, runId);
7672
+ await this.start(workflow, input, runId, runTenant);
7450
7673
  reached.push({
7451
7674
  workflow,
7452
7675
  runId
@@ -7464,7 +7687,7 @@ var WorkflowEngine = class _WorkflowEngine {
7464
7687
  if (local?.has(workflow) || only && !only.has(workflow)) continue;
7465
7688
  try {
7466
7689
  const runId = runIdOf(workflow);
7467
- await this.start(workflow, payload, runId);
7690
+ await this.start(workflow, payload, runId, runTenant);
7468
7691
  reached.push({
7469
7692
  workflow,
7470
7693
  runId
@@ -7821,11 +8044,12 @@ var WorkflowEngine = class _WorkflowEngine {
7821
8044
  const triggers = this.eventTriggers.get(lifecycleEventName(run.workflow, kind));
7822
8045
  if (!triggers || !this.servesNamespace(run.namespace)) return out;
7823
8046
  let payload;
8047
+ const tenant = this.lifecycleBatchTenant(run)?.id;
7824
8048
  for (const [workflow, subscriptions] of triggers) {
7825
8049
  const batch = this.latest.get(workflow)?.eventBatch;
7826
8050
  if (!batch) continue;
7827
8051
  if (!batch.key && subscriptions.every((sub2) => !sub2.where)) {
7828
- out.set(workflow, accumulatorRunId(workflow));
8052
+ out.set(workflow, accumulatorRunId(workflow, void 0, tenant));
7829
8053
  continue;
7830
8054
  }
7831
8055
  try {
@@ -7833,7 +8057,7 @@ var WorkflowEngine = class _WorkflowEngine {
7833
8057
  const { accepted } = acceptingSubscription(subscriptions, payload);
7834
8058
  if (!accepted) continue;
7835
8059
  const input = accepted.input ? accepted.input(payload) : payload;
7836
- out.set(workflow, accumulatorRunId(workflow, batch.key ? String(batch.key(input)) : void 0));
8060
+ out.set(workflow, accumulatorRunId(workflow, batch.key ? String(batch.key(input)) : void 0, tenant));
7837
8061
  } catch {
7838
8062
  out.set(workflow, void 0);
7839
8063
  }
@@ -8012,7 +8236,9 @@ var WorkflowEngine = class _WorkflowEngine {
8012
8236
  */
8013
8237
  async triggeredRuns(source) {
8014
8238
  const run = typeof source === "string" ? await this.store.getRun(source) : source;
8015
- return run ? triggeredRunsOf(run) : [];
8239
+ if (!run) return [];
8240
+ const filter = this.restrictiveFilter();
8241
+ return filter && !tenantVisible(run, filter) ? [] : triggeredRunsOf(run);
8016
8242
  }
8017
8243
  /** The live path of {@link publishSettled}: right after this instance settled the run. */
8018
8244
  publishLifecycle(event) {
@@ -8145,7 +8371,18 @@ var WorkflowEngine = class _WorkflowEngine {
8145
8371
  }
8146
8372
  if (targets.length === 0 && owe.size === 0 && !resolved) return void 0;
8147
8373
  const runIdOf = /* @__PURE__ */ __name((sub2) => lifecycleRunId(run.id, kind, sub2), "runIdOf");
8148
- const { reached, failed } = targets.length > 0 ? await this.startSubscribers(name, lifecycleEventOf(run), runIdOf, new Set(targets), remote, runIdOf) : {
8374
+ const { reached, failed } = targets.length > 0 ? await this.startSubscribers(
8375
+ name,
8376
+ lifecycleEventOf(run),
8377
+ runIdOf,
8378
+ new Set(targets),
8379
+ remote,
8380
+ runIdOf,
8381
+ this.lifecycleBatchTenant(run),
8382
+ // The downstream run belongs to the settled run's customer, whoever publishes it (the
8383
+ // turn that settled it, or the background retry pass outside any request).
8384
+ inheritTenant(run)
8385
+ ) : {
8149
8386
  reached: [],
8150
8387
  failed: []
8151
8388
  };
@@ -8658,7 +8895,8 @@ var WorkflowEngine = class _WorkflowEngine {
8658
8895
  async start(workflow, input, runId, opts) {
8659
8896
  const name = workflowName(workflow);
8660
8897
  const pinned = opts?.version;
8661
- let registered = pinned === void 0 ? this.latest.get(name) : this.workflows.get(versionKey(name, pinned));
8898
+ const startOnly = pinned === void 0 ? this.startOnlyLatest.get(name) : this.startOnly.get(versionKey(name, pinned));
8899
+ let registered = pinned === void 0 ? this.latest.get(name) ?? startOnly : this.workflows.get(versionKey(name, pinned)) ?? startOnly;
8662
8900
  if (!registered && pinned === void 0) {
8663
8901
  const ancestor = await this.findRemoteAncestor(runId);
8664
8902
  if (ancestor) registered = this.synthesizeRemoteChild(name, ancestor.version, ancestor);
@@ -8687,14 +8925,7 @@ var WorkflowEngine = class _WorkflowEngine {
8687
8925
  }
8688
8926
  await registered.validateInput?.(input);
8689
8927
  const prior = await this.store.getRun(runId);
8690
- if (prior) {
8691
- return {
8692
- runId,
8693
- status: prior.status,
8694
- output: prior.output,
8695
- error: prior.error
8696
- };
8697
- }
8928
+ if (prior) return this.existingStartResult(prior);
8698
8929
  const quota = await resolveConcurrency(opts?.concurrency, registered.concurrency, input);
8699
8930
  if (quota) await assertConcurrency(this.store, name, quota);
8700
8931
  const now = /* @__PURE__ */ new Date();
@@ -8734,6 +8965,7 @@ var WorkflowEngine = class _WorkflowEngine {
8734
8965
  tags,
8735
8966
  searchAttributes: opts?.searchAttributes,
8736
8967
  priority: opts?.priority,
8968
+ ...this.startTenant(opts),
8737
8969
  createdAt: now,
8738
8970
  updatedAt: now
8739
8971
  };
@@ -8742,12 +8974,7 @@ var WorkflowEngine = class _WorkflowEngine {
8742
8974
  } catch (err) {
8743
8975
  const winner = await this.store.getRun(runId).catch(() => null);
8744
8976
  if (!winner) throw err;
8745
- return {
8746
- runId,
8747
- status: winner.status,
8748
- output: winner.output,
8749
- error: winner.error
8750
- };
8977
+ return this.existingStartResult(winner);
8751
8978
  }
8752
8979
  if (delayed) {
8753
8980
  this.emit({
@@ -8761,7 +8988,10 @@ var WorkflowEngine = class _WorkflowEngine {
8761
8988
  status: "suspended"
8762
8989
  };
8763
8990
  }
8764
- await this.dispatchRun(runId, run.priority, pendingStateKey(run.updatedAt));
8991
+ const runsLocally = this.customDispatcher === void 0 && !this.dispatchesOverTransport;
8992
+ if (!(runsLocally && registered === startOnly)) {
8993
+ await this.dispatchRun(runId, run.priority, pendingStateKey(run.updatedAt));
8994
+ }
8765
8995
  if (this.controlPlane && !this.queuesRunsOverTransport) {
8766
8996
  void this.controlPlane.publishControl({
8767
8997
  kind: "enqueued",
@@ -8774,13 +9004,125 @@ var WorkflowEngine = class _WorkflowEngine {
8774
9004
  status: "pending"
8775
9005
  };
8776
9006
  }
8777
- /** Read a run's current persisted state (or null if unknown). A thin pass-through to the store. */
9007
+ /**
9008
+ * The tenant columns a new run gets: an explicit `opts.tenantId` (`null` = none) wins, else the
9009
+ * context tenant when tenancy is on, else none (no keys at all, so a run row is unchanged when
9010
+ * tenancy is off).
9011
+ */
9012
+ startTenant(opts) {
9013
+ const tenant = opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
9014
+ id: opts.tenantId,
9015
+ kind: opts.tenantKind
9016
+ } : this.tenancy?.current();
9017
+ if (!tenant) return {};
9018
+ return tenant.kind !== void 0 ? {
9019
+ tenantId: tenant.id,
9020
+ tenantKind: tenant.kind
9021
+ } : {
9022
+ tenantId: tenant.id
9023
+ };
9024
+ }
9025
+ /**
9026
+ * The context tenant a run started NOW would be stamped with (tenancy on), else undefined. For code
9027
+ * that records a start to replay it later outside the request, e.g. a transactional outbox.
9028
+ */
9029
+ contextTenant() {
9030
+ return this.tenancy?.current();
9031
+ }
9032
+ /**
9033
+ * The tenant whose debounce/batch accumulator a named event published now goes into: the
9034
+ * publisher's tenant, or `null` (the shared accumulator, no tenant) for a tenantless, `system` or
9035
+ * `all` publisher. Undefined when tenancy is off (the accumulator starts as it always did).
9036
+ */
9037
+ publishBatchTenant() {
9038
+ if (!this.tenancy) return void 0;
9039
+ const filter = this.tenantFilter();
9040
+ if (filter.mode !== "tenant") return null;
9041
+ const current = this.tenancy.current();
9042
+ return current?.id === filter.tenantId ? current : {
9043
+ id: filter.tenantId
9044
+ };
9045
+ }
9046
+ /**
9047
+ * The tenant whose debounce/batch accumulator `run`'s lifecycle event goes into: the run's own
9048
+ * (its publisher), or `null` for a run with no tenant. Undefined when tenancy is off.
9049
+ */
9050
+ lifecycleBatchTenant(run) {
9051
+ if (!this.tenancy) return void 0;
9052
+ return rowTenant(run) ?? null;
9053
+ }
9054
+ /** The matching filter for an app-facing call made now: `system` (sees all) when tenancy is off. */
9055
+ tenantFilter() {
9056
+ return this.tenancy?.filter() ?? {
9057
+ mode: "system"
9058
+ };
9059
+ }
9060
+ /**
9061
+ * The run `runId` if the caller may see it under the tenancy matching rule, else null — an
9062
+ * invisible run reads exactly like a missing one (not found, never forbidden).
9063
+ */
9064
+ visibleRun(runId) {
9065
+ const filter = this.restrictiveFilter();
9066
+ if (!filter) return this.store.getRun(runId);
9067
+ return this.store.getRun(runId).then((run) => run && tenantVisible(run, filter) ? run : null);
9068
+ }
9069
+ /**
9070
+ * What `start` returns for an id that already has a run. A run the caller may not see (tenancy)
9071
+ * returns its id and status only: never its output or error.
9072
+ */
9073
+ existingStartResult(run) {
9074
+ const filter = this.restrictiveFilter();
9075
+ if (filter && !tenantVisible(run, filter)) return {
9076
+ runId: run.id,
9077
+ status: run.status
9078
+ };
9079
+ return {
9080
+ runId: run.id,
9081
+ status: run.status,
9082
+ output: run.output,
9083
+ error: run.error
9084
+ };
9085
+ }
9086
+ /** The caller's filter when it can hide rows (`tenant` / `tenantless`), else undefined. */
9087
+ restrictiveFilter() {
9088
+ const filter = this.tenantFilter();
9089
+ return filter.mode === "system" || filter.mode === "all" ? void 0 : filter;
9090
+ }
9091
+ /**
9092
+ * True when the caller may NOT act on `runId` (it is missing or invisible to it). Callers guard
9093
+ * with `this.restrictiveFilter() && (await this.hidden(runId))`, so nothing is awaited when the
9094
+ * caller sees everything.
9095
+ */
9096
+ async hidden(runId) {
9097
+ return await this.visibleRun(runId) === null;
9098
+ }
9099
+ /**
9100
+ * Narrow `query` to the runs the caller may see (the tenancy matching rule). Use it before an
9101
+ * app-facing `store.listRuns`; a no-op when tenancy is off or the caller is `system`/`all`.
9102
+ */
9103
+ scopeRunQuery(query) {
9104
+ return scopeTenantQuery(query, this.tenantFilter());
9105
+ }
9106
+ /**
9107
+ * Run `fn` with `run`'s tenant restored as the context tenant (so a step body, a downstream lib and
9108
+ * every dispatched task's context carrier see it), whatever path drove the turn: a request, a
9109
+ * timer, a signal, recovery or a worker. A run with no tenant, or tenancy off, runs `fn` as is.
9110
+ */
9111
+ inRunTenant(run, fn) {
9112
+ const tenant = this.tenancy ? rowTenant(run) : void 0;
9113
+ return tenant && this.tenancy ? this.tenancy.run(tenant, fn) : fn();
9114
+ }
9115
+ /**
9116
+ * Read a run's current persisted state (or null if unknown). With tenancy on, a run of another
9117
+ * tenant reads as null (see {@link WorkflowEngineDeps.tenancy}).
9118
+ */
8778
9119
  getRun(runId) {
8779
- return this.store.getRun(runId);
9120
+ return this.visibleRun(runId);
8780
9121
  }
8781
- /** A run's full checkpoint timeline, ordered by seq. A thin pass-through to the store (it is what
8782
- * the testing kit's `captureHistory` reads, next to {@link getRun}). */
8783
- listCheckpoints(runId) {
9122
+ /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9123
+ * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9124
+ async listCheckpoints(runId) {
9125
+ if (this.restrictiveFilter() && await this.hidden(runId)) return [];
8784
9126
  return this.store.listCheckpoints(runId);
8785
9127
  }
8786
9128
  /**
@@ -8792,6 +9134,13 @@ var WorkflowEngine = class _WorkflowEngine {
8792
9134
  * terminal too.
8793
9135
  */
8794
9136
  resume(runId) {
9137
+ if (this.restrictiveFilter()) {
9138
+ return this.hidden(runId).then((hidden) => {
9139
+ if (hidden) throw new Error(`run ${runId} not found`);
9140
+ this.noteWakeReason(runId, void 0);
9141
+ return this.resumeRun(runId, true);
9142
+ });
9143
+ }
8795
9144
  this.noteWakeReason(runId, void 0);
8796
9145
  return this.resumeRun(runId, true);
8797
9146
  }
@@ -9418,7 +9767,7 @@ var WorkflowEngine = class _WorkflowEngine {
9418
9767
  result: settled2,
9419
9768
  dispatch: false
9420
9769
  };
9421
- if (settled2 === void 0) this.logUnregisteredSkip(run);
9770
+ if (settled2 === void 0 && !this.isStartOnlyHere(run)) this.logUnregisteredSkip(run);
9422
9771
  return void 0;
9423
9772
  }
9424
9773
  const settled = await this.countRecovery(run);
@@ -9670,10 +10019,12 @@ var WorkflowEngine = class _WorkflowEngine {
9670
10019
  await this.store.removeBufferedEvent(candidate.id);
9671
10020
  continue;
9672
10021
  }
9673
- if (!eventMatches(candidate.payload, match)) continue;
10022
+ const { payload, tenantIds } = readBufferedEvent(candidate.payload);
10023
+ if (!bufferedEventReaches(tenantIds, run.tenantId)) continue;
10024
+ if (!eventMatches(payload, match)) continue;
9674
10025
  if (!await this.store.removeBufferedEvent(candidate.id)) continue;
9675
10026
  await this.store.removeSignalWaiter(waiter);
9676
- const settled = await this.deliverSignal(waiter, candidate.payload, true);
10027
+ const settled = await this.deliverSignal(waiter, payload, true);
9677
10028
  return settled ?? {
9678
10029
  runId: run.id,
9679
10030
  status: run.status
@@ -9699,6 +10050,7 @@ var WorkflowEngine = class _WorkflowEngine {
9699
10050
  const run = await this.store.getRun(runId);
9700
10051
  const settled = run ? await this.settleUnregistered(run, nowMs) : null;
9701
10052
  if (settled !== void 0) return settled;
10053
+ if (run && this.isStartOnlyHere(run)) return null;
9702
10054
  }
9703
10055
  throw err;
9704
10056
  });
@@ -9711,6 +10063,7 @@ var WorkflowEngine = class _WorkflowEngine {
9711
10063
  * the HTTP request on workflow execution.
9712
10064
  */
9713
10065
  async requeue(runId, _seen) {
10066
+ if (_seen === void 0 && this.restrictiveFilter() && await this.hidden(runId)) return null;
9714
10067
  const seen = _seen ?? /* @__PURE__ */ new Set();
9715
10068
  if (seen.has(runId)) return null;
9716
10069
  seen.add(runId);
@@ -9818,7 +10171,7 @@ var WorkflowEngine = class _WorkflowEngine {
9818
10171
  * run's current status (with the count re-dispatched), or null if the run is unknown.
9819
10172
  */
9820
10173
  async redispatchPending(runId) {
9821
- const run = await this.store.getRun(runId);
10174
+ const run = await this.visibleRun(runId);
9822
10175
  if (!run) return null;
9823
10176
  const pending = (await this.store.listCheckpoints(runId)).filter((cp) => cp.kind === "remote" && cp.status === "pending");
9824
10177
  let redispatched = 0;
@@ -9833,7 +10186,7 @@ var WorkflowEngine = class _WorkflowEngine {
9833
10186
  startedAt: reEnqueuedAt,
9834
10187
  finishedAt: reEnqueuedAt
9835
10188
  });
9836
- await this.dispatchRemoteTask({
10189
+ await this.inRunTenant(run, () => this.dispatchRemoteTask({
9837
10190
  runId,
9838
10191
  seq: cp.seq,
9839
10192
  name: cp.name,
@@ -9841,7 +10194,7 @@ var WorkflowEngine = class _WorkflowEngine {
9841
10194
  group: cp.workerGroup ?? sanitizeQueueToken(cp.name),
9842
10195
  input: cp.input,
9843
10196
  attempt: reAttempt
9844
- });
10197
+ }));
9845
10198
  redispatched += 1;
9846
10199
  }
9847
10200
  return {
@@ -9856,12 +10209,13 @@ var WorkflowEngine = class _WorkflowEngine {
9856
10209
  * the original stays inspectable. Returns the new run's id, or null if `runId` is unknown.
9857
10210
  */
9858
10211
  async retryWithInput(runId, input, newRunId) {
9859
- const run = await this.store.getRun(runId);
10212
+ const run = await this.visibleRun(runId);
9860
10213
  if (!run) return null;
9861
10214
  const id = newRunId ?? `${runId}~retry~${globalThis.crypto.randomUUID().slice(0, 8)}`;
9862
10215
  await this.start(run.workflow, input, id, {
9863
10216
  tags: run.tags,
9864
- namespace: run.namespace
10217
+ namespace: run.namespace,
10218
+ ...inheritTenant(run)
9865
10219
  });
9866
10220
  return {
9867
10221
  runId: id
@@ -9910,6 +10264,7 @@ var WorkflowEngine = class _WorkflowEngine {
9910
10264
  output: run.output,
9911
10265
  error: run.error
9912
10266
  }), "toResult");
10267
+ const filter = this.restrictiveFilter();
9913
10268
  return new Promise((resolve, reject) => {
9914
10269
  let done = false;
9915
10270
  let off = /* @__PURE__ */ __name(() => {
@@ -9940,6 +10295,10 @@ var WorkflowEngine = class _WorkflowEngine {
9940
10295
  const check = /* @__PURE__ */ __name(() => {
9941
10296
  if (done) return;
9942
10297
  void this.store.getRun(runId).then((run) => {
10298
+ if (run && filter && !tenantVisible(run, filter)) {
10299
+ fail(new Error(`run ${runId} not found`));
10300
+ return;
10301
+ }
9943
10302
  if (run && isSettled(run)) finish(run);
9944
10303
  }, fail);
9945
10304
  }, "check");
@@ -9988,6 +10347,7 @@ var WorkflowEngine = class _WorkflowEngine {
9988
10347
  if (error2 instanceof WorkflowNotRegistered) {
9989
10348
  const settled = await this.settleUnregistered(run, this.clock()).catch(() => void 0);
9990
10349
  if (settled) return settled;
10350
+ if (this.isStartOnlyHere(run)) return void 0;
9991
10351
  }
9992
10352
  console.error(`[nestjs-durable] could not resume run ${run.id} (${run.workflow}@${run.workflowVersion}); leaving it for another instance:`, error2);
9993
10353
  return void 0;
@@ -10017,7 +10377,7 @@ var WorkflowEngine = class _WorkflowEngine {
10017
10377
  if (error2 instanceof WorkflowNotRegistered) {
10018
10378
  const settled = await this.settleUnregistered(run, nowMs).catch(() => void 0);
10019
10379
  if (settled) results.push(settled);
10020
- if (settled !== void 0) continue;
10380
+ if (settled !== void 0 || this.isStartOnlyHere(run)) continue;
10021
10381
  }
10022
10382
  console.error(`[nestjs-durable] could not resume run ${run.id} (${run.workflow}@${run.workflowVersion}); leaving it for another instance:`, error2);
10023
10383
  } finally {
@@ -10056,17 +10416,23 @@ var WorkflowEngine = class _WorkflowEngine {
10056
10416
  */
10057
10417
  async publishEvent(name, payload, opts) {
10058
10418
  let touched = 0;
10419
+ const filter = this.restrictiveFilter();
10420
+ const reaches = /* @__PURE__ */ __name(async (runId) => {
10421
+ if (!filter) return true;
10422
+ const run = await this.store.getRun(runId);
10423
+ return run !== null && tenantVisible(run, filter);
10424
+ }, "reaches");
10059
10425
  const waiters = await this.store.listSignalWaiters(eventPrefix(name));
10060
10426
  for (const w of waiters) {
10061
- if (eventMatches(payload, eventMatchOf(w.token))) {
10062
- await this.signal(w.token, payload);
10427
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10428
+ await this.signalUnchecked(w.token, payload);
10063
10429
  touched += 1;
10064
10430
  }
10065
10431
  }
10066
10432
  const remote = await this.announcedRemoteSubscribers(name, null);
10067
10433
  if (this.eventTriggers.get(name)?.size || remote.length > 0) {
10068
10434
  const eventId = opts?.id ?? globalThis.crypto.randomUUID();
10069
- const { reached, failed } = await this.startSubscribers(name, payload, (workflow) => `evt:${eventId}:${workflow}`, void 0, remote);
10435
+ const { reached, failed } = await this.startSubscribers(name, payload, (workflow) => `evt:${eventId}:${workflow}`, void 0, remote, void 0, this.publishBatchTenant());
10070
10436
  touched += reached.length;
10071
10437
  for (const { workflow, error: error2 } of failed) {
10072
10438
  console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error2);
@@ -10076,12 +10442,18 @@ var WorkflowEngine = class _WorkflowEngine {
10076
10442
  const bufferedId = globalThis.crypto.randomUUID();
10077
10443
  await this.store.bufferEvent({
10078
10444
  name,
10079
- payload,
10445
+ payload: scopeBufferedEvent(payload, filter ? tenantIdsFor(filter) : void 0),
10080
10446
  id: bufferedId,
10081
10447
  publishedAt: this.clock()
10082
10448
  });
10083
10449
  const lateWaiters = await this.store.listSignalWaiters(eventPrefix(name));
10084
- const lateWaiter = lateWaiters.find((w) => eventMatches(payload, eventMatchOf(w.token)));
10450
+ let lateWaiter;
10451
+ for (const w of lateWaiters) {
10452
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10453
+ lateWaiter = w;
10454
+ break;
10455
+ }
10456
+ }
10085
10457
  if (!lateWaiter) return touched;
10086
10458
  if (!await this.store.removeBufferedEvent(bufferedId)) return touched;
10087
10459
  const waiter = await this.store.takeSignalWaiter(lateWaiter.token);
@@ -10388,7 +10760,23 @@ var WorkflowEngine = class _WorkflowEngine {
10388
10760
  * Either way, the destructive `take*` ops (on the waiter row, on the buffer) arbitrate: whichever
10389
10761
  * side actually removes the row is the one that delivers, so a signal is never delivered twice.
10390
10762
  */
10391
- async signal(token, payload, opts) {
10763
+ signal(token, payload, opts) {
10764
+ const filter = parseWebhookToken(token) ? void 0 : this.restrictiveFilter();
10765
+ if (!filter) return this.signalUnchecked(token, payload, opts);
10766
+ return this.signalTargetVisible(token, filter).then((visible) => visible ? this.signalUnchecked(token, payload, opts) : null);
10767
+ }
10768
+ /**
10769
+ * False when a run waits on `token` and `filter` may not see it (the tenancy matching rule). A
10770
+ * token nobody waits on yet is buffered as before (there is no run to check).
10771
+ */
10772
+ async signalTargetVisible(token, filter) {
10773
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
10774
+ if (!waiter) return true;
10775
+ const run = await this.store.getRun(waiter.runId);
10776
+ return !run || tenantVisible(run, filter);
10777
+ }
10778
+ /** {@link signal} without the tenancy check — the engine's own deliveries. */
10779
+ async signalUnchecked(token, payload, opts) {
10392
10780
  const id = opts?.id;
10393
10781
  if (id === void 0) return this.deliverOrBuffer(token, payload);
10394
10782
  if (!this.store.claimSignalId) {
@@ -10472,14 +10860,16 @@ var WorkflowEngine = class _WorkflowEngine {
10472
10860
  * null if no run is waiting on the task (e.g. a duplicate/late delivery) — a safe no-op.
10473
10861
  */
10474
10862
  async completeTask(runId, name, result) {
10475
- return this.signal(`task:${runId}:${name}`, {
10863
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
10864
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10476
10865
  ok: true,
10477
10866
  value: result
10478
10867
  });
10479
10868
  }
10480
10869
  /** Report that a `ctx.task` failed — the run resumes and throws a FatalError at the task. */
10481
10870
  async failTask(runId, name, error2) {
10482
- return this.signal(`task:${runId}:${name}`, {
10871
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
10872
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10483
10873
  ok: false,
10484
10874
  error: error2
10485
10875
  });
@@ -10518,7 +10908,7 @@ var WorkflowEngine = class _WorkflowEngine {
10518
10908
  if (cancelled) return;
10519
10909
  const childId = token.slice(CHILD_TOKEN_PREFIX.length);
10520
10910
  if (!await childCompletionNeedsBuffer(this.store, childId, completion)) return;
10521
- await this.signal(token, completion);
10911
+ await this.signalUnchecked(token, completion);
10522
10912
  return;
10523
10913
  } catch (err) {
10524
10914
  if (err instanceof NamespaceMismatch) return;
@@ -10567,7 +10957,12 @@ var WorkflowEngine = class _WorkflowEngine {
10567
10957
  * steps' compensations run in reverse (visible as `compensate:<step>` events), then it's marked
10568
10958
  * cancelled. Without it, cancellation is immediate (no undo).
10569
10959
  */
10570
- async cancel(runId, opts) {
10960
+ cancel(runId, opts) {
10961
+ if (!this.restrictiveFilter()) return this.cancelUnchecked(runId, opts);
10962
+ return this.hidden(runId).then((hidden) => hidden ? null : this.cancelUnchecked(runId, opts));
10963
+ }
10964
+ /** {@link cancel} without the tenancy check — the engine's own cascades and bulk paths. */
10965
+ async cancelUnchecked(runId, opts) {
10571
10966
  const run = await this.store.getRun(runId);
10572
10967
  if (!run) return null;
10573
10968
  if (TERMINAL_RUN_STATUSES.includes(run.status)) {
@@ -10649,10 +11044,10 @@ var WorkflowEngine = class _WorkflowEngine {
10649
11044
  * their terminal status — `cancel` is a no-op on them, never clobbering a completed/dead run).
10650
11045
  */
10651
11046
  async cancelWhere(filter, opts) {
10652
- const runs = await this.store.listRuns(filter);
11047
+ const runs = await this.store.listRuns(this.scopeRunQuery(filter));
10653
11048
  const results = [];
10654
11049
  for (const run of runs) {
10655
- const r = await this.cancel(run.id, opts);
11050
+ const r = await this.cancelUnchecked(run.id, opts);
10656
11051
  if (r) results.push(r);
10657
11052
  }
10658
11053
  return results;
@@ -10668,11 +11063,16 @@ var WorkflowEngine = class _WorkflowEngine {
10668
11063
  * its worker (its next checkpoint write fails). Returns the number of runs deleted (0 if absent).
10669
11064
  */
10670
11065
  async deleteRun(runId) {
11066
+ if (this.restrictiveFilter() && await this.hidden(runId)) return 0;
11067
+ return await this.deleteRunUnchecked(runId);
11068
+ }
11069
+ /** {@link deleteRun} without the tenancy check (its own subtree recursion). */
11070
+ async deleteRunUnchecked(runId) {
10671
11071
  const run = await this.store.getRun(runId);
10672
11072
  if (!run) return 0;
10673
11073
  let deleted = 0;
10674
- for (const childId of await this.getRunChildren(runId)) {
10675
- deleted += await this.deleteRun(childId);
11074
+ for (const childId of await this.runChildrenUnchecked(runId)) {
11075
+ deleted += await this.deleteRunUnchecked(childId);
10676
11076
  }
10677
11077
  await this.store.deleteRun(runId);
10678
11078
  return deleted + 1;
@@ -10701,6 +11101,7 @@ var WorkflowEngine = class _WorkflowEngine {
10701
11101
  if (!isNonEmptyRunScope(scope)) {
10702
11102
  throw new Error("purgeRuns: refusing an empty scope (it would delete every run) \u2014 pass at least one predicate, e.g. { namespace }");
10703
11103
  }
11104
+ const scoped = this.scopeRunQuery(scope);
10704
11105
  const batchSize = Math.max(1, opts?.batchSize ?? 500);
10705
11106
  const cancelLive = opts?.cancelLive ?? true;
10706
11107
  const withChildren = opts?.children ?? true;
@@ -10711,7 +11112,7 @@ var WorkflowEngine = class _WorkflowEngine {
10711
11112
  let previous = "";
10712
11113
  for (; ; ) {
10713
11114
  const batch = await this.store.listRuns({
10714
- ...scope,
11115
+ ...scoped,
10715
11116
  statuses,
10716
11117
  limit: batchSize
10717
11118
  });
@@ -10732,7 +11133,7 @@ var WorkflowEngine = class _WorkflowEngine {
10732
11133
  if (status === void 0) continue;
10733
11134
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
10734
11135
  if (!cancelLive) continue;
10735
- await this.cancel(id).catch(() => void 0);
11136
+ await this.cancelUnchecked(id).catch(() => void 0);
10736
11137
  }
10737
11138
  doomed.push(id);
10738
11139
  }
@@ -10793,10 +11194,10 @@ var WorkflowEngine = class _WorkflowEngine {
10793
11194
  * explicitly cancelled one's does, or the children are orphans nobody is holding a reference to.
10794
11195
  */
10795
11196
  async cancelChildren(parentRunId, opts) {
10796
- for (const id of await this.getRunChildren(parentRunId)) {
11197
+ for (const id of await this.runChildrenUnchecked(parentRunId)) {
10797
11198
  const child = await this.store.getRun(id).catch(() => null);
10798
11199
  if (child?.tags?.includes(`${PARENT_CLOSE_TAG_PREFIX}abandon`)) continue;
10799
- await this.cancel(id, opts).catch(() => void 0);
11200
+ await this.cancelUnchecked(id, opts).catch(() => void 0);
10800
11201
  }
10801
11202
  }
10802
11203
  /**
@@ -10814,7 +11215,7 @@ var WorkflowEngine = class _WorkflowEngine {
10814
11215
  if (event.type === "run.suspended") return;
10815
11216
  for (const [childId, policy] of intents) {
10816
11217
  if (policy === "abandon") continue;
10817
- queueMicrotask(() => void this.cancel(childId, {
11218
+ queueMicrotask(() => void this.cancelUnchecked(childId, {
10818
11219
  compensate: policy === "cancel"
10819
11220
  }).catch(() => void 0));
10820
11221
  }
@@ -10838,7 +11239,13 @@ var WorkflowEngine = class _WorkflowEngine {
10838
11239
  parentRunId
10839
11240
  ])).filter((w) => w.token.startsWith("child:") && !isAnyMember(w)).map((w) => w.token.slice("child:".length));
10840
11241
  }
11242
+ /** The child runs of `parentRunId`; empty for a parent the caller may not see. */
10841
11243
  async getRunChildren(parentRunId) {
11244
+ if (this.restrictiveFilter() && await this.hidden(parentRunId)) return [];
11245
+ return this.runChildrenUnchecked(parentRunId);
11246
+ }
11247
+ /** {@link getRunChildren} without the tenancy check (the engine's own subtree walks). */
11248
+ async runChildrenUnchecked(parentRunId) {
10842
11249
  const childIds = new Set(await this.awaitedChildIds(parentRunId));
10843
11250
  const prefixes = CHILD_EDGE_PREFIXES;
10844
11251
  const childCheckpoints = this.store.listCheckpointsByNamePrefix ? await this.store.listCheckpointsByNamePrefix(parentRunId, prefixes) : (await this.store.listCheckpoints(parentRunId)).filter((cp) => prefixes.some((p) => cp.name.startsWith(p)));
@@ -11199,7 +11606,7 @@ var WorkflowEngine = class _WorkflowEngine {
11199
11606
  const served = /* @__PURE__ */ new Set();
11200
11607
  this.turnServedWakes.set(run.id, served);
11201
11608
  if (registered?.remote) await this.noteServedWakes(run.id);
11202
- const result = registered?.remote ? await this.runRemoteExecution(run, registered) : await this.runExecution(run, fn, registered);
11609
+ const result = await this.inRunTenant(run, () => registered?.remote ? this.runRemoteExecution(run, registered) : this.runExecution(run, fn, registered));
11203
11610
  if (registered?.singleton && (result.status === "completed" || result.status === "failed" || result.status === "cancelled" || result.status === "dead")) {
11204
11611
  void this.singletons.wakeNext(run).catch(() => void 0);
11205
11612
  }
@@ -11515,7 +11922,8 @@ var WorkflowEngine = class _WorkflowEngine {
11515
11922
  error: error2
11516
11923
  });
11517
11924
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11518
- namespace: run.namespace
11925
+ namespace: run.namespace,
11926
+ ...inheritTenant(run)
11519
11927
  });
11520
11928
  return {
11521
11929
  kind: "suspended"
@@ -11562,7 +11970,8 @@ var WorkflowEngine = class _WorkflowEngine {
11562
11970
  if (!handlerRun) {
11563
11971
  const handler = handoff.input;
11564
11972
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11565
- namespace: run.namespace
11973
+ namespace: run.namespace,
11974
+ ...inheritTenant(run)
11566
11975
  });
11567
11976
  }
11568
11977
  return {
@@ -12347,7 +12756,8 @@ ${run.workflowVersion}`;
12347
12756
  const existingChild = await this.store.getRun(childId);
12348
12757
  if (!existingChild) {
12349
12758
  this.startChildDeferred(cmd.workflow, cmd.input, childId, {
12350
- namespace: run.namespace
12759
+ namespace: run.namespace,
12760
+ ...inheritTenant(run)
12351
12761
  });
12352
12762
  } else {
12353
12763
  this.redeliverFinishedChild(childId, existingChild);
@@ -12466,7 +12876,7 @@ ${run.workflowVersion}`;
12466
12876
  this.awaitedRemoteSteps.set(run.id, awaitedSteps);
12467
12877
  const awaitedFans = [];
12468
12878
  this.awaitedStepFans.set(run.id, awaitedFans);
12469
- const ctx = warm ? void 0 : createWorkflowCtx(this.ctxHostFor(replay, run.namespace, cont), run.id, compensations, run.workflow, registered?.searchAttributesSchema);
12879
+ const ctx = warm ? void 0 : createWorkflowCtx(this.ctxHostFor(replay, run.namespace, cont, inheritTenant(run)), run.id, compensations, run.workflow, registered?.searchAttributesSchema);
12470
12880
  try {
12471
12881
  const handoff = liveHandoff(run.id, snapshot);
12472
12882
  if (handoff && !this.cancelRequested.has(run.id)) {
@@ -12524,7 +12934,7 @@ ${run.workflowVersion}`;
12524
12934
  value: void 0
12525
12935
  });
12526
12936
  const nextId = nextContinuationId(run.id);
12527
- queueMicrotask(() => void this.start(run.workflow, err.input, nextId).catch(() => void 0));
12937
+ queueMicrotask(() => void this.start(run.workflow, err.input, nextId, inheritTenant(run)).catch(() => void 0));
12528
12938
  return {
12529
12939
  runId: run.id,
12530
12940
  status: "completed"
@@ -12797,7 +13207,7 @@ ${run.workflowVersion}`;
12797
13207
  /** The seam handed to {@link createWorkflowCtx}: the authoring API reaches durability + lifecycle
12798
13208
  * (checkpointing, dispatch, child start) through this, so the ctx primitives live in their own
12799
13209
  * module and the engine stays the orchestrator. */
12800
- ctxHostFor(replay, parentNamespace, sticky) {
13210
+ ctxHostFor(replay, parentNamespace, sticky, parentTenant) {
12801
13211
  return {
12802
13212
  store: this.store,
12803
13213
  replay,
@@ -12844,6 +13254,8 @@ ${run.workflowVersion}`;
12844
13254
  this.startChildDeferred(workflow, input, id, {
12845
13255
  priority,
12846
13256
  namespace: parentNamespace,
13257
+ // The child belongs to the parent's customer, whichever instance or context drives it.
13258
+ ...parentTenant,
12847
13259
  // Absent unless the body pinned one (`ctx.child(ref, input, { version })`) — an omitted
12848
13260
  // pin must stay omitted, so the child keeps resolving `latest` exactly as before.
12849
13261
  version,
@@ -12867,7 +13279,7 @@ ${run.workflowVersion}`;
12867
13279
  // idempotent on a terminal/cancelled run (returns its existing status without side effects), so
12868
13280
  // no extra guard is needed here for the failFast replay case (re-issuing the same cancel calls).
12869
13281
  cancelChild: /* @__PURE__ */ __name((childId) => {
12870
- queueMicrotask(() => void this.cancel(childId).catch(() => void 0));
13282
+ queueMicrotask(() => void this.cancelUnchecked(childId).catch(() => void 0));
12871
13283
  }, "cancelChild"),
12872
13284
  // Shallow-merge into the run's searchAttributes (the ctx primitive makes this exactly-once).
12873
13285
  upsertSearchAttributes: /* @__PURE__ */ __name(async (runId, attrs) => {
@@ -12894,7 +13306,7 @@ ${run.workflowVersion}`;
12894
13306
  console.warn(`[nestjs-durable] waking entity "${name}" key "${key}" failed (its op stays buffered for the next wake):`, err);
12895
13307
  }));
12896
13308
  }, "kickEntity"),
12897
- interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body), "interceptStep")
13309
+ interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body, parentTenant), "interceptStep")
12898
13310
  };
12899
13311
  }
12900
13312
  /**
@@ -12903,10 +13315,11 @@ ${run.workflowVersion}`;
12903
13315
  * paused at a breakpoint.
12904
13316
  */
12905
13317
  async continue(runId) {
13318
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
12906
13319
  const checkpoints = await this.store.listCheckpoints(runId);
12907
13320
  const bp = checkpoints.find(isBreakpoint);
12908
13321
  if (!bp) return null;
12909
- return this.signal(breakpointToken(runId, bp.seq), void 0);
13322
+ return this.signalUnchecked(breakpointToken(runId, bp.seq), void 0);
12910
13323
  }
12911
13324
  /**
12912
13325
  * Read the latest value a run published for `key` via {@link WorkflowCtx.setEvent} — a
@@ -12914,6 +13327,7 @@ ${run.workflowVersion}`;
12914
13327
  * never published that key. The suspend-model counterpart of a Temporal query.
12915
13328
  */
12916
13329
  async getEvent(runId, key) {
13330
+ if (this.restrictiveFilter() && await this.hidden(runId)) return void 0;
12917
13331
  const name = `event:${key}`;
12918
13332
  if (this.store.getLatestCheckpointByName) {
12919
13333
  const latest2 = await this.store.getLatestCheckpointByName(runId, name);
@@ -12938,7 +13352,7 @@ ${run.workflowVersion}`;
12938
13352
  * if nothing was waiting — a too-early or duplicate update).
12939
13353
  */
12940
13354
  async update(runId, name, arg) {
12941
- const run = await this.store.getRun(runId);
13355
+ const run = await this.visibleRun(runId);
12942
13356
  if (!run) return {
12943
13357
  accepted: false,
12944
13358
  reason: `run ${runId} not found`
@@ -12958,7 +13372,7 @@ ${run.workflowVersion}`;
12958
13372
  };
12959
13373
  }
12960
13374
  }
12961
- const result = await this.signal(`update:${runId}:${name}`, arg);
13375
+ const result = await this.signalUnchecked(`update:${runId}:${name}`, arg);
12962
13376
  return {
12963
13377
  accepted: true,
12964
13378
  run: result
@@ -16143,6 +16557,9 @@ var InMemoryStateStore = class {
16143
16557
  if (query.origins) {
16144
16558
  runs = runs.filter((r) => query.origins?.includes(r.origin ?? null));
16145
16559
  }
16560
+ if (query.tenantId !== void 0 || query.tenantIds !== void 0) {
16561
+ runs = runs.filter((r) => matchesTenantPredicates(r, query));
16562
+ }
16146
16563
  if (query.attributes?.length) {
16147
16564
  let candidates = null;
16148
16565
  for (const f of query.attributes) {
@@ -16216,7 +16633,7 @@ var InMemoryStateStore = class {
16216
16633
  async listSchedules(query) {
16217
16634
  const rows = [
16218
16635
  ...this.schedules.values()
16219
- ].filter((s) => query.namespace === void 0 || s.namespace === query.namespace).filter((s) => query.workflow === void 0 || s.workflow === query.workflow).filter((s) => query.tag === void 0 || (s.tags ?? []).includes(query.tag)).filter((s) => query.paused === void 0 || s.paused === query.paused).filter((s) => query.dueBy === void 0 || !s.paused && s.nextFireAt !== null && s.nextFireAt <= query.dueBy).sort((a, b) => (a.nextFireAt ?? Number.POSITIVE_INFINITY) - (b.nextFireAt ?? Number.POSITIVE_INFINITY) || a.id.localeCompare(b.id));
16636
+ ].filter((s) => query.namespace === void 0 || s.namespace === query.namespace).filter((s) => query.workflow === void 0 || s.workflow === query.workflow).filter((s) => query.tag === void 0 || (s.tags ?? []).includes(query.tag)).filter((s) => query.paused === void 0 || s.paused === query.paused).filter((s) => matchesTenantPredicates(s, query)).filter((s) => query.dueBy === void 0 || !s.paused && s.nextFireAt !== null && s.nextFireAt <= query.dueBy).sort((a, b) => (a.nextFireAt ?? Number.POSITIVE_INFINITY) - (b.nextFireAt ?? Number.POSITIVE_INFINITY) || a.id.localeCompare(b.id));
16220
16637
  const offset = query.offset ?? 0;
16221
16638
  return rows.slice(offset, query.limit != null ? offset + query.limit : void 0).map((s) => structuredClone(s));
16222
16639
  }
@@ -16587,6 +17004,7 @@ export {
16587
17004
  axisIsRunColumn,
16588
17005
  bindWorkflowClass,
16589
17006
  breakpointToken,
17007
+ bufferedEventReaches,
16590
17008
  buildWorkflowDirectory,
16591
17009
  canRoute,
16592
17010
  capableWorkers,
@@ -16634,6 +17052,7 @@ export {
16634
17052
  hmacTenantVerifier,
16635
17053
  indexWaitersByRun,
16636
17054
  info,
17055
+ inheritTenant,
16637
17056
  isAnyCheckpoint,
16638
17057
  isAnyMember,
16639
17058
  isEngineMintedTag,
@@ -16660,6 +17079,7 @@ export {
16660
17079
  log,
16661
17080
  markRemoteEvent,
16662
17081
  matchesAttributes,
17082
+ matchesTenantPredicates,
16663
17083
  mergeRunFacetRows,
16664
17084
  mergeRunValueFacetRows,
16665
17085
  missingCapabilities,
@@ -16684,6 +17104,7 @@ export {
16684
17104
  prevCronFireMs,
16685
17105
  prevRRuleFireMs,
16686
17106
  queryCheckpointsOf,
17107
+ readBufferedEvent,
16687
17108
  readRunsByIds,
16688
17109
  readSearchAttributes,
16689
17110
  requiredCapabilities,
@@ -16695,6 +17116,7 @@ export {
16695
17116
  retentionKeeps,
16696
17117
  retiredHandoffName,
16697
17118
  routeFor,
17119
+ rowTenant,
16698
17120
  runCompletedEvent,
16699
17121
  runDetailEtag,
16700
17122
  runDurableExecution,
@@ -16712,6 +17134,8 @@ export {
16712
17134
  sanitizeQueueToken,
16713
17135
  scheduleRunIdAt,
16714
17136
  scheduledRunId,
17137
+ scopeBufferedEvent,
17138
+ scopeTenantQuery,
16715
17139
  settleResultsWithPlainCalls,
16716
17140
  signTenantToken,
16717
17141
  singletonAdmissionDenialPatch,
@@ -16728,6 +17152,8 @@ export {
16728
17152
  summarizeRunFromStore,
16729
17153
  summarizeTimeline,
16730
17154
  tenantGroup,
17155
+ tenantIdsFor,
17156
+ tenantVisible,
16731
17157
  toEventSubscription,
16732
17158
  traceIdOfTraceparent,
16733
17159
  triggerFailedSubscribersOf,