Skip to content

Commit 120dbb0

Browse files
only21milcodexmaria-rcks
authored
fix(mobile): recover incoming shares after interrupted writes (#22115)
Co-authored-by: GPT-6.1 Sol <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent f2417cd commit 120dbb0

2 files changed

Lines changed: 243 additions & 20 deletions

File tree

‎apps/mobile/src/features/sharing/incoming-share-storage.test.ts‎

Lines changed: 202 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,116 @@ import { afterEach, describe, expect, it } from "@effect/vitest";
22
import { vi } from "vite-plus/test";
33

44
const fileSystemMocks = vi.hoisted(() => {
5-
let entries: File[] = [];
5+
const files = new Map<string, string>();
6+
let failNextWrite = false;
7+
let failRelocationTo = "";
8+
let snapshots: Map<string, string>[] | undefined;
9+
const record = () => snapshots?.push(new Map(files));
610

711
class File {
8-
readonly exists = true;
12+
name: string;
13+
readonly parentDirectory: Directory;
14+
readonly contents: string;
915

10-
constructor(
11-
readonly name: string,
12-
private readonly contents: string,
13-
) {}
16+
constructor(parent: string | Directory, nameOrContents: string) {
17+
this.name = typeof parent === "string" ? parent : nameOrContents;
18+
this.parentDirectory = typeof parent === "string" ? new Directory() : parent;
19+
this.contents = typeof parent === "string" ? nameOrContents : "";
20+
}
21+
22+
get exists(): boolean {
23+
return files.has(this.name);
24+
}
25+
26+
create(): void {
27+
files.set(this.name, "");
28+
record();
29+
}
30+
31+
async write(contents: string): Promise<void> {
32+
files.set(this.name, contents.slice(0, 1));
33+
record();
34+
if (failNextWrite) {
35+
failNextWrite = false;
36+
throw new Error("interrupted write");
37+
}
38+
files.set(this.name, contents);
39+
record();
40+
}
41+
42+
copySync(destination: File): void {
43+
files.delete(destination.name);
44+
record();
45+
files.set(destination.name, files.get(this.name)!.slice(0, 1));
46+
record();
47+
if (destination.name.endsWith(failRelocationTo) && failRelocationTo) {
48+
failRelocationTo = "";
49+
throw new Error("copy failed after partial destination write");
50+
}
51+
files.set(destination.name, files.get(this.name)!);
52+
record();
53+
}
54+
55+
moveSync(destination: File): void {
56+
// Expo removes the destination before attempting the native move.
57+
files.delete(destination.name);
58+
record();
59+
if (destination.name.endsWith(failRelocationTo) && failRelocationTo) {
60+
failRelocationTo = "";
61+
throw new Error("move failed after destination removal");
62+
}
63+
// Android can fall back to copy-and-delete after native moves fail.
64+
files.set(destination.name, files.get(this.name)!.slice(0, 1));
65+
record();
66+
if (failRelocationTo === "partial") {
67+
failRelocationTo = "";
68+
throw new Error("move failed during fallback copy");
69+
}
70+
files.set(destination.name, files.get(this.name)!);
71+
files.delete(this.name);
72+
this.name = destination.name;
73+
record();
74+
}
75+
76+
delete(): void {
77+
files.delete(this.name);
78+
record();
79+
}
1480

1581
async text(): Promise<string> {
16-
return this.contents;
82+
return files.get(this.name)!;
1783
}
1884
}
1985

2086
class Directory {
2187
create(): void {}
2288

2389
list(): ReadonlyArray<File> {
24-
return entries;
90+
return [...files].map(([name, contents]) => new File(name, contents));
2591
}
2692
}
2793

2894
return {
2995
Directory,
3096
File,
97+
failNextWrite() {
98+
failNextWrite = true;
99+
},
100+
failRelocationTo(suffix: string) {
101+
failRelocationTo = suffix;
102+
},
103+
trackOperations() {
104+
snapshots = [];
105+
return snapshots;
106+
},
31107
setEntries(next: File[]) {
32-
entries = next;
108+
files.clear();
109+
for (const file of next) {
110+
files.set(file.name, file.contents);
111+
}
112+
failNextWrite = false;
113+
failRelocationTo = "";
114+
snapshots = undefined;
33115
},
34116
};
35117
});
@@ -40,7 +122,12 @@ vi.mock("expo-file-system", () => ({
40122
Paths: { document: "/documents" },
41123
}));
42124

43-
import { loadIncomingShareDrafts } from "./incoming-share-storage";
125+
import {
126+
IncomingShareStorageError,
127+
loadIncomingShareDrafts,
128+
removeIncomingShareDraft,
129+
writeIncomingShareDraft,
130+
} from "./incoming-share-storage";
44131

45132
const VALID_DRAFT = {
46133
schemaVersion: 1,
@@ -67,4 +154,109 @@ describe("incoming share storage", () => {
67154
await expect(loadIncomingShareDrafts()).resolves.toEqual([VALID_DRAFT]);
68155
expect(warning).toHaveBeenCalledOnce();
69156
});
157+
158+
it.each(["write", "partial"])("retries an interrupted initial %s", async (failure) => {
159+
if (failure === "write") fileSystemMocks.failNextWrite();
160+
else fileSystemMocks.failRelocationTo(failure);
161+
162+
await expect(writeIncomingShareDraft(VALID_DRAFT)).rejects.toMatchObject({
163+
operation: "write",
164+
shareId: VALID_DRAFT.id,
165+
});
166+
vi.spyOn(console, "warn").mockImplementation(() => undefined);
167+
await expect(loadIncomingShareDrafts()).resolves.toEqual([]);
168+
169+
await writeIncomingShareDraft(VALID_DRAFT);
170+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
171+
});
172+
173+
it("preserves a saved share when its reservation write fails and allows retrying", async () => {
174+
await writeIncomingShareDraft(VALID_DRAFT);
175+
const reserved = {
176+
...VALID_DRAFT,
177+
destination: { environmentId: "env-1", projectId: "project-1" },
178+
};
179+
fileSystemMocks.failNextWrite();
180+
181+
await expect(writeIncomingShareDraft(reserved)).rejects.toBeInstanceOf(
182+
IncomingShareStorageError,
183+
);
184+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
185+
186+
await writeIncomingShareDraft(reserved);
187+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([reserved]);
188+
});
189+
190+
it("removes staging and backup files after a successful replacement", async () => {
191+
await writeIncomingShareDraft(VALID_DRAFT);
192+
const updated = { ...VALID_DRAFT, text: "Updated" };
193+
194+
await writeIncomingShareDraft(updated);
195+
196+
expect(new fileSystemMocks.Directory().list().map((file) => file.name)).toEqual([
197+
`${VALID_DRAFT.id}.json`,
198+
]);
199+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([updated]);
200+
});
201+
202+
it("keeps a successful replacement when backup cleanup fails", async () => {
203+
await writeIncomingShareDraft(VALID_DRAFT);
204+
const updated = { ...VALID_DRAFT, text: "Updated" };
205+
vi.spyOn(fileSystemMocks.File.prototype, "delete").mockImplementationOnce(() => {
206+
throw new Error("backup cleanup failed");
207+
});
208+
209+
await expect(writeIncomingShareDraft(updated)).resolves.toBeUndefined();
210+
211+
expect(new fileSystemMocks.File(`${VALID_DRAFT.id}.json.bak`, "").exists).toBe(true);
212+
expect(new fileSystemMocks.File(`${VALID_DRAFT.id}.json.tmp`, "").exists).toBe(false);
213+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([updated]);
214+
});
215+
216+
it.each([".bak", ".json", "partial"])(
217+
"recovers after a failed replacement of %s",
218+
async (suffix) => {
219+
await writeIncomingShareDraft(VALID_DRAFT);
220+
fileSystemMocks.failRelocationTo(suffix);
221+
222+
await expect(
223+
writeIncomingShareDraft({ ...VALID_DRAFT, text: "Updated" }),
224+
).rejects.toBeInstanceOf(IncomingShareStorageError);
225+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
226+
227+
// A second failed write must not damage a backup left by the failed move.
228+
fileSystemMocks.failNextWrite();
229+
await expect(writeIncomingShareDraft(VALID_DRAFT)).rejects.toBeInstanceOf(
230+
IncomingShareStorageError,
231+
);
232+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
233+
fileSystemMocks.failRelocationTo(".json");
234+
await expect(writeIncomingShareDraft(VALID_DRAFT)).rejects.toBeInstanceOf(
235+
IncomingShareStorageError,
236+
);
237+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
238+
await writeIncomingShareDraft(VALID_DRAFT);
239+
await removeIncomingShareDraft(VALID_DRAFT.id);
240+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([]);
241+
},
242+
);
243+
244+
it("loads one complete share after interruption at each replacement operation", async () => {
245+
await writeIncomingShareDraft(VALID_DRAFT);
246+
const updated = { ...VALID_DRAFT, text: "Updated" };
247+
const snapshots = fileSystemMocks.trackOperations();
248+
await writeIncomingShareDraft(updated);
249+
250+
for (const snapshot of snapshots) {
251+
fileSystemMocks.setEntries(
252+
[...snapshot].map(([name, contents]) => new fileSystemMocks.File(name, contents)),
253+
);
254+
const loaded = await loadIncomingShareDrafts({ strict: true });
255+
expect(loaded).toHaveLength(1);
256+
expect([VALID_DRAFT, updated]).toContainEqual(loaded[0]);
257+
await removeIncomingShareDraft(VALID_DRAFT.id);
258+
await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([]);
259+
}
260+
expect(snapshots.length).toBeGreaterThan(0);
261+
});
70262
});

