UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

397 lines (396 loc) • 12.8 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { C as runWithGatewayDetachedWorkContinuation } from "./gateway-work-admission-79pid1hQ.mjs"; import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs"; import { n as startDiffReadTiming, t as addDiffReadDurations } from "./diff-read-timing-DfUiUh2O.mjs"; import { t as runGitWorkerOperation } from "./git-worker-FuYEKt2U.mjs"; import { performance } from "node:perf_hooks"; //#region src/infra/git-read-cache.ts const MAX_CACHED_CHECKOUTS = 1e3; const log = createSubsystemLogger("git/read"); function gitEnvironment() { return Object.keys(process.env).filter((e) => /^(GIT_|HOME$|XDG_CONFIG_HOME$|PATH$|SUDO_UID$)/i.test(e)).toSorted((e, t) => e.localeCompare(t)).map((e) => [e, process.env[e]]); } function diffRevisionMissReason(e, t) { try { const n = JSON.parse(e ?? "null"); const r = JSON.parse(t ?? "null"); if (n && r) { for (const [e, t] of [ ["head", "revision-changed-head"], ["index", "revision-changed-index"], ["untrackedSet", "revision-changed-untracked-set"], ["worktreeMtime", "revision-changed-worktree-mtime"] ]) if (n[e] !== r[e]) return t; } } catch {} return "revision-changed-metadata"; } function createReadCache(e, t, n, r, i = () => true, a = MAX_CACHED_CHECKOUTS, o) { const s = typeof t === "number" ? t : t.milliseconds; const c = typeof t !== "number" && t.joinPending; const l = /* @__PURE__ */ new Map(); const u = /* @__PURE__ */ new Map(); const d = /* @__PURE__ */ new Set(); const f = /* @__PURE__ */ new Map(); let p = Promise.resolve(); let m = false; let h = 0; const releasePoll = (e, t) => { if (l.get(e) !== t || !t.poll) return; delete t.poll; h--; if (!t.entry) l.delete(e); }; const remove = (e, t) => { const n = l.get(e); if (n?.entry === t) { delete n.entry; if (!n.poll) l.delete(e); } }; const read = async (h, g = {}, _, v) => { try { var y = _usingCtx(); g.signal?.throwIfAborted(); const b = y.u(o ? startDiffReadTiming("checkout.diff") : void 0); const x = b ?? g.diffTiming; const S = x ? performance.now() : 0; const C = _ ?? gitEnvironment(); const w = v ?? JSON.stringify([h, C]); let T = l.get(w)?.entry; const E = !g.refresh && (T?.retryAt ?? 0) > monotonicNow(); let D = E ? T.revision : void 0; let O; if (n && !E) { const e = n(h, T?.value); const t = JSON.stringify([e, C]); let r = f.get(t); if (!r) { const n = new AbortController(); const i = x ? { durations: {} } : void 0; r = { controller: n, promise: runGitWorkerOperation({ type: "checkout.revision", input: e }, { signal: n.signal, diffTiming: i }).finally(() => { f.delete(t); }), timing: i }; f.set(t, r); } O = await racePromiseWithAbortSignal(r.promise, g.signal, (e) => toErrorObject(e.reason, "Git read aborted")); D = O?.key ?? null; if (x && r.timing) { addDiffReadDurations(x, r.timing); x.revisionUnavailableReason = r.timing.revisionUnavailableReason; } } if (x) x.durations["cache-validate"] = performance.now() - S; const k = typeof t !== "number" && typeof D === "string" ? Number.POSITIVE_INFINITY : s; g.signal?.throwIfAborted(); if (m) throw new Error("Git reads are unavailable while the Gateway is restarting"); T = l.get(w)?.entry; const A = T; const j = u.delete(w); let M = !T?.pending; if (g.refresh && (D === null || T?.retryAt !== void 0) || !T || T.revision !== D || T.expiresAt <= monotonicNow() && (!(r || c) || !T.pending)) { if (r && d.size >= MAX_CACHED_CHECKOUTS) return T?.value ?? r.empty(); M = false; const t = x ? { durations: {} } : void 0; const n = p; const a = new AbortController(); const o = { revision: D, expiresAt: k === 0 ? Number.POSITIVE_INFINITY : monotonicNow() + (D === null ? Math.min(k, 75e3) : k), controller: a, pending: true, timing: t, value: T?.value, promise: Promise.resolve().then(() => r ? runWithGatewayDetachedWorkContinuation(async () => { await n; a.signal.throwIfAborted(); return e(h, a.signal, t, O); }, "runtime:project-discovery") : e(h, a.signal, t, O)) }; d.add(o); o.promise = o.promise.then((e) => { o.pending = false; d.delete(o); a.signal.throwIfAborted(); o.value = e; if (r) o.expiresAt = monotonicNow() + s; const t = i(e); if (typeof t === "number") o.retryAt = o.expiresAt = monotonicNow() + t; else if (k === 0 || !t) remove(w, o); else if (c && D === null) o.retryAt = o.expiresAt; return e; }, (e) => { o.pending = false; d.delete(o); if (r) o.expiresAt = monotonicNow() + s; else { o.expiresAt = 0; remove(w, o); } throw e; }); if (r) p = o.promise.catch(() => { if (!a.signal.aborted) log.warn("Repository discovery refresh failed; retaining the previous project snapshot"); }); T = o; } const N = l.get(w) ?? {}; N.entry = T; l.delete(w); l.set(w, N); for (const [e, t] of l) { if (l.size <= a) break; if (t.poll) { if (t.poll.pending || t.poll.expiresAt > monotonicNow()) continue; releasePoll(e, t); } l.delete(e); u.set(e, true); } pruneMapToMaxSize(u, a); const P = r ? T.value ?? r.empty() : await racePromiseWithAbortSignal(T.promise, g.signal, (e) => toErrorObject(e.reason, "Git read aborted")); if (x) { x.outcome = M ? "cache-hit" : "cache-miss"; x.missReason = M ? void 0 : D === null ? x.revisionUnavailableReason ?? "no-revision" : !A ? j ? "evicted" : "cold" : A.revision !== D ? diffRevisionMissReason(A.revision, D) : "pending"; if (!M && T.timing) addDiffReadDurations(x, T.timing); } if (b && g.diffTiming) { addDiffReadDurations(g.diffTiming, b); g.diffTiming.outcome = b.outcome; g.diffTiming.missReason = b.missReason; } return P; } catch (e) { y.e = e; } finally { y.d(); } }; return { async read(e, t = {}) { t.signal?.throwIfAborted(); if (m) throw new Error("Git reads are unavailable while the Gateway is restarting"); if (!o || !t.poll) return read(e, t); const computing = () => { if (t.diffTiming) { t.diffTiming.outcome = "cache-miss"; t.diffTiming.missReason = "pending"; } return o.empty(); }; const n = gitEnvironment(); const r = JSON.stringify([e, n]); const i = l.get(r) ?? {}; if (i.poll && !i.poll.pending && i.poll.expiresAt <= monotonicNow()) releasePoll(r, i); let s = i.poll; if (!s && i.entry?.value) return read(e, t, n, r); if (!s) { if (h >= a) { for (const [e, t] of l) if (t.poll && !t.poll.pending && t.poll.expiresAt <= monotonicNow()) releasePoll(e, t); } if (h >= a) return computing(); const n = new AbortController(); const o = runWithGatewayDetachedWorkContinuation(() => read(e, { ...t, signal: n.signal, diffTiming: void 0 }), "runtime:checkout-diff"); s = { promise: o, controller: n, pending: true, expiresAt: Number.POSITIVE_INFINITY }; const c = s; const settled = () => { c.pending = false; c.expiresAt = monotonicNow() + 1e3; }; o.then(settled, settled); i.poll = s; h++; l.set(r, i); } let c = false; let u; try { const e = await racePromiseWithAbortSignal(s.pending ? Promise.race([s.promise, new Promise((e) => { u = setTimeout(() => { c = true; e(computing()); }, 2e3); })]) : s.promise, t.signal, (e) => toErrorObject(e.reason, "Git read aborted")); if (!c && t.diffTiming) { t.diffTiming.outcome = "cache-hit"; t.diffTiming.missReason = void 0; } return e; } finally { clearTimeout(u); } }, async close() { m = true; for (const { controller: e } of f.values()) e.abort(); const e = [...d]; for (const t of e) { t.expiresAt = 0; t.controller.abort(); } const t = Array.from(l.values()).flatMap((e) => e.poll ? [e.poll] : []); for (const e of t) e.controller.abort(); l.clear(); h = 0; u.clear(); await Promise.allSettled([ ...Array.from(f.values(), (e) => e.promise), ...e.map((e) => e.promise), ...t.map((e) => e.promise) ]); } }; } function createDiffReadCache(e, t = MAX_CACHED_CHECKOUTS) { const revisionInput = (e, t) => ({ root: e.cwd, scope: "diff", summaryOnly: e.summaryOnly === true, paths: t?.files.flatMap((e) => e.oldPath ? [e.path, e.oldPath] : [e.path]).toSorted() }); return createReadCache((e, t, n, r) => runGitWorkerOperation({ type: "checkout.diff", input: { ...e, ...r?.cleanWorktree ? { cleanWorktree: r.cleanWorktree } : {} } }, { signal: t, diffTiming: n }), e, revisionInput, void 0, (e) => e.unavailableReason === "not_git" ? 1e3 : !e.unavailableReason, t, { empty: () => ({ files: [], additions: 0, deletions: 0, computing: true }) }); } function createReadCaches() { const e = createReadCache((e, t) => runGitWorkerOperation({ type: "pull-request.branch-comparison", input: e }, { signal: t }), Number.POSITIVE_INFINITY, ({ root: e, branch: t, defaultBranch: n }) => ({ root: e, branch: t, defaultBranch: n, scope: "refs" }), void 0, (e) => e.complete); return { comparisons: e, identities: createReadCache((e, t) => runGitWorkerOperation({ type: "repository.identities", input: e }, { signal: t }), 6e4, void 0, { empty: () => [] }), context: createReadCache((e, t) => runGitWorkerOperation({ type: "checkout.context", input: e }, { signal: t }), Number.POSITIVE_INFINITY, ({ root: e }) => ({ root: e, scope: "context" })), branchFacts: createReadCache(async (t, n) => { try { const { refreshIndex: r, ...i } = t; const a = await e.read(i, { signal: n, refresh: true }); return await runGitWorkerOperation({ type: "pull-request.branch-facts", input: { ...t, comparison: a } }, { signal: n }); } catch { n.throwIfAborted(); log.warn("PR comparison unavailable; fetch repository history and retry. Dependent comparisons skipped."); return { creatable: false, stats: null }; } }, 3e5, ({ root: e, branch: t, defaultBranch: n }) => ({ root: e, branch: t, defaultBranch: n, scope: "worktree" })), diff: createDiffReadCache({ milliseconds: 0 }, 32), diffSummary: createDiffReadCache({ milliseconds: 1e4, joinPending: true }), branches: createReadCache((e, t) => runGitWorkerOperation({ type: "repository.branches", input: e }, { signal: t }), 0), baseline: createReadCache((e, t) => runGitWorkerOperation({ type: "checkout.baseline", input: e }, { signal: t }), 0) }; } function runtime() { return resolveGlobalSingleton(Symbol.for("openclaw.gitReadCache"), () => ({}), (e) => { e.closing ??= Promise.resolve().then(async () => { const t = e.caches; e.caches = void 0; if (t) await Promise.all(Object.values(t).map((e) => e.close())); }).finally(() => { e.closing = void 0; }); return e.closing; }); } function runGitReadOperation(e, t) { const n = runtime(); if (n.closing) return Promise.reject(/* @__PURE__ */ new Error("Git reads are unavailable while the Gateway is restarting")); const r = n.caches ??= createReadCaches(); const { context: i, branchFacts: a, branches: o, baseline: s, identities: c } = r; switch (e.type) { case "repository.identities": return c.read(e.input, t); case "checkout.revision": return runGitWorkerOperation(e, t); case "checkout.context": return i.read(e.input, t); case "pull-request.branch-facts": return a.read(e.input, t); case "checkout.diff": return readDiff(e.input.summaryOnly ? r.diffSummary : r.diff, e.input, t); case "repository.branches": return o.read(e.input, t); case "checkout.baseline": return s.read(e.input, t); } throw new Error("Unsupported Git read operation"); } async function readDiff(e, t, n) { const r = await e.read(t, n); return { ...r, files: r.files.map((e) => ({ ...e })), ...r.commits ? { commits: r.commits.map((e) => ({ ...e })) } : {}, ...r.mergeBase ? { mergeBase: { ...r.mergeBase } } : {} }; } //#endregion export { runGitReadOperation as t };