Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

incoming-share-storage.ts

117 lines4.2 KB

1import * as Schema from "effect/Schema";
2import type { File } from "expo-file-system";
3​
4import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";
5​
6const INCOMING_SHARE_DIRECTORY = "incoming-shares";
7​
8export class IncomingShareStorageError extends Schema.TaggedError<IncomingShareStorageError>()(
9 "IncomingShareStorageError",
10 {
11 operation: Schema.Literals(["load", "write", "remove"]),
12 shareId: Schema.NullOr(Schema.String),
13 cause: Schema.Defect(),
14 },
15) {
16 override get message(): string {
17 return `Incoming share storage operation ${this.operation} failed for ${this.shareId ?? "unknown"}.`;
18 }
20​
21function fileName(shareId: string): string {
22 return `${encodeURIComponent(shareId)}.json`;
24​
25async function getDirectory() {
26 const { Directory, Paths } = await import("expo-file-system");
27 const directory = new Directory(Paths.document, INCOMING_SHARE_DIRECTORY);
28 directory.create({ idempotent: true, intermediates: true });
29 return directory;
31​
32async function getFile(shareId: string, suffix = "") {
33 const { File } = await import("expo-file-system");
34 return new File(await getDirectory(), `${fileName(shareId)}${suffix}`);
36​
37async 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 }
50​
51export async function loadIncomingShareDrafts(options?: {
52 readonly strict?: boolean;
53}): Promise<ReadonlyArray<IncomingShareDraft>> {
54 try {
55 const { File } = await import("expo-file-system");
56 const drafts: IncomingShareDraft[] = [];
57 for (const entry of (await getDirectory()).list()) {
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")) {
62 continue;
63 }
64 try {
65 drafts.push((await readSavedDraft(entry)).draft);
66 } catch (cause) {
67 const error = new IncomingShareStorageError({ operation: "load", shareId: null, cause });
68 if (options?.strict) {
69 throw error;
70 }
71 console.warn("[incoming-share] ignored invalid persisted share", error);
72 }
73 }
74 return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
75 } catch (cause) {
76 if (cause instanceof IncomingShareStorageError) {
77 throw cause;
78 }
79 throw new IncomingShareStorageError({ operation: "load", shareId: null, cause });
80 }
82​
83export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise<void> {
84 try {
85 const file = await getFile(draft.id);
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.
101 }
102 } catch (cause) {
103 throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause });
104 }
106​
107export async function removeIncomingShareDraft(shareId: string): Promise<void> {
108 try {
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();
113 }
114 } catch (cause) {
115 throw new IncomingShareStorageError({ operation: "remove", shareId, cause });
116 }