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
core/backup import: fix a deadlock
Adorian Dorand96c50fc25e5
diff --git a/apps/server/src/routes/api/setup_restore.ts b/apps/server/src/routes/api/setup_restore.tsindex 990bde43ac..19ab600aeb 100644--- a/apps/server/src/routes/api/setup_restore.ts+++ b/apps/server/src/routes/api/setup_restore.ts@@ -9,6 +9,7 @@ import dataDir from "../../services/data_dir.js";import {getRestoreProgress,readBackupFormat,+ reportRestoreFailure,restoreDatabase,RestoreFailure,type RestoreFailureReason,@@ -139,8 +140,12 @@ async function start(req: Request) {throw e;}- }).catch(() => {- // Already recorded in the progress the client is polling, and logged where it happened.+ }).catch((e) => {+ // A restore that ran has already recorded why it stopped. One that was refused before it+ // began has recorded nothing, and a client polling for progress would wait on it forever.+ if (!(e instanceof RestoreFailure)) {+ reportRestoreFailure(request.fileName, e);+ }});return { started: true };diff --git a/apps/server/src/services/database_restore.spec.ts b/apps/server/src/services/database_restore.spec.tsindex cde77dba83..defd7008c1 100644--- a/apps/server/src/services/database_restore.spec.ts+++ b/apps/server/src/services/database_restore.spec.ts@@ -11,6 +11,7 @@ import {exchangeDatabaseFiles,getRestoreProgress,readBackupFormat,+ reportRestoreFailure,restoreDatabase,RestoreFailure,stageBackup@@ -245,6 +246,17 @@ describe("restoring a database", () => {});});+ it("records a failure that happened instead of a restore, so nothing waits on a run that never began", () => {+ reportRestoreFailure("backup.db", new Error("setup is already busy with 'new-document'"));++ expect(getRestoreProgress()).toEqual({+ stage: "failed",+ fileName: "backup.db",+ error: "setup is already busy with 'new-document'",+ reason: "restore-refused"+ });+ });+it("stops before touching the live database when the backup is from a newer version", async () => {const detach = vi.spyOn(getSql(), "detachConnection").mockImplementation(() => {});const database = validDatabase();diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.tsindex 74f7fa5e6d..487843b280 100644--- a/apps/server/src/services/database_restore.ts+++ b/apps/server/src/services/database_restore.ts@@ -57,7 +57,9 @@ export type RestoreFailureReason =/** The files could not be exchanged; the original database is back in place. */| "swap-failed"/** The restored database is in place but would not open. */- | "migration-failed";+ | "migration-failed"+ /** The restore never started, e.g. setup was busy with something else. */+ | "restore-refused";export interface RestoreProgress {stage: RestoreStage;@@ -143,6 +145,22 @@ export async function restoreDatabase(request: RestoreRequest): Promise<void> {}}+/**+ * Records a failure that happened *instead of* a restore rather than during one, e.g. one that was+ * refused before it could start.+ *+ * Without this such a failure is reported nowhere: {@link restoreDatabase} never ran, so it left no+ * progress behind, and a client polling for one waits on a run that is never going to begin.+ */+export function reportRestoreFailure(fileName: string, error: unknown): void {+ progress = {+ stage: "failed",+ fileName,+ error: messageOf(error),+ reason: error instanceof RestoreFailure ? error.reason : "restore-refused"+ };+}+/*** Undoes a restore that was interrupted between the database being moved aside and the restored one* opening.diff --git a/packages/trilium-core/src/services/setup_lock.spec.ts b/packages/trilium-core/src/services/setup_lock.spec.tsindex ea8249c039..b3f318bc8d 100644--- a/packages/trilium-core/src/services/setup_lock.spec.ts+++ b/packages/trilium-core/src/services/setup_lock.spec.ts@@ -39,7 +39,7 @@ describe("setup lock", () => {expect(getRunningSetupOperation()).toBe("restore-backup");await expect(withSetupLock("new-document", async () => "wiped")).rejects.toThrow(/already busy/);- expect(() => holdSetup("restore-backup")).toThrow(/already busy/);+ expect(() => holdSetup("restore-backup")).toThrow(/already reserved/);release();@@ -47,6 +47,32 @@ describe("setup lock", () => {await expect(withSetupLock("new-document", async () => "created")).resolves.toBe("created");});+ it("lets the operation a hold was taken for actually run, which is the point of the hold", async () => {+ // The upload reserves setup, then the restore it was reserved for runs — and must not be+ // turned away by its own reservation.+ const release = holdSetup("restore-backup");++ await expect(withSetupLock("restore-backup", async () => "restored")).resolves.toBe("restored");++ // The hold outlives the attempt, so a second one (a corrected passphrase) is still covered.+ expect(getRunningSetupOperation()).toBe("restore-backup");+ await expect(withSetupLock("new-document", async () => "wiped")).rejects.toThrow(/already busy/);+ await expect(withSetupLock("restore-backup", async () => "restored again")).resolves.toBe("restored again");++ release();+ expect(getRunningSetupOperation()).toBe(null);+ });++ it("does not let a second run of the same operation join the first", async () => {+ const first = pending<string>();+ const running = withSetupLock("restore-backup", () => first.promise);++ await expect(withSetupLock("restore-backup", async () => "second")).rejects.toThrow(/already running/);++ first.resolve("first");+ await running;+ });+it("refuses a hold while an operation is running", async () => {const first = pending<void>();const running = withSetupLock("new-document", () => first.promise);diff --git a/packages/trilium-core/src/services/setup_lock.ts b/packages/trilium-core/src/services/setup_lock.tsindex 4ec426b8b9..353db2472b 100644--- a/packages/trilium-core/src/services/setup_lock.ts+++ b/packages/trilium-core/src/services/setup_lock.ts@@ -52,6 +52,10 @@ export async function withSetupLock<T>(operation: SetupOperation, work: () => Pr*/export function holdSetup(operation: SetupOperation): () => void {requireIdle(operation);+ if (holds.has(operation)) {+ throw new ConflictError(`Setup is already reserved for '${operation}'.`);+ }+holds.add(operation);return () => holds.delete(operation);@@ -65,13 +69,25 @@ export function getRunningSetupOperation(): SetupOperation | null {/*** Deciding and taking must not be separated: two requests that both looked first and took second* would both proceed, which is the whole thing this exists to prevent.+ *+ * An operation's own hold does not stand in its way. A hold is taken *for* the operation that later+ * runs — an upload reserving setup for the restore it is going to feed — so treating it as a rival+ * would have the reservation refuse the very thing it was reserving for. The hold outlives the run+ * and keeps setup reserved across a second attempt, e.g. after a passphrase turned out to be wrong.*/function requireIdle(operation: SetupOperation): void {- const current = getRunningSetupOperation();+ const blocking = running && running !== operation+ ? running+ : [ ...holds ].find((held) => held !== operation);- if (current) {+ if (blocking) {throw new ConflictError(- `Cannot start '${operation}': setup is already busy with '${current}'.`+ `Cannot start '${operation}': setup is already busy with '${blocking}'.`);}++ // Two runs of the same operation are still two runs, and the second must not join the first.+ if (running) {+ throw new ConflictError(`Cannot start '${operation}': it is already running.`);+ }}