@dudousxd/nestjs-durable 0.56.0 → 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
@@ -2628,9 +2628,23 @@ var StoreRunGateway = class {
2628
2628
  role: "control-plane"
2629
2629
  };
2630
2630
  }
2631
- 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) {
2632
2640
  const run = await this.store.getRun(runId);
2633
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;
2634
2648
  const links = await this.lifecycleLinks(run);
2635
2649
  const over = options?.summarizeFansOver;
2636
2650
  if (over === void 0) {
@@ -2775,10 +2789,10 @@ var StoreRunGateway = class {
2775
2789
  return this.engine.lifecycleSubscribers(workflow, kind, namespace);
2776
2790
  }
2777
2791
  getRun(runId) {
2778
- return this.store.getRun(runId);
2792
+ return this.visibleRun(runId);
2779
2793
  }
2780
2794
  async getFanMembers(runId, group, query) {
2781
- if (!await this.store.getRun(runId)) return null;
2795
+ if (!await this.visibleRun(runId)) return null;
2782
2796
  if ((0, import_nestjs_durable_core14.aggregatesCheckpoints)(this.store)) {
2783
2797
  const stats = await this.store.checkpointStats(runId, {
2784
2798
  group
@@ -2800,7 +2814,7 @@ var StoreRunGateway = class {
2800
2814
  return (0, import_nestjs_durable_core14.pageFan)(await this.store.listCheckpoints(runId), group, query);
2801
2815
  }
2802
2816
  async listRuns(query) {
2803
- const runs = await this.store.listRuns(withoutRegistry(query));
2817
+ const runs = await this.store.listRuns(this.scoped(withoutRegistry(query)));
2804
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)));
2805
2819
  return runs.map((run) => {
2806
2820
  const waiting = (0, import_nestjs_durable_core14.resolveRunWaiting)(run, waiterByRun);
@@ -2817,7 +2831,7 @@ var StoreRunGateway = class {
2817
2831
  * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
2818
2832
  */
2819
2833
  async runFacets(query) {
2820
- const scoped = withoutRegistry(query);
2834
+ const scoped = this.scoped(withoutRegistry(query));
2821
2835
  if (this.store.runFacets) return this.store.runFacets(scoped);
2822
2836
  const runs = await this.store.listRuns(scoped);
2823
2837
  return (0, import_nestjs_durable_core14.mergeRunFacetRows)(runs.map((r) => ({
@@ -2834,7 +2848,7 @@ var StoreRunGateway = class {
2834
2848
  * still works without it.
2835
2849
  */
2836
2850
  async runValueFacets(axis, query, opts) {
2837
- return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
2851
+ return this.store.runValueFacets?.(axis, this.scoped(withoutRegistry(query)), opts) ?? [];
2838
2852
  }
2839
2853
  /**
2840
2854
  * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
@@ -2850,11 +2864,11 @@ var StoreRunGateway = class {
2850
2864
  if (runIds.length === 0) return {};
2851
2865
  const idSet = new Set(runIds);
2852
2866
  const [suspended, waiters] = await Promise.all([
2853
- this.store.listRuns({
2867
+ this.store.listRuns(this.scoped({
2854
2868
  statuses: [
2855
2869
  "suspended"
2856
2870
  ]
2857
- }),
2871
+ })),
2858
2872
  (0, import_nestjs_durable_core14.listSignalWaitersOfRuns)(this.store, runIds)
2859
2873
  ]);
2860
2874
  const waiterByRun = (0, import_nestjs_durable_core14.indexWaitersByRun)(waiters);
@@ -2890,10 +2904,44 @@ var StoreRunGateway = class {
2890
2904
  republishLifecycle(target) {
2891
2905
  return this.engine.republishLifecycle(target);
2892
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
+ */
2893
2911
  subscribe(runId, onEvent) {
2894
- return this.engine.subscribe((event) => {
2895
- 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();
2896
2939
  });
2940
+ check();
2941
+ return () => {
2942
+ held = [];
2943
+ off();
2944
+ };
2897
2945
  }
2898
2946
  };
2899
2947
  StoreRunGateway = _ts_decorate9([
@@ -2906,6 +2954,111 @@ StoreRunGateway = _ts_decorate9([
2906
2954
  ])
2907
2955
  ], StoreRunGateway);
2908
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
+
2909
3062
  // src/tenant-event-republisher.ts
2910
3063
  function isTerminalRunEvent(event) {
2911
3064
  return event.type === "run.completed" || event.type === "run.failed";
@@ -3491,11 +3644,18 @@ function carrierFromAccessor(accessor) {
3491
3644
  if (traceId !== void 0) carrier.traceId = traceId;
3492
3645
  const tenantId = accessor.tenantId();
3493
3646
  if (tenantId !== void 0) carrier.tenantId = tenantId;
3647
+ const tenant = accessor.tenant?.();
3648
+ if (tenant !== void 0 && tenant.source !== "legacy") carrier.tenant = tenant;
3494
3649
  const userRef = accessor.userRef();
3495
3650
  if (userRef !== void 0) carrier.userRef = userRef;
3496
3651
  return carrier;
3497
3652
  }
3498
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");
3499
3659
  function isContextRuntime(x) {
3500
3660
  return !!x && typeof x.deserialize === "function";
3501
3661
  }
@@ -3681,6 +3841,38 @@ RunGatewayBootstrap = _ts_decorate13([
3681
3841
  typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
3682
3842
  ])
3683
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);
3684
3876
  var DurableModule = class _DurableModule {
3685
3877
  static {
3686
3878
  __name(this, "DurableModule");
@@ -3778,7 +3970,8 @@ var DurableModule = class _DurableModule {
3778
3970
  const primary = transport ?? options.transports?.[0]?.transport;
3779
3971
  const accessor = resolveAccessor(moduleRef);
3780
3972
  const context = options.context ?? (accessor ? () => carrierFromAccessor(accessor) : void 0);
3781
- const runtime = accessor ? await resolveContextRuntime() : void 0;
3973
+ const runtimeNeeded = accessor !== void 0 || contextSlotPresent();
3974
+ const runtime = runtimeNeeded ? await resolveContextRuntime() : void 0;
3782
3975
  const rehydrate = runtime && ((carrier, fn) => carrier && Object.keys(carrier).length > 0 ? runtime.deserialize(carrier, fn) : fn());
3783
3976
  if (options.consumers === false) {
3784
3977
  for (const t of [
@@ -3816,7 +4009,9 @@ var DurableModule = class _DurableModule {
3816
4009
  webhookUrl: options.webhookUrl,
3817
4010
  traceparent: options.traceparent,
3818
4011
  context,
3819
- 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),
3820
4015
  compensationRetries: options.compensationRetries,
3821
4016
  verifyTenant: auth.verifyTenant,
3822
4017
  // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving
@@ -3871,6 +4066,7 @@ var DurableModule = class _DurableModule {
3871
4066
  ]
3872
4067
  },
3873
4068
  RunGatewayBootstrap,
4069
+ DurableTenancyBridge,
3874
4070
  // Co-located in-app worker (uniform dispatch): inert unless BOTH `store` and `connection` are
3875
4071
  // set — see `in-app-worker.ts`.
3876
4072
  ...inAppWorkerProviders(),