@dudousxd/nestjs-durable-core 0.89.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;
@@ -6645,6 +6815,7 @@ var WorkflowEngine = class _WorkflowEngine {
6645
6815
  this.traceparent = deps.traceparent;
6646
6816
  this.context = deps.context;
6647
6817
  this.rehydrate = deps.rehydrate ?? ((_carrier, fn) => fn());
6818
+ this.tenancy = deps.tenancy;
6648
6819
  this.compensationRetries = Math.max(1, deps.compensationRetries ?? 1);
6649
6820
  this.trackStepStart = deps.trackStepStart ?? true;
6650
6821
  this.localWork = new BoundedRunner(LOCAL_RUN_CONCURRENCY);
@@ -6674,7 +6845,9 @@ var WorkflowEngine = class _WorkflowEngine {
6674
6845
  this.schedules = new ScheduleClient(this.store, {
6675
6846
  start: /* @__PURE__ */ __name((workflow, input, runId, opts) => this.start(workflow, input, runId, opts), "start"),
6676
6847
  getRun: /* @__PURE__ */ __name((runId) => this.store.getRun(runId), "getRun"),
6677
- 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")
6678
6851
  }, {
6679
6852
  namespace: this.namespace,
6680
6853
  clock: this.clock
@@ -6778,7 +6951,18 @@ var WorkflowEngine = class _WorkflowEngine {
6778
6951
  }
6779
6952
  }
6780
6953
  });
6781
- 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
+ });
6782
6966
  this.entities = new Entities(this, {
6783
6967
  bufferSignal: /* @__PURE__ */ __name((token, payload) => this.store.bufferSignal(token, payload), "bufferSignal"),
6784
6968
  wakeWaiter: /* @__PURE__ */ __name((token, payload) => this.wakeSignalWaiter(token, payload), "wakeWaiter"),
@@ -7254,15 +7438,19 @@ var WorkflowEngine = class _WorkflowEngine {
7254
7438
  * time from {@link context} — the SAME reader stamped on dispatched remote tasks — so a local step
7255
7439
  * sees the live tenant / user / trace ids ambiently (via the {@link rehydrate} bridge). Default
7256
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.
7257
7445
  */
7258
- interceptStep(invocation, body) {
7446
+ interceptStep(invocation, body, tenant) {
7259
7447
  const carrier = this.context?.();
7260
7448
  const run = /* @__PURE__ */ __name(() => {
7261
7449
  if (this.interceptors.length === 0) return body();
7262
7450
  const chain = this.interceptors.reduceRight((next, interceptor) => () => interceptor(invocation, next), body);
7263
7451
  return chain();
7264
7452
  }, "run");
7265
- return this.rehydrate(carrier, run);
7453
+ return this.rehydrate(carrier, () => tenant ? this.inRunTenant(tenant, run) : run());
7266
7454
  }
7267
7455
  /**
7268
7456
  * Be notified when a run is cancelled — on ANY instance, via the transport control plane. A
@@ -7453,9 +7641,12 @@ var WorkflowEngine = class _WorkflowEngine {
7453
7641
  * an announcement carries no `where` or `input`. `routeIdOf` names the event for a subscriber's
7454
7642
  * debounce/batch accumulator, which counts an id once. Returns the subscribers reached, with the
7455
7643
  * run each started (none when the payload went into its debounce/batch accumulator), and the ones
7456
- * 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).
7457
7648
  */
7458
- async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf) {
7649
+ async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf, batchTenant, runTenant) {
7459
7650
  const reached = [];
7460
7651
  const failed = [];
7461
7652
  for (const [workflow, subscriptions] of this.eventTriggers.get(name) ?? []) {
@@ -7472,13 +7663,13 @@ var WorkflowEngine = class _WorkflowEngine {
7472
7663
  const input = accepted.input ? accepted.input(payload) : payload;
7473
7664
  const batch = this.latest.get(workflow)?.eventBatch;
7474
7665
  if (batch) {
7475
- await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow));
7666
+ await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow), batchTenant);
7476
7667
  reached.push({
7477
7668
  workflow
7478
7669
  });
7479
7670
  } else {
7480
7671
  const runId = runIdOf(workflow);
7481
- await this.start(workflow, input, runId);
7672
+ await this.start(workflow, input, runId, runTenant);
7482
7673
  reached.push({
7483
7674
  workflow,
7484
7675
  runId
@@ -7496,7 +7687,7 @@ var WorkflowEngine = class _WorkflowEngine {
7496
7687
  if (local?.has(workflow) || only && !only.has(workflow)) continue;
7497
7688
  try {
7498
7689
  const runId = runIdOf(workflow);
7499
- await this.start(workflow, payload, runId);
7690
+ await this.start(workflow, payload, runId, runTenant);
7500
7691
  reached.push({
7501
7692
  workflow,
7502
7693
  runId
@@ -7853,11 +8044,12 @@ var WorkflowEngine = class _WorkflowEngine {
7853
8044
  const triggers = this.eventTriggers.get(lifecycleEventName(run.workflow, kind));
7854
8045
  if (!triggers || !this.servesNamespace(run.namespace)) return out;
7855
8046
  let payload;
8047
+ const tenant = this.lifecycleBatchTenant(run)?.id;
7856
8048
  for (const [workflow, subscriptions] of triggers) {
7857
8049
  const batch = this.latest.get(workflow)?.eventBatch;
7858
8050
  if (!batch) continue;
7859
8051
  if (!batch.key && subscriptions.every((sub2) => !sub2.where)) {
7860
- out.set(workflow, accumulatorRunId(workflow));
8052
+ out.set(workflow, accumulatorRunId(workflow, void 0, tenant));
7861
8053
  continue;
7862
8054
  }
7863
8055
  try {
@@ -7865,7 +8057,7 @@ var WorkflowEngine = class _WorkflowEngine {
7865
8057
  const { accepted } = acceptingSubscription(subscriptions, payload);
7866
8058
  if (!accepted) continue;
7867
8059
  const input = accepted.input ? accepted.input(payload) : payload;
7868
- 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));
7869
8061
  } catch {
7870
8062
  out.set(workflow, void 0);
7871
8063
  }
@@ -8044,7 +8236,9 @@ var WorkflowEngine = class _WorkflowEngine {
8044
8236
  */
8045
8237
  async triggeredRuns(source) {
8046
8238
  const run = typeof source === "string" ? await this.store.getRun(source) : source;
8047
- return run ? triggeredRunsOf(run) : [];
8239
+ if (!run) return [];
8240
+ const filter = this.restrictiveFilter();
8241
+ return filter && !tenantVisible(run, filter) ? [] : triggeredRunsOf(run);
8048
8242
  }
8049
8243
  /** The live path of {@link publishSettled}: right after this instance settled the run. */
8050
8244
  publishLifecycle(event) {
@@ -8177,7 +8371,18 @@ var WorkflowEngine = class _WorkflowEngine {
8177
8371
  }
8178
8372
  if (targets.length === 0 && owe.size === 0 && !resolved) return void 0;
8179
8373
  const runIdOf = /* @__PURE__ */ __name((sub2) => lifecycleRunId(run.id, kind, sub2), "runIdOf");
8180
- 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
+ ) : {
8181
8386
  reached: [],
8182
8387
  failed: []
8183
8388
  };
@@ -8720,14 +8925,7 @@ var WorkflowEngine = class _WorkflowEngine {
8720
8925
  }
8721
8926
  await registered.validateInput?.(input);
8722
8927
  const prior = await this.store.getRun(runId);
8723
- if (prior) {
8724
- return {
8725
- runId,
8726
- status: prior.status,
8727
- output: prior.output,
8728
- error: prior.error
8729
- };
8730
- }
8928
+ if (prior) return this.existingStartResult(prior);
8731
8929
  const quota = await resolveConcurrency(opts?.concurrency, registered.concurrency, input);
8732
8930
  if (quota) await assertConcurrency(this.store, name, quota);
8733
8931
  const now = /* @__PURE__ */ new Date();
@@ -8767,6 +8965,7 @@ var WorkflowEngine = class _WorkflowEngine {
8767
8965
  tags,
8768
8966
  searchAttributes: opts?.searchAttributes,
8769
8967
  priority: opts?.priority,
8968
+ ...this.startTenant(opts),
8770
8969
  createdAt: now,
8771
8970
  updatedAt: now
8772
8971
  };
@@ -8775,12 +8974,7 @@ var WorkflowEngine = class _WorkflowEngine {
8775
8974
  } catch (err) {
8776
8975
  const winner = await this.store.getRun(runId).catch(() => null);
8777
8976
  if (!winner) throw err;
8778
- return {
8779
- runId,
8780
- status: winner.status,
8781
- output: winner.output,
8782
- error: winner.error
8783
- };
8977
+ return this.existingStartResult(winner);
8784
8978
  }
8785
8979
  if (delayed) {
8786
8980
  this.emit({
@@ -8810,13 +9004,125 @@ var WorkflowEngine = class _WorkflowEngine {
8810
9004
  status: "pending"
8811
9005
  };
8812
9006
  }
8813
- /** 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
+ */
8814
9119
  getRun(runId) {
8815
- return this.store.getRun(runId);
9120
+ return this.visibleRun(runId);
8816
9121
  }
8817
- /** A run's full checkpoint timeline, ordered by seq. A thin pass-through to the store (it is what
8818
- * the testing kit's `captureHistory` reads, next to {@link getRun}). */
8819
- 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 [];
8820
9126
  return this.store.listCheckpoints(runId);
8821
9127
  }
8822
9128
  /**
@@ -8828,6 +9134,13 @@ var WorkflowEngine = class _WorkflowEngine {
8828
9134
  * terminal too.
8829
9135
  */
8830
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
+ }
8831
9144
  this.noteWakeReason(runId, void 0);
8832
9145
  return this.resumeRun(runId, true);
8833
9146
  }
@@ -9706,10 +10019,12 @@ var WorkflowEngine = class _WorkflowEngine {
9706
10019
  await this.store.removeBufferedEvent(candidate.id);
9707
10020
  continue;
9708
10021
  }
9709
- 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;
9710
10025
  if (!await this.store.removeBufferedEvent(candidate.id)) continue;
9711
10026
  await this.store.removeSignalWaiter(waiter);
9712
- const settled = await this.deliverSignal(waiter, candidate.payload, true);
10027
+ const settled = await this.deliverSignal(waiter, payload, true);
9713
10028
  return settled ?? {
9714
10029
  runId: run.id,
9715
10030
  status: run.status
@@ -9748,6 +10063,7 @@ var WorkflowEngine = class _WorkflowEngine {
9748
10063
  * the HTTP request on workflow execution.
9749
10064
  */
9750
10065
  async requeue(runId, _seen) {
10066
+ if (_seen === void 0 && this.restrictiveFilter() && await this.hidden(runId)) return null;
9751
10067
  const seen = _seen ?? /* @__PURE__ */ new Set();
9752
10068
  if (seen.has(runId)) return null;
9753
10069
  seen.add(runId);
@@ -9855,7 +10171,7 @@ var WorkflowEngine = class _WorkflowEngine {
9855
10171
  * run's current status (with the count re-dispatched), or null if the run is unknown.
9856
10172
  */
9857
10173
  async redispatchPending(runId) {
9858
- const run = await this.store.getRun(runId);
10174
+ const run = await this.visibleRun(runId);
9859
10175
  if (!run) return null;
9860
10176
  const pending = (await this.store.listCheckpoints(runId)).filter((cp) => cp.kind === "remote" && cp.status === "pending");
9861
10177
  let redispatched = 0;
@@ -9870,7 +10186,7 @@ var WorkflowEngine = class _WorkflowEngine {
9870
10186
  startedAt: reEnqueuedAt,
9871
10187
  finishedAt: reEnqueuedAt
9872
10188
  });
9873
- await this.dispatchRemoteTask({
10189
+ await this.inRunTenant(run, () => this.dispatchRemoteTask({
9874
10190
  runId,
9875
10191
  seq: cp.seq,
9876
10192
  name: cp.name,
@@ -9878,7 +10194,7 @@ var WorkflowEngine = class _WorkflowEngine {
9878
10194
  group: cp.workerGroup ?? sanitizeQueueToken(cp.name),
9879
10195
  input: cp.input,
9880
10196
  attempt: reAttempt
9881
- });
10197
+ }));
9882
10198
  redispatched += 1;
9883
10199
  }
9884
10200
  return {
@@ -9893,12 +10209,13 @@ var WorkflowEngine = class _WorkflowEngine {
9893
10209
  * the original stays inspectable. Returns the new run's id, or null if `runId` is unknown.
9894
10210
  */
9895
10211
  async retryWithInput(runId, input, newRunId) {
9896
- const run = await this.store.getRun(runId);
10212
+ const run = await this.visibleRun(runId);
9897
10213
  if (!run) return null;
9898
10214
  const id = newRunId ?? `${runId}~retry~${globalThis.crypto.randomUUID().slice(0, 8)}`;
9899
10215
  await this.start(run.workflow, input, id, {
9900
10216
  tags: run.tags,
9901
- namespace: run.namespace
10217
+ namespace: run.namespace,
10218
+ ...inheritTenant(run)
9902
10219
  });
9903
10220
  return {
9904
10221
  runId: id
@@ -9947,6 +10264,7 @@ var WorkflowEngine = class _WorkflowEngine {
9947
10264
  output: run.output,
9948
10265
  error: run.error
9949
10266
  }), "toResult");
10267
+ const filter = this.restrictiveFilter();
9950
10268
  return new Promise((resolve, reject) => {
9951
10269
  let done = false;
9952
10270
  let off = /* @__PURE__ */ __name(() => {
@@ -9977,6 +10295,10 @@ var WorkflowEngine = class _WorkflowEngine {
9977
10295
  const check = /* @__PURE__ */ __name(() => {
9978
10296
  if (done) return;
9979
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
+ }
9980
10302
  if (run && isSettled(run)) finish(run);
9981
10303
  }, fail);
9982
10304
  }, "check");
@@ -10094,17 +10416,23 @@ var WorkflowEngine = class _WorkflowEngine {
10094
10416
  */
10095
10417
  async publishEvent(name, payload, opts) {
10096
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");
10097
10425
  const waiters = await this.store.listSignalWaiters(eventPrefix(name));
10098
10426
  for (const w of waiters) {
10099
- if (eventMatches(payload, eventMatchOf(w.token))) {
10100
- await this.signal(w.token, payload);
10427
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10428
+ await this.signalUnchecked(w.token, payload);
10101
10429
  touched += 1;
10102
10430
  }
10103
10431
  }
10104
10432
  const remote = await this.announcedRemoteSubscribers(name, null);
10105
10433
  if (this.eventTriggers.get(name)?.size || remote.length > 0) {
10106
10434
  const eventId = opts?.id ?? globalThis.crypto.randomUUID();
10107
- 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());
10108
10436
  touched += reached.length;
10109
10437
  for (const { workflow, error: error2 } of failed) {
10110
10438
  console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error2);
@@ -10114,12 +10442,18 @@ var WorkflowEngine = class _WorkflowEngine {
10114
10442
  const bufferedId = globalThis.crypto.randomUUID();
10115
10443
  await this.store.bufferEvent({
10116
10444
  name,
10117
- payload,
10445
+ payload: scopeBufferedEvent(payload, filter ? tenantIdsFor(filter) : void 0),
10118
10446
  id: bufferedId,
10119
10447
  publishedAt: this.clock()
10120
10448
  });
10121
10449
  const lateWaiters = await this.store.listSignalWaiters(eventPrefix(name));
10122
- 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
+ }
10123
10457
  if (!lateWaiter) return touched;
10124
10458
  if (!await this.store.removeBufferedEvent(bufferedId)) return touched;
10125
10459
  const waiter = await this.store.takeSignalWaiter(lateWaiter.token);
@@ -10426,7 +10760,23 @@ var WorkflowEngine = class _WorkflowEngine {
10426
10760
  * Either way, the destructive `take*` ops (on the waiter row, on the buffer) arbitrate: whichever
10427
10761
  * side actually removes the row is the one that delivers, so a signal is never delivered twice.
10428
10762
  */
10429
- 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) {
10430
10780
  const id = opts?.id;
10431
10781
  if (id === void 0) return this.deliverOrBuffer(token, payload);
10432
10782
  if (!this.store.claimSignalId) {
@@ -10510,14 +10860,16 @@ var WorkflowEngine = class _WorkflowEngine {
10510
10860
  * null if no run is waiting on the task (e.g. a duplicate/late delivery) — a safe no-op.
10511
10861
  */
10512
10862
  async completeTask(runId, name, result) {
10513
- return this.signal(`task:${runId}:${name}`, {
10863
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
10864
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10514
10865
  ok: true,
10515
10866
  value: result
10516
10867
  });
10517
10868
  }
10518
10869
  /** Report that a `ctx.task` failed — the run resumes and throws a FatalError at the task. */
10519
10870
  async failTask(runId, name, error2) {
10520
- return this.signal(`task:${runId}:${name}`, {
10871
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
10872
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10521
10873
  ok: false,
10522
10874
  error: error2
10523
10875
  });
@@ -10556,7 +10908,7 @@ var WorkflowEngine = class _WorkflowEngine {
10556
10908
  if (cancelled) return;
10557
10909
  const childId = token.slice(CHILD_TOKEN_PREFIX.length);
10558
10910
  if (!await childCompletionNeedsBuffer(this.store, childId, completion)) return;
10559
- await this.signal(token, completion);
10911
+ await this.signalUnchecked(token, completion);
10560
10912
  return;
10561
10913
  } catch (err) {
10562
10914
  if (err instanceof NamespaceMismatch) return;
@@ -10605,7 +10957,12 @@ var WorkflowEngine = class _WorkflowEngine {
10605
10957
  * steps' compensations run in reverse (visible as `compensate:<step>` events), then it's marked
10606
10958
  * cancelled. Without it, cancellation is immediate (no undo).
10607
10959
  */
10608
- 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) {
10609
10966
  const run = await this.store.getRun(runId);
10610
10967
  if (!run) return null;
10611
10968
  if (TERMINAL_RUN_STATUSES.includes(run.status)) {
@@ -10687,10 +11044,10 @@ var WorkflowEngine = class _WorkflowEngine {
10687
11044
  * their terminal status — `cancel` is a no-op on them, never clobbering a completed/dead run).
10688
11045
  */
10689
11046
  async cancelWhere(filter, opts) {
10690
- const runs = await this.store.listRuns(filter);
11047
+ const runs = await this.store.listRuns(this.scopeRunQuery(filter));
10691
11048
  const results = [];
10692
11049
  for (const run of runs) {
10693
- const r = await this.cancel(run.id, opts);
11050
+ const r = await this.cancelUnchecked(run.id, opts);
10694
11051
  if (r) results.push(r);
10695
11052
  }
10696
11053
  return results;
@@ -10706,11 +11063,16 @@ var WorkflowEngine = class _WorkflowEngine {
10706
11063
  * its worker (its next checkpoint write fails). Returns the number of runs deleted (0 if absent).
10707
11064
  */
10708
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) {
10709
11071
  const run = await this.store.getRun(runId);
10710
11072
  if (!run) return 0;
10711
11073
  let deleted = 0;
10712
- for (const childId of await this.getRunChildren(runId)) {
10713
- deleted += await this.deleteRun(childId);
11074
+ for (const childId of await this.runChildrenUnchecked(runId)) {
11075
+ deleted += await this.deleteRunUnchecked(childId);
10714
11076
  }
10715
11077
  await this.store.deleteRun(runId);
10716
11078
  return deleted + 1;
@@ -10739,6 +11101,7 @@ var WorkflowEngine = class _WorkflowEngine {
10739
11101
  if (!isNonEmptyRunScope(scope)) {
10740
11102
  throw new Error("purgeRuns: refusing an empty scope (it would delete every run) \u2014 pass at least one predicate, e.g. { namespace }");
10741
11103
  }
11104
+ const scoped = this.scopeRunQuery(scope);
10742
11105
  const batchSize = Math.max(1, opts?.batchSize ?? 500);
10743
11106
  const cancelLive = opts?.cancelLive ?? true;
10744
11107
  const withChildren = opts?.children ?? true;
@@ -10749,7 +11112,7 @@ var WorkflowEngine = class _WorkflowEngine {
10749
11112
  let previous = "";
10750
11113
  for (; ; ) {
10751
11114
  const batch = await this.store.listRuns({
10752
- ...scope,
11115
+ ...scoped,
10753
11116
  statuses,
10754
11117
  limit: batchSize
10755
11118
  });
@@ -10770,7 +11133,7 @@ var WorkflowEngine = class _WorkflowEngine {
10770
11133
  if (status === void 0) continue;
10771
11134
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
10772
11135
  if (!cancelLive) continue;
10773
- await this.cancel(id).catch(() => void 0);
11136
+ await this.cancelUnchecked(id).catch(() => void 0);
10774
11137
  }
10775
11138
  doomed.push(id);
10776
11139
  }
@@ -10831,10 +11194,10 @@ var WorkflowEngine = class _WorkflowEngine {
10831
11194
  * explicitly cancelled one's does, or the children are orphans nobody is holding a reference to.
10832
11195
  */
10833
11196
  async cancelChildren(parentRunId, opts) {
10834
- for (const id of await this.getRunChildren(parentRunId)) {
11197
+ for (const id of await this.runChildrenUnchecked(parentRunId)) {
10835
11198
  const child = await this.store.getRun(id).catch(() => null);
10836
11199
  if (child?.tags?.includes(`${PARENT_CLOSE_TAG_PREFIX}abandon`)) continue;
10837
- await this.cancel(id, opts).catch(() => void 0);
11200
+ await this.cancelUnchecked(id, opts).catch(() => void 0);
10838
11201
  }
10839
11202
  }
10840
11203
  /**
@@ -10852,7 +11215,7 @@ var WorkflowEngine = class _WorkflowEngine {
10852
11215
  if (event.type === "run.suspended") return;
10853
11216
  for (const [childId, policy] of intents) {
10854
11217
  if (policy === "abandon") continue;
10855
- queueMicrotask(() => void this.cancel(childId, {
11218
+ queueMicrotask(() => void this.cancelUnchecked(childId, {
10856
11219
  compensate: policy === "cancel"
10857
11220
  }).catch(() => void 0));
10858
11221
  }
@@ -10876,7 +11239,13 @@ var WorkflowEngine = class _WorkflowEngine {
10876
11239
  parentRunId
10877
11240
  ])).filter((w) => w.token.startsWith("child:") && !isAnyMember(w)).map((w) => w.token.slice("child:".length));
10878
11241
  }
11242
+ /** The child runs of `parentRunId`; empty for a parent the caller may not see. */
10879
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) {
10880
11249
  const childIds = new Set(await this.awaitedChildIds(parentRunId));
10881
11250
  const prefixes = CHILD_EDGE_PREFIXES;
10882
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)));
@@ -11237,7 +11606,7 @@ var WorkflowEngine = class _WorkflowEngine {
11237
11606
  const served = /* @__PURE__ */ new Set();
11238
11607
  this.turnServedWakes.set(run.id, served);
11239
11608
  if (registered?.remote) await this.noteServedWakes(run.id);
11240
- 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));
11241
11610
  if (registered?.singleton && (result.status === "completed" || result.status === "failed" || result.status === "cancelled" || result.status === "dead")) {
11242
11611
  void this.singletons.wakeNext(run).catch(() => void 0);
11243
11612
  }
@@ -11553,7 +11922,8 @@ var WorkflowEngine = class _WorkflowEngine {
11553
11922
  error: error2
11554
11923
  });
11555
11924
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11556
- namespace: run.namespace
11925
+ namespace: run.namespace,
11926
+ ...inheritTenant(run)
11557
11927
  });
11558
11928
  return {
11559
11929
  kind: "suspended"
@@ -11600,7 +11970,8 @@ var WorkflowEngine = class _WorkflowEngine {
11600
11970
  if (!handlerRun) {
11601
11971
  const handler = handoff.input;
11602
11972
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11603
- namespace: run.namespace
11973
+ namespace: run.namespace,
11974
+ ...inheritTenant(run)
11604
11975
  });
11605
11976
  }
11606
11977
  return {
@@ -12385,7 +12756,8 @@ ${run.workflowVersion}`;
12385
12756
  const existingChild = await this.store.getRun(childId);
12386
12757
  if (!existingChild) {
12387
12758
  this.startChildDeferred(cmd.workflow, cmd.input, childId, {
12388
- namespace: run.namespace
12759
+ namespace: run.namespace,
12760
+ ...inheritTenant(run)
12389
12761
  });
12390
12762
  } else {
12391
12763
  this.redeliverFinishedChild(childId, existingChild);
@@ -12504,7 +12876,7 @@ ${run.workflowVersion}`;
12504
12876
  this.awaitedRemoteSteps.set(run.id, awaitedSteps);
12505
12877
  const awaitedFans = [];
12506
12878
  this.awaitedStepFans.set(run.id, awaitedFans);
12507
- 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);
12508
12880
  try {
12509
12881
  const handoff = liveHandoff(run.id, snapshot);
12510
12882
  if (handoff && !this.cancelRequested.has(run.id)) {
@@ -12562,7 +12934,7 @@ ${run.workflowVersion}`;
12562
12934
  value: void 0
12563
12935
  });
12564
12936
  const nextId = nextContinuationId(run.id);
12565
- 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));
12566
12938
  return {
12567
12939
  runId: run.id,
12568
12940
  status: "completed"
@@ -12835,7 +13207,7 @@ ${run.workflowVersion}`;
12835
13207
  /** The seam handed to {@link createWorkflowCtx}: the authoring API reaches durability + lifecycle
12836
13208
  * (checkpointing, dispatch, child start) through this, so the ctx primitives live in their own
12837
13209
  * module and the engine stays the orchestrator. */
12838
- ctxHostFor(replay, parentNamespace, sticky) {
13210
+ ctxHostFor(replay, parentNamespace, sticky, parentTenant) {
12839
13211
  return {
12840
13212
  store: this.store,
12841
13213
  replay,
@@ -12882,6 +13254,8 @@ ${run.workflowVersion}`;
12882
13254
  this.startChildDeferred(workflow, input, id, {
12883
13255
  priority,
12884
13256
  namespace: parentNamespace,
13257
+ // The child belongs to the parent's customer, whichever instance or context drives it.
13258
+ ...parentTenant,
12885
13259
  // Absent unless the body pinned one (`ctx.child(ref, input, { version })`) — an omitted
12886
13260
  // pin must stay omitted, so the child keeps resolving `latest` exactly as before.
12887
13261
  version,
@@ -12905,7 +13279,7 @@ ${run.workflowVersion}`;
12905
13279
  // idempotent on a terminal/cancelled run (returns its existing status without side effects), so
12906
13280
  // no extra guard is needed here for the failFast replay case (re-issuing the same cancel calls).
12907
13281
  cancelChild: /* @__PURE__ */ __name((childId) => {
12908
- queueMicrotask(() => void this.cancel(childId).catch(() => void 0));
13282
+ queueMicrotask(() => void this.cancelUnchecked(childId).catch(() => void 0));
12909
13283
  }, "cancelChild"),
12910
13284
  // Shallow-merge into the run's searchAttributes (the ctx primitive makes this exactly-once).
12911
13285
  upsertSearchAttributes: /* @__PURE__ */ __name(async (runId, attrs) => {
@@ -12932,7 +13306,7 @@ ${run.workflowVersion}`;
12932
13306
  console.warn(`[nestjs-durable] waking entity "${name}" key "${key}" failed (its op stays buffered for the next wake):`, err);
12933
13307
  }));
12934
13308
  }, "kickEntity"),
12935
- interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body), "interceptStep")
13309
+ interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body, parentTenant), "interceptStep")
12936
13310
  };
12937
13311
  }
12938
13312
  /**
@@ -12941,10 +13315,11 @@ ${run.workflowVersion}`;
12941
13315
  * paused at a breakpoint.
12942
13316
  */
12943
13317
  async continue(runId) {
13318
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
12944
13319
  const checkpoints = await this.store.listCheckpoints(runId);
12945
13320
  const bp = checkpoints.find(isBreakpoint);
12946
13321
  if (!bp) return null;
12947
- return this.signal(breakpointToken(runId, bp.seq), void 0);
13322
+ return this.signalUnchecked(breakpointToken(runId, bp.seq), void 0);
12948
13323
  }
12949
13324
  /**
12950
13325
  * Read the latest value a run published for `key` via {@link WorkflowCtx.setEvent} — a
@@ -12952,6 +13327,7 @@ ${run.workflowVersion}`;
12952
13327
  * never published that key. The suspend-model counterpart of a Temporal query.
12953
13328
  */
12954
13329
  async getEvent(runId, key) {
13330
+ if (this.restrictiveFilter() && await this.hidden(runId)) return void 0;
12955
13331
  const name = `event:${key}`;
12956
13332
  if (this.store.getLatestCheckpointByName) {
12957
13333
  const latest2 = await this.store.getLatestCheckpointByName(runId, name);
@@ -12976,7 +13352,7 @@ ${run.workflowVersion}`;
12976
13352
  * if nothing was waiting — a too-early or duplicate update).
12977
13353
  */
12978
13354
  async update(runId, name, arg) {
12979
- const run = await this.store.getRun(runId);
13355
+ const run = await this.visibleRun(runId);
12980
13356
  if (!run) return {
12981
13357
  accepted: false,
12982
13358
  reason: `run ${runId} not found`
@@ -12996,7 +13372,7 @@ ${run.workflowVersion}`;
12996
13372
  };
12997
13373
  }
12998
13374
  }
12999
- const result = await this.signal(`update:${runId}:${name}`, arg);
13375
+ const result = await this.signalUnchecked(`update:${runId}:${name}`, arg);
13000
13376
  return {
13001
13377
  accepted: true,
13002
13378
  run: result
@@ -16181,6 +16557,9 @@ var InMemoryStateStore = class {
16181
16557
  if (query.origins) {
16182
16558
  runs = runs.filter((r) => query.origins?.includes(r.origin ?? null));
16183
16559
  }
16560
+ if (query.tenantId !== void 0 || query.tenantIds !== void 0) {
16561
+ runs = runs.filter((r) => matchesTenantPredicates(r, query));
16562
+ }
16184
16563
  if (query.attributes?.length) {
16185
16564
  let candidates = null;
16186
16565
  for (const f of query.attributes) {
@@ -16254,7 +16633,7 @@ var InMemoryStateStore = class {
16254
16633
  async listSchedules(query) {
16255
16634
  const rows = [
16256
16635
  ...this.schedules.values()
16257
- ].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));
16258
16637
  const offset = query.offset ?? 0;
16259
16638
  return rows.slice(offset, query.limit != null ? offset + query.limit : void 0).map((s) => structuredClone(s));
16260
16639
  }
@@ -16625,6 +17004,7 @@ export {
16625
17004
  axisIsRunColumn,
16626
17005
  bindWorkflowClass,
16627
17006
  breakpointToken,
17007
+ bufferedEventReaches,
16628
17008
  buildWorkflowDirectory,
16629
17009
  canRoute,
16630
17010
  capableWorkers,
@@ -16672,6 +17052,7 @@ export {
16672
17052
  hmacTenantVerifier,
16673
17053
  indexWaitersByRun,
16674
17054
  info,
17055
+ inheritTenant,
16675
17056
  isAnyCheckpoint,
16676
17057
  isAnyMember,
16677
17058
  isEngineMintedTag,
@@ -16698,6 +17079,7 @@ export {
16698
17079
  log,
16699
17080
  markRemoteEvent,
16700
17081
  matchesAttributes,
17082
+ matchesTenantPredicates,
16701
17083
  mergeRunFacetRows,
16702
17084
  mergeRunValueFacetRows,
16703
17085
  missingCapabilities,
@@ -16722,6 +17104,7 @@ export {
16722
17104
  prevCronFireMs,
16723
17105
  prevRRuleFireMs,
16724
17106
  queryCheckpointsOf,
17107
+ readBufferedEvent,
16725
17108
  readRunsByIds,
16726
17109
  readSearchAttributes,
16727
17110
  requiredCapabilities,
@@ -16733,6 +17116,7 @@ export {
16733
17116
  retentionKeeps,
16734
17117
  retiredHandoffName,
16735
17118
  routeFor,
17119
+ rowTenant,
16736
17120
  runCompletedEvent,
16737
17121
  runDetailEtag,
16738
17122
  runDurableExecution,
@@ -16750,6 +17134,8 @@ export {
16750
17134
  sanitizeQueueToken,
16751
17135
  scheduleRunIdAt,
16752
17136
  scheduledRunId,
17137
+ scopeBufferedEvent,
17138
+ scopeTenantQuery,
16753
17139
  settleResultsWithPlainCalls,
16754
17140
  signTenantToken,
16755
17141
  singletonAdmissionDenialPatch,
@@ -16766,6 +17152,8 @@ export {
16766
17152
  summarizeRunFromStore,
16767
17153
  summarizeTimeline,
16768
17154
  tenantGroup,
17155
+ tenantIdsFor,
17156
+ tenantVisible,
16769
17157
  toEventSubscription,
16770
17158
  traceIdOfTraceparent,
16771
17159
  triggerFailedSubscribersOf,