@nagi-js/core 0.1.1-rc.13 → 0.1.1-rc.14
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.d.ts +218 -64
- package/dist/index.js +531 -18
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -856,6 +856,45 @@ var NagiCanceledError = class extends Error {
|
|
|
856
856
|
};
|
|
857
857
|
}
|
|
858
858
|
};
|
|
859
|
+
var NagiFlowSnapshotGoneError = class extends Error {
|
|
860
|
+
runId;
|
|
861
|
+
flowId;
|
|
862
|
+
pinnedHash;
|
|
863
|
+
currentHash;
|
|
864
|
+
constructor({
|
|
865
|
+
runId,
|
|
866
|
+
flowId,
|
|
867
|
+
pinnedHash,
|
|
868
|
+
currentHash
|
|
869
|
+
}) {
|
|
870
|
+
super(
|
|
871
|
+
currentHash === null ? `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but flow "${flowId}" is not registered with the current nagi(). Pin a worker on the prior code version or migrate the run.` : `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but the current registry has hash ${currentHash.slice(0, 12)}\u2026. Pin a worker on the prior code version or migrate the run.`
|
|
872
|
+
);
|
|
873
|
+
this.name = "NagiFlowSnapshotGoneError";
|
|
874
|
+
this.runId = runId;
|
|
875
|
+
this.flowId = flowId;
|
|
876
|
+
this.pinnedHash = pinnedHash;
|
|
877
|
+
this.currentHash = currentHash;
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
var NagiConcurrencyConflictError = class extends Error {
|
|
881
|
+
runId;
|
|
882
|
+
flowId;
|
|
883
|
+
concurrencyKey;
|
|
884
|
+
constructor({
|
|
885
|
+
runId,
|
|
886
|
+
flowId,
|
|
887
|
+
concurrencyKey
|
|
888
|
+
}) {
|
|
889
|
+
super(
|
|
890
|
+
`Run ${runId}: concurrent start lost the race on flow "${flowId}" concurrency key "${concurrencyKey}" \u2014 retry the caller transaction.`
|
|
891
|
+
);
|
|
892
|
+
this.name = "NagiConcurrencyConflictError";
|
|
893
|
+
this.runId = runId;
|
|
894
|
+
this.flowId = flowId;
|
|
895
|
+
this.concurrencyKey = concurrencyKey;
|
|
896
|
+
}
|
|
897
|
+
};
|
|
859
898
|
var NagiSnapshotDriftError = class extends Error {
|
|
860
899
|
runId;
|
|
861
900
|
expected;
|
|
@@ -885,6 +924,23 @@ function serializeError(err) {
|
|
|
885
924
|
return { name: "Error", message: String(err) };
|
|
886
925
|
}
|
|
887
926
|
|
|
927
|
+
// src/lease-reaper.ts
|
|
928
|
+
function decideExpiredLeaseAction(args) {
|
|
929
|
+
const { lease, stepStatus, now } = args;
|
|
930
|
+
if (stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
|
|
931
|
+
return { tag: "skip", reason: "terminal" };
|
|
932
|
+
}
|
|
933
|
+
if (lease.expiresAt > now) {
|
|
934
|
+
return { tag: "skip", reason: "still-live" };
|
|
935
|
+
}
|
|
936
|
+
return {
|
|
937
|
+
tag: "reap",
|
|
938
|
+
nextAttempt: lease.attempt + 1,
|
|
939
|
+
backoffMs: 0
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
var DEFAULT_REAPER_INTERVAL_MS = 3e4;
|
|
943
|
+
|
|
888
944
|
// src/facts.ts
|
|
889
945
|
var Facts = {
|
|
890
946
|
flowStarted(a) {
|
|
@@ -1007,6 +1063,17 @@ var Facts = {
|
|
|
1007
1063
|
...compact({ signalName: a.signalName })
|
|
1008
1064
|
};
|
|
1009
1065
|
},
|
|
1066
|
+
leaseReaped(a) {
|
|
1067
|
+
return {
|
|
1068
|
+
kind: "lease.reaped",
|
|
1069
|
+
runId: a.runId,
|
|
1070
|
+
stepId: a.stepId,
|
|
1071
|
+
attempt: a.attempt,
|
|
1072
|
+
at: a.at,
|
|
1073
|
+
reapedAt: a.reapedAt,
|
|
1074
|
+
reason: "expired"
|
|
1075
|
+
};
|
|
1076
|
+
},
|
|
1010
1077
|
flowRefUpdated(a) {
|
|
1011
1078
|
return {
|
|
1012
1079
|
kind: "flow_ref.updated",
|
|
@@ -1409,6 +1476,12 @@ var InMemoryStore = class {
|
|
|
1409
1476
|
}
|
|
1410
1477
|
return { started: true, canceled };
|
|
1411
1478
|
}
|
|
1479
|
+
// In-memory has no real tx; we share the underlying maps with tryStartRun,
|
|
1480
|
+
// so the implementation is intentionally a straight delegate. The `tx`
|
|
1481
|
+
// parameter is accepted for shape-compat with the Store contract.
|
|
1482
|
+
async tryStartRunOnTx(_tx, runId, fact, concurrency) {
|
|
1483
|
+
return this.tryStartRun(runId, fact, concurrency);
|
|
1484
|
+
}
|
|
1412
1485
|
async listChildren(parentRunId) {
|
|
1413
1486
|
const set = this.childrenByParent.get(parentRunId);
|
|
1414
1487
|
if (set === void 0) return [];
|
|
@@ -1428,6 +1501,72 @@ var InMemoryStore = class {
|
|
|
1428
1501
|
this.leases.set(key, { token, expiresAt: now + this.leaseMs });
|
|
1429
1502
|
return token;
|
|
1430
1503
|
}
|
|
1504
|
+
async extendLease(runId, stepId, attempt, leaseMs) {
|
|
1505
|
+
const key = `${runId}::${stepId}::${attempt}`;
|
|
1506
|
+
const existing = this.leases.get(key);
|
|
1507
|
+
if (existing === void 0) return;
|
|
1508
|
+
this.leases.set(key, {
|
|
1509
|
+
token: existing.token,
|
|
1510
|
+
expiresAt: Date.now() + leaseMs
|
|
1511
|
+
});
|
|
1512
|
+
}
|
|
1513
|
+
async sweepLeases(args) {
|
|
1514
|
+
const { now, queue, limit = 100 } = args;
|
|
1515
|
+
const reaped = [];
|
|
1516
|
+
const candidates = [];
|
|
1517
|
+
for (const [key, lease] of this.leases) {
|
|
1518
|
+
if (candidates.length >= limit) break;
|
|
1519
|
+
const parts = key.split("::");
|
|
1520
|
+
if (parts.length !== 3) continue;
|
|
1521
|
+
const [runId, stepId, attemptStr] = parts;
|
|
1522
|
+
candidates.push({
|
|
1523
|
+
key,
|
|
1524
|
+
runId,
|
|
1525
|
+
stepId,
|
|
1526
|
+
attempt: Number(attemptStr),
|
|
1527
|
+
expiresAt: new Date(lease.expiresAt)
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
for (const c of candidates) {
|
|
1531
|
+
const factList = this.facts.get(c.runId);
|
|
1532
|
+
const state = factList ? foldRun(c.runId, factList) : null;
|
|
1533
|
+
const ss = state ? stepStateOf(state, c.stepId) : null;
|
|
1534
|
+
const stepStatus = ss === null ? "pending" : stepStatusOf(ss);
|
|
1535
|
+
const decision = decideExpiredLeaseAction({
|
|
1536
|
+
lease: {
|
|
1537
|
+
runId: c.runId,
|
|
1538
|
+
stepId: c.stepId,
|
|
1539
|
+
attempt: c.attempt,
|
|
1540
|
+
expiresAt: c.expiresAt
|
|
1541
|
+
},
|
|
1542
|
+
stepStatus,
|
|
1543
|
+
now
|
|
1544
|
+
});
|
|
1545
|
+
if (decision.tag === "skip") continue;
|
|
1546
|
+
this.leases.delete(c.key);
|
|
1547
|
+
await this.appendFact(
|
|
1548
|
+
c.runId,
|
|
1549
|
+
Facts.leaseReaped({
|
|
1550
|
+
runId: c.runId,
|
|
1551
|
+
stepId: c.stepId,
|
|
1552
|
+
attempt: c.attempt,
|
|
1553
|
+
at: now,
|
|
1554
|
+
reapedAt: now
|
|
1555
|
+
})
|
|
1556
|
+
);
|
|
1557
|
+
await queue.enqueue(c.runId, c.stepId, {
|
|
1558
|
+
attempt: decision.nextAttempt,
|
|
1559
|
+
delayMs: decision.backoffMs
|
|
1560
|
+
});
|
|
1561
|
+
reaped.push({
|
|
1562
|
+
runId: c.runId,
|
|
1563
|
+
stepId: c.stepId,
|
|
1564
|
+
attempt: c.attempt,
|
|
1565
|
+
nextAttempt: decision.nextAttempt
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
return reaped;
|
|
1569
|
+
}
|
|
1431
1570
|
async settleStep(runId, _stepId, fact) {
|
|
1432
1571
|
await this.appendFact(runId, fact);
|
|
1433
1572
|
}
|
|
@@ -1513,6 +1652,117 @@ var InMemoryStore = class {
|
|
|
1513
1652
|
const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
|
|
1514
1653
|
return { runs: page, cursor };
|
|
1515
1654
|
}
|
|
1655
|
+
async describe(runId) {
|
|
1656
|
+
const factList = this.facts.get(runId);
|
|
1657
|
+
if (factList === void 0 || factList.length === 0) return null;
|
|
1658
|
+
const first = factList[0];
|
|
1659
|
+
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
1660
|
+
const state = foldRun(runId, factList);
|
|
1661
|
+
const status = runStatusOf(state);
|
|
1662
|
+
let completedAt;
|
|
1663
|
+
let output;
|
|
1664
|
+
let error;
|
|
1665
|
+
let canceledByRunId;
|
|
1666
|
+
let concurrencyKey;
|
|
1667
|
+
for (let i = factList.length - 1; i >= 0; i--) {
|
|
1668
|
+
const f = factList[i];
|
|
1669
|
+
if (f === void 0) continue;
|
|
1670
|
+
if (f.kind === "flow.completed") {
|
|
1671
|
+
completedAt = f.at;
|
|
1672
|
+
output = f.output;
|
|
1673
|
+
break;
|
|
1674
|
+
}
|
|
1675
|
+
if (f.kind === "flow.failed") {
|
|
1676
|
+
completedAt = f.at;
|
|
1677
|
+
error = f.error;
|
|
1678
|
+
break;
|
|
1679
|
+
}
|
|
1680
|
+
if (f.kind === "flow.canceled") {
|
|
1681
|
+
completedAt = f.at;
|
|
1682
|
+
if (f.cause === "concurrency") {
|
|
1683
|
+
canceledByRunId = f.canceledByRunId;
|
|
1684
|
+
}
|
|
1685
|
+
break;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
const slot = this.keyByActiveRun.get(runId);
|
|
1689
|
+
if (slot !== void 0) {
|
|
1690
|
+
const sep = slot.indexOf("::");
|
|
1691
|
+
if (sep >= 0) concurrencyKey = slot.slice(sep + 2);
|
|
1692
|
+
}
|
|
1693
|
+
if (concurrencyKey === void 0) {
|
|
1694
|
+
for (const f of factList) {
|
|
1695
|
+
if (f.kind === "flow.canceled" && f.cause === "concurrency") {
|
|
1696
|
+
concurrencyKey = f.concurrencyKey;
|
|
1697
|
+
break;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
const childSet = this.childrenByParent.get(runId);
|
|
1702
|
+
const children = childSet ? Array.from(childSet) : [];
|
|
1703
|
+
const parent = first.parent;
|
|
1704
|
+
const run = {
|
|
1705
|
+
runId,
|
|
1706
|
+
flowId: first.flowId,
|
|
1707
|
+
flowHash: first.flowHash ?? "",
|
|
1708
|
+
status,
|
|
1709
|
+
startedAt: first.at,
|
|
1710
|
+
input: first.input,
|
|
1711
|
+
children,
|
|
1712
|
+
...completedAt !== void 0 ? { completedAt } : {},
|
|
1713
|
+
...output !== void 0 ? { output } : {},
|
|
1714
|
+
...error !== void 0 ? { error } : {},
|
|
1715
|
+
...canceledByRunId !== void 0 ? { canceledByRunId } : {},
|
|
1716
|
+
...concurrencyKey !== void 0 ? { concurrencyKey } : {},
|
|
1717
|
+
...parent !== void 0 ? { parent } : {}
|
|
1718
|
+
};
|
|
1719
|
+
const steps = [];
|
|
1720
|
+
const startedAtByStep = /* @__PURE__ */ new Map();
|
|
1721
|
+
const completedAtByStep = /* @__PURE__ */ new Map();
|
|
1722
|
+
for (const f of factList) {
|
|
1723
|
+
if (f.kind === "step.started" && !startedAtByStep.has(f.stepId)) {
|
|
1724
|
+
startedAtByStep.set(f.stepId, f.at);
|
|
1725
|
+
}
|
|
1726
|
+
if ((f.kind === "step.completed" || f.kind === "step.failed" || f.kind === "step.canceled" || f.kind === "step.skipped") && !completedAtByStep.has(f.stepId)) {
|
|
1727
|
+
completedAtByStep.set(f.stepId, f.at);
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
const now = Date.now();
|
|
1731
|
+
for (const [stepId, stepState] of Object.entries(state.steps)) {
|
|
1732
|
+
const status2 = stepStatusOf(stepState);
|
|
1733
|
+
const attempt = attemptOf(stepState);
|
|
1734
|
+
const out = outputOf(stepState);
|
|
1735
|
+
const err = errorOf(stepState);
|
|
1736
|
+
const startedAt = startedAtByStep.get(stepId);
|
|
1737
|
+
const completedAt2 = completedAtByStep.get(stepId);
|
|
1738
|
+
let lease;
|
|
1739
|
+
const leasePrefix = `${runId}::${stepId}::`;
|
|
1740
|
+
let bestExpiry = 0;
|
|
1741
|
+
for (const [key, l] of this.leases) {
|
|
1742
|
+
if (!key.startsWith(leasePrefix)) continue;
|
|
1743
|
+
if (l.expiresAt > now && l.expiresAt > bestExpiry)
|
|
1744
|
+
bestExpiry = l.expiresAt;
|
|
1745
|
+
}
|
|
1746
|
+
if (bestExpiry > 0) lease = { expiresAt: new Date(bestExpiry) };
|
|
1747
|
+
steps.push({
|
|
1748
|
+
stepId,
|
|
1749
|
+
attempt,
|
|
1750
|
+
status: status2,
|
|
1751
|
+
...startedAt !== void 0 ? { startedAt } : {},
|
|
1752
|
+
...completedAt2 !== void 0 ? { completedAt: completedAt2 } : {},
|
|
1753
|
+
...out !== null ? { output: out } : {},
|
|
1754
|
+
...err !== void 0 ? { error: err } : {},
|
|
1755
|
+
...lease !== void 0 ? { lease } : {}
|
|
1756
|
+
});
|
|
1757
|
+
}
|
|
1758
|
+
steps.sort((a, b) => {
|
|
1759
|
+
const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
1760
|
+
const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
1761
|
+
if (ta !== tb) return ta - tb;
|
|
1762
|
+
return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
|
|
1763
|
+
});
|
|
1764
|
+
return { run, steps };
|
|
1765
|
+
}
|
|
1516
1766
|
async pruneFacts(opts) {
|
|
1517
1767
|
const olderThanMs = opts.olderThan.getTime();
|
|
1518
1768
|
const statusSet = new Set(opts.statuses);
|
|
@@ -1757,6 +2007,26 @@ var InMemoryTrigger = class {
|
|
|
1757
2007
|
}
|
|
1758
2008
|
};
|
|
1759
2009
|
|
|
2010
|
+
// src/run-id.ts
|
|
2011
|
+
var RunId = {
|
|
2012
|
+
parse(s) {
|
|
2013
|
+
if (typeof s !== "string" || s.length === 0) {
|
|
2014
|
+
throw validationError("RunId.parse: must be a non-empty string", [
|
|
2015
|
+
"runId"
|
|
2016
|
+
]);
|
|
2017
|
+
}
|
|
2018
|
+
if (/\s/.test(s)) {
|
|
2019
|
+
throw validationError("RunId.parse: must not contain whitespace", [
|
|
2020
|
+
"runId"
|
|
2021
|
+
]);
|
|
2022
|
+
}
|
|
2023
|
+
return s;
|
|
2024
|
+
},
|
|
2025
|
+
fromTrusted(s) {
|
|
2026
|
+
return s;
|
|
2027
|
+
}
|
|
2028
|
+
};
|
|
2029
|
+
|
|
1760
2030
|
// src/exec/hooks.ts
|
|
1761
2031
|
function makeHooks(deps) {
|
|
1762
2032
|
async function fireHook(hook, event, hookName) {
|
|
@@ -1996,14 +2266,14 @@ var DEFAULT_RETRY2 = {
|
|
|
1996
2266
|
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
1997
2267
|
var NagiAbortError = class extends Error {
|
|
1998
2268
|
runId;
|
|
1999
|
-
|
|
2000
|
-
constructor(runId,
|
|
2269
|
+
kind;
|
|
2270
|
+
constructor(runId, kind) {
|
|
2001
2271
|
super(
|
|
2002
|
-
|
|
2272
|
+
kind === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
|
|
2003
2273
|
);
|
|
2004
|
-
this.name = "
|
|
2274
|
+
this.name = "AbortError";
|
|
2005
2275
|
this.runId = runId;
|
|
2006
|
-
this.
|
|
2276
|
+
this.kind = kind;
|
|
2007
2277
|
}
|
|
2008
2278
|
};
|
|
2009
2279
|
function resolveExecutionFact(args) {
|
|
@@ -2055,21 +2325,38 @@ function startCancelWatcher(args) {
|
|
|
2055
2325
|
var DEFAULT_HEARTBEAT_LEASE_MS = 12e4;
|
|
2056
2326
|
var DEFAULT_HEARTBEAT_INTERVAL_MS = 4e4;
|
|
2057
2327
|
function startHeartbeat(args) {
|
|
2058
|
-
const {
|
|
2328
|
+
const {
|
|
2329
|
+
queue,
|
|
2330
|
+
store,
|
|
2331
|
+
runId,
|
|
2332
|
+
stepId,
|
|
2333
|
+
attempt,
|
|
2334
|
+
receipt,
|
|
2335
|
+
intervalMs,
|
|
2336
|
+
leaseMs,
|
|
2337
|
+
emitLog
|
|
2338
|
+
} = args;
|
|
2059
2339
|
let stopped = false;
|
|
2060
2340
|
let timer;
|
|
2061
2341
|
const schedule = () => {
|
|
2062
2342
|
timer = setTimeout(() => {
|
|
2063
2343
|
void (async () => {
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
})
|
|
2072
|
-
|
|
2344
|
+
await Promise.all([
|
|
2345
|
+
queue.extend(receipt, leaseMs).catch((err) => {
|
|
2346
|
+
emitLog({
|
|
2347
|
+
level: "warn",
|
|
2348
|
+
msg: "heartbeat: failed to extend message visibility",
|
|
2349
|
+
attrs: { receipt, error: String(err) }
|
|
2350
|
+
});
|
|
2351
|
+
}),
|
|
2352
|
+
store.extendLease(runId, stepId, attempt, leaseMs).catch((err) => {
|
|
2353
|
+
emitLog({
|
|
2354
|
+
level: "warn",
|
|
2355
|
+
msg: "heartbeat: failed to extend store lease",
|
|
2356
|
+
attrs: { runId, stepId, attempt, error: String(err) }
|
|
2357
|
+
});
|
|
2358
|
+
})
|
|
2359
|
+
]);
|
|
2073
2360
|
if (!stopped) schedule();
|
|
2074
2361
|
})();
|
|
2075
2362
|
}, intervalMs);
|
|
@@ -2095,11 +2382,29 @@ function classifyFailure(args) {
|
|
|
2095
2382
|
includeError: isAbort
|
|
2096
2383
|
};
|
|
2097
2384
|
}
|
|
2385
|
+
const cancel = findNagiCanceledError(err);
|
|
2386
|
+
if (cancel !== void 0) {
|
|
2387
|
+
return {
|
|
2388
|
+
tag: "flowCanceled",
|
|
2389
|
+
canceledByRunId: cancel.canceledByRunId,
|
|
2390
|
+
concurrencyKey: cancel.concurrencyKey
|
|
2391
|
+
};
|
|
2392
|
+
}
|
|
2098
2393
|
if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
|
|
2099
2394
|
return { tag: "retry", delayMs: computeBackoff(policy, attempt) };
|
|
2100
2395
|
}
|
|
2101
2396
|
return { tag: "failed" };
|
|
2102
2397
|
}
|
|
2398
|
+
function findNagiCanceledError(err) {
|
|
2399
|
+
let cursor = err;
|
|
2400
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2401
|
+
while (cursor instanceof Error && !seen.has(cursor)) {
|
|
2402
|
+
if (cursor instanceof NagiCanceledError) return cursor;
|
|
2403
|
+
seen.add(cursor);
|
|
2404
|
+
cursor = cursor.cause;
|
|
2405
|
+
}
|
|
2406
|
+
return void 0;
|
|
2407
|
+
}
|
|
2103
2408
|
function computeBackoff(policy, attempt) {
|
|
2104
2409
|
const initial = policy.initialDelayMs ?? 1e3;
|
|
2105
2410
|
const max = policy.maxDelayMs ?? 6e4;
|
|
@@ -2169,6 +2474,10 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2169
2474
|
const startedAt = Date.now();
|
|
2170
2475
|
const heartbeat = startHeartbeat({
|
|
2171
2476
|
queue,
|
|
2477
|
+
store: deps.store,
|
|
2478
|
+
runId: message.runId,
|
|
2479
|
+
stepId: message.stepId,
|
|
2480
|
+
attempt: message.attempt,
|
|
2172
2481
|
receipt: message.receipt,
|
|
2173
2482
|
intervalMs: deps.heartbeat.intervalMs,
|
|
2174
2483
|
leaseMs: deps.heartbeat.leaseMs,
|
|
@@ -2541,6 +2850,23 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2541
2850
|
);
|
|
2542
2851
|
return { tag: "advance" };
|
|
2543
2852
|
}
|
|
2853
|
+
case "flowCanceled": {
|
|
2854
|
+
const at = clock.now();
|
|
2855
|
+
await store.appendFact(
|
|
2856
|
+
runId,
|
|
2857
|
+
Facts.stepCanceled(runId, stepId, attempt, at, error)
|
|
2858
|
+
);
|
|
2859
|
+
await store.appendFact(
|
|
2860
|
+
runId,
|
|
2861
|
+
Facts.flowCanceledByConcurrency({
|
|
2862
|
+
runId,
|
|
2863
|
+
at,
|
|
2864
|
+
canceledByRunId: outcome.canceledByRunId,
|
|
2865
|
+
concurrencyKey: outcome.concurrencyKey
|
|
2866
|
+
})
|
|
2867
|
+
);
|
|
2868
|
+
return { tag: "parked" };
|
|
2869
|
+
}
|
|
2544
2870
|
}
|
|
2545
2871
|
}
|
|
2546
2872
|
return { dispatchMessage };
|
|
@@ -2756,8 +3082,20 @@ function makeFlowRegistry(flows) {
|
|
|
2756
3082
|
}
|
|
2757
3083
|
return flow2;
|
|
2758
3084
|
},
|
|
2759
|
-
requireForRun(flowId, runId) {
|
|
3085
|
+
requireForRun(flowId, runId, pinnedHash, currentHashOf) {
|
|
2760
3086
|
const flow2 = byId.get(flowId);
|
|
3087
|
+
if (pinnedHash !== void 0) {
|
|
3088
|
+
const currentHash = flow2 === void 0 ? null : currentHashOf?.(flowId) ?? null;
|
|
3089
|
+
if (flow2 === void 0 || currentHash !== pinnedHash) {
|
|
3090
|
+
throw new NagiFlowSnapshotGoneError({
|
|
3091
|
+
runId,
|
|
3092
|
+
flowId,
|
|
3093
|
+
pinnedHash,
|
|
3094
|
+
currentHash
|
|
3095
|
+
});
|
|
3096
|
+
}
|
|
3097
|
+
return flow2;
|
|
3098
|
+
}
|
|
2761
3099
|
if (!flow2) {
|
|
2762
3100
|
throw new NagiRuntimeError(
|
|
2763
3101
|
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
@@ -3081,6 +3419,23 @@ var WorkerImpl = class {
|
|
|
3081
3419
|
try {
|
|
3082
3420
|
await this.dispatcher.dispatchMessage(msg);
|
|
3083
3421
|
} catch (err) {
|
|
3422
|
+
if (err instanceof NagiFlowSnapshotGoneError) {
|
|
3423
|
+
this.deps.emitLog({
|
|
3424
|
+
level: "warn",
|
|
3425
|
+
msg: "worker.dispatch: flow snapshot gone \u2014 nacking",
|
|
3426
|
+
attrs: {
|
|
3427
|
+
runId: err.runId,
|
|
3428
|
+
flowId: err.flowId,
|
|
3429
|
+
pinnedHash: err.pinnedHash,
|
|
3430
|
+
currentHash: err.currentHash
|
|
3431
|
+
}
|
|
3432
|
+
});
|
|
3433
|
+
try {
|
|
3434
|
+
await this.deps.queue.nack(msg.receipt);
|
|
3435
|
+
} catch {
|
|
3436
|
+
}
|
|
3437
|
+
return;
|
|
3438
|
+
}
|
|
3084
3439
|
this.deps.emitLog({
|
|
3085
3440
|
level: "error",
|
|
3086
3441
|
msg: "worker.dispatch threw uncaught",
|
|
@@ -3151,7 +3506,12 @@ async function nagiImpl(config) {
|
|
|
3151
3506
|
const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
|
|
3152
3507
|
async function flowFor(runId) {
|
|
3153
3508
|
const runState = await config.store.loadRunState(runId);
|
|
3154
|
-
return registry.requireForRun(
|
|
3509
|
+
return registry.requireForRun(
|
|
3510
|
+
runState.flowId,
|
|
3511
|
+
runId,
|
|
3512
|
+
runState.flowHash,
|
|
3513
|
+
(id) => flowHashById.get(id)
|
|
3514
|
+
);
|
|
3155
3515
|
}
|
|
3156
3516
|
function lookupFlow(flowId) {
|
|
3157
3517
|
return registry.get(flowId);
|
|
@@ -3358,6 +3718,121 @@ async function nagiImpl(config) {
|
|
|
3358
3718
|
await startRunInternal({ flow: flow2, validatedInput: validated, runId });
|
|
3359
3719
|
return runId;
|
|
3360
3720
|
},
|
|
3721
|
+
async startStaged(flow2, input, opts) {
|
|
3722
|
+
return wf.startStagedById(flow2.id, input, opts);
|
|
3723
|
+
},
|
|
3724
|
+
async startStagedById(flowId, input, opts) {
|
|
3725
|
+
if (opts === void 0 || opts.tx === void 0) {
|
|
3726
|
+
throw validationError(
|
|
3727
|
+
"startStaged: opts.tx is required (the caller-supplied transaction the run row, flow.started fact, and initial enqueue commit on).",
|
|
3728
|
+
["tx"]
|
|
3729
|
+
);
|
|
3730
|
+
}
|
|
3731
|
+
const flow2 = registry.require(flowId);
|
|
3732
|
+
let runId;
|
|
3733
|
+
if (opts.runId !== void 0) {
|
|
3734
|
+
if (typeof opts.runId !== "string" || opts.runId.length === 0) {
|
|
3735
|
+
throw validationError("opts.runId must be a non-empty string", [
|
|
3736
|
+
"runId"
|
|
3737
|
+
]);
|
|
3738
|
+
}
|
|
3739
|
+
runId = opts.runId;
|
|
3740
|
+
} else {
|
|
3741
|
+
runId = mintRunId();
|
|
3742
|
+
}
|
|
3743
|
+
const validated = await validate(flow2.input, input);
|
|
3744
|
+
const startedAt = clock.now();
|
|
3745
|
+
const flowHash = flowHashById.get(flow2.id);
|
|
3746
|
+
const fact = Facts.flowStarted({
|
|
3747
|
+
runId,
|
|
3748
|
+
flowId: flow2.id,
|
|
3749
|
+
input: validated,
|
|
3750
|
+
at: startedAt,
|
|
3751
|
+
codeVersion,
|
|
3752
|
+
...compact({ flowHash })
|
|
3753
|
+
});
|
|
3754
|
+
let concurrencyArg;
|
|
3755
|
+
if (flow2.concurrency !== void 0) {
|
|
3756
|
+
const derived = flow2.concurrency.keyFn(validated);
|
|
3757
|
+
if (typeof derived !== "string" || derived.length === 0) {
|
|
3758
|
+
throw validationError(
|
|
3759
|
+
`flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
3760
|
+
["concurrency", "keyFn"]
|
|
3761
|
+
);
|
|
3762
|
+
}
|
|
3763
|
+
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
3764
|
+
}
|
|
3765
|
+
const { started, canceled } = await config.store.tryStartRunOnTx(
|
|
3766
|
+
opts.tx,
|
|
3767
|
+
runId,
|
|
3768
|
+
fact,
|
|
3769
|
+
concurrencyArg
|
|
3770
|
+
);
|
|
3771
|
+
if (started) {
|
|
3772
|
+
const seedState = foldRun(runId, [fact]);
|
|
3773
|
+
const transition = nextTransition(flow2, seedState);
|
|
3774
|
+
if (transition.kind === "dispatch") {
|
|
3775
|
+
const txQueue = bindQueueToTx(config.queue, opts.tx);
|
|
3776
|
+
for (const stepId of transition.runnable) {
|
|
3777
|
+
await txQueue.enqueue(runId, stepId);
|
|
3778
|
+
}
|
|
3779
|
+
}
|
|
3780
|
+
}
|
|
3781
|
+
let fired = false;
|
|
3782
|
+
const applyOnCommit = async () => {
|
|
3783
|
+
if (fired) return;
|
|
3784
|
+
fired = true;
|
|
3785
|
+
if (!started) return;
|
|
3786
|
+
for (const c of canceled) {
|
|
3787
|
+
const cancelError = new NagiCanceledError({
|
|
3788
|
+
runId: c.runId,
|
|
3789
|
+
canceledByRunId: runId,
|
|
3790
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
3791
|
+
});
|
|
3792
|
+
const serialized = {
|
|
3793
|
+
...serializeError(cancelError),
|
|
3794
|
+
cause: {
|
|
3795
|
+
canceledByRunId: runId,
|
|
3796
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
3797
|
+
}
|
|
3798
|
+
};
|
|
3799
|
+
const errorEvent = {
|
|
3800
|
+
runId: c.runId,
|
|
3801
|
+
flowId: flow2.id,
|
|
3802
|
+
error: serialized,
|
|
3803
|
+
at: c.fact.at
|
|
3804
|
+
};
|
|
3805
|
+
await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
|
|
3806
|
+
await hooks.fireHook(
|
|
3807
|
+
config.hooks?.onFlowError,
|
|
3808
|
+
errorEvent,
|
|
3809
|
+
"onFlowError"
|
|
3810
|
+
);
|
|
3811
|
+
await dispatcher.propagateToParent(c.runId, {
|
|
3812
|
+
kind: "canceled",
|
|
3813
|
+
error: serialized
|
|
3814
|
+
});
|
|
3815
|
+
}
|
|
3816
|
+
const startEvent = {
|
|
3817
|
+
runId,
|
|
3818
|
+
flowId: flow2.id,
|
|
3819
|
+
input: validated,
|
|
3820
|
+
at: startedAt
|
|
3821
|
+
};
|
|
3822
|
+
await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
|
|
3823
|
+
await hooks.fireHook(
|
|
3824
|
+
config.hooks?.onFlowStart,
|
|
3825
|
+
startEvent,
|
|
3826
|
+
"onFlowStart"
|
|
3827
|
+
);
|
|
3828
|
+
};
|
|
3829
|
+
return {
|
|
3830
|
+
runId,
|
|
3831
|
+
started,
|
|
3832
|
+
canceled: canceled.map((c) => c.runId),
|
|
3833
|
+
applyOnCommit
|
|
3834
|
+
};
|
|
3835
|
+
},
|
|
3361
3836
|
signal: signals.signal,
|
|
3362
3837
|
async cancel(runId, opts) {
|
|
3363
3838
|
await cancelRunRecursive(runId, {
|
|
@@ -3384,6 +3859,9 @@ async function nagiImpl(config) {
|
|
|
3384
3859
|
return makeWorker({ ...dispatchDeps, clock }, workerConfig);
|
|
3385
3860
|
},
|
|
3386
3861
|
replay: replayer.replay,
|
|
3862
|
+
async describe(runId) {
|
|
3863
|
+
return config.store.describe(runId);
|
|
3864
|
+
},
|
|
3387
3865
|
async queryRuns(opts = {}) {
|
|
3388
3866
|
if (opts.latest === true) {
|
|
3389
3867
|
if (opts.limit !== void 0 || opts.cursor !== void 0) {
|
|
@@ -3454,6 +3932,7 @@ async function nagiRun(config) {
|
|
|
3454
3932
|
const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
|
|
3455
3933
|
const worker = wf.worker({ ...config.worker, signal });
|
|
3456
3934
|
const emitLog = makeEmit(config.onLog);
|
|
3935
|
+
const clock = config.clock ?? new InMemoryClock();
|
|
3457
3936
|
const loop = worker.run();
|
|
3458
3937
|
loop.catch((err) => {
|
|
3459
3938
|
if (signal.aborted) return;
|
|
@@ -3463,6 +3942,31 @@ async function nagiRun(config) {
|
|
|
3463
3942
|
attrs: { error: String(err) }
|
|
3464
3943
|
});
|
|
3465
3944
|
});
|
|
3945
|
+
const reaperIntervalMs = config.reaperIntervalMs ?? DEFAULT_REAPER_INTERVAL_MS;
|
|
3946
|
+
const reaper = reaperIntervalMs > 0 ? (async () => {
|
|
3947
|
+
while (!signal.aborted) {
|
|
3948
|
+
try {
|
|
3949
|
+
await clock.sleep(reaperIntervalMs, signal);
|
|
3950
|
+
} catch {
|
|
3951
|
+
return;
|
|
3952
|
+
}
|
|
3953
|
+
if (signal.aborted) return;
|
|
3954
|
+
try {
|
|
3955
|
+
await config.store.sweepLeases({
|
|
3956
|
+
now: clock.now(),
|
|
3957
|
+
queue: config.queue
|
|
3958
|
+
});
|
|
3959
|
+
} catch (err) {
|
|
3960
|
+
emitLog({
|
|
3961
|
+
level: "warn",
|
|
3962
|
+
msg: "nagi.run: lease reaper sweep failed",
|
|
3963
|
+
attrs: { error: String(err) }
|
|
3964
|
+
});
|
|
3965
|
+
}
|
|
3966
|
+
}
|
|
3967
|
+
})() : Promise.resolve();
|
|
3968
|
+
reaper.catch(() => {
|
|
3969
|
+
});
|
|
3466
3970
|
let stopping;
|
|
3467
3971
|
const stop = () => {
|
|
3468
3972
|
stopping ??= (async () => {
|
|
@@ -3471,6 +3975,10 @@ async function nagiRun(config) {
|
|
|
3471
3975
|
await loop;
|
|
3472
3976
|
} catch {
|
|
3473
3977
|
}
|
|
3978
|
+
try {
|
|
3979
|
+
await reaper;
|
|
3980
|
+
} catch {
|
|
3981
|
+
}
|
|
3474
3982
|
})();
|
|
3475
3983
|
return stopping;
|
|
3476
3984
|
};
|
|
@@ -3487,7 +3995,12 @@ function asStreamTransport(store) {
|
|
|
3487
3995
|
const s = store;
|
|
3488
3996
|
return typeof s.subscribeStream === "function" && typeof s.publishChunk === "function" ? s : void 0;
|
|
3489
3997
|
}
|
|
3998
|
+
function bindQueueToTx(queue, tx) {
|
|
3999
|
+
const q = queue;
|
|
4000
|
+
if (typeof q.withTx === "function") return q.withTx(tx);
|
|
4001
|
+
return queue;
|
|
4002
|
+
}
|
|
3490
4003
|
|
|
3491
|
-
export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiCanceledError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, attemptOf, canonicalize, decideSignal, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
|
|
4004
|
+
export { DEFAULT_REAPER_INTERVAL_MS, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, RunId, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
|
|
3492
4005
|
//# sourceMappingURL=index.js.map
|
|
3493
4006
|
//# sourceMappingURL=index.js.map
|