@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.js CHANGED
@@ -351,6 +351,150 @@ __name(attributesOf, "attributesOf");
351
351
  import { resolveTenantToken, workflowName } from "@dudousxd/nestjs-durable-core";
352
352
  import { Injectable } from "@nestjs/common";
353
353
 
354
+ // src/tenant-contracts.ts
355
+ var RESOLVED = Symbol("nestjs-durable:resolved-tenant-auth");
356
+ function markResolved(fn) {
357
+ Object.defineProperty(fn, RESOLVED, {
358
+ value: true
359
+ });
360
+ return fn;
361
+ }
362
+ __name(markResolved, "markResolved");
363
+ function isResolved(value) {
364
+ return typeof value === "function" && value[RESOLVED] === true;
365
+ }
366
+ __name(isResolved, "isResolved");
367
+ function isClass(value, method) {
368
+ if (typeof value !== "function") return false;
369
+ const proto = value.prototype;
370
+ if (typeof proto?.[method] === "function") return true;
371
+ return /^class[\s{]/.test(Function.prototype.toString.call(value));
372
+ }
373
+ __name(isClass, "isClass");
374
+ function hasMethod(value, method) {
375
+ return typeof value === "object" && value !== null && typeof value[method] === "function";
376
+ }
377
+ __name(hasMethod, "hasMethod");
378
+ function lazyDefault(value, method) {
379
+ if (typeof value !== "object" || value === null || !("default" in value)) return void 0;
380
+ const target = value.default;
381
+ return isClass(target, method) || hasMethod(target, method) ? target : void 0;
382
+ }
383
+ __name(lazyDefault, "lazyDefault");
384
+ function instanceFactory(Class, moduleRef) {
385
+ let pending;
386
+ return () => {
387
+ pending ??= (async () => {
388
+ if (!moduleRef) return new Class();
389
+ try {
390
+ const registered = moduleRef.get(Class, {
391
+ strict: false
392
+ });
393
+ if (registered) return registered;
394
+ } catch {
395
+ }
396
+ try {
397
+ return await moduleRef.create(Class);
398
+ } catch (cause) {
399
+ 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`, {
400
+ cause
401
+ });
402
+ }
403
+ })();
404
+ pending.catch(() => {
405
+ pending = void 0;
406
+ });
407
+ return pending;
408
+ };
409
+ }
410
+ __name(instanceFactory, "instanceFactory");
411
+ function contractInstance(target, method, moduleRef) {
412
+ if (isClass(target, method)) return instanceFactory(target, moduleRef);
413
+ const instance = Promise.resolve(target);
414
+ return () => instance;
415
+ }
416
+ __name(contractInstance, "contractInstance");
417
+ function functionOrLazy(fn, method, moduleRef) {
418
+ let lazy;
419
+ let plain = false;
420
+ let probing;
421
+ return async (...args) => {
422
+ for (; ; ) {
423
+ if (lazy) return {
424
+ contract: await lazy()
425
+ };
426
+ if (plain) return {
427
+ result: await fn(...args)
428
+ };
429
+ if (!probing) {
430
+ const probe = (async () => fn(...args))();
431
+ probing = probe;
432
+ try {
433
+ const result = await probe;
434
+ const target = lazyDefault(result, method);
435
+ if (target === void 0) {
436
+ plain = true;
437
+ return {
438
+ result
439
+ };
440
+ }
441
+ lazy = contractInstance(target, method, moduleRef);
442
+ return {
443
+ contract: await lazy()
444
+ };
445
+ } finally {
446
+ if (probing === probe) probing = void 0;
447
+ }
448
+ }
449
+ await probing.catch(() => void 0);
450
+ }
451
+ };
452
+ }
453
+ __name(functionOrLazy, "functionOrLazy");
454
+ function resolveTenantVerifier(option, moduleRef) {
455
+ if (option === void 0 || isResolved(option)) return option;
456
+ const instance = isClass(option, "verify") || hasMethod(option, "verify") ? contractInstance(option, "verify", moduleRef) : void 0;
457
+ if (!instance && typeof option !== "function") {
458
+ throw new Error("`verifyTenant` must be a function, an object or class with verify(), or a lazy import of one.");
459
+ }
460
+ const call = functionOrLazy(option, "verify", moduleRef);
461
+ return markResolved(async (input) => {
462
+ if (instance) return (await instance()).verify(input);
463
+ const probed = await call(input);
464
+ if ("contract" in probed) return probed.contract.verify(input);
465
+ return probed.result;
466
+ });
467
+ }
468
+ __name(resolveTenantVerifier, "resolveTenantVerifier");
469
+ function requireToken(token) {
470
+ if (typeof token !== "string" || token.length === 0) {
471
+ throw new Error("tenantToken produced no token (an empty or non-string value)");
472
+ }
473
+ return token;
474
+ }
475
+ __name(requireToken, "requireToken");
476
+ function resolveTenantTokenSource(option, moduleRef) {
477
+ if (typeof option === "string") {
478
+ if (option.length === 0) {
479
+ throw new Error("`tenantToken` is an empty string. Set the token this tenant presents, or remove `tenantToken` to send the partition.");
480
+ }
481
+ return option;
482
+ }
483
+ if (option === void 0 || isResolved(option)) return option;
484
+ const instance = isClass(option, "token") || hasMethod(option, "token") ? contractInstance(option, "token", moduleRef) : void 0;
485
+ if (!instance && typeof option !== "function") {
486
+ throw new Error("`tenantToken` must be a string, a function, an object or class with token(), or a lazy import of one.");
487
+ }
488
+ const call = functionOrLazy(option, "token", moduleRef);
489
+ return markResolved(async () => {
490
+ if (instance) return requireToken(await (await instance()).token());
491
+ const probed = await call();
492
+ if ("contract" in probed) return requireToken(await probed.contract.token());
493
+ return requireToken(probed.result);
494
+ });
495
+ }
496
+ __name(resolveTenantTokenSource, "resolveTenantTokenSource");
497
+
354
498
  // src/worker-sdk.ts
355
499
  async function workerSdk() {
356
500
  try {
@@ -398,17 +542,19 @@ var DurableStartClient = class {
398
542
  options;
399
543
  deps;
400
544
  tenant;
545
+ tenantToken;
401
546
  constructor(options, deps) {
402
547
  this.options = options;
403
548
  this.deps = deps;
404
549
  this.tenant = options.partition ?? "default";
550
+ this.tenantToken = resolveTenantTokenSource(options.tenantToken);
405
551
  }
406
552
  async start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
407
553
  const name = workflowName(workflow);
408
554
  await startRun(this.options.connection, {
409
555
  // The signed token (when configured) rides in the `tenant` field, as on every run request; an
410
556
  // operator with `verifyTenant` derives the run's namespace from it.
411
- tenant: this.options.tenantToken !== void 0 ? await resolveTenantToken(this.options.tenantToken) : this.tenant,
557
+ tenant: this.tenantToken !== void 0 ? await resolveTenantToken(this.tenantToken) : this.tenant,
412
558
  workflow: name,
413
559
  input,
414
560
  runId,
@@ -3291,35 +3437,51 @@ function assertValidRole(options) {
3291
3437
  }
3292
3438
  }
3293
3439
  __name(assertValidRole, "assertValidRole");
3440
+ var TOPOLOGIES = [
3441
+ "standalone",
3442
+ "control-plane",
3443
+ "tenant"
3444
+ ];
3294
3445
  function assertValidTopology(options) {
3295
3446
  const topology = options.topology;
3296
- if (topology === void 0) return;
3297
- if (topology.role === "control-plane") {
3447
+ if (topology === void 0 || topology === "standalone") {
3448
+ assertValidRole(options);
3449
+ return;
3450
+ }
3451
+ if (typeof topology !== "string" || !TOPOLOGIES.includes(topology)) {
3452
+ const hint = typeof topology === "object" && topology !== null ? "\nThe object form is gone: `topology: { role: 'tenant', tenant: 'acme' }` is now `topology: 'tenant', partition: 'acme'`." : "";
3453
+ throw new Error(`topology must be 'standalone', 'control-plane' or 'tenant' (got ${JSON.stringify(topology)}).${hint}`);
3454
+ }
3455
+ if (topology === "control-plane") {
3298
3456
  if (options.store === void 0 || options.transport === void 0 && options.transports === void 0) {
3299
- 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.");
3457
+ 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.");
3300
3458
  }
3301
- if (options.partition !== void 0) {
3302
- 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.");
3459
+ if (options.tenantToken !== void 0) {
3460
+ 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.");
3303
3461
  }
3304
- if (topology.tenant !== void 0 && options.namespace !== void 0 && options.namespace !== topology.tenant) {
3305
- throw new Error(`topology: { role: 'control-plane', tenant: '${topology.tenant}' } conflicts with \`namespace: '${options.namespace}'\`.
3306
- tenant maps 1:1 onto namespace (the operator's poll-scoping axis) \u2014 set only \`tenant\`, or set \`namespace\` to the same value.`);
3462
+ const { partition: partition2, namespace } = options;
3463
+ if (partition2 !== void 0 && namespace !== void 0 && namespace !== partition2) {
3464
+ throw new Error(`topology: 'control-plane' with \`partition: '${partition2}'\` conflicts with \`namespace: '${namespace}'\`.
3465
+ On a control plane, partition becomes its namespace (the runs it drives). Set only \`partition\`, or set \`namespace\` to the same value.`);
3307
3466
  }
3308
3467
  return;
3309
3468
  }
3469
+ const partition = options.partition;
3470
+ if (typeof partition !== "string" || partition.length === 0) {
3471
+ 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.");
3472
+ }
3310
3473
  if (options.connection === void 0) {
3311
- throw new Error(`topology: { role: 'tenant', tenant: '${topology.tenant}' } needs \`connection\`.
3474
+ throw new Error(`topology: 'tenant' (partition '${partition}') needs \`connection\`.
3312
3475
  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.`);
3313
3476
  }
3314
3477
  if (options.store !== void 0) {
3315
- 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).");
3478
+ 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).");
3316
3479
  }
3317
- if (options.namespace !== void 0) {
3318
- 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.");
3480
+ if (options.verifyTenant !== void 0) {
3481
+ 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.");
3319
3482
  }
3320
- if (options.partition !== void 0 && options.partition !== topology.tenant) {
3321
- throw new Error(`topology: { role: 'tenant', tenant: '${topology.tenant}' } conflicts with \`partition: '${options.partition}'\`.
3322
- tenant maps 1:1 onto partition (the worker queue-routing suffix) \u2014 set only \`tenant\`, or set \`partition\` to the same value.`);
3483
+ if (options.namespace !== void 0) {
3484
+ 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.");
3323
3485
  }
3324
3486
  }
3325
3487
  __name(assertValidTopology, "assertValidTopology");
@@ -3336,29 +3498,14 @@ function servingPartition(options) {
3336
3498
  }
3337
3499
  __name(servingPartition, "servingPartition");
3338
3500
  function resolveTopologyPreset(options) {
3339
- const topology = options.topology;
3340
- if (topology === void 0) return options;
3341
- if (topology.role === "control-plane") {
3342
- if (topology.tenant === void 0) return options;
3343
- return {
3344
- ...options,
3345
- // An explicit `namespace` is already validated equal to `tenant` (assertValidTopology), so
3346
- // keeping it is a no-op rather than a conflict.
3347
- namespace: options.namespace ?? topology.tenant,
3348
- // The tenant is ALSO this node's worker-routing suffix: its engine now dispatches a run's steps
3349
- // to `<name>@<tenant>` (core's `stepGroup`), so its own co-located worker must SUBSCRIBE those
3350
- // same tokens. Without this the node would dispatch into queues it is not itself listening on.
3351
- // `partition` is user-forbidden on this role (assertValidTopology), so we own it here.
3352
- partition: topology.tenant
3353
- };
3354
- }
3355
- if (options.partition !== void 0) return options;
3501
+ if (options.topology !== "control-plane" || options.partition === void 0) return options;
3356
3502
  return {
3357
3503
  ...options,
3358
- partition: topology.tenant
3504
+ namespace: options.namespace ?? options.partition
3359
3505
  };
3360
3506
  }
3361
3507
  __name(resolveTopologyPreset, "resolveTopologyPreset");
3508
+ var TENANT_AUTH = Symbol("nestjs-durable:tenant-auth");
3362
3509
  var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3363
3510
  static {
3364
3511
  __name(this, "RunGatewayBootstrap");
@@ -3368,13 +3515,15 @@ var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3368
3515
  gateway;
3369
3516
  store;
3370
3517
  options;
3518
+ auth;
3371
3519
  unsubscribe;
3372
- constructor(engine, transport, gateway, store, options) {
3520
+ constructor(engine, transport, gateway, store, options, auth) {
3373
3521
  this.engine = engine;
3374
3522
  this.transport = transport;
3375
3523
  this.gateway = gateway;
3376
3524
  this.store = store;
3377
3525
  this.options = options;
3526
+ this.auth = auth;
3378
3527
  }
3379
3528
  onApplicationBootstrap() {
3380
3529
  if (!isDrivingOperator(this.options) || !this.transport) return;
@@ -3387,13 +3536,13 @@ var RunGatewayBootstrap = class RunGatewayBootstrap2 {
3387
3536
  publishRunReply: publishRunReply.bind(this.transport)
3388
3537
  };
3389
3538
  new RunRequestResponder(runRequestTransport, this.gateway, {
3390
- verifyTenant: this.options.verifyTenant,
3391
- // Mirrors Agora's rule (`warnWithoutVerifier: role === 'control-plane'`): only a deployment
3392
- // that EXPLICITLY names itself the control plane is told it runs without tenant auth. A plain
3393
- // operator (role inferred from `store`) is Agora's `standalone`: anyone with broker access
3539
+ verifyTenant: this.auth.verifyTenant,
3540
+ // Mirrors Agora's rule (`warnWithoutVerifier: topology === 'control-plane'`): only a deployment
3541
+ // that EXPLICITLY names itself the control plane is told it runs without tenant auth. On a
3542
+ // `standalone` operator (role inferred from `store`) anyone with broker access
3394
3543
  // can already enqueue steps and results there, so the warning would be noise on every boot
3395
3544
  // of an app that never serves tenants.
3396
- warnWithoutVerifier: this.options.topology?.role === "control-plane"
3545
+ warnWithoutVerifier: this.options.topology === "control-plane"
3397
3546
  }).start();
3398
3547
  }
3399
3548
  if (typeof publishTenantEvent === "function") {
@@ -3412,13 +3561,15 @@ RunGatewayBootstrap = _ts_decorate13([
3412
3561
  _ts_param9(1, Inject9(TRANSPORT_CANONICAL3)),
3413
3562
  _ts_param9(3, Inject9(STATE_STORE_CANONICAL4)),
3414
3563
  _ts_param9(4, Inject9(DURABLE_OPTIONS_CANONICAL8)),
3564
+ _ts_param9(5, Inject9(TENANT_AUTH)),
3415
3565
  _ts_metadata13("design:type", Function),
3416
3566
  _ts_metadata13("design:paramtypes", [
3417
3567
  typeof WorkflowEngine6 === "undefined" ? Object : WorkflowEngine6,
3418
3568
  Object,
3419
3569
  typeof RunGateway2 === "undefined" ? Object : RunGateway2,
3420
3570
  Object,
3421
- typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions
3571
+ typeof DurableModuleOptions === "undefined" ? Object : DurableModuleOptions,
3572
+ typeof ResolvedTenantAuth === "undefined" ? Object : ResolvedTenantAuth
3422
3573
  ])
3423
3574
  ], RunGatewayBootstrap);
3424
3575
  var DurableModule = class _DurableModule {
@@ -3443,19 +3594,9 @@ var DurableModule = class _DurableModule {
3443
3594
  inject: options.inject ?? []
3444
3595
  });
3445
3596
  }
3446
- /**
3447
- * Validates role/axis constraints, in resolution order. When {@link DurableModuleOptions.topology}
3448
- * is set, it OWNS validation — {@link assertValidTopology}'s own store/transport/connection checks
3449
- * are strictly stronger than {@link assertValidRole}'s, so the topology-specific, axis-teaching
3450
- * message is what a `topology`-opted-in consumer sees (not the older generic one). Falls back to
3451
- * {@link assertValidRole} unchanged when `topology` is absent — zero behavior change.
3452
- */
3597
+ /** Validates the topology and its role/axis constraints; see {@link assertValidTopology}. */
3453
3598
  static assertValid(options) {
3454
- if (options.topology !== void 0) {
3455
- assertValidTopology(options);
3456
- return;
3457
- }
3458
- assertValidRole(options);
3599
+ assertValidTopology(options);
3459
3600
  }
3460
3601
  static build(optionsProvider) {
3461
3602
  return {
@@ -3484,6 +3625,17 @@ var DurableModule = class _DurableModule {
3484
3625
  DURABLE_OPTIONS_CANONICAL8
3485
3626
  ]
3486
3627
  },
3628
+ {
3629
+ provide: TENANT_AUTH,
3630
+ useFactory: /* @__PURE__ */ __name((options, moduleRef) => ({
3631
+ verifyTenant: resolveTenantVerifier(options.verifyTenant, moduleRef),
3632
+ tenantToken: resolveTenantTokenSource(options.tenantToken, moduleRef)
3633
+ }), "useFactory"),
3634
+ inject: [
3635
+ DURABLE_OPTIONS_CANONICAL8,
3636
+ ModuleRef2
3637
+ ]
3638
+ },
3487
3639
  // Legacy back-compat aliases (deprecated tokens still resolve to the same instances):
3488
3640
  {
3489
3641
  provide: STATE_STORE,
@@ -3502,9 +3654,14 @@ var DurableModule = class _DurableModule {
3502
3654
  // `DurableStartClient` facade for a thin worker (no `store`) — either way, `WorkflowService`
3503
3655
  // and app code call `engine.start(...)` unchanged.
3504
3656
  provide: WorkflowEngine6,
3505
- useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef) => {
3657
+ useFactory: /* @__PURE__ */ __name(async (options, store, transport, moduleRef, auth) => {
3506
3658
  if (options.store === void 0) {
3507
- return new DurableStartClient(options);
3659
+ return new DurableStartClient({
3660
+ ...options,
3661
+ ...auth.tenantToken !== void 0 ? {
3662
+ tenantToken: auth.tenantToken
3663
+ } : {}
3664
+ });
3508
3665
  }
3509
3666
  if (!store) {
3510
3667
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
@@ -3552,7 +3709,7 @@ var DurableModule = class _DurableModule {
3552
3709
  context,
3553
3710
  rehydrate: rehydrate || void 0,
3554
3711
  compensationRetries: options.compensationRetries,
3555
- verifyTenant: options.verifyTenant,
3712
+ verifyTenant: auth.verifyTenant,
3556
3713
  // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving
3557
3714
  // each `pending` run in the store for a DRIVING instance's poll. A driving operator gets
3558
3715
  // the engine's default in-process dispatcher: for a body registered inline, it runs
@@ -3572,7 +3729,8 @@ var DurableModule = class _DurableModule {
3572
3729
  DURABLE_OPTIONS_CANONICAL8,
3573
3730
  STATE_STORE_CANONICAL4,
3574
3731
  TRANSPORT_CANONICAL3,
3575
- ModuleRef2
3732
+ ModuleRef2,
3733
+ TENANT_AUTH
3576
3734
  ]
3577
3735
  },
3578
3736
  WorkflowService,
@@ -3587,19 +3745,20 @@ var DurableModule = class _DurableModule {
3587
3745
  // gateway whose every method rejects with a clear tenant error.
3588
3746
  {
3589
3747
  provide: RunGateway2,
3590
- useFactory: /* @__PURE__ */ __name((options, store, engine) => {
3748
+ useFactory: /* @__PURE__ */ __name((options, store, engine, auth) => {
3591
3749
  if (options.store !== void 0) {
3592
3750
  if (!store) {
3593
3751
  throw new Error("unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set");
3594
3752
  }
3595
3753
  return new StoreRunGateway(store, engine);
3596
3754
  }
3597
- return options.transport ? new ProxyRunGateway(options.transport, options.partition ?? "default", options.runGatewayTimeoutMs, void 0, options.tenantToken) : unavailableRunGateway();
3755
+ return options.transport ? new ProxyRunGateway(options.transport, options.partition ?? "default", options.runGatewayTimeoutMs, void 0, auth.tenantToken) : unavailableRunGateway();
3598
3756
  }, "useFactory"),
3599
3757
  inject: [
3600
3758
  DURABLE_OPTIONS_CANONICAL8,
3601
3759
  STATE_STORE_CANONICAL4,
3602
- WorkflowEngine6
3760
+ WorkflowEngine6,
3761
+ TENANT_AUTH
3603
3762
  ]
3604
3763
  },
3605
3764
  RunGatewayBootstrap,