@dudousxd/nestjs-durable-core 0.89.0 → 0.90.1

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;
@@ -6245,6 +6413,7 @@ var PARENT_NOTIFY_BACKOFF_MS = 250;
6245
6413
  var LEASE_RECHECK_MAX_MS = 2e3;
6246
6414
  var LEASE_RECHECK_SLACK_MS = 100;
6247
6415
  var LEASE_RECHECK_ATTEMPTS = 30;
6416
+ var RETRY_LEASE_POLL_MS = 100;
6248
6417
  function wakeSeen(request, settledFans, served) {
6249
6418
  if (request.id !== void 0 && served.has(request.id)) return true;
6250
6419
  return isFanWakeRequest(request.payload) && request.payload.fans.every(([first, seq]) => (settledFans.get(first) ?? -1) >= seq);
@@ -6436,6 +6605,8 @@ var WorkflowEngine = class _WorkflowEngine {
6436
6605
  context;
6437
6606
  /** Establish the originating context ambiently around a local step body (see {@link WorkflowEngineDeps.rehydrate}). Default passthrough. */
6438
6607
  rehydrate;
6608
+ /** Tenancy seam (see {@link WorkflowEngineDeps.tenancy}); undefined = off. */
6609
+ tenancy;
6439
6610
  compensationRetries;
6440
6611
  /** Persist a `running` checkpoint at the start of a local step body (see {@link WorkflowEngineDeps.trackStepStart}). */
6441
6612
  trackStepStart;
@@ -6645,6 +6816,7 @@ var WorkflowEngine = class _WorkflowEngine {
6645
6816
  this.traceparent = deps.traceparent;
6646
6817
  this.context = deps.context;
6647
6818
  this.rehydrate = deps.rehydrate ?? ((_carrier, fn) => fn());
6819
+ this.tenancy = deps.tenancy;
6648
6820
  this.compensationRetries = Math.max(1, deps.compensationRetries ?? 1);
6649
6821
  this.trackStepStart = deps.trackStepStart ?? true;
6650
6822
  this.localWork = new BoundedRunner(LOCAL_RUN_CONCURRENCY);
@@ -6674,7 +6846,9 @@ var WorkflowEngine = class _WorkflowEngine {
6674
6846
  this.schedules = new ScheduleClient(this.store, {
6675
6847
  start: /* @__PURE__ */ __name((workflow, input, runId, opts) => this.start(workflow, input, runId, opts), "start"),
6676
6848
  getRun: /* @__PURE__ */ __name((runId) => this.store.getRun(runId), "getRun"),
6677
- isDraining: /* @__PURE__ */ __name(() => this.draining, "isDraining")
6849
+ isDraining: /* @__PURE__ */ __name(() => this.draining, "isDraining"),
6850
+ tenant: /* @__PURE__ */ __name(() => this.tenancy?.current(), "tenant"),
6851
+ tenantFilter: /* @__PURE__ */ __name(() => this.tenantFilter(), "tenantFilter")
6678
6852
  }, {
6679
6853
  namespace: this.namespace,
6680
6854
  clock: this.clock
@@ -6778,7 +6952,18 @@ var WorkflowEngine = class _WorkflowEngine {
6778
6952
  }
6779
6953
  }
6780
6954
  });
6781
- this.accumulators = new EventAccumulators(this);
6955
+ this.accumulators = new EventAccumulators({
6956
+ register: /* @__PURE__ */ __name((name, version, fn, opts) => this.register(name, version, fn, opts), "register"),
6957
+ // The engine picks the accumulator's tenant itself, so its signal is the engine's own
6958
+ // delivery: not subject to the publisher's tenancy filter.
6959
+ signalWithStart: /* @__PURE__ */ __name(async (workflow, input, runId, signal, opts) => {
6960
+ await this.start(workflow, input, runId, opts);
6961
+ await this.signalUnchecked(signal.token, signal.payload);
6962
+ return {
6963
+ runId
6964
+ };
6965
+ }, "signalWithStart")
6966
+ });
6782
6967
  this.entities = new Entities(this, {
6783
6968
  bufferSignal: /* @__PURE__ */ __name((token, payload) => this.store.bufferSignal(token, payload), "bufferSignal"),
6784
6969
  wakeWaiter: /* @__PURE__ */ __name((token, payload) => this.wakeSignalWaiter(token, payload), "wakeWaiter"),
@@ -7254,15 +7439,19 @@ var WorkflowEngine = class _WorkflowEngine {
7254
7439
  * time from {@link context} — the SAME reader stamped on dispatched remote tasks — so a local step
7255
7440
  * sees the live tenant / user / trace ids ambiently (via the {@link rehydrate} bridge). Default
7256
7441
  * `rehydrate` is a passthrough, so this is byte-identical to a bare body call when unwired.
7442
+ *
7443
+ * The run row's tenant is re-applied INSIDE the rehydrated context: an app carrier (a custom
7444
+ * `serialize`/`deserialize`) may not carry the tenant, and its deserializer would otherwise replace
7445
+ * the tenant the turn was started with. Local steps always see the row's tenant.
7257
7446
  */
7258
- interceptStep(invocation, body) {
7447
+ interceptStep(invocation, body, tenant) {
7259
7448
  const carrier = this.context?.();
7260
7449
  const run = /* @__PURE__ */ __name(() => {
7261
7450
  if (this.interceptors.length === 0) return body();
7262
7451
  const chain = this.interceptors.reduceRight((next, interceptor) => () => interceptor(invocation, next), body);
7263
7452
  return chain();
7264
7453
  }, "run");
7265
- return this.rehydrate(carrier, run);
7454
+ return this.rehydrate(carrier, () => tenant ? this.inRunTenant(tenant, run) : run());
7266
7455
  }
7267
7456
  /**
7268
7457
  * Be notified when a run is cancelled — on ANY instance, via the transport control plane. A
@@ -7453,9 +7642,12 @@ var WorkflowEngine = class _WorkflowEngine {
7453
7642
  * an announcement carries no `where` or `input`. `routeIdOf` names the event for a subscriber's
7454
7643
  * debounce/batch accumulator, which counts an id once. Returns the subscribers reached, with the
7455
7644
  * run each started (none when the payload went into its debounce/batch accumulator), and the ones
7456
- * that could not be started, with why.
7645
+ * that could not be started, with why. `batchTenant` is the tenant whose debounce/batch accumulator
7646
+ * the payload goes into (see {@link EventAccumulators.route}). `runTenant`, when set, is the tenant
7647
+ * every directly started subscriber run gets (a lifecycle event: the settled run's), instead of the
7648
+ * context's at publish time (which may be none, e.g. the background retry pass).
7457
7649
  */
7458
- async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf) {
7650
+ async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf, batchTenant, runTenant) {
7459
7651
  const reached = [];
7460
7652
  const failed = [];
7461
7653
  for (const [workflow, subscriptions] of this.eventTriggers.get(name) ?? []) {
@@ -7472,13 +7664,13 @@ var WorkflowEngine = class _WorkflowEngine {
7472
7664
  const input = accepted.input ? accepted.input(payload) : payload;
7473
7665
  const batch = this.latest.get(workflow)?.eventBatch;
7474
7666
  if (batch) {
7475
- await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow));
7667
+ await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow), batchTenant);
7476
7668
  reached.push({
7477
7669
  workflow
7478
7670
  });
7479
7671
  } else {
7480
7672
  const runId = runIdOf(workflow);
7481
- await this.start(workflow, input, runId);
7673
+ await this.start(workflow, input, runId, runTenant);
7482
7674
  reached.push({
7483
7675
  workflow,
7484
7676
  runId
@@ -7496,7 +7688,7 @@ var WorkflowEngine = class _WorkflowEngine {
7496
7688
  if (local?.has(workflow) || only && !only.has(workflow)) continue;
7497
7689
  try {
7498
7690
  const runId = runIdOf(workflow);
7499
- await this.start(workflow, payload, runId);
7691
+ await this.start(workflow, payload, runId, runTenant);
7500
7692
  reached.push({
7501
7693
  workflow,
7502
7694
  runId
@@ -7853,11 +8045,12 @@ var WorkflowEngine = class _WorkflowEngine {
7853
8045
  const triggers = this.eventTriggers.get(lifecycleEventName(run.workflow, kind));
7854
8046
  if (!triggers || !this.servesNamespace(run.namespace)) return out;
7855
8047
  let payload;
8048
+ const tenant = this.lifecycleBatchTenant(run)?.id;
7856
8049
  for (const [workflow, subscriptions] of triggers) {
7857
8050
  const batch = this.latest.get(workflow)?.eventBatch;
7858
8051
  if (!batch) continue;
7859
8052
  if (!batch.key && subscriptions.every((sub2) => !sub2.where)) {
7860
- out.set(workflow, accumulatorRunId(workflow));
8053
+ out.set(workflow, accumulatorRunId(workflow, void 0, tenant));
7861
8054
  continue;
7862
8055
  }
7863
8056
  try {
@@ -7865,7 +8058,7 @@ var WorkflowEngine = class _WorkflowEngine {
7865
8058
  const { accepted } = acceptingSubscription(subscriptions, payload);
7866
8059
  if (!accepted) continue;
7867
8060
  const input = accepted.input ? accepted.input(payload) : payload;
7868
- out.set(workflow, accumulatorRunId(workflow, batch.key ? String(batch.key(input)) : void 0));
8061
+ out.set(workflow, accumulatorRunId(workflow, batch.key ? String(batch.key(input)) : void 0, tenant));
7869
8062
  } catch {
7870
8063
  out.set(workflow, void 0);
7871
8064
  }
@@ -8044,7 +8237,9 @@ var WorkflowEngine = class _WorkflowEngine {
8044
8237
  */
8045
8238
  async triggeredRuns(source) {
8046
8239
  const run = typeof source === "string" ? await this.store.getRun(source) : source;
8047
- return run ? triggeredRunsOf(run) : [];
8240
+ if (!run) return [];
8241
+ const filter = this.restrictiveFilter();
8242
+ return filter && !tenantVisible(run, filter) ? [] : triggeredRunsOf(run);
8048
8243
  }
8049
8244
  /** The live path of {@link publishSettled}: right after this instance settled the run. */
8050
8245
  publishLifecycle(event) {
@@ -8177,7 +8372,18 @@ var WorkflowEngine = class _WorkflowEngine {
8177
8372
  }
8178
8373
  if (targets.length === 0 && owe.size === 0 && !resolved) return void 0;
8179
8374
  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) : {
8375
+ const { reached, failed } = targets.length > 0 ? await this.startSubscribers(
8376
+ name,
8377
+ lifecycleEventOf(run),
8378
+ runIdOf,
8379
+ new Set(targets),
8380
+ remote,
8381
+ runIdOf,
8382
+ this.lifecycleBatchTenant(run),
8383
+ // The downstream run belongs to the settled run's customer, whoever publishes it (the
8384
+ // turn that settled it, or the background retry pass outside any request).
8385
+ inheritTenant(run)
8386
+ ) : {
8181
8387
  reached: [],
8182
8388
  failed: []
8183
8389
  };
@@ -8720,14 +8926,7 @@ var WorkflowEngine = class _WorkflowEngine {
8720
8926
  }
8721
8927
  await registered.validateInput?.(input);
8722
8928
  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
- }
8929
+ if (prior) return this.existingStartResult(prior);
8731
8930
  const quota = await resolveConcurrency(opts?.concurrency, registered.concurrency, input);
8732
8931
  if (quota) await assertConcurrency(this.store, name, quota);
8733
8932
  const now = /* @__PURE__ */ new Date();
@@ -8767,6 +8966,7 @@ var WorkflowEngine = class _WorkflowEngine {
8767
8966
  tags,
8768
8967
  searchAttributes: opts?.searchAttributes,
8769
8968
  priority: opts?.priority,
8969
+ ...this.startTenant(opts),
8770
8970
  createdAt: now,
8771
8971
  updatedAt: now
8772
8972
  };
@@ -8775,12 +8975,7 @@ var WorkflowEngine = class _WorkflowEngine {
8775
8975
  } catch (err) {
8776
8976
  const winner = await this.store.getRun(runId).catch(() => null);
8777
8977
  if (!winner) throw err;
8778
- return {
8779
- runId,
8780
- status: winner.status,
8781
- output: winner.output,
8782
- error: winner.error
8783
- };
8978
+ return this.existingStartResult(winner);
8784
8979
  }
8785
8980
  if (delayed) {
8786
8981
  this.emit({
@@ -8810,13 +9005,125 @@ var WorkflowEngine = class _WorkflowEngine {
8810
9005
  status: "pending"
8811
9006
  };
8812
9007
  }
8813
- /** Read a run's current persisted state (or null if unknown). A thin pass-through to the store. */
9008
+ /**
9009
+ * The tenant columns a new run gets: an explicit `opts.tenantId` (`null` = none) wins, else the
9010
+ * context tenant when tenancy is on, else none (no keys at all, so a run row is unchanged when
9011
+ * tenancy is off).
9012
+ */
9013
+ startTenant(opts) {
9014
+ const tenant = opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
9015
+ id: opts.tenantId,
9016
+ kind: opts.tenantKind
9017
+ } : this.tenancy?.current();
9018
+ if (!tenant) return {};
9019
+ return tenant.kind !== void 0 ? {
9020
+ tenantId: tenant.id,
9021
+ tenantKind: tenant.kind
9022
+ } : {
9023
+ tenantId: tenant.id
9024
+ };
9025
+ }
9026
+ /**
9027
+ * The context tenant a run started NOW would be stamped with (tenancy on), else undefined. For code
9028
+ * that records a start to replay it later outside the request, e.g. a transactional outbox.
9029
+ */
9030
+ contextTenant() {
9031
+ return this.tenancy?.current();
9032
+ }
9033
+ /**
9034
+ * The tenant whose debounce/batch accumulator a named event published now goes into: the
9035
+ * publisher's tenant, or `null` (the shared accumulator, no tenant) for a tenantless, `system` or
9036
+ * `all` publisher. Undefined when tenancy is off (the accumulator starts as it always did).
9037
+ */
9038
+ publishBatchTenant() {
9039
+ if (!this.tenancy) return void 0;
9040
+ const filter = this.tenantFilter();
9041
+ if (filter.mode !== "tenant") return null;
9042
+ const current = this.tenancy.current();
9043
+ return current?.id === filter.tenantId ? current : {
9044
+ id: filter.tenantId
9045
+ };
9046
+ }
9047
+ /**
9048
+ * The tenant whose debounce/batch accumulator `run`'s lifecycle event goes into: the run's own
9049
+ * (its publisher), or `null` for a run with no tenant. Undefined when tenancy is off.
9050
+ */
9051
+ lifecycleBatchTenant(run) {
9052
+ if (!this.tenancy) return void 0;
9053
+ return rowTenant(run) ?? null;
9054
+ }
9055
+ /** The matching filter for an app-facing call made now: `system` (sees all) when tenancy is off. */
9056
+ tenantFilter() {
9057
+ return this.tenancy?.filter() ?? {
9058
+ mode: "system"
9059
+ };
9060
+ }
9061
+ /**
9062
+ * The run `runId` if the caller may see it under the tenancy matching rule, else null — an
9063
+ * invisible run reads exactly like a missing one (not found, never forbidden).
9064
+ */
9065
+ visibleRun(runId) {
9066
+ const filter = this.restrictiveFilter();
9067
+ if (!filter) return this.store.getRun(runId);
9068
+ return this.store.getRun(runId).then((run) => run && tenantVisible(run, filter) ? run : null);
9069
+ }
9070
+ /**
9071
+ * What `start` returns for an id that already has a run. A run the caller may not see (tenancy)
9072
+ * returns its id and status only: never its output or error.
9073
+ */
9074
+ existingStartResult(run) {
9075
+ const filter = this.restrictiveFilter();
9076
+ if (filter && !tenantVisible(run, filter)) return {
9077
+ runId: run.id,
9078
+ status: run.status
9079
+ };
9080
+ return {
9081
+ runId: run.id,
9082
+ status: run.status,
9083
+ output: run.output,
9084
+ error: run.error
9085
+ };
9086
+ }
9087
+ /** The caller's filter when it can hide rows (`tenant` / `tenantless`), else undefined. */
9088
+ restrictiveFilter() {
9089
+ const filter = this.tenantFilter();
9090
+ return filter.mode === "system" || filter.mode === "all" ? void 0 : filter;
9091
+ }
9092
+ /**
9093
+ * True when the caller may NOT act on `runId` (it is missing or invisible to it). Callers guard
9094
+ * with `this.restrictiveFilter() && (await this.hidden(runId))`, so nothing is awaited when the
9095
+ * caller sees everything.
9096
+ */
9097
+ async hidden(runId) {
9098
+ return await this.visibleRun(runId) === null;
9099
+ }
9100
+ /**
9101
+ * Narrow `query` to the runs the caller may see (the tenancy matching rule). Use it before an
9102
+ * app-facing `store.listRuns`; a no-op when tenancy is off or the caller is `system`/`all`.
9103
+ */
9104
+ scopeRunQuery(query) {
9105
+ return scopeTenantQuery(query, this.tenantFilter());
9106
+ }
9107
+ /**
9108
+ * Run `fn` with `run`'s tenant restored as the context tenant (so a step body, a downstream lib and
9109
+ * every dispatched task's context carrier see it), whatever path drove the turn: a request, a
9110
+ * timer, a signal, recovery or a worker. A run with no tenant, or tenancy off, runs `fn` as is.
9111
+ */
9112
+ inRunTenant(run, fn) {
9113
+ const tenant = this.tenancy ? rowTenant(run) : void 0;
9114
+ return tenant && this.tenancy ? this.tenancy.run(tenant, fn) : fn();
9115
+ }
9116
+ /**
9117
+ * Read a run's current persisted state (or null if unknown). With tenancy on, a run of another
9118
+ * tenant reads as null (see {@link WorkflowEngineDeps.tenancy}).
9119
+ */
8814
9120
  getRun(runId) {
8815
- return this.store.getRun(runId);
9121
+ return this.visibleRun(runId);
8816
9122
  }
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) {
9123
+ /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9124
+ * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9125
+ async listCheckpoints(runId) {
9126
+ if (this.restrictiveFilter() && await this.hidden(runId)) return [];
8820
9127
  return this.store.listCheckpoints(runId);
8821
9128
  }
8822
9129
  /**
@@ -8828,6 +9135,13 @@ var WorkflowEngine = class _WorkflowEngine {
8828
9135
  * terminal too.
8829
9136
  */
8830
9137
  resume(runId) {
9138
+ if (this.restrictiveFilter()) {
9139
+ return this.hidden(runId).then((hidden) => {
9140
+ if (hidden) throw new Error(`run ${runId} not found`);
9141
+ this.noteWakeReason(runId, void 0);
9142
+ return this.resumeRun(runId, true);
9143
+ });
9144
+ }
8831
9145
  this.noteWakeReason(runId, void 0);
8832
9146
  return this.resumeRun(runId, true);
8833
9147
  }
@@ -9706,10 +10020,12 @@ var WorkflowEngine = class _WorkflowEngine {
9706
10020
  await this.store.removeBufferedEvent(candidate.id);
9707
10021
  continue;
9708
10022
  }
9709
- if (!eventMatches(candidate.payload, match)) continue;
10023
+ const { payload, tenantIds } = readBufferedEvent(candidate.payload);
10024
+ if (!bufferedEventReaches(tenantIds, run.tenantId)) continue;
10025
+ if (!eventMatches(payload, match)) continue;
9710
10026
  if (!await this.store.removeBufferedEvent(candidate.id)) continue;
9711
10027
  await this.store.removeSignalWaiter(waiter);
9712
- const settled = await this.deliverSignal(waiter, candidate.payload, true);
10028
+ const settled = await this.deliverSignal(waiter, payload, true);
9713
10029
  return settled ?? {
9714
10030
  runId: run.id,
9715
10031
  status: run.status
@@ -9748,6 +10064,7 @@ var WorkflowEngine = class _WorkflowEngine {
9748
10064
  * the HTTP request on workflow execution.
9749
10065
  */
9750
10066
  async requeue(runId, _seen) {
10067
+ if (_seen === void 0 && this.restrictiveFilter() && await this.hidden(runId)) return null;
9751
10068
  const seen = _seen ?? /* @__PURE__ */ new Set();
9752
10069
  if (seen.has(runId)) return null;
9753
10070
  seen.add(runId);
@@ -9855,7 +10172,7 @@ var WorkflowEngine = class _WorkflowEngine {
9855
10172
  * run's current status (with the count re-dispatched), or null if the run is unknown.
9856
10173
  */
9857
10174
  async redispatchPending(runId) {
9858
- const run = await this.store.getRun(runId);
10175
+ const run = await this.visibleRun(runId);
9859
10176
  if (!run) return null;
9860
10177
  const pending = (await this.store.listCheckpoints(runId)).filter((cp) => cp.kind === "remote" && cp.status === "pending");
9861
10178
  let redispatched = 0;
@@ -9870,7 +10187,7 @@ var WorkflowEngine = class _WorkflowEngine {
9870
10187
  startedAt: reEnqueuedAt,
9871
10188
  finishedAt: reEnqueuedAt
9872
10189
  });
9873
- await this.dispatchRemoteTask({
10190
+ await this.inRunTenant(run, () => this.dispatchRemoteTask({
9874
10191
  runId,
9875
10192
  seq: cp.seq,
9876
10193
  name: cp.name,
@@ -9878,7 +10195,7 @@ var WorkflowEngine = class _WorkflowEngine {
9878
10195
  group: cp.workerGroup ?? sanitizeQueueToken(cp.name),
9879
10196
  input: cp.input,
9880
10197
  attempt: reAttempt
9881
- });
10198
+ }));
9882
10199
  redispatched += 1;
9883
10200
  }
9884
10201
  return {
@@ -9893,12 +10210,13 @@ var WorkflowEngine = class _WorkflowEngine {
9893
10210
  * the original stays inspectable. Returns the new run's id, or null if `runId` is unknown.
9894
10211
  */
9895
10212
  async retryWithInput(runId, input, newRunId) {
9896
- const run = await this.store.getRun(runId);
10213
+ const run = await this.visibleRun(runId);
9897
10214
  if (!run) return null;
9898
10215
  const id = newRunId ?? `${runId}~retry~${globalThis.crypto.randomUUID().slice(0, 8)}`;
9899
10216
  await this.start(run.workflow, input, id, {
9900
10217
  tags: run.tags,
9901
- namespace: run.namespace
10218
+ namespace: run.namespace,
10219
+ ...inheritTenant(run)
9902
10220
  });
9903
10221
  return {
9904
10222
  runId: id
@@ -9947,6 +10265,7 @@ var WorkflowEngine = class _WorkflowEngine {
9947
10265
  output: run.output,
9948
10266
  error: run.error
9949
10267
  }), "toResult");
10268
+ const filter = this.restrictiveFilter();
9950
10269
  return new Promise((resolve, reject) => {
9951
10270
  let done = false;
9952
10271
  let off = /* @__PURE__ */ __name(() => {
@@ -9977,6 +10296,10 @@ var WorkflowEngine = class _WorkflowEngine {
9977
10296
  const check = /* @__PURE__ */ __name(() => {
9978
10297
  if (done) return;
9979
10298
  void this.store.getRun(runId).then((run) => {
10299
+ if (run && filter && !tenantVisible(run, filter)) {
10300
+ fail(new Error(`run ${runId} not found`));
10301
+ return;
10302
+ }
9980
10303
  if (run && isSettled(run)) finish(run);
9981
10304
  }, fail);
9982
10305
  }, "check");
@@ -10094,17 +10417,23 @@ var WorkflowEngine = class _WorkflowEngine {
10094
10417
  */
10095
10418
  async publishEvent(name, payload, opts) {
10096
10419
  let touched = 0;
10420
+ const filter = this.restrictiveFilter();
10421
+ const reaches = /* @__PURE__ */ __name(async (runId) => {
10422
+ if (!filter) return true;
10423
+ const run = await this.store.getRun(runId);
10424
+ return run !== null && tenantVisible(run, filter);
10425
+ }, "reaches");
10097
10426
  const waiters = await this.store.listSignalWaiters(eventPrefix(name));
10098
10427
  for (const w of waiters) {
10099
- if (eventMatches(payload, eventMatchOf(w.token))) {
10100
- await this.signal(w.token, payload);
10428
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10429
+ await this.signalUnchecked(w.token, payload);
10101
10430
  touched += 1;
10102
10431
  }
10103
10432
  }
10104
10433
  const remote = await this.announcedRemoteSubscribers(name, null);
10105
10434
  if (this.eventTriggers.get(name)?.size || remote.length > 0) {
10106
10435
  const eventId = opts?.id ?? globalThis.crypto.randomUUID();
10107
- const { reached, failed } = await this.startSubscribers(name, payload, (workflow) => `evt:${eventId}:${workflow}`, void 0, remote);
10436
+ const { reached, failed } = await this.startSubscribers(name, payload, (workflow) => `evt:${eventId}:${workflow}`, void 0, remote, void 0, this.publishBatchTenant());
10108
10437
  touched += reached.length;
10109
10438
  for (const { workflow, error: error2 } of failed) {
10110
10439
  console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error2);
@@ -10114,12 +10443,18 @@ var WorkflowEngine = class _WorkflowEngine {
10114
10443
  const bufferedId = globalThis.crypto.randomUUID();
10115
10444
  await this.store.bufferEvent({
10116
10445
  name,
10117
- payload,
10446
+ payload: scopeBufferedEvent(payload, filter ? tenantIdsFor(filter) : void 0),
10118
10447
  id: bufferedId,
10119
10448
  publishedAt: this.clock()
10120
10449
  });
10121
10450
  const lateWaiters = await this.store.listSignalWaiters(eventPrefix(name));
10122
- const lateWaiter = lateWaiters.find((w) => eventMatches(payload, eventMatchOf(w.token)));
10451
+ let lateWaiter;
10452
+ for (const w of lateWaiters) {
10453
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10454
+ lateWaiter = w;
10455
+ break;
10456
+ }
10457
+ }
10123
10458
  if (!lateWaiter) return touched;
10124
10459
  if (!await this.store.removeBufferedEvent(bufferedId)) return touched;
10125
10460
  const waiter = await this.store.takeSignalWaiter(lateWaiter.token);
@@ -10426,7 +10761,23 @@ var WorkflowEngine = class _WorkflowEngine {
10426
10761
  * Either way, the destructive `take*` ops (on the waiter row, on the buffer) arbitrate: whichever
10427
10762
  * side actually removes the row is the one that delivers, so a signal is never delivered twice.
10428
10763
  */
10429
- async signal(token, payload, opts) {
10764
+ signal(token, payload, opts) {
10765
+ const filter = parseWebhookToken(token) ? void 0 : this.restrictiveFilter();
10766
+ if (!filter) return this.signalUnchecked(token, payload, opts);
10767
+ return this.signalTargetVisible(token, filter).then((visible) => visible ? this.signalUnchecked(token, payload, opts) : null);
10768
+ }
10769
+ /**
10770
+ * False when a run waits on `token` and `filter` may not see it (the tenancy matching rule). A
10771
+ * token nobody waits on yet is buffered as before (there is no run to check).
10772
+ */
10773
+ async signalTargetVisible(token, filter) {
10774
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
10775
+ if (!waiter) return true;
10776
+ const run = await this.store.getRun(waiter.runId);
10777
+ return !run || tenantVisible(run, filter);
10778
+ }
10779
+ /** {@link signal} without the tenancy check — the engine's own deliveries. */
10780
+ async signalUnchecked(token, payload, opts) {
10430
10781
  const id = opts?.id;
10431
10782
  if (id === void 0) return this.deliverOrBuffer(token, payload);
10432
10783
  if (!this.store.claimSignalId) {
@@ -10510,14 +10861,16 @@ var WorkflowEngine = class _WorkflowEngine {
10510
10861
  * null if no run is waiting on the task (e.g. a duplicate/late delivery) — a safe no-op.
10511
10862
  */
10512
10863
  async completeTask(runId, name, result) {
10513
- return this.signal(`task:${runId}:${name}`, {
10864
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
10865
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10514
10866
  ok: true,
10515
10867
  value: result
10516
10868
  });
10517
10869
  }
10518
10870
  /** Report that a `ctx.task` failed — the run resumes and throws a FatalError at the task. */
10519
10871
  async failTask(runId, name, error2) {
10520
- return this.signal(`task:${runId}:${name}`, {
10872
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
10873
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10521
10874
  ok: false,
10522
10875
  error: error2
10523
10876
  });
@@ -10556,7 +10909,7 @@ var WorkflowEngine = class _WorkflowEngine {
10556
10909
  if (cancelled) return;
10557
10910
  const childId = token.slice(CHILD_TOKEN_PREFIX.length);
10558
10911
  if (!await childCompletionNeedsBuffer(this.store, childId, completion)) return;
10559
- await this.signal(token, completion);
10912
+ await this.signalUnchecked(token, completion);
10560
10913
  return;
10561
10914
  } catch (err) {
10562
10915
  if (err instanceof NamespaceMismatch) return;
@@ -10605,7 +10958,12 @@ var WorkflowEngine = class _WorkflowEngine {
10605
10958
  * steps' compensations run in reverse (visible as `compensate:<step>` events), then it's marked
10606
10959
  * cancelled. Without it, cancellation is immediate (no undo).
10607
10960
  */
10608
- async cancel(runId, opts) {
10961
+ cancel(runId, opts) {
10962
+ if (!this.restrictiveFilter()) return this.cancelUnchecked(runId, opts);
10963
+ return this.hidden(runId).then((hidden) => hidden ? null : this.cancelUnchecked(runId, opts));
10964
+ }
10965
+ /** {@link cancel} without the tenancy check — the engine's own cascades and bulk paths. */
10966
+ async cancelUnchecked(runId, opts) {
10609
10967
  const run = await this.store.getRun(runId);
10610
10968
  if (!run) return null;
10611
10969
  if (TERMINAL_RUN_STATUSES.includes(run.status)) {
@@ -10687,10 +11045,10 @@ var WorkflowEngine = class _WorkflowEngine {
10687
11045
  * their terminal status — `cancel` is a no-op on them, never clobbering a completed/dead run).
10688
11046
  */
10689
11047
  async cancelWhere(filter, opts) {
10690
- const runs = await this.store.listRuns(filter);
11048
+ const runs = await this.store.listRuns(this.scopeRunQuery(filter));
10691
11049
  const results = [];
10692
11050
  for (const run of runs) {
10693
- const r = await this.cancel(run.id, opts);
11051
+ const r = await this.cancelUnchecked(run.id, opts);
10694
11052
  if (r) results.push(r);
10695
11053
  }
10696
11054
  return results;
@@ -10706,11 +11064,16 @@ var WorkflowEngine = class _WorkflowEngine {
10706
11064
  * its worker (its next checkpoint write fails). Returns the number of runs deleted (0 if absent).
10707
11065
  */
10708
11066
  async deleteRun(runId) {
11067
+ if (this.restrictiveFilter() && await this.hidden(runId)) return 0;
11068
+ return await this.deleteRunUnchecked(runId);
11069
+ }
11070
+ /** {@link deleteRun} without the tenancy check (its own subtree recursion). */
11071
+ async deleteRunUnchecked(runId) {
10709
11072
  const run = await this.store.getRun(runId);
10710
11073
  if (!run) return 0;
10711
11074
  let deleted = 0;
10712
- for (const childId of await this.getRunChildren(runId)) {
10713
- deleted += await this.deleteRun(childId);
11075
+ for (const childId of await this.runChildrenUnchecked(runId)) {
11076
+ deleted += await this.deleteRunUnchecked(childId);
10714
11077
  }
10715
11078
  await this.store.deleteRun(runId);
10716
11079
  return deleted + 1;
@@ -10739,6 +11102,7 @@ var WorkflowEngine = class _WorkflowEngine {
10739
11102
  if (!isNonEmptyRunScope(scope)) {
10740
11103
  throw new Error("purgeRuns: refusing an empty scope (it would delete every run) \u2014 pass at least one predicate, e.g. { namespace }");
10741
11104
  }
11105
+ const scoped = this.scopeRunQuery(scope);
10742
11106
  const batchSize = Math.max(1, opts?.batchSize ?? 500);
10743
11107
  const cancelLive = opts?.cancelLive ?? true;
10744
11108
  const withChildren = opts?.children ?? true;
@@ -10749,7 +11113,7 @@ var WorkflowEngine = class _WorkflowEngine {
10749
11113
  let previous = "";
10750
11114
  for (; ; ) {
10751
11115
  const batch = await this.store.listRuns({
10752
- ...scope,
11116
+ ...scoped,
10753
11117
  statuses,
10754
11118
  limit: batchSize
10755
11119
  });
@@ -10770,7 +11134,7 @@ var WorkflowEngine = class _WorkflowEngine {
10770
11134
  if (status === void 0) continue;
10771
11135
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
10772
11136
  if (!cancelLive) continue;
10773
- await this.cancel(id).catch(() => void 0);
11137
+ await this.cancelUnchecked(id).catch(() => void 0);
10774
11138
  }
10775
11139
  doomed.push(id);
10776
11140
  }
@@ -10831,10 +11195,10 @@ var WorkflowEngine = class _WorkflowEngine {
10831
11195
  * explicitly cancelled one's does, or the children are orphans nobody is holding a reference to.
10832
11196
  */
10833
11197
  async cancelChildren(parentRunId, opts) {
10834
- for (const id of await this.getRunChildren(parentRunId)) {
11198
+ for (const id of await this.runChildrenUnchecked(parentRunId)) {
10835
11199
  const child = await this.store.getRun(id).catch(() => null);
10836
11200
  if (child?.tags?.includes(`${PARENT_CLOSE_TAG_PREFIX}abandon`)) continue;
10837
- await this.cancel(id, opts).catch(() => void 0);
11201
+ await this.cancelUnchecked(id, opts).catch(() => void 0);
10838
11202
  }
10839
11203
  }
10840
11204
  /**
@@ -10852,7 +11216,7 @@ var WorkflowEngine = class _WorkflowEngine {
10852
11216
  if (event.type === "run.suspended") return;
10853
11217
  for (const [childId, policy] of intents) {
10854
11218
  if (policy === "abandon") continue;
10855
- queueMicrotask(() => void this.cancel(childId, {
11219
+ queueMicrotask(() => void this.cancelUnchecked(childId, {
10856
11220
  compensate: policy === "cancel"
10857
11221
  }).catch(() => void 0));
10858
11222
  }
@@ -10876,7 +11240,13 @@ var WorkflowEngine = class _WorkflowEngine {
10876
11240
  parentRunId
10877
11241
  ])).filter((w) => w.token.startsWith("child:") && !isAnyMember(w)).map((w) => w.token.slice("child:".length));
10878
11242
  }
11243
+ /** The child runs of `parentRunId`; empty for a parent the caller may not see. */
10879
11244
  async getRunChildren(parentRunId) {
11245
+ if (this.restrictiveFilter() && await this.hidden(parentRunId)) return [];
11246
+ return this.runChildrenUnchecked(parentRunId);
11247
+ }
11248
+ /** {@link getRunChildren} without the tenancy check (the engine's own subtree walks). */
11249
+ async runChildrenUnchecked(parentRunId) {
10880
11250
  const childIds = new Set(await this.awaitedChildIds(parentRunId));
10881
11251
  const prefixes = CHILD_EDGE_PREFIXES;
10882
11252
  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)));
@@ -11210,26 +11580,87 @@ var WorkflowEngine = class _WorkflowEngine {
11210
11580
  const reentered = run.lockedBy === this.instanceId && (run.lockedUntil ?? 0) > lockNow && (lockedForTurn || await this.proveOwnLease(run.id, lockNow));
11211
11581
  if (!reentered) {
11212
11582
  if (!await this.store.tryLockRun(run.id, this.instanceId, lockNow + this.leaseMs, lockNow)) {
11213
- if (reason.generic) {
11214
- if (!this.genericWakeRequested.has(run.id)) {
11215
- this.genericWakeRequested.add(run.id);
11216
- this.inBackground(this.requestWakeAfterTurn(run.id, null));
11217
- }
11218
- } else {
11219
- const fans = {
11220
- fans: [
11221
- ...reason.fans
11222
- ]
11223
- };
11224
- this.inBackground(this.requestWakeAfterTurn(run.id, fans));
11583
+ if (run.status === "failed") {
11584
+ const taken = await this.takeLeaseForRetry(run.id);
11585
+ if ("result" in taken) return taken.result;
11586
+ return this.executeLeased(taken.run, fn, registered);
11225
11587
  }
11226
- this.recheckAfterLease(run.id, run.lockedUntil);
11588
+ return this.keepWakeForHeldLease(run, reason);
11589
+ }
11590
+ }
11591
+ return this.executeLeased(run, fn, registered);
11592
+ }
11593
+ /**
11594
+ * A wake that found `run`'s lease held by another execution: keep it for that execution to honor
11595
+ * once it releases the lease, and answer with the run's status as read.
11596
+ */
11597
+ keepWakeForHeldLease(run, reason) {
11598
+ if (reason.generic) {
11599
+ if (!this.genericWakeRequested.has(run.id)) {
11600
+ this.genericWakeRequested.add(run.id);
11601
+ this.inBackground(this.requestWakeAfterTurn(run.id, null));
11602
+ }
11603
+ } else {
11604
+ const fans = {
11605
+ fans: [
11606
+ ...reason.fans
11607
+ ]
11608
+ };
11609
+ this.inBackground(this.requestWakeAfterTurn(run.id, fans));
11610
+ }
11611
+ this.recheckAfterLease(run.id, run.lockedUntil);
11612
+ return {
11613
+ runId: run.id,
11614
+ status: run.status
11615
+ };
11616
+ }
11617
+ /**
11618
+ * Take `runId`'s lease for an explicit retry of a `failed` run that found it held: the turn that
11619
+ * failed the run has not released it yet, or another instance holds it for a moment. Polls the
11620
+ * lease with the usual fenced take ({@link StateStore.tryLockRun}, which also takes over a lease
11621
+ * that expired; the old holder's renewal then fences it) until it is free. Returns the run, read
11622
+ * under the lease, while it is still `failed`; or the run's state when something else moved it on
11623
+ * meanwhile (nothing to retry). Throws when the lease stays held by a live execution for longer
11624
+ * than one lease period, or the engine starts draining: the retry is refused, never dropped.
11625
+ */
11626
+ async takeLeaseForRetry(runId) {
11627
+ const giveUpAt = Date.now() + this.leaseMs + LEASE_RECHECK_MAX_MS;
11628
+ for (; ; ) {
11629
+ const current = await this.store.getRun(runId);
11630
+ if (!current) throw new Error(`run ${runId} not found`);
11631
+ if (current.status !== "failed") return {
11632
+ result: this.resultOf(current)
11633
+ };
11634
+ const nowMs = this.clock();
11635
+ if (await this.store.tryLockRun(runId, this.instanceId, nowMs + this.leaseMs, nowMs)) {
11636
+ const fresh = await this.store.getRun(runId);
11637
+ if (fresh?.status === "failed") return {
11638
+ run: fresh
11639
+ };
11640
+ await this.releaseLeaseBestEffort(runId);
11227
11641
  return {
11228
- runId: run.id,
11229
- status: run.status
11642
+ result: fresh ? this.resultOf(fresh) : await this.echoCurrentStatus(runId)
11230
11643
  };
11231
11644
  }
11645
+ if (this.draining || Date.now() >= giveUpAt) {
11646
+ throw new Error(`run ${runId} could not be retried: its lease is held by ${current.lockedBy ?? "another execution"}${this.draining ? " and this engine is draining" : ""}; resume it again once that execution settles`);
11647
+ }
11648
+ const leaseLeft = (current.lockedUntil ?? nowMs) - nowMs;
11649
+ const wait = Math.min(RETRY_LEASE_POLL_MS, Math.max(10, leaseLeft + LEASE_RECHECK_SLACK_MS));
11650
+ await new Promise((resolve) => setTimeout(resolve, wait));
11232
11651
  }
11652
+ }
11653
+ /** `run` as a {@link RunResult}. */
11654
+ resultOf(run) {
11655
+ return {
11656
+ runId: run.id,
11657
+ status: run.status,
11658
+ output: run.output,
11659
+ error: run.error
11660
+ };
11661
+ }
11662
+ /** The body of {@link execute} once this instance holds `run`'s lease. */
11663
+ async executeLeased(run, fn, registered) {
11233
11664
  const settledFans = /* @__PURE__ */ new Map();
11234
11665
  this.turnSettledFans.set(run.id, settledFans);
11235
11666
  const held = this.holdExecutionLease(run.id);
@@ -11237,7 +11668,7 @@ var WorkflowEngine = class _WorkflowEngine {
11237
11668
  const served = /* @__PURE__ */ new Set();
11238
11669
  this.turnServedWakes.set(run.id, served);
11239
11670
  if (registered?.remote) await this.noteServedWakes(run.id);
11240
- const result = registered?.remote ? await this.runRemoteExecution(run, registered) : await this.runExecution(run, fn, registered);
11671
+ const result = await this.inRunTenant(run, () => registered?.remote ? this.runRemoteExecution(run, registered) : this.runExecution(run, fn, registered));
11241
11672
  if (registered?.singleton && (result.status === "completed" || result.status === "failed" || result.status === "cancelled" || result.status === "dead")) {
11242
11673
  void this.singletons.wakeNext(run).catch(() => void 0);
11243
11674
  }
@@ -11553,7 +11984,8 @@ var WorkflowEngine = class _WorkflowEngine {
11553
11984
  error: error2
11554
11985
  });
11555
11986
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11556
- namespace: run.namespace
11987
+ namespace: run.namespace,
11988
+ ...inheritTenant(run)
11557
11989
  });
11558
11990
  return {
11559
11991
  kind: "suspended"
@@ -11600,7 +12032,8 @@ var WorkflowEngine = class _WorkflowEngine {
11600
12032
  if (!handlerRun) {
11601
12033
  const handler = handoff.input;
11602
12034
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11603
- namespace: run.namespace
12035
+ namespace: run.namespace,
12036
+ ...inheritTenant(run)
11604
12037
  });
11605
12038
  }
11606
12039
  return {
@@ -12385,7 +12818,8 @@ ${run.workflowVersion}`;
12385
12818
  const existingChild = await this.store.getRun(childId);
12386
12819
  if (!existingChild) {
12387
12820
  this.startChildDeferred(cmd.workflow, cmd.input, childId, {
12388
- namespace: run.namespace
12821
+ namespace: run.namespace,
12822
+ ...inheritTenant(run)
12389
12823
  });
12390
12824
  } else {
12391
12825
  this.redeliverFinishedChild(childId, existingChild);
@@ -12504,7 +12938,7 @@ ${run.workflowVersion}`;
12504
12938
  this.awaitedRemoteSteps.set(run.id, awaitedSteps);
12505
12939
  const awaitedFans = [];
12506
12940
  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);
12941
+ const ctx = warm ? void 0 : createWorkflowCtx(this.ctxHostFor(replay, run.namespace, cont, inheritTenant(run)), run.id, compensations, run.workflow, registered?.searchAttributesSchema);
12508
12942
  try {
12509
12943
  const handoff = liveHandoff(run.id, snapshot);
12510
12944
  if (handoff && !this.cancelRequested.has(run.id)) {
@@ -12562,7 +12996,7 @@ ${run.workflowVersion}`;
12562
12996
  value: void 0
12563
12997
  });
12564
12998
  const nextId = nextContinuationId(run.id);
12565
- queueMicrotask(() => void this.start(run.workflow, err.input, nextId).catch(() => void 0));
12999
+ queueMicrotask(() => void this.start(run.workflow, err.input, nextId, inheritTenant(run)).catch(() => void 0));
12566
13000
  return {
12567
13001
  runId: run.id,
12568
13002
  status: "completed"
@@ -12835,7 +13269,7 @@ ${run.workflowVersion}`;
12835
13269
  /** The seam handed to {@link createWorkflowCtx}: the authoring API reaches durability + lifecycle
12836
13270
  * (checkpointing, dispatch, child start) through this, so the ctx primitives live in their own
12837
13271
  * module and the engine stays the orchestrator. */
12838
- ctxHostFor(replay, parentNamespace, sticky) {
13272
+ ctxHostFor(replay, parentNamespace, sticky, parentTenant) {
12839
13273
  return {
12840
13274
  store: this.store,
12841
13275
  replay,
@@ -12882,6 +13316,8 @@ ${run.workflowVersion}`;
12882
13316
  this.startChildDeferred(workflow, input, id, {
12883
13317
  priority,
12884
13318
  namespace: parentNamespace,
13319
+ // The child belongs to the parent's customer, whichever instance or context drives it.
13320
+ ...parentTenant,
12885
13321
  // Absent unless the body pinned one (`ctx.child(ref, input, { version })`) — an omitted
12886
13322
  // pin must stay omitted, so the child keeps resolving `latest` exactly as before.
12887
13323
  version,
@@ -12905,7 +13341,7 @@ ${run.workflowVersion}`;
12905
13341
  // idempotent on a terminal/cancelled run (returns its existing status without side effects), so
12906
13342
  // no extra guard is needed here for the failFast replay case (re-issuing the same cancel calls).
12907
13343
  cancelChild: /* @__PURE__ */ __name((childId) => {
12908
- queueMicrotask(() => void this.cancel(childId).catch(() => void 0));
13344
+ queueMicrotask(() => void this.cancelUnchecked(childId).catch(() => void 0));
12909
13345
  }, "cancelChild"),
12910
13346
  // Shallow-merge into the run's searchAttributes (the ctx primitive makes this exactly-once).
12911
13347
  upsertSearchAttributes: /* @__PURE__ */ __name(async (runId, attrs) => {
@@ -12932,7 +13368,7 @@ ${run.workflowVersion}`;
12932
13368
  console.warn(`[nestjs-durable] waking entity "${name}" key "${key}" failed (its op stays buffered for the next wake):`, err);
12933
13369
  }));
12934
13370
  }, "kickEntity"),
12935
- interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body), "interceptStep")
13371
+ interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body, parentTenant), "interceptStep")
12936
13372
  };
12937
13373
  }
12938
13374
  /**
@@ -12941,10 +13377,11 @@ ${run.workflowVersion}`;
12941
13377
  * paused at a breakpoint.
12942
13378
  */
12943
13379
  async continue(runId) {
13380
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
12944
13381
  const checkpoints = await this.store.listCheckpoints(runId);
12945
13382
  const bp = checkpoints.find(isBreakpoint);
12946
13383
  if (!bp) return null;
12947
- return this.signal(breakpointToken(runId, bp.seq), void 0);
13384
+ return this.signalUnchecked(breakpointToken(runId, bp.seq), void 0);
12948
13385
  }
12949
13386
  /**
12950
13387
  * Read the latest value a run published for `key` via {@link WorkflowCtx.setEvent} — a
@@ -12952,6 +13389,7 @@ ${run.workflowVersion}`;
12952
13389
  * never published that key. The suspend-model counterpart of a Temporal query.
12953
13390
  */
12954
13391
  async getEvent(runId, key) {
13392
+ if (this.restrictiveFilter() && await this.hidden(runId)) return void 0;
12955
13393
  const name = `event:${key}`;
12956
13394
  if (this.store.getLatestCheckpointByName) {
12957
13395
  const latest2 = await this.store.getLatestCheckpointByName(runId, name);
@@ -12976,7 +13414,7 @@ ${run.workflowVersion}`;
12976
13414
  * if nothing was waiting — a too-early or duplicate update).
12977
13415
  */
12978
13416
  async update(runId, name, arg) {
12979
- const run = await this.store.getRun(runId);
13417
+ const run = await this.visibleRun(runId);
12980
13418
  if (!run) return {
12981
13419
  accepted: false,
12982
13420
  reason: `run ${runId} not found`
@@ -12996,7 +13434,7 @@ ${run.workflowVersion}`;
12996
13434
  };
12997
13435
  }
12998
13436
  }
12999
- const result = await this.signal(`update:${runId}:${name}`, arg);
13437
+ const result = await this.signalUnchecked(`update:${runId}:${name}`, arg);
13000
13438
  return {
13001
13439
  accepted: true,
13002
13440
  run: result
@@ -16181,6 +16619,9 @@ var InMemoryStateStore = class {
16181
16619
  if (query.origins) {
16182
16620
  runs = runs.filter((r) => query.origins?.includes(r.origin ?? null));
16183
16621
  }
16622
+ if (query.tenantId !== void 0 || query.tenantIds !== void 0) {
16623
+ runs = runs.filter((r) => matchesTenantPredicates(r, query));
16624
+ }
16184
16625
  if (query.attributes?.length) {
16185
16626
  let candidates = null;
16186
16627
  for (const f of query.attributes) {
@@ -16254,7 +16695,7 @@ var InMemoryStateStore = class {
16254
16695
  async listSchedules(query) {
16255
16696
  const rows = [
16256
16697
  ...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));
16698
+ ].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
16699
  const offset = query.offset ?? 0;
16259
16700
  return rows.slice(offset, query.limit != null ? offset + query.limit : void 0).map((s) => structuredClone(s));
16260
16701
  }
@@ -16625,6 +17066,7 @@ export {
16625
17066
  axisIsRunColumn,
16626
17067
  bindWorkflowClass,
16627
17068
  breakpointToken,
17069
+ bufferedEventReaches,
16628
17070
  buildWorkflowDirectory,
16629
17071
  canRoute,
16630
17072
  capableWorkers,
@@ -16672,6 +17114,7 @@ export {
16672
17114
  hmacTenantVerifier,
16673
17115
  indexWaitersByRun,
16674
17116
  info,
17117
+ inheritTenant,
16675
17118
  isAnyCheckpoint,
16676
17119
  isAnyMember,
16677
17120
  isEngineMintedTag,
@@ -16698,6 +17141,7 @@ export {
16698
17141
  log,
16699
17142
  markRemoteEvent,
16700
17143
  matchesAttributes,
17144
+ matchesTenantPredicates,
16701
17145
  mergeRunFacetRows,
16702
17146
  mergeRunValueFacetRows,
16703
17147
  missingCapabilities,
@@ -16722,6 +17166,7 @@ export {
16722
17166
  prevCronFireMs,
16723
17167
  prevRRuleFireMs,
16724
17168
  queryCheckpointsOf,
17169
+ readBufferedEvent,
16725
17170
  readRunsByIds,
16726
17171
  readSearchAttributes,
16727
17172
  requiredCapabilities,
@@ -16733,6 +17178,7 @@ export {
16733
17178
  retentionKeeps,
16734
17179
  retiredHandoffName,
16735
17180
  routeFor,
17181
+ rowTenant,
16736
17182
  runCompletedEvent,
16737
17183
  runDetailEtag,
16738
17184
  runDurableExecution,
@@ -16750,6 +17196,8 @@ export {
16750
17196
  sanitizeQueueToken,
16751
17197
  scheduleRunIdAt,
16752
17198
  scheduledRunId,
17199
+ scopeBufferedEvent,
17200
+ scopeTenantQuery,
16753
17201
  settleResultsWithPlainCalls,
16754
17202
  signTenantToken,
16755
17203
  singletonAdmissionDenialPatch,
@@ -16766,6 +17214,8 @@ export {
16766
17214
  summarizeRunFromStore,
16767
17215
  summarizeTimeline,
16768
17216
  tenantGroup,
17217
+ tenantIdsFor,
17218
+ tenantVisible,
16769
17219
  toEventSubscription,
16770
17220
  traceIdOfTraceparent,
16771
17221
  triggerFailedSubscribersOf,