Skip to content
TypeScript

fix(mobile): remove orphaned temp files after atomic write failures (#20736)

Kevin Rajanc15a793282f3
diff --git a/apps/mobile/src/lib/atomic-file.test.ts b/apps/mobile/src/lib/atomic-file.test.ts
new file mode 100644
index 00000000000..deb7c217b2f
--- /dev/null
+++ b/apps/mobile/src/lib/atomic-file.test.ts
@@ -0,0 +1,111 @@
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const files = new Map<string, { text: string; deleted: boolean }>();
+const failMode = vi.hoisted(() => ({
+ current: "none" as "none" | "write" | "move",
+ cleanupFails: false,
+}));
+
+vi.mock("expo-file-system", () => ({
+ File: class {
+ readonly uri: string;
+ readonly name: string;
+ readonly parentDirectory: { readonly uri: string };
+
+ constructor(parent: string | { readonly uri: string }, name?: string) {
+ const parentUri = typeof parent === "string" ? parent : parent.uri;
+ this.uri = name ? `${parentUri}/${name}` : parentUri;
+ this.name = name ?? this.uri.split("/").at(-1) ?? "file";
+ this.parentDirectory = { uri: parentUri };
+ }
+
+ get exists(): boolean {
+ return files.has(this.uri) && files.get(this.uri)?.deleted === false;
+ }
+
+ create(): void {
+ files.set(this.uri, { text: "", deleted: false });
+ }
+
+ async write(text: string): Promise<void> {
+ await Promise.resolve(); // Exercise asynchronous file-write rejection.
+ if (failMode.current === "write") throw new Error("disk full");
+ files.set(this.uri, { text, deleted: false });
+ }
+
+ moveSync(destination: { readonly uri: string }): void {
+ if (failMode.current === "move") throw new Error("rename failed");
+ const entry = files.get(this.uri);
+ if (!entry) throw new Error("missing staged file");
+ files.set(destination.uri, entry);
+ files.delete(this.uri);
+ }
+
+ delete(): void {
+ if (failMode.cleanupFails) throw new Error("cleanup failed");
+ if (!files.has(this.uri)) throw new Error("missing file");
+ files.delete(this.uri);
+ }
+ },
+}));
+
+import { writeFileAtomically } from "./atomic-file";
+import { File as ExpoFile } from "expo-file-system";
+
+const DIRECTORY_URI = "file:///documents/thread-outbox";
+
+function tempFileUris(): Array<string> {
+ return [...files.keys()].filter(
+ (uri) => uri.startsWith(`${DIRECTORY_URI}/`) && uri.endsWith(".tmp"),
+ );
+}
+
+function makeFile(name: string): ExpoFile {
+ return new ExpoFile(DIRECTORY_URI, name);
+}
+
+describe("writeFileAtomically", () => {
+ beforeEach(() => {
+ files.clear();
+ failMode.current = "none";
+ failMode.cleanupFails = false;
+ });
+
+ it("lands contents at the final path and leaves no temp file behind", async () => {
+ const file = makeFile("message.json");
+ await writeFileAtomically(file, '{"ok":true}');
+ expect(files.get(file.uri)?.text).toBe('{"ok":true}');
+ expect(tempFileUris()).toEqual([]);
+ });
+
+ it("removes its staging file when the write fails", async () => {
+ failMode.current = "write";
+ const file = makeFile("message.json");
+ await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow("disk full");
+ expect(tempFileUris()).toEqual([]);
+ });
+
+ it("removes its staging file when the rename fails", async () => {
+ failMode.current = "move";
+ const file = makeFile("message.json");
+ await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow("rename failed");
+ expect(tempFileUris()).toEqual([]);
+ expect(files.has(file.uri)).toBe(false);
+ });
+
+ it("preserves the original error when cleanup also fails", async () => {
+ failMode.current = "write";
+ failMode.cleanupFails = true;
+ const file = makeFile("message.json");
+ await expect(writeFileAtomically(file, "{}")).rejects.toThrow("disk full");
+ });
+
+ it("does not accumulate a temp file per retry", async () => {
+ failMode.current = "write";
+ const file = makeFile("message.json");
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow();
+ }
+ expect(tempFileUris()).toEqual([]);
+ });
+});
diff --git a/apps/mobile/src/lib/atomic-file.ts b/apps/mobile/src/lib/atomic-file.ts
index f4318b6e068..a6ed504c707 100644
--- a/apps/mobile/src/lib/atomic-file.ts
+++ b/apps/mobile/src/lib/atomic-file.ts
@@ -5,12 +5,22 @@ let tempFileSequence = 0;
/**
* Each write stages through its own temp file so concurrent writers to the same
* destination cannot move or clobber each other's staging file mid-flight.
+ * A failed write must clean up its own staging file so retries do not leak it.
*/
export async function writeFileAtomically(file: File, contents: string): Promise<void> {
const { File: FileConstructor } = await import("expo-file-system");
tempFileSequence += 1;
const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
- temp.create({ intermediates: true, overwrite: true });
- await temp.write(contents);
- temp.moveSync(file, { overwrite: true });
+ try {
+ temp.create({ intermediates: true, overwrite: true });
+ await temp.write(contents);
+ temp.moveSync(file, { overwrite: true });
+ } catch (error) {
+ try {
+ if (temp.exists) temp.delete();
+ } catch {
+ // Preserve the original write failure even if best-effort cleanup fails.
+ }
+ throw error;
+ }
}