@dudousxd/nestjs-durable 0.56.0 → 0.58.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
@@ -40,7 +40,6 @@ __export(src_exports, {
40
40
  DeadLetter: () => DeadLetter,
41
41
  DurableModule: () => DurableModule,
42
42
  DurableStartClient: () => DurableStartClient,
43
- DurableStep: () => DurableStep,
44
43
  ENTITY_METADATA: () => ENTITY_METADATA,
45
44
  ENTITY_ON_METADATA: () => ENTITY_ON_METADATA,
46
45
  Entity: () => Entity,
@@ -57,7 +56,6 @@ __export(src_exports, {
57
56
  On: () => On,
58
57
  OnDurableEvent: () => OnDurableEvent,
59
58
  OnError: () => OnError,
60
- OnEvent: () => OnEvent,
61
59
  OnWorkflowCompleted: () => OnWorkflowCompleted,
62
60
  OnWorkflowFailed: () => OnWorkflowFailed,
63
61
  ProxyRunGateway: () => ProxyRunGateway,
@@ -228,9 +226,6 @@ __name(fileOfFrame, "fileOfFrame");
228
226
  var WORKFLOW_METADATA = Symbol("nestjs-durable:workflow");
229
227
  function Workflow(options) {
230
228
  const declaredIn = declaringFile(Workflow);
231
- if (options.input !== void 0 && options.inputSchema !== void 0) {
232
- throw new Error(`@Workflow ${options.name}: set either \`input\` or its alias \`inputSchema\`, not both`);
233
- }
234
229
  return (target) => {
235
230
  rememberDeclaringFile(target, declaredIn);
236
231
  const meta = {
@@ -242,7 +237,7 @@ function Workflow(options) {
242
237
  singleton: options.singleton,
243
238
  concurrency: options.concurrency,
244
239
  executionTimeout: options.executionTimeout,
245
- input: options.input ?? options.inputSchema,
240
+ input: options.input,
246
241
  output: options.output,
247
242
  validateInput: options.validateInput,
248
243
  searchAttributes: options.searchAttributes,
@@ -299,7 +294,6 @@ function Step(nameOrOptions) {
299
294
  };
300
295
  }
301
296
  __name(Step, "Step");
302
- var DurableStep = Step;
303
297
  function getDurableStepMeta(method) {
304
298
  return Reflect.getMetadata(DURABLE_STEP_METADATA, method);
305
299
  }
@@ -427,7 +421,6 @@ function addEventSubscriptions(target, entries) {
427
421
  ], target);
428
422
  }
429
423
  __name(addEventSubscriptions, "addEventSubscriptions");
430
- var OnEvent = OnDurableEvent;
431
424
  function getOnEvents(meta, target) {
432
425
  const fromDecorator = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
433
426
  const names = /* @__PURE__ */ new Set();
@@ -2628,9 +2621,23 @@ var StoreRunGateway = class {
2628
2621
  role: "control-plane"
2629
2622
  };
2630
2623
  }
2631
- async getRunDetail(runId, options) {
2624
+ /**
2625
+ * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s
2626
+ * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).
2627
+ */
2628
+ scoped(query) {
2629
+ return typeof this.engine?.scopeRunQuery === "function" ? this.engine.scopeRunQuery(query) : query;
2630
+ }
2631
+ /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */
2632
+ async visibleRun(runId) {
2632
2633
  const run = await this.store.getRun(runId);
2633
2634
  if (!run) return null;
2635
+ const { tenantIds } = this.scoped({});
2636
+ return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;
2637
+ }
2638
+ async getRunDetail(runId, options) {
2639
+ const run = await this.visibleRun(runId);
2640
+ if (!run) return null;
2634
2641
  const links = await this.lifecycleLinks(run);
2635
2642
  const over = options?.summarizeFansOver;
2636
2643
  if (over === void 0) {
@@ -2775,10 +2782,10 @@ var StoreRunGateway = class {
2775
2782
  return this.engine.lifecycleSubscribers(workflow, kind, namespace);
2776
2783
  }
2777
2784
  getRun(runId) {
2778
- return this.store.getRun(runId);
2785
+ return this.visibleRun(runId);
2779
2786
  }
2780
2787
  async getFanMembers(runId, group, query) {
2781
- if (!await this.store.getRun(runId)) return null;
2788
+ if (!await this.visibleRun(runId)) return null;
2782
2789
  if ((0, import_nestjs_durable_core14.aggregatesCheckpoints)(this.store)) {
2783
2790
  const stats = await this.store.checkpointStats(runId, {
2784
2791
  group
@@ -2800,7 +2807,7 @@ var StoreRunGateway = class {
2800
2807
  return (0, import_nestjs_durable_core14.pageFan)(await this.store.listCheckpoints(runId), group, query);
2801
2808
  }
2802
2809
  async listRuns(query) {
2803
- const runs = await this.store.listRuns(withoutRegistry(query));
2810
+ const runs = await this.store.listRuns(this.scoped(withoutRegistry(query)));
2804
2811
  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
2812
  return runs.map((run) => {
2806
2813
  const waiting = (0, import_nestjs_durable_core14.resolveRunWaiting)(run, waiterByRun);
@@ -2817,7 +2824,7 @@ var StoreRunGateway = class {
2817
2824
  * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
2818
2825
  */
2819
2826
  async runFacets(query) {
2820
- const scoped = withoutRegistry(query);
2827
+ const scoped = this.scoped(withoutRegistry(query));
2821
2828
  if (this.store.runFacets) return this.store.runFacets(scoped);
2822
2829
  const runs = await this.store.listRuns(scoped);
2823
2830
  return (0, import_nestjs_durable_core14.mergeRunFacetRows)(runs.map((r) => ({
@@ -2834,7 +2841,7 @@ var StoreRunGateway = class {
2834
2841
  * still works without it.
2835
2842
  */
2836
2843
  async runValueFacets(axis, query, opts) {
2837
- return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
2844
+ return this.store.runValueFacets?.(axis, this.scoped(withoutRegistry(query)), opts) ?? [];
2838
2845
  }
2839
2846
  /**
2840
2847
  * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
@@ -2850,11 +2857,11 @@ var StoreRunGateway = class {
2850
2857
  if (runIds.length === 0) return {};
2851
2858
  const idSet = new Set(runIds);
2852
2859
  const [suspended, waiters] = await Promise.all([
2853
- this.store.listRuns({
2860
+ this.store.listRuns(this.scoped({
2854
2861
  statuses: [
2855
2862
  "suspended"
2856
2863
  ]
2857
- }),
2864
+ })),
2858
2865
  (0, import_nestjs_durable_core14.listSignalWaitersOfRuns)(this.store, runIds)
2859
2866
  ]);
2860
2867
  const waiterByRun = (0, import_nestjs_durable_core14.indexWaitersByRun)(waiters);
@@ -2890,10 +2897,44 @@ var StoreRunGateway = class {
2890
2897
  republishLifecycle(target) {
2891
2898
  return this.engine.republishLifecycle(target);
2892
2899
  }
2900
+ /**
2901
+ * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
2902
+ * run that does not exist yet are held until its row shows whose it is.
2903
+ */
2893
2904
  subscribe(runId, onEvent) {
2894
- return this.engine.subscribe((event) => {
2895
- if (event.runId === runId) onEvent(event);
2905
+ const { tenantIds } = this.scoped({});
2906
+ if (!tenantIds) {
2907
+ return this.engine.subscribe((event) => {
2908
+ if (event.runId === runId) onEvent(event);
2909
+ });
2910
+ }
2911
+ let visible;
2912
+ let held = [];
2913
+ let checking = false;
2914
+ const check = /* @__PURE__ */ __name(() => {
2915
+ if (checking || visible !== void 0) return;
2916
+ checking = true;
2917
+ void this.store.getRun(runId).then((run) => {
2918
+ if (run) visible = tenantIds.includes(run.tenantId ?? null);
2919
+ }, () => void 0).finally(() => {
2920
+ checking = false;
2921
+ if (visible === void 0) return;
2922
+ const pending = held;
2923
+ held = [];
2924
+ if (visible) for (const event of pending) onEvent(event);
2925
+ });
2926
+ }, "check");
2927
+ const off = this.engine.subscribe((event) => {
2928
+ if (event.runId !== runId || visible === false) return;
2929
+ if (visible) return onEvent(event);
2930
+ held.push(event);
2931
+ check();
2896
2932
  });
2933
+ check();
2934
+ return () => {
2935
+ held = [];
2936
+ off();
2937
+ };
2897
2938
  }
2898
2939
  };
2899
2940
  StoreRunGateway = _ts_decorate9([
@@ -2906,6 +2947,111 @@ StoreRunGateway = _ts_decorate9([
2906
2947
  ])
2907
2948
  ], StoreRunGateway);
2908
2949
 
2950
+ // src/tenancy.ts
2951
+ var SLOT = Symbol.for("@dudousxd/nestjs-diagnostics:accessor");
2952
+ function accessorOf(accessor) {
2953
+ if (accessor) return accessor;
2954
+ const slot = globalThis[SLOT];
2955
+ return slot?.current ?? void 0;
2956
+ }
2957
+ __name(accessorOf, "accessorOf");
2958
+ function readTenancy(option, accessor) {
2959
+ const a = accessorOf(accessor);
2960
+ if (option === false || typeof a?.tenancy !== "function" || typeof a.tenantFilter !== "function") {
2961
+ return {
2962
+ enabled: false
2963
+ };
2964
+ }
2965
+ const own = typeof option === "object" ? option : {};
2966
+ const inherit = own.enabled === void 0 || own.enabled === "inherit";
2967
+ if (!(inherit ? a.tenancy().enabled : own.enabled)) return {
2968
+ enabled: false
2969
+ };
2970
+ const kinds = own.kinds;
2971
+ const tenantFilter = a.tenantFilter.bind(a);
2972
+ return {
2973
+ enabled: true,
2974
+ nullRows: own.nullRows ?? "tenantless",
2975
+ filter: /* @__PURE__ */ __name(() => tenantFilter(kinds ? {
2976
+ kinds
2977
+ } : void 0), "filter")
2978
+ };
2979
+ }
2980
+ __name(readTenancy, "readTenancy");
2981
+ function isTenantRuntime(x) {
2982
+ return !!x && typeof x.withTenant === "function";
2983
+ }
2984
+ __name(isTenantRuntime, "isTenantRuntime");
2985
+ function restore(runtime, tenant, fn) {
2986
+ return runtime.withTenant({
2987
+ id: tenant.id,
2988
+ kind: tenant.kind ?? "unknown",
2989
+ source: "carrier"
2990
+ }, fn);
2991
+ }
2992
+ __name(restore, "restore");
2993
+ function buildEngineTenancy(option, accessor, runtime) {
2994
+ if (option === false || !runtime) return void 0;
2995
+ return {
2996
+ current() {
2997
+ const t = readTenancy(option, accessor);
2998
+ if (!t.enabled) return void 0;
2999
+ const f = t.filter();
3000
+ return f.mode === "tenant" ? {
3001
+ id: f.tenant.id,
3002
+ kind: f.tenant.kind
3003
+ } : void 0;
3004
+ },
3005
+ filter() {
3006
+ const t = readTenancy(option, accessor);
3007
+ if (!t.enabled) return {
3008
+ mode: "system"
3009
+ };
3010
+ const f = t.filter();
3011
+ if (f.mode === "tenant") return {
3012
+ mode: "tenant",
3013
+ tenantId: f.tenant.id,
3014
+ nullRows: t.nullRows
3015
+ };
3016
+ if (f.mode === "tenantless") return {
3017
+ mode: "tenantless"
3018
+ };
3019
+ return f.mode === "all" ? {
3020
+ mode: "all"
3021
+ } : {
3022
+ mode: "system"
3023
+ };
3024
+ },
3025
+ run: /* @__PURE__ */ __name((tenant, fn) => restore(runtime, tenant, fn), "run")
3026
+ };
3027
+ }
3028
+ __name(buildEngineTenancy, "buildEngineTenancy");
3029
+ function tenantFromCarrier(carrier) {
3030
+ const ref = carrier?.tenant;
3031
+ if (ref && typeof ref.id === "string") {
3032
+ return typeof ref.kind === "string" ? {
3033
+ id: ref.id,
3034
+ kind: ref.kind
3035
+ } : {
3036
+ id: ref.id
3037
+ };
3038
+ }
3039
+ const id = carrier?.tenantId;
3040
+ return typeof id === "string" ? {
3041
+ id
3042
+ } : void 0;
3043
+ }
3044
+ __name(tenantFromCarrier, "tenantFromCarrier");
3045
+ function stepTenantWrapper(option, accessor, runtime) {
3046
+ return (execution, next) => {
3047
+ if (execution.unit !== "step") return next();
3048
+ const tenant = tenantFromCarrier(execution.context);
3049
+ if (!tenant || !readTenancy(option, accessor).enabled) return next();
3050
+ return restore(runtime, tenant, next);
3051
+ };
3052
+ }
3053
+ __name(stepTenantWrapper, "stepTenantWrapper");
3054
+
2909
3055
  // src/tenant-event-republisher.ts
2910
3056
  function isTerminalRunEvent(event) {
2911
3057
  return event.type === "run.completed" || event.type === "run.failed";
@@ -3491,11 +3637,18 @@ function carrierFromAccessor(accessor) {
3491
3637
  if (traceId !== void 0) carrier.traceId = traceId;
3492
3638
  const tenantId = accessor.tenantId();
3493
3639
  if (tenantId !== void 0) carrier.tenantId = tenantId;
3640
+ const tenant = accessor.tenant?.();
3641
+ if (tenant !== void 0 && tenant.source !== "legacy") carrier.tenant = tenant;
3494
3642
  const userRef = accessor.userRef();
3495
3643
  if (userRef !== void 0) carrier.userRef = userRef;
3496
3644
  return carrier;
3497
3645
  }
3498
3646
  __name(carrierFromAccessor, "carrierFromAccessor");
3647
+ function contextSlotPresent() {
3648
+ const slot = globalThis[Symbol.for("@dudousxd/nestjs-diagnostics:accessor")];
3649
+ return !!slot?.current;
3650
+ }
3651
+ __name(contextSlotPresent, "contextSlotPresent");
3499
3652
  function isContextRuntime(x) {
3500
3653
  return !!x && typeof x.deserialize === "function";
3501
3654
  }
@@ -3681,6 +3834,38 @@ RunGatewayBootstrap = _ts_decorate13([
3681
3834
  typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
3682
3835
  ])
3683
3836
  ], RunGatewayBootstrap);
3837
+ var DurableTenancyBridge = class DurableTenancyBridge2 {
3838
+ static {
3839
+ __name(this, "DurableTenancyBridge");
3840
+ }
3841
+ options;
3842
+ moduleRef;
3843
+ unregister;
3844
+ constructor(options, moduleRef) {
3845
+ this.options = options;
3846
+ this.moduleRef = moduleRef;
3847
+ }
3848
+ async onApplicationBootstrap() {
3849
+ if (this.options.tenancy === false) return;
3850
+ const accessor = resolveAccessor(this.moduleRef);
3851
+ if (!readTenancy(this.options.tenancy, accessor).enabled) return;
3852
+ const runtime = await resolveContextRuntime();
3853
+ if (!isTenantRuntime(runtime)) return;
3854
+ this.unregister = (0, import_nestjs_durable_core19.useDurableExecution)(stepTenantWrapper(this.options.tenancy, accessor, runtime));
3855
+ }
3856
+ onModuleDestroy() {
3857
+ this.unregister?.();
3858
+ }
3859
+ };
3860
+ DurableTenancyBridge = _ts_decorate13([
3861
+ (0, import_common13.Injectable)(),
3862
+ _ts_param9(0, (0, import_common13.Inject)(import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL)),
3863
+ _ts_metadata13("design:type", Function),
3864
+ _ts_metadata13("design:paramtypes", [
3865
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3866
+ typeof import_core6.ModuleRef === "undefined" ? Object : import_core6.ModuleRef
3867
+ ])
3868
+ ], DurableTenancyBridge);
3684
3869
  var DurableModule = class _DurableModule {
3685
3870
  static {
3686
3871
  __name(this, "DurableModule");
@@ -3745,7 +3930,7 @@ var DurableModule = class _DurableModule {
3745
3930
  import_core6.ModuleRef
3746
3931
  ]
3747
3932
  },
3748
- // Legacy back-compat aliases (deprecated tokens still resolve to the same instances):
3933
+ // Deprecated tokens that published releases still import resolve to the same instances:
3749
3934
  {
3750
3935
  provide: import_nestjs_durable_core19.STATE_STORE,
3751
3936
  useExisting: import_nestjs_durable_core19.STATE_STORE_CANONICAL
@@ -3778,7 +3963,8 @@ var DurableModule = class _DurableModule {
3778
3963
  const primary = transport ?? options.transports?.[0]?.transport;
3779
3964
  const accessor = resolveAccessor(moduleRef);
3780
3965
  const context = options.context ?? (accessor ? () => carrierFromAccessor(accessor) : void 0);
3781
- const runtime = accessor ? await resolveContextRuntime() : void 0;
3966
+ const runtimeNeeded = accessor !== void 0 || contextSlotPresent();
3967
+ const runtime = runtimeNeeded ? await resolveContextRuntime() : void 0;
3782
3968
  const rehydrate = runtime && ((carrier, fn) => carrier && Object.keys(carrier).length > 0 ? runtime.deserialize(carrier, fn) : fn());
3783
3969
  if (options.consumers === false) {
3784
3970
  for (const t of [
@@ -3816,7 +4002,9 @@ var DurableModule = class _DurableModule {
3816
4002
  webhookUrl: options.webhookUrl,
3817
4003
  traceparent: options.traceparent,
3818
4004
  context,
3819
- rehydrate: rehydrate || void 0,
4005
+ rehydrate: accessor && rehydrate || void 0,
4006
+ // The run's tenant, restored around every turn (see `tenancy` above).
4007
+ tenancy: buildEngineTenancy(options.tenancy, accessor, isTenantRuntime(runtime) ? runtime : void 0),
3820
4008
  compensationRetries: options.compensationRetries,
3821
4009
  verifyTenant: auth.verifyTenant,
3822
4010
  // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving
@@ -3871,6 +4059,7 @@ var DurableModule = class _DurableModule {
3871
4059
  ]
3872
4060
  },
3873
4061
  RunGatewayBootstrap,
4062
+ DurableTenancyBridge,
3874
4063
  // Co-located in-app worker (uniform dispatch): inert unless BOTH `store` and `connection` are
3875
4064
  // set — see `in-app-worker.ts`.
3876
4065
  ...inAppWorkerProviders(),
@@ -3909,7 +4098,6 @@ var import_nestjs_durable_core20 = require("@dudousxd/nestjs-durable-core");
3909
4098
  DeadLetter,
3910
4099
  DurableModule,
3911
4100
  DurableStartClient,
3912
- DurableStep,
3913
4101
  ENTITY_METADATA,
3914
4102
  ENTITY_ON_METADATA,
3915
4103
  Entity,
@@ -3926,7 +4114,6 @@ var import_nestjs_durable_core20 = require("@dudousxd/nestjs-durable-core");
3926
4114
  On,
3927
4115
  OnDurableEvent,
3928
4116
  OnError,
3929
- OnEvent,
3930
4117
  OnWorkflowCompleted,
3931
4118
  OnWorkflowFailed,
3932
4119
  ProxyRunGateway,