@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.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,
@@ -161,6 +164,7 @@ __export(index_exports, {
161
164
  findStalledRuns: () => findStalledRuns,
162
165
  foldedCount: () => foldedCount,
163
166
  getRunsByIds: () => getRunsByIds,
167
+ grantsClientTenant: () => grantsClientTenant,
164
168
  handoffHandlerId: () => handoffHandlerId,
165
169
  handoffName: () => handoffName,
166
170
  hasDurableExecutionWrappers: () => hasDurableExecutionWrappers,
@@ -252,6 +256,7 @@ __export(index_exports, {
252
256
  scheduledRunId: () => scheduledRunId,
253
257
  scopeBufferedEvent: () => scopeBufferedEvent,
254
258
  scopeTenantQuery: () => scopeTenantQuery,
259
+ sealDurableCopies: () => sealDurableCopies,
255
260
  settleResultsWithPlainCalls: () => settleResultsWithPlainCalls,
256
261
  signTenantToken: () => signTenantToken,
257
262
  singletonAdmissionDenialPatch: () => singletonAdmissionDenialPatch,
@@ -276,6 +281,7 @@ __export(index_exports, {
276
281
  triggeredRunsOf: () => triggeredRunsOf,
277
282
  triggeredSubscribersOf: () => triggeredSubscribersOf,
278
283
  useDurableExecution: () => useDurableExecution,
284
+ verifyWireTenant: () => verifyWireTenant,
279
285
  warn: () => warn,
280
286
  withSingletonTracked: () => withSingletonTracked,
281
287
  withoutSingletonMarkers: () => withoutSingletonMarkers,
@@ -382,16 +388,16 @@ var QueueController = class {
382
388
  * A bare item (no waiterId) is compared on its hints directly.
383
389
  */
384
390
  isNext(waiterId, item) {
385
- const self = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
391
+ const self2 = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
386
392
  priority: item?.priority ?? 0,
387
393
  key: item?.key,
388
394
  seq: Number.POSITIVE_INFINITY
389
395
  };
390
- let best = self;
396
+ let best = self2;
391
397
  for (const w of this.waiters.values()) {
392
398
  if (this.better(w, best)) best = w;
393
399
  }
394
- return best === self;
400
+ return best === self2;
395
401
  }
396
402
  /** Strict "a should be admitted before b" comparison under the active policy. */
397
403
  better(a, b) {
@@ -845,6 +851,113 @@ function parseDuration(duration) {
845
851
  }
846
852
  __name(parseDuration, "parseDuration");
847
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
+
848
961
  // src/backoff.ts
849
962
  function backoffDelay(attempt, options) {
850
963
  const base = options?.backoffMs ?? 0;
@@ -2150,9 +2263,6 @@ async function assertConcurrency(store, workflow, quota) {
2150
2263
  }
2151
2264
  __name(assertConcurrency, "assertConcurrency");
2152
2265
 
2153
- // src/origin.ts
2154
- var CORE_ORIGIN = "@dudousxd/nestjs-durable-core";
2155
-
2156
2266
  // src/entities.ts
2157
2267
  var NUDGE = {
2158
2268
  nudge: true
@@ -3829,13 +3939,7 @@ async function runSchedules(engine, schedules, nowMs, opts) {
3829
3939
  ] : due;
3830
3940
  const candidates = windows.filter((id) => !settled.get(s.key)?.has(id));
3831
3941
  if (candidates.length === 0) continue;
3832
- if (s.overlap === "skip" && s.everyMs) {
3833
- const prevBucket = Math.floor(nowMs / s.everyMs) - 1;
3834
- if (prevBucket >= 0) {
3835
- const prev = await engine.getRun(`sched:${s.key}:${prevBucket}`);
3836
- if (prev && (prev.status === "running" || prev.status === "suspended")) continue;
3837
- }
3838
- }
3942
+ if (s.overlap === "skip" && await overlapping(engine, s, nowMs)) continue;
3839
3943
  if (!(s.jitter && s.jitter > 0)) jitterFireAt.get(engine)?.delete(s.key);
3840
3944
  const firing = s.jitter && s.jitter > 0 ? jitterDue(engine, s, candidates, nowMs, random) : candidates;
3841
3945
  if (firing.length === 0) continue;
@@ -3843,16 +3947,97 @@ async function runSchedules(engine, schedules, nowMs, opts) {
3843
3947
  if (engine.isDraining?.()) break;
3844
3948
  const existing = await engine.getRun(runId);
3845
3949
  remember(settled, s.key, runId);
3846
- 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
+ }
3847
3957
  await engine.start(workflowName(s.workflow), s.input, runId, {
3848
3958
  namespace: s.namespace
3849
3959
  });
3850
3960
  ids.push(runId);
3961
+ if (s.overlap === "skip") {
3962
+ noteInFlight(engine, s.key, runId);
3963
+ break;
3964
+ }
3851
3965
  }
3852
3966
  }
3853
3967
  return ids;
3854
3968
  }
3855
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");
3856
4041
  var settledRunIds = /* @__PURE__ */ new WeakMap();
3857
4042
  function settledIdsFor(engine) {
3858
4043
  let memo = settledRunIds.get(engine);
@@ -4923,6 +5108,21 @@ function hmacTenantVerifier(secret, capabilities) {
4923
5108
  };
4924
5109
  }
4925
5110
  __name(hmacTenantVerifier, "hmacTenantVerifier");
5111
+ async function verifyWireTenant(wireTenant, verifyTenant) {
5112
+ if (!verifyTenant) return {
5113
+ tenant: wireTenant
5114
+ };
5115
+ return await verifyTenant({
5116
+ token: wireTenant,
5117
+ tenant: wireTenant
5118
+ }) ?? null;
5119
+ }
5120
+ __name(verifyWireTenant, "verifyWireTenant");
5121
+ function grantsClientTenant(verified, tenantId) {
5122
+ const capabilities = verified?.capabilities ?? [];
5123
+ return capabilities.includes("tenancy:*") || capabilities.includes(`tenancy:${tenantId}`);
5124
+ }
5125
+ __name(grantsClientTenant, "grantsClientTenant");
4926
5126
  async function resolveWireTenant(wireTenant, verifyTenant) {
4927
5127
  if (!verifyTenant) return wireTenant;
4928
5128
  const verified = await verifyTenant({
@@ -7193,20 +7393,31 @@ var WorkflowEngine = class _WorkflowEngine {
7193
7393
  }
7194
7394
  const verifyTenant = deps.verifyTenant;
7195
7395
  this.pool.onStartRun(async (message) => {
7196
- let tenant;
7396
+ let verified;
7197
7397
  try {
7198
- tenant = await resolveWireTenant(message.tenant, verifyTenant);
7398
+ verified = await verifyWireTenant(message.tenant, verifyTenant);
7199
7399
  } catch {
7200
- tenant = null;
7400
+ verified = null;
7201
7401
  }
7202
- if (tenant === null) {
7402
+ const tenant = verified?.tenant ?? null;
7403
+ if (verified === null || tenant === null) {
7203
7404
  console.warn(`[nestjs-durable] dropped a start-run for "${message.workflow}": invalid or unauthorized tenant token`);
7204
7405
  return;
7205
7406
  }
7206
7407
  await this.start(message.workflow, message.input, message.runId ?? globalThis.crypto.randomUUID(), {
7207
7408
  namespace: tenant,
7208
7409
  tags: message.tags,
7209
- searchAttributes: message.searchAttributes
7410
+ searchAttributes: message.searchAttributes,
7411
+ // The customer a tenant process claims for the run (A4): kept only when its verified
7412
+ // token grants `tenancy:*` or `tenancy:<id>`, else the run gets no customer tenant.
7413
+ ...message.tenantId !== void 0 ? grantsClientTenant(verified, message.tenantId) ? message.tenantKind !== void 0 ? {
7414
+ tenantId: message.tenantId,
7415
+ tenantKind: message.tenantKind
7416
+ } : {
7417
+ tenantId: message.tenantId
7418
+ } : {
7419
+ tenantId: null
7420
+ } : {}
7210
7421
  });
7211
7422
  });
7212
7423
  this.controlPlane?.onControl((msg) => {
@@ -9345,7 +9556,12 @@ var WorkflowEngine = class _WorkflowEngine {
9345
9556
  * invisible run reads exactly like a missing one (not found, never forbidden).
9346
9557
  */
9347
9558
  visibleRun(runId) {
9348
- const filter = this.restrictiveFilter();
9559
+ let filter;
9560
+ try {
9561
+ filter = this.restrictiveFilter();
9562
+ } catch (err) {
9563
+ return Promise.reject(err);
9564
+ }
9349
9565
  if (!filter) return this.store.getRun(runId);
9350
9566
  return this.store.getRun(runId).then((run) => run && tenantVisible(run, filter) ? run : null);
9351
9567
  }
@@ -9392,8 +9608,11 @@ var WorkflowEngine = class _WorkflowEngine {
9392
9608
  * timer, a signal, recovery or a worker. A run with no tenant, or tenancy off, runs `fn` as is.
9393
9609
  */
9394
9610
  inRunTenant(run, fn) {
9395
- const tenant = this.tenancy ? rowTenant(run) : void 0;
9396
- return tenant && this.tenancy ? this.tenancy.run(tenant, fn) : fn();
9611
+ const tenancy = this.tenancy;
9612
+ if (!tenancy) return fn();
9613
+ const tenant = rowTenant(run);
9614
+ const turn = tenant ? () => tenancy.run(tenant, fn) : fn;
9615
+ return tenancy.system ? tenancy.system(turn) : turn();
9397
9616
  }
9398
9617
  /**
9399
9618
  * Read a run's current persisted state (or null if unknown). With tenancy on, a run of another
@@ -9402,6 +9621,14 @@ var WorkflowEngine = class _WorkflowEngine {
9402
9621
  getRun(runId) {
9403
9622
  return this.visibleRun(runId);
9404
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
+ }
9405
9632
  /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9406
9633
  * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9407
9634
  async listCheckpoints(runId) {
@@ -17267,6 +17494,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17267
17494
  DURABLE_OPTIONS_CANONICAL,
17268
17495
  DURABLE_STEP_CONFIG,
17269
17496
  DURABLE_STEP_NAME,
17497
+ DuplicateDurableCopyError,
17270
17498
  DurableWorkflow,
17271
17499
  ENGINE_MINTED_TAG_PREFIXES,
17272
17500
  ENTITY_WORKFLOW,
@@ -17343,6 +17571,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17343
17571
  applyAttributeQuery,
17344
17572
  assertConcurrency,
17345
17573
  assertRoutes,
17574
+ assertSingleDurableCopy,
17346
17575
  attributeColumnFor,
17347
17576
  attributeOperand,
17348
17577
  attributePredicateOperands,
@@ -17376,6 +17605,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17376
17605
  describeWorker,
17377
17606
  descriptorHash,
17378
17607
  detailsOf,
17608
+ durableCopies,
17379
17609
  error,
17380
17610
  etagMatches,
17381
17611
  eventMatchOf,
@@ -17390,6 +17620,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17390
17620
  findStalledRuns,
17391
17621
  foldedCount,
17392
17622
  getRunsByIds,
17623
+ grantsClientTenant,
17393
17624
  handoffHandlerId,
17394
17625
  handoffName,
17395
17626
  hasDurableExecutionWrappers,
@@ -17481,6 +17712,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17481
17712
  scheduledRunId,
17482
17713
  scopeBufferedEvent,
17483
17714
  scopeTenantQuery,
17715
+ sealDurableCopies,
17484
17716
  settleResultsWithPlainCalls,
17485
17717
  signTenantToken,
17486
17718
  singletonAdmissionDenialPatch,
@@ -17505,6 +17737,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17505
17737
  triggeredRunsOf,
17506
17738
  triggeredSubscribersOf,
17507
17739
  useDurableExecution,
17740
+ verifyWireTenant,
17508
17741
  warn,
17509
17742
  withSingletonTracked,
17510
17743
  withoutSingletonMarkers,