@dudousxd/nestjs-durable-core 0.92.0 → 0.94.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);
@@ -9154,6 +9333,14 @@ var WorkflowEngine = class _WorkflowEngine {
9154
9333
  getRun(runId) {
9155
9334
  return this.visibleRun(runId);
9156
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
+ }
9157
9344
  /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9158
9345
  * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9159
9346
  async listCheckpoints(runId) {
@@ -15932,6 +16119,144 @@ function collectMetrics(engine) {
15932
16119
  }
15933
16120
  __name(collectMetrics, "collectMetrics");
15934
16121
 
16122
+ // src/run-app.ts
16123
+ import { createHash } from "node:crypto";
16124
+ function runTraceId(runId) {
16125
+ const hex = createHash("sha256").update(`durable:run:${runId}`).digest("hex").slice(0, 32);
16126
+ return /^0+$/.test(hex) ? `${hex.slice(0, 31)}1` : hex;
16127
+ }
16128
+ __name(runTraceId, "runTraceId");
16129
+ function tenantAppOf(namespace, own = []) {
16130
+ if (namespace === void 0 || namespace === "" || namespace === "default") return void 0;
16131
+ const mine = Array.isArray(own) ? own.includes(namespace) : own.has(namespace);
16132
+ return mine ? void 0 : namespace;
16133
+ }
16134
+ __name(tenantAppOf, "tenantAppOf");
16135
+ function positive(value, fallback) {
16136
+ return value !== void 0 && Number.isFinite(value) ? Math.max(1, value) : fallback;
16137
+ }
16138
+ __name(positive, "positive");
16139
+ var FAILED = Symbol("failed");
16140
+ var RunAppStamper = class {
16141
+ static {
16142
+ __name(this, "RunAppStamper");
16143
+ }
16144
+ #lookup;
16145
+ #own;
16146
+ #max;
16147
+ #timeoutMs;
16148
+ /** runId → app (`null`: the control plane's own run). */
16149
+ #apps = /* @__PURE__ */ new Map();
16150
+ /** runId → the last queued event of that run, while one is waiting on a read. */
16151
+ #tails = /* @__PURE__ */ new Map();
16152
+ constructor(options) {
16153
+ this.#lookup = (runId) => options.namespaceOf(runId);
16154
+ this.#own = new Set(options.own ?? []);
16155
+ this.#max = positive(options.cacheSize, 1e4);
16156
+ this.#timeoutMs = positive(options.lookupTimeoutMs, 5e3);
16157
+ }
16158
+ /** Call `forward` with `event` stamped with its app (when it has one), now or once it is known. */
16159
+ stamp(event, forward) {
16160
+ const runId = event.runId;
16161
+ const tail = this.#tails.get(runId);
16162
+ if (tail === void 0) {
16163
+ const known = this.#known(event);
16164
+ if (known !== void 0) {
16165
+ this.#forward(event, known, forward);
16166
+ return;
16167
+ }
16168
+ }
16169
+ const next = (tail ?? Promise.resolve()).then(async () => {
16170
+ try {
16171
+ let app = this.#known(event);
16172
+ if (app === void 0) {
16173
+ const namespace = await this.#read(runId);
16174
+ if (namespace === FAILED) {
16175
+ app = null;
16176
+ } else {
16177
+ app = tenantAppOf(namespace, this.#own) ?? null;
16178
+ this.#remember(runId, app);
16179
+ }
16180
+ }
16181
+ this.#forward(event, app, forward);
16182
+ } catch {
16183
+ }
16184
+ });
16185
+ this.#tails.set(runId, next);
16186
+ void next.then(() => {
16187
+ if (this.#tails.get(runId) === next) this.#tails.delete(runId);
16188
+ });
16189
+ }
16190
+ #forward(event, app, forward) {
16191
+ try {
16192
+ forward(this.#with(event, app));
16193
+ } finally {
16194
+ if (event.type === "run.completed" || event.type === "run.failed") {
16195
+ this.#apps.delete(event.runId);
16196
+ }
16197
+ }
16198
+ }
16199
+ /** The run's namespace, or {@link FAILED} when the read threw or did not answer in time. */
16200
+ async #read(runId) {
16201
+ let timer;
16202
+ const timeout = new Promise((resolve) => {
16203
+ timer = setTimeout(() => resolve(FAILED), this.#timeoutMs);
16204
+ timer.unref?.();
16205
+ });
16206
+ try {
16207
+ return await Promise.race([
16208
+ Promise.resolve().then(() => this.#lookup(runId)).catch(() => FAILED),
16209
+ timeout
16210
+ ]);
16211
+ } finally {
16212
+ clearTimeout(timer);
16213
+ }
16214
+ }
16215
+ /** The app of `event`'s run when it is known without a read (`null`: no app). */
16216
+ #known(event) {
16217
+ if (event.namespace !== void 0) {
16218
+ const app = tenantAppOf(event.namespace, this.#own) ?? null;
16219
+ this.#remember(event.runId, app);
16220
+ return app;
16221
+ }
16222
+ return this.#apps.get(event.runId);
16223
+ }
16224
+ /** A tenant's event carries its app, and its partition as `namespace` (step events have none). */
16225
+ #with(event, app) {
16226
+ if (app === null) return event;
16227
+ return event.namespace === void 0 ? {
16228
+ ...event,
16229
+ namespace: app,
16230
+ app
16231
+ } : {
16232
+ ...event,
16233
+ app
16234
+ };
16235
+ }
16236
+ #remember(runId, app) {
16237
+ if (this.#apps.has(runId)) this.#apps.delete(runId);
16238
+ else if (this.#apps.size >= this.#max) {
16239
+ const oldest = this.#apps.keys().next().value;
16240
+ if (oldest !== void 0) this.#apps.delete(oldest);
16241
+ }
16242
+ this.#apps.set(runId, app);
16243
+ }
16244
+ };
16245
+ function controlPlaneAttribution(options, getRun) {
16246
+ if (options?.topology !== "control-plane") return void 0;
16247
+ const own = [
16248
+ options.namespace,
16249
+ options.partition
16250
+ ].filter((ns) => typeof ns === "string" && ns !== "");
16251
+ return {
16252
+ namespaceOf: /* @__PURE__ */ __name(async (runId) => (await getRun(runId))?.namespace, "namespaceOf"),
16253
+ ...own.length > 0 ? {
16254
+ own
16255
+ } : {}
16256
+ };
16257
+ }
16258
+ __name(controlPlaneAttribution, "controlPlaneAttribution");
16259
+
15935
16260
  // src/search-attributes.ts
15936
16261
  function compare(actual, filter) {
15937
16262
  if (filter.op === "in") return filter.values.some((v) => actual === v);
@@ -17018,6 +17343,7 @@ export {
17018
17343
  DURABLE_OPTIONS_CANONICAL,
17019
17344
  DURABLE_STEP_CONFIG,
17020
17345
  DURABLE_STEP_NAME,
17346
+ DuplicateDurableCopyError,
17021
17347
  DurableWorkflow,
17022
17348
  ENGINE_MINTED_TAG_PREFIXES,
17023
17349
  ENTITY_WORKFLOW,
@@ -17061,6 +17387,7 @@ export {
17061
17387
  RemoteStepTimeout,
17062
17388
  RemoteWorkflowExecutor,
17063
17389
  RemoteWorkflowTimeout,
17390
+ RunAppStamper,
17064
17391
  RunGateway,
17065
17392
  SINGLETON_ACTIVE_STATUSES,
17066
17393
  SINGLETON_ADMITTED_TAG,
@@ -17094,6 +17421,7 @@ export {
17094
17421
  applyAttributeQuery,
17095
17422
  assertConcurrency,
17096
17423
  assertRoutes,
17424
+ assertSingleDurableCopy,
17097
17425
  attributeColumnFor,
17098
17426
  attributeOperand,
17099
17427
  attributePredicateOperands,
@@ -17116,6 +17444,7 @@ export {
17116
17444
  codeOf,
17117
17445
  collectMetrics,
17118
17446
  concurrencyTag,
17447
+ controlPlaneAttribution,
17119
17448
  controlPlaneDescriptor,
17120
17449
  countRuns,
17121
17450
  coveredTokens,
@@ -17127,6 +17456,7 @@ export {
17127
17456
  describeWorker,
17128
17457
  descriptorHash,
17129
17458
  detailsOf,
17459
+ durableCopies,
17130
17460
  error,
17131
17461
  etagMatches,
17132
17462
  eventMatchOf,
@@ -17224,6 +17554,7 @@ export {
17224
17554
  runOutsideWorkflowCtx,
17225
17555
  runSchedules,
17226
17556
  runStepHandler,
17557
+ runTraceId,
17227
17558
  runValueFacetsFromRuns,
17228
17559
  runWaitPrefix,
17229
17560
  runWaitTargetOf,
@@ -17233,6 +17564,7 @@ export {
17233
17564
  scheduledRunId,
17234
17565
  scopeBufferedEvent,
17235
17566
  scopeTenantQuery,
17567
+ sealDurableCopies,
17236
17568
  settleResultsWithPlainCalls,
17237
17569
  signTenantToken,
17238
17570
  singletonAdmissionDenialPatch,
@@ -17248,6 +17580,7 @@ export {
17248
17580
  summarizeFan,
17249
17581
  summarizeRunFromStore,
17250
17582
  summarizeTimeline,
17583
+ tenantAppOf,
17251
17584
  tenantGroup,
17252
17585
  tenantIdsFor,
17253
17586
  tenantVisible,