Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio-server): write served files atomically (#4285)
Miguel Ángel9f19d9d32521
diff --git a/.github/workflows/preview-regression.yml b/.github/workflows/preview-regression.ymlindex d7f6f519c3..8ab6b25085 100644--- a/.github/workflows/preview-regression.yml+++ b/.github/workflows/preview-regression.yml@@ -22,7 +22,7 @@ jobs:changes:name: Detect changesruns-on: ubuntu-latest- timeout-minutes: 2+ timeout-minutes: 5outputs:preview: ${{ steps.filter.outputs.preview }}steps:diff --git a/packages/studio-server/src/helpers/applyFileMutations.ts b/packages/studio-server/src/helpers/applyFileMutations.tsindex d1988d5453..5e912228b2 100644--- a/packages/studio-server/src/helpers/applyFileMutations.ts+++ b/packages/studio-server/src/helpers/applyFileMutations.ts@@ -1,4 +1,5 @@-import { readFileSync, writeFileSync } from "node:fs";+import { readFileSync, statSync } from "node:fs";+import { replaceFileAtomically } from "./atomicFile.js";import { backupPathForResponse, snapshotBeforeWrite } from "./backupJournal.js";import {clearFileWriteReceipt,@@ -30,7 +31,8 @@ export function applyFileMutations(projectDir: string,mutations: readonly FileMutationInput[],requestToken?: string,- writeFile: (path: string, content: string, encoding: "utf-8") => void = writeFileSync,+ writeFile: (path: string, content: string, encoding: "utf-8") => void = (path, content) =>+ replaceFileAtomically(path, content, statSync(path).mode),): AppliedFileMutation[] {const prepared = mutations.map((mutation) => ({...mutation,diff --git a/packages/studio-server/src/helpers/atomicFile.test.ts b/packages/studio-server/src/helpers/atomicFile.test.tsnew file mode 100644index 0000000000..9e8c8b084d--- /dev/null+++ b/packages/studio-server/src/helpers/atomicFile.test.ts@@ -0,0 +1,107 @@+import { afterEach, describe, expect, it } from "vitest";+import * as fs from "node:fs";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { replaceFileAtomically } from "./atomicFile.js";++describe("replaceFileAtomically", () => {+ const dirs: string[] = [];++ afterEach(() => {+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });+ dirs.length = 0;+ });++ it("writes the sibling completely before replacing the project file", () => {+ const dir = mkdtempSync(join(tmpdir(), "atomic-file-test-"));+ dirs.push(dir);+ const file = join(dir, "index.html");+ writeFileSync(file, "old", { mode: 0o640 });+ const events: string[] = [];+ const operations = {+ writeFileSync: (path: fs.PathLike, ...args: any[]) => {+ events.push(`write:${String(path)}`);+ return fs.writeFileSync(path, ...args);+ },+ chmodSync: fs.chmodSync,+ renameSync: (from: fs.PathLike, to: fs.PathLike) => {+ events.push(`rename:${String(from)}:${String(to)}`);+ expect(readFileSync(from, "utf-8")).toBe("new complete html");+ return fs.renameSync(from, to);+ },+ unlinkSync: fs.unlinkSync,+ };++ replaceFileAtomically(file, "new complete html", 0o640, operations);++ expect(events).toHaveLength(2);+ expect(events[0]).toMatch(new RegExp(`^write:${file}\\.\\d+\\.[0-9a-f-]+\\.tmp$`));+ const tempPath = events[0]!.slice("write:".length);+ expect(events[1]).toBe(`rename:${tempPath}:${file}`);+ expect(readFileSync(file, "utf-8")).toBe("new complete html");+ expect(fs.statSync(file).mode & 0o777).toBe(0o640);+ });++ it("replaces an existing destination", () => {+ const dir = mkdtempSync(join(tmpdir(), "atomic-file-replace-test-"));+ dirs.push(dir);+ const file = join(dir, "index.html");+ writeFileSync(file, "old destination");++ replaceFileAtomically(file, "new destination", 0o640);++ expect(readFileSync(file, "utf-8")).toBe("new destination");+ });++ it("allocates a distinct temporary sibling for each writer", () => {+ const dir = mkdtempSync(join(tmpdir(), "atomic-file-unique-test-"));+ dirs.push(dir);+ const file = join(dir, "index.html");+ writeFileSync(file, "old");+ const tempPaths: string[] = [];+ const operations = {+ writeFileSync: (path: fs.PathLike, ...args: any[]) => {+ tempPaths.push(String(path));+ return fs.writeFileSync(path, ...args);+ },+ chmodSync: fs.chmodSync,+ renameSync: fs.renameSync,+ unlinkSync: fs.unlinkSync,+ };++ replaceFileAtomically(file, "first", 0o640, operations);+ replaceFileAtomically(file, "second", 0o640, operations);++ expect(tempPaths).toHaveLength(2);+ expect(tempPaths[0]).not.toBe(tempPaths[1]);+ });++ it("uses a unique temporary sibling and removes it when publication fails", () => {+ const dir = mkdtempSync(join(tmpdir(), "atomic-file-failure-test-"));+ dirs.push(dir);+ const file = join(dir, "index.html");+ writeFileSync(file, "old");+ const tempPaths: string[] = [];+ const removed: string[] = [];+ const operations = {+ writeFileSync: (path: fs.PathLike, ...args: any[]) => {+ tempPaths.push(String(path));+ return fs.writeFileSync(path, ...args);+ },+ chmodSync: fs.chmodSync,+ renameSync: () => {+ throw new Error("publish failed");+ },+ unlinkSync: (path: fs.PathLike) => {+ removed.push(String(path));+ return fs.unlinkSync(path);+ },+ };++ expect(() => replaceFileAtomically(file, "new", 0o640, operations)).toThrow("publish failed");+ expect(tempPaths).toHaveLength(1);+ expect(tempPaths[0]).toMatch(new RegExp(`^${file}\\.\\d+\\.[0-9a-f-]+\\.tmp$`));+ expect(removed).toEqual(tempPaths);+ });+});diff --git a/packages/studio-server/src/helpers/atomicFile.ts b/packages/studio-server/src/helpers/atomicFile.tsnew file mode 100644index 0000000000..8526c05b55--- /dev/null+++ b/packages/studio-server/src/helpers/atomicFile.ts@@ -0,0 +1,30 @@+import * as fs from "node:fs";+import { randomUUID } from "node:crypto";++type AtomicFileSystem = Pick<+ typeof fs,+ "writeFileSync" | "chmodSync" | "renameSync" | "unlinkSync"+>;++/** Replace a file only after the complete sibling temp file is written. */+export function replaceFileAtomically(+ filePath: string,+ content: string | Uint8Array,+ mode: number,+ operations: AtomicFileSystem = fs,+): void {+ const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;+ try {+ operations.writeFileSync(tempPath, content, { encoding: "utf-8", mode });+ operations.chmodSync(tempPath, mode);+ // Node fs.rename uses libuv uv_fs_rename; win32 calls MoveFileExW with MOVEFILE_REPLACE_EXISTING.+ operations.renameSync(tempPath, filePath);+ } catch (error) {+ try {+ operations.unlinkSync(tempPath);+ } catch {+ // Preserve the write error; cleanup is best effort.+ }+ throw error;+ }+}diff --git a/packages/studio-server/src/helpers/hfIdPersist.test.ts b/packages/studio-server/src/helpers/hfIdPersist.test.tsindex 0a4b203b55..2e1cf75789 100644--- a/packages/studio-server/src/helpers/hfIdPersist.test.ts+++ b/packages/studio-server/src/helpers/hfIdPersist.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, afterEach } from "vitest";-import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";+import { mkdtempSync, writeFileSync, readFileSync, readdirSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { persistHfIdsIfNeeded, stampFileHfIds } from "./hfIdPersist.js";@@ -93,6 +93,15 @@ describe("stampFileHfIds", () => {expect(readFileSync(file, "utf-8")).toBe(returned);});+ it("replaces the stamped file and removes its temporary sibling", () => {+ const file = tmpFile(`<div class="clip" data-start="0" data-end="3">Hi</div>`);++ const returned = stampFileHfIds(file);++ expect(readFileSync(file, "utf-8")).toBe(returned);+ expect(readdirSync(file.replace(/\/[^/]+$/, ""))).toEqual(["scene.html"]);+ });+it("does not rewrite an already-stamped file", () => {const file = tmpFile(`<div data-hf-id="hf-keep">Hi</div>`);const before = readFileSync(file, "utf-8");diff --git a/packages/studio-server/src/helpers/hfIdPersist.ts b/packages/studio-server/src/helpers/hfIdPersist.tsindex 50d79c05a1..1785861126 100644--- a/packages/studio-server/src/helpers/hfIdPersist.ts+++ b/packages/studio-server/src/helpers/hfIdPersist.ts@@ -1,14 +1,6 @@import { ensureHfIds } from "@hyperframes/parsers/hf-ids";-import {- closeSync,- constants,- fstatSync,- ftruncateSync,- openSync,- readFileSync,- writeFileSync,- writeSync,-} from "node:fs";+import { closeSync, constants, fstatSync, openSync, readFileSync, statSync } from "node:fs";+import { replaceFileAtomically } from "./atomicFile.js";/*** Ensure `html` has `data-hf-id` attributes minted, and write the result back@@ -35,7 +27,7 @@ export function persistHfIdsIfNeeded(filePath: string, html: string): string {// still be overwritten (microsecond window).const current = readFileSync(filePath, "utf-8");if (current === html) {- writeFileSync(filePath, normalized, "utf-8");+ replaceFileAtomically(filePath, normalized, statSync(filePath).mode);}} catch (err) {// Non-fatal — serve with ids even if the disk write fails (e.g. read-only@@ -75,7 +67,7 @@ function openNoFollow(filePath: string, flags: number): number | null {* persistHfIdsIfNeeded documents) — the next save simply re-persists.*/export function stampFileHfIds(filePath: string): string | null {- let fd = openNoFollow(filePath, constants.O_RDWR);+ let fd: number | null = openNoFollow(filePath, constants.O_RDWR);let writable = true;if (fd === null) {fd = openNoFollow(filePath, constants.O_RDONLY);@@ -91,14 +83,16 @@ export function stampFileHfIds(filePath: string): string | null {const idsBefore = (html.match(/\bdata-hf-id=/g) ?? []).length;const idsAfter = (normalized.match(/\bdata-hf-id=/g) ?? []).length;if (writable && idsAfter > idsBefore) {- ftruncateSync(fd, 0);- writeSync(fd, normalized, 0, "utf-8");+ const mode = fstatSync(fd).mode;+ closeSync(fd);+ fd = null;+ replaceFileAtomically(filePath, normalized, mode);}return normalized;} catch (err) {console.warn("[hyperframes] stampFileHfIds: failed to stamp ids:", err);return null;} finally {- closeSync(fd);+ if (fd !== null) closeSync(fd);}}diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.tsindex 8673b50431..ed68ee328f 100644--- a/packages/studio-server/src/routes/files.ts+++ b/packages/studio-server/src/routes/files.ts@@ -7,7 +7,6 @@ import { bodyLimit } from "hono/body-limit";import {closeSync,existsSync,- ftruncateSync,openSync,readFileSync,writeFileSync,@@ -16,12 +15,14 @@ import {unlinkSync,rmSync,statSync,+ fstatSync,renameSync,readdirSync,} from "node:fs";import { resolve, dirname, join } from "node:path";import type { StudioApiAdapter } from "../types.js";import { isAudioFile } from "../helpers/mime.js";+import { replaceFileAtomically } from "../helpers/atomicFile.js";import { generateWaveformCache } from "../helpers/waveform.js";import { validateUploadedMediaBuffer } from "../helpers/mediaValidation.js";import { isSafePath, resolveWithinProject } from "../helpers/safePath.js";@@ -323,7 +324,8 @@ function foldElementPatches(export function commitElementPatchBatches(projectDir: string,batches: ElementPatchBatchRequest[],- writeFile: (path: string, content: string, encoding: "utf-8") => void = writeFileSync,+ writeFile: (path: string, content: string, encoding: "utf-8") => void = (path, content) =>+ replaceFileAtomically(path, content, statSync(path).mode),requestToken?: string,):| { error: "duplicate" | "forbidden" | "not-found"; sourceFile: string }@@ -436,7 +438,7 @@ function writeFileWithReceipt(absPath: string,html: string,): { version: string; writeToken: string } {- writeFileSync(absPath, html, "utf-8");+ replaceFileAtomically(absPath, html, statSync(absPath).mode);// The synchronous write cannot yield before its receipt is recorded; keep this block await-free.return recordMutationReceipt(c, filePath, absPath, html);}@@ -586,7 +588,7 @@ function updateReferences(projectDir: string, oldPath: string, newPath: string):const updated = content.split(oldPath).join(newPath);if (updated !== content) {- writeFileSync(file, updated, "utf-8");+ replaceFileAtomically(file, updated, statSync(file).mode);updatedCount++;}}@@ -2343,7 +2345,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {closeSync(fd);}} else {- let fd: number;+ let fd: number | null;try {fd = openSync(res.absPath, "r+");} catch (error) {@@ -2376,10 +2378,12 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {}backup = snapshotBeforeWrite(res.project.dir, res.absPath);if (backup.error) return c.json({ error: `backup failed: ${backup.error}` }, 500);- ftruncateSync(fd, 0);- writeSync(fd, body, 0, body.length, 0);- } finally {+ const mode = fstatSync(fd).mode;closeSync(fd);+ fd = null;+ replaceFileAtomically(res.absPath, body, mode);+ } finally {+ if (fd !== null) closeSync(fd);}}const version = fileContentVersion(body);@@ -2665,7 +2669,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {const written: FoldedAtomicCutFile[] = [];try {for (const file of prepared) {- writeFileSync(file.absPath, file.after, "utf-8");+ replaceFileAtomically(file.absPath, file.after, statSync(file.absPath).mode);written.push(file);recordFileWriteReceipt(file.absPath, {path: file.path,@@ -2682,7 +2686,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {conflicts.push(file.path);continue;}- writeFileSync(file.absPath, file.before, "utf-8");+ replaceFileAtomically(file.absPath, file.before, statSync(file.absPath).mode);recordFileWriteReceipt(file.absPath, {path: file.path,version: fileContentVersion(file.before),@@ -3224,7 +3228,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {if (current !== body.expected) {return c.json({ ok: true, restored: false, conflict: true });}- writeFileSync(res.absPath, body.restore, "utf-8");+ replaceFileAtomically(res.absPath, body.restore, statSync(res.absPath).mode);return c.json({ ok: true, restored: true, conflict: false });});}