@dudousxd/nestjs-durable 0.55.2 → 0.56.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,
@@ -3400,35 +3546,51 @@ function assertValidRole(options) {
3400
3546
  }
3401
3547
  }
3402
3548
  __name(assertValidRole, "assertValidRole");
3549
+ var TOPOLOGIES = [
3550
+ "standalone",
3551
+ "control-plane",
3552
+ "tenant"
3553
+ ];
3403
3554
  function assertValidTopology(options) {
3404
3555
  const topology = options.topology;
3405
- if (topology === void 0) return;
3406
- if (topology.role === "control-plane") {
3556
+ if (topology === void 0 || topology === "standalone") {
3557
+ assertValidRole(options);
3558
+ return;
3559
+ }
3560
+ if (typeof topology !== "string" || !TOPOLOGIES.includes(topology)) {
3561
+ const hint = typeof topology === "object" && topology !== null ? "\nThe object form is gone: `topology: { role: 'tenant', tenant: 'acme' }` is now `topology: 'tenant', partition: 'acme'`." : "";
3562
+ throw new Error(`topology must be 'standalone', 'control-plane' or 'tenant' (got ${JSON.stringify(topology)}).${hint}`);
3563
+ }
3564
+ if (topology === "control-plane") {
3407
3565
  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.");
3566
+ 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
3567
  }
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.");
3568
+ if (options.tenantToken !== void 0) {
3569
+ 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
3570
  }
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.`);
3571
+ const { partition: partition2, namespace } = options;
3572
+ if (partition2 !== void 0 && namespace !== void 0 && namespace !== partition2) {
3573
+ throw new Error(`topology: 'control-plane' with \`partition: '${partition2}'\` conflicts with \`namespace: '${namespace}'\`.
3574
+ On a control plane, partition becomes its namespace (the runs it drives). Set only \`partition\`, or set \`namespace\` to the same value.`);
3416
3575
  }
3417
3576
  return;
3418
3577
  }
3578
+ const partition = options.partition;
3579
+ if (typeof partition !== "string" || partition.length === 0) {
3580
+ 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.");
3581
+ }
3419
3582
  if (options.connection === void 0) {
3420
- throw new Error(`topology: { role: 'tenant', tenant: '${topology.tenant}' } needs \`connection\`.
3583
+ throw new Error(`topology: 'tenant' (partition '${partition}') needs \`connection\`.
3421
3584
  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
3585
  }
3423
3586
  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).");
3587
+ 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
3588
  }
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.");
3589
+ if (options.verifyTenant !== void 0) {
3590
+ 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
3591
  }
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.`);
3592
+ if (options.namespace !== void 0) {
3593
+ 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
3594
  }
3433
3595
  }
3434
3596
  __name(assertValidTopology, "assertValidTopology");
@@ -3445,29 +3607,14 @@ function servingPartition(options) {
3445
3607
  }
3446
3608
  __name(servingPartition, "servingPartition");
3447
3609
  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;
3610
+ if (options.topology !== "control-plane" || options.partition === void 0) return options;
3465
3611
  return {
3466
3612
  ...options,
3467
- partition: topology.tenant
3613
+ namespace: options.namespace ?? options.partition
3468
3614
  };
3469
3615
  }
3470
3616
  __name(resolveTopologyPreset, "resolveTopologyPreset");
3617
+ var TENANT_AUTH = Symbol("nestjs-durable:tenant-auth");
3471
3618
  var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3472
3619
  static {
3473
3620
  __name(this, "RunGatewayBootstrap");
@@ -3477,13 +3624,15 @@ var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3477
3624
  gateway;
3478
3625
  store;
3479
3626
  options;
3627
+ auth;
3480
3628
  unsubscribe;
3481
- constructor(engine, transport, gateway, store, options) {
3629
+ constructor(engine, transport, gateway, store, options, auth) {
3482
3630
  this.engine = engine;
3483
3631
  this.transport = transport;
3484
3632
  this.gateway = gateway;
3485
3633
  this.store = store;
3486
3634
  this.options = options;
3635
+ this.auth = auth;
3487
3636
  }
3488
3637
  onApplicationBootstrap() {
3489
3638
  if (!isDrivingOperator(this.options) || !this.transport) return;
@@ -3496,13 +3645,13 @@ var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3496
3645
  publishRunReply: publishRunReply.bind(this.transport)
3497
3646
  };
3498
3647
  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
3648
+ verifyTenant: this.auth.verifyTenant,
3649
+ // Mirrors Agora's rule (`warnWithoutVerifier: topology === 'control-plane'`): only a deployment
3650
+ // that EXPLICITLY names itself the control plane is told it runs without tenant auth. On a
3651
+ // `standalone` operator (role inferred from `store`) anyone with broker access
3503
3652
  // can already enqueue steps and results there, so the warning would be noise on every boot
3504
3653
  // of an app that never serves tenants.
3505
- warnWithoutVerifier: this.options.topology?.role === "control-plane"
3654
+ warnWithoutVerifier: this.options.topology === "control-plane"
3506
3655
  }).start();
3507
3656
  }
