Skip to content

Write HTML. Render video. Built for agents.

fix(studio-server): one process at a time keeps a project's history open (#4448)

Miguel Ángel31441701fc6b
diff --git a/packages/cli/src/server/studioServer.test.ts b/packages/cli/src/server/studioServer.test.ts
index 08c0099d75..c2c8018b6d 100644
--- a/packages/cli/src/server/studioServer.test.ts
+++ b/packages/cli/src/server/studioServer.test.ts
@@ -3,7 +3,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
-import { createProjectSignature, fileContentVersion } from "@hyperframes/studio-server";
+import {
+ createProjectSignature,
+ fileContentVersion,
+ HistoryBusyError,
+} from "@hyperframes/studio-server";
import { loadHyperframeRuntimeSource } from "@hyperframes/core";
import { loadRuntimeSource } from "./runtimeSource.js";
import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
@@ -152,6 +156,19 @@ describe("createStudioServer project history (D-491)", () => {
await server.shutdown();
});
+ it("tries a history another process was holding again on the next request, instead of turning it off", async () => {
+ historyState.open = async () => {
+ historyState.open = null;
+ throw new HistoryBusyError(1);
+ };
+ const projectDir = tmpProject();
+ server = createStudioServer({ projectDir, historyRoot: tmpProject() });
+ const historyUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
+ expect((await server.app.request(historyUrl)).status).toBe(404);
+ expect((await server.app.request(historyUrl)).status).toBe(200);
+ await server.shutdown();
+ });
+
it("shutdown returns within preview's exit watchdog while the history is still opening", async () => {
historyState.open = () => new Promise(() => {});
try {
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts
index 02ec736179..4727680065 100644
--- a/packages/cli/src/server/studioServer.ts
+++ b/packages/cli/src/server/studioServer.ts
@@ -55,6 +55,7 @@ import {
stampProjectHfIds,
DEFAULT_HISTORY_ROOT,
openProjectHistory,
+ HistoryBusyError,
type ProjectHistory,
} from "@hyperframes/studio-server";
import { resolveAutoProxy } from "../utils/projectConfig.js";
@@ -427,7 +428,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
};
// Opened on first use, so a server that never serves Studio's history never writes one. A failed open stays off
- // for this run.
+ // for this run; one another process was holding is tried again on the next request.
let history: Promise<ProjectHistory | null> | undefined;
const projectHistory = () =>
(history ??= openProjectHistory({
@@ -435,6 +436,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
historyRoot: options.historyRoot ?? DEFAULT_HISTORY_ROOT,
}).catch((error: unknown) => {
console.warn(`[studio] Project history is off: ${String(error)}`);
+ if (error instanceof HistoryBusyError) history = undefined;
return null;
}));
watcher.addListener((changedPath) => {
diff --git a/packages/studio-server/src/history/ownerLock.ts b/packages/studio-server/src/history/ownerLock.ts
new file mode 100644
index 0000000000..eef000275d
--- /dev/null
+++ b/packages/studio-server/src/history/ownerLock.ts
@@ -0,0 +1,95 @@
+import { randomUUID } from "node:crypto";
+import { linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+export class HistoryBusyError extends Error {
+ constructor(readonly pid: number) {
+ super(`This project's history is open in another process (pid ${pid}).`);
+ this.name = "HistoryBusyError";
+ }
+}
+
+function alive(pid: number): boolean {
+ if (!Number.isInteger(pid) || pid <= 0) return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+/** The pid in `file`; null when there is no file, NaN when it holds no pid (so it reads as dead). */
+function ownerOf(file: string): number | null {
+ try {
+ const text = readFileSync(file, "utf-8");
+ return /^\d+$/.test(text) ? Number(text) : Number.NaN;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw error;
+ }
+}
+
+/** Takes `file` if nobody holds it: written aside and linked in, so a reader never sees it without its pid. */
+function claim(file: string): boolean {
+ const draft = `${file}-${randomUUID()}.tmp`;
+ writeFileSync(draft, String(process.pid));
+ try {
+ linkSync(draft, file);
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ return false;
+ } finally {
+ rmSync(draft, { force: true });
+ }
+}
+
+/** Removes `file` only while it names this process, so a release never takes a later owner's lock. */
+function releaseOwn(file: string): void {
+ if (ownerOf(file) === process.pid) rmSync(file, { force: true });
+}
+
+/**
+ * Removes a dead owner's lock under an evict lock, re-reading the owner, so a live owner's lock survives. False when
+ * another evictor holds it. ponytail: a crashed evictor's lock is cleared unguarded; racing that can give two owners.
+ */
+function evictDeadOwner(file: string): boolean {
+ const evictor = `${file}.evict`;
+ if (!claim(evictor)) {
+ const holder = ownerOf(evictor);
+ if (holder !== null && !alive(holder)) rmSync(evictor, { force: true });
+ return false;
+ }
+ try {
+ const pid = ownerOf(file);
+ if (pid !== null && !alive(pid)) rmSync(file, { force: true });
+ return true;
+ } finally {
+ releaseOwn(evictor);
+ }
+}
+
+/**
+ * One process at a time keeps a project's history open (a second opener would fork the log). Waits up to `waitMs`
+ * for the owner to close, takes over a dead owner's lock.
+ */
+export async function takeHistoryOwnership(home: string, waitMs: number): Promise<() => void> {
+ const file = join(home, "owner.pid");
+ const deadline = Date.now() + waitMs;
+ mkdirSync(home, { recursive: true });
+ for (;;) {
+ if (claim(file)) {
+ let held = true;
+ return () => {
+ if (held) releaseOwn(file);
+ held = false;
+ };
+ }
+ const pid = ownerOf(file);
+ if (pid === null) continue;
+ if (!alive(pid) && evictDeadOwner(file)) continue;
+ if (Date.now() >= deadline) throw new HistoryBusyError(pid);
+ await new Promise((settle) => setTimeout(settle, 50));
+ }
+}
diff --git a/packages/studio-server/src/history/projectHistory.test.ts b/packages/studio-server/src/history/projectHistory.test.ts
index f35e4bb23e..623f8c9c43 100644
--- a/packages/studio-server/src/history/projectHistory.test.ts
+++ b/packages/studio-server/src/history/projectHistory.test.ts
@@ -10,10 +10,12 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
+import { spawnSync } from "node:child_process";
import { tmpdir } from "node:os";
import { dirname, join, relative } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { fileContentVersion } from "../helpers/fileVersion";
+import { HistoryBusyError } from "./ownerLock";
import { openProjectHistory, type ProjectHistory } from "./projectHistory";
import { START, type HistoryWho } from "./historyLog";
@@ -191,6 +193,66 @@ describe("openProjectHistory", () => {
expect(copied.list()).toEqual([]);
});
+ it("lets one process at a time hold a project's history, so a second opener cannot fork its log", async () => {
+ const { history, projectDir, historyRoot } = await project({ "index.html": "v1" });
+ await expect(openProjectHistory({ projectDir, historyRoot, ownerWaitMs: 0 })).rejects.toThrow(
+ `pid ${process.pid}`,
+ );
+ const waiting = open(projectDir, historyRoot, { ownerWaitMs: 5000 });
+ await history.close();
+ expect((await waiting).projectId).toBe(history.projectId);
+ });
+
+ it("takes over the lock of an owner that died without closing", async () => {
+ const { history, projectDir, historyRoot } = await project({ "index.html": "v1" });
+ await history.close();
+ const dead = spawnSync(process.execPath, ["-e", "process.stdout.write(String(process.pid))"]);
+ writeFileSync(join(historyRoot, history.projectId, "owner.pid"), dead.stdout);
+ expect((await open(projectDir, historyRoot, { ownerWaitMs: 0 })).projectId).toBe(
+ history.projectId,
+ );
+ });
+
+ it("never removes a lock another process holds: not on close, not while another evicts a dead owner", async () => {
+ const { history, projectDir, historyRoot } = await project({ "index.html": "v1" });
+ const lock = join(historyRoot, history.projectId, "owner.pid");
+ const other = String(process.ppid); // a live process that is not this one
+ writeFileSync(lock, other);
+ await history.close();
+ expect(readFileSync(lock, "utf-8"), "a close leaves a later owner's lock").toBe(other);
+
+ const dead = spawnSync(process.execPath, ["-e", "process.stdout.write(String(process.pid))"]);
+ writeFileSync(lock, dead.stdout);
+ writeFileSync(`${lock}.evict`, other);
+ await expect(
+ openProjectHistory({ projectDir, historyRoot, ownerWaitMs: 200 }),
+ "only the evictor that holds the evict lock removes a dead owner",
+ ).rejects.toThrow(HistoryBusyError);
+
+ writeFileSync(`${lock}.evict`, dead.stdout);
+ expect((await open(projectDir, historyRoot, { ownerWaitMs: 200 })).projectId).toBe(
+ history.projectId,
+ );
+ });
+
+ it("fails an open whose lock cannot be read, instead of retrying it forever", async () => {
+ const { history, projectDir, historyRoot } = await project({ "index.html": "v1" });
+ await history.close();
+ mkdirSync(join(historyRoot, history.projectId, "owner.pid"));
+ await expect(openProjectHistory({ projectDir, historyRoot, ownerWaitMs: 0 })).rejects.toThrow(
+ /EISDIR/,
+ );
+ });
+
+ it("takes over a lock file that holds no pid", async () => {
+ const { history, projectDir, historyRoot } = await project({ "index.html": "v1" });
+ await history.close();
+ writeFileSync(join(historyRoot, history.projectId, "owner.pid"), "");
+ expect((await open(projectDir, historyRoot, { ownerWaitMs: 0 })).projectId).toBe(
+ history.projectId,
+ );
+ });
+
it("rewrites a history folder removed while open, so a reopen still has the change", async () => {
const { history, write, projectDir, historyRoot } = await project({ "index.html": "v1" });
const earlier = await change(history, you, "Second", () => write("index.html", "v2"));
diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.ts
index c6ed9cb437..48b3a4f772 100644
--- a/packages/studio-server/src/history/projectHistory.ts
+++ b/packages/studio-server/src/history/projectHistory.ts
@@ -13,6 +13,7 @@ import {
import { affectsProjectSignature, listProjectFiles } from "../helpers/projectSignature.js";
import { openBlobStore, type BlobStore } from "./blobStore.js";
import { projectHistoryId } from "./historyId.js";
+import { takeHistoryOwnership } from "./ownerLock.js";
import {
START,
foldOldest,
@@ -46,6 +47,8 @@ export interface ProjectHistoryOptions {
budgetBytes?: number;
/** A sweep or commit that a watcher or timer started failed. */
onError?: (error: unknown) => void;
+ /** How long an open waits for another process to close the same history (default 5 s). */
+ ownerWaitMs?: number;
}
interface ClaimOptions {
@@ -734,8 +737,21 @@ class Engine {
/** 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<ProjectHistory> {
const projectId = projectHistoryId(options.projectDir, options.historyRoot);
- const blobs = await openBlobStore(join(options.historyRoot, projectId, "blobs"));
- const engine = new Engine(options, projectId, blobs);
- await engine.queue(() => engine.start());
- return engine.api();
+ const release = await takeHistoryOwnership(
+ join(options.historyRoot, projectId),
+ options.ownerWaitMs ?? 5000,
+ );
+ try {
+ const blobs = await openBlobStore(join(options.historyRoot, projectId, "blobs"));
+ const engine = new Engine(options, projectId, blobs);
+ await engine.queue(() => engine.start());
+ const api = engine.api();
+ return {
+ ...api,
+ close: () => api.close().finally(release),
+ };
+ } catch (error) {
+ release();
+ throw error;
+ }
}
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index 471f74bea1..f057a39d58 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -10,6 +10,7 @@ export {
type HistoryResult,
type HistoryWindow,
} from "./history/projectHistory.js";
+export { HistoryBusyError } from "./history/ownerLock.js";
export {
START as HISTORY_START,
type HistoryEntry,