Skip to content

Build your personal knowledge base with Trilium Notes

standalone/start again: fix an issue

Adorian Doran22f52c04e130
diff --git a/apps/standalone/src/lightweight/database_restore.spec.ts b/apps/standalone/src/lightweight/database_restore.spec.ts
index 4ce5a81415..c779f4bad0 100644
--- a/apps/standalone/src/lightweight/database_restore.spec.ts
+++ b/apps/standalone/src/lightweight/database_restore.spec.ts
@@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
DEFAULT_DATABASE_NAME,
+ eraseDatabase,
readCurrentDatabaseName,
readInSlices,
restoreDatabase,
@@ -634,3 +635,81 @@ describe("a backup that cannot be restored", () => {
expect(pointer).toBe(DEFAULT_DATABASE_NAME);
});
});
+
+/**
+ * Erasing is the same close/exchange/open dance as a restore, and the same thing can go wrong in the
+ * middle of it: the pointer that outlives this worker and the entry the worker is actually holding
+ * can end up naming different databases. A start reads only the pointer, so everything written into
+ * the other one after that is simply never seen again.
+ */
+describe("erasing the live database", () => {
+ it("moves the pointer, unlinks what was live, and opens an empty one in its place", async () => {
+ const { files, pool } = fakePool();
+ files.set(DEFAULT_DATABASE_NAME, databaseBytes());
+ const { target, acted } = fakeTarget(pool);
+
+ await eraseDatabase(target);
+
+ expect(files.has(DEFAULT_DATABASE_NAME)).toBe(false);
+ expect(pointer).toBe(DEFAULT_DATABASE_NAME);
+ expect(acted).toEqual([ "close", `open:${DEFAULT_DATABASE_NAME}` ]);
+ });
+
+ it("comes back on the entry the pointer names, having been live on the other one", async () => {
+ // Which is where an instance sits after a restore: the two names alternate, so the live
+ // entry is the candidate rather than the default.
+ const { files, pool } = fakePool();
+ files.set(CANDIDATE_NAME, databaseBytes());
+ pointer = CANDIDATE_NAME;
+ const { target, acted } = fakeTarget(pool);
+
+ await eraseDatabase(target);
+
+ expect(files.has(CANDIDATE_NAME)).toBe(false);
+ expect(pointer).toBe(DEFAULT_DATABASE_NAME);
+ expect(acted).toEqual([ "close", `open:${DEFAULT_DATABASE_NAME}` ]);
+ });
+
+ it("erases nothing and reopens what was live when the pointer will not move", async () => {
+ // The pointer is moved first for exactly this: a write that fails has destroyed nothing, and
+ // reopening the entry it still names leaves the two halves agreeing.
+ const { files, pool } = fakePool();
+ files.set(CANDIDATE_NAME, databaseBytes());
+ pointer = CANDIDATE_NAME;
+ refusePointer = () => true;
+ const { target, acted } = fakeTarget(pool);
+
+ await expect(eraseDatabase(target)).rejects.toThrow(/pointer could not be written/);
+
+ expect(files.has(CANDIDATE_NAME)).toBe(true);
+ expect(pointer).toBe(CANDIDATE_NAME);
+ expect(acted).toEqual([ "close", `open:${CANDIDATE_NAME}` ]);
+ });
+
+ it("still comes back on the entry the pointer names when the old one will not unlink", async () => {
+ // The old entry is left behind taking up room, which is a leak and not a trap: nothing reads
+ // it again, and the worker and the next start agree on what is live.
+ const { files, pool } = fakePool();
+ files.set(CANDIDATE_NAME, databaseBytes());
+ pointer = CANDIDATE_NAME;
+ pool.unlink = () => { throw new Error("the entry is in use"); };
+ const { target, acted } = fakeTarget(pool);
+
+ await eraseDatabase(target);
+
+ expect(pointer).toBe(DEFAULT_DATABASE_NAME);
+ expect(acted).toEqual([ "close", `open:${DEFAULT_DATABASE_NAME}` ]);
+ });
+
+ it("always tries to open something, so the worker is never left holding nothing", async () => {
+ // A detached service answers every request with "DB not open" for as long as the worker
+ // lives, and the wizard needs one to report what went wrong and offer another path.
+ const { files, pool } = fakePool();
+ files.set(DEFAULT_DATABASE_NAME, databaseBytes());
+ const { target, acted } = fakeTarget(pool, { failToOpen: DEFAULT_DATABASE_NAME });
+
+ await expect(eraseDatabase(target)).rejects.toThrow(/database is locked/);
+
+ expect(acted).toEqual([ "close", `open-failed:${DEFAULT_DATABASE_NAME}` ]);
+ });
+});
diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.ts
index 558acec68e..2c2415ecd8 100644
--- a/apps/standalone/src/lightweight/database_restore.ts
+++ b/apps/standalone/src/lightweight/database_restore.ts
@@ -380,6 +380,51 @@ async function reacquireAccessHandles(pool: SAHPoolUtil): Promise<void> {
await pool.unpauseVfs();
}
+/**
+ * Erases the live database and leaves an empty one in its place.
+ *
+ * What the setup wizard does when the user asks for it. The pool has no notion of "no database", and
+ * everything after this point in the wizard writes to one — creating a document, converging a sync —
+ * so the entry is unlinked and a fresh one opened under the name a first run uses, which is exactly
+ * the state a browser that had never run Trilium is in.
+ *
+ * Beside the restore because it is the same dance: close, exchange, open. The order below is what
+ * keeps a failure part-way through from leaving the two halves of "which database is live"
+ * disagreeing, and each step says what it costs when it is the one that fails.
+ *
+ * @throws Error where the pointer could not be moved, having erased nothing.
+ */
+export async function eraseDatabase(target: RestoreTarget): Promise<void> {
+ const live = await readCurrentDatabaseName();
+ target.close();
+
+ // Which entry the caller will be holding when this returns. It moves only once the pointer that
+ // outlives this worker agrees, so the two can never come out of here naming different databases:
+ // the next start reads that pointer, and running on one entry while the pointer names another
+ // would silently strand everything written in between.
+ let opening = live;
+
+ try {
+ // The pointer first, and the unlink second. The other way round, a pointer write that failed
+ // would leave it naming an entry that no longer exists while this worker ran on the default
+ // one. A pointer that is moved and then not followed through only leaks the old entry.
+ await writeCurrentDatabaseName(DEFAULT_DATABASE_NAME);
+ opening = DEFAULT_DATABASE_NAME;
+
+ try {
+ target.pool.unlink(live);
+ } catch {
+ // Already gone, which is the state the caller asked for.
+ }
+ } finally {
+ // Whatever happened above, the caller has to come back holding a database: everything after
+ // this point writes to one, and a detached service answers every request with "DB not open"
+ // for as long as this worker lives. The pool creates the entry where there is none, so this
+ // opens either the one just cleared out, or the one nothing got around to clearing.
+ target.open(opening);
+ }
+}
+
/** 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();
diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.ts
index 84fed5cd50..019ef90d15 100644
--- a/apps/standalone/src/local-server-worker.ts
+++ b/apps/standalone/src/local-server-worker.ts
@@ -429,33 +429,17 @@ async function removeStandaloneDatabase(): Promise<void> {
throw new Error("The database is not open, so there is nothing to erase.");
}
- const {
- DEFAULT_DATABASE_NAME,
- readCurrentDatabaseName,
- writeCurrentDatabaseName
- } = await import('./lightweight/database_restore.js');
-
- const live = await readCurrentDatabaseName();
- // Through the SQL service rather than straight at the provider: it holds prepared statements of
- // its own, bound to the connection this closes, and the wizard goes on using the same worker
- // afterwards — creating a document runs against the database opened below, in this very request.
- coreModule.getSql().detachConnection();
-
- try {
- try {
- pool.unlink(live);
- } catch {
- // Already gone, which is the state the caller asked for.
- }
-
- await writeCurrentDatabaseName(DEFAULT_DATABASE_NAME);
- } finally {
- // Whatever happened above, the worker has to come back holding a database: everything after
- // this point writes to one, and a detached service answers every request with "DB not open"
- // for as long as this worker lives. The pool creates the entry where there is none, so this
- // opens either the one that was just cleared out or a fresh one under the same name.
- sqlProvider.loadFromSahPool(DEFAULT_DATABASE_NAME);
- }
+ const { eraseDatabase } = await import('./lightweight/database_restore.js');
+
+ await eraseDatabase({
+ pool,
+ // Closed through the SQL service rather than straight at the provider: the service holds
+ // prepared statements of its own, bound to the connection this closes, and the wizard goes
+ // on using the same worker afterwards — creating a document runs against the database
+ // opened at the end of this, in this very request.
+ close: () => coreModule?.getSql().detachConnection(),
+ open: (dbName) => sqlProvider?.loadFromSahPool(dbName)
+ });
}
/**