@dudousxd/nestjs-durable-core 0.91.0 → 0.93.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
@@ -100,16 +100,16 @@ var QueueController = class {
100
100
  * A bare item (no waiterId) is compared on its hints directly.
101
101
  */
102
102
  isNext(waiterId, item) {
103
- const self = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
103
+ const self2 = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
104
104
  priority: item?.priority ?? 0,
105
105
  key: item?.key,
106
106
  seq: Number.POSITIVE_INFINITY
107
107
  };
108
- let best = self;
108
+ let best = self2;
109
109
  for (const w of this.waiters.values()) {
110
110
  if (this.better(w, best)) best = w;
111
111
  }
112
- return best === self;
112
+ return best === self2;
113
113
  }
114
114
  /** Strict "a should be admitted before b" comparison under the active policy. */
115
115
  better(a, b) {
@@ -563,6 +563,113 @@ function parseDuration(duration) {
563
563
  }
564
564
  __name(parseDuration, "parseDuration");
565
565
 
566
+ // src/copy-guard.ts
567
+ import { readFileSync, realpathSync } from "node:fs";
568
+ import { dirname, join } from "node:path";
569
+ import { fileURLToPath } from "node:url";
570
+
571
+ // src/origin.ts
572
+ var CORE_ORIGIN = "@dudousxd/nestjs-durable-core";
573
+
574
+ // src/copy-guard.ts
575
+ var DURABLE_COPIES_KEY = Symbol.for("@dudousxd/nestjs-durable.copies");
576
+ var DUPLICATE_COPY_DOCS = "https://davidecarvalho.github.io/aviary/docs/durable/troubleshooting#two-copies-of-dudousxdnestjs-durable-core";
577
+ var DUPLICATE_COPY_FIX = `Make every package resolve one copy: declare the same peer dependency versions in the app as in the workspace packages that depend on ${CORE_ORIGIN} (or pin them with pnpm overrides), reinstall, and check that \`pnpm why ${CORE_ORIGIN}\` shows a single variant.`;
578
+ var DuplicateDurableCopyError = class extends Error {
579
+ static {
580
+ __name(this, "DuplicateDurableCopyError");
581
+ }
582
+ copies;
583
+ constructor(copies) {
584
+ super(duplicateCopyMessage(copies));
585
+ this.name = "DuplicateDurableCopyError";
586
+ this.copies = copies;
587
+ }
588
+ };
589
+ function duplicateCopyMessage(copies) {
590
+ const list2 = copies.map((c) => ` - ${c.version} at ${c.root}`).join("\n");
591
+ return [
592
+ `${CORE_ORIGIN} is loaded ${copies.length} times, from different installs:`,
593
+ list2,
594
+ "Each copy has its own WorkflowEngine class, so code from one copy cannot resolve the engine the other copy registered (Nest cannot inject `WorkflowEngine`, `instanceof` checks fail, and workflows registered on one engine are unknown to the other).",
595
+ DUPLICATE_COPY_FIX,
596
+ `See ${DUPLICATE_COPY_DOCS}`
597
+ ].join("\n");
598
+ }
599
+ __name(duplicateCopyMessage, "duplicateCopyMessage");
600
+ function durableCopyRegistry() {
601
+ const slot = globalThis;
602
+ const existing = slot[DURABLE_COPIES_KEY];
603
+ if (existing?.copies instanceof Map) return existing;
604
+ const fresh = {
605
+ copies: /* @__PURE__ */ new Map(),
606
+ booted: false
607
+ };
608
+ slot[DURABLE_COPIES_KEY] = fresh;
609
+ return fresh;
610
+ }
611
+ __name(durableCopyRegistry, "durableCopyRegistry");
612
+ function durableCopies(registry = durableCopyRegistry()) {
613
+ return [
614
+ ...registry.copies.values()
615
+ ];
616
+ }
617
+ __name(durableCopies, "durableCopies");
618
+ function registerDurableCopy(copy, registry = durableCopyRegistry()) {
619
+ if (registry.copies.has(copy.root)) return;
620
+ registry.copies.set(copy.root, copy);
621
+ if (registry.booted) assertSingleDurableCopy(registry);
622
+ }
623
+ __name(registerDurableCopy, "registerDurableCopy");
624
+ function assertSingleDurableCopy(registry = durableCopyRegistry()) {
625
+ const copies = durableCopies(registry);
626
+ if (copies.length > 1) throw new DuplicateDurableCopyError(copies);
627
+ }
628
+ __name(assertSingleDurableCopy, "assertSingleDurableCopy");
629
+ function sealDurableCopies(registry = durableCopyRegistry()) {
630
+ assertSingleDurableCopy(registry);
631
+ registry.booted = true;
632
+ }
633
+ __name(sealDurableCopies, "sealDurableCopies");
634
+ function thisCopy() {
635
+ let start;
636
+ try {
637
+ start = dirname(fileURLToPath(import.meta.url));
638
+ } catch {
639
+ return null;
640
+ }
641
+ let dir = start;
642
+ for (; ; ) {
643
+ try {
644
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
645
+ if (pkg.name === CORE_ORIGIN) {
646
+ return {
647
+ version: typeof pkg.version === "string" ? pkg.version : "unknown",
648
+ root: realPath(dir)
649
+ };
650
+ }
651
+ } catch {
652
+ }
653
+ const parent = dirname(dir);
654
+ if (parent === dir) return {
655
+ version: "unknown",
656
+ root: realPath(start)
657
+ };
658
+ dir = parent;
659
+ }
660
+ }
661
+ __name(thisCopy, "thisCopy");
662
+ function realPath(path) {
663
+ try {
664
+ return realpathSync(path);
665
+ } catch {
666
+ return path;
667
+ }
668
+ }
669
+ __name(realPath, "realPath");
670
+ var self = thisCopy();
671
+ if (self !== null) registerDurableCopy(self);
672
+
566
673
  // src/backoff.ts
567
674
  function backoffDelay(attempt, options) {
568
675
  const base = options?.backoffMs ?? 0;
@@ -1868,9 +1975,6 @@ async function assertConcurrency(store, workflow, quota) {
1868
1975
  }
1869
1976
  __name(assertConcurrency, "assertConcurrency");
1870
1977
 
1871
- // src/origin.ts
1872
- var CORE_ORIGIN = "@dudousxd/nestjs-durable-core";
1873
-
1874
1978
  // src/entities.ts
1875
1979
  var NUDGE = {
1876
1980
  nudge: true
@@ -3547,13 +3651,7 @@ async function runSchedules(engine, schedules, nowMs, opts) {
3547
3651
  ] : due;
3548
3652
  const candidates = windows.filter((id) => !settled.get(s.key)?.has(id));
3549
3653
  if (candidates.length === 0) continue;
3550
- if (s.overlap === "skip" && s.everyMs) {
3551
- const prevBucket = Math.floor(nowMs / s.everyMs) - 1;
3552
- if (prevBucket >= 0) {
3553
- const prev = await engine.getRun(`sched:${s.key}:${prevBucket}`);
3554
- if (prev && (prev.status === "running" || prev.status === "suspended")) continue;
3555
- }
3556
- }
3654
+ if (s.overlap === "skip" && await overlapping(engine, s, nowMs)) continue;
3557
3655
  if (!(s.jitter && s.jitter > 0)) jitterFireAt.get(engine)?.delete(s.key);
3558
3656
  const firing = s.jitter && s.jitter > 0 ? jitterDue(engine, s, candidates, nowMs, random) : candidates;
3559
3657
  if (firing.length === 0) continue;
@@ -3561,16 +3659,97 @@ async function runSchedules(engine, schedules, nowMs, opts) {
3561
3659
  if (engine.isDraining?.()) break;
3562
3660
  const existing = await engine.getRun(runId);
3563
3661
  remember(settled, s.key, runId);
3564
- if (existing) continue;
3662
+ if (existing) {
3663
+ if (s.overlap === "skip" && !isTerminal(existing.status)) {
3664
+ noteInFlight(engine, s.key, runId);
3665
+ break;
3666
+ }
3667
+ continue;
3668
+ }
3565
3669
  await engine.start(workflowName(s.workflow), s.input, runId, {
3566
3670
  namespace: s.namespace
3567
3671
  });
3568
3672
  ids.push(runId);
3673
+ if (s.overlap === "skip") {
3674
+ noteInFlight(engine, s.key, runId);
3675
+ break;
3676
+ }
3569
3677
  }
3570
3678
  }
3571
3679
  return ids;
3572
3680
  }
3573
3681
  __name(runSchedules, "runSchedules");
3682
+ var IN_FLIGHT = [
3683
+ "pending",
3684
+ "running",
3685
+ "suspended",
3686
+ "blocked",
3687
+ "cancelling"
3688
+ ];
3689
+ function isTerminal(status) {
3690
+ return TERMINAL_RUN_STATUSES.includes(status);
3691
+ }
3692
+ __name(isTerminal, "isTerminal");
3693
+ var inFlightRuns = /* @__PURE__ */ new WeakMap();
3694
+ function inFlightFor(engine, key) {
3695
+ let byKey = inFlightRuns.get(engine);
3696
+ if (byKey === void 0) {
3697
+ byKey = /* @__PURE__ */ new Map();
3698
+ inFlightRuns.set(engine, byKey);
3699
+ }
3700
+ let ids = byKey.get(key);
3701
+ if (ids === void 0) {
3702
+ ids = /* @__PURE__ */ new Set();
3703
+ byKey.set(key, ids);
3704
+ }
3705
+ return ids;
3706
+ }
3707
+ __name(inFlightFor, "inFlightFor");
3708
+ function noteInFlight(engine, key, runId) {
3709
+ const ids = inFlightFor(engine, key);
3710
+ ids.add(runId);
3711
+ if (ids.size > 64) ids.delete(ids.values().next().value);
3712
+ }
3713
+ __name(noteInFlight, "noteInFlight");
3714
+ async function overlapping(engine, s, nowMs) {
3715
+ const known = inFlightFor(engine, s.key);
3716
+ for (const runId of [
3717
+ ...known
3718
+ ].reverse()) {
3719
+ const run2 = await engine.getRun(runId);
3720
+ if (run2 && !isTerminal(run2.status)) return true;
3721
+ known.delete(runId);
3722
+ }
3723
+ if (engine.listRuns) {
3724
+ const prefix = `sched:${s.key}:`;
3725
+ const runs = await engine.listRuns({
3726
+ workflow: workflowName(s.workflow),
3727
+ statuses: IN_FLIGHT
3728
+ });
3729
+ const blocking = runs.filter((r) => r.id.startsWith(prefix) && !isTerminal(r.status));
3730
+ for (const r of blocking) noteInFlight(engine, s.key, r.id);
3731
+ return blocking.length > 0;
3732
+ }
3733
+ const prev = previousWindowRunId(s, nowMs);
3734
+ if (prev === void 0) return false;
3735
+ const run = await engine.getRun(prev);
3736
+ if (!run || isTerminal(run.status)) return false;
3737
+ noteInFlight(engine, s.key, prev);
3738
+ return true;
3739
+ }
3740
+ __name(overlapping, "overlapping");
3741
+ function previousWindowRunId(s, nowMs) {
3742
+ if (s.cron != null) {
3743
+ const current = prevCronFireMs(s.cron, nowMs, s.timezone);
3744
+ return `sched:${s.key}:${prevCronFireMs(s.cron, current - 1, s.timezone)}`;
3745
+ }
3746
+ if (s.everyMs != null) {
3747
+ const bucket = Math.floor(nowMs / s.everyMs) - 1;
3748
+ return bucket >= 0 ? `sched:${s.key}:${bucket}` : void 0;
3749
+ }
3750
+ return void 0;
3751
+ }
3752
+ __name(previousWindowRunId, "previousWindowRunId");
3574
3753
  var settledRunIds = /* @__PURE__ */ new WeakMap();
3575
3754
  function settledIdsFor(engine) {
3576
3755
  let memo = settledRunIds.get(engine);
@@ -4641,6 +4820,21 @@ function hmacTenantVerifier(secret, capabilities) {
4641
4820
  };
4642
4821
  }
4643
4822
  __name(hmacTenantVerifier, "hmacTenantVerifier");
4823
+ async function verifyWireTenant(wireTenant, verifyTenant) {
4824
+ if (!verifyTenant) return {
4825
+ tenant: wireTenant
4826
+ };
4827
+ return await verifyTenant({
4828
+ token: wireTenant,
4829
+ tenant: wireTenant
4830
+ }) ?? null;
4831
+ }
4832
+ __name(verifyWireTenant, "verifyWireTenant");
4833
+ function grantsClientTenant(verified, tenantId) {
4834
+ const capabilities = verified?.capabilities ?? [];
4835
+ return capabilities.includes("tenancy:*") || capabilities.includes(`tenancy:${tenantId}`);
4836
+ }
4837
+ __name(grantsClientTenant, "grantsClientTenant");
4644
4838
  async function resolveWireTenant(wireTenant, verifyTenant) {
4645
4839
  if (!verifyTenant) return wireTenant;
4646
4840
  const verified = await verifyTenant({
@@ -6911,20 +7105,31 @@ var WorkflowEngine = class _WorkflowEngine {
6911
7105
  }
6912
7106
  const verifyTenant = deps.verifyTenant;
6913
7107
  this.pool.onStartRun(async (message) => {
6914
- let tenant;
7108
+ let verified;
6915
7109
  try {
6916
- tenant = await resolveWireTenant(message.tenant, verifyTenant);
7110
+ verified = await verifyWireTenant(message.tenant, verifyTenant);
6917
7111
  } catch {
6918
- tenant = null;
7112
+ verified = null;
6919
7113
  }
6920
- if (tenant === null) {
7114
+ const tenant = verified?.tenant ?? null;
7115
+ if (verified === null || tenant === null) {
6921
7116
  console.warn(`[nestjs-durable] dropped a start-run for "${message.workflow}": invalid or unauthorized tenant token`);
6922
7117
  return;
6923
7118
  }
6924
7119
  await this.start(message.workflow, message.input, message.runId ?? globalThis.crypto.randomUUID(), {
6925
7120
  namespace: tenant,
6926
7121
  tags: message.tags,
6927
- searchAttributes: message.searchAttributes
7122
+ searchAttributes: message.searchAttributes,
7123
+ // The customer a tenant process claims for the run (A4): kept only when its verified
7124
+ // token grants `tenancy:*` or `tenancy:<id>`, else the run gets no customer tenant.
7125
+ ...message.tenantId !== void 0 ? grantsClientTenant(verified, message.tenantId) ? message.tenantKind !== void 0 ? {
7126
+ tenantId: message.tenantId,
7127
+ tenantKind: message.tenantKind
7128
+ } : {
7129
+ tenantId: message.tenantId
7130
+ } : {
7131
+ tenantId: null
7132
+ } : {}
6928
7133
  });
6929
7134
  });
6930
7135
  this.controlPlane?.onControl((msg) => {
@@ -9063,7 +9268,12 @@ var WorkflowEngine = class _WorkflowEngine {
9063
9268
  * invisible run reads exactly like a missing one (not found, never forbidden).
9064
9269
  */
9065
9270
  visibleRun(runId) {
9066
- const filter = this.restrictiveFilter();
9271
+ let filter;
9272
+ try {
9273
+ filter = this.restrictiveFilter();
9274
+ } catch (err) {
9275
+ return Promise.reject(err);
9276
+ }
9067
9277
  if (!filter) return this.store.getRun(runId);
9068
9278
  return this.store.getRun(runId).then((run) => run && tenantVisible(run, filter) ? run : null);
9069
9279
  }
@@ -9110,8 +9320,11 @@ var WorkflowEngine = class _WorkflowEngine {
9110
9320
  * timer, a signal, recovery or a worker. A run with no tenant, or tenancy off, runs `fn` as is.
9111
9321
  */
9112
9322
  inRunTenant(run, fn) {
9113
- const tenant = this.tenancy ? rowTenant(run) : void 0;
9114
- return tenant && this.tenancy ? this.tenancy.run(tenant, fn) : fn();
9323
+ const tenancy = this.tenancy;
9324
+ if (!tenancy) return fn();
9325
+ const tenant = rowTenant(run);
9326
+ const turn = tenant ? () => tenancy.run(tenant, fn) : fn;
9327
+ return tenancy.system ? tenancy.system(turn) : turn();
9115
9328
  }
9116
9329
  /**
9117
9330
  * Read a run's current persisted state (or null if unknown). With tenancy on, a run of another
@@ -9120,6 +9333,14 @@ var WorkflowEngine = class _WorkflowEngine {
9120
9333
  getRun(runId) {
9121
9334
  return this.visibleRun(runId);
9122
9335
  }
9336
+ /**
9337
+ * The runs matching `query`, narrowed to the ones the caller may see (with tenancy on, another
9338
+ * tenant's runs are left out, like {@link getRun}). Pair it with `workflow` / `statuses` to bound
9339
+ * the scan on a large store. `overlap: 'skip'` schedules use it to find their in-flight runs.
9340
+ */
9341
+ listRuns(query) {
9342
+ return this.store.listRuns(this.scopeRunQuery(query));
9343
+ }
9123
9344
  /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9124
9345
  * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9125
9346
  async listCheckpoints(runId) {
@@ -16984,6 +17205,7 @@ export {
16984
17205
  DURABLE_OPTIONS_CANONICAL,
16985
17206
  DURABLE_STEP_CONFIG,
16986
17207
  DURABLE_STEP_NAME,
17208
+ DuplicateDurableCopyError,
16987
17209
  DurableWorkflow,
16988
17210
  ENGINE_MINTED_TAG_PREFIXES,
16989
17211
  ENTITY_WORKFLOW,
@@ -17060,6 +17282,7 @@ export {
17060
17282
  applyAttributeQuery,
17061
17283
  assertConcurrency,
17062
17284
  assertRoutes,
17285
+ assertSingleDurableCopy,
17063
17286
  attributeColumnFor,
17064
17287
  attributeOperand,
17065
17288
  attributePredicateOperands,
@@ -17093,6 +17316,7 @@ export {
17093
17316
  describeWorker,
17094
17317
  descriptorHash,
17095
17318
  detailsOf,
17319
+ durableCopies,
17096
17320
  error,
17097
17321
  etagMatches,
17098
17322
  eventMatchOf,
@@ -17107,6 +17331,7 @@ export {
17107
17331
  findStalledRuns,
17108
17332
  foldedCount,
17109
17333
  getRunsByIds,
17334
+ grantsClientTenant,
17110
17335
  handoffHandlerId,
17111
17336
  handoffName,
17112
17337
  hasDurableExecutionWrappers,
@@ -17198,6 +17423,7 @@ export {
17198
17423
  scheduledRunId,
17199
17424
  scopeBufferedEvent,
17200
17425
  scopeTenantQuery,
17426
+ sealDurableCopies,
17201
17427
  settleResultsWithPlainCalls,
17202
17428
  signTenantToken,
17203
17429
  singletonAdmissionDenialPatch,
@@ -17222,6 +17448,7 @@ export {
17222
17448
  triggeredRunsOf,
17223
17449
  triggeredSubscribersOf,
17224
17450
  useDurableExecution,
17451
+ verifyWireTenant,
17225
17452
  warn,
17226
17453
  withSingletonTracked,
17227
17454
  withoutSingletonMarkers,