@dudousxd/nestjs-durable-core 0.92.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.cjs CHANGED
@@ -38,6 +38,7 @@ __export(index_exports, {
38
38
  DURABLE_OPTIONS_CANONICAL: () => DURABLE_OPTIONS_CANONICAL,
39
39
  DURABLE_STEP_CONFIG: () => DURABLE_STEP_CONFIG,
40
40
  DURABLE_STEP_NAME: () => DURABLE_STEP_NAME,
41
+ DuplicateDurableCopyError: () => DuplicateDurableCopyError,
41
42
  DurableWorkflow: () => DurableWorkflow,
42
43
  ENGINE_MINTED_TAG_PREFIXES: () => ENGINE_MINTED_TAG_PREFIXES,
43
44
  ENTITY_WORKFLOW: () => ENTITY_WORKFLOW,
@@ -114,6 +115,7 @@ __export(index_exports, {
114
115
  applyAttributeQuery: () => applyAttributeQuery,
115
116
  assertConcurrency: () => assertConcurrency,
116
117
  assertRoutes: () => assertRoutes,
118
+ assertSingleDurableCopy: () => assertSingleDurableCopy,
117
119
  attributeColumnFor: () => attributeColumnFor,
118
120
  attributeOperand: () => attributeOperand,
119
121
  attributePredicateOperands: () => attributePredicateOperands,
@@ -147,6 +149,7 @@ __export(index_exports, {
147
149
  describeWorker: () => describeWorker,
148
150
  descriptorHash: () => descriptorHash,
149
151
  detailsOf: () => detailsOf,
152
+ durableCopies: () => durableCopies,
150
153
  error: () => error,
151
154
  etagMatches: () => etagMatches,
152
155
  eventMatchOf: () => eventMatchOf,
@@ -253,6 +256,7 @@ __export(index_exports, {
253
256
  scheduledRunId: () => scheduledRunId,
254
257
  scopeBufferedEvent: () => scopeBufferedEvent,
255
258
  scopeTenantQuery: () => scopeTenantQuery,
259
+ sealDurableCopies: () => sealDurableCopies,
256
260
  settleResultsWithPlainCalls: () => settleResultsWithPlainCalls,
257
261
  signTenantToken: () => signTenantToken,
258
262
  singletonAdmissionDenialPatch: () => singletonAdmissionDenialPatch,
@@ -384,16 +388,16 @@ var QueueController = class {
384
388
  * A bare item (no waiterId) is compared on its hints directly.
385
389
  */
386
390
  isNext(waiterId, item) {
387
- const self = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
391
+ const self2 = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
388
392
  priority: item?.priority ?? 0,
389
393
  key: item?.key,
390
394
  seq: Number.POSITIVE_INFINITY
391
395
  };
392
- let best = self;
396
+ let best = self2;
393
397
  for (const w of this.waiters.values()) {
394
398
  if (this.better(w, best)) best = w;
395
399
  }
396
- return best === self;
400
+ return best === self2;
397
401
  }
398
402
  /** Strict "a should be admitted before b" comparison under the active policy. */
399
403
  better(a, b) {
@@ -847,6 +851,113 @@ function parseDuration(duration) {
847
851
  }
848
852
  __name(parseDuration, "parseDuration");
849
853
 
854
+ // src/copy-guard.ts
855
+ var import_node_fs = require("fs");
856
+ var import_node_path = require("path");
857
+ var import_node_url = require("url");
858
+
859
+ // src/origin.ts
860
+ var CORE_ORIGIN = "@dudousxd/nestjs-durable-core";
861
+
862
+ // src/copy-guard.ts
863
+ var DURABLE_COPIES_KEY = Symbol.for("@dudousxd/nestjs-durable.copies");
864
+ var DUPLICATE_COPY_DOCS = "https://davidecarvalho.github.io/aviary/docs/durable/troubleshooting#two-copies-of-dudousxdnestjs-durable-core";
865
+ 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.`;
866
+ var DuplicateDurableCopyError = class extends Error {
867
+ static {
868
+ __name(this, "DuplicateDurableCopyError");
869
+ }
870
+ copies;
871
+ constructor(copies) {
872
+ super(duplicateCopyMessage(copies));
873
+ this.name = "DuplicateDurableCopyError";
874
+ this.copies = copies;
875
+ }
876
+ };
877
+ function duplicateCopyMessage(copies) {
878
+ const list2 = copies.map((c) => ` - ${c.version} at ${c.root}`).join("\n");
879
+ return [
880
+ `${CORE_ORIGIN} is loaded ${copies.length} times, from different installs:`,
881
+ list2,
882
+ "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).",
883
+ DUPLICATE_COPY_FIX,
884
+ `See ${DUPLICATE_COPY_DOCS}`
885
+ ].join("\n");
886
+ }
887
+ __name(duplicateCopyMessage, "duplicateCopyMessage");
888
+ function durableCopyRegistry() {
889
+ const slot = globalThis;
890
+ const existing = slot[DURABLE_COPIES_KEY];
891
+ if (existing?.copies instanceof Map) return existing;
892
+ const fresh = {
893
+ copies: /* @__PURE__ */ new Map(),
894
+ booted: false
895
+ };
896
+ slot[DURABLE_COPIES_KEY] = fresh;
897
+ return fresh;
898
+ }
899
+ __name(durableCopyRegistry, "durableCopyRegistry");
900
+ function durableCopies(registry = durableCopyRegistry()) {
901
+ return [
902
+ ...registry.copies.values()
903
+ ];
904
+ }
905
+ __name(durableCopies, "durableCopies");
906
+ function registerDurableCopy(copy, registry = durableCopyRegistry()) {
907
+ if (registry.copies.has(copy.root)) return;
908
+ registry.copies.set(copy.root, copy);
909
+ if (registry.booted) assertSingleDurableCopy(registry);
910
+ }
911
+ __name(registerDurableCopy, "registerDurableCopy");
912
+ function assertSingleDurableCopy(registry = durableCopyRegistry()) {
913
+ const copies = durableCopies(registry);
914
+ if (copies.length > 1) throw new DuplicateDurableCopyError(copies);
915
+ }
916
+ __name(assertSingleDurableCopy, "assertSingleDurableCopy");
917
+ function sealDurableCopies(registry = durableCopyRegistry()) {
918
+ assertSingleDurableCopy(registry);
919
+ registry.booted = true;
920
+ }
921
+ __name(sealDurableCopies, "sealDurableCopies");
922
+ function thisCopy() {
923
+ let start;
924
+ try {
925
+ start = (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(__importMetaUrl));
926
+ } catch {
927
+ return null;
928
+ }
929
+ let dir = start;
930
+ for (; ; ) {
931
+ try {
932
+ const pkg = JSON.parse((0, import_node_fs.readFileSync)((0, import_node_path.join)(dir, "package.json"), "utf8"));
933
+ if (pkg.name === CORE_ORIGIN) {
934
+ return {
935
+ version: typeof pkg.version === "string" ? pkg.version : "unknown",
936
+ root: realPath(dir)
937
+ };
938
+ }
939
+ } catch {
940
+ }
941
+ const parent = (0, import_node_path.dirname)(dir);
942
+ if (parent === dir) return {
943
+ version: "unknown",
944
+ root: realPath(start)
945
+ };
946
+ dir = parent;
947
+ }
948
+ }
949
+ __name(thisCopy, "thisCopy");
950
+ function realPath(path) {
951
+ try {
952
+ return (0, import_node_fs.realpathSync)(path);
953
+ } catch {
954
+ return path;
955
+ }
956
+ }
957
+ __name(realPath, "realPath");
958
+ var self = thisCopy();
959
+ if (self !== null) registerDurableCopy(self);
960
+
850
961
  // src/backoff.ts
851
962
  function backoffDelay(attempt, options) {
852
963
  const base = options?.backoffMs ?? 0;
@@ -2152,9 +2263,6 @@ async function assertConcurrency(store, workflow, quota) {
2152
2263
  }
2153
2264
  __name(assertConcurrency, "assertConcurrency");
2154
2265
 
2155
- // src/origin.ts
2156
- var CORE_ORIGIN = "@dudousxd/nestjs-durable-core";
2157
-
2158
2266
  // src/entities.ts
2159
2267
  var NUDGE = {
2160
2268
  nudge: true
@@ -3831,13 +3939,7 @@ async function runSchedules(engine, schedules, nowMs, opts) {
3831
3939
  ] : due;
3832
3940
  const candidates = windows.filter((id) => !settled.get(s.key)?.has(id));
3833
3941
  if (candidates.length === 0) continue;
3834
- if (s.overlap === "skip" && s.everyMs) {
3835
- const prevBucket = Math.floor(nowMs / s.everyMs) - 1;
3836
- if (prevBucket >= 0) {
3837
- const prev = await engine.getRun(`sched:${s.key}:${prevBucket}`);
3838
- if (prev && (prev.status === "running" || prev.status === "suspended")) continue;
3839
- }
3840
- }
3942
+ if (s.overlap === "skip" && await overlapping(engine, s, nowMs)) continue;
3841
3943
  if (!(s.jitter && s.jitter > 0)) jitterFireAt.get(engine)?.delete(s.key);
3842
3944
  const firing = s.jitter && s.jitter > 0 ? jitterDue(engine, s, candidates, nowMs, random) : candidates;
3843
3945
  if (firing.length === 0) continue;
@@ -3845,16 +3947,97 @@ async function runSchedules(engine, schedules, nowMs, opts) {
3845
3947
  if (engine.isDraining?.()) break;
3846
3948
  const existing = await engine.getRun(runId);
3847
3949
  remember(settled, s.key, runId);
3848
- if (existing) continue;
3950
+ if (existing) {
3951
+ if (s.overlap === "skip" && !isTerminal(existing.status)) {
3952
+ noteInFlight(engine, s.key, runId);
3953
+ break;
3954
+ }
3955
+ continue;
3956
+ }
3849
3957
  await engine.start(workflowName(s.workflow), s.input, runId, {
3850
3958
  namespace: s.namespace
3851
3959
  });
3852
3960
  ids.push(runId);
3961
+ if (s.overlap === "skip") {
3962
+ noteInFlight(engine, s.key, runId);
3963
+ break;
3964
+ }
3853
3965
  }
3854
3966
  }
3855
3967
  return ids;
3856
3968
  }
3857
3969
  __name(runSchedules, "runSchedules");
3970
+ var IN_FLIGHT = [
3971
+ "pending",
3972
+ "running",
3973
+ "suspended",
3974
+ "blocked",
3975
+ "cancelling"
3976
+ ];
3977
+ function isTerminal(status) {
3978
+ return TERMINAL_RUN_STATUSES.includes(status);
3979
+ }
3980
+ __name(isTerminal, "isTerminal");
3981
+ var inFlightRuns = /* @__PURE__ */ new WeakMap();
3982
+ function inFlightFor(engine, key) {
3983
+ let byKey = inFlightRuns.get(engine);
3984
+ if (byKey === void 0) {
3985
+ byKey = /* @__PURE__ */ new Map();
3986
+ inFlightRuns.set(engine, byKey);
3987
+ }
3988
+ let ids = byKey.get(key);
3989
+ if (ids === void 0) {
3990
+ ids = /* @__PURE__ */ new Set();
3991
+ byKey.set(key, ids);
3992
+ }
3993
+ return ids;
3994
+ }
3995
+ __name(inFlightFor, "inFlightFor");
3996
+ function noteInFlight(engine, key, runId) {
3997
+ const ids = inFlightFor(engine, key);
3998
+ ids.add(runId);
3999
+ if (ids.size > 64) ids.delete(ids.values().next().value);
4000
+ }
4001
+ __name(noteInFlight, "noteInFlight");
4002
+ async function overlapping(engine, s, nowMs) {
4003
+ const known = inFlightFor(engine, s.key);
4004
+ for (const runId of [
4005
+ ...known
4006
+ ].reverse()) {
4007
+ const run2 = await engine.getRun(runId);
4008
+ if (run2 && !isTerminal(run2.status)) return true;
4009
+ known.delete(runId);
4010
+ }
4011
+ if (engine.listRuns) {
4012
+ const prefix = `sched:${s.key}:`;
4013
+ const runs = await engine.listRuns({
4014
+ workflow: workflowName(s.workflow),
4015
+ statuses: IN_FLIGHT
4016
+ });
4017
+ const blocking = runs.filter((r) => r.id.startsWith(prefix) && !isTerminal(r.status));
4018
+ for (const r of blocking) noteInFlight(engine, s.key, r.id);
4019
+ return blocking.length > 0;
4020
+ }
4021
+ const prev = previousWindowRunId(s, nowMs);
4022
+ if (prev === void 0) return false;
4023
+ const run = await engine.getRun(prev);
4024
+ if (!run || isTerminal(run.status)) return false;
4025
+ noteInFlight(engine, s.key, prev);
4026
+ return true;
4027
+ }
4028
+ __name(overlapping, "overlapping");
4029
+ function previousWindowRunId(s, nowMs) {
4030
+ if (s.cron != null) {
4031
+ const current = prevCronFireMs(s.cron, nowMs, s.timezone);
4032
+ return `sched:${s.key}:${prevCronFireMs(s.cron, current - 1, s.timezone)}`;
4033
+ }
4034
+ if (s.everyMs != null) {
4035
+ const bucket = Math.floor(nowMs / s.everyMs) - 1;
4036
+ return bucket >= 0 ? `sched:${s.key}:${bucket}` : void 0;
4037
+ }
4038
+ return void 0;
4039
+ }
4040
+ __name(previousWindowRunId, "previousWindowRunId");
3858
4041
  var settledRunIds = /* @__PURE__ */ new WeakMap();
3859
4042
  function settledIdsFor(engine) {
3860
4043
  let memo = settledRunIds.get(engine);
@@ -9438,6 +9621,14 @@ var WorkflowEngine = class _WorkflowEngine {
9438
9621
  getRun(runId) {
9439
9622
  return this.visibleRun(runId);
9440
9623
  }
9624
+ /**
9625
+ * The runs matching `query`, narrowed to the ones the caller may see (with tenancy on, another
9626
+ * tenant's runs are left out, like {@link getRun}). Pair it with `workflow` / `statuses` to bound
9627
+ * the scan on a large store. `overlap: 'skip'` schedules use it to find their in-flight runs.
9628
+ */
9629
+ listRuns(query) {
9630
+ return this.store.listRuns(this.scopeRunQuery(query));
9631
+ }
9441
9632
  /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9442
9633
  * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9443
9634
  async listCheckpoints(runId) {
@@ -17303,6 +17494,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17303
17494
  DURABLE_OPTIONS_CANONICAL,
17304
17495
  DURABLE_STEP_CONFIG,
17305
17496
  DURABLE_STEP_NAME,
17497
+ DuplicateDurableCopyError,
17306
17498
  DurableWorkflow,
17307
17499
  ENGINE_MINTED_TAG_PREFIXES,
17308
17500
  ENTITY_WORKFLOW,
@@ -17379,6 +17571,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17379
17571
  applyAttributeQuery,
17380
17572
  assertConcurrency,
17381
17573
  assertRoutes,
17574
+ assertSingleDurableCopy,
17382
17575
  attributeColumnFor,
17383
17576
  attributeOperand,
17384
17577
  attributePredicateOperands,
@@ -17412,6 +17605,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17412
17605
  describeWorker,
17413
17606
  descriptorHash,
17414
17607
  detailsOf,
17608
+ durableCopies,
17415
17609
  error,
17416
17610
  etagMatches,
17417
17611
  eventMatchOf,
@@ -17518,6 +17712,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17518
17712
  scheduledRunId,
17519
17713
  scopeBufferedEvent,
17520
17714
  scopeTenantQuery,
17715
+ sealDurableCopies,
17521
17716
  settleResultsWithPlainCalls,
17522
17717
  signTenantToken,
17523
17718
  singletonAdmissionDenialPatch,