diff --git a/packages/core/src/atomicFile.ts b/packages/core/src/atomicFile.ts index c17dc7c295..71092cfc4f 100644 --- a/packages/core/src/atomicFile.ts +++ b/packages/core/src/atomicFile.ts @@ -1,8 +1,9 @@ import * as fs from "node:fs"; +import * as fsp from "node:fs/promises"; import { createHash, randomBytes } from "node:crypto"; import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path"; import { realpath } from "./safePath.js"; -import { renameWithRetry } from "./renameWithRetry.js"; +import { renameWithRetry, renameWithRetryAsync } from "./renameWithRetry.js"; import { terminalText } from "./terminalText.js"; type SiblingFileSystem = Pick; @@ -68,6 +69,47 @@ export function replaceFileAtomically( ); } +/** Async twin of {@link replaceFileAtomically}: a disk that never answers holds a pool thread, never the caller's. */ +export async function replaceFileAtomicallyAsync( + filePath: string, + content: string | Uint8Array, + mode?: number, +): Promise { + traceWrite(filePath, content); + try { + await fsp.access(filePath, fs.constants.W_OK); + } catch (error) { + if (errorCode(error) !== "ENOENT") throw error; + } + const tempPath = await writeTempSiblingAsync(filePath, content, mode); + try { + if (mode !== undefined) await fsp.chmod(tempPath, mode); + await renameWithRetryAsync(tempPath, filePath); + } catch (error) { + await fsp.unlink(tempPath).catch(() => undefined); + throw error; + } +} + +async function writeTempSiblingAsync( + filePath: string, + content: string | Uint8Array, + mode: number | undefined, +): Promise { + for (let attempt = 1; ; attempt++) { + const tempPath = atomicTempPath(filePath); + try { + await fsp.writeFile(tempPath, content, { encoding: "utf-8", mode, flag: "wx" }); + return tempPath; + } catch (error) { + const taken = errorCode(error) === "EEXIST"; + if (taken && attempt < TEMP_NAME_TRIES) continue; + if (!taken) await fsp.unlink(tempPath).catch(() => undefined); + throw error; + } + } +} + export function refuseReadOnly(filePath: string): void { try { fs.accessSync(filePath, fs.constants.W_OK); diff --git a/packages/studio-server/src/history/videoState.ts b/packages/studio-server/src/history/videoState.ts index 3cbf943482..700bab8254 100644 --- a/packages/studio-server/src/history/videoState.ts +++ b/packages/studio-server/src/history/videoState.ts @@ -1,7 +1,8 @@ import { createHash, randomUUID } from "node:crypto"; -import { createReadStream, existsSync, readFileSync, renameSync, statSync } from "node:fs"; +import { createReadStream } from "node:fs"; +import { readFile, rename, stat } from "node:fs/promises"; import { isAbsolute, join, resolve } from "node:path"; -import { replaceFileAtomically } from "@hyperframes/core/atomic-file"; +import { replaceFileAtomicallyAsync } from "@hyperframes/core/atomic-file"; import { pinProjectRecord } from "../helpers/safePath.js"; import { listProjectFilesAsync } from "../helpers/projectSignature.js"; import { readId } from "./historyId.js"; @@ -102,31 +103,51 @@ const emptyState = (): VideoState => ({ snapshots: collection(), }); -function readState(dir: string): VideoState { - if (!existsSync(statePath(dir))) return emptyState(); - const state: VideoState = JSON.parse(readFileSync(statePath(dir), "utf8")); +async function readState(dir: string): Promise { + let text: string; + try { + text = await readFile(statePath(dir), "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return emptyState(); + throw error; + } + const state: VideoState = JSON.parse(text); if (state.version !== 1 || !state.checks || !state.snapshots || !state.revisions || !state.files) throw new Error("Unsupported video-state schema."); return state; } +const STATE_WAIT_MS = 5000; + +async function rewriteState(dir: string, update: (state: VideoState) => void): Promise { + let state: VideoState; + try { + state = await readState(dir); + } catch (error) { + if (!(error instanceof SyntaxError)) throw error; + await rename(statePath(dir), `${statePath(dir)}.invalid-${randomUUID()}`); + state = emptyState(); + } + update(state); + await replaceFileAtomicallyAsync(statePath(dir), JSON.stringify(state, null, 2) + "\n", 0o644); +} + async function updateState(dir: string, update: (state: VideoState) => void): Promise { const lock = pinProjectRecord(dir, ".hyperframes/video-state-lock"); if (!lock) throw new Error("Video state lock must stay inside the project."); - const release = await takeHistoryOwnership(lock, 5000); + const release = await takeHistoryOwnership(lock, STATE_WAIT_MS); + const writeHoldingTheLock = rewriteState(dir, update).finally(release); + let timer: ReturnType | undefined; + const gaveUp = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`The video state did not answer within ${STATE_WAIT_MS} ms.`)), + STATE_WAIT_MS, + ); + }); try { - let state: VideoState; - try { - state = readState(dir); - } catch (error) { - if (!(error instanceof SyntaxError)) throw error; - renameSync(statePath(dir), `${statePath(dir)}.invalid-${randomUUID()}`); - state = emptyState(); - } - update(state); - replaceFileAtomically(statePath(dir), JSON.stringify(state, null, 2) + "\n", 0o644); + await Promise.race([writeHoldingTheLock, gaveUp]); } finally { - release(); + clearTimeout(timer); } } @@ -216,7 +237,7 @@ export interface ArtifactCapture { export async function beginArtifactCapture(projectDir: string): Promise { const files = await fileHashes(projectDir); - const state = readState(projectDir); + const state = await readState(projectDir); const matches = state.historyId !== null && readId(projectDir) === state.historyId && @@ -249,7 +270,12 @@ export async function recordArtifacts( for (const artifact of artifactsToRecord) { const path = artifact.kind === "check" ? artifact.report : artifact.image; if (!path || !isAbsolute(path)) throw new Error("Artifact needs an absolute output path."); - hashes.set(artifact.id, createHash("sha256").update(readFileSync(path)).digest("hex")); + hashes.set( + artifact.id, + createHash("sha256") + .update(await readFile(path)) + .digest("hex"), + ); } const after = await beginArtifactCapture(projectDir); const unchanged = after.fingerprint === capture.fingerprint; @@ -363,7 +389,7 @@ export async function recordRenderSuccess( status: RenderRecord["status"] = "completed", capture?: ArtifactCapture, ): Promise { - const outputFile = statSync(output); + const outputFile = await stat(output); if ( (!outputFile.isFile() && !outputFile.isDirectory()) || (outputFile.isFile() && outputFile.size === 0) diff --git a/packages/studio-server/src/history/videoStateSilentDrive.test.ts b/packages/studio-server/src/history/videoStateSilentDrive.test.ts new file mode 100644 index 0000000000..d2c51b3746 --- /dev/null +++ b/packages/studio-server/src/history/videoStateSilentDrive.test.ts @@ -0,0 +1,60 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { open } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { writeHistoryState } from "./videoState.js"; + +const collection = () => ({ latest: null, revisions: {}, unversioned: [] }); +const stored = { + version: 1, + historyId: null, + currentRevision: null, + pendingChanges: true, + files: {}, + revisions: {}, + checks: collection(), + snapshots: collection(), +}; + +let projectDir = ""; +afterEach(() => { + vi.useRealTimers(); + rmSync(projectDir, { recursive: true, force: true }); +}); + +const write = (historyId: string) => + writeHistoryState(projectDir, historyId, join(projectDir, "h"), [], new Map(), new Map()); + +// fails without the fix: the state file was read and written with sync calls on the caller's thread, so a project +// whose drive stopped answering froze the app that opened it until the drive answered. +it.skipIf(process.platform === "win32")( + "a state file whose drive never answers leaves the caller's thread free and gives up at its deadline", + async () => { + projectDir = mkdtempSync(join(tmpdir(), "hf-video-state-silent-")); + mkdirSync(join(projectDir, ".hyperframes")); + const state = join(projectDir, ".hyperframes/video-state.json"); + execFileSync("mkfifo", [state]); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + + let settled = false; + const first = write("first").finally(() => (settled = true)); + const outcome = first.then( + () => "wrote", + (error: Error) => error.message, + ); + for (let turn = 0; turn < 5; turn++) await new Promise((next) => setImmediate(next)); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(5000); + expect(await outcome).toMatch(/did not answer within 5000 ms/); + vi.useRealTimers(); + + // The drive answers: the given-up write finishes and frees the lock, so the next write takes it (one still held + // would refuse it busy after the lock's 5 s wait). + const drive = await open(state, "w"); + await drive.writeFile(JSON.stringify(stored)); + await drive.close(); + await expect(write("second")).resolves.toBeUndefined(); + }, +);