Skip to content

Commit 9f19d9d

Browse files
fix(studio-server): write served files atomically (heygen-com#4285)
* fix(studio-server): write project files atomically * fix(studio-server): isolate atomic write temporary files * test(studio-server): document Windows atomic replacement * ci: allow change detection checkout to finish * test(studio-server): assert atomic stamp cleanup without ESM spy
1 parent 05d09a7 commit 9f19d9d

7 files changed

Lines changed: 176 additions & 30 deletions

File tree

‎.github/workflows/preview-regression.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ jobs:
2222
changes:
2323
name: Detect changes
2424
runs-on: ubuntu-latest
25-
timeout-minutes: 2
25+
timeout-minutes: 5
2626
outputs:
2727
preview: ${{ steps.filter.outputs.preview }}
2828
steps:

‎packages/studio-server/src/helpers/applyFileMutations.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { readFileSync, writeFileSync } from "node:fs";
1+
import { readFileSync, statSync } from "node:fs";
2+
import { replaceFileAtomically } from "./atomicFile.js";
23
import { backupPathForResponse, snapshotBeforeWrite } from "./backupJournal.js";
34
import {
45
clearFileWriteReceipt,
@@ -30,7 +31,8 @@ export function applyFileMutations(
3031
projectDir: string,
3132
mutations: readonly FileMutationInput[],
3233
requestToken?: string,
33-
writeFile: (path: string, content: string, encoding: "utf-8") => void = writeFileSync,
34+
writeFile: (path: string, content: string, encoding: "utf-8") => void = (path, content) =>
35+
replaceFileAtomically(path, content, statSync(path).mode),
3436
): AppliedFileMutation[] {
3537
const prepared = mutations.map((mutation) => ({
3638
...mutation,
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import { afterEach, describe, expect, it } from "vitest";
2+
import * as fs from "node:fs";
3+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4+
import { tmpdir } from "node:os";
5+
import { join } from "node:path";
6+
import { replaceFileAtomically } from "./atomicFile.js";
7+
8+
describe("replaceFileAtomically", () => {
9+
const dirs: string[] = [];
10+
11+
afterEach(() => {
12+
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
13+
dirs.length = 0;
14+
});
15+
16+
it("writes the sibling completely before replacing the project file", () => {
17+
const dir = mkdtempSync(join(tmpdir(), "atomic-file-test-"));
18+
dirs.push(dir);
19+
const file = join(dir, "index.html");
20+
writeFileSync(file, "old", { mode: 0o640 });
21+
const events: string[] = [];
22+
const operations = {
23+
writeFileSync: (path: fs.PathLike, ...args: any[]) => {
24+
events.push(`write:${String(path)}`);
25+
return fs.writeFileSync(path, ...args);
26+
},
27+
chmodSync: fs.chmodSync,
28+
renameSync: (from: fs.PathLike, to: fs.PathLike) => {
29+
events.push(`rename:${String(from)}:${String(to)}`);
30+
expect(readFileSync(from, "utf-8")).toBe("new complete html");
31+
return fs.renameSync(from, to);
32+
},
33+
unlinkSync: fs.unlinkSync,
34+
};
35+
36+
replaceFileAtomically(file, "new complete html", 0o640, operations);
37+
38+
expect(events).toHaveLength(2);
39+
expect(events[0]).toMatch(new RegExp(`^write:${file}\\.\\d+\\.[0-9a-f-]+\\.tmp$`));
40+
const tempPath = events[0]!.slice("write:".length);
41+
expect(events[1]).toBe(`rename:${tempPath}:${file}`);
42+
expect(readFileSync(file, "utf-8")).toBe("new complete html");
43+
expect(fs.statSync(file).mode & 0o777).toBe(0o640);
44+
});
45+
46+
it("replaces an existing destination", () => {
47+
const dir = mkdtempSync(join(tmpdir(), "atomic-file-replace-test-"));
48+
dirs.push(dir);
49+
const file = join(dir, "index.html");
50+
writeFileSync(file, "old destination");
51+
52+
replaceFileAtomically(file, "new destination", 0o640);
53+
54+
expect(readFileSync(file, "utf-8")).toBe("new destination");
55+
});
56+
57+
it("allocates a distinct temporary sibling for each writer", () => {
58+
const dir = mkdtempSync(join(tmpdir(), "atomic-file-unique-test-"));
59+
dirs.push(dir);
60+
const file = join(dir, "index.html");
61+
writeFileSync(file, "old");
62+
const tempPaths: string[] = [];
63+
const operations = {
64+
writeFileSync: (path: fs.PathLike, ...args: any[]) => {
65+
tempPaths.push(String(path));
66+
return fs.writeFileSync(path, ...args);
67+
},
68+
chmodSync: fs.chmodSync,
69+
renameSync: fs.renameSync,
70+
unlinkSync: fs.unlinkSync,
71+
};
72+
73+
replaceFileAtomically(file, "first", 0o640, operations);
74+
replaceFileAtomically(file, "second", 0o640, operations);
75+
76+
expect(tempPaths).toHaveLength(2);
77+
expect(tempPaths[0]).not.toBe(tempPaths[1]);
78+
});
79+
80+
it("uses a unique temporary sibling and removes it when publication fails", () => {
81+
const dir = mkdtempSync(join(tmpdir(), "atomic-file-failure-test-"));
82+
dirs.push(dir);
83+
const file = join(dir, "index.html");
84+
writeFileSync(file, "old");
85+
const tempPaths: string[] = [];
86+
const removed: string[] = [];
87+
const operations = {
88+
writeFileSync: (path: fs.PathLike, ...args: any[]) => {
89+
tempPaths.push(String(path));
90+
return fs.writeFileSync(path, ...args);
91+
},
92+
chmodSync: fs.chmodSync,
93+
renameSync: () => {
94+
throw new Error("publish failed");
95+
},
96+
unlinkSync: (path: fs.PathLike) => {
97+
removed.push(String(path));
98+
return fs.unlinkSync(path);
99+
},
100+
};
101+
102+
expect(() => replaceFileAtomically(file, "new", 0o640, operations)).toThrow("publish failed");
103+
expect(tempPaths).toHaveLength(1);
104+
expect(tempPaths[0]).toMatch(new RegExp(`^${file}\\.\\d+\\.[0-9a-f-]+\\.tmp$`));
105+
expect(removed).toEqual(tempPaths);
106+
});
107+
});
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import * as fs from "node:fs";
2+
import { randomUUID } from "node:crypto";
3+
4+
type AtomicFileSystem = Pick<
5+
typeof fs,
6+
"writeFileSync" | "chmodSync" | "renameSync" | "unlinkSync"
7+
>;
8+
9+
/** Replace a file only after the complete sibling temp file is written. */
10+
export function replaceFileAtomically(
11+
filePath: string,
12+
content: string | Uint8Array,
13+
mode: number,
14+
operations: AtomicFileSystem = fs,
15+
): void {
16+
const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
17+
try {
18+
operations.writeFileSync(tempPath, content, { encoding: "utf-8", mode });
19+
operations.chmodSync(tempPath, mode);
20+
// Node fs.rename uses libuv uv_fs_rename; win32 calls MoveFileExW with MOVEFILE_REPLACE_EXISTING.
21+
operations.renameSync(tempPath, filePath);
22+
} catch (error) {
23+
try {
24+
operations.unlinkSync(tempPath);
25+
} catch {
26+
// Preserve the write error; cleanup is best effort.
27+
}
28+
throw error;
29+
}
30+
}

‎packages/studio-server/src/helpers/hfIdPersist.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, it, expect, afterEach } from "vitest";
2-
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
2+
import { mkdtempSync, writeFileSync, readFileSync, readdirSync, rmSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { persistHfIdsIfNeeded, stampFileHfIds } from "./hfIdPersist.js";
@@ -93,6 +93,15 @@ describe("stampFileHfIds", () => {
9393
expect(readFileSync(file, "utf-8")).toBe(returned);
9494
});
9595

96+
it("replaces the stamped file and removes its temporary sibling", () => {
97+
const file = tmpFile(`<div class="clip" data-start="0" data-end="3">Hi</div>`);
98+
99+
const returned = stampFileHfIds(file);
100+
101+
expect(readFileSync(file, "utf-8")).toBe(returned);
102+
expect(readdirSync(file.replace(/\/[^/]+$/, ""))).toEqual(["scene.html"]);
103+
});
104+
96105
it("does not rewrite an already-stamped file", () => {
97106
const file = tmpFile(`<div data-hf-id="hf-keep">Hi</div>`);
98107
const before = readFileSync(file, "utf-8");

‎packages/studio-server/src/helpers/hfIdPersist.ts‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,6 @@
11
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
2-
import {
3-
closeSync,
4-
constants,
5-
fstatSync,
6-
ftruncateSync,
7-
openSync,
8-
readFileSync,
9-
writeFileSync,
10-
writeSync,
11-
} from "node:fs";
2+
import { closeSync, constants, fstatSync, openSync, readFileSync, statSync } from "node:fs";
3+
import { replaceFileAtomically } from "./atomicFile.js";
124

135
/**
146
* 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 {
3527
// still be overwritten (microsecond window).
3628
const current = readFileSync(filePath, "utf-8");
3729
if (current === html) {
38-
writeFileSync(filePath, normalized, "utf-8");
30+
replaceFileAtomically(filePath, normalized, statSync(filePath).mode);
3931
}
4032
} catch (err) {
4133
// 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 {
7567
* persistHfIdsIfNeeded documents) — the next save simply re-persists.
7668
*/
7769
export function stampFileHfIds(filePath: string): string | null {
78-
let fd = openNoFollow(filePath, constants.O_RDWR);
70+
let fd: number | null = openNoFollow(filePath, constants.O_RDWR);
7971
let writable = true;
8072
if (fd === null) {
8173
fd = openNoFollow(filePath, constants.O_RDONLY);
@@ -91,14 +83,16 @@ export function stampFileHfIds(filePath: string): string | null {
9183
const idsBefore = (html.match(/\bdata-hf-id=/g) ?? []).length;
9284
const idsAfter = (normalized.match(/\bdata-hf-id=/g) ?? []).length;
9385
if (writable && idsAfter > idsBefore) {
94-
ftruncateSync(fd, 0);
95-
writeSync(fd, normalized, 0, "utf-8");
86+
const mode = fstatSync(fd).mode;
87+
closeSync(fd);
88+
fd = null;
89+
replaceFileAtomically(filePath, normalized, mode);
9690
}
9791
return normalized;
9892
} catch (err) {
9993
console.warn("[hyperframes] stampFileHfIds: failed to stamp ids:", err);
10094
return null;
10195
} finally {
102-
closeSync(fd);
96+
if (fd !== null) closeSync(fd);
10397
}
10498
}

‎packages/studio-server/src/routes/files.ts‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import { bodyLimit } from "hono/body-limit";
77
import {
88
closeSync,
99
existsSync,
10-
ftruncateSync,
1110
openSync,
1211
readFileSync,
1312
writeFileSync,
@@ -16,12 +15,14 @@ import {
1615
unlinkSync,
1716
rmSync,
1817
statSync,
18+
fstatSync,
1919
renameSync,
2020
readdirSync,
2121
} from "node:fs";
2222
import { resolve, dirname, join } from "node:path";
2323
import type { StudioApiAdapter } from "../types.js";
2424
import { isAudioFile } from "../helpers/mime.js";
25+
import { replaceFileAtomically } from "../helpers/atomicFile.js";
2526
import { generateWaveformCache } from "../helpers/waveform.js";
2627
import { validateUploadedMediaBuffer } from "../helpers/mediaValidation.js";
2728
import { isSafePath, resolveWithinProject } from "../helpers/safePath.js";
@@ -323,7 +324,8 @@ function foldElementPatches(
323324
export function commitElementPatchBatches(
324325
projectDir: string,
325326
batches: ElementPatchBatchRequest[],
326-
writeFile: (path: string, content: string, encoding: "utf-8") => void = writeFileSync,
327+
writeFile: (path: string, content: string, encoding: "utf-8") => void = (path, content) =>
328+
replaceFileAtomically(path, content, statSync(path).mode),
327329
requestToken?: string,
328330
):
329331
| { error: "duplicate" | "forbidden" | "not-found"; sourceFile: string }
@@ -436,7 +438,7 @@ function writeFileWithReceipt(
436438
absPath: string,
437439
html: string,
438440
): { version: string; writeToken: string } {
439-
writeFileSync(absPath, html, "utf-8");
441+
replaceFileAtomically(absPath, html, statSync(absPath).mode);
440442
// The synchronous write cannot yield before its receipt is recorded; keep this block await-free.
441443
return recordMutationReceipt(c, filePath, absPath, html);
442444
}
@@ -586,7 +588,7 @@ function updateReferences(projectDir: string, oldPath: string, newPath: string):
586588

587589
const updated = content.split(oldPath).join(newPath);
588590
if (updated !== content) {
589-
writeFileSync(file, updated, "utf-8");
591+
replaceFileAtomically(file, updated, statSync(file).mode);
590592
updatedCount++;
591593
}
592594
}
@@ -2343,7 +2345,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
23432345
closeSync(fd);
23442346
}
23452347
} else {
2346-
let fd: number;
2348+
let fd: number | null;
23472349
try {
23482350
fd = openSync(res.absPath, "r+");
23492351
} catch (error) {
@@ -2376,10 +2378,12 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
23762378
}
23772379
backup = snapshotBeforeWrite(res.project.dir, res.absPath);
23782380
if (backup.error) return c.json({ error: `backup failed: ${backup.error}` }, 500);
2379-
ftruncateSync(fd, 0);
2380-
writeSync(fd, body, 0, body.length, 0);
2381-
} finally {
2381+
const mode = fstatSync(fd).mode;
23822382
closeSync(fd);
2383+
fd = null;
2384+
replaceFileAtomically(res.absPath, body, mode);
2385+
} finally {
2386+
if (fd !== null) closeSync(fd);
23832387
}
23842388
}
23852389
const version = fileContentVersion(body);
@@ -2665,7 +2669,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
26652669
const written: FoldedAtomicCutFile[] = [];
26662670
try {
26672671
for (const file of prepared) {
2668-
writeFileSync(file.absPath, file.after, "utf-8");
2672+
replaceFileAtomically(file.absPath, file.after, statSync(file.absPath).mode);
26692673
written.push(file);
26702674
recordFileWriteReceipt(file.absPath, {
26712675
path: file.path,
@@ -2682,7 +2686,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
26822686
conflicts.push(file.path);
26832687
continue;
26842688
}
2685-
writeFileSync(file.absPath, file.before, "utf-8");
2689+
replaceFileAtomically(file.absPath, file.before, statSync(file.absPath).mode);
26862690
recordFileWriteReceipt(file.absPath, {
26872691
path: file.path,
26882692
version: fileContentVersion(file.before),
@@ -3224,7 +3228,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
32243228
if (current !== body.expected) {
32253229
return c.json({ ok: true, restored: false, conflict: true });
32263230
}
3227-
writeFileSync(res.absPath, body.restore, "utf-8");
3231+
replaceFileAtomically(res.absPath, body.restore, statSync(res.absPath).mode);
32283232
return c.json({ ok: true, restored: true, conflict: false });
32293233
});
32303234
}

0 commit comments

Comments
 (0)