Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
standalone/backup: fix Safari's FileSystemSyncAccessHandle issue
Adorian Doran66764a7b6c03
diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsxindex 5baad69445..22971cea49 100644--- a/apps/client/src/setup_restore.tsx+++ b/apps/client/src/setup_restore.tsx@@ -318,6 +318,7 @@ function headlineFor(reason: string | undefined): string {case "database-too-old": return t("setup.restore-error-too-old");case "database-not-initialized": return t("setup.restore-error-unfinished");case "swap-failed": return t("setup.restore-error-swap-failed");+ case "swap-failed-reload": return t("setup.restore-error-swap-failed-reload");case "migration-failed": return t("setup.restore-error-would-not-open");case "restore-refused": return t("setup.restore-error-refused");case "already-initialized": return t("setup.restore-error-already-initialized");diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex bcb4d67ded..888a86cc4c 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3746,6 +3746,7 @@"restore-error-too-old": "This backup is from a version of Trilium that is too old to be restored.","restore-error-unfinished": "This backup was taken from a setup that was never finished, so there is nothing in it to restore.","restore-error-swap-failed": "The database could not be replaced. Your previous database is back in place.",+ "restore-error-swap-failed-reload": "The database could not be replaced. Your previous database is back in place, but Trilium could not reopen it. Reload this page to continue.","restore-error-would-not-open": "The restored database could not be opened. Your previous database is back in place.","restore-error-refused": "Another setup step is already running.","restore-error-already-initialized": "This instance already has a knowledge base, so it cannot be restored over. Reload the page.",diff --git a/apps/standalone/src/lightweight/database_restore.spec.ts b/apps/standalone/src/lightweight/database_restore.spec.tsindex 5bb7245938..eafdfba0e3 100644--- a/apps/standalone/src/lightweight/database_restore.spec.ts+++ b/apps/standalone/src/lightweight/database_restore.spec.ts@@ -94,12 +94,30 @@ function fakePool() {close() { /* nothing to release */ }}+ /**+ * Whether the browser has taken the pool's access handles away, and what it took to get them+ * back. A pool never notices the taking, which is the whole difficulty: only pausing clears its+ * belief that it still holds them.+ */+ const handles = { closed: false, paused: 0, unpaused: 0 };+const pool = {OpfsSAHPoolDb: FakeDb,getCapacity: () => 6,getFileCount: () => files.size,addCapacity: async () => 1,unlink: (name: string) => files.delete(name),+ pauseVfs() {+ handles.paused++;++ return pool;+ },+ async unpauseVfs() {+ handles.unpaused++;+ handles.closed = false;++ return pool;+ },importDb: async (name: string, pull: () => Promise<Uint8Array | undefined>) => {const chunks: Uint8Array[] = [];for (let chunk = await pull(); chunk; chunk = await pull()) {@@ -111,7 +129,12 @@ function fakePool() {}};- return { asked, files, answers, pool: pool as unknown as SAHPoolUtil };+ return { asked, files, answers, handles, pool: pool as unknown as SAHPoolUtil };+}++/** What WebKit throws once it has closed a sync access handle underneath the pool holding it. */+function closedAccessHandle(): DOMException {+ return new DOMException("AccessHandle is closed", "InvalidStateError");}function concat(chunks: Uint8Array[]): Uint8Array {@@ -127,12 +150,23 @@ function concat(chunks: Uint8Array[]): Uint8Array {}/** The database the restore acts on, recording what it was asked to do and in what order. */-function fakeTarget(pool: SAHPoolUtil, options: { failToOpen?: string } = {}) {+function fakeTarget(pool: SAHPoolUtil, options: {+ failToOpen?: string;+ /** Run before each open; throwing from it is how a test makes that open fail its own way. */+ beforeOpen?: (dbName: string) => void;+} = {}) {const acted: string[] = [];const target: RestoreTarget = {pool,close: () => { acted.push("close"); },open: (dbName) => {+ try {+ options.beforeOpen?.(dbName);+ } catch (e) {+ acted.push(`open-failed:${dbName}`);+ throw e;+ }+if (dbName === options.failToOpen) {acted.push(`open-failed:${dbName}`);throw new Error("database is locked");@@ -303,7 +337,7 @@ describe("a backup that cannot be restored", () => {});it("puts the previous database back when the restored one will not open", async () => {- const { pool } = fakePool();+ const { pool, handles } = fakePool();const { target, acted } = fakeTarget(pool, { failToOpen: CANDIDATE_NAME });await expect(restoreDatabase(target, new Blob([ databaseBytes() ])))@@ -311,5 +345,53 @@ describe("a backup that cannot be restored", () => {expect(acted).toEqual([ "close", `open-failed:${CANDIDATE_NAME}`, `open:${DEFAULT_DATABASE_NAME}` ]);expect(pointer).toBe(DEFAULT_DATABASE_NAME);+ // Tried once and not retried: the handles were never the problem, and an open refused for+ // any other reason is refused just the same the second time.+ expect(handles.paused).toBe(0);+ });++ it("takes the pool's access handles back where the browser has closed them, and opens", async () => {+ const { pool, handles } = fakePool();+ // Closed while the restore was working, which is what a file picker, a screen lock or a+ // switch to another application does on iOS. The pool is never told, so the open is what+ // finds out.+ const { target, acted } = fakeTarget(pool, {+ beforeOpen: () => {+ if (handles.closed) {+ throw closedAccessHandle();+ }+ }+ });+ handles.closed = true;++ await restoreDatabase(target, new Blob([ databaseBytes() ]));++ expect(acted).toEqual([ "close", `open-failed:${CANDIDATE_NAME}`, `open:${CANDIDATE_NAME}` ]);+ // Paused before unpausing: a pool whose handles were taken still believes it holds them, so+ // unpausing on its own would return having done nothing at all.+ expect(handles).toMatchObject({ paused: 1, unpaused: 1 });+ expect(pointer).toBe(CANDIDATE_NAME);+ });++ it("reports what stopped the swap, not what stopped the rollback, and asks for a reload", async () => {+ const { pool } = fakePool();+ // The candidate will not open, and the previous one cannot be reopened either. Both halves+ // failing is what used to leave the browser's own error standing in place of ours, over a+ // sentence promising the previous database was back.+ const { target } = fakeTarget(pool, {+ failToOpen: CANDIDATE_NAME,+ beforeOpen: (dbName) => {+ if (dbName === DEFAULT_DATABASE_NAME) {+ throw closedAccessHandle();+ }+ }+ });++ await expect(restoreDatabase(target, new Blob([ databaseBytes() ])))+ .rejects.toMatchObject({ reason: "swap-failed-reload", message: "database is locked" });++ // The pointer is the whole of what a start reads, so the notes that were here are still the+ // ones it opens; this instance just cannot get to them without one.+ expect(pointer).toBe(DEFAULT_DATABASE_NAME);});});diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.tsindex e6a45b6d6e..bd1459319f 100644--- a/apps/standalone/src/lightweight/database_restore.ts+++ b/apps/standalone/src/lightweight/database_restore.ts@@ -230,19 +230,92 @@ async function swapIn(target: RestoreTarget, previous: string, candidate: stringawait writeCurrentDatabaseName(candidate);try {- target.open(candidate);+ await openWithHandles(target, candidate);} catch (e) {// Put back what was live, so a candidate that will not open costs nothing.- await writeCurrentDatabaseName(previous);- target.open(previous);-- throw new RestoreFailure("swap-failed", messageOf(e));+ throw await rollBackTo(target, previous, e);}// Only once the restored database is open: until then the old one is what a restart needs.await removeQuietly(target.pool, previous);}+/**+ * Opens `dbName`, taking the pool's access handles back first where the browser has closed them.+ *+ * Retried once, and only for that: a database that will not open for any other reason will not open+ * the second time either, and the first failure is the one worth reporting.+ */+async function openWithHandles(target: RestoreTarget, dbName: string): Promise<void> {+ try {+ target.open(dbName);+ } catch (e) {+ if (!isClosedAccessHandle(e)) {+ throw e;+ }++ await reacquireAccessHandles(target.pool);+ target.open(dbName);+ }+}++/**+ * Puts the previous database back after a swap that did not take.+ *+ * The pointer is the whole of what decides which database a start opens, so restoring it is what+ * makes a failed swap harmless: whatever happens next, the notes are the ones that were here before.+ * Reopening it is the part that can fail again, since the handles the reopen needs may be the very+ * thing that was taken, and that failure must not replace the one being reported or the screen would+ * explain the wrong problem.+ */+async function rollBackTo(+ target: RestoreTarget,+ previous: string,+ cause: unknown+): Promise<RestoreFailure> {+ await writeCurrentDatabaseName(previous);++ try {+ await openWithHandles(target, previous);+ } catch {+ // The pointer is back, so a start comes up on the database that was here all along. This+ // instance simply cannot get there without one, which is the one thing the user has to be+ // told rather than left to discover.+ return new RestoreFailure("swap-failed-reload", messageOf(cause));+ }++ return new RestoreFailure("swap-failed", messageOf(cause));+}++/**+ * Whether a failure is the browser having closed the pool's access handles underneath it.+ *+ * WebKit closes them whenever it suspends the page: a file picker, a screen lock, a switch to+ * another application. The pool takes its handles once and holds them for its lifetime, so it never+ * learns they are gone, and the next operation against it fails with this.+ */+function isClosedAccessHandle(e: unknown): boolean {+ if (e instanceof DOMException && e.name === "InvalidStateError") {+ return true;+ }++ return /access\s*handle.*closed|closed.*access\s*handle/i.test(messageOf(e));+}++/**+ * Takes the pool's access handles back.+ *+ * The pause is the part that matters, and `isPaused` is no help in deciding whether to do it: it+ * reports what the pool did to itself, and a pool whose handles were taken from underneath it still+ * believes it holds them, so `unpauseVfs` on its own returns having done nothing. Pausing is what+ * clears that belief. It is refused while any database is open, which is why this belongs to the+ * moment between closing one and opening the next.+ */+async function reacquireAccessHandles(pool: SAHPoolUtil): Promise<void> {+ pool.pauseVfs();+ await pool.unpauseVfs();+}+/** Points the next start at `dbName`, which is the whole of what makes a database the live one. */export async function writeCurrentDatabaseName(dbName: string): Promise<void> {const root = await navigator.storage.getDirectory();