@nagi-js/core 0.1.1-rc.13 → 0.1.1-rc.15
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 +548 -25
- 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,41 @@ 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
|
+
async function deriveChildRunId(parent) {
|
|
2030
|
+
const seed = `nagi:subflow:${parent.runId}:${parent.stepId}:${parent.attempt}`;
|
|
2031
|
+
const digest = await crypto.subtle.digest(
|
|
2032
|
+
"SHA-256",
|
|
2033
|
+
new TextEncoder().encode(seed)
|
|
2034
|
+
);
|
|
2035
|
+
const bytes = new Uint8Array(digest).subarray(0, 16);
|
|
2036
|
+
bytes[6] = (bytes[6] ?? 0) & 15 | 80;
|
|
2037
|
+
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
2038
|
+
const hex2 = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
|
|
2039
|
+
""
|
|
2040
|
+
);
|
|
2041
|
+
const uuid = `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20, 32)}`;
|
|
2042
|
+
return `run-${uuid}`;
|
|
2043
|
+
}
|
|
2044
|
+
|
|
1760
2045
|
// src/exec/hooks.ts
|
|
1761
2046
|
function makeHooks(deps) {
|
|
1762
2047
|
async function fireHook(hook, event, hookName) {
|
|
@@ -1996,14 +2281,14 @@ var DEFAULT_RETRY2 = {
|
|
|
1996
2281
|
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
1997
2282
|
var NagiAbortError = class extends Error {
|
|
1998
2283
|
runId;
|
|
1999
|
-
|
|
2000
|
-
constructor(runId,
|
|
2284
|
+
kind;
|
|
2285
|
+
constructor(runId, kind) {
|
|
2001
2286
|
super(
|
|
2002
|
-
|
|
2287
|
+
kind === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
|
|
2003
2288
|
);
|
|
2004
|
-
this.name = "
|
|
2289
|
+
this.name = "AbortError";
|
|
2005
2290
|
this.runId = runId;
|
|
2006
|
-
this.
|
|
2291
|
+
this.kind = kind;
|
|
2007
2292
|
}
|
|
2008
2293
|
};
|
|
2009
2294
|
function resolveExecutionFact(args) {
|
|
@@ -2055,21 +2340,38 @@ function startCancelWatcher(args) {
|
|
|
2055
2340
|
var DEFAULT_HEARTBEAT_LEASE_MS = 12e4;
|
|
2056
2341
|
var DEFAULT_HEARTBEAT_INTERVAL_MS = 4e4;
|
|
2057
2342
|
function startHeartbeat(args) {
|
|
2058
|
-
const {
|
|
2343
|
+
const {
|
|
2344
|
+
queue,
|
|
2345
|
+
store,
|
|
2346
|
+
runId,
|
|
2347
|
+
stepId,
|
|
2348
|
+
attempt,
|
|
2349
|
+
receipt,
|
|
2350
|
+
intervalMs,
|
|
2351
|
+
leaseMs,
|
|
2352
|
+
emitLog
|
|
2353
|
+
} = args;
|
|
2059
2354
|
let stopped = false;
|
|
2060
2355
|
let timer;
|
|
2061
2356
|
const schedule = () => {
|
|
2062
2357
|
timer = setTimeout(() => {
|
|
2063
2358
|
void (async () => {
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
})
|
|
2072
|
-
|
|
2359
|
+
await Promise.all([
|
|
2360
|
+
queue.extend(receipt, leaseMs).catch((err) => {
|
|
2361
|
+
emitLog({
|
|
2362
|
+
level: "warn",
|
|
2363
|
+
msg: "heartbeat: failed to extend message visibility",
|
|
2364
|
+
attrs: { receipt, error: String(err) }
|
|
2365
|
+
});
|
|
2366
|
+
}),
|
|
2367
|
+
store.extendLease(runId, stepId, attempt, leaseMs).catch((err) => {
|
|
2368
|
+
emitLog({
|
|
2369
|
+
level: "warn",
|
|
2370
|
+
msg: "heartbeat: failed to extend store lease",
|
|
2371
|
+
attrs: { runId, stepId, attempt, error: String(err) }
|
|
2372
|
+
});
|
|
2373
|
+
})
|
|
2374
|
+
]);
|
|
2073
2375
|
if (!stopped) schedule();
|
|
2074
2376
|
})();
|
|
2075
2377
|
}, intervalMs);
|
|
@@ -2095,11 +2397,29 @@ function classifyFailure(args) {
|
|
|
2095
2397
|
includeError: isAbort
|
|
2096
2398
|
};
|
|
2097
2399
|
}
|
|
2400
|
+
const cancel = findNagiCanceledError(err);
|
|
2401
|
+
if (cancel !== void 0) {
|
|
2402
|
+
return {
|
|
2403
|
+
tag: "flowCanceled",
|
|
2404
|
+
canceledByRunId: cancel.canceledByRunId,
|
|
2405
|
+
concurrencyKey: cancel.concurrencyKey
|
|
2406
|
+
};
|
|
2407
|
+
}
|
|
2098
2408
|
if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
|
|
2099
2409
|
return { tag: "retry", delayMs: computeBackoff(policy, attempt) };
|
|
2100
2410
|
}
|
|
2101
2411
|
return { tag: "failed" };
|
|
2102
2412
|
}
|
|
2413
|
+
function findNagiCanceledError(err) {
|
|
2414
|
+
let cursor = err;
|
|
2415
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2416
|
+
while (cursor instanceof Error && !seen.has(cursor)) {
|
|
2417
|
+
if (cursor instanceof NagiCanceledError) return cursor;
|
|
2418
|
+
seen.add(cursor);
|
|
2419
|
+
cursor = cursor.cause;
|
|
2420
|
+
}
|
|
2421
|
+
return void 0;
|
|
2422
|
+
}
|
|
2103
2423
|
function computeBackoff(policy, attempt) {
|
|
2104
2424
|
const initial = policy.initialDelayMs ?? 1e3;
|
|
2105
2425
|
const max = policy.maxDelayMs ?? 6e4;
|
|
@@ -2169,6 +2489,10 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2169
2489
|
const startedAt = Date.now();
|
|
2170
2490
|
const heartbeat = startHeartbeat({
|
|
2171
2491
|
queue,
|
|
2492
|
+
store: deps.store,
|
|
2493
|
+
runId: message.runId,
|
|
2494
|
+
stepId: message.stepId,
|
|
2495
|
+
attempt: message.attempt,
|
|
2172
2496
|
receipt: message.receipt,
|
|
2173
2497
|
intervalMs: deps.heartbeat.intervalMs,
|
|
2174
2498
|
leaseMs: deps.heartbeat.leaseMs,
|
|
@@ -2541,6 +2865,23 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2541
2865
|
);
|
|
2542
2866
|
return { tag: "advance" };
|
|
2543
2867
|
}
|
|
2868
|
+
case "flowCanceled": {
|
|
2869
|
+
const at = clock.now();
|
|
2870
|
+
await store.appendFact(
|
|
2871
|
+
runId,
|
|
2872
|
+
Facts.stepCanceled(runId, stepId, attempt, at, error)
|
|
2873
|
+
);
|
|
2874
|
+
await store.appendFact(
|
|
2875
|
+
runId,
|
|
2876
|
+
Facts.flowCanceledByConcurrency({
|
|
2877
|
+
runId,
|
|
2878
|
+
at,
|
|
2879
|
+
canceledByRunId: outcome.canceledByRunId,
|
|
2880
|
+
concurrencyKey: outcome.concurrencyKey
|
|
2881
|
+
})
|
|
2882
|
+
);
|
|
2883
|
+
return { tag: "parked" };
|
|
2884
|
+
}
|
|
2544
2885
|
}
|
|
2545
2886
|
}
|
|
2546
2887
|
return { dispatchMessage };
|
|
@@ -2756,8 +3097,20 @@ function makeFlowRegistry(flows) {
|
|
|
2756
3097
|
}
|
|
2757
3098
|
return flow2;
|
|
2758
3099
|
},
|
|
2759
|
-
requireForRun(flowId, runId) {
|
|
3100
|
+
requireForRun(flowId, runId, pinnedHash, currentHashOf) {
|
|
2760
3101
|
const flow2 = byId.get(flowId);
|
|
3102
|
+
if (pinnedHash !== void 0) {
|
|
3103
|
+
const currentHash = flow2 === void 0 ? null : currentHashOf?.(flowId) ?? null;
|
|
3104
|
+
if (flow2 === void 0 || currentHash !== pinnedHash) {
|
|
3105
|
+
throw new NagiFlowSnapshotGoneError({
|
|
3106
|
+
runId,
|
|
3107
|
+
flowId,
|
|
3108
|
+
pinnedHash,
|
|
3109
|
+
currentHash
|
|
3110
|
+
});
|
|
3111
|
+
}
|
|
3112
|
+
return flow2;
|
|
3113
|
+
}
|
|
2761
3114
|
if (!flow2) {
|
|
2762
3115
|
throw new NagiRuntimeError(
|
|
2763
3116
|
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
@@ -3081,6 +3434,23 @@ var WorkerImpl = class {
|
|
|
3081
3434
|
try {
|
|
3082
3435
|
await this.dispatcher.dispatchMessage(msg);
|
|
3083
3436
|
} catch (err) {
|
|
3437
|
+
if (err instanceof NagiFlowSnapshotGoneError) {
|
|
3438
|
+
this.deps.emitLog({
|
|
3439
|
+
level: "warn",
|
|
3440
|
+
msg: "worker.dispatch: flow snapshot gone \u2014 nacking",
|
|
3441
|
+
attrs: {
|
|
3442
|
+
runId: err.runId,
|
|
3443
|
+
flowId: err.flowId,
|
|
3444
|
+
pinnedHash: err.pinnedHash,
|
|
3445
|
+
currentHash: err.currentHash
|
|
3446
|
+
}
|
|
3447
|
+
});
|
|
3448
|
+
try {
|
|
3449
|
+
await this.deps.queue.nack(msg.receipt);
|
|
3450
|
+
} catch {
|
|
3451
|
+
}
|
|
3452
|
+
return;
|
|
3453
|
+
}
|
|
3084
3454
|
this.deps.emitLog({
|
|
3085
3455
|
level: "error",
|
|
3086
3456
|
msg: "worker.dispatch threw uncaught",
|
|
@@ -3151,7 +3521,12 @@ async function nagiImpl(config) {
|
|
|
3151
3521
|
const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
|
|
3152
3522
|
async function flowFor(runId) {
|
|
3153
3523
|
const runState = await config.store.loadRunState(runId);
|
|
3154
|
-
return registry.requireForRun(
|
|
3524
|
+
return registry.requireForRun(
|
|
3525
|
+
runState.flowId,
|
|
3526
|
+
runId,
|
|
3527
|
+
runState.flowHash,
|
|
3528
|
+
(id) => flowHashById.get(id)
|
|
3529
|
+
);
|
|
3155
3530
|
}
|
|
3156
3531
|
function lookupFlow(flowId) {
|
|
3157
3532
|
return registry.get(flowId);
|
|
@@ -3247,18 +3622,13 @@ async function nagiImpl(config) {
|
|
|
3247
3622
|
);
|
|
3248
3623
|
}
|
|
3249
3624
|
const validated = await validate(child.input, childInput);
|
|
3250
|
-
const childRunId =
|
|
3251
|
-
|
|
3625
|
+
const childRunId = await deriveChildRunId(parent);
|
|
3626
|
+
await startRunInternal({
|
|
3252
3627
|
flow: child,
|
|
3253
3628
|
validatedInput: validated,
|
|
3254
3629
|
runId: childRunId,
|
|
3255
3630
|
parent
|
|
3256
3631
|
});
|
|
3257
|
-
if (!started) {
|
|
3258
|
-
throw new NagiRuntimeError(
|
|
3259
|
-
`startChildRun: minted child runId collided with an existing run (${childRunId})`
|
|
3260
|
-
);
|
|
3261
|
-
}
|
|
3262
3632
|
return childRunId;
|
|
3263
3633
|
}
|
|
3264
3634
|
async function cancelRunRecursive(runId, args) {
|
|
@@ -3358,6 +3728,121 @@ async function nagiImpl(config) {
|
|
|
3358
3728
|
await startRunInternal({ flow: flow2, validatedInput: validated, runId });
|
|
3359
3729
|
return runId;
|
|
3360
3730
|
},
|
|
3731
|
+
async startStaged(flow2, input, opts) {
|
|
3732
|
+
return wf.startStagedById(flow2.id, input, opts);
|
|
3733
|
+
},
|
|
3734
|
+
async startStagedById(flowId, input, opts) {
|
|
3735
|
+
if (opts === void 0 || opts.tx === void 0) {
|
|
3736
|
+
throw validationError(
|
|
3737
|
+
"startStaged: opts.tx is required (the caller-supplied transaction the run row, flow.started fact, and initial enqueue commit on).",
|
|
3738
|
+
["tx"]
|
|
3739
|
+
);
|
|
3740
|
+
}
|
|
3741
|
+
const flow2 = registry.require(flowId);
|
|
3742
|
+
let runId;
|
|
3743
|
+
if (opts.runId !== void 0) {
|
|
3744
|
+
if (typeof opts.runId !== "string" || opts.runId.length === 0) {
|
|
3745
|
+
throw validationError("opts.runId must be a non-empty string", [
|
|
3746
|
+
"runId"
|
|
3747
|
+
]);
|
|
3748
|
+
}
|
|
3749
|
+
runId = opts.runId;
|
|
3750
|
+
} else {
|
|
3751
|
+
runId = mintRunId();
|
|
3752
|
+
}
|
|
3753
|
+
const validated = await validate(flow2.input, input);
|
|
3754
|
+
const startedAt = clock.now();
|
|
3755
|
+
const flowHash = flowHashById.get(flow2.id);
|
|
3756
|
+
const fact = Facts.flowStarted({
|
|
3757
|
+
runId,
|
|
3758
|
+
flowId: flow2.id,
|
|
3759
|
+
input: validated,
|
|
3760
|
+
at: startedAt,
|
|
3761
|
+
codeVersion,
|
|
3762
|
+
...compact({ flowHash })
|
|
3763
|
+
});
|
|
3764
|
+
let concurrencyArg;
|
|
3765
|
+
if (flow2.concurrency !== void 0) {
|
|
3766
|
+
const derived = flow2.concurrency.keyFn(validated);
|
|
3767
|
+
if (typeof derived !== "string" || derived.length === 0) {
|
|
3768
|
+
throw validationError(
|
|
3769
|
+
`flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
3770
|
+
["concurrency", "keyFn"]
|
|
3771
|
+
);
|
|
3772
|
+
}
|
|
3773
|
+
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
3774
|
+
}
|
|
3775
|
+
const { started, canceled } = await config.store.tryStartRunOnTx(
|
|
3776
|
+
opts.tx,
|
|
3777
|
+
runId,
|
|
3778
|
+
fact,
|
|
3779
|
+
concurrencyArg
|
|
3780
|
+
);
|
|
3781
|
+
if (started) {
|
|
3782
|
+
const seedState = foldRun(runId, [fact]);
|
|
3783
|
+
const transition = nextTransition(flow2, seedState);
|
|
3784
|
+
if (transition.kind === "dispatch") {
|
|
3785
|
+
const txQueue = bindQueueToTx(config.queue, opts.tx);
|
|
3786
|
+
for (const stepId of transition.runnable) {
|
|
3787
|
+
await txQueue.enqueue(runId, stepId);
|
|
3788
|
+
}
|
|
3789
|
+
}
|
|
3790
|
+
}
|
|
3791
|
+
let fired = false;
|
|
3792
|
+
const applyOnCommit = async () => {
|
|
3793
|
+
if (fired) return;
|
|
3794
|
+
fired = true;
|
|
3795
|
+
if (!started) return;
|
|
3796
|
+
for (const c of canceled) {
|
|
3797
|
+
const cancelError = new NagiCanceledError({
|
|
3798
|
+
runId: c.runId,
|
|
3799
|
+
canceledByRunId: runId,
|
|
3800
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
3801
|
+
});
|
|
3802
|
+
const serialized = {
|
|
3803
|
+
...serializeError(cancelError),
|
|
3804
|
+
cause: {
|
|
3805
|
+
canceledByRunId: runId,
|
|
3806
|
+
concurrencyKey: c.fact.concurrencyKey
|
|
3807
|
+
}
|
|
3808
|
+
};
|
|
3809
|
+
const errorEvent = {
|
|
3810
|
+
runId: c.runId,
|
|
3811
|
+
flowId: flow2.id,
|
|
3812
|
+
error: serialized,
|
|
3813
|
+
at: c.fact.at
|
|
3814
|
+
};
|
|
3815
|
+
await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
|
|
3816
|
+
await hooks.fireHook(
|
|
3817
|
+
config.hooks?.onFlowError,
|
|
3818
|
+
errorEvent,
|
|
3819
|
+
"onFlowError"
|
|
3820
|
+
);
|
|
3821
|
+
await dispatcher.propagateToParent(c.runId, {
|
|
3822
|
+
kind: "canceled",
|
|
3823
|
+
error: serialized
|
|
3824
|
+
});
|
|
3825
|
+
}
|
|
3826
|
+
const startEvent = {
|
|
3827
|
+
runId,
|
|
3828
|
+
flowId: flow2.id,
|
|
3829
|
+
input: validated,
|
|
3830
|
+
at: startedAt
|
|
3831
|
+
};
|
|
3832
|
+
await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
|
|
3833
|
+
await hooks.fireHook(
|
|
3834
|
+
config.hooks?.onFlowStart,
|
|
3835
|
+
startEvent,
|
|
3836
|
+
"onFlowStart"
|
|
3837
|
+
);
|
|
3838
|
+
};
|
|
3839
|
+
return {
|
|
3840
|
+
runId,
|
|
3841
|
+
started,
|
|
3842
|
+
canceled: canceled.map((c) => c.runId),
|
|
3843
|
+
applyOnCommit
|
|
3844
|
+
};
|
|
3845
|
+
},
|
|
3361
3846
|
signal: signals.signal,
|
|
3362
3847
|
async cancel(runId, opts) {
|
|
3363
3848
|
await cancelRunRecursive(runId, {
|
|
@@ -3384,6 +3869,9 @@ async function nagiImpl(config) {
|
|
|
3384
3869
|
return makeWorker({ ...dispatchDeps, clock }, workerConfig);
|
|
3385
3870
|
},
|
|
3386
3871
|
replay: replayer.replay,
|
|
3872
|
+
async describe(runId) {
|
|
3873
|
+
return config.store.describe(runId);
|
|
3874
|
+
},
|
|
3387
3875
|
async queryRuns(opts = {}) {
|
|
3388
3876
|
if (opts.latest === true) {
|
|
3389
3877
|
if (opts.limit !== void 0 || opts.cursor !== void 0) {
|
|
@@ -3454,6 +3942,7 @@ async function nagiRun(config) {
|
|
|
3454
3942
|
const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
|
|
3455
3943
|
const worker = wf.worker({ ...config.worker, signal });
|
|
3456
3944
|
const emitLog = makeEmit(config.onLog);
|
|
3945
|
+
const clock = config.clock ?? new InMemoryClock();
|
|
3457
3946
|
const loop = worker.run();
|
|
3458
3947
|
loop.catch((err) => {
|
|
3459
3948
|
if (signal.aborted) return;
|
|
@@ -3463,6 +3952,31 @@ async function nagiRun(config) {
|
|
|
3463
3952
|
attrs: { error: String(err) }
|
|
3464
3953
|
});
|
|
3465
3954
|
});
|
|
3955
|
+
const reaperIntervalMs = config.reaperIntervalMs ?? DEFAULT_REAPER_INTERVAL_MS;
|
|
3956
|
+
const reaper = reaperIntervalMs > 0 ? (async () => {
|
|
3957
|
+
while (!signal.aborted) {
|
|
3958
|
+
try {
|
|
3959
|
+
await clock.sleep(reaperIntervalMs, signal);
|
|
3960
|
+
} catch {
|
|
3961
|
+
return;
|
|
3962
|
+
}
|
|
3963
|
+
if (signal.aborted) return;
|
|
3964
|
+
try {
|
|
3965
|
+
await config.store.sweepLeases({
|
|
3966
|
+
now: clock.now(),
|
|
3967
|
+
queue: config.queue
|
|
3968
|
+
});
|
|
3969
|
+
} catch (err) {
|
|
3970
|
+
emitLog({
|
|
3971
|
+
level: "warn",
|
|
3972
|
+
msg: "nagi.run: lease reaper sweep failed",
|
|
3973
|
+
attrs: { error: String(err) }
|
|
3974
|
+
});
|
|
3975
|
+
}
|
|
3976
|
+
}
|
|
3977
|
+
})() : Promise.resolve();
|
|
3978
|
+
reaper.catch(() => {
|
|
3979
|
+
});
|
|
3466
3980
|
let stopping;
|
|
3467
3981
|
const stop = () => {
|
|
3468
3982
|
stopping ??= (async () => {
|
|
@@ -3471,6 +3985,10 @@ async function nagiRun(config) {
|
|
|
3471
3985
|
await loop;
|
|
3472
3986
|
} catch {
|
|
3473
3987
|
}
|
|
3988
|
+
try {
|
|
3989
|
+
await reaper;
|
|
3990
|
+
} catch {
|
|
3991
|
+
}
|
|
3474
3992
|
})();
|
|
3475
3993
|
return stopping;
|
|
3476
3994
|
};
|
|
@@ -3487,7 +4005,12 @@ function asStreamTransport(store) {
|
|
|
3487
4005
|
const s = store;
|
|
3488
4006
|
return typeof s.subscribeStream === "function" && typeof s.publishChunk === "function" ? s : void 0;
|
|
3489
4007
|
}
|
|
4008
|
+
function bindQueueToTx(queue, tx) {
|
|
4009
|
+
const q = queue;
|
|
4010
|
+
if (typeof q.withTx === "function") return q.withTx(tx);
|
|
4011
|
+
return queue;
|
|
4012
|
+
}
|
|
3490
4013
|
|
|
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 };
|
|
4014
|
+
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
4015
|
//# sourceMappingURL=index.js.map
|
|
3493
4016
|
//# sourceMappingURL=index.js.map
|