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 error handling and reporting
Adorian Doran8c2af209e6b0
diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsxindex 22971cea49..03f81d2896 100644--- a/apps/client/src/setup_restore.tsx+++ b/apps/client/src/setup_restore.tsx@@ -319,6 +319,8 @@ function headlineFor(reason: string | undefined): string {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 "check-failed": return t("setup.restore-error-check-failed");+ case "restore-failed": return t("setup.restore-error-failed");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 888a86cc4c..f9b1ba23c5 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3747,6 +3747,8 @@"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-check-failed": "The backup could not be checked. This may be a problem on this device rather than with the backup itself, so it is worth trying again.",+ "restore-error-failed": "The restore could not be completed. Nothing was replaced, so your knowledge base is as it was.","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 1512c94997..7724a47073 100644--- a/apps/standalone/src/lightweight/database_restore.spec.ts+++ b/apps/standalone/src/lightweight/database_restore.spec.ts@@ -180,9 +180,12 @@ function fakeTarget(pool: SAHPoolUtil, options: {/** Stands in for the origin's private filesystem, which is where the pointer lives. */let pointer: string | undefined;+/** Set by a test to make writing the pointer fail, which is the one write nothing else can repair. */+let refusePointer: ((name: string) => boolean) | undefined;beforeEach(() => {pointer = undefined;+ refusePointer = undefined;vi.stubGlobal("navigator", {storage: {getDirectory: async () => ({@@ -194,7 +197,12 @@ beforeEach(() => {return {getFile: async () => ({ text: async () => pointer ?? "" }),createWritable: async () => ({- write: async (text: string) => { pointer = text; },+ write: async (text: string) => {+ if (refusePointer?.(text)) {+ throw new Error("the pointer could not be written");+ }+ pointer = text;+ },close: async () => {}})};@@ -387,7 +395,10 @@ describe("a backup that cannot be restored", () => {pool.OpfsSAHPoolDb.prototype.selectValues = function (sql: string) {if (answered.times++ === 0) {handles.closed = true;- throw closedAccessHandle();+ // Worded differently on purpose, and reported wrapped in the checks' own failure:+ // what marks it out has to be the kind of error it is, not the sentence a given+ // browser version happens to use.+ throw new DOMException("The file handle was invalidated", "InvalidStateError");}return tables.call(this, sql);@@ -399,6 +410,24 @@ describe("a backup that cannot be restored", () => {expect(pointer).toBe(CANDIDATE_NAME);});+ it("says the check could not be carried out, rather than calling the backup damaged", async () => {+ const { pool, files } = fakePool();+ const { target } = fakeTarget(pool);+ pool.OpfsSAHPoolDb.prototype.selectValues = () => {+ throw new Error("out of memory");+ };++ // The checks call a database damaged by looking at it. Where the looking is what failed,+ // there is nothing to conclude about the file, and concluding anyway is how someone deletes+ // the only copy of their notes.+ await expect(restoreDatabase(target, new Blob([ databaseBytes() ])))+ .rejects.toMatchObject({ reason: "check-failed", message: expect.stringContaining("out of memory") });++ // Still cleaned up after, and the live database is untouched.+ expect(files.has(CANDIDATE_NAME)).toBe(false);+ expect(pointer).toBeUndefined();+ });+it("reports what stopped an import that no recovery could help", async () => {const { pool, handles } = fakePool();const { target } = fakeTarget(pool);@@ -406,11 +435,32 @@ describe("a backup that cannot be restored", () => {throw new Error("the pool is full");};+ // Never reached the swap, so it must not say the database was replaced and put back.await expect(restoreDatabase(target, new Blob([ databaseBytes() ])))- .rejects.toMatchObject({ message: expect.stringContaining("the pool is full") });+ .rejects.toMatchObject({+ reason: "restore-failed",+ message: expect.stringContaining("the pool is full")+ });// Nothing to take back, so nothing was let go of either.expect(handles.paused).toBe(0);+ expect(pointer).toBeUndefined();+ });++ it("keeps the restored database when the pointer cannot be put back on the old one", async () => {+ const { pool, files } = fakePool();+ const { target } = fakeTarget(pool, { failToOpen: CANDIDATE_NAME });+ // The swap fails, and so does putting the pointer back, which leaves it naming the+ // candidate: the one state where that entry is not a leftover but the database itself.+ refusePointer = (name) => name === DEFAULT_DATABASE_NAME;++ await expect(restoreDatabase(target, new Blob([ databaseBytes() ])))+ .rejects.toMatchObject({ reason: "swap-failed-reload" });++ // Kept, because a start would open it and removing it would leave nothing to open at all.+ // It has passed its checks by this point, so opening it is safe.+ expect(files.has(CANDIDATE_NAME)).toBe(true);+ expect(pointer).toBe(CANDIDATE_NAME);});it("takes the pool's access handles back where the browser has closed them, and opens", async () => {diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.tsindex 171c7114ac..26ad136d24 100644--- a/apps/standalone/src/lightweight/database_restore.ts+++ b/apps/standalone/src/lightweight/database_restore.ts@@ -122,8 +122,13 @@ export async function restoreDatabase(report({ stage: "done" });} catch (e) {const failure = asFailure(e);- // The candidate is no use to anyone now, and the pool's slots are finite.- await removeQuietly(target.pool, candidate);+ // The candidate is no use to anyone now, and the pool's slots are finite. Unless a start+ // would open it, which is the one case where it is not a leftover but the database itself:+ // the pointer is only ever put on it once it has passed its checks, and removing what the+ // pointer names would leave nothing to open at all.+ if (await readCurrentDatabaseName() !== candidate) {+ await removeQuietly(target.pool, candidate);+ }report({ stage: "failed", error: failure.message, reason: failure.reason });throw failure;@@ -132,8 +137,8 @@ export async function restoreDatabase(/** A failure with a reason attached, so the setup screen can tell the cases apart. */export class RestoreFailure extends Error {- constructor(readonly reason: string, message: string) {- super(message);+ constructor(readonly reason: string, message: string, options?: ErrorOptions) {+ super(message, options);this.name = "RestoreFailure";}}@@ -199,19 +204,11 @@ 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,- rejection: "damaged-database",- message: `The database could not be read: ${messageOf(e)}`- };+ // Not a verdict on the backup. The checks call a database damaged by looking at it and+ // finding it so; this is the looking itself having failed, which says nothing about what+ // was being looked at. Calling it damaged because the device ran out of memory, or because+ // the browser took the pool's handles away, is how a perfectly good backup gets thrown out.+ throw new RestoreFailure("check-failed", messageOf(e), { cause: e });} finally {db.close();}@@ -235,9 +232,11 @@ function candidateOf(db: InstanceType<SAHPoolUtil["OpfsSAHPoolDb"]>): CandidateD*/async function swapIn(target: RestoreTarget, previous: string, candidate: string): Promise<void> {target.close();- await writeCurrentDatabaseName(candidate);try {+ // Inside the rollback's reach, because a pointer half-written is the one failure that could+ // leave a start reading neither name.+ await writeCurrentDatabaseName(candidate);await openWithHandles(target, candidate);} catch (e) {// Put back what was live, so a candidate that will not open costs nothing.@@ -281,7 +280,14 @@ async function rollBackTo(previous: string,cause: unknown): Promise<RestoreFailure> {- await writeCurrentDatabaseName(previous);+ try {+ await writeCurrentDatabaseName(previous);+ } catch {+ // The pointer is whatever it was left as, which may be the candidate. That one has passed+ // its checks, so a start finding it is not in danger; it is simply not the database this+ // instance was told to keep, and only a start can settle which it opens.+ return new RestoreFailure("swap-failed-reload", messageOf(cause));+ }try {await openWithHandles(target, previous);@@ -349,6 +355,12 @@ function isClosedAccessHandle(e: unknown): boolean {return true;}+ // Through whatever wrapped it. A step reports a failure in its own terms, and it has no business+ // deciding on the way whether the browser's error underneath is one that can be recovered from.+ if (e instanceof Error && e.cause !== undefined && isClosedAccessHandle(e.cause)) {+ return true;+ }+return /access\s*handle.*closed|closed.*access\s*handle/i.test(messageOf(e));}@@ -429,7 +441,10 @@ function asFailure(e: unknown): RestoreFailure {return new RestoreFailure(e.reason, e.message);}- return new RestoreFailure("swap-failed", messageOf(e));+ // Not "swap-failed": everything that reaches here failed before the swap was reached, and+ // saying otherwise would tell the user their database had been replaced and put back when it+ // was never touched.+ return new RestoreFailure("restore-failed", messageOf(e));}function messageOf(e: unknown): string {