diff --git a/apps/server/src/build/git.ts b/apps/server/src/build/git.ts index 5616df8..b15e844 100644 --- a/apps/server/src/build/git.ts +++ b/apps/server/src/build/git.ts @@ -7,10 +7,15 @@ import { killGroupAfter } from "../util/processTimeout.js"; // A clone that never finishes (e.g. ssh waiting on a prompt) would otherwise hang forever. const GIT_TIMEOUT_MS = 5 * 60 * 1000; -export function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> { +export function run( + cmd: string, + args: string[], + cwd?: string, + timeoutMs = GIT_TIMEOUT_MS, +): Promise<{ code: number; output: string }> { return new Promise((resolve, reject) => { const child = spawn(cmd, args, { cwd, detached: true }); - killGroupAfter(child, GIT_TIMEOUT_MS); + killGroupAfter(child, timeoutMs); let output = ""; child.stdout.on("data", (d) => (output += d.toString())); child.stderr.on("data", (d) => (output += d.toString())); diff --git a/apps/server/src/system/remoteCheck.test.ts b/apps/server/src/system/remoteCheck.test.ts index fbd7815..77823b6 100644 --- a/apps/server/src/system/remoteCheck.test.ts +++ b/apps/server/src/system/remoteCheck.test.ts @@ -16,11 +16,11 @@ function git(cwd: string, ...args: string[]) { }).trim(); } -async function load() { +async function load(ref = "main") { vi.resetModules(); vi.stubEnv("DATA_DIR", path.join(tmp, "data")); vi.stubEnv("SELF_UPDATE_REPO_URL", origin); - vi.stubEnv("SELF_UPDATE_REF", "main"); + vi.stubEnv("SELF_UPDATE_REF", ref); return import("./remoteCheck.js"); } @@ -41,6 +41,23 @@ afterAll(() => { }); describe("checkRemote", () => { + it("resolves an annotated tag to its commit", async () => { + git(origin, "tag", "-a", "v1", "-m", "release", shas[2]!); + const { checkRemote } = await load("v1"); + const status = await checkRemote(shas[0], true); + expect(status.remoteSha).toBe(shas[2]); + expect(status.behind).toBe(2); + }); + + it("runs a fresh check after a forced refresh requested mid-flight", async () => { + const { checkRemote } = await load(); + const first = checkRemote(shas[0]); + const forced = checkRemote(shas[0], true); + const [a, b] = await Promise.all([first, forced]); + expect(b.checkedAt >= a.checkedAt).toBe(true); + expect(b).not.toBe(a); + }); + it("counts the commits the installed sha is missing", async () => { const { checkRemote } = await load(); const status = await checkRemote(shas[0], true); diff --git a/apps/server/src/system/remoteCheck.ts b/apps/server/src/system/remoteCheck.ts index 5562e0d..3cce58d 100644 --- a/apps/server/src/system/remoteCheck.ts +++ b/apps/server/src/system/remoteCheck.ts @@ -10,6 +10,8 @@ const CHECK_DIR = "_manager-check"; const OK_TTL_MS = 10 * 60 * 1000; const ERROR_TTL_MS = 60 * 1000; const MAX_LISTED = 20; +// The panel waits on this, so it gets far less than the 5 min installs allow for a clone. +const GIT_CHECK_TIMEOUT_MS = 60 * 1000; export interface RemoteStatus { checkedAt: string; @@ -22,9 +24,10 @@ export interface RemoteStatus { let cached: { status: RemoteStatus; expires: number; forSha: string | undefined } | null = null; let inFlight: Promise | null = null; +let queuedForce: Promise | null = null; async function git(cwd: string, args: string[]) { - return run("git", args, cwd).catch((err: Error) => ({ code: 1, output: err.message })); + return run("git", args, cwd, GIT_CHECK_TIMEOUT_MS).catch((err: Error) => ({ code: 1, output: err.message })); } async function compute(installedSha: string | undefined): Promise { @@ -40,12 +43,14 @@ async function compute(installedSha: string | undefined): Promise } // Blobless fetch where the server supports it; plain fetch otherwise. - const fetchArgs = ["fetch", "--quiet", "--no-tags", url, config.selfUpdateRef]; - let fetched = await git(dir, [fetchArgs[0]!, "--filter=blob:none", ...fetchArgs.slice(1)]); - if (fetched.code !== 0) fetched = await git(dir, fetchArgs); + const fetchTail = ["--quiet", "--no-tags", "--", url, config.selfUpdateRef]; + let fetched = await git(dir, ["fetch", "--filter=blob:none", ...fetchTail]); + // Only a server that doesn't do partial clones warrants the retry; an unreachable one would + // just make the panel wait twice as long. + if (fetched.code !== 0 && /filter/i.test(fetched.output)) fetched = await git(dir, ["fetch", ...fetchTail]); if (fetched.code !== 0) return { ...base, error: `git fetch failed: ${fetched.output.trim().slice(-300)}` }; - const head = await git(dir, ["rev-parse", "FETCH_HEAD"]); + const head = await git(dir, ["rev-parse", "--verify", "FETCH_HEAD^{commit}"]); const remoteSha = head.output.trim(); if (head.code !== 0 || !remoteSha) return { ...base, error: "could not read the fetched head" }; if (!installedSha) return { ...base, remoteSha }; @@ -58,22 +63,15 @@ async function compute(installedSha: string | undefined): Promise const range = `${installedSha}..${remoteSha}`; const count = await git(dir, ["rev-list", "--count", range]); - const log = await git(dir, ["log", `-n${MAX_LISTED}`, "--format=%h%x09%s", range]); const behind = Number.parseInt(count.output.trim(), 10); - return { - ...base, - remoteSha, - behind: Number.isNaN(behind) ? null : behind, - commits: parseCommitLog(log.output), - }; + if (count.code !== 0 || Number.isNaN(behind)) { + return { ...base, remoteSha, error: `git rev-list failed: ${count.output.trim().slice(-200)}` }; + } + const log = await git(dir, ["log", `-n${MAX_LISTED}`, "--format=%h%x09%s", range]); + return { ...base, remoteSha, behind, commits: log.code === 0 ? parseCommitLog(log.output) : [] }; } -/** Cached for a few minutes; concurrent callers share one fetch. `force` skips the cache. */ -export function checkRemote(installedSha: string | undefined, force = false): Promise { - if (!force && cached && cached.expires > Date.now() && cached.forSha === installedSha) { - return Promise.resolve(cached.status); - } - if (inFlight) return inFlight; +function start(installedSha: string | undefined): Promise { inFlight = compute(installedSha) .catch((err: Error): RemoteStatus => ({ checkedAt: new Date().toISOString(), @@ -92,6 +90,24 @@ export function checkRemote(installedSha: string | undefined, force = false): Pr return inFlight; } +/** + * Cached for a few minutes; concurrent callers share one fetch. `force` skips the cache, and if a + * fetch is already running (it may have read the refs before a push) waits for it and runs a + * fresh one after it — at most one is ever queued. + */ +export function checkRemote(installedSha: string | undefined, force = false): Promise { + if (!force && cached && cached.expires > Date.now() && cached.forSha === installedSha) { + return Promise.resolve(cached.status); + } + if (!inFlight) return start(installedSha); + if (!force) return inFlight; + queuedForce ??= inFlight.then(() => { + queuedForce = null; + return start(installedSha); + }); + return queuedForce; +} + /** Last known result without triggering a fetch (null if none yet). */ export function cachedRemoteStatus(): RemoteStatus | null { return cached?.status ?? null; diff --git a/apps/web/src/components/ManagerCard.tsx b/apps/web/src/components/ManagerCard.tsx index 4d9b3dc..0b88ec0 100644 --- a/apps/web/src/components/ManagerCard.tsx +++ b/apps/web/src/components/ManagerCard.tsx @@ -19,6 +19,7 @@ export function ManagerCard() { const [startedAt, setStartedAt] = useState(null); const [gaveUp, setGaveUp] = useState(false); const [checking, setChecking] = useState(false); + const [remoteGaveUp, setRemoteGaveUp] = useState(false); async function refresh() { try { @@ -59,21 +60,24 @@ export function ManagerCard() { }, [requested, info, unreachable, startedAt]); const repoConfigured = info !== null && info.unavailableReason !== "SELF_UPDATE_REPO_URL is not set"; - const waitingForRemote = repoConfigured && info !== null && info.remote === null && info.phase === "idle"; + const waitingForRemote = repoConfigured && info !== null && info.remote === null && info.phase === "idle" && !remoteGaveUp; // The first remote check runs in the background on the server; poll briefly until it lands. useEffect(() => { if (!waitingForRemote) return; let tries = 0; const timer = setInterval(() => { - if (++tries > 10) clearInterval(timer); - else refresh(); + if (++tries > 10) { + clearInterval(timer); + setRemoteGaveUp(true); + } else refresh(); }, 3000); return () => clearInterval(timer); }, [waitingForRemote]); async function checkNow() { setChecking(true); + setRemoteGaveUp(false); setError(null); try { setInfo(await api.checkManager()); @@ -157,7 +161,9 @@ export function ManagerCard() { function RemoteLine({ info, checking }: { info: SystemInfo; checking: boolean }) { const remote = info.remote; - if (!remote) return

{checking ? "Checking the remote…" : ""}

; + if (!remote) { + return

{checking ? "Checking the remote…" : "Not checked yet; use Check for updates."}

; + } if (remote.error) return

Could not check the remote: {remote.error}

; const head = remote.remoteSha?.slice(0, 7);