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: improve stability
Adorian Doran226888391fad
diff --git a/apps/standalone/src/lightweight/database_restore.spec.ts b/apps/standalone/src/lightweight/database_restore.spec.tsindex eafdfba0e3..1512c94997 100644--- a/apps/standalone/src/lightweight/database_restore.spec.ts+++ b/apps/standalone/src/lightweight/database_restore.spec.ts@@ -350,6 +350,69 @@ describe("a backup that cannot be restored", () => {expect(handles.paused).toBe(0);});+ it("takes the handles back mid-import and starts the import over", async () => {+ const { pool, files, handles } = fakePool();+ const { target, acted } = fakeTarget(pool);+ const original = databaseBytes();+ // Closed while the backup was being read, which is the suspension this cannot otherwise+ // survive: the database being replaced is still open, so the pool cannot even be paused+ // until it is let go of.+ let imports = 0;+ const importDb = pool.importDb.bind(pool);+ pool.importDb = async (name, pull) => {+ if (imports++ === 0) {+ handles.closed = true;+ throw closedAccessHandle();+ }++ return importDb(name, pull);+ };++ await restoreDatabase(target, new Blob([ original ]));++ expect(files.get(CANDIDATE_NAME)).toEqual(original);+ expect(imports).toBe(2);+ // Let go of, taken back, put straight back: the screen behind the restore still reads from+ // the database that has not been replaced yet.+ expect(acted.slice(0, 2)).toEqual([ "close", `open:${DEFAULT_DATABASE_NAME}` ]);+ expect(handles).toMatchObject({ paused: 1, unpaused: 1 });+ expect(pointer).toBe(CANDIDATE_NAME);+ });++ it("takes the handles back mid-check rather than calling the backup damaged", async () => {+ const { pool, handles } = fakePool();+ const { target } = fakeTarget(pool);+ const answered = { times: 0 };+ const tables = pool.OpfsSAHPoolDb.prototype.selectValues;+ pool.OpfsSAHPoolDb.prototype.selectValues = function (sql: string) {+ if (answered.times++ === 0) {+ handles.closed = true;+ throw closedAccessHandle();+ }++ return tables.call(this, sql);+ };++ await restoreDatabase(target, new Blob([ databaseBytes() ]));++ expect(handles).toMatchObject({ paused: 1, unpaused: 1 });+ expect(pointer).toBe(CANDIDATE_NAME);+ });++ it("reports what stopped an import that no recovery could help", async () => {+ const { pool, handles } = fakePool();+ const { target } = fakeTarget(pool);+ pool.importDb = async () => {+ throw new Error("the pool is full");+ };++ await expect(restoreDatabase(target, new Blob([ databaseBytes() ])))+ .rejects.toMatchObject({ message: expect.stringContaining("the pool is full") });++ // Nothing to take back, so nothing was let go of either.+ 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 adiff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.tsindex bd1459319f..171c7114ac 100644--- a/apps/standalone/src/lightweight/database_restore.ts+++ b/apps/standalone/src/lightweight/database_restore.ts@@ -106,11 +106,12 @@ export async function restoreDatabase(try {report({ stage: "staging" });- await stageCandidate(target.pool, candidate, backup, options.passphrase, (fraction) =>- report({ stage: "staging", fraction }));+ await keepingHandles(target, live, () =>+ stageCandidate(target.pool, candidate, backup, options.passphrase, (fraction) =>+ report({ stage: "staging", fraction })));report({ stage: "validating" });- const validation = validate(target.pool, candidate);+ const validation = await keepingHandles(target, live, async () => validate(target.pool, candidate));if (!validation.valid) {throw new RestoreFailure(validation.rejection, validation.message);}@@ -198,6 +199,13 @@ function validate(pool: SAHPoolUtil, candidate: string): DatabaseValidation {try {return validateDatabase(candidateOf(db), { skipIntegrityCheck: true });} catch (e) {+ // The browser taking the pool's handles away is not this database being damaged, and saying+ // so would condemn a backup that is perfectly good. Left to the caller, which can take them+ // back and ask again.+ if (isClosedAccessHandle(e)) {+ throw e;+ }+// What a database too damaged to query throws is this driver's business, not the checks'.return {valid: false,@@ -287,6 +295,48 @@ async function rollBackTo(return new RestoreFailure("swap-failed", messageOf(cause));}+/**+ * Runs `work`, and where the browser closed the pool's handles underneath it, takes them back and+ * runs it once more.+ *+ * This is for the part of a restore that happens before the swap, where the database being replaced+ * is still open and serving the screen behind all this. Taking the handles back means letting go of+ * it for a moment, since the pool refuses to be paused while anything is open at all, so it is+ * closed and opened again around the recovery.+ *+ * The retry starts the work over rather than resuming it, which for the import means reading the+ * backup from the beginning. That is worth it against the alternative: without it a restore that+ * was suspended halfway is simply lost, and the suspension is usually the user coming back to the+ * application rather than leaving it.+ *+ * @param live the database to put back, which is the one this restore has not replaced yet.+ */+async function keepingHandles<T>(+ target: RestoreTarget,+ live: string,+ work: () => Promise<T>+): Promise<T> {+ try {+ return await work();+ } catch (e) {+ if (!isClosedAccessHandle(e)) {+ throw e;+ }++ try {+ target.close();+ await reacquireAccessHandles(target.pool);+ target.open(live);+ } catch {+ // The handles could not be had back, so the failure to report is the one that was+ // actually hit rather than whatever went wrong trying to recover from it.+ throw e;+ }++ return await work();+ }+}+/*** Whether a failure is the browser having closed the pool's access handles underneath it.*