diff --git a/packages/studio-server/src/helpers/ownedFolders.test.ts b/packages/studio-server/src/helpers/ownedFolders.test.ts index c77afc7de3..36dc95bfd5 100644 --- a/packages/studio-server/src/helpers/ownedFolders.test.ts +++ b/packages/studio-server/src/helpers/ownedFolders.test.ts @@ -90,12 +90,12 @@ describe.skipIf(process.platform === "win32")("the tool's own folders inside a p expect(listing(outside)).toEqual(["notes.txt"]); }); - it("keep a new history id from creating the target of a dangling link", () => { + it("keep a new history id from creating the target of a dangling link", async () => { const { project, outside } = projectWithOutsideFolder(); mkdirSync(join(project, ".hyperframes")); symlinkSync(join(outside, "planted"), join(project, ".hyperframes", "history-id")); - const id = projectHistoryId(project, tempDir()); + const id = await projectHistoryId(project, tempDir()); expect(listing(outside)).toEqual(["notes.txt"]); expect(readFileSync(join(project, ".hyperframes", "history-id"), "utf-8")).toBe(`${id}\n`); diff --git a/packages/studio-server/src/history/historyId.ts b/packages/studio-server/src/history/historyId.ts index 84c8cbb2af..6f8631e850 100644 --- a/packages/studio-server/src/history/historyId.ts +++ b/packages/studio-server/src/history/historyId.ts @@ -1,5 +1,6 @@ import { randomUUID } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, statSync, utimesSync } from "node:fs"; +import { readFile, stat } from "node:fs/promises"; import { basename, join, resolve } from "node:path"; import { replaceFileAtomically } from "@hyperframes/core/atomic-file"; import { mkdirOwnedWithinProject } from "../helpers/safePath.js"; @@ -19,6 +20,25 @@ export function readId(projectDir: string): string | null { } } +export async function readIdOffThread(projectDir: string): Promise { + try { + const id = (await readFile(join(projectDir, ID_PATH), "utf-8")).trim(); + return ID_SHAPE.test(id) ? id : null; + } catch { + return null; + } +} + +export async function statOffThread(path: string) { + try { + return await stat(path); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === "ENOENT" || code === "ENOTDIR") return undefined; + throw error; + } +} + export type FolderIdentity = { ino: number; birthtimeMs: number }; export const sameFolder = (a: FolderIdentity, b: FolderIdentity) => @@ -57,11 +77,11 @@ function isCopyOf0878Folder(recordedDir: string, id: string, folder: FolderIdent * The project's history id, kept in the project so a rename or move keeps its history; only the folder its history * was recorded for keeps it (isRecordedFolder). An id file that cannot be read is refused, never replaced. */ -export function projectHistoryId(projectDir: string, historyRoot: string): string { +export async function projectHistoryId(projectDir: string, historyRoot: string): Promise { const dir = resolve(projectDir); - const folder = statSync(dir); - let id = readId(dir); - if (!id && existsSync(join(dir, ID_PATH))) + const folder = await stat(dir); + let id = await readIdOffThread(dir); + if (!id && (await statOffThread(join(dir, ID_PATH)))) throw new HistoryIdError( `${join(dir, ID_PATH)} holds no history id this version can read; move it aside to start anew.`, ); diff --git a/packages/studio-server/src/history/historyOffThread.test.ts b/packages/studio-server/src/history/historyOffThread.test.ts new file mode 100644 index 0000000000..b977d62f23 --- /dev/null +++ b/packages/studio-server/src/history/historyOffThread.test.ts @@ -0,0 +1,93 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Worker } from "node:worker_threads"; +import { describe, expect, it, onTestFinished } from "vitest"; +import { ID_PATH } from "./historyId.js"; +import { openProjectHistory } from "./projectHistory.js"; +import { KEEP_GONE_PROJECT_HISTORY_MS, pruneGoneProjectHistories } from "./pruneHistories.js"; + +// Answers the first read of a named pipe only once the main thread has run while that read waits, as a slow, cloud +// or unmounted disk would; later reads find a plain file. A read that holds the thread never lets it run. +const SLOW_DISK = ` +const { workerData, parentPort } = require("node:worker_threads"); +const fs = require("node:fs"); +const { pipe, id, flag } = workerData; +const fd = fs.openSync(pipe, "w"); +const mainRan = Atomics.wait(new Int32Array(flag), 0, 0, 5000) !== "timed-out"; +fs.writeFileSync(pipe + ".next", id + "\\n"); +fs.renameSync(pipe + ".next", pipe); +fs.writeSync(fd, id + "\\n"); +fs.closeSync(fd); +parentPort.postMessage(mainRan); +`; + +function tempDir(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + return dir; +} + +async function projectWithClosedHistory(historyRoot: string) { + const projectDir = join(tempDir("hf-offthread-project-"), "film"); + mkdirSync(projectDir, { recursive: true }); + writeFileSync(join(projectDir, "index.html"), "

A

"); + const history = await openProjectHistory({ projectDir, historyRoot }); + await new Promise((settle) => setImmediate(settle)); + await history.close(); + return projectDir; +} + +/** Whether the main thread ran while `start` waited on the project's history id. */ +async function ranWhileIdWaits(projectDir: string, start: () => Promise) { + const pipe = join(projectDir, ID_PATH); + const id = readFileSync(pipe, "utf-8").trim(); + rmSync(pipe); + execFileSync("mkfifo", [pipe]); + const flag = new SharedArrayBuffer(4); + const disk = new Worker(SLOW_DISK, { eval: true, workerData: { pipe, id, flag } }); + const answered = new Promise((resolve, reject) => { + disk.once("message", resolve); + disk.once("error", reject); + }); + const running = start(); + await new Promise((next) => setImmediate(next)); + Atomics.store(new Int32Array(flag), 0, 1); + Atomics.notify(new Int32Array(flag), 0); + const mainRan = await answered; + return { mainRan, result: await running }; +} + +describe.skipIf(process.platform === "win32")( + "a project's history id is read off the thread", + () => { + // fails without the fix: the prune read each project's history id with readFileSync. + it("by the prune of gone projects", async () => { + const historyRoot = tempDir("hf-offthread-root-"); + const projectDir = await projectWithClosedHistory(historyRoot); + + const { mainRan, result } = await ranWhileIdWaits(projectDir, () => + pruneGoneProjectHistories(historyRoot, { + now: Date.now() + 1 + KEEP_GONE_PROJECT_HISTORY_MS, + }), + ); + + expect(mainRan).toBe(true); + expect(result).toEqual([]); + }); + + // fails without the fix: the open read the project's history id with readFileSync. + it("by an open", async () => { + const historyRoot = tempDir("hf-offthread-root-"); + const projectDir = await projectWithClosedHistory(historyRoot); + + const { mainRan, result: history } = await ranWhileIdWaits(projectDir, () => + openProjectHistory({ projectDir, historyRoot }), + ); + await history.close(); + + expect(mainRan).toBe(true); + }); + }, +); diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.ts index bbfbb118ab..75166d0eff 100644 --- a/packages/studio-server/src/history/projectHistory.ts +++ b/packages/studio-server/src/history/projectHistory.ts @@ -45,6 +45,7 @@ import { sameFolder, projectHistoryId, readId, + statOffThread, recordProject, type FolderIdentity, } from "./historyId.js"; @@ -1584,9 +1585,9 @@ export class HistoryRefusedError extends Error { /** Opens a project's history: every write to its files becomes an entry that can be undone or restored. */ export async function openProjectHistory(options: ProjectHistoryOptions): Promise { - if (!existsSync(options.projectDir)) + if (!(await statOffThread(options.projectDir))) throw new HistoryClosedError(`${options.projectDir} is gone or now another project.`); - const projectId = projectHistoryId(options.projectDir, options.historyRoot); + const projectId = await projectHistoryId(options.projectDir, options.historyRoot); const release = await takeHistoryOwnership( join(options.historyRoot, projectId), options.ownerWaitMs ?? 5000, diff --git a/packages/studio-server/src/history/pruneHistories.ts b/packages/studio-server/src/history/pruneHistories.ts index ca67a0cb24..c99453ef8c 100644 --- a/packages/studio-server/src/history/pruneHistories.ts +++ b/packages/studio-server/src/history/pruneHistories.ts @@ -4,7 +4,14 @@ import { lstat, readdir, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { isSafePath } from "../helpers/safePath.js"; -import { ID_PATH, isHistoryId, readId, readRecord } from "./historyId.js"; +import { + ID_PATH, + isHistoryId, + readId, + readIdOffThread, + readRecord, + statOffThread, +} from "./historyId.js"; import { HistoryBusyError, readPlainFile, @@ -113,12 +120,12 @@ async function pruneOne( run: PruneRun, ): Promise { const home = join(historyRoot, id); - if (abandonedProject(home, id, run.now, run.tempDir) === null) return null; + if ((await abandonedProject(home, id, run.now, run.tempDir)) === null) return null; const release = await takeUnlessBusy(home); if (!release) return null; let taken: { projectDir: string; trash: string | null } | null; try { - taken = recheckAndMoveAway(historyRoot, id, run); + taken = await recheckAndMoveAway(historyRoot, id, run); } catch (error) { release(); throw error; @@ -145,10 +152,14 @@ async function takeUnlessBusy(home: string): Promise<(() => void) | null> { } } -function recheckAndMoveAway(historyRoot: string, id: string, { now, dryRun, tempDir }: PruneRun) { +async function recheckAndMoveAway( + historyRoot: string, + id: string, + { now, dryRun, tempDir }: PruneRun, +) { const home = join(historyRoot, id); // Re-read under the lock: an open that recorded this project again meanwhile keeps it. - const projectDir = abandonedProject(home, id, now, tempDir); + const projectDir = await abandonedProject(home, id, now, tempDir); if (projectDir === null) return null; if (dryRun) return { projectDir, trash: null }; // One rename takes the lock along, so an interrupted delete leaves a `.pruned-` folder the next run finishes. @@ -157,31 +168,41 @@ function recheckAndMoveAway(historyRoot: string, id: string, { now, dryRun, temp return { projectDir, trash }; } -/** The folder a history was recorded for, when that project is gone; null while it may still need its history. */ -function abandonedProject(home: string, id: string, now: number, tempDir: string): string | null { +/** The folder a history was recorded for, when that project is gone; null while it may still need its history. Its + * folder is read off the thread: a project not opened in weeks may sit on a slow, cloud or unmounted disk. */ +async function abandonedProject( + home: string, + id: string, + now: number, + tempDir: string, +): Promise { const record = readRecord(home); const dir = record?.dir; if (typeof dir !== "string") return null; if (now - lastUsed(home) < KEEP_GONE_PROJECT_HISTORY_MS && !isSafePath(tempDir, dir)) return null; - return projectGone(dir, id, record?.dev, tempDir) ? dir : null; + return (await projectGone(dir, id, record?.dev, tempDir)) ? dir : null; } -function projectGone(dir: string, id: string, dev: unknown, tempDir: string): boolean { - if (!statSync(join(dir, ID_PATH), { throwIfNoEntry: false })) - return diskStillHere(dir, dev, tempDir); +async function projectGone( + dir: string, + id: string, + dev: unknown, + tempDir: string, +): Promise { + if (!(await statOffThread(join(dir, ID_PATH)))) return diskStillHere(dir, dev, tempDir); // An id file this version cannot read is refused, never replaced, so its history is still the project's. - const there = readId(dir); + const there = await readIdOffThread(dir); return there !== null && there !== id; } /** A project without its id is gone only if the disk that held it is here: an unmounted drive or share keeps it. */ -function diskStillHere(dir: string, dev: unknown, tempDir: string): boolean { +async function diskStillHere(dir: string, dev: unknown, tempDir: string): Promise { let at = dir; - let stat = statSync(at, { throwIfNoEntry: false }); + let stat = await statOffThread(at); while (!stat) { if (dirname(at) === at) return false; at = dirname(at); - stat = statSync(at, { throwIfNoEntry: false }); + stat = await statOffThread(at); } if (typeof dev === "number") return stat.dev === dev; // Recorded before `dev`: a missing folder may sit on an unmounted disk, so only an emptied folder or temp counts.