Skip to content

Commit 829ded7

Browse files
committed
fix(mobile): clean up atomic write staging files on failure
1 parent 2a337fe commit 829ded7

2 files changed

Lines changed: 121 additions & 3 deletions

File tree

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2+
3+
const files = new Map<string, { text: string; deleted: boolean }>();
4+
const failMode = vi.hoisted(() => ({ current: "none" as "none" | "write" | "move", cleanupFails: false }));
5+
6+
vi.mock("expo-file-system", () => ({
7+
File: class {
8+
readonly uri: string;
9+
readonly name: string;
10+
readonly parentDirectory: { readonly uri: string };
11+
12+
constructor(parent: string | { readonly uri: string }, name?: string) {
13+
const parentUri = typeof parent === "string" ? parent : parent.uri;
14+
this.uri = name ? `${parentUri}/${name}` : parentUri;
15+
this.name = name ?? this.uri.split("/").at(-1) ?? "file";
16+
this.parentDirectory = { uri: parentUri };
17+
}
18+
19+
get exists(): boolean {
20+
return files.has(this.uri) && files.get(this.uri)?.deleted === false;
21+
}
22+
23+
create(): void {
24+
files.set(this.uri, { text: "", deleted: false });
25+
}
26+
27+
async write(text: string): Promise<void> {
28+
await Promise.resolve(); // Exercise asynchronous file-write rejection.
29+
if (failMode.current === "write") throw new Error("disk full");
30+
files.set(this.uri, { text, deleted: false });
31+
}
32+
33+
moveSync(destination: { readonly uri: string }): void {
34+
if (failMode.current === "move") throw new Error("rename failed");
35+
const entry = files.get(this.uri);
36+
if (!entry) throw new Error("missing staged file");
37+
files.set(destination.uri, entry);
38+
files.delete(this.uri);
39+
}
40+
41+
delete(): void {
42+
if (failMode.cleanupFails) throw new Error("cleanup failed");
43+
if (!files.has(this.uri)) throw new Error("missing file");
44+
files.delete(this.uri);
45+
}
46+
},
47+
}));
48+
49+
import { writeFileAtomically } from "./atomic-file";
50+
import { File as ExpoFile } from "expo-file-system";
51+
52+
const DIRECTORY_URI = "file:///documents/thread-outbox";
53+
54+
function tempFileUris(): Array<string> {
55+
return [...files.keys()].filter(
56+
(uri) => uri.startsWith(`${DIRECTORY_URI}/`) && uri.endsWith(".tmp"),
57+
);
58+
}
59+
60+
function makeFile(name: string): ExpoFile {
61+
return new ExpoFile(DIRECTORY_URI, name);
62+
}
63+
64+
describe("writeFileAtomically", () => {
65+
beforeEach(() => {
66+
files.clear();
67+
failMode.current = "none";
68+
failMode.cleanupFails = false;
69+
});
70+
71+
it("lands contents at the final path and leaves no temp file behind", async () => {
72+
const file = makeFile("message.json");
73+
await writeFileAtomically(file, '{"ok":true}');
74+
expect(files.get(file.uri)?.text).toBe('{"ok":true}');
75+
expect(tempFileUris()).toEqual([]);
76+
});
77+
78+
it("removes its staging file when the write fails", async () => {
79+
failMode.current = "write";
80+
const file = makeFile("message.json");
81+
await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow("disk full");
82+
expect(tempFileUris()).toEqual([]);
83+
});
84+
85+
it("removes its staging file when the rename fails", async () => {
86+
failMode.current = "move";
87+
const file = makeFile("message.json");
88+
await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow("rename failed");
89+
expect(tempFileUris()).toEqual([]);
90+
expect(files.has(file.uri)).toBe(false);
91+
});
92+
93+
it("preserves the original error when cleanup also fails", async () => {
94+
failMode.current = "write";
95+
failMode.cleanupFails = true;
96+
const file = makeFile("message.json");
97+
await expect(writeFileAtomically(file, "{}")).rejects.toThrow("disk full");
98+
});
99+
100+
it("does not accumulate a temp file per retry", async () => {
101+
failMode.current = "write";
102+
const file = makeFile("message.json");
103+
for (let attempt = 0; attempt < 3; attempt += 1) {
104+
await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow();
105+
}
106+
expect(tempFileUris()).toEqual([]);
107+
});
108+
});

‎apps/mobile/src/lib/atomic-file.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,22 @@ let tempFileSequence = 0;
55
/**
66
* Each write stages through its own temp file so concurrent writers to the same
77
* destination cannot move or clobber each other's staging file mid-flight.
8+
* A failed write must clean up its own staging file so retries do not leak it.
89
*/
910
export async function writeFileAtomically(file: File, contents: string): Promise<void> {
1011
const { File: FileConstructor } = await import("expo-file-system");
1112
tempFileSequence += 1;
1213
const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
13-
temp.create({ intermediates: true, overwrite: true });
14-
await temp.write(contents);
15-
temp.moveSync(file, { overwrite: true });
14+
try {
15+
temp.create({ intermediates: true, overwrite: true });
16+
await temp.write(contents);
17+
temp.moveSync(file, { overwrite: true });
18+
} catch (error) {
19+
try {
20+
if (temp.exists) temp.delete();
21+
} catch {
22+
// Preserve the original write failure even if best-effort cleanup fails.
23+
}
24+
throw error;
25+
}
1626
}

0 commit comments

Comments
 (0)