Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(android): serialize local database writes during image sharing

tianma-ifae536431ec02
diff --git a/apps/mobile/src/lib/local-mirror.ts b/apps/mobile/src/lib/local-mirror.ts
index 5bbbe250..7098ee36 100644
--- a/apps/mobile/src/lib/local-mirror.ts
+++ b/apps/mobile/src/lib/local-mirror.ts
@@ -9,6 +9,7 @@ import {
type TagSummary,
} from "@edgeever/shared";
import * as SQLite from "expo-sqlite";
+import { serializeMobileDatabaseWrites } from "./mobile-database-access";
import { filterLocalMemosByExactTag, summarizeMobileTags } from "./mobile-tags";
const DATABASE_NAME = "edgeever-mobile.db";
@@ -16,7 +17,7 @@ const BOOTSTRAP_PAGE_SIZE = 200;
const BOOTSTRAP_WRITE_BATCH_SIZE = 50;
const CHANGE_PAGE_SIZE = 200;
-let databasePromise: Promise<SQLite.SQLiteDatabase> | null = null;
+let databasePromise: Promise<ReturnType<typeof serializeMobileDatabaseWrites>> | null = null;
const syncPromises = new Map<string, Promise<number>>();
type StoredMemoRow = { data_json: string };
@@ -390,12 +391,12 @@ const getDatabase = async () => {
PRIMARY KEY (scope, temporary_id)
);
`);
- return db;
+ return serializeMobileDatabaseWrites(db);
});
return databasePromise;
};
-const upsertNotebook = (db: SQLite.SQLiteDatabase, scope: string, notebook: Notebook) =>
+const upsertNotebook = (db: Pick<SQLite.SQLiteDatabase, "runAsync">, scope: string, notebook: Notebook) =>
db.runAsync(
`INSERT OR REPLACE INTO mobile_notebooks (scope, id, name, sort_order, data_json) VALUES (?, ?, ?, ?, ?)`,
scope,
@@ -405,7 +406,7 @@ const upsertNotebook = (db: SQLite.SQLiteDatabase, scope: string, notebook: Note
JSON.stringify(notebook)
);
-const upsertMemo = (db: SQLite.SQLiteDatabase, scope: string, memo: MemoDetail) =>
+const upsertMemo = (db: Pick<SQLite.SQLiteDatabase, "runAsync">, scope: string, memo: MemoDetail) =>
db.runAsync(
`INSERT OR REPLACE INTO mobile_memos
(scope, id, notebook_id, title, content_text, tags_text, is_pinned, is_deleted, created_at, updated_at, deleted_at, data_json)
@@ -424,14 +425,14 @@ const upsertMemo = (db: SQLite.SQLiteDatabase, scope: string, memo: MemoDetail)
JSON.stringify(memo)
);
-const setCursor = (db: SQLite.SQLiteDatabase, scope: string, cursor: number) =>
+const setCursor = (db: Pick<SQLite.SQLiteDatabase, "runAsync">, scope: string, cursor: number) =>
db.runAsync(
`INSERT OR REPLACE INTO mobile_sync_meta (scope, key, value) VALUES (?, 'cursor', ?)`,
scope,
String(cursor)
);
-const setSyncIdentity = (db: SQLite.SQLiteDatabase, scope: string, identity: string) =>
+const setSyncIdentity = (db: Pick<SQLite.SQLiteDatabase, "runAsync">, scope: string, identity: string) =>
db.runAsync(
`INSERT OR REPLACE INTO mobile_sync_meta (scope, key, value) VALUES (?, 'identity', ?)`,
scope,
diff --git a/apps/mobile/src/lib/mobile-database-access.test.ts b/apps/mobile/src/lib/mobile-database-access.test.ts
new file mode 100644
index 00000000..bf07fb2b
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-database-access.test.ts
@@ -0,0 +1,89 @@
+import { expect, test } from "bun:test";
+import type { SQLiteDatabase } from "expo-sqlite";
+import { serializeMobileDatabaseWrites } from "./mobile-database-access";
+
+const deferred = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ return { promise, resolve };
+};
+
+const fixture = () => {
+ const entered = deferred();
+ const release = deferred();
+ let locked = false;
+ const writes: string[] = [];
+ const raw = {
+ runAsync: async (sql: string) => {
+ if (locked) throw new Error("NativeStatement.finalizeAsync: database is locked");
+ writes.push(sql);
+ return { changes: 1, lastInsertRowId: 1 };
+ },
+ getFirstAsync: async () => ({ value: "previous snapshot" }),
+ getAllAsync: async () => [],
+ withExclusiveTransactionAsync: async (task: (tx: SQLiteDatabase) => Promise<void>) => {
+ if (locked) throw new Error("database is locked");
+ locked = true;
+ entered.resolve();
+ await release.promise;
+ try {
+ // Raw transaction statements must bypass the outer queue.
+ await task({ runAsync: async (sql: string) => { writes.push(sql); } } as SQLiteDatabase);
+ } finally {
+ locked = false;
+ }
+ },
+ };
+ return {
+ db: serializeMobileDatabaseWrites(raw as unknown as SQLiteDatabase),
+ entered, release, writes,
+ };
+};
+
+test("share materialization and other scopes wait for the whole sync transaction", async () => {
+ const { db, entered, release, writes } = fixture();
+ const sync = db.withExclusiveTransactionAsync(async (tx) => {
+ await tx.runAsync("sync memo");
+ await tx.runAsync("sync cursor");
+ });
+ await entered.promise;
+ const share = db.runAsync("shared image memo");
+ const otherAccount = db.withExclusiveTransactionAsync(async (tx) => {
+ await tx.runAsync("other account sync");
+ });
+ // WAL readers remain available while the writer is busy.
+ expect(await db.getFirstAsync("read memo")).toEqual({ value: "previous snapshot" });
+ expect(writes).toEqual([]);
+ release.resolve();
+ await Promise.all([sync, share, otherAccount]);
+ expect(writes).toEqual(["sync memo", "sync cursor", "shared image memo", "other account sync"]);
+});
+
+test("a rejected transaction does not prevent subsequent attachment saves", async () => {
+ const { db, release, writes } = fixture();
+ release.resolve();
+ const failed = db.withExclusiveTransactionAsync(async () => { throw new Error("rollback"); });
+ const save = db.runAsync("attachment memo");
+ await expect(failed).rejects.toThrow("rollback");
+ await save;
+ expect(writes).toEqual(["attachment memo"]);
+});
+
+test("a failed standalone write reaches the caller and later writes still run", async () => {
+ const error = new Error("disk full");
+ let calls = 0;
+ const db = serializeMobileDatabaseWrites({
+ runAsync: async () => {
+ if (++calls === 1) throw error;
+ return { changes: 1, lastInsertRowId: 1 };
+ },
+ getFirstAsync: async () => null,
+ getAllAsync: async () => [],
+ withExclusiveTransactionAsync: async () => {},
+ } as unknown as SQLiteDatabase);
+ const failed = db.runAsync("first save");
+ const next = db.runAsync("next save");
+ await expect(failed).rejects.toBe(error);
+ expect(await next).toEqual({ changes: 1, lastInsertRowId: 1 });
+ expect(calls).toBe(2);
+});
diff --git a/apps/mobile/src/lib/mobile-database-access.ts b/apps/mobile/src/lib/mobile-database-access.ts
new file mode 100644
index 00000000..c874d96b
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-database-access.ts
@@ -0,0 +1,24 @@
+import type { SQLiteDatabase } from "expo-sqlite";
+
+type MobileDatabase = Pick<SQLiteDatabase, "getAllAsync" | "getFirstAsync" | "runAsync" | "withExclusiveTransactionAsync">;
+
+/** One writer per database, shared by every account scope. Never queue network work. */
+export const serializeMobileDatabaseWrites = (db: MobileDatabase): MobileDatabase => {
+ let pending: Promise<unknown> = Promise.resolve();
+ const write = <T>(operation: () => Promise<T>): Promise<T> => {
+ const result = pending.then(operation);
+ // A rejected write must reach its caller without poisoning subsequent saves.
+ pending = result.catch(() => undefined);
+ return result;
+ };
+
+ return {
+ getAllAsync: db.getAllAsync.bind(db),
+ getFirstAsync: db.getFirstAsync.bind(db),
+ runAsync: ((...args: Parameters<SQLiteDatabase["runAsync"]>) =>
+ write(() => db.runAsync(...args))) as SQLiteDatabase["runAsync"],
+ // Transaction statements use the raw transaction handle. Queuing those
+ // individually would deadlock behind their own enclosing transaction.
+ withExclusiveTransactionAsync: (task) => write(() => db.withExclusiveTransactionAsync(task)),
+ };
+};
diff --git a/apps/mobile/src/screens/WorkspaceEditors.tsx b/apps/mobile/src/screens/WorkspaceEditors.tsx
index 621435de..31fd8ec1 100644
--- a/apps/mobile/src/screens/WorkspaceEditors.tsx
+++ b/apps/mobile/src/screens/WorkspaceEditors.tsx
@@ -205,6 +205,7 @@ export const CreateMemoModal = ({
const sharedImagesHandledRef = useRef(false);
const [importingSharedImages, setImportingSharedImages] = useState(initialSharedImages.length > 0);
const [sharedImageImportFailed, setSharedImageImportFailed] = useState(false);
+ const failedSharedImageUrisRef = useRef(new Set<string>());
const shareHandoffStartedRef = useRef(false);
const createPendingRef = useRef(false);
const submitStartedRef = useRef(false);
@@ -540,10 +541,21 @@ export const CreateMemoModal = ({
if (resource.kind === "image" && !keepBusy) {
safeDomCall(() => editorRef.current?.finishImageBatch([resource.url]));
}
+ failedSharedImageUrisRef.current.delete(asset.uri);
+ setSharedImageImportFailed(failedSharedImageUrisRef.current.size > 0);
return resource.kind === "image" ? resource.url : null;
} catch (error) {
cancelMobileEditorUpload(editorRef, uploadId);
- Alert.alert("附件上传失败", error instanceof Error ? error.message : "请检查网络连接后重试");
+ if (asset && initialSharedImages.some((image) => image.uri === asset.uri)) {
+ failedSharedImageUrisRef.current.add(asset.uri);
+ setSharedImageImportFailed(true);
+ }
+ Alert.alert("附件上传失败", error instanceof Error ? error.message : "请检查网络连接后重试", [
+ { text: "取消", style: "cancel" },
+ // Keep the source asset in this editor so retrying does not require
+ // sharing again or creating another remote memo.
+ { text: "重试", onPress: () => { void uploadImageAsset(asset); } },
+ ]);
} finally {
if (!keepBusy) setImageOperation("idle");
}