3508
3657
  if (typeof publishTenantEvent === "function") {
@@ -3521,13 +3670,15 @@ RunGatewayBootstrap = _ts_decorate13([
3521
3670
  _ts_param9(1, (0, import_common13.Inject)(import_nestjs_durable_core19.TRANSPORT_CANONICAL)),
3522
3671
  _ts_param9(3, (0, import_common13.Inject)(import_nestjs_durable_core19.STATE_STORE_CANONICAL)),
3523
3672
  _ts_param9(4, (0, import_common13.Inject)(import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL)),
3673
+ _ts_param9(5, (0, import_common13.Inject)(TENANT_AUTH)),
3524
3674
  _ts_metadata13("design:type", Function),
3525
3675
  _ts_metadata13("design:paramtypes", [
3526
3676
  typeof import_nestjs_durable_core19.WorkflowEngine === "undefined" ? Object : import_nestjs_durable_core19.WorkflowEngine,
3527
3677
  Object,
3528
3678
  typeof import_nestjs_durable_core19.RunGateway === "undefined" ? Object : import_nestjs_durable_core19.RunGateway,
3529
3679
  Object,
3530
- typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions
3680
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3681
+ typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
3531
3682
  ])
3532
3683
  ], RunGatewayBootstrap);
3533
3684
  var DurableModule = class _DurableModule {
@@ -3552,19 +3703,9 @@ var DurableModule = class _DurableModule {
3552
3703
  inject: options.inject ?? []
3553
3704
  });
3554
3705
  }
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
- */
3706
+ /** Validates the topology and its role/axis constraints; see {@link assertValidTopology}. */
3562
3707
  static assertValid(options) {
3563
- if (options.topology !== void 0) {
3564
- assertValidTopology(options);
3565
- return;
3566
- }
3567
- assertValidRole(options);
3708
+ assertValidTopology(options);
3568
3709
  }
3569
3710
  static build(optionsProvider) {
3570
3711
  return {
@@ -3593,6 +3734,17 @@ var DurableModule = class _DurableModule {
3593
3734
  import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL
3594
3735
  ]
3595
3736
  },
3737
+ {
3738
+ provide: TENANT_AUTH,
3739
+ useFactory: /* @__PURE__ */ __name((options, moduleRef) => ({
3740
+ verifyTenant: resolveTenantVerifier(options.verifyTenant, moduleRef),
3741
+ tenantToken: resolveTenantTokenSource(options.tenantToken, moduleRef)
3742
+ }), "useFactory"),
3743
+ inject: [
3744
+ import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL,
3745
+ import_core6.ModuleRef
3746
+ ]
3747
+ },
3596
3748
  // Legacy back-compat aliases (deprecated tokens still resolve to the same instances):
3597
3749
  {
3598
3750
  provide: import_nestjs_durable_core19.STATE_STORE,
@@ -3611,9 +3763,14 @@ var DurableModule = class _DurableModule {
3611
3763
  // `DurableStartClient` facade for a thin worker (no `store`) — either way, `WorkflowService`
3612
3764
  // and app code call `engine.start(...)` unchanged.
3613
3765
  provide: import_nestjs_durable_core19.WorkflowEngine,
3614
- useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef) => {
3766
+ useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef, auth) => {
3615
3767
  if (options.store === void 0) {
3616
- return new DurableStartClient(options);
3768
+ return new DurableStartClient({
3769
+ ...options,
3770
+ ...auth.tenantToken !== void 0 ? {
3771
+ tenantToken: auth.tenantToken
3772
+ } : {}
3773
+ });
3617
3774
  }
3618
3775
  if (!store) {
3619
3776
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
@@ -3661,7 +3818,7 @@ var DurableModule = class _DurableModule {
3661
3818
  context,
3662
3819
  rehydrate: rehydrate || void 0,
3663
3820
  compensationRetries: options.compensationRetries,
3664
- verifyTenant: options.verifyTenant,
3821
+ verifyTenant: auth.verifyTenant,
3665
3822
  // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving
3666
3823
  // each `pending` run in the store for a DRIVING instance's poll. A driving operator gets
3667
3824
  // the engine's default in-process dispatcher: for a body registered inline, it runs
@@ -3681,7 +3838,8 @@ var DurableModule = class _DurableModule {
3681
3838
  import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL,
3682
3839
  import_nestjs_durable_core19.STATE_STORE_CANONICAL,
3683
3840
  import_nestjs_durable_core19.TRANSPORT_CANONICAL,
3684
- import_core6.ModuleRef
3841
+ import_core6.ModuleRef,
3842
+ TENANT_AUTH
3685
3843
  ]
3686
3844
  },
3687
3845
  WorkflowService,
@@ -3696,19 +3854,20 @@ var DurableModule = class _DurableModule {
3696
3854
  // gateway whose every method rejects with a clear tenant error.
3697
3855
  {
3698
3856
  provide: import_nestjs_durable_core19.RunGateway,
3699
- useFactory: /* @__PURE__ */ __name((options, store, engine) => {
3857
+ useFactory: /* @__PURE__ */ __name((options, store, engine, auth) => {
3700
3858
  if (options.store !== void 0) {
3701
3859
  if (!store) {
3702
3860
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
3703
3861
  }
3704
3862
  return new StoreRunGateway(store, engine);
3705
3863
  }
3706
- return options.transport ? new ProxyRunGateway(options.transport, options.partition ?? "default", options.runGatewayTimeoutMs, void 0, options.tenantToken) : unavailableRunGateway();
3864
+ return options.transport ? new ProxyRunGateway(options.transport, options.partition ?? "default", options.runGatewayTimeoutMs, void 0, auth.tenantToken) : unavailableRunGateway();
3707
3865
  }, "useFactory"),
3708
3866
  inject: [
3709
3867
  import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL,
3710
3868
  import_nestjs_durable_core19.STATE_STORE_CANONICAL,
3711
- import_nestjs_durable_core19.WorkflowEngine
3869
+ import_nestjs_durable_core19.WorkflowEngine,
3870
+ TENANT_AUTH
3712
3871
  ]
3713
3872
  },
3714
3873
  RunGatewayBootstrap,