@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.cjs CHANGED
@@ -460,6 +460,150 @@ __name(attributesOf, "attributesOf");
460
460
  var import_nestjs_durable_core3 = require("@dudousxd/nestjs-durable-core");
461
461
  var import_common = require("@nestjs/common");
462
462
 
463
+ // src/tenant-contracts.ts
464
+ var RESOLVED = Symbol("nestjs-durable:resolved-tenant-auth");
465
+ function markResolved(fn) {
466
+ Object.defineProperty(fn, RESOLVED, {
467
+ value: true
468
+ });
469
+ return fn;
470
+ }
471
+ __name(markResolved, "markResolved");
472
+ function isResolved(value) {
473
+ return typeof value === "function" && value[RESOLVED] === true;
474
+ }
475
+ __name(isResolved, "isResolved");
476
+ function isClass(value, method) {
477
+ if (typeof value !== "function") return false;
478
+ const proto = value.prototype;
479
+ if (typeof proto?.[method] === "function") return true;
480
+ return /^class[\s{]/.test(Function.prototype.toString.call(value));
481
+ }
482
+ __name(isClass, "isClass");
483
+ function hasMethod(value, method) {
484
+ return typeof value === "object" && value !== null && typeof value[method] === "function";
485
+ }
486
+ __name(hasMethod, "hasMethod");
487
+ function lazyDefault(value, method) {
488
+ if (typeof value !== "object" || value === null || !("default" in value)) return void 0;
489
+ const target = value.default;
490
+ return isClass(target, method) || hasMethod(target, method) ? target : void 0;
491
+ }
492
+ __name(lazyDefault, "lazyDefault");
493
+ function instanceFactory(Class, moduleRef) {
494
+ let pending;
495
+ return () => {
496
+ pending ??= (async () => {
497
+ if (!moduleRef) return new Class();
498
+ try {
499
+ const registered = moduleRef.get(Class, {
500
+ strict: false
501
+ });
502
+ if (registered) return registered;
503
+ } catch {
504
+ }
505
+ try {
506
+ return await moduleRef.create(Class);
507
+ } catch (cause) {
508
+ 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`, {
509
+ cause
510
+ });
511
+ }
512
+ })();
513
+ pending.catch(() => {
514
+ pending = void 0;
515
+ });
516
+ return pending;
517
+ };
518
+ }
519
+ __name(instanceFactory, "instanceFactory");
520
+ function contractInstance(target, method, moduleRef) {
521
+ if (isClass(target, method)) return instanceFactory(target, moduleRef);
522
+ const instance = Promise.resolve(target);
523
+ return () => instance;
524
+ }
525
+ __name(contractInstance, "contractInstance");
526
+ function functionOrLazy(fn, method, moduleRef) {
527
+ let lazy;
528
+ let plain = false;
529
+ let probing;
530
+ return async (...args) => {
531
+ for (; ; ) {
532
+ if (lazy) return {
533
+ contract: await lazy()
534
+ };
535
+ if (plain) return {
536
+ result: await fn(...args)
537
+ };
538
+ if (!probing) {
539
+ const probe = (async () => fn(...args))();
540
+ probing = probe;
541
+ try {
542
+ const result = await probe;
543
+ const target = lazyDefault(result, method);
544
+ if (target === void 0) {
545
+ plain = true;
546
+ return {
547
+ result
548
+ };
549
+ }
550
+ lazy = contractInstance(target, method, moduleRef);
551
+ return {
552
+ contract: await lazy()
553
+ };
554
+ } finally {
555
+ if (probing === probe) probing = void 0;
556
+ }
557
+ }
558
+ await probing.catch(() => void 0);
559
+ }
560
+ };
561
+ }
562
+ __name(functionOrLazy, "functionOrLazy");
563
+ function resolveTenantVerifier(option, moduleRef) {
564
+ if (option === void 0 || isResolved(option)) return option;
565
+ const instance = isClass(option, "verify") || hasMethod(option, "verify") ? contractInstance(option, "verify", moduleRef) : void 0;
566
+ if (!instance && typeof option !== "function") {
567
+ throw new Error("`verifyTenant` must be a function, an object or class with verify(), or a lazy import of one.");
568
+ }
569
+ const call = functionOrLazy(option, "verify", moduleRef);
570
+ return markResolved(async (input) => {
571
+ if (instance) return (await instance()).verify(input);
572
+ const probed = await call(input);
573
+ if ("contract" in probed) return probed.contract.verify(input);
574
+ return probed.result;
575
+ });
576
+ }
577
+ __name(resolveTenantVerifier, "resolveTenantVerifier");
578
+ function requireToken(token) {
579
+ if (typeof token !== "string" || token.length === 0) {
580
+ throw new Error("tenantToken produced no token (an empty or non-string value)");
581
+ }
582
+ return token;
583
+ }
584
+ __name(requireToken, "requireToken");
585
+ function resolveTenantTokenSource(option, moduleRef) {
586
+ if (typeof option === "string") {
587
+ if (option.length === 0) {
588
+ throw new Error("`tenantToken` is an empty string. Set the token this tenant presents, or remove `tenantToken` to send the partition.");
589
+ }
590
+ return option;
591
+ }
592
+ if (option === void 0 || isResolved(option)) return option;
593
+ const instance = isClass(option, "token") || hasMethod(option, "token") ? contractInstance(option, "token", moduleRef) : void 0;
594
+ if (!instance && typeof option !== "function") {
595
+ throw new Error("`tenantToken` must be a string, a function, an object or class with token(), or a lazy import of one.");
596
+ }
597
+ const call = functionOrLazy(option, "token", moduleRef);
598
+ return markResolved(async () => {
599
+ if (instance) return requireToken(await (await instance()).token());
600
+ const probed = await call();
601
+ if ("contract" in probed) return requireToken(await probed.contract.token());
602
+ return requireToken(probed.result);
603
+ });
604
+ }
605
+ __name(resolveTenantTokenSource, "resolveTenantTokenSource");
606
+
463
607
  // src/worker-sdk.ts
464
608
  async function workerSdk() {
465
609
  try {
@@ -507,17 +651,19 @@ var DurableStartClient = class {
507
651
  options;
508
652
  deps;
509
653
  tenant;
654
+ tenantToken;
510
655
  constructor(options, deps) {
511
656
  this.options = options;
512
657
  this.deps = deps;
513
658
  this.tenant = options.partition ?? "default";
659
+ this.tenantToken = resolveTenantTokenSource(options.tenantToken);
514
660
  }
515
661
  async start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
516
662
  const name = (0, import_nestjs_durable_core3.workflowName)(workflow);
517
663
  await startRun(this.options.connection, {
518
664
  // The signed token (when configured) rides in the `tenant` field, as on every run request; an
519
665
  // operator with `verifyTenant` derives the run's namespace from it.
520
- tenant: this.options.tenantToken !== void 0 ? await (0, import_nestjs_durable_core3.resolveTenantToken)(this.options.tenantToken) : this.tenant,
666
+ tenant: this.tenantToken !== void 0 ? await (0, import_nestjs_durable_core3.resolveTenantToken)(this.tenantToken) : this.tenant,
521
667
  workflow: name,
522
668
  input,
523
669
  runId,
@@ -2482,9 +2628,23 @@ var StoreRunGateway = class {
2482
2628
  role: "control-plane"
2483
2629
  };
2484
2630
  }
2485
- async getRunDetail(runId, options) {
2631
+ /**
2632
+ * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s
2633
+ * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).
2634
+ */
2635
+ scoped(query) {
2636
+ return typeof this.engine?.scopeRunQuery === "function" ? this.engine.scopeRunQuery(query) : query;
2637
+ }
2638
+ /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */
2639
+ async visibleRun(runId) {
2486
2640
  const run = await this.store.getRun(runId);
2487
2641
  if (!run) return null;
2642
+ const { tenantIds } = this.scoped({});
2643
+ return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;
2644
+ }
2645
+ async getRunDetail(runId, options) {
2646
+ const run = await this.visibleRun(runId);
2647
+ if (!run) return null;
2488
2648
  const links = await this.lifecycleLinks(run);
2489
2649
  const over = options?.summarizeFansOver;
2490
2650
  if (over === void 0) {
@@ -2629,10 +2789,10 @@ var StoreRunGateway = class {
2629
2789
  return this.engine.lifecycleSubscribers(workflow, kind, namespace);
2630
2790
  }
2631
2791
  getRun(runId) {
2632
- return this.store.getRun(runId);
2792
+ return this.visibleRun(runId);
2633
2793
  }
2634
2794
  async getFanMembers(runId, group, query) {
2635
- if (!await this.store.getRun(runId)) return null;
2795
+ if (!await this.visibleRun(runId)) return null;
2636
2796
  if ((0, import_nestjs_durable_core14.aggregatesCheckpoints)(this.store)) {
2637
2797
  const stats = await this.store.checkpointStats(runId, {
2638
2798
  group
@@ -2654,7 +2814,7 @@ var StoreRunGateway = class {
2654
2814
  return (0, import_nestjs_durable_core14.pageFan)(await this.store.listCheckpoints(runId), group, query);
2655
2815
  }
2656
2816
  async listRuns(query) {
2657
- const runs = await this.store.listRuns(withoutRegistry(query));
2817
+ const runs = await this.store.listRuns(this.scoped(withoutRegistry(query)));
2658
2818
  const waiterByRun = (0, import_nestjs_durable_core14.indexWaitersByRun)(await (0, import_nestjs_durable_core14.listSignalWaitersOfRuns)(this.store, runs.filter((run) => run.status === "suspended").map((run) => run.id)));
2659
2819
  return runs.map((run) => {
2660
2820
  const waiting = (0, import_nestjs_durable_core14.resolveRunWaiting)(run, waiterByRun);
@@ -2671,7 +2831,7 @@ var StoreRunGateway = class {
2671
2831
  * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
2672
2832
  */
2673
2833
  async runFacets(query) {
2674
- const scoped = withoutRegistry(query);
2834
+ const scoped = this.scoped(withoutRegistry(query));
2675
2835
  if (this.store.runFacets) return this.store.runFacets(scoped);
2676
2836
  const runs = await this.store.listRuns(scoped);
2677
2837
  return (0, import_nestjs_durable_core14.mergeRunFacetRows)(runs.map((r) => ({
@@ -2688,7 +2848,7 @@ var StoreRunGateway = class {
2688
2848
  * still works without it.
2689
2849
  */
2690
2850
  async runValueFacets(axis, query, opts) {
2691
- return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
2851
+ return this.store.runValueFacets?.(axis, this.scoped(withoutRegistry(query)), opts) ?? [];
2692
2852
  }
2693
2853
  /**
2694
2854
  * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
@@ -2704,11 +2864,11 @@ var StoreRunGateway = class {
2704
2864
  if (runIds.length === 0) return {};
2705
2865
  const idSet = new Set(runIds);
2706
2866
  const [suspended, waiters] = await Promise.all([
2707
- this.store.listRuns({
2867
+ this.store.listRuns(this.scoped({
2708
2868
  statuses: [
2709
2869
  "suspended"
2710
2870
  ]
2711
- }),
2871
+ })),
2712
2872
  (0, import_nestjs_durable_core14.listSignalWaitersOfRuns)(this.store, runIds)
2713
2873
  ]);
2714
2874
  const waiterByRun = (0, import_nestjs_durable_core14.indexWaitersByRun)(waiters);
@@ -2744,10 +2904,44 @@ var StoreRunGateway = class {
2744
2904
  republishLifecycle(target) {
2745
2905
  return this.engine.republishLifecycle(target);
2746
2906
  }
2907
+ /**
2908
+ * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
2909
+ * run that does not exist yet are held until its row shows whose it is.
2910
+ */
2747
2911
  subscribe(runId, onEvent) {
2748
- return this.engine.subscribe((event) => {
2749
- if (event.runId === runId) onEvent(event);
2912
+ const { tenantIds } = this.scoped({});
2913
+ if (!tenantIds) {
2914
+ return this.engine.subscribe((event) => {
2915
+ if (event.runId === runId) onEvent(event);
2916
+ });
2917
+ }
2918
+ let visible;
2919
+ let held = [];
2920
+ let checking = false;
2921
+ const check = /* @__PURE__ */ __name(() => {
2922
+ if (checking || visible !== void 0) return;
2923
+ checking = true;
2924
+ void this.store.getRun(runId).then((run) => {
2925
+ if (run) visible = tenantIds.includes(run.tenantId ?? null);
2926
+ }, () => void 0).finally(() => {
2927
+ checking = false;
2928
+ if (visible === void 0) return;
2929
+ const pending = held;
2930
+ held = [];
2931
+ if (visible) for (const event of pending) onEvent(event);
2932
+ });
2933
+ }, "check");
2934
+ const off = this.engine.subscribe((event) => {
2935
+ if (event.runId !== runId || visible === false) return;
2936
+ if (visible) return onEvent(event);
2937
+ held.push(event);
2938
+ check();
2750
2939
  });
2940
+ check();
2941
+ return () => {
2942
+ held = [];
2943
+ off();
2944
+ };
2751
2945
  }
2752
2946
  };
2753
2947
  StoreRunGateway = _ts_decorate9([
@@ -2760,6 +2954,111 @@ StoreRunGateway = _ts_decorate9([
2760
2954
  ])
2761
2955
  ], StoreRunGateway);
2762
2956
 
2957
+ // src/tenancy.ts
2958
+ var SLOT = Symbol.for("@dudousxd/nestjs-diagnostics:accessor");
2959
+ function accessorOf(accessor) {
2960
+ if (accessor) return accessor;
2961
+ const slot = globalThis[SLOT];
2962
+ return slot?.current ?? void 0;
2963
+ }
2964
+ __name(accessorOf, "accessorOf");
2965
+ function readTenancy(option, accessor) {
2966
+ const a = accessorOf(accessor);
2967
+ if (option === false || typeof a?.tenancy !== "function" || typeof a.tenantFilter !== "function") {
2968
+ return {
2969
+ enabled: false
2970
+ };
2971
+ }
2972
+ const own = typeof option === "object" ? option : {};
2973
+ const inherit = own.enabled === void 0 || own.enabled === "inherit";
2974
+ if (!(inherit ? a.tenancy().enabled : own.enabled)) return {
2975
+ enabled: false
2976
+ };
2977
+ const kinds = own.kinds;
2978
+ const tenantFilter = a.tenantFilter.bind(a);
2979
+ return {
2980
+ enabled: true,
2981
+ nullRows: own.nullRows ?? "tenantless",
2982
+ filter: /* @__PURE__ */ __name(() => tenantFilter(kinds ? {
2983
+ kinds
2984
+ } : void 0), "filter")
2985
+ };
2986
+ }
2987
+ __name(readTenancy, "readTenancy");
2988
+ function isTenantRuntime(x) {
2989
+ return !!x && typeof x.withTenant === "function";
2990
+ }
2991
+ __name(isTenantRuntime, "isTenantRuntime");
2992
+ function restore(runtime, tenant, fn) {
2993
+ return runtime.withTenant({
2994
+ id: tenant.id,
2995
+ kind: tenant.kind ?? "unknown",
2996
+ source: "carrier"
2997
+ }, fn);
2998
+ }
2999
+ __name(restore, "restore");
3000
+ function buildEngineTenancy(option, accessor, runtime) {
3001
+ if (option === false || !runtime) return void 0;
3002
+ return {
3003
+ current() {
3004
+ const t = readTenancy(option, accessor);
3005
+ if (!t.enabled) return void 0;
3006
+ const f = t.filter();
3007
+ return f.mode === "tenant" ? {
3008
+ id: f.tenant.id,
3009
+ kind: f.tenant.kind
3010
+ } : void 0;
3011
+ },
3012
+ filter() {
3013
+ const t = readTenancy(option, accessor);
3014
+ if (!t.enabled) return {
3015
+ mode: "system"
3016
+ };
3017
+ const f = t.filter();
3018
+ if (f.mode === "tenant") return {
3019
+ mode: "tenant",
3020
+ tenantId: f.tenant.id,
3021
+ nullRows: t.nullRows
3022
+ };
3023
+ if (f.mode === "tenantless") return {
3024
+ mode: "tenantless"
3025
+ };
3026
+ return f.mode === "all" ? {
3027
+ mode: "all"
3028
+ } : {
3029
+ mode: "system"
3030
+ };
3031
+ },
3032
+ run: /* @__PURE__ */ __name((tenant, fn) => restore(runtime, tenant, fn), "run")
3033
+ };
3034
+ }
3035
+ __name(buildEngineTenancy, "buildEngineTenancy");
3036
+ function tenantFromCarrier(carrier) {
3037
+ const ref = carrier?.tenant;
3038
+ if (ref && typeof ref.id === "string") {
3039
+ return typeof ref.kind === "string" ? {
3040
+ id: ref.id,
3041
+ kind: ref.kind
3042
+ } : {
3043
+ id: ref.id
3044
+ };
3045
+ }
3046
+ const id = carrier?.tenantId;
3047
+ return typeof id === "string" ? {
3048
+ id
3049
+ } : void 0;
3050
+ }
3051
+ __name(tenantFromCarrier, "tenantFromCarrier");
3052
+ function stepTenantWrapper(option, accessor, runtime) {
3053
+ return (execution, next) => {
3054
+ if (execution.unit !== "step") return next();
3055
+ const tenant = tenantFromCarrier(execution.context);
3056
+ if (!tenant || !readTenancy(option, accessor).enabled) return next();
3057
+ return restore(runtime, tenant, next);
3058
+ };
3059
+ }
3060
+ __name(stepTenantWrapper, "stepTenantWrapper");
3061
+
2763
3062
  // src/tenant-event-republisher.ts
2764
3063
  function isTerminalRunEvent(event) {
2765
3064
  return event.type === "run.completed" || event.type === "run.failed";
@@ -3345,11 +3644,18 @@ function carrierFromAccessor(accessor) {
3345
3644
  if (traceId !== void 0) carrier.traceId = traceId;
3346
3645
  const tenantId = accessor.tenantId();
3347
3646
  if (tenantId !== void 0) carrier.tenantId = tenantId;
3647
+ const tenant = accessor.tenant?.();
3648
+ if (tenant !== void 0 && tenant.source !== "legacy") carrier.tenant = tenant;
3348
3649
  const userRef = accessor.userRef();
3349
3650
  if (userRef !== void 0) carrier.userRef = userRef;
3350
3651
  return carrier;
3351
3652
  }
3352
3653
  __name(carrierFromAccessor, "carrierFromAccessor");
3654
+ function contextSlotPresent() {
3655
+ const slot = globalThis[Symbol.for("@dudousxd/nestjs-diagnostics:accessor")];
3656
+ return !!slot?.current;
3657
+ }
3658
+ __name(contextSlotPresent, "contextSlotPresent");
3353
3659
  function isContextRuntime(x) {
3354
3660
  return !!x && typeof x.deserialize === "function";
3355
3661
  }
@@ -3400,35 +3706,51 @@ function assertValidRole(options) {
3400
3706
  }
3401
3707
  }
3402
3708
  __name(assertValidRole, "assertValidRole");
3709
+ var TOPOLOGIES = [
3710
+ "standalone",
3711
+ "control-plane",
3712
+ "tenant"
3713
+ ];
3403
3714
  function assertValidTopology(options) {
3404
3715
  const topology = options.topology;
3405
- if (topology === void 0) return;
3406
- if (topology.role === "control-plane") {
3716
+ if (topology === void 0 || topology === "standalone") {
3717
+ assertValidRole(options);
3718
+ return;
3719
+ }
3720
+ if (typeof topology !== "string" || !TOPOLOGIES.includes(topology)) {
3721
+ const hint = typeof topology === "object" && topology !== null ? "\nThe object form is gone: `topology: { role: 'tenant', tenant: 'acme' }` is now `topology: 'tenant', partition: 'acme'`." : "";
3722
+ throw new Error(`topology must be 'standalone', 'control-plane' or 'tenant' (got ${JSON.stringify(topology)}).${hint}`);
3723
+ }
3724
+ if (topology === "control-plane") {
3407
3725
  if (options.store === void 0 || options.transport === void 0 && options.transports === void 0) {
3408
- 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.");
3726
+ 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.");
3409
3727
  }
3410
- if (options.partition !== void 0) {
3411
- 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.");
3728
+ if (options.tenantToken !== void 0) {
3729
+ 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.");
3412
3730
  }
3413
- if (topology.tenant !== void 0 && options.namespace !== void 0 && options.namespace !== topology.tenant) {
3414
- throw new Error(`topology: { role: 'control-plane', tenant: '${topology.tenant}' } conflicts with \`namespace: '${options.namespace}'\`.
3415
- tenant maps 1:1 onto namespace (the operator's poll-scoping axis) \u2014 set only \`tenant\`, or set \`namespace\` to the same value.`);
3731
+ const { partition: partition2, namespace } = options;
3732
+ if (partition2 !== void 0 && namespace !== void 0 && namespace !== partition2) {
3733
+ throw new Error(`topology: 'control-plane' with \`partition: '${partition2}'\` conflicts with \`namespace: '${namespace}'\`.
3734
+ On a control plane, partition becomes its namespace (the runs it drives). Set only \`partition\`, or set \`namespace\` to the same value.`);
3416
3735
  }
3417
3736
  return;
3418
3737
  }
3738
+ const partition = options.partition;
3739
+ if (typeof partition !== "string" || partition.length === 0) {
3740
+ 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.");
3741
+ }
3419
3742
  if (options.connection === void 0) {
3420
- throw new Error(`topology: { role: 'tenant', tenant: '${topology.tenant}' } needs \`connection\`.
3743
+ throw new Error(`topology: 'tenant' (partition '${partition}') needs \`connection\`.
3421
3744
  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.`);
3422
3745
  }
3423
3746
  if (options.store !== void 0) {
3424
- 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).");
3747
+ 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).");
3425
3748
  }
3426
- if (options.namespace !== void 0) {
3427
- 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.");
3749
+ if (options.verifyTenant !== void 0) {
3750
+ 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.");
3428
3751
  }
3429
- if (options.partition !== void 0 && options.partition !== topology.tenant) {
3430
- throw new Error(`topology: { role: 'tenant', tenant: '${topology.tenant}' } conflicts with \`partition: '${options.partition}'\`.
3431
- tenant maps 1:1 onto partition (the worker queue-routing suffix) \u2014 set only \`tenant\`, or set \`partition\` to the same value.`);
3752
+ if (options.namespace !== void 0) {
3753
+ 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.");
3432
3754
  }
3433
3755
  }
3434
3756
  __name(assertValidTopology, "assertValidTopology");
@@ -3445,29 +3767,14 @@ function servingPartition(options) {
3445
3767
  }
3446
3768
  __name(servingPartition, "servingPartition");
3447
3769
  function resolveTopologyPreset(options) {
3448
- const topology = options.topology;
3449
- if (topology === void 0) return options;
3450
- if (topology.role === "control-plane") {
3451
- if (topology.tenant === void 0) return options;
3452
- return {
3453
- ...options,
3454
- // An explicit `namespace` is already validated equal to `tenant` (assertValidTopology), so
3455
- // keeping it is a no-op rather than a conflict.
3456
- namespace: options.namespace ?? topology.tenant,
3457
- // The tenant is ALSO this node's worker-routing suffix: its engine now dispatches a run's steps
3458
- // to `<name>@<tenant>` (core's `stepGroup`), so its own co-located worker must SUBSCRIBE those
3459
- // same tokens. Without this the node would dispatch into queues it is not itself listening on.
3460
- // `partition` is user-forbidden on this role (assertValidTopology), so we own it here.
3461
- partition: topology.tenant
3462
- };
3463
- }
3464
- if (options.partition !== void 0) return options;
3770
+ if (options.topology !== "control-plane" || options.partition === void 0) return options;
3465
3771
  return {
3466
3772
  ...options,
3467
- partition: topology.tenant
3773
+ namespace: options.namespace ?? options.partition
3468
3774
  };
3469
3775
  }
3470
3776
  __name(resolveTopologyPreset, "resolveTopologyPreset");
3777
+ var TENANT_AUTH = Symbol("nestjs-durable:tenant-auth");
3471
3778
  var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3472
3779
  static {
3473
3780
  __name(this, "RunGatewayBootstrap");
@@ -3477,13 +3784,15 @@ var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3477
3784
  gateway;
3478
3785
  store;
3479
3786
  options;
3787
+ auth;
3480
3788
  unsubscribe;
3481
- constructor(engine, transport, gateway, store, options) {
3789
+ constructor(engine, transport, gateway, store, options, auth) {
3482
3790
  this.engine = engine;
3483
3791
  this.transport = transport;
3484
3792
  this.gateway = gateway;
3485
3793
  this.store = store;
3486
3794
  this.options = options;
3795
+ this.auth = auth;
3487
3796
  }
3488
3797
  onApplicationBootstrap() {
3489
3798
  if (!isDrivingOperator(this.options) || !this.transport) return;
@@ -3496,13 +3805,13 @@ var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3496
3805
  publishRunReply: publishRunReply.bind(this.transport)
3497
3806
  };
3498
3807
  new RunRequestResponder(runRequestTransport, this.gateway, {
3499
- verifyTenant: this.options.verifyTenant,
3500
- // Mirrors Agora's rule (`warnWithoutVerifier: role === 'control-plane'`): only a deployment
3501
- // that EXPLICITLY names itself the control plane is told it runs without tenant auth. A plain
3502
- // operator (role inferred from `store`) is Agora's `standalone`: anyone with broker access
3808
+ verifyTenant: this.auth.verifyTenant,
3809
+ // Mirrors Agora's rule (`warnWithoutVerifier: topology === 'control-plane'`): only a deployment
3810
+ // that EXPLICITLY names itself the control plane is told it runs without tenant auth. On a
3811
+ // `standalone` operator (role inferred from `store`) anyone with broker access
3503
3812
  // can already enqueue steps and results there, so the warning would be noise on every boot
3504
3813
  // of an app that never serves tenants.
3505
- warnWithoutVerifier: this.options.topology?.role === "control-plane"
3814
+ warnWithoutVerifier: this.options.topology === "control-plane"
3506
3815
  }).start();
3507
3816
  }
3508
3817
  if (typeof publishTenantEvent === "function") {
@@ -3521,15 +3830,49 @@ RunGatewayBootstrap = _ts_decorate13([
3521
3830
  _ts_param9(1, (0, import_common13.Inject)(import_nestjs_durable_core19.TRANSPORT_CANONICAL)),
3522
3831
  _ts_param9(3, (0, import_common13.Inject)(import_nestjs_durable_core19.STATE_STORE_CANONICAL)),
3523
3832
  _ts_param9(4, (0, import_common13.Inject)(import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL)),
3833
+ _ts_param9(5, (0, import_common13.Inject)(TENANT_AUTH)),
3524
3834
  _ts_metadata13("design:type", Function),
3525
3835
  _ts_metadata13("design:paramtypes", [
3526
3836
  typeof import_nestjs_durable_core19.WorkflowEngine === "undefined" ? Object : import_nestjs_durable_core19.WorkflowEngine,
3527
3837
  Object,
3528
3838
  typeof import_nestjs_durable_core19.RunGateway === "undefined" ? Object : import_nestjs_durable_core19.RunGateway,
3529
3839
  Object,
3530
- typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions
3840
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3841
+ typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
3531
3842
  ])
3532
3843
  ], RunGatewayBootstrap);
3844
+ var DurableTenancyBridge = class DurableTenancyBridge2 {
3845
+ static {
3846
+ __name(this, "DurableTenancyBridge");
3847
+ }
3848
+ options;
3849
+ moduleRef;
3850
+ unregister;
3851
+ constructor(options, moduleRef) {
3852
+ this.options = options;
3853
+ this.moduleRef = moduleRef;
3854
+ }
3855
+ async onApplicationBootstrap() {
3856
+ if (this.options.tenancy === false) return;
3857
+ const accessor = resolveAccessor(this.moduleRef);
3858
+ if (!readTenancy(this.options.tenancy, accessor).enabled) return;
3859
+ const runtime = await resolveContextRuntime();
3860
+ if (!isTenantRuntime(runtime)) return;
3861
+ this.unregister = (0, import_nestjs_durable_core19.useDurableExecution)(stepTenantWrapper(this.options.tenancy, accessor, runtime));
3862
+ }
3863
+ onModuleDestroy() {
3864
+ this.unregister?.();
3865
+ }
3866
+ };
3867
+ DurableTenancyBridge = _ts_decorate13([
3868
+ (0, import_common13.Injectable)(),
3869
+ _ts_param9(0, (0, import_common13.Inject)(import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL)),
3870
+ _ts_metadata13("design:type", Function),
3871
+ _ts_metadata13("design:paramtypes", [
3872
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3873
+ typeof import_core6.ModuleRef === "undefined" ? Object : import_core6.ModuleRef
3874
+ ])
3875
+ ], DurableTenancyBridge);
3533
3876
  var DurableModule = class _DurableModule {
3534
3877
  static {
3535
3878
  __name(this, "DurableModule");
@@ -3552,19 +3895,9 @@ var DurableModule = class _DurableModule {
3552
3895
  inject: options.inject ?? []
3553
3896
  });
3554
3897
  }
3555
- /**
3556
- * Validates role/axis constraints, in resolution order. When {@link DurableModuleOptions.topology}
3557
- * is set, it OWNS validation — {@link assertValidTopology}'s own store/transport/connection checks
3558
- * are strictly stronger than {@link assertValidRole}'s, so the topology-specific, axis-teaching
3559
- * message is what a `topology`-opted-in consumer sees (not the older generic one). Falls back to
3560
- * {@link assertValidRole} unchanged when `topology` is absent — zero behavior change.
3561
- */
3898
+ /** Validates the topology and its role/axis constraints; see {@link assertValidTopology}. */
3562
3899
  static assertValid(options) {
3563
- if (options.topology !== void 0) {
3564
- assertValidTopology(options);
3565
- return;
3566
- }
3567
- assertValidRole(options);
3900
+ assertValidTopology(options);
3568
3901
  }
3569
3902
  static build(optionsProvider) {
3570
3903
  return {
@@ -3593,6 +3926,17 @@ var DurableModule = class _DurableModule {
3593
3926
  import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL
3594
3927
  ]
3595
3928
  },
3929
+ {
3930
+ provide: TENANT_AUTH,
3931
+ useFactory: /* @__PURE__ */ __name((options, moduleRef) => ({
3932
+ verifyTenant: resolveTenantVerifier(options.verifyTenant, moduleRef),
3933
+ tenantToken: resolveTenantTokenSource(options.tenantToken, moduleRef)
3934
+ }), "useFactory"),
3935
+ inject: [
3936
+ import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL,
3937
+ import_core6.ModuleRef
3938
+ ]
3939
+ },
3596
3940
  // Legacy back-compat aliases (deprecated tokens still resolve to the same instances):
3597
3941
  {
3598
3942
  provide: import_nestjs_durable_core19.STATE_STORE,
@@ -3611,9 +3955,14 @@ var DurableModule = class _DurableModule {
3611
3955
  // `DurableStartClient` facade for a thin worker (no `store`) — either way, `WorkflowService`
3612
3956
  // and app code call `engine.start(...)` unchanged.
3613
3957
  provide: import_nestjs_durable_core19.WorkflowEngine,
3614
- useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef) => {
3958
+ useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef, auth) => {
3615
3959
  if (options.store === void 0) {
3616
- return new DurableStartClient(options);
3960
+ return new DurableStartClient({
3961
+ ...options,
3962
+ ...auth.tenantToken !== void 0 ? {
3963
+ tenantToken: auth.tenantToken
3964
+ } : {}
3965
+ });
3617
3966
  }
3618
3967
  if (!store) {
3619
3968
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
@@ -3621,7 +3970,8 @@ var DurableModule = class _DurableModule {
3621
3970
  const primary = transport ?? options.transports?.[0]?.transport;
3622
3971
  const accessor = resolveAccessor(moduleRef);
3623
3972
  const context = options.context ?? (accessor ? () => carrierFromAccessor(accessor) : void 0);
3624
- const runtime = accessor ? await resolveContextRuntime() : void 0;
3973
+ const runtimeNeeded = accessor !== void 0 || contextSlotPresent();
3974
+ const runtime = runtimeNeeded ? await resolveContextRuntime() : void 0;
3625
3975
  const rehydrate = runtime && ((carrier, fn) => carrier && Object.keys(carrier).length > 0 ? runtime.deserialize(carrier, fn) : fn());
3626
3976
  if (options.consumers === false) {
3627
3977
  for (const t of [
@@ -3659,9 +4009,11 @@ var DurableModule = class _DurableModule {
3659
4009
  webhookUrl: options.webhookUrl,
3660
4010
  traceparent: options.traceparent,
3661
4011
  context,
3662
- rehydrate: rehydrate || void 0,
4012
+ rehydrate: accessor && rehydrate || void 0,
4013
+ // The run's tenant, restored around every turn (see `tenancy` above).
4014
+ tenancy: buildEngineTenancy(options.tenancy, accessor, isTenantRuntime(runtime) ? runtime : void 0),
3663
4015
  compensationRetries: options.compensationRetries,
3664
- verifyTenant: options.verifyTenant,
4016
+ verifyTenant: auth.verifyTenant,
3665
4017
  // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving
3666
4018
  // each `pending` run in the store for a DRIVING instance's poll. A driving operator gets
3667
4019
  // the engine's default in-process dispatcher: for a body registered inline, it runs
@@ -3681,7 +4033,8 @@ var DurableModule = class _DurableModule {
3681
4033
  import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL,
3682
4034
  import_nestjs_durable_core19.STATE_STORE_CANONICAL,
3683
4035
  import_nestjs_durable_core19.TRANSPORT_CANONICAL,
3684
- import_core6.ModuleRef
4036
+ import_core6.ModuleRef,
4037
+ TENANT_AUTH
3685
4038
  ]
3686
4039
  },
3687
4040
  WorkflowService,
@@ -3696,22 +4049,24 @@ var DurableModule = class _DurableModule {
3696
4049
  // gateway whose every method rejects with a clear tenant error.
3697
4050
  {
3698
4051
  provide: import_nestjs_durable_core19.RunGateway,
3699
- useFactory: /* @__PURE__ */ __name((options, store, engine) => {
4052
+ useFactory: /* @__PURE__ */ __name((options, store, engine, auth) => {
3700
4053
  if (options.store !== void 0) {
3701
4054
  if (!store) {
3702
4055
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
3703
4056
  }
3704
4057
  return new StoreRunGateway(store, engine);
3705
4058
  }
3706
- return options.transport ? new ProxyRunGateway(options.transport, options.partition ?? "default", options.runGatewayTimeoutMs, void 0, options.tenantToken) : unavailableRunGateway();
4059
+ return options.transport ? new ProxyRunGateway(options.transport, options.partition ?? "default", options.runGatewayTimeoutMs, void 0, auth.tenantToken) : unavailableRunGateway();
3707
4060
  }, "useFactory"),
3708
4061
  inject: [
3709
4062
  import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL,
3710
4063
  import_nestjs_durable_core19.STATE_STORE_CANONICAL,
3711
- import_nestjs_durable_core19.WorkflowEngine
4064
+ import_nestjs_durable_core19.WorkflowEngine,
4065
+ TENANT_AUTH
3712
4066
  ]
3713
4067
  },
3714
4068
  RunGatewayBootstrap,
4069
+ DurableTenancyBridge,
3715
4070
  // Co-located in-app worker (uniform dispatch): inert unless BOTH `store` and `connection` are
3716
4071
  // set — see `in-app-worker.ts`.
3717
4072
  ...inAppWorkerProviders(),