Skip to content

Commit 063c2f8

Browse files
fix(studio-server): a failed save reports its real error when a later file was never written (#5364)
* fix(studio-server): a failed save reports its real error when a later file was never written * refactor(studio-server): share the file writer type and harden rollback test cleanup
1 parent f8ee010 commit 063c2f8

3 files changed

Lines changed: 101 additions & 17 deletions

File tree

‎.fallowrc.jsonc‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,7 @@
538538
"packages/engine/src/services/extractionCache.test.ts",
539539
"packages/studio-server/src/routes/preview.test.ts",
540540
"packages/studio-server/src/routes/projects.test.ts",
541+
"packages/studio-server/src/helpers/applyFileMutations.test.ts",
541542
"packages/studio-server/src/helpers/backupJournal.test.ts",
542543
"packages/studio-server/src/helpers/finiteMutation.test.ts",
543544
"packages/studio-server/src/helpers/hfIdPersist.test.ts",

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

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1+
import {
2+
chmodSync,
3+
existsSync,
4+
mkdirSync,
5+
mkdtempSync,
6+
readFileSync,
7+
rmSync,
8+
writeFileSync,
9+
} from "node:fs";
210
import { join } from "node:path";
311
import { tmpdir } from "node:os";
412
import { describe, expect, it } from "vitest";
@@ -171,4 +179,69 @@ describe("applyFileMutations", () => {
171179
rmSync(projectDir, { recursive: true, force: true });
172180
}
173181
});
182+
183+
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
184+
"reports the write error, not a failed rollback, when a later file was never written",
185+
() => {
186+
resetFileWriteReceipts();
187+
const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-readonly-"));
188+
const first = join(projectDir, "first.html");
189+
const lockedDir = join(projectDir, "locked");
190+
const second = join(lockedDir, "second.html");
191+
try {
192+
mkdirSync(lockedDir);
193+
writeFileSync(first, "first-before", "utf8");
194+
writeFileSync(second, "second-before", "utf8");
195+
chmodSync(lockedDir, 0o555);
196+
let thrown: unknown;
197+
try {
198+
applyFileMutations(projectDir, [
199+
{ sourceFile: "first.html", absPath: first, after: "first-after" },
200+
{ sourceFile: "locked/second.html", absPath: second, after: "second-after" },
201+
]);
202+
} catch (error) {
203+
thrown = error;
204+
}
205+
expect(thrown).not.toBeInstanceOf(AggregateError);
206+
expect(thrown).toMatchObject({ code: "EACCES" });
207+
expect(readFileSync(first, "utf8")).toBe("first-before");
208+
expect(readFileSync(second, "utf8")).toBe("second-before");
209+
expect(identifyFileWrite(first, fileContentVersion("first-after"))).toBeNull();
210+
} finally {
211+
if (existsSync(lockedDir)) chmodSync(lockedDir, 0o755);
212+
resetFileWriteReceipts();
213+
rmSync(projectDir, { recursive: true, force: true });
214+
}
215+
},
216+
);
217+
218+
it("still reports an incomplete rollback when a written file cannot be restored", () => {
219+
const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-restore-"));
220+
try {
221+
for (const name of ["first", "second"])
222+
writeFileSync(join(projectDir, `${name}.html`), `${name}-before`, "utf8");
223+
let writes = 0;
224+
expect(() =>
225+
applyFileMutations(
226+
projectDir,
227+
["first", "second"].map((name) => ({
228+
sourceFile: `${name}.html`,
229+
absPath: join(projectDir, `${name}.html`),
230+
after: `${name}-after`,
231+
})),
232+
undefined,
233+
(path, content, encoding) => {
234+
writes += 1;
235+
if (writes === 2) throw new Error("second write failed");
236+
if (writes === 3) throw new Error("first restore failed");
237+
writeFileSync(path, content, encoding);
238+
},
239+
),
240+
).toThrow("File mutation failed and rollback did not complete");
241+
expect(readFileSync(join(projectDir, "first.html"), "utf8")).toBe("first-after");
242+
} finally {
243+
resetFileWriteReceipts();
244+
rmSync(projectDir, { recursive: true, force: true });
245+
}
246+
});
174247
});

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

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -31,17 +31,15 @@ export function applyFileMutations(
3131
projectDir: string,
3232
mutations: readonly FileMutationInput[],
3333
requestToken?: string,
34-
writeFile: (path: string, content: string, encoding: "utf-8") => void = (path, content) =>
34+
writeFile: WriteFile = (path, content) =>
3535
replaceFileAtomically(path, content, statSync(path).mode),
3636
): AppliedFileMutation[] {
3737
const prepared = mutations.map((mutation) => ({
3838
...mutation,
3939
before: mutation.before ?? readFileSync(mutation.absPath, "utf-8"),
4040
}));
4141
const results: AppliedFileMutation[] = [];
42-
const attempted: Array<
43-
PreparedMutation & { version: string; writeToken: string; written: boolean }
44-
> = [];
42+
const attempted: AttemptedMutation[] = [];
4543
for (const mutation of prepared)
4644
assertExpectedVersion(mutation, readFileSync(mutation.absPath, "utf-8"));
4745
try {
@@ -50,16 +48,7 @@ export function applyFileMutations(
5048
}
5149
return results;
5250
} catch (error) {
53-
const rollbackErrors: unknown[] = [];
54-
for (const mutation of attempted.reverse()) {
55-
try {
56-
if (!mutation.written || readFileSync(mutation.absPath, "utf-8") === mutation.after)
57-
writeFile(mutation.absPath, mutation.before, "utf-8");
58-
clearFileWriteReceipt(mutation.absPath, mutation.version, mutation.writeToken);
59-
} catch (rollbackError) {
60-
rollbackErrors.push(rollbackError);
61-
}
62-
}
51+
const rollbackErrors = rollBack(attempted, writeFile);
6352
if (rollbackErrors.length > 0) {
6453
throw new AggregateError(
6554
[error, ...rollbackErrors],
@@ -71,13 +60,34 @@ export function applyFileMutations(
7160
}
7261

7362
type PreparedMutation = FileMutationInput & { before: string };
63+
type WriteFile = (path: string, content: string, encoding: "utf-8") => void;
64+
type AttemptedMutation = PreparedMutation & {
65+
version: string;
66+
writeToken: string;
67+
written: boolean;
68+
};
69+
70+
function rollBack(attempted: AttemptedMutation[], writeFile: WriteFile): unknown[] {
71+
const errors: unknown[] = [];
72+
for (const mutation of attempted.reverse()) {
73+
try {
74+
const current = readFileSync(mutation.absPath, "utf-8");
75+
if (mutation.written ? current === mutation.after : current !== mutation.before)
76+
writeFile(mutation.absPath, mutation.before, "utf-8");
77+
clearFileWriteReceipt(mutation.absPath, mutation.version, mutation.writeToken);
78+
} catch (rollbackError) {
79+
errors.push(rollbackError);
80+
}
81+
}
82+
return errors;
83+
}
7484

7585
function applyOneMutation(
7686
projectDir: string,
7787
mutation: PreparedMutation,
7888
requestToken: string | undefined,
79-
writeFile: (path: string, content: string, encoding: "utf-8") => void,
80-
attempted: Array<PreparedMutation & { version: string; writeToken: string; written: boolean }>,
89+
writeFile: WriteFile,
90+
attempted: AttemptedMutation[],
8191
): AppliedFileMutation {
8292
const current = readFileSync(mutation.absPath, "utf-8");
8393
assertExpectedVersion(mutation, current);

0 commit comments

Comments
 (0)