@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.cjs CHANGED
@@ -120,6 +120,7 @@ __export(index_exports, {
120
120
  axisIsRunColumn: () => axisIsRunColumn,
121
121
  bindWorkflowClass: () => bindWorkflowClass,
122
122
  breakpointToken: () => breakpointToken,
123
+ bufferedEventReaches: () => bufferedEventReaches,
123
124
  buildWorkflowDirectory: () => buildWorkflowDirectory,
124
125
  canRoute: () => canRoute,
125
126
  capableWorkers: () => capableWorkers,
@@ -167,6 +168,7 @@ __export(index_exports, {
167
168
  hmacTenantVerifier: () => hmacTenantVerifier,
168
169
  indexWaitersByRun: () => indexWaitersByRun,
169
170
  info: () => info,
171
+ inheritTenant: () => inheritTenant,
170
172
  isAnyCheckpoint: () => isAnyCheckpoint,
171
173
  isAnyMember: () => isAnyMember,
172
174
  isEngineMintedTag: () => isEngineMintedTag,
@@ -193,6 +195,7 @@ __export(index_exports, {
193
195
  log: () => log,
194
196
  markRemoteEvent: () => markRemoteEvent,
195
197
  matchesAttributes: () => matchesAttributes,
198
+ matchesTenantPredicates: () => matchesTenantPredicates,
196
199
  mergeRunFacetRows: () => mergeRunFacetRows,
197
200
  mergeRunValueFacetRows: () => mergeRunValueFacetRows,
198
201
  missingCapabilities: () => missingCapabilities,
@@ -217,6 +220,7 @@ __export(index_exports, {
217
220
  prevCronFireMs: () => prevCronFireMs,
218
221
  prevRRuleFireMs: () => prevRRuleFireMs,
219
222
  queryCheckpointsOf: () => queryCheckpointsOf,
223
+ readBufferedEvent: () => readBufferedEvent,
220
224
  readRunsByIds: () => readRunsByIds,
221
225
  readSearchAttributes: () => readSearchAttributes,
222
226
  requiredCapabilities: () => requiredCapabilities,
@@ -228,6 +232,7 @@ __export(index_exports, {
228
232
  retentionKeeps: () => retentionKeeps,
229
233
  retiredHandoffName: () => retiredHandoffName,
230
234
  routeFor: () => routeFor,
235
+ rowTenant: () => rowTenant,
231
236
  runCompletedEvent: () => runCompletedEvent,
232
237
  runDetailEtag: () => runDetailEtag,
233
238
  runDurableExecution: () => runDurableExecution,
@@ -245,6 +250,8 @@ __export(index_exports, {
245
250
  sanitizeQueueToken: () => sanitizeQueueToken,
246
251
  scheduleRunIdAt: () => scheduleRunIdAt,
247
252
  scheduledRunId: () => scheduledRunId,
253
+ scopeBufferedEvent: () => scopeBufferedEvent,
254
+ scopeTenantQuery: () => scopeTenantQuery,
248
255
  settleResultsWithPlainCalls: () => settleResultsWithPlainCalls,
249
256
  signTenantToken: () => signTenantToken,
250
257
  singletonAdmissionDenialPatch: () => singletonAdmissionDenialPatch,
@@ -261,6 +268,8 @@ __export(index_exports, {
261
268
  summarizeRunFromStore: () => summarizeRunFromStore,
262
269
  summarizeTimeline: () => summarizeTimeline,
263
270
  tenantGroup: () => tenantGroup,
271
+ tenantIdsFor: () => tenantIdsFor,
272
+ tenantVisible: () => tenantVisible,
264
273
  toEventSubscription: () => toEventSubscription,
265
274
  traceIdOfTraceparent: () => traceIdOfTraceparent,
266
275
  triggerFailedSubscribersOf: () => triggerFailedSubscribersOf,
@@ -1044,7 +1053,7 @@ var TERMINAL_RUN_STATUSES = [
1044
1053
  ];
1045
1054
  function isNonEmptyRunScope(scope) {
1046
1055
  if (!scope) return false;
1047
- 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;
1056
+ 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;
1048
1057
  }
1049
1058
  __name(isNonEmptyRunScope, "isNonEmptyRunScope");
1050
1059
  var PARENT_CLOSE_TAG_PREFIX = "parent-close:";
@@ -1117,6 +1126,31 @@ function acceptingSubscription(subscriptions, payload) {
1117
1126
  };
1118
1127
  }
1119
1128
  __name(acceptingSubscription, "acceptingSubscription");
1129
+ var BUFFERED_EVENT_TENANTS = "__durableEventTenants";
1130
+ function scopeBufferedEvent(payload, tenantIds) {
1131
+ return tenantIds === void 0 ? payload : {
1132
+ [BUFFERED_EVENT_TENANTS]: tenantIds,
1133
+ payload
1134
+ };
1135
+ }
1136
+ __name(scopeBufferedEvent, "scopeBufferedEvent");
1137
+ function readBufferedEvent(stored) {
1138
+ if (stored !== null && typeof stored === "object" && Array.isArray(stored[BUFFERED_EVENT_TENANTS]) && Object.keys(stored).length === 2 && "payload" in stored) {
1139
+ const scoped = stored;
1140
+ return {
1141
+ payload: scoped.payload,
1142
+ tenantIds: scoped[BUFFERED_EVENT_TENANTS]
1143
+ };
1144
+ }
1145
+ return {
1146
+ payload: stored
1147
+ };
1148
+ }
1149
+ __name(readBufferedEvent, "readBufferedEvent");
1150
+ function bufferedEventReaches(tenantIds, tenantId) {
1151
+ return tenantIds === void 0 || tenantIds.includes(tenantId ?? null);
1152
+ }
1153
+ __name(bufferedEventReaches, "bufferedEventReaches");
1120
1154
 
1121
1155
  // src/lifecycle-events.ts
1122
1156
  function runCompletedEvent(workflow) {
@@ -1906,7 +1940,8 @@ async function runStepHandler(task, handler) {
1906
1940
  workflow: void 0,
1907
1941
  name: task.name,
1908
1942
  seq: task.seq,
1909
- attempt: task.attempt
1943
+ attempt: task.attempt,
1944
+ context: task.context
1910
1945
  },
1911
1946
  // Outside any ambient workflow ctx: an in-process transport runs the handler on the parent
1912
1947
  // body's async path, but a handler is not the body (see `runOutsideWorkflowCtx`).
@@ -2247,10 +2282,14 @@ var Entities = class {
2247
2282
  };
2248
2283
 
2249
2284
  // src/event-accumulators.ts
2250
- function accumulatorRunId(target, key) {
2251
- if (key === void 0) return `__evtacc__:${target}`;
2252
- const escaped = encodeURIComponent(key).replace(/[~!'()*.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
2253
- return `__evtacc__:${target}:${escaped}`;
2285
+ function escapeIdPart(value) {
2286
+ return encodeURIComponent(value).replace(/[~!'()*.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
2287
+ }
2288
+ __name(escapeIdPart, "escapeIdPart");
2289
+ function accumulatorRunId(target, key, tenant) {
2290
+ const base = tenant === void 0 ? "__evtacc__" : `__evtacc__@${escapeIdPart(tenant)}`;
2291
+ if (key === void 0) return `${base}:${target}`;
2292
+ return `${base}:${target}:${escapeIdPart(key)}`;
2254
2293
  }
2255
2294
  __name(accumulatorRunId, "accumulatorRunId");
2256
2295
  var ACCUMULATOR_SEEN_MAX = 1e3;
@@ -2295,7 +2334,7 @@ var SeenEvents = class SeenEvents2 {
2295
2334
  } : rest;
2296
2335
  }
2297
2336
  };
2298
- var accToken = /* @__PURE__ */ __name((input) => accumulatorRunId(input.target, input.key), "accToken");
2337
+ var accToken = /* @__PURE__ */ __name((input) => accumulatorRunId(input.target, input.key, input.tenant), "accToken");
2299
2338
  var EventAccumulators = class {
2300
2339
  static {
2301
2340
  __name(this, "EventAccumulators");
@@ -2314,8 +2353,12 @@ var EventAccumulators = class {
2314
2353
  * Route an `onEvent` payload into its target's debounce/batch accumulator: the target's one, or
2315
2354
  * with a `key`, the one for `String(config.key(payload))`. A `key` that throws rejects the route.
2316
2355
  * With `id`, the accumulator counts the event once however many times it is routed.
2356
+ *
2357
+ * `tenant` is the tenant the event belongs to when tenancy is on: a tenant gets its own
2358
+ * accumulator, stamped with it (so its target runs are too); `null` routes into the shared one,
2359
+ * stamped with no tenant. Undefined (tenancy off) starts the accumulator as before.
2317
2360
  */
2318
- route(target, config, payload, id) {
2361
+ route(target, config, payload, id, tenant) {
2319
2362
  const input = {
2320
2363
  target,
2321
2364
  windowMs: config.windowMs,
@@ -2324,6 +2367,9 @@ var EventAccumulators = class {
2324
2367
  } : {},
2325
2368
  ...config.key ? {
2326
2369
  key: String(config.key(payload))
2370
+ } : {},
2371
+ ...tenant ? {
2372
+ tenant: tenant.id
2327
2373
  } : {}
2328
2374
  };
2329
2375
  const workflow = config.mode === "debounce" ? "__evt_debounce" : "__evt_batch";
@@ -2333,10 +2379,18 @@ var EventAccumulators = class {
2333
2379
  id,
2334
2380
  payload
2335
2381
  };
2382
+ const opts = tenant === void 0 ? void 0 : tenant === null ? {
2383
+ tenantId: null
2384
+ } : {
2385
+ tenantId: tenant.id,
2386
+ ...tenant.kind !== void 0 ? {
2387
+ tenantKind: tenant.kind
2388
+ } : {}
2389
+ };
2336
2390
  return this.host.signalWithStart(workflow, input, token, {
2337
2391
  token,
2338
2392
  payload: signal
2339
- });
2393
+ }, opts);
2340
2394
  }
2341
2395
  /** Fire the target with the LAST payload once events have been quiet for `windowMs`. */
2342
2396
  async debounce(ctx, input) {
@@ -3824,6 +3878,78 @@ function remember(memo, key, runId) {
3824
3878
  }
3825
3879
  __name(remember, "remember");
3826
3880
 
3881
+ // src/tenancy.ts
3882
+ function tenantVisible(row, filter) {
3883
+ const id = row.tenantId ?? null;
3884
+ switch (filter.mode) {
3885
+ case "system":
3886
+ case "all":
3887
+ return true;
3888
+ case "tenantless":
3889
+ return id === null;
3890
+ case "tenant":
3891
+ return id === filter.tenantId || id === null && filter.nullRows === "shared";
3892
+ }
3893
+ }
3894
+ __name(tenantVisible, "tenantVisible");
3895
+ function tenantIdsFor(filter) {
3896
+ switch (filter.mode) {
3897
+ case "system":
3898
+ case "all":
3899
+ return void 0;
3900
+ case "tenantless":
3901
+ return [
3902
+ null
3903
+ ];
3904
+ case "tenant":
3905
+ return filter.nullRows === "shared" ? [
3906
+ filter.tenantId,
3907
+ null
3908
+ ] : [
3909
+ filter.tenantId
3910
+ ];
3911
+ }
3912
+ }
3913
+ __name(tenantIdsFor, "tenantIdsFor");
3914
+ function scopeTenantQuery(query, filter) {
3915
+ const allowed = tenantIdsFor(filter);
3916
+ if (allowed === void 0) return query;
3917
+ const tenantIds = query.tenantIds ? query.tenantIds.filter((id) => allowed.includes(id)) : allowed;
3918
+ return {
3919
+ ...query,
3920
+ tenantIds
3921
+ };
3922
+ }
3923
+ __name(scopeTenantQuery, "scopeTenantQuery");
3924
+ function rowTenant(row) {
3925
+ if (row.tenantId == null) return void 0;
3926
+ return row.tenantKind != null ? {
3927
+ id: row.tenantId,
3928
+ kind: row.tenantKind
3929
+ } : {
3930
+ id: row.tenantId
3931
+ };
3932
+ }
3933
+ __name(rowTenant, "rowTenant");
3934
+ function inheritTenant(row) {
3935
+ return row.tenantId == null ? {
3936
+ tenantId: null
3937
+ } : {
3938
+ tenantId: row.tenantId,
3939
+ ...row.tenantKind != null ? {
3940
+ tenantKind: row.tenantKind
3941
+ } : {}
3942
+ };
3943
+ }
3944
+ __name(inheritTenant, "inheritTenant");
3945
+ function matchesTenantPredicates(row, query) {
3946
+ const id = row.tenantId ?? null;
3947
+ if (query.tenantId !== void 0 && id !== query.tenantId) return false;
3948
+ if (query.tenantIds !== void 0 && !query.tenantIds.includes(id)) return false;
3949
+ return true;
3950
+ }
3951
+ __name(matchesTenantPredicates, "matchesTenantPredicates");
3952
+
3827
3953
  // src/schedules.ts
3828
3954
  var ScheduleAlreadyExistsError = class extends Error {
3829
3955
  static {
@@ -3881,6 +4007,16 @@ var ScheduleClient = class {
3881
4007
  listSchedules: /* @__PURE__ */ __name((q) => s.listSchedules.call(s, q), "listSchedules")
3882
4008
  };
3883
4009
  }
4010
+ filter() {
4011
+ return this.host.tenantFilter?.() ?? {
4012
+ mode: "system"
4013
+ };
4014
+ }
4015
+ /** The schedule `id` if it exists and the caller may see it (tenancy), else null. */
4016
+ async visible(id) {
4017
+ const record = await this.requireStore().getSchedule(id);
4018
+ return record && tenantVisible(record, this.filter()) ? record : null;
4019
+ }
3884
4020
  /** Create a schedule. Throws {@link ScheduleAlreadyExistsError} if the id is taken. */
3885
4021
  async create(opts) {
3886
4022
  const store = this.requireStore();
@@ -3894,19 +4030,24 @@ var ScheduleClient = class {
3894
4030
  */
3895
4031
  async upsert(opts) {
3896
4032
  const store = this.requireStore();
3897
- return this.write(opts, await store.getSchedule(opts.id));
4033
+ const existing = await store.getSchedule(opts.id);
4034
+ if (existing && !tenantVisible(existing, this.filter())) {
4035
+ throw new ScheduleAlreadyExistsError(opts.id);
4036
+ }
4037
+ return this.write(opts, existing);
3898
4038
  }
3899
- /** The schedule `id`, or null. */
4039
+ /** The schedule `id`, or null (also null for another tenant's schedule). */
3900
4040
  async get(id) {
3901
- const record = await this.requireStore().getSchedule(id);
4041
+ const record = await this.visible(id);
3902
4042
  return record ? describe(record) : null;
3903
4043
  }
3904
- /** Schedules matching `query`, soonest-due first. */
4044
+ /** Schedules matching `query` (and visible to the caller's tenant), soonest-due first. */
3905
4045
  async list(query = {}) {
3906
- return (await this.requireStore().listSchedules(query)).map(describe);
4046
+ return (await this.requireStore().listSchedules(scopeTenantQuery(query, this.filter()))).map(describe);
3907
4047
  }
3908
4048
  /** Delete the schedule. Runs it already started are left alone. Returns whether it existed. */
3909
- delete(id) {
4049
+ async delete(id) {
4050
+ if (!await this.visible(id)) return false;
3910
4051
  return this.requireStore().deleteSchedule(id);
3911
4052
  }
3912
4053
  /** Stop firing until {@link resume}. `note` records why (shown by `get`/`list`). */
@@ -4041,10 +4182,34 @@ var ScheduleClient = class {
4041
4182
  return !!prev && !TERMINAL_RUN_STATUSES.includes(prev.status);
4042
4183
  }
4043
4184
  async mustGet(id) {
4044
- const record = await this.requireStore().getSchedule(id);
4185
+ const record = await this.visible(id);
4045
4186
  if (!record) throw new ScheduleNotFoundError(id);
4046
4187
  return record;
4047
4188
  }
4189
+ /** Explicit `opts.tenantId` → the existing schedule's tenant (upsert) → the context tenant → none. */
4190
+ scheduleTenant(opts, existing) {
4191
+ let tenant;
4192
+ if (opts.tenantId !== void 0) {
4193
+ tenant = opts.tenantId === null ? void 0 : {
4194
+ id: opts.tenantId,
4195
+ kind: opts.tenantKind
4196
+ };
4197
+ } else if (existing) {
4198
+ tenant = existing.tenantId == null ? void 0 : {
4199
+ id: existing.tenantId,
4200
+ kind: existing.tenantKind ?? void 0
4201
+ };
4202
+ } else {
4203
+ tenant = this.host.tenant?.();
4204
+ }
4205
+ if (!tenant) return {};
4206
+ return tenant.kind !== void 0 ? {
4207
+ tenantId: tenant.id,
4208
+ tenantKind: tenant.kind
4209
+ } : {
4210
+ tenantId: tenant.id
4211
+ };
4212
+ }
4048
4213
  async write(opts, existing) {
4049
4214
  const store = this.requireStore();
4050
4215
  const spec = toSpec(opts);
@@ -4063,6 +4228,7 @@ var ScheduleClient = class {
4063
4228
  ...existing?.state ?? {},
4064
4229
  window
4065
4230
  }),
4231
+ ...this.scheduleTenant(opts, existing),
4066
4232
  createdAt: existing?.createdAt ?? new Date(now),
4067
4233
  updatedAt: new Date(now)
4068
4234
  };
@@ -4145,7 +4311,10 @@ function startOptions(record) {
4145
4311
  namespace: record.namespace,
4146
4312
  searchAttributes: spec.searchAttributes,
4147
4313
  priority: spec.priority,
4148
- concurrency: spec.concurrency
4314
+ concurrency: spec.concurrency,
4315
+ // Every fire belongs to the schedule's customer (or explicitly to none), never to whichever
4316
+ // poller or request happened to fire it.
4317
+ ...inheritTenant(record)
4149
4318
  });
4150
4319
  }
4151
4320
  __name(startOptions, "startOptions");
@@ -4175,6 +4344,8 @@ function describe(record) {
4175
4344
  lastRunId: state.lastRunId,
4176
4345
  fires: state.fires ?? 0,
4177
4346
  lastError: state.lastError,
4347
+ tenantId: record.tenantId ?? void 0,
4348
+ tenantKind: record.tenantKind ?? void 0,
4178
4349
  createdAt: record.createdAt,
4179
4350
  updatedAt: record.updatedAt
4180
4351
  });
@@ -5528,8 +5699,14 @@ function createWorkflowCtx(host, runId, compensations, workflow = "", searchAttr
5528
5699
  }, "consumeBuffered");
5529
5700
  const consumeBufferedEvent = /* @__PURE__ */ __name(async (name, match, token, seq) => {
5530
5701
  const candidates = await store.listBufferedEvents(name, EVENT_BUFFER_SCAN_LIMIT);
5702
+ let runTenantId;
5531
5703
  for (const candidate of candidates) {
5532
- if (!eventMatches(candidate.payload, match ?? {})) continue;
5704
+ const { payload, tenantIds } = readBufferedEvent(candidate.payload);
5705
+ if (!eventMatches(payload, match ?? {})) continue;
5706
+ if (tenantIds !== void 0) {
5707
+ runTenantId ??= store.getRun(runId).then((run) => run?.tenantId ?? null);
5708
+ if (!bufferedEventReaches(tenantIds, await runTenantId)) continue;
5709
+ }
5533
5710
  if (!await store.removeBufferedEvent(candidate.id)) continue;
5534
5711
  await store.removeSignalWaiter({
5535
5712
  token,
@@ -5541,10 +5718,10 @@ function createWorkflowCtx(host, runId, compensations, workflow = "", searchAttr
5541
5718
  seq,
5542
5719
  name: `signal:${token}`,
5543
5720
  kind: "signal",
5544
- output: candidate.payload
5721
+ output: payload
5545
5722
  }));
5546
5723
  return {
5547
- value: candidate.payload
5724
+ value: payload
5548
5725
  };
5549
5726
  }
5550
5727
  return null;
@@ -6709,6 +6886,8 @@ var WorkflowEngine = class _WorkflowEngine {
6709
6886
  context;
6710
6887
  /** Establish the originating context ambiently around a local step body (see {@link WorkflowEngineDeps.rehydrate}). Default passthrough. */
6711
6888
  rehydrate;
6889
+ /** Tenancy seam (see {@link WorkflowEngineDeps.tenancy}); undefined = off. */
6890
+ tenancy;
6712
6891
  compensationRetries;
6713
6892
  /** Persist a `running` checkpoint at the start of a local step body (see {@link WorkflowEngineDeps.trackStepStart}). */
6714
6893
  trackStepStart;
@@ -6918,6 +7097,7 @@ var WorkflowEngine = class _WorkflowEngine {
6918
7097
  this.traceparent = deps.traceparent;
6919
7098
  this.context = deps.context;
6920
7099
  this.rehydrate = deps.rehydrate ?? ((_carrier, fn) => fn());
7100
+ this.tenancy = deps.tenancy;
6921
7101
  this.compensationRetries = Math.max(1, deps.compensationRetries ?? 1);
6922
7102
  this.trackStepStart = deps.trackStepStart ?? true;
6923
7103
  this.localWork = new BoundedRunner(LOCAL_RUN_CONCURRENCY);
@@ -6947,7 +7127,9 @@ var WorkflowEngine = class _WorkflowEngine {
6947
7127
  this.schedules = new ScheduleClient(this.store, {
6948
7128
  start: /* @__PURE__ */ __name((workflow, input, runId, opts) => this.start(workflow, input, runId, opts), "start"),
6949
7129
  getRun: /* @__PURE__ */ __name((runId) => this.store.getRun(runId), "getRun"),
6950
- isDraining: /* @__PURE__ */ __name(() => this.draining, "isDraining")
7130
+ isDraining: /* @__PURE__ */ __name(() => this.draining, "isDraining"),
7131
+ tenant: /* @__PURE__ */ __name(() => this.tenancy?.current(), "tenant"),
7132
+ tenantFilter: /* @__PURE__ */ __name(() => this.tenantFilter(), "tenantFilter")
6951
7133
  }, {
6952
7134
  namespace: this.namespace,
6953
7135
  clock: this.clock
@@ -7051,7 +7233,18 @@ var WorkflowEngine = class _WorkflowEngine {
7051
7233
  }
7052
7234
  }
7053
7235
  });
7054
- this.accumulators = new EventAccumulators(this);
7236
+ this.accumulators = new EventAccumulators({
7237
+ register: /* @__PURE__ */ __name((name, version, fn, opts) => this.register(name, version, fn, opts), "register"),
7238
+ // The engine picks the accumulator's tenant itself, so its signal is the engine's own
7239
+ // delivery: not subject to the publisher's tenancy filter.
7240
+ signalWithStart: /* @__PURE__ */ __name(async (workflow, input, runId, signal, opts) => {
7241
+ await this.start(workflow, input, runId, opts);
7242
+ await this.signalUnchecked(signal.token, signal.payload);
7243
+ return {
7244
+ runId
7245
+ };
7246
+ }, "signalWithStart")
7247
+ });
7055
7248
  this.entities = new Entities(this, {
7056
7249
  bufferSignal: /* @__PURE__ */ __name((token, payload) => this.store.bufferSignal(token, payload), "bufferSignal"),
7057
7250
  wakeWaiter: /* @__PURE__ */ __name((token, payload) => this.wakeSignalWaiter(token, payload), "wakeWaiter"),
@@ -7527,15 +7720,19 @@ var WorkflowEngine = class _WorkflowEngine {
7527
7720
  * time from {@link context} — the SAME reader stamped on dispatched remote tasks — so a local step
7528
7721
  * sees the live tenant / user / trace ids ambiently (via the {@link rehydrate} bridge). Default
7529
7722
  * `rehydrate` is a passthrough, so this is byte-identical to a bare body call when unwired.
7723
+ *
7724
+ * The run row's tenant is re-applied INSIDE the rehydrated context: an app carrier (a custom
7725
+ * `serialize`/`deserialize`) may not carry the tenant, and its deserializer would otherwise replace
7726
+ * the tenant the turn was started with. Local steps always see the row's tenant.
7530
7727
  */
7531
- interceptStep(invocation, body) {
7728
+ interceptStep(invocation, body, tenant) {
7532
7729
  const carrier = this.context?.();
7533
7730
  const run = /* @__PURE__ */ __name(() => {
7534
7731
  if (this.interceptors.length === 0) return body();
7535
7732
  const chain = this.interceptors.reduceRight((next, interceptor) => () => interceptor(invocation, next), body);
7536
7733
  return chain();
7537
7734
  }, "run");
7538
- return this.rehydrate(carrier, run);
7735
+ return this.rehydrate(carrier, () => tenant ? this.inRunTenant(tenant, run) : run());
7539
7736
  }
7540
7737
  /**
7541
7738
  * Be notified when a run is cancelled — on ANY instance, via the transport control plane. A
@@ -7726,9 +7923,12 @@ var WorkflowEngine = class _WorkflowEngine {
7726
7923
  * an announcement carries no `where` or `input`. `routeIdOf` names the event for a subscriber's
7727
7924
  * debounce/batch accumulator, which counts an id once. Returns the subscribers reached, with the
7728
7925
  * run each started (none when the payload went into its debounce/batch accumulator), and the ones
7729
- * that could not be started, with why.
7926
+ * that could not be started, with why. `batchTenant` is the tenant whose debounce/batch accumulator
7927
+ * the payload goes into (see {@link EventAccumulators.route}). `runTenant`, when set, is the tenant
7928
+ * every directly started subscriber run gets (a lifecycle event: the settled run's), instead of the
7929
+ * context's at publish time (which may be none, e.g. the background retry pass).
7730
7930
  */
7731
- async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf) {
7931
+ async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf, batchTenant, runTenant) {
7732
7932
  const reached = [];
7733
7933
  const failed = [];
7734
7934
  for (const [workflow, subscriptions] of this.eventTriggers.get(name) ?? []) {
@@ -7745,13 +7945,13 @@ var WorkflowEngine = class _WorkflowEngine {
7745
7945
  const input = accepted.input ? accepted.input(payload) : payload;
7746
7946
  const batch = this.latest.get(workflow)?.eventBatch;
7747
7947
  if (batch) {
7748
- await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow));
7948
+ await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow), batchTenant);
7749
7949
  reached.push({
7750
7950
  workflow
7751
7951
  });
7752
7952
  } else {
7753
7953
  const runId = runIdOf(workflow);
7754
- await this.start(workflow, input, runId);
7954
+ await this.start(workflow, input, runId, runTenant);
7755
7955
  reached.push({
7756
7956
  workflow,
7757
7957
  runId
@@ -7769,7 +7969,7 @@ var WorkflowEngine = class _WorkflowEngine {
7769
7969
  if (local?.has(workflow) || only && !only.has(workflow)) continue;
7770
7970
  try {
7771
7971
  const runId = runIdOf(workflow);
7772
- await this.start(workflow, payload, runId);
7972
+ await this.start(workflow, payload, runId, runTenant);
7773
7973
  reached.push({
7774
7974
  workflow,
7775
7975
  runId
@@ -8126,11 +8326,12 @@ var WorkflowEngine = class _WorkflowEngine {
8126
8326
  const triggers = this.eventTriggers.get(lifecycleEventName(run.workflow, kind));
8127
8327
  if (!triggers || !this.servesNamespace(run.namespace)) return out;
8128
8328
  let payload;
8329
+ const tenant = this.lifecycleBatchTenant(run)?.id;
8129
8330
  for (const [workflow, subscriptions] of triggers) {
8130
8331
  const batch = this.latest.get(workflow)?.eventBatch;
8131
8332
  if (!batch) continue;
8132
8333
  if (!batch.key && subscriptions.every((sub2) => !sub2.where)) {
8133
- out.set(workflow, accumulatorRunId(workflow));
8334
+ out.set(workflow, accumulatorRunId(workflow, void 0, tenant));
8134
8335
  continue;
8135
8336
  }
8136
8337
  try {
@@ -8138,7 +8339,7 @@ var WorkflowEngine = class _WorkflowEngine {
8138
8339
  const { accepted } = acceptingSubscription(subscriptions, payload);
8139
8340
  if (!accepted) continue;
8140
8341
  const input = accepted.input ? accepted.input(payload) : payload;
8141
- out.set(workflow, accumulatorRunId(workflow, batch.key ? String(batch.key(input)) : void 0));
8342
+ out.set(workflow, accumulatorRunId(workflow, batch.key ? String(batch.key(input)) : void 0, tenant));
8142
8343
  } catch {
8143
8344
  out.set(workflow, void 0);
8144
8345
  }
@@ -8317,7 +8518,9 @@ var WorkflowEngine = class _WorkflowEngine {
8317
8518
  */
8318
8519
  async triggeredRuns(source) {
8319
8520
  const run = typeof source === "string" ? await this.store.getRun(source) : source;
8320
- return run ? triggeredRunsOf(run) : [];
8521
+ if (!run) return [];
8522
+ const filter = this.restrictiveFilter();
8523
+ return filter && !tenantVisible(run, filter) ? [] : triggeredRunsOf(run);
8321
8524
  }
8322
8525
  /** The live path of {@link publishSettled}: right after this instance settled the run. */
8323
8526
  publishLifecycle(event) {
@@ -8450,7 +8653,18 @@ var WorkflowEngine = class _WorkflowEngine {
8450
8653
  }
8451
8654
  if (targets.length === 0 && owe.size === 0 && !resolved) return void 0;
8452
8655
  const runIdOf = /* @__PURE__ */ __name((sub2) => lifecycleRunId(run.id, kind, sub2), "runIdOf");
8453
- const { reached, failed } = targets.length > 0 ? await this.startSubscribers(name, lifecycleEventOf(run), runIdOf, new Set(targets), remote, runIdOf) : {
8656
+ const { reached, failed } = targets.length > 0 ? await this.startSubscribers(
8657
+ name,
8658
+ lifecycleEventOf(run),
8659
+ runIdOf,
8660
+ new Set(targets),
8661
+ remote,
8662
+ runIdOf,
8663
+ this.lifecycleBatchTenant(run),
8664
+ // The downstream run belongs to the settled run's customer, whoever publishes it (the
8665
+ // turn that settled it, or the background retry pass outside any request).
8666
+ inheritTenant(run)
8667
+ ) : {
8454
8668
  reached: [],
8455
8669
  failed: []
8456
8670
  };
@@ -8993,14 +9207,7 @@ var WorkflowEngine = class _WorkflowEngine {
8993
9207
  }
8994
9208
  await registered.validateInput?.(input);
8995
9209
  const prior = await this.store.getRun(runId);
8996
- if (prior) {
8997
- return {
8998
- runId,
8999
- status: prior.status,
9000
- output: prior.output,
9001
- error: prior.error
9002
- };
9003
- }
9210
+ if (prior) return this.existingStartResult(prior);
9004
9211
  const quota = await resolveConcurrency(opts?.concurrency, registered.concurrency, input);
9005
9212
  if (quota) await assertConcurrency(this.store, name, quota);
9006
9213
  const now = /* @__PURE__ */ new Date();
@@ -9040,6 +9247,7 @@ var WorkflowEngine = class _WorkflowEngine {
9040
9247
  tags,
9041
9248
  searchAttributes: opts?.searchAttributes,
9042
9249
  priority: opts?.priority,
9250
+ ...this.startTenant(opts),
9043
9251
  createdAt: now,
9044
9252
  updatedAt: now
9045
9253
  };
@@ -9048,12 +9256,7 @@ var WorkflowEngine = class _WorkflowEngine {
9048
9256
  } catch (err) {
9049
9257
  const winner = await this.store.getRun(runId).catch(() => null);
9050
9258
  if (!winner) throw err;
9051
- return {
9052
- runId,
9053
- status: winner.status,
9054
- output: winner.output,
9055
- error: winner.error
9056
- };
9259
+ return this.existingStartResult(winner);
9057
9260
  }
9058
9261
  if (delayed) {
9059
9262
  this.emit({
@@ -9083,13 +9286,125 @@ var WorkflowEngine = class _WorkflowEngine {
9083
9286
  status: "pending"
9084
9287
  };
9085
9288
  }
9086
- /** Read a run's current persisted state (or null if unknown). A thin pass-through to the store. */
9289
+ /**
9290
+ * The tenant columns a new run gets: an explicit `opts.tenantId` (`null` = none) wins, else the
9291
+ * context tenant when tenancy is on, else none (no keys at all, so a run row is unchanged when
9292
+ * tenancy is off).
9293
+ */
9294
+ startTenant(opts) {
9295
+ const tenant = opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
9296
+ id: opts.tenantId,
9297
+ kind: opts.tenantKind
9298
+ } : this.tenancy?.current();
9299
+ if (!tenant) return {};
9300
+ return tenant.kind !== void 0 ? {
9301
+ tenantId: tenant.id,
9302
+ tenantKind: tenant.kind
9303
+ } : {
9304
+ tenantId: tenant.id
9305
+ };
9306
+ }
9307
+ /**
9308
+ * The context tenant a run started NOW would be stamped with (tenancy on), else undefined. For code
9309
+ * that records a start to replay it later outside the request, e.g. a transactional outbox.
9310
+ */
9311
+ contextTenant() {
9312
+ return this.tenancy?.current();
9313
+ }
9314
+ /**
9315
+ * The tenant whose debounce/batch accumulator a named event published now goes into: the
9316
+ * publisher's tenant, or `null` (the shared accumulator, no tenant) for a tenantless, `system` or
9317
+ * `all` publisher. Undefined when tenancy is off (the accumulator starts as it always did).
9318
+ */
9319
+ publishBatchTenant() {
9320
+ if (!this.tenancy) return void 0;
9321
+ const filter = this.tenantFilter();
9322
+ if (filter.mode !== "tenant") return null;
9323
+ const current = this.tenancy.current();
9324
+ return current?.id === filter.tenantId ? current : {
9325
+ id: filter.tenantId
9326
+ };
9327
+ }
9328
+ /**
9329
+ * The tenant whose debounce/batch accumulator `run`'s lifecycle event goes into: the run's own
9330
+ * (its publisher), or `null` for a run with no tenant. Undefined when tenancy is off.
9331
+ */
9332
+ lifecycleBatchTenant(run) {
9333
+ if (!this.tenancy) return void 0;
9334
+ return rowTenant(run) ?? null;
9335
+ }
9336
+ /** The matching filter for an app-facing call made now: `system` (sees all) when tenancy is off. */
9337
+ tenantFilter() {
9338
+ return this.tenancy?.filter() ?? {
9339
+ mode: "system"
9340
+ };
9341
+ }
9342
+ /**
9343
+ * The run `runId` if the caller may see it under the tenancy matching rule, else null — an
9344
+ * invisible run reads exactly like a missing one (not found, never forbidden).
9345
+ */
9346
+ visibleRun(runId) {
9347
+ const filter = this.restrictiveFilter();
9348
+ if (!filter) return this.store.getRun(runId);
9349
+ return this.store.getRun(runId).then((run) => run && tenantVisible(run, filter) ? run : null);
9350
+ }
9351
+ /**
9352
+ * What `start` returns for an id that already has a run. A run the caller may not see (tenancy)
9353
+ * returns its id and status only: never its output or error.
9354
+ */
9355
+ existingStartResult(run) {
9356
+ const filter = this.restrictiveFilter();
9357
+ if (filter && !tenantVisible(run, filter)) return {
9358
+ runId: run.id,
9359
+ status: run.status
9360
+ };
9361
+ return {
9362
+ runId: run.id,
9363
+ status: run.status,
9364
+ output: run.output,
9365
+ error: run.error
9366
+ };
9367
+ }
9368
+ /** The caller's filter when it can hide rows (`tenant` / `tenantless`), else undefined. */
9369
+ restrictiveFilter() {
9370
+ const filter = this.tenantFilter();
9371
+ return filter.mode === "system" || filter.mode === "all" ? void 0 : filter;
9372
+ }
9373
+ /**
9374
+ * True when the caller may NOT act on `runId` (it is missing or invisible to it). Callers guard
9375
+ * with `this.restrictiveFilter() && (await this.hidden(runId))`, so nothing is awaited when the
9376
+ * caller sees everything.
9377
+ */
9378
+ async hidden(runId) {
9379
+ return await this.visibleRun(runId) === null;
9380
+ }
9381
+ /**
9382
+ * Narrow `query` to the runs the caller may see (the tenancy matching rule). Use it before an
9383
+ * app-facing `store.listRuns`; a no-op when tenancy is off or the caller is `system`/`all`.
9384
+ */
9385
+ scopeRunQuery(query) {
9386
+ return scopeTenantQuery(query, this.tenantFilter());
9387
+ }
9388
+ /**
9389
+ * Run `fn` with `run`'s tenant restored as the context tenant (so a step body, a downstream lib and
9390
+ * every dispatched task's context carrier see it), whatever path drove the turn: a request, a
9391
+ * timer, a signal, recovery or a worker. A run with no tenant, or tenancy off, runs `fn` as is.
9392
+ */
9393
+ inRunTenant(run, fn) {
9394
+ const tenant = this.tenancy ? rowTenant(run) : void 0;
9395
+ return tenant && this.tenancy ? this.tenancy.run(tenant, fn) : fn();
9396
+ }
9397
+ /**
9398
+ * Read a run's current persisted state (or null if unknown). With tenancy on, a run of another
9399
+ * tenant reads as null (see {@link WorkflowEngineDeps.tenancy}).
9400
+ */
9087
9401
  getRun(runId) {
9088
- return this.store.getRun(runId);
9402
+ return this.visibleRun(runId);
9089
9403
  }
9090
- /** A run's full checkpoint timeline, ordered by seq. A thin pass-through to the store (it is what
9091
- * the testing kit's `captureHistory` reads, next to {@link getRun}). */
9092
- listCheckpoints(runId) {
9404
+ /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9405
+ * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9406
+ async listCheckpoints(runId) {
9407
+ if (this.restrictiveFilter() && await this.hidden(runId)) return [];
9093
9408
  return this.store.listCheckpoints(runId);
9094
9409
  }
9095
9410
  /**
@@ -9101,6 +9416,13 @@ var WorkflowEngine = class _WorkflowEngine {
9101
9416
  * terminal too.
9102
9417
  */
9103
9418
  resume(runId) {
9419
+ if (this.restrictiveFilter()) {
9420
+ return this.hidden(runId).then((hidden) => {
9421
+ if (hidden) throw new Error(`run ${runId} not found`);
9422
+ this.noteWakeReason(runId, void 0);
9423
+ return this.resumeRun(runId, true);
9424
+ });
9425
+ }
9104
9426
  this.noteWakeReason(runId, void 0);
9105
9427
  return this.resumeRun(runId, true);
9106
9428
  }
@@ -9979,10 +10301,12 @@ var WorkflowEngine = class _WorkflowEngine {
9979
10301
  await this.store.removeBufferedEvent(candidate.id);
9980
10302
  continue;
9981
10303
  }
9982
- if (!eventMatches(candidate.payload, match)) continue;
10304
+ const { payload, tenantIds } = readBufferedEvent(candidate.payload);
10305
+ if (!bufferedEventReaches(tenantIds, run.tenantId)) continue;
10306
+ if (!eventMatches(payload, match)) continue;
9983
10307
  if (!await this.store.removeBufferedEvent(candidate.id)) continue;
9984
10308
  await this.store.removeSignalWaiter(waiter);
9985
- const settled = await this.deliverSignal(waiter, candidate.payload, true);
10309
+ const settled = await this.deliverSignal(waiter, payload, true);
9986
10310
  return settled ?? {
9987
10311
  runId: run.id,
9988
10312
  status: run.status
@@ -10021,6 +10345,7 @@ var WorkflowEngine = class _WorkflowEngine {
10021
10345
  * the HTTP request on workflow execution.
10022
10346
  */
10023
10347
  async requeue(runId, _seen) {
10348
+ if (_seen === void 0 && this.restrictiveFilter() && await this.hidden(runId)) return null;
10024
10349
  const seen = _seen ?? /* @__PURE__ */ new Set();
10025
10350
  if (seen.has(runId)) return null;
10026
10351
  seen.add(runId);
@@ -10128,7 +10453,7 @@ var WorkflowEngine = class _WorkflowEngine {
10128
10453
  * run's current status (with the count re-dispatched), or null if the run is unknown.
10129
10454
  */
10130
10455
  async redispatchPending(runId) {
10131
- const run = await this.store.getRun(runId);
10456
+ const run = await this.visibleRun(runId);
10132
10457
  if (!run) return null;
10133
10458
  const pending = (await this.store.listCheckpoints(runId)).filter((cp) => cp.kind === "remote" && cp.status === "pending");
10134
10459
  let redispatched = 0;
@@ -10143,7 +10468,7 @@ var WorkflowEngine = class _WorkflowEngine {
10143
10468
  startedAt: reEnqueuedAt,
10144
10469
  finishedAt: reEnqueuedAt
10145
10470
  });
10146
- await this.dispatchRemoteTask({
10471
+ await this.inRunTenant(run, () => this.dispatchRemoteTask({
10147
10472
  runId,
10148
10473
  seq: cp.seq,
10149
10474
  name: cp.name,
@@ -10151,7 +10476,7 @@ var WorkflowEngine = class _WorkflowEngine {
10151
10476
  group: cp.workerGroup ?? sanitizeQueueToken(cp.name),
10152
10477
  input: cp.input,
10153
10478
  attempt: reAttempt
10154
- });
10479
+ }));
10155
10480
  redispatched += 1;
10156
10481
  }
10157
10482
  return {
@@ -10166,12 +10491,13 @@ var WorkflowEngine = class _WorkflowEngine {
10166
10491
  * the original stays inspectable. Returns the new run's id, or null if `runId` is unknown.
10167
10492
  */
10168
10493
  async retryWithInput(runId, input, newRunId) {
10169
- const run = await this.store.getRun(runId);
10494
+ const run = await this.visibleRun(runId);
10170
10495
  if (!run) return null;
10171
10496
  const id = newRunId ?? `${runId}~retry~${globalThis.crypto.randomUUID().slice(0, 8)}`;
10172
10497
  await this.start(run.workflow, input, id, {
10173
10498
  tags: run.tags,
10174
- namespace: run.namespace
10499
+ namespace: run.namespace,
10500
+ ...inheritTenant(run)
10175
10501
  });
10176
10502
  return {
10177
10503
  runId: id
@@ -10220,6 +10546,7 @@ var WorkflowEngine = class _WorkflowEngine {
10220
10546
  output: run.output,
10221
10547
  error: run.error
10222
10548
  }), "toResult");
10549
+ const filter = this.restrictiveFilter();
10223
10550
  return new Promise((resolve, reject) => {
10224
10551
  let done = false;
10225
10552
  let off = /* @__PURE__ */ __name(() => {
@@ -10250,6 +10577,10 @@ var WorkflowEngine = class _WorkflowEngine {
10250
10577
  const check = /* @__PURE__ */ __name(() => {
10251
10578
  if (done) return;
10252
10579
  void this.store.getRun(runId).then((run) => {
10580
+ if (run && filter && !tenantVisible(run, filter)) {
10581
+ fail(new Error(`run ${runId} not found`));
10582
+ return;
10583
+ }
10253
10584
  if (run && isSettled(run)) finish(run);
10254
10585
  }, fail);
10255
10586
  }, "check");
@@ -10367,17 +10698,23 @@ var WorkflowEngine = class _WorkflowEngine {
10367
10698
  */
10368
10699
  async publishEvent(name, payload, opts) {
10369
10700
  let touched = 0;
10701
+ const filter = this.restrictiveFilter();
10702
+ const reaches = /* @__PURE__ */ __name(async (runId) => {
10703
+ if (!filter) return true;
10704
+ const run = await this.store.getRun(runId);
10705
+ return run !== null && tenantVisible(run, filter);
10706
+ }, "reaches");
10370
10707
  const waiters = await this.store.listSignalWaiters(eventPrefix(name));
10371
10708
  for (const w of waiters) {
10372
- if (eventMatches(payload, eventMatchOf(w.token))) {
10373
- await this.signal(w.token, payload);
10709
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10710
+ await this.signalUnchecked(w.token, payload);
10374
10711
  touched += 1;
10375
10712
  }
10376
10713
  }
10377
10714
  const remote = await this.announcedRemoteSubscribers(name, null);
10378
10715
  if (this.eventTriggers.get(name)?.size || remote.length > 0) {
10379
10716
  const eventId = opts?.id ?? globalThis.crypto.randomUUID();
10380
- const { reached, failed } = await this.startSubscribers(name, payload, (workflow) => `evt:${eventId}:${workflow}`, void 0, remote);
10717
+ const { reached, failed } = await this.startSubscribers(name, payload, (workflow) => `evt:${eventId}:${workflow}`, void 0, remote, void 0, this.publishBatchTenant());
10381
10718
  touched += reached.length;
10382
10719
  for (const { workflow, error: error2 } of failed) {
10383
10720
  console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error2);
@@ -10387,12 +10724,18 @@ var WorkflowEngine = class _WorkflowEngine {
10387
10724
  const bufferedId = globalThis.crypto.randomUUID();
10388
10725
  await this.store.bufferEvent({
10389
10726
  name,
10390
- payload,
10727
+ payload: scopeBufferedEvent(payload, filter ? tenantIdsFor(filter) : void 0),
10391
10728
  id: bufferedId,
10392
10729
  publishedAt: this.clock()
10393
10730
  });
10394
10731
  const lateWaiters = await this.store.listSignalWaiters(eventPrefix(name));
10395
- const lateWaiter = lateWaiters.find((w) => eventMatches(payload, eventMatchOf(w.token)));
10732
+ let lateWaiter;
10733
+ for (const w of lateWaiters) {
10734
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10735
+ lateWaiter = w;
10736
+ break;
10737
+ }
10738
+ }
10396
10739
  if (!lateWaiter) return touched;
10397
10740
  if (!await this.store.removeBufferedEvent(bufferedId)) return touched;
10398
10741
  const waiter = await this.store.takeSignalWaiter(lateWaiter.token);
@@ -10699,7 +11042,23 @@ var WorkflowEngine = class _WorkflowEngine {
10699
11042
  * Either way, the destructive `take*` ops (on the waiter row, on the buffer) arbitrate: whichever
10700
11043
  * side actually removes the row is the one that delivers, so a signal is never delivered twice.
10701
11044
  */
10702
- async signal(token, payload, opts) {
11045
+ signal(token, payload, opts) {
11046
+ const filter = parseWebhookToken(token) ? void 0 : this.restrictiveFilter();
11047
+ if (!filter) return this.signalUnchecked(token, payload, opts);
11048
+ return this.signalTargetVisible(token, filter).then((visible) => visible ? this.signalUnchecked(token, payload, opts) : null);
11049
+ }
11050
+ /**
11051
+ * False when a run waits on `token` and `filter` may not see it (the tenancy matching rule). A
11052
+ * token nobody waits on yet is buffered as before (there is no run to check).
11053
+ */
11054
+ async signalTargetVisible(token, filter) {
11055
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
11056
+ if (!waiter) return true;
11057
+ const run = await this.store.getRun(waiter.runId);
11058
+ return !run || tenantVisible(run, filter);
11059
+ }
11060
+ /** {@link signal} without the tenancy check — the engine's own deliveries. */
11061
+ async signalUnchecked(token, payload, opts) {
10703
11062
  const id = opts?.id;
10704
11063
  if (id === void 0) return this.deliverOrBuffer(token, payload);
10705
11064
  if (!this.store.claimSignalId) {
@@ -10783,14 +11142,16 @@ var WorkflowEngine = class _WorkflowEngine {
10783
11142
  * null if no run is waiting on the task (e.g. a duplicate/late delivery) — a safe no-op.
10784
11143
  */
10785
11144
  async completeTask(runId, name, result) {
10786
- return this.signal(`task:${runId}:${name}`, {
11145
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
11146
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10787
11147
  ok: true,
10788
11148
  value: result
10789
11149
  });
10790
11150
  }
10791
11151
  /** Report that a `ctx.task` failed — the run resumes and throws a FatalError at the task. */
10792
11152
  async failTask(runId, name, error2) {
10793
- return this.signal(`task:${runId}:${name}`, {
11153
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
11154
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10794
11155
  ok: false,
10795
11156
  error: error2
10796
11157
  });
@@ -10829,7 +11190,7 @@ var WorkflowEngine = class _WorkflowEngine {
10829
11190
  if (cancelled) return;
10830
11191
  const childId = token.slice(CHILD_TOKEN_PREFIX.length);
10831
11192
  if (!await childCompletionNeedsBuffer(this.store, childId, completion)) return;
10832
- await this.signal(token, completion);
11193
+ await this.signalUnchecked(token, completion);
10833
11194
  return;
10834
11195
  } catch (err) {
10835
11196
  if (err instanceof NamespaceMismatch) return;
@@ -10878,7 +11239,12 @@ var WorkflowEngine = class _WorkflowEngine {
10878
11239
  * steps' compensations run in reverse (visible as `compensate:<step>` events), then it's marked
10879
11240
  * cancelled. Without it, cancellation is immediate (no undo).
10880
11241
  */
10881
- async cancel(runId, opts) {
11242
+ cancel(runId, opts) {
11243
+ if (!this.restrictiveFilter()) return this.cancelUnchecked(runId, opts);
11244
+ return this.hidden(runId).then((hidden) => hidden ? null : this.cancelUnchecked(runId, opts));
11245
+ }
11246
+ /** {@link cancel} without the tenancy check — the engine's own cascades and bulk paths. */
11247
+ async cancelUnchecked(runId, opts) {
10882
11248
  const run = await this.store.getRun(runId);
10883
11249
  if (!run) return null;
10884
11250
  if (TERMINAL_RUN_STATUSES.includes(run.status)) {
@@ -10960,10 +11326,10 @@ var WorkflowEngine = class _WorkflowEngine {
10960
11326
  * their terminal status — `cancel` is a no-op on them, never clobbering a completed/dead run).
10961
11327
  */
10962
11328
  async cancelWhere(filter, opts) {
10963
- const runs = await this.store.listRuns(filter);
11329
+ const runs = await this.store.listRuns(this.scopeRunQuery(filter));
10964
11330
  const results = [];
10965
11331
  for (const run of runs) {
10966
- const r = await this.cancel(run.id, opts);
11332
+ const r = await this.cancelUnchecked(run.id, opts);
10967
11333
  if (r) results.push(r);
10968
11334
  }
10969
11335
  return results;
@@ -10979,11 +11345,16 @@ var WorkflowEngine = class _WorkflowEngine {
10979
11345
  * its worker (its next checkpoint write fails). Returns the number of runs deleted (0 if absent).
10980
11346
  */
10981
11347
  async deleteRun(runId) {
11348
+ if (this.restrictiveFilter() && await this.hidden(runId)) return 0;
11349
+ return await this.deleteRunUnchecked(runId);
11350
+ }
11351
+ /** {@link deleteRun} without the tenancy check (its own subtree recursion). */
11352
+ async deleteRunUnchecked(runId) {
10982
11353
  const run = await this.store.getRun(runId);
10983
11354
  if (!run) return 0;
10984
11355
  let deleted = 0;
10985
- for (const childId of await this.getRunChildren(runId)) {
10986
- deleted += await this.deleteRun(childId);
11356
+ for (const childId of await this.runChildrenUnchecked(runId)) {
11357
+ deleted += await this.deleteRunUnchecked(childId);
10987
11358
  }
10988
11359
  await this.store.deleteRun(runId);
10989
11360
  return deleted + 1;
@@ -11012,6 +11383,7 @@ var WorkflowEngine = class _WorkflowEngine {
11012
11383
  if (!isNonEmptyRunScope(scope)) {
11013
11384
  throw new Error("purgeRuns: refusing an empty scope (it would delete every run) \u2014 pass at least one predicate, e.g. { namespace }");
11014
11385
  }
11386
+ const scoped = this.scopeRunQuery(scope);
11015
11387
  const batchSize = Math.max(1, opts?.batchSize ?? 500);
11016
11388
  const cancelLive = opts?.cancelLive ?? true;
11017
11389
  const withChildren = opts?.children ?? true;
@@ -11022,7 +11394,7 @@ var WorkflowEngine = class _WorkflowEngine {
11022
11394
  let previous = "";
11023
11395
  for (; ; ) {
11024
11396
  const batch = await this.store.listRuns({
11025
- ...scope,
11397
+ ...scoped,
11026
11398
  statuses,
11027
11399
  limit: batchSize
11028
11400
  });
@@ -11043,7 +11415,7 @@ var WorkflowEngine = class _WorkflowEngine {
11043
11415
  if (status === void 0) continue;
11044
11416
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
11045
11417
  if (!cancelLive) continue;
11046
- await this.cancel(id).catch(() => void 0);
11418
+ await this.cancelUnchecked(id).catch(() => void 0);
11047
11419
  }
11048
11420
  doomed.push(id);
11049
11421
  }
@@ -11104,10 +11476,10 @@ var WorkflowEngine = class _WorkflowEngine {
11104
11476
  * explicitly cancelled one's does, or the children are orphans nobody is holding a reference to.
11105
11477
  */
11106
11478
  async cancelChildren(parentRunId, opts) {
11107
- for (const id of await this.getRunChildren(parentRunId)) {
11479
+ for (const id of await this.runChildrenUnchecked(parentRunId)) {
11108
11480
  const child = await this.store.getRun(id).catch(() => null);
11109
11481
  if (child?.tags?.includes(`${PARENT_CLOSE_TAG_PREFIX}abandon`)) continue;
11110
- await this.cancel(id, opts).catch(() => void 0);
11482
+ await this.cancelUnchecked(id, opts).catch(() => void 0);
11111
11483
  }
11112
11484
  }
11113
11485
  /**
@@ -11125,7 +11497,7 @@ var WorkflowEngine = class _WorkflowEngine {
11125
11497
  if (event.type === "run.suspended") return;
11126
11498
  for (const [childId, policy] of intents) {
11127
11499
  if (policy === "abandon") continue;
11128
- queueMicrotask(() => void this.cancel(childId, {
11500
+ queueMicrotask(() => void this.cancelUnchecked(childId, {
11129
11501
  compensate: policy === "cancel"
11130
11502
  }).catch(() => void 0));
11131
11503
  }
@@ -11149,7 +11521,13 @@ var WorkflowEngine = class _WorkflowEngine {
11149
11521
  parentRunId
11150
11522
  ])).filter((w) => w.token.startsWith("child:") && !isAnyMember(w)).map((w) => w.token.slice("child:".length));
11151
11523
  }
11524
+ /** The child runs of `parentRunId`; empty for a parent the caller may not see. */
11152
11525
  async getRunChildren(parentRunId) {
11526
+ if (this.restrictiveFilter() && await this.hidden(parentRunId)) return [];
11527
+ return this.runChildrenUnchecked(parentRunId);
11528
+ }
11529
+ /** {@link getRunChildren} without the tenancy check (the engine's own subtree walks). */
11530
+ async runChildrenUnchecked(parentRunId) {
11153
11531
  const childIds = new Set(await this.awaitedChildIds(parentRunId));
11154
11532
  const prefixes = CHILD_EDGE_PREFIXES;
11155
11533
  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)));
@@ -11510,7 +11888,7 @@ var WorkflowEngine = class _WorkflowEngine {
11510
11888
  const served = /* @__PURE__ */ new Set();
11511
11889
  this.turnServedWakes.set(run.id, served);
11512
11890
  if (registered?.remote) await this.noteServedWakes(run.id);
11513
- const result = registered?.remote ? await this.runRemoteExecution(run, registered) : await this.runExecution(run, fn, registered);
11891
+ const result = await this.inRunTenant(run, () => registered?.remote ? this.runRemoteExecution(run, registered) : this.runExecution(run, fn, registered));
11514
11892
  if (registered?.singleton && (result.status === "completed" || result.status === "failed" || result.status === "cancelled" || result.status === "dead")) {
11515
11893
  void this.singletons.wakeNext(run).catch(() => void 0);
11516
11894
  }
@@ -11826,7 +12204,8 @@ var WorkflowEngine = class _WorkflowEngine {
11826
12204
  error: error2
11827
12205
  });
11828
12206
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11829
- namespace: run.namespace
12207
+ namespace: run.namespace,
12208
+ ...inheritTenant(run)
11830
12209
  });
11831
12210
  return {
11832
12211
  kind: "suspended"
@@ -11873,7 +12252,8 @@ var WorkflowEngine = class _WorkflowEngine {
11873
12252
  if (!handlerRun) {
11874
12253
  const handler = handoff.input;
11875
12254
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11876
- namespace: run.namespace
12255
+ namespace: run.namespace,
12256
+ ...inheritTenant(run)
11877
12257
  });
11878
12258
  }
11879
12259
  return {
@@ -12658,7 +13038,8 @@ ${run.workflowVersion}`;
12658
13038
  const existingChild = await this.store.getRun(childId);
12659
13039
  if (!existingChild) {
12660
13040
  this.startChildDeferred(cmd.workflow, cmd.input, childId, {
12661
- namespace: run.namespace
13041
+ namespace: run.namespace,
13042
+ ...inheritTenant(run)
12662
13043
  });
12663
13044
  } else {
12664
13045
  this.redeliverFinishedChild(childId, existingChild);
@@ -12777,7 +13158,7 @@ ${run.workflowVersion}`;
12777
13158
  this.awaitedRemoteSteps.set(run.id, awaitedSteps);
12778
13159
  const awaitedFans = [];
12779
13160
  this.awaitedStepFans.set(run.id, awaitedFans);
12780
- const ctx = warm ? void 0 : createWorkflowCtx(this.ctxHostFor(replay, run.namespace, cont), run.id, compensations, run.workflow, registered?.searchAttributesSchema);
13161
+ const ctx = warm ? void 0 : createWorkflowCtx(this.ctxHostFor(replay, run.namespace, cont, inheritTenant(run)), run.id, compensations, run.workflow, registered?.searchAttributesSchema);
12781
13162
  try {
12782
13163
  const handoff = liveHandoff(run.id, snapshot);
12783
13164
  if (handoff && !this.cancelRequested.has(run.id)) {
@@ -12835,7 +13216,7 @@ ${run.workflowVersion}`;
12835
13216
  value: void 0
12836
13217
  });
12837
13218
  const nextId = nextContinuationId(run.id);
12838
- queueMicrotask(() => void this.start(run.workflow, err.input, nextId).catch(() => void 0));
13219
+ queueMicrotask(() => void this.start(run.workflow, err.input, nextId, inheritTenant(run)).catch(() => void 0));
12839
13220
  return {
12840
13221
  runId: run.id,
12841
13222
  status: "completed"
@@ -13108,7 +13489,7 @@ ${run.workflowVersion}`;
13108
13489
  /** The seam handed to {@link createWorkflowCtx}: the authoring API reaches durability + lifecycle
13109
13490
  * (checkpointing, dispatch, child start) through this, so the ctx primitives live in their own
13110
13491
  * module and the engine stays the orchestrator. */
13111
- ctxHostFor(replay, parentNamespace, sticky) {
13492
+ ctxHostFor(replay, parentNamespace, sticky, parentTenant) {
13112
13493
  return {
13113
13494
  store: this.store,
13114
13495
  replay,
@@ -13155,6 +13536,8 @@ ${run.workflowVersion}`;
13155
13536
  this.startChildDeferred(workflow, input, id, {
13156
13537
  priority,
13157
13538
  namespace: parentNamespace,
13539
+ // The child belongs to the parent's customer, whichever instance or context drives it.
13540
+ ...parentTenant,
13158
13541
  // Absent unless the body pinned one (`ctx.child(ref, input, { version })`) — an omitted
13159
13542
  // pin must stay omitted, so the child keeps resolving `latest` exactly as before.
13160
13543
  version,
@@ -13178,7 +13561,7 @@ ${run.workflowVersion}`;
13178
13561
  // idempotent on a terminal/cancelled run (returns its existing status without side effects), so
13179
13562
  // no extra guard is needed here for the failFast replay case (re-issuing the same cancel calls).
13180
13563
  cancelChild: /* @__PURE__ */ __name((childId) => {
13181
- queueMicrotask(() => void this.cancel(childId).catch(() => void 0));
13564
+ queueMicrotask(() => void this.cancelUnchecked(childId).catch(() => void 0));
13182
13565
  }, "cancelChild"),
13183
13566
  // Shallow-merge into the run's searchAttributes (the ctx primitive makes this exactly-once).
13184
13567
  upsertSearchAttributes: /* @__PURE__ */ __name(async (runId, attrs) => {
@@ -13205,7 +13588,7 @@ ${run.workflowVersion}`;
13205
13588
  console.warn(`[nestjs-durable] waking entity "${name}" key "${key}" failed (its op stays buffered for the next wake):`, err);
13206
13589
  }));
13207
13590
  }, "kickEntity"),
13208
- interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body), "interceptStep")
13591
+ interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body, parentTenant), "interceptStep")
13209
13592
  };
13210
13593
  }
13211
13594
  /**
@@ -13214,10 +13597,11 @@ ${run.workflowVersion}`;
13214
13597
  * paused at a breakpoint.
13215
13598
  */
13216
13599
  async continue(runId) {
13600
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
13217
13601
  const checkpoints = await this.store.listCheckpoints(runId);
13218
13602
  const bp = checkpoints.find(isBreakpoint);
13219
13603
  if (!bp) return null;
13220
- return this.signal(breakpointToken(runId, bp.seq), void 0);
13604
+ return this.signalUnchecked(breakpointToken(runId, bp.seq), void 0);
13221
13605
  }
13222
13606
  /**
13223
13607
  * Read the latest value a run published for `key` via {@link WorkflowCtx.setEvent} — a
@@ -13225,6 +13609,7 @@ ${run.workflowVersion}`;
13225
13609
  * never published that key. The suspend-model counterpart of a Temporal query.
13226
13610
  */
13227
13611
  async getEvent(runId, key) {
13612
+ if (this.restrictiveFilter() && await this.hidden(runId)) return void 0;
13228
13613
  const name = `event:${key}`;
13229
13614
  if (this.store.getLatestCheckpointByName) {
13230
13615
  const latest2 = await this.store.getLatestCheckpointByName(runId, name);
@@ -13249,7 +13634,7 @@ ${run.workflowVersion}`;
13249
13634
  * if nothing was waiting — a too-early or duplicate update).
13250
13635
  */
13251
13636
  async update(runId, name, arg) {
13252
- const run = await this.store.getRun(runId);
13637
+ const run = await this.visibleRun(runId);
13253
13638
  if (!run) return {
13254
13639
  accepted: false,
13255
13640
  reason: `run ${runId} not found`
@@ -13269,7 +13654,7 @@ ${run.workflowVersion}`;
13269
13654
  };
13270
13655
  }
13271
13656
  }
13272
- const result = await this.signal(`update:${runId}:${name}`, arg);
13657
+ const result = await this.signalUnchecked(`update:${runId}:${name}`, arg);
13273
13658
  return {
13274
13659
  accepted: true,
13275
13660
  run: result
@@ -16454,6 +16839,9 @@ var InMemoryStateStore = class {
16454
16839
  if (query.origins) {
16455
16840
  runs = runs.filter((r) => query.origins?.includes(r.origin ?? null));
16456
16841
  }
16842
+ if (query.tenantId !== void 0 || query.tenantIds !== void 0) {
16843
+ runs = runs.filter((r) => matchesTenantPredicates(r, query));
16844
+ }
16457
16845
  if (query.attributes?.length) {
16458
16846
  let candidates = null;
16459
16847
  for (const f of query.attributes) {
@@ -16527,7 +16915,7 @@ var InMemoryStateStore = class {
16527
16915
  async listSchedules(query) {
16528
16916
  const rows = [
16529
16917
  ...this.schedules.values()
16530
- ].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));
16918
+ ].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));
16531
16919
  const offset = query.offset ?? 0;
16532
16920
  return rows.slice(offset, query.limit != null ? offset + query.limit : void 0).map((s) => structuredClone(s));
16533
16921
  }
@@ -16899,6 +17287,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16899
17287
  axisIsRunColumn,
16900
17288
  bindWorkflowClass,
16901
17289
  breakpointToken,
17290
+ bufferedEventReaches,
16902
17291
  buildWorkflowDirectory,
16903
17292
  canRoute,
16904
17293
  capableWorkers,
@@ -16946,6 +17335,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16946
17335
  hmacTenantVerifier,
16947
17336
  indexWaitersByRun,
16948
17337
  info,
17338
+ inheritTenant,
16949
17339
  isAnyCheckpoint,
16950
17340
  isAnyMember,
16951
17341
  isEngineMintedTag,
@@ -16972,6 +17362,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16972
17362
  log,
16973
17363
  markRemoteEvent,
16974
17364
  matchesAttributes,
17365
+ matchesTenantPredicates,
16975
17366
  mergeRunFacetRows,
16976
17367
  mergeRunValueFacetRows,
16977
17368
  missingCapabilities,
@@ -16996,6 +17387,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16996
17387
  prevCronFireMs,
16997
17388
  prevRRuleFireMs,
16998
17389
  queryCheckpointsOf,
17390
+ readBufferedEvent,
16999
17391
  readRunsByIds,
17000
17392
  readSearchAttributes,
17001
17393
  requiredCapabilities,
@@ -17007,6 +17399,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17007
17399
  retentionKeeps,
17008
17400
  retiredHandoffName,
17009
17401
  routeFor,
17402
+ rowTenant,
17010
17403
  runCompletedEvent,
17011
17404
  runDetailEtag,
17012
17405
  runDurableExecution,
@@ -17024,6 +17417,8 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17024
17417
  sanitizeQueueToken,
17025
17418
  scheduleRunIdAt,
17026
17419
  scheduledRunId,
17420
+ scopeBufferedEvent,
17421
+ scopeTenantQuery,
17027
17422
  settleResultsWithPlainCalls,
17028
17423
  signTenantToken,
17029
17424
  singletonAdmissionDenialPatch,
@@ -17040,6 +17435,8 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17040
17435
  summarizeRunFromStore,
17041
17436
  summarizeTimeline,
17042
17437
  tenantGroup,
17438
+ tenantIdsFor,
17439
+ tenantVisible,
17043
17440
  toEventSubscription,
17044
17441
  traceIdOfTraceparent,
17045
17442
  triggerFailedSubscribersOf,