@dudousxd/nestjs-durable 0.55.2 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -351,6 +351,150 @@ __name(attributesOf, "attributesOf");
351
351
  import { resolveTenantToken, workflowName } from "@dudousxd/nestjs-durable-core";
352
352
  import { Injectable } from "@nestjs/common";
353
353
 
354
+ // src/tenant-contracts.ts
355
+ var RESOLVED = Symbol("nestjs-durable:resolved-tenant-auth");
356
+ function markResolved(fn) {
357
+ Object.defineProperty(fn, RESOLVED, {
358
+ value: true
359
+ });
360
+ return fn;
361
+ }
362
+ __name(markResolved, "markResolved");
363
+ function isResolved(value) {
364
+ return typeof value === "function" && value[RESOLVED] === true;
365
+ }
366
+ __name(isResolved, "isResolved");
367
+ function isClass(value, method) {
368
+ if (typeof value !== "function") return false;
369
+ const proto = value.prototype;
370
+ if (typeof proto?.[method] === "function") return true;
371
+ return /^class[\s{]/.test(Function.prototype.toString.call(value));
372
+ }
373
+ __name(isClass, "isClass");
374
+ function hasMethod(value, method) {
375
+ return typeof value === "object" && value !== null && typeof value[method] === "function";
376
+ }
377
+ __name(hasMethod, "hasMethod");
378
+ function lazyDefault(value, method) {
379
+ if (typeof value !== "object" || value === null || !("default" in value)) return void 0;
380
+ const target = value.default;
381
+ return isClass(target, method) || hasMethod(target, method) ? target : void 0;
382
+ }
383
+ __name(lazyDefault, "lazyDefault");
384
+ function instanceFactory(Class, moduleRef) {
385
+ let pending;
386
+ return () => {
387
+ pending ??= (async () => {
388
+ if (!moduleRef) return new Class();
389
+ try {
390
+ const registered = moduleRef.get(Class, {
391
+ strict: false
392
+ });
393
+ if (registered) return registered;
394
+ } catch {
395
+ }
396
+ try {
397
+ return await moduleRef.create(Class);
398
+ } catch (cause) {
399
+ throw new Error(`could not build ${Class.name || "the tenant auth class"}: register it as a provider in your module, or make its dependencies global`, {
400
+ cause
401
+ });
402
+ }
403
+ })();
404
+ pending.catch(() => {
405
+ pending = void 0;
406
+ });
407
+ return pending;
408
+ };
409
+ }
410
+ __name(instanceFactory, "instanceFactory");
411
+ function contractInstance(target, method, moduleRef) {
412
+ if (isClass(target, method)) return instanceFactory(target, moduleRef);
413
+ const instance = Promise.resolve(target);
414
+ return () => instance;
415
+ }
416
+ __name(contractInstance, "contractInstance");
417
+ function functionOrLazy(fn, method, moduleRef) {
418
+ let lazy;
419
+ let plain = false;
420
+ let probing;
421
+ return async (...args) => {
422
+ for (; ; ) {
423
+ if (lazy) return {
424
+ contract: await lazy()
425
+ };
426
+ if (plain) return {
427
+ result: await fn(...args)
428
+ };
429
+ if (!probing) {
430
+ const probe = (async () => fn(...args))();
431
+ probing = probe;
432
+ try {
433
+ const result = await probe;
434
+ const target = lazyDefault(result, method);
435
+ if (target === void 0) {
436
+ plain = true;
437
+ return {
438
+ result
439
+ };
440
+ }
441
+ lazy = contractInstance(target, method, moduleRef);
442
+ return {
443
+ contract: await lazy()
444
+ };
445
+ } finally {
446
+ if (probing === probe) probing = void 0;
447
+ }
448
+ }
449
+ await probing.catch(() => void 0);
450
+ }
451
+ };
452
+ }
453
+ __name(functionOrLazy, "functionOrLazy");
454
+ function resolveTenantVerifier(option, moduleRef) {
455
+ if (option === void 0 || isResolved(option)) return option;
456
+ const instance = isClass(option, "verify") || hasMethod(option, "verify") ? contractInstance(option, "verify", moduleRef) : void 0;
457
+ if (!instance && typeof option !== "function") {
458
+ throw new Error("`verifyTenant` must be a function, an object or class with verify(), or a lazy import of one.");
459
+ }
460
+ const call = functionOrLazy(option, "verify", moduleRef);
461
+ return markResolved(async (input) => {
462
+ if (instance) return (await instance()).verify(input);
463
+ const probed = await call(input);
464
+ if ("contract" in probed) return probed.contract.verify(input);
465
+ return probed.result;
466
+ });
467
+ }
468
+ __name(resolveTenantVerifier, "resolveTenantVerifier");
469
+ function requireToken(token) {
470
+ if (typeof token !== "string" || token.length === 0) {
471
+ throw new Error("tenantToken produced no token (an empty or non-string value)");
472
+ }
473
+ return token;
474
+ }
475
+ __name(requireToken, "requireToken");
476
+ function resolveTenantTokenSource(option, moduleRef) {
477
+ if (typeof option === "string") {
478
+ if (option.length === 0) {
479
+ throw new Error("`tenantToken` is an empty string. Set the token this tenant presents, or remove `tenantToken` to send the partition.");
480
+ }
481
+ return option;
482
+ }
483
+ if (option === void 0 || isResolved(option)) return option;
484
+ const instance = isClass(option, "token") || hasMethod(option, "token") ? contractInstance(option, "token", moduleRef) : void 0;
485
+ if (!instance && typeof option !== "function") {
486
+ throw new Error("`tenantToken` must be a string, a function, an object or class with token(), or a lazy import of one.");
487
+ }
488
+ const call = functionOrLazy(option, "token", moduleRef);
489
+ return markResolved(async () => {
490
+ if (instance) return requireToken(await (await instance()).token());
491
+ const probed = await call();
492
+ if ("contract" in probed) return requireToken(await probed.contract.token());
493
+ return requireToken(probed.result);
494
+ });
495
+ }
496
+ __name(resolveTenantTokenSource, "resolveTenantTokenSource");
497
+
354
498
  // src/worker-sdk.ts
355
499
  async function workerSdk() {
356
500
  try {
@@ -398,17 +542,19 @@ var DurableStartClient = class {
398
542
  options;
399
543
  deps;
400
544
  tenant;
545
+ tenantToken;
401
546
  constructor(options, deps) {
402
547
  this.options = options;
403
548
  this.deps = deps;
404
549
  this.tenant = options.partition ?? "default";
550
+ this.tenantToken = resolveTenantTokenSource(options.tenantToken);
405
551
  }
406
552
  async start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
407
553
  const name = workflowName(workflow);
408
554
  await startRun(this.options.connection, {
409
555
  // The signed token (when configured) rides in the `tenant` field, as on every run request; an
410
556
  // operator with `verifyTenant` derives the run's namespace from it.
411
- tenant: this.options.tenantToken !== void 0 ? await resolveTenantToken(this.options.tenantToken) : this.tenant,
557
+ tenant: this.tenantToken !== void 0 ? await resolveTenantToken(this.tenantToken) : this.tenant,
412
558
  workflow: name,
413
559
  input,
414
560
  runId,
@@ -915,7 +1061,7 @@ function unavailableRunGateway() {
915
1061
  __name(unavailableRunGateway, "unavailableRunGateway");
916
1062
 
917
1063
  // src/durable.module.ts
918
- import { DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL8, RunGateway as RunGateway2, STATE_STORE, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL4, TRANSPORT, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL3, WorkflowEngine as WorkflowEngine6 } from "@dudousxd/nestjs-durable-core";
1064
+ import { DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL as DURABLE_OPTIONS_CANONICAL8, RunGateway as RunGateway2, STATE_STORE, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL4, TRANSPORT, TRANSPORT_CANONICAL as TRANSPORT_CANONICAL3, WorkflowEngine as WorkflowEngine6, useDurableExecution } from "@dudousxd/nestjs-durable-core";
919
1065
  import { Inject as Inject9, Injectable as Injectable13, Module } from "@nestjs/common";
920
1066
  import { DiscoveryModule, ModuleRef as ModuleRef2 } from "@nestjs/core";
921
1067
 
@@ -2373,9 +2519,23 @@ var StoreRunGateway = class {
2373
2519
  role: "control-plane"
2374
2520
  };
2375
2521
  }
2376
- async getRunDetail(runId, options) {
2522
+ /**
2523
+ * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s
2524
+ * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).
2525
+ */
2526
+ scoped(query) {
2527
+ return typeof this.engine?.scopeRunQuery === "function" ? this.engine.scopeRunQuery(query) : query;
2528
+ }
2529
+ /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */
2530
+ async visibleRun(runId) {
2377
2531
  const run = await this.store.getRun(runId);
2378
2532
  if (!run) return null;
2533
+ const { tenantIds } = this.scoped({});
2534
+ return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;
2535
+ }
2536
+ async getRunDetail(runId, options) {
2537
+ const run = await this.visibleRun(runId);
2538
+ if (!run) return null;
2379
2539
  const links = await this.lifecycleLinks(run);
2380
2540
  const over = options?.summarizeFansOver;
2381
2541
  if (over === void 0) {
@@ -2520,10 +2680,10 @@ var StoreRunGateway = class {
2520
2680
  return this.engine.lifecycleSubscribers(workflow, kind, namespace);
2521
2681
  }
2522
2682
  getRun(runId) {
2523
- return this.store.getRun(runId);
2683
+ return this.visibleRun(runId);
2524
2684
  }
2525
2685
  async getFanMembers(runId, group, query) {
2526
- if (!await this.store.getRun(runId)) return null;
2686
+ if (!await this.visibleRun(runId)) return null;
2527
2687
  if (aggregatesCheckpoints(this.store)) {
2528
2688
  const stats = await this.store.checkpointStats(runId, {
2529
2689
  group
@@ -2545,7 +2705,7 @@ var StoreRunGateway = class {
2545
2705
  return pageFan2(await this.store.listCheckpoints(runId), group, query);
2546
2706
  }
2547
2707
  async listRuns(query) {
2548
- const runs = await this.store.listRuns(withoutRegistry(query));
2708
+ const runs = await this.store.listRuns(this.scoped(withoutRegistry(query)));
2549
2709
  const waiterByRun = indexWaitersByRun(await listSignalWaitersOfRuns(this.store, runs.filter((run) => run.status === "suspended").map((run) => run.id)));
2550
2710
  return runs.map((run) => {
2551
2711
  const waiting = resolveRunWaiting(run, waiterByRun);
@@ -2562,7 +2722,7 @@ var StoreRunGateway = class {
2562
2722
  * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
2563
2723
  */
2564
2724
  async runFacets(query) {
2565
- const scoped = withoutRegistry(query);
2725
+ const scoped = this.scoped(withoutRegistry(query));
2566
2726
  if (this.store.runFacets) return this.store.runFacets(scoped);
2567
2727
  const runs = await this.store.listRuns(scoped);
2568
2728
  return mergeRunFacetRows(runs.map((r) => ({
@@ -2579,7 +2739,7 @@ var StoreRunGateway = class {
2579
2739
  * still works without it.
2580
2740
  */
2581
2741
  async runValueFacets(axis, query, opts) {
2582
- return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
2742
+ return this.store.runValueFacets?.(axis, this.scoped(withoutRegistry(query)), opts) ?? [];
2583
2743
  }
2584
2744
  /**
2585
2745
  * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
@@ -2595,11 +2755,11 @@ var StoreRunGateway = class {
2595
2755
  if (runIds.length === 0) return {};
2596
2756
  const idSet = new Set(runIds);
2597
2757
  const [suspended, waiters] = await Promise.all([
2598
- this.store.listRuns({
2758
+ this.store.listRuns(this.scoped({
2599
2759
  statuses: [
2600
2760
  "suspended"
2601
2761
  ]
2602
- }),
2762
+ })),
2603
2763
  listSignalWaitersOfRuns(this.store, runIds)
2604
2764
  ]);
2605
2765
  const waiterByRun = indexWaitersByRun(waiters);
@@ -2635,10 +2795,44 @@ var StoreRunGateway = class {
2635
2795
  republishLifecycle(target) {
2636
2796
  return this.engine.republishLifecycle(target);
2637
2797
  }
2798
+ /**
2799
+ * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
2800
+ * run that does not exist yet are held until its row shows whose it is.
2801
+ */
2638
2802
  subscribe(runId, onEvent) {
2639
- return this.engine.subscribe((event) => {
2640
- if (event.runId === runId) onEvent(event);
2803
+ const { tenantIds } = this.scoped({});
2804
+ if (!tenantIds) {
2805
+ return this.engine.subscribe((event) => {
2806
+ if (event.runId === runId) onEvent(event);
2807
+ });
2808
+ }
2809
+ let visible;
2810
+ let held = [];
2811
+ let checking = false;
2812
+ const check = /* @__PURE__ */ __name(() => {
2813
+ if (checking || visible !== void 0) return;
2814
+ checking = true;
2815
+ void this.store.getRun(runId).then((run) => {
2816
+ if (run) visible = tenantIds.includes(run.tenantId ?? null);
2817
+ }, () => void 0).finally(() => {
2818
+ checking = false;
2819
+ if (visible === void 0) return;
2820
+ const pending = held;
2821
+ held = [];
2822
+ if (visible) for (const event of pending) onEvent(event);
2823
+ });
2824
+ }, "check");
2825
+ const off = this.engine.subscribe((event) => {
2826
+ if (event.runId !== runId || visible === false) return;
2827
+ if (visible) return onEvent(event);
2828
+ held.push(event);
2829
+ check();
2641
2830
  });
2831
+ check();
2832
+ return () => {
2833
+ held = [];
2834
+ off();
2835
+ };
2642
2836
  }
2643
2837
  };
2644
2838
  StoreRunGateway = _ts_decorate9([
@@ -2651,6 +2845,111 @@ StoreRunGateway = _ts_decorate9([
2651
2845
  ])
2652
2846
  ], StoreRunGateway);
2653
2847
 
2848
+ // src/tenancy.ts
2849
+ var SLOT = Symbol.for("@dudousxd/nestjs-diagnostics:accessor");
2850
+ function accessorOf(accessor) {
2851
+ if (accessor) return accessor;
2852
+ const slot = globalThis[SLOT];
2853
+ return slot?.current ?? void 0;
2854
+ }
2855
+ __name(accessorOf, "accessorOf");
2856
+ function readTenancy(option, accessor) {
2857
+ const a = accessorOf(accessor);
2858
+ if (option === false || typeof a?.tenancy !== "function" || typeof a.tenantFilter !== "function") {
2859
+ return {
2860
+ enabled: false
2861
+ };
2862
+ }
2863
+ const own = typeof option === "object" ? option : {};
2864
+ const inherit = own.enabled === void 0 || own.enabled === "inherit";
2865
+ if (!(inherit ? a.tenancy().enabled : own.enabled)) return {
2866
+ enabled: false
2867
+ };
2868
+ const kinds = own.kinds;
2869
+ const tenantFilter = a.tenantFilter.bind(a);
2870
+ return {
2871
+ enabled: true,
2872
+ nullRows: own.nullRows ?? "tenantless",
2873
+ filter: /* @__PURE__ */ __name(() => tenantFilter(kinds ? {
2874
+ kinds
2875
+ } : void 0), "filter")
2876
+ };
2877
+ }
2878
+ __name(readTenancy, "readTenancy");
2879
+ function isTenantRuntime(x) {
2880
+ return !!x && typeof x.withTenant === "function";
2881
+ }
2882
+ __name(isTenantRuntime, "isTenantRuntime");
2883
+ function restore(runtime, tenant, fn) {
2884
+ return runtime.withTenant({
2885
+ id: tenant.id,
2886
+ kind: tenant.kind ?? "unknown",
2887
+ source: "carrier"
2888
+ }, fn);
2889
+ }
2890
+ __name(restore, "restore");
2891
+ function buildEngineTenancy(option, accessor, runtime) {
2892
+ if (option === false || !runtime) return void 0;
2893
+ return {
2894
+ current() {
2895
+ const t = readTenancy(option, accessor);
2896
+ if (!t.enabled) return void 0;
2897
+ const f = t.filter();
2898
+ return f.mode === "tenant" ? {
2899
+ id: f.tenant.id,
2900
+ kind: f.tenant.kind
2901
+ } : void 0;
2902
+ },
2903
+ filter() {
2904
+ const t = readTenancy(option, accessor);
2905
+ if (!t.enabled) return {
2906
+ mode: "system"
2907
+ };
2908
+ const f = t.filter();
2909
+ if (f.mode === "tenant") return {
2910
+ mode: "tenant",
2911
+ tenantId: f.tenant.id,
2912
+ nullRows: t.nullRows
2913
+ };
2914
+ if (f.mode === "tenantless") return {
2915
+ mode: "tenantless"
2916
+ };
2917
+ return f.mode === "all" ? {
2918
+ mode: "all"
2919
+ } : {
2920
+ mode: "system"
2921
+ };
2922
+ },
2923
+ run: /* @__PURE__ */ __name((tenant, fn) => restore(runtime, tenant, fn), "run")
2924
+ };
2925
+ }
2926
+ __name(buildEngineTenancy, "buildEngineTenancy");
2927
+ function tenantFromCarrier(carrier) {
2928
+ const ref = carrier?.tenant;
2929
+ if (ref && typeof ref.id === "string") {
2930
+ return typeof ref.kind === "string" ? {
2931
+ id: ref.id,
2932
+ kind: ref.kind
2933
+ } : {
2934
+ id: ref.id
2935
+ };
2936
+ }
2937
+ const id = carrier?.tenantId;
2938
+ return typeof id === "string" ? {
2939
+ id
2940
+ } : void 0;
2941
+ }
2942
+ __name(tenantFromCarrier, "tenantFromCarrier");
2943
+ function stepTenantWrapper(option, accessor, runtime) {
2944
+ return (execution, next) => {
2945
+ if (execution.unit !== "step") return next();
2946
+ const tenant = tenantFromCarrier(execution.context);
2947
+ if (!tenant || !readTenancy(option, accessor).enabled) return next();
2948
+ return restore(runtime, tenant, next);
2949
+ };
2950
+ }
2951
+ __name(stepTenantWrapper, "stepTenantWrapper");
2952
+
2654
2953
  // src/tenant-event-republisher.ts
2655
2954
  function isTerminalRunEvent(event) {
2656
2955
  return event.type === "run.completed" || event.type === "run.failed";
@@ -3236,11 +3535,18 @@ function carrierFromAccessor(accessor) {
3236
3535
  if (traceId !== void 0) carrier.traceId = traceId;
3237
3536
  const tenantId = accessor.tenantId();
3238
3537
  if (tenantId !== void 0) carrier.tenantId = tenantId;
3538
+ const tenant = accessor.tenant?.();
3539
+ if (tenant !== void 0 && tenant.source !== "legacy") carrier.tenant = tenant;
3239
3540
  const userRef = accessor.userRef();
3240
3541
  if (userRef !== void 0) carrier.userRef = userRef;
3241
3542
  return carrier;
3242
3543
  }
3243
3544
  __name(carrierFromAccessor, "carrierFromAccessor");
3545
+ function contextSlotPresent() {
3546
+ const slot = globalThis[Symbol.for("@dudousxd/nestjs-diagnostics:accessor")];
3547
+ return !!slot?.current;
3548
+ }
3549
+ __name(contextSlotPresent, "contextSlotPresent");
3244
3550
  function isContextRuntime(x) {
3245
3551
  return !!x && typeof x.deserialize === "function";
3246
3552
  }
@@ -3291,35 +3597,51 @@ function assertValidRole(options) {
3291
3597
  }
3292
3598
  }
3293
3599
  __name(assertValidRole, "assertValidRole");
3600
+ var TOPOLOGIES = [
3601
+ "standalone",
3602
+ "control-plane",
3603
+ "tenant"
3604
+ ];
3294
3605
  function assertValidTopology(options) {
3295
3606
  const topology = options.topology;
3296
- if (topology === void 0) return;
3297
- if (topology.role === "control-plane") {
3607
+ if (topology === void 0 || topology === "standalone") {
3608
+ assertValidRole(options);
3609
+ return;
3610
+ }
3611
+ if (typeof topology !== "string" || !TOPOLOGIES.includes(topology)) {
3612
+ const hint = typeof topology === "object" && topology !== null ? "\nThe object form is gone: `topology: { role: 'tenant', tenant: 'acme' }` is now `topology: 'tenant', partition: 'acme'`." : "";
3613
+ throw new Error(`topology must be 'standalone', 'control-plane' or 'tenant' (got ${JSON.stringify(topology)}).${hint}`);
3614
+ }
3615
+ if (topology === "control-plane") {
3298
3616
  if (options.store === void 0 || options.transport === void 0 && options.transports === void 0) {
3299
- throw new Error("topology: { role: 'control-plane' } needs `store` AND (`transport` or `transports`).\nA control-plane node is the durable operator: it owns the state store and dispatches runs to workers over a transport \u2014 without both, there is nothing for it to operate.");
3617
+ throw new Error("topology: 'control-plane' needs `store` AND (`transport` or `transports`).\nA control-plane node is the durable operator: it owns the state store and dispatches runs to workers over a transport. Without both, there is nothing for it to operate.");
3300
3618
  }
3301
- if (options.partition !== void 0) {
3302
- throw new Error("topology: { role: 'control-plane' } forbids `partition`.\npartition is the WORKER queue-routing suffix \u2014 on a control-plane node, runs are dispatched to tenant partitions via each run's namespace, not via this option. Set `partition` (or `topology: { role: 'tenant', tenant }`) on the WORKER node instead.");
3619
+ if (options.tenantToken !== void 0) {
3620
+ throw new Error("topology: 'control-plane' forbids `tenantToken`.\nA control plane verifies tenant tokens (`verifyTenant`); it does not present one. `tenantToken` belongs on the `topology: 'tenant'` process.");
3303
3621
  }
3304
- if (topology.tenant !== void 0 && options.namespace !== void 0 && options.namespace !== topology.tenant) {
3305
- throw new Error(`topology: { role: 'control-plane', tenant: '${topology.tenant}' } conflicts with \`namespace: '${options.namespace}'\`.
3306
- tenant maps 1:1 onto namespace (the operator's poll-scoping axis) \u2014 set only \`tenant\`, or set \`namespace\` to the same value.`);
3622
+ const { partition: partition2, namespace } = options;
3623
+ if (partition2 !== void 0 && namespace !== void 0 && namespace !== partition2) {
3624
+ throw new Error(`topology: 'control-plane' with \`partition: '${partition2}'\` conflicts with \`namespace: '${namespace}'\`.
3625
+ On a control plane, partition becomes its namespace (the runs it drives). Set only \`partition\`, or set \`namespace\` to the same value.`);
3307
3626
  }
3308
3627
  return;
3309
3628
  }
3629
+ const partition = options.partition;
3630
+ if (typeof partition !== "string" || partition.length === 0) {
3631
+ throw new Error("topology: 'tenant' needs `partition`.\nIt names the tenant this process serves: its consumers pull `<name>@<partition>` tasks and its requests act as that tenant.");
3632
+ }
3310
3633
  if (options.connection === void 0) {
3311
- throw new Error(`topology: { role: 'tenant', tenant: '${topology.tenant}' } needs \`connection\`.
3634
+ throw new Error(`topology: 'tenant' (partition '${partition}') needs \`connection\`.
3312
3635
  A tenant is a store-less worker: it connects to the broker directly to pull its own partition of tasks instead of polling a store it does not have.`);
3313
3636
  }
3314
3637
  if (options.store !== void 0) {
3315
- throw new Error("topology: { role: 'tenant' } forbids `store`.\nA tenant is store-less BY DEFINITION \u2014 a `store` present means you actually wanted `topology: { role: 'control-plane' }` (the store-owning role).");
3638
+ throw new Error("topology: 'tenant' forbids `store`.\nA tenant is store-less BY DEFINITION. A `store` present means you actually wanted `topology: 'control-plane'` (the store-owning role).");
3316
3639
  }
3317
- if (options.namespace !== void 0) {
3318
- throw new Error("topology: { role: 'tenant' } forbids `namespace`.\nnamespace is the OPERATOR's poll-scoping axis (which runs a control-plane instance drives/recovers/resumes) \u2014 a tenant worker has no poll loop for it to scope. Use this preset's `tenant` field for the worker's own routing axis instead.");
3640
+ if (options.verifyTenant !== void 0) {
3641
+ throw new Error("topology: 'tenant' forbids `verifyTenant`.\nA tenant presents a token (`tenantToken`); the control plane verifies it. `verifyTenant` belongs on the `topology: 'control-plane'` process.");
3319
3642
  }
3320
- if (options.partition !== void 0 && options.partition !== topology.tenant) {
3321
- throw new Error(`topology: { role: 'tenant', tenant: '${topology.tenant}' } conflicts with \`partition: '${options.partition}'\`.
3322
- tenant maps 1:1 onto partition (the worker queue-routing suffix) \u2014 set only \`tenant\`, or set \`partition\` to the same value.`);
3643
+ if (options.namespace !== void 0) {
3644
+ throw new Error("topology: 'tenant' forbids `namespace`.\nnamespace is the OPERATOR's poll-scoping axis (which runs a control-plane instance drives/recovers/resumes); a tenant worker has no poll loop for it to scope. Use `partition` for the tenant this process serves.");
3323
3645
  }
3324
3646
  }
3325
3647
  __name(assertValidTopology, "assertValidTopology");
@@ -3336,29 +3658,14 @@ function servingPartition(options) {
3336
3658
  }
3337
3659
  __name(servingPartition, "servingPartition");
3338
3660
  function resolveTopologyPreset(options) {
3339
- const topology = options.topology;
3340
- if (topology === void 0) return options;
3341
- if (topology.role === "control-plane") {
3342
- if (topology.tenant === void 0) return options;
3343
- return {
3344
- ...options,
3345
- // An explicit `namespace` is already validated equal to `tenant` (assertValidTopology), so
3346
- // keeping it is a no-op rather than a conflict.
3347
- namespace: options.namespace ?? topology.tenant,
3348
- // The tenant is ALSO this node's worker-routing suffix: its engine now dispatches a run's steps
3349
- // to `<name>@<tenant>` (core's `stepGroup`), so its own co-located worker must SUBSCRIBE those
3350
- // same tokens. Without this the node would dispatch into queues it is not itself listening on.
3351
- // `partition` is user-forbidden on this role (assertValidTopology), so we own it here.
3352
- partition: topology.tenant
3353
- };
3354
- }
3355
- if (options.partition !== void 0) return options;
3661
+ if (options.topology !== "control-plane" || options.partition === void 0) return options;
3356
3662
  return {
3357
3663
  ...options,
3358
- partition: topology.tenant
3664
+ namespace: options.namespace ?? options.partition
3359
3665
  };
3360
3666
  }
3361
3667
  __name(resolveTopologyPreset, "resolveTopologyPreset");
3668
+ var TENANT_AUTH = Symbol("nestjs-durable:tenant-auth");
3362
3669
  var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3363
3670
  static {
3364
3671
  __name(this, "RunGatewayBootstrap");
@@ -3368,13 +3675,15 @@ var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3368
3675
  gateway;
3369
3676
  store;
3370
3677
  options;
3678
+ auth;
3371
3679
  unsubscribe;
3372
- constructor(engine, transport, gateway, store, options) {
3680
+ constructor(engine, transport, gateway, store, options, auth) {
3373
3681
  this.engine = engine;
3374
3682
  this.transport = transport;
3375
3683
  this.gateway = gateway;
3376
3684
  this.store = store;
3377
3685
  this.options = options;
3686
+ this.auth = auth;
3378
3687
  }
3379
3688
  onApplicationBootstrap() {
3380
3689
  if (!isDrivingOperator(this.options) || !this.transport) return;
@@ -3387,13 +3696,13 @@ var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3387
3696
  publishRunReply: publishRunReply.bind(this.transport)
3388
3697
  };
3389
3698
  new RunRequestResponder(runRequestTransport, this.gateway, {
3390
- verifyTenant: this.options.verifyTenant,
3391
- // Mirrors Agora's rule (`warnWithoutVerifier: role === 'control-plane'`): only a deployment
3392
- // that EXPLICITLY names itself the control plane is told it runs without tenant auth. A plain
3393
- // operator (role inferred from `store`) is Agora's `standalone`: anyone with broker access
3699
+ verifyTenant: this.auth.verifyTenant,
3700
+ // Mirrors Agora's rule (`warnWithoutVerifier: topology === 'control-plane'`): only a deployment
3701
+ // that EXPLICITLY names itself the control plane is told it runs without tenant auth. On a
3702
+ // `standalone` operator (role inferred from `store`) anyone with broker access
3394
3703
  // can already enqueue steps and results there, so the warning would be noise on every boot
3395
3704
  // of an app that never serves tenants.
3396
- warnWithoutVerifier: this.options.topology?.role === "control-plane"
3705
+ warnWithoutVerifier: this.options.topology === "control-plane"
3397
3706
  }).start();
3398
3707
  }
3399
3708
  if (typeof publishTenantEvent === "function") {
@@ -3412,15 +3721,49 @@ RunGatewayBootstrap = _ts_decorate13([
3412
3721
  _ts_param9(1, Inject9(TRANSPORT_CANONICAL3)),
3413
3722
  _ts_param9(3, Inject9(STATE_STORE_CANONICAL4)),
3414
3723
  _ts_param9(4, Inject9(DURABLE_OPTIONS_CANONICAL8)),
3724
+ _ts_param9(5, Inject9(TENANT_AUTH)),
3415
3725
  _ts_metadata13("design:type", Function),
3416
3726
  _ts_metadata13("design:paramtypes", [
3417
3727
  typeof WorkflowEngine6 === "undefined" ? Object : WorkflowEngine6,
3418
3728
  Object,
3419
3729
  typeof RunGateway2 === "undefined" ? Object : RunGateway2,
3420
3730
  Object,
3421
- typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions
3731
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3732
+ typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
3422
3733
  ])
3423
3734
  ], RunGatewayBootstrap);
3735
+ var DurableTenancyBridge = class DurableTenancyBridge2 {
3736
+ static {
3737
+ __name(this, "DurableTenancyBridge");
3738
+ }
3739
+ options;
3740
+ moduleRef;
3741
+ unregister;
3742
+ constructor(options, moduleRef) {
3743
+ this.options = options;
3744
+ this.moduleRef = moduleRef;
3745
+ }
3746
+ async onApplicationBootstrap() {
3747
+ if (this.options.tenancy === false) return;
3748
+ const accessor = resolveAccessor(this.moduleRef);
3749
+ if (!readTenancy(this.options.tenancy, accessor).enabled) return;
3750
+ const runtime = await resolveContextRuntime();
3751
+ if (!isTenantRuntime(runtime)) return;
3752
+ this.unregister = useDurableExecution(stepTenantWrapper(this.options.tenancy, accessor, runtime));
3753
+ }
3754
+ onModuleDestroy() {
3755
+ this.unregister?.();
3756
+ }
3757
+ };
3758
+ DurableTenancyBridge = _ts_decorate13([
3759
+ Injectable13(),
3760
+ _ts_param9(0, Inject9(DURABLE_OPTIONS_CANONICAL8)),
3761
+ _ts_metadata13("design:type", Function),
3762
+ _ts_metadata13("design:paramtypes", [
3763
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3764
+ typeof ModuleRef2 === "undefined" ? Object : ModuleRef2
3765
+ ])
3766
+ ], DurableTenancyBridge);
3424
3767
  var DurableModule = class _DurableModule {
3425
3768
  static {
3426
3769
  __name(this, "DurableModule");
@@ -3443,19 +3786,9 @@ var DurableModule = class _DurableModule {
3443
3786
  inject: options.inject ?? []
3444
3787
  });
3445
3788
  }
3446
- /**
3447
- * Validates role/axis constraints, in resolution order. When {@link DurableModuleOptions.topology}
3448
- * is set, it OWNS validation — {@link assertValidTopology}'s own store/transport/connection checks
3449
- * are strictly stronger than {@link assertValidRole}'s, so the topology-specific, axis-teaching
3450
- * message is what a `topology`-opted-in consumer sees (not the older generic one). Falls back to
3451
- * {@link assertValidRole} unchanged when `topology` is absent — zero behavior change.
3452
- */
3789
+ /** Validates the topology and its role/axis constraints; see {@link assertValidTopology}. */
3453
3790
  static assertValid(options) {
3454
- if (options.topology !== void 0) {
3455
- assertValidTopology(options);
3456
- return;
3457
- }
3458
- assertValidRole(options);
3791
+ assertValidTopology(options);
3459
3792
  }
3460
3793
  static build(optionsProvider) {
3461
3794
  return {
@@ -3484,6 +3817,17 @@ var DurableModule = class _DurableModule {
3484
3817
  DURABLE_OPTIONS_CANONICAL8
3485
3818
  ]
3486
3819
  },
3820
+ {
3821
+ provide: TENANT_AUTH,
3822
+ useFactory: /* @__PURE__ */ __name((options, moduleRef) => ({
3823
+ verifyTenant: resolveTenantVerifier(options.verifyTenant, moduleRef),
3824
+ tenantToken: resolveTenantTokenSource(options.tenantToken, moduleRef)
3825
+ }), "useFactory"),
3826
+ inject: [
3827
+ DURABLE_OPTIONS_CANONICAL8,
3828
+ ModuleRef2
3829
+ ]
3830
+ },
3487
3831
  // Legacy back-compat aliases (deprecated tokens still resolve to the same instances):
3488
3832
  {
3489
3833
  provide: STATE_STORE,
@@ -3502,9 +3846,14 @@ var DurableModule = class _DurableModule {
3502
3846
  // `DurableStartClient` facade for a thin worker (no `store`) — either way, `WorkflowService`
3503
3847
  // and app code call `engine.start(...)` unchanged.
3504
3848
  provide: WorkflowEngine6,
3505
- useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef) => {
3849
+ useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef, auth) => {
3506
3850
  if (options.store === void 0) {
3507
- return new DurableStartClient(options);
3851
+ return new DurableStartClient({
3852
+ ...options,
3853
+ ...auth.tenantToken !== void 0 ? {
3854
+ tenantToken: auth.tenantToken
3855
+ } : {}
3856
+ });
3508
3857
  }
3509
3858
  if (!store) {
3510
3859
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
@@ -3512,7 +3861,8 @@ var DurableModule = class _DurableModule {
3512
3861
  const primary = transport ?? options.transports?.[0]?.transport;
3513
3862
  const accessor = resolveAccessor(moduleRef);
3514
3863
  const context = options.context ?? (accessor ? () => carrierFromAccessor(accessor) : void 0);
3515
- const runtime = accessor ? await resolveContextRuntime() : void 0;
3864
+ const runtimeNeeded = accessor !== void 0 || contextSlotPresent();
3865
+ const runtime = runtimeNeeded ? await resolveContextRuntime() : void 0;
3516
3866
  const rehydrate = runtime && ((carrier, fn) => carrier && Object.keys(carrier).length > 0 ? runtime.deserialize(carrier, fn) : fn());
3517
3867
  if (options.consumers === false) {
3518
3868
  for (const t of [
@@ -3550,9 +3900,11 @@ var DurableModule = class _DurableModule {
3550
3900
  webhookUrl: options.webhookUrl,
3551
3901
  traceparent: options.traceparent,
3552
3902
  context,
3553
- rehydrate: rehydrate || void 0,
3903
+ rehydrate: accessor && rehydrate || void 0,
3904
+ // The run's tenant, restored around every turn (see `tenancy` above).
3905
+ tenancy: buildEngineTenancy(options.tenancy, accessor, isTenantRuntime(runtime) ? runtime : void 0),
3554
3906
  compensationRetries: options.compensationRetries,
3555
- verifyTenant: options.verifyTenant,
3907
+ verifyTenant: auth.verifyTenant,
3556
3908
  // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving
3557
3909
  // each `pending` run in the store for a DRIVING instance's poll. A driving operator gets
3558
3910
  // the engine's default in-process dispatcher: for a body registered inline, it runs
@@ -3572,7 +3924,8 @@ var DurableModule = class _DurableModule {
3572
3924
  DURABLE_OPTIONS_CANONICAL8,
3573
3925
  STATE_STORE_CANONICAL4,
3574
3926
  TRANSPORT_CANONICAL3,
3575
- ModuleRef2
3927
+ ModuleRef2,
3928
+ TENANT_AUTH
3576
3929
  ]
3577
3930
  },
3578
3931
  WorkflowService,
@@ -3587,22 +3940,24 @@ var DurableModule = class _DurableModule {
3587
3940
  // gateway whose every method rejects with a clear tenant error.
3588
3941
  {
3589
3942
  provide: RunGateway2,
3590
- useFactory: /* @__PURE__ */ __name((options, store, engine) => {
3943
+ useFactory: /* @__PURE__ */ __name((options, store, engine, auth) => {
3591
3944
  if (options.store !== void 0) {
3592
3945
  if (!store) {
3593
3946
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
3594
3947
  }
3595
3948
  return new StoreRunGateway(store, engine);
3596
3949
  }
3597
- return options.transport ? new ProxyRunGateway(options.transport, options.partition ?? "default", options.runGatewayTimeoutMs, void 0, options.tenantToken) : unavailableRunGateway();
3950
+ return options.transport ? new ProxyRunGateway(options.transport, options.partition ?? "default", options.runGatewayTimeoutMs, void 0, auth.tenantToken) : unavailableRunGateway();
3598
3951
  }, "useFactory"),
3599
3952
  inject: [
3600
3953
  DURABLE_OPTIONS_CANONICAL8,
3601
3954
  STATE_STORE_CANONICAL4,
3602
- WorkflowEngine6
3955
+ WorkflowEngine6,
3956
+ TENANT_AUTH
3603
3957
  ]
3604
3958
  },
3605
3959
  RunGatewayBootstrap,
3960
+ DurableTenancyBridge,
3606
3961
  // Co-located in-app worker (uniform dispatch): inert unless BOTH `store` and `connection` are
3607
3962
  // set — see `in-app-worker.ts`.
3608
3963
  ...inAppWorkerProviders(),