@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.js CHANGED
@@ -119,9 +119,6 @@ __name(fileOfFrame, "fileOfFrame");
119
119
  var WORKFLOW_METADATA = Symbol("nestjs-durable:workflow");
120
120
  function Workflow(options) {
121
121
  const declaredIn = declaringFile(Workflow);
122
- if (options.input !== void 0 && options.inputSchema !== void 0) {
123
- throw new Error(`@Workflow ${options.name}: set either \`input\` or its alias \`inputSchema\`, not both`);
124
- }
125
122
  return (target) => {
126
123
  rememberDeclaringFile(target, declaredIn);
127
124
  const meta = {
@@ -133,7 +130,7 @@ function Workflow(options) {
133
130
  singleton: options.singleton,
134
131
  concurrency: options.concurrency,
135
132
  executionTimeout: options.executionTimeout,
136
- input: options.input ?? options.inputSchema,
133
+ input: options.input,
137
134
  output: options.output,
138
135
  validateInput: options.validateInput,
139
136
  searchAttributes: options.searchAttributes,
@@ -190,7 +187,6 @@ function Step(nameOrOptions) {
190
187
  };
191
188
  }
192
189
  __name(Step, "Step");
193
- var DurableStep = Step;
194
190
  function getDurableStepMeta(method) {
195
191
  return Reflect.getMetadata(DURABLE_STEP_METADATA, method);
196
192
  }
@@ -318,7 +314,6 @@ function addEventSubscriptions(target, entries) {
318
314
  ], target);
319
315
  }
320
316
  __name(addEventSubscriptions, "addEventSubscriptions");
321
- var OnEvent = OnDurableEvent;
322
317
  function getOnEvents(meta, target) {
323
318
  const fromDecorator = Reflect.getMetadata(ON_EVENT_METADATA, target) ?? [];
324
319
  const names = /* @__PURE__ */ new Set();
@@ -1061,7 +1056,7 @@ function unavailableRunGateway() {
1061
1056
  __name(unavailableRunGateway, "unavailableRunGateway");
1062
1057
 
1063
1058
  // src/durable.module.ts
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 } from "@dudousxd/nestjs-durable-core";
1059
+ 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";
1065
1060
  import { Inject as Inject9, Injectable as Injectable13, Module } from "@nestjs/common";
1066
1061
  import { DiscoveryModule, ModuleRef as ModuleRef2 } from "@nestjs/core";
1067
1062
 
@@ -2519,9 +2514,23 @@ var StoreRunGateway = class {
2519
2514
  role: "control-plane"
2520
2515
  };
2521
2516
  }
2522
- async getRunDetail(runId, options) {
2517
+ /**
2518
+ * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s
2519
+ * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).
2520
+ */
2521
+ scoped(query) {
2522
+ return typeof this.engine?.scopeRunQuery === "function" ? this.engine.scopeRunQuery(query) : query;
2523
+ }
2524
+ /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */
2525
+ async visibleRun(runId) {
2523
2526
  const run = await this.store.getRun(runId);
2524
2527
  if (!run) return null;
2528
+ const { tenantIds } = this.scoped({});
2529
+ return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;
2530
+ }
2531
+ async getRunDetail(runId, options) {
2532
+ const run = await this.visibleRun(runId);
2533
+ if (!run) return null;
2525
2534
  const links = await this.lifecycleLinks(run);
2526
2535
  const over = options?.summarizeFansOver;
2527
2536
  if (over === void 0) {
@@ -2666,10 +2675,10 @@ var StoreRunGateway = class {
2666
2675
  return this.engine.lifecycleSubscribers(workflow, kind, namespace);
2667
2676
  }
2668
2677
  getRun(runId) {
2669
- return this.store.getRun(runId);
2678
+ return this.visibleRun(runId);
2670
2679
  }
2671
2680
  async getFanMembers(runId, group, query) {
2672
- if (!await this.store.getRun(runId)) return null;
2681
+ if (!await this.visibleRun(runId)) return null;
2673
2682
  if (aggregatesCheckpoints(this.store)) {
2674
2683
  const stats = await this.store.checkpointStats(runId, {
2675
2684
  group
@@ -2691,7 +2700,7 @@ var StoreRunGateway = class {
2691
2700
  return pageFan2(await this.store.listCheckpoints(runId), group, query);
2692
2701
  }
2693
2702
  async listRuns(query) {
2694
- const runs = await this.store.listRuns(withoutRegistry(query));
2703
+ const runs = await this.store.listRuns(this.scoped(withoutRegistry(query)));
2695
2704
  const waiterByRun = indexWaitersByRun(await listSignalWaitersOfRuns(this.store, runs.filter((run) => run.status === "suspended").map((run) => run.id)));
2696
2705
  return runs.map((run) => {
2697
2706
  const waiting = resolveRunWaiting(run, waiterByRun);
@@ -2708,7 +2717,7 @@ var StoreRunGateway = class {
2708
2717
  * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
2709
2718
  */
2710
2719
  async runFacets(query) {
2711
- const scoped = withoutRegistry(query);
2720
+ const scoped = this.scoped(withoutRegistry(query));
2712
2721
  if (this.store.runFacets) return this.store.runFacets(scoped);
2713
2722
  const runs = await this.store.listRuns(scoped);
2714
2723
  return mergeRunFacetRows(runs.map((r) => ({
@@ -2725,7 +2734,7 @@ var StoreRunGateway = class {
2725
2734
  * still works without it.
2726
2735
  */
2727
2736
  async runValueFacets(axis, query, opts) {
2728
- return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
2737
+ return this.store.runValueFacets?.(axis, this.scoped(withoutRegistry(query)), opts) ?? [];
2729
2738
  }
2730
2739
  /**
2731
2740
  * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
@@ -2741,11 +2750,11 @@ var StoreRunGateway = class {
2741
2750
  if (runIds.length === 0) return {};
2742
2751
  const idSet = new Set(runIds);
2743
2752
  const [suspended, waiters] = await Promise.all([
2744
- this.store.listRuns({
2753
+ this.store.listRuns(this.scoped({
2745
2754
  statuses: [
2746
2755
  "suspended"
2747
2756
  ]
2748
- }),
2757
+ })),
2749
2758
  listSignalWaitersOfRuns(this.store, runIds)
2750
2759
  ]);
2751
2760
  const waiterByRun = indexWaitersByRun(waiters);
@@ -2781,10 +2790,44 @@ var StoreRunGateway = class {
2781
2790
  republishLifecycle(target) {
2782
2791
  return this.engine.republishLifecycle(target);
2783
2792
  }
2793
+ /**
2794
+ * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a
2795
+ * run that does not exist yet are held until its row shows whose it is.
2796
+ */
2784
2797
  subscribe(runId, onEvent) {
2785
- return this.engine.subscribe((event) => {
2786
- if (event.runId === runId) onEvent(event);
2798
+ const { tenantIds } = this.scoped({});
2799
+ if (!tenantIds) {
2800
+ return this.engine.subscribe((event) => {
2801
+ if (event.runId === runId) onEvent(event);
2802
+ });
2803
+ }
2804
+ let visible;
2805
+ let held = [];
2806
+ let checking = false;
2807
+ const check = /* @__PURE__ */ __name(() => {
2808
+ if (checking || visible !== void 0) return;
2809
+ checking = true;
2810
+ void this.store.getRun(runId).then((run) => {
2811
+ if (run) visible = tenantIds.includes(run.tenantId ?? null);
2812
+ }, () => void 0).finally(() => {
2813
+ checking = false;
2814
+ if (visible === void 0) return;
2815
+ const pending = held;
2816
+ held = [];
2817
+ if (visible) for (const event of pending) onEvent(event);
2818
+ });
2819
+ }, "check");
2820
+ const off = this.engine.subscribe((event) => {
2821
+ if (event.runId !== runId || visible === false) return;
2822
+ if (visible) return onEvent(event);
2823
+ held.push(event);
2824
+ check();
2787
2825
  });
2826
+ check();
2827
+ return () => {
2828
+ held = [];
2829
+ off();
2830
+ };
2788
2831
  }
2789
2832
  };
2790
2833
  StoreRunGateway = _ts_decorate9([
@@ -2797,6 +2840,111 @@ StoreRunGateway = _ts_decorate9([
2797
2840
  ])
2798
2841
  ], StoreRunGateway);
2799
2842
 
2843
+ // src/tenancy.ts
2844
+ var SLOT = Symbol.for("@dudousxd/nestjs-diagnostics:accessor");
2845
+ function accessorOf(accessor) {
2846
+ if (accessor) return accessor;
2847
+ const slot = globalThis[SLOT];
2848
+ return slot?.current ?? void 0;
2849
+ }
2850
+ __name(accessorOf, "accessorOf");
2851
+ function readTenancy(option, accessor) {
2852
+ const a = accessorOf(accessor);
2853
+ if (option === false || typeof a?.tenancy !== "function" || typeof a.tenantFilter !== "function") {
2854
+ return {
2855
+ enabled: false
2856
+ };
2857
+ }
2858
+ const own = typeof option === "object" ? option : {};
2859
+ const inherit = own.enabled === void 0 || own.enabled === "inherit";
2860
+ if (!(inherit ? a.tenancy().enabled : own.enabled)) return {
2861
+ enabled: false
2862
+ };
2863
+ const kinds = own.kinds;
2864
+ const tenantFilter = a.tenantFilter.bind(a);
2865
+ return {
2866
+ enabled: true,
2867
+ nullRows: own.nullRows ?? "tenantless",
2868
+ filter: /* @__PURE__ */ __name(() => tenantFilter(kinds ? {
2869
+ kinds
2870
+ } : void 0), "filter")
2871
+ };
2872
+ }
2873
+ __name(readTenancy, "readTenancy");
2874
+ function isTenantRuntime(x) {
2875
+ return !!x && typeof x.withTenant === "function";
2876
+ }
2877
+ __name(isTenantRuntime, "isTenantRuntime");
2878
+ function restore(runtime, tenant, fn) {
2879
+ return runtime.withTenant({
2880
+ id: tenant.id,
2881
+ kind: tenant.kind ?? "unknown",
2882
+ source: "carrier"
2883
+ }, fn);
2884
+ }
2885
+ __name(restore, "restore");
2886
+ function buildEngineTenancy(option, accessor, runtime) {
2887
+ if (option === false || !runtime) return void 0;
2888
+ return {
2889
+ current() {
2890
+ const t = readTenancy(option, accessor);
2891
+ if (!t.enabled) return void 0;
2892
+ const f = t.filter();
2893
+ return f.mode === "tenant" ? {
2894
+ id: f.tenant.id,
2895
+ kind: f.tenant.kind
2896
+ } : void 0;
2897
+ },
2898
+ filter() {
2899
+ const t = readTenancy(option, accessor);
2900
+ if (!t.enabled) return {
2901
+ mode: "system"
2902
+ };
2903
+ const f = t.filter();
2904
+ if (f.mode === "tenant") return {
2905
+ mode: "tenant",
2906
+ tenantId: f.tenant.id,
2907
+ nullRows: t.nullRows
2908
+ };
2909
+ if (f.mode === "tenantless") return {
2910
+ mode: "tenantless"
2911
+ };
2912
+ return f.mode === "all" ? {
2913
+ mode: "all"
2914
+ } : {
2915
+ mode: "system"
2916
+ };
2917
+ },
2918
+ run: /* @__PURE__ */ __name((tenant, fn) => restore(runtime, tenant, fn), "run")
2919
+ };
2920
+ }
2921
+ __name(buildEngineTenancy, "buildEngineTenancy");
2922
+ function tenantFromCarrier(carrier) {
2923
+ const ref = carrier?.tenant;
2924
+ if (ref && typeof ref.id === "string") {
2925
+ return typeof ref.kind === "string" ? {
2926
+ id: ref.id,
2927
+ kind: ref.kind
2928
+ } : {
2929
+ id: ref.id
2930
+ };
2931
+ }
2932
+ const id = carrier?.tenantId;
2933
+ return typeof id === "string" ? {
2934
+ id
2935
+ } : void 0;
2936
+ }
2937
+ __name(tenantFromCarrier, "tenantFromCarrier");
2938
+ function stepTenantWrapper(option, accessor, runtime) {
2939
+ return (execution, next) => {
2940
+ if (execution.unit !== "step") return next();
2941
+ const tenant = tenantFromCarrier(execution.context);
2942
+ if (!tenant || !readTenancy(option, accessor).enabled) return next();
2943
+ return restore(runtime, tenant, next);
2944
+ };
2945
+ }
2946
+ __name(stepTenantWrapper, "stepTenantWrapper");
2947
+
2800
2948
  // src/tenant-event-republisher.ts
2801
2949
  function isTerminalRunEvent(event) {
2802
2950
  return event.type === "run.completed" || event.type === "run.failed";
@@ -3382,11 +3530,18 @@ function carrierFromAccessor(accessor) {
3382
3530
  if (traceId !== void 0) carrier.traceId = traceId;
3383
3531
  const tenantId = accessor.tenantId();
3384
3532
  if (tenantId !== void 0) carrier.tenantId = tenantId;
3533
+ const tenant = accessor.tenant?.();
3534
+ if (tenant !== void 0 && tenant.source !== "legacy") carrier.tenant = tenant;
3385
3535
  const userRef = accessor.userRef();
3386
3536
  if (userRef !== void 0) carrier.userRef = userRef;
3387
3537
  return carrier;
3388
3538
  }
3389
3539
  __name(carrierFromAccessor, "carrierFromAccessor");
3540
+ function contextSlotPresent() {
3541
+ const slot = globalThis[Symbol.for("@dudousxd/nestjs-diagnostics:accessor")];
3542
+ return !!slot?.current;
3543
+ }
3544
+ __name(contextSlotPresent, "contextSlotPresent");
3390
3545
  function isContextRuntime(x) {
3391
3546
  return !!x && typeof x.deserialize === "function";
3392
3547
  }
@@ -3572,6 +3727,38 @@ RunGatewayBootstrap = _ts_decorate13([
3572
3727
  typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
3573
3728
  ])
3574
3729
  ], RunGatewayBootstrap);
3730
+ var DurableTenancyBridge = class DurableTenancyBridge2 {
3731
+ static {
3732
+ __name(this, "DurableTenancyBridge");
3733
+ }
3734
+ options;
3735
+ moduleRef;
3736
+ unregister;
3737
+ constructor(options, moduleRef) {
3738
+ this.options = options;
3739
+ this.moduleRef = moduleRef;
3740
+ }
3741
+ async onApplicationBootstrap() {
3742
+ if (this.options.tenancy === false) return;
3743
+ const accessor = resolveAccessor(this.moduleRef);
3744
+ if (!readTenancy(this.options.tenancy, accessor).enabled) return;
3745
+ const runtime = await resolveContextRuntime();
3746
+ if (!isTenantRuntime(runtime)) return;
3747
+ this.unregister = useDurableExecution(stepTenantWrapper(this.options.tenancy, accessor, runtime));
3748
+ }
3749
+ onModuleDestroy() {
3750
+ this.unregister?.();
3751
+ }
3752
+ };
3753
+ DurableTenancyBridge = _ts_decorate13([
3754
+ Injectable13(),
3755
+ _ts_param9(0, Inject9(DURABLE_OPTIONS_CANONICAL8)),
3756
+ _ts_metadata13("design:type", Function),
3757
+ _ts_metadata13("design:paramtypes", [
3758
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3759
+ typeof ModuleRef2 === "undefined" ? Object : ModuleRef2
3760
+ ])
3761
+ ], DurableTenancyBridge);
3575
3762
  var DurableModule = class _DurableModule {
3576
3763
  static {
3577
3764
  __name(this, "DurableModule");
@@ -3636,7 +3823,7 @@ var DurableModule = class _DurableModule {
3636
3823
  ModuleRef2
3637
3824
  ]
3638
3825
  },
3639
- // Legacy back-compat aliases (deprecated tokens still resolve to the same instances):
3826
+ // Deprecated tokens that published releases still import resolve to the same instances:
3640
3827
  {
3641
3828
  provide: STATE_STORE,
3642
3829
  useExisting: STATE_STORE_CANONICAL4
@@ -3669,7 +3856,8 @@ var DurableModule = class _DurableModule {
3669
3856
  const primary = transport ?? options.transports?.[0]?.transport;
3670
3857
  const accessor = resolveAccessor(moduleRef);
3671
3858
  const context = options.context ?? (accessor ? () => carrierFromAccessor(accessor) : void 0);
3672
- const runtime = accessor ? await resolveContextRuntime() : void 0;
3859
+ const runtimeNeeded = accessor !== void 0 || contextSlotPresent();
3860
+ const runtime = runtimeNeeded ? await resolveContextRuntime() : void 0;
3673
3861
  const rehydrate = runtime && ((carrier, fn) => carrier && Object.keys(carrier).length > 0 ? runtime.deserialize(carrier, fn) : fn());
3674
3862
  if (options.consumers === false) {
3675
3863
  for (const t of [
@@ -3707,7 +3895,9 @@ var DurableModule = class _DurableModule {
3707
3895
  webhookUrl: options.webhookUrl,
3708
3896
  traceparent: options.traceparent,
3709
3897
  context,
3710
- rehydrate: rehydrate || void 0,
3898
+ rehydrate: accessor && rehydrate || void 0,
3899
+ // The run's tenant, restored around every turn (see `tenancy` above).
3900
+ tenancy: buildEngineTenancy(options.tenancy, accessor, isTenantRuntime(runtime) ? runtime : void 0),
3711
3901
  compensationRetries: options.compensationRetries,
3712
3902
  verifyTenant: auth.verifyTenant,
3713
3903
  // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving
@@ -3762,6 +3952,7 @@ var DurableModule = class _DurableModule {
3762
3952
  ]
3763
3953
  },
3764
3954
  RunGatewayBootstrap,
3955
+ DurableTenancyBridge,
3765
3956
  // Co-located in-app worker (uniform dispatch): inert unless BOTH `store` and `connection` are
3766
3957
  // set — see `in-app-worker.ts`.
3767
3958
  ...inAppWorkerProviders(),
@@ -3799,7 +3990,6 @@ export {
3799
3990
  DeadLetter,
3800
3991
  DurableModule,
3801
3992
  DurableStartClient,
3802
- DurableStep,
3803
3993
  ENTITY_METADATA,
3804
3994
  ENTITY_ON_METADATA,
3805
3995
  Entity,
@@ -3816,7 +4006,6 @@ export {
3816
4006
  On,
3817
4007
  OnDurableEvent,
3818
4008
  OnError,
3819
- OnEvent,
3820
4009
  OnWorkflowCompleted,
3821
4010
  OnWorkflowFailed,
3822
4011
  ProxyRunGateway,