‎apps/mobile/src/features/sharing/incoming-share-storage.ts‎

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as Schema from "effect/Schema";
2+
import type { File } from "expo-file-system";
23

34
import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";
45

@@ -28,9 +29,23 @@ async function getDirectory() {
2829
return directory;
2930
}
3031

31-
async function getFile(shareId: string) {
32+
async function getFile(shareId: string, suffix = "") {
3233
const { File } = await import("expo-file-system");
33-
return new File(await getDirectory(), fileName(shareId));
34+
return new File(await getDirectory(), `${fileName(shareId)}${suffix}`);
35+
}
36+
37+
async function readSavedDraft(file: File) {
38+
try {
39+
return { file, draft: decodeIncomingShareDraft(JSON.parse(await file.text()) as unknown) };
40+
} catch (cause) {
41+
const { File } = await import("expo-file-system");
42+
const backup = new File(file.parentDirectory, `${file.name}.bak`);
43+
if (!backup.exists) throw cause;
44+
return {
45+
file: backup,
46+
draft: decodeIncomingShareDraft(JSON.parse(await backup.text()) as unknown),
47+
};
48+
}
3449
}
3550

3651
export async function loadIncomingShareDrafts(options?: {
@@ -40,11 +55,14 @@ export async function loadIncomingShareDrafts(options?: {
4055
const { File } = await import("expo-file-system");
4156
const drafts: IncomingShareDraft[] = [];
4257
for (const entry of (await getDirectory()).list()) {
43-
if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
58+
if (!(entry instanceof File)) continue;
59+
if (entry.name.endsWith(".json.bak")) {
60+
if (new File(entry.parentDirectory, entry.name.slice(0, -4)).exists) continue;
61+
} else if (!entry.name.endsWith(".json")) {
4462
continue;
4563
}
4664
try {
47-
drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown));
65+
drafts.push((await readSavedDraft(entry)).draft);
4866
} catch (cause) {
4967
const error = new IncomingShareStorageError({ operation: "load", shareId: null, cause });
5068
if (options?.strict) {
@@ -65,20 +83,33 @@ export async function loadIncomingShareDrafts(options?: {
6583
export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise<void> {
6684
try {
6785
const file = await getFile(draft.id);
68-
if (!file.exists) {
69-
file.create({ intermediates: true, overwrite: true });
86+
const backup = await getFile(draft.id, ".bak");
87+
const temp = await getFile(draft.id, ".tmp");
88+
// Inbox mutations are serialized, so each share can reuse its staging path.
89+
temp.create({ intermediates: true, overwrite: true });
90+
await temp.write(JSON.stringify(draft));
91+
// Expo can remove or partially copy the destination before a move fails.
92+
if (file.exists) {
93+
const saved = await readSavedDraft(file).catch(() => undefined);
94+
if (!saved || saved.file === file) file.copySync(backup, { overwrite: true });
95+
}
96+
temp.moveSync(file, { overwrite: true });
97+
try {
98+
if (backup.exists) backup.delete();
99+
} catch {
100+
// The installed JSON is authoritative even if backup cleanup fails.
70101
}
71-
await file.write(JSON.stringify(draft));
72102
} catch (cause) {
73103
throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause });
74104
}
75105
}
76106

77107
export async function removeIncomingShareDraft(shareId: string): Promise<void> {
78108
try {
79-
const file = await getFile(shareId);
80-
if (file.exists) {
81-
file.delete();
109+
// Delete the backup first so a failed removal cannot resurrect a consumed share.
110+
for (const suffix of [".tmp", ".bak", ""]) {
111+
const file = await getFile(shareId, suffix);
112+
if (file.exists) file.delete();
82113
}
83114
} catch (cause) {
84115
throw new IncomingShareStorageError({ operation: "remove", shareId, cause });

0 commit comments

Comments
 (0)