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
start again: improve test coverage
Adorian Doran061fde1f3665
diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsxindex c45be401e3..46fbbcd0f7 100644--- a/apps/client/src/setup.spec.tsx+++ b/apps/client/src/setup.spec.tsx@@ -48,6 +48,18 @@ function renderInto(vnode: preact.ComponentChild) {const flushEffects = () => vi.advanceTimersByTimeAsync(50);const nextPoll = () => vi.advanceTimersByTimeAsync(1000);+/** Answers the sync form enough for it to let Finish be pressed. */+function fillSyncForm(root: HTMLElement) {+ const host = root.querySelector<HTMLInputElement>("input:not([type=password])");+ const password = root.querySelector<HTMLInputElement>("input[type=password]");++ for (const [ field, value ] of [ [ host, "https://srv" ], [ password, "pw" ] ] as const) {+ if (!field) continue;+ field.value = value;+ field.dispatchEvent(new Event("input", { bubbles: true }));+ }+}+/** Routes the mocked server.get; `stats` can be swapped between polls. */let stats: Stats;function mockRoutes(extra: Record<string, unknown> = {}) {@@ -284,6 +296,20 @@ describe("creating the knowledge base", () => {container.remove();}});++ it("stops claiming there is anything to go back to once the server has erased it", async () => {+ // This path erases server-side as its first step, so a failure may well have left nothing+ // behind the wizard — and the page it fails on came from a start that still believed there+ // was. Asked again rather than assumed, since only the server knows.+ window.glob.hasExistingData = true;+ mockRoutes({ "setup/status": { hasExistingData: false } });+ serverMock.post.mockRejectedValue(new Error("the disk is full"));++ renderInto(renderState("createNewDocumentEmpty", vi.fn()));+ await flushEffects();++ expect(window.glob.hasExistingData).toBe(false);+ });});describe("SyncInProgress", () => {@@ -409,6 +435,40 @@ describe("SyncFromServer", () => {expect(host.value).toBe("https://typed.example.com");});+ it("stops claiming there is anything to go back to when the failure came after the erase", async () => {+ // Reaching the server can fail on something the user corrects right here, and the knowledge+ // base is deliberately still there for those. Past the point the server answers, the last+ // step erases before it builds — so which of the two happened is asked, not assumed.+ window.glob.hasExistingData = true;+ mockRoutes({ "setup/status": { hasExistingData: false } });+ serverMock.post.mockResolvedValue({ result: "failure", error: "the disk is full" });+ const c = renderInto(<SyncFromServer setState={vi.fn()} />);+ await flushEffects();+ fillSyncForm(c);+ await flushEffects();++ c.querySelector<HTMLElement>("footer button")?.click();+ await flushEffects();++ expect(window.glob.hasExistingData).toBe(false);+ expect(c.querySelector(".page-error")?.textContent).toContain("setup.sync-failed");+ });++ it("keeps it where the server refused the credentials, which erases nothing", async () => {+ window.glob.hasExistingData = true;+ mockRoutes({ "setup/status": { hasExistingData: true } });+ serverMock.post.mockResolvedValue({ result: "failure", error: "Incorrect password" });+ const c = renderInto(<SyncFromServer setState={vi.fn()} />);+ await flushEffects();+ fillSyncForm(c);+ await flushEffects();++ c.querySelector<HTMLElement>("footer button")?.click();+ await flushEffects();++ expect(window.glob.hasExistingData).toBe(true);+ });+it("leaves the form empty on a fresh setup (no stored sync options)", async () => {mockRoutes({ "setup/status": { isInitialized: false, schemaExists: false } });const c = renderInto(<SyncFromServer setState={vi.fn()} />);diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex a2ee1f8e98..d001ecc8e5 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -11,7 +11,12 @@ import { getCurrentLanguage, initLocale, t } from "./services/i18n";import server from "./services/server";import { isElectron, isMobileApp } from "./services/utils";import SetupBackupDatabase from "./setup_backup";-import ExistingData, { deleteExistingData, hasExistingData, keepExistingData } from "./setup_existing";+import ExistingData, {+ deleteExistingData,+ hasExistingData,+ keepExistingData,+ refreshExistingData+} from "./setup_existing";import RestoreFromBackup from "./setup_restore";import SetupUnlock from "./setup_unlock";import Admonition, { ExtendedAdmonition } from "./widgets/react/Admonition";@@ -552,7 +557,13 @@ function CreateNewDocumentInProgress({ withDemo = false, setState }: {useEffect(() => {server.post(`setup/new-document${withDemo ? "" : "?skipDemoDb"}`, { locale: getCurrentLanguage() }).then(onSetupFinished)- .catch((e: unknown) => setError(messageOf(e)));+ .catch(async (e: unknown) => {+ // The knowledge base is erased server-side as the first step of this, so a failure+ // may well have left nothing behind the wizard. Asked again before the menu is+ // shown once more, which decides from that answer what it may still offer.+ await refreshExistingData();+ setError(messageOf(e));+ });}, [ withDemo ]);return (@@ -646,7 +657,17 @@ export function SyncFromServer({ setState }: { setState: (state: State) => voidif (resp.result === "success") {setState("syncFromServerInProgress");- } else if (resp.error.includes("Incorrect password")) {+ return;+ }++ // A failure here is usually one the user can correct on this very form — a mistyped+ // host, a refused password — and the knowledge base is deliberately still there for+ // those. It is not for all of them: once the server has answered, the last step erases+ // before it builds, so a failure past that point leaves nothing behind the wizard. Only+ // the server knows which of the two happened, so it is asked rather than guessed at.+ await refreshExistingData();++ if (resp.error.includes("Incorrect password")) {setIsWrongPassword(true);} else {raiseError(t("setup.sync-failed", { message: resp.error }));diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsxindex 21afdc55b4..cfcc6ad7f4 100644--- a/apps/client/src/setup_existing.tsx+++ b/apps/client/src/setup_existing.tsx@@ -4,7 +4,8 @@ import type {SetupBackupDefaults,SetupBackupSettings,SetupExistingBackup,- SetupExistingBackupStatus+ SetupExistingBackupStatus,+ SetupStatusResponse} from "@triliumnext/commons";import { useEffect, useState } from "preact/hooks";@@ -530,3 +531,21 @@ export function keepExistingData(): Promise<void> {export function hasExistingData(): boolean {return window.glob.hasExistingData === true;}++/**+ * Asks the server again, for the paths that erase without going through this page.+ *+ * Creating a document and syncing from a server both erase server-side, at the last moment before+ * the database that replaces this one is built. Where that replacement then fails, the wizard stays+ * open on a screen that came from a start which still believed there was something behind it — and+ * would go on offering a way back to it. Never throws: a wizard that cannot reach its own server has+ * a larger problem than a stale flag, and the screens read the flag while rendering.+ */+export async function refreshExistingData(): Promise<void> {+ try {+ const { hasExistingData } = await server.get<SetupStatusResponse>("setup/status");+ window.glob.hasExistingData = hasExistingData === true;+ } catch {+ // Left as it was, which is the answer the page already had.+ }+}diff --git a/apps/server/src/services/setup_marker.spec.ts b/apps/server/src/services/setup_marker.spec.tsindex 46475c9920..0316ca369c 100644--- a/apps/server/src/services/setup_marker.spec.ts+++ b/apps/server/src/services/setup_marker.spec.ts@@ -106,6 +106,35 @@ describe("erasing the database the wizard was booted away from", () => {expect(getSql().getValue("SELECT 1")).toBe(1);expect(fs.existsSync(dataDirs.DOCUMENT_PATH)).toBe(true);});++ it("takes the sidecars first, so a removal that stops part-way leaves a whole database", async () => {+ // The other order can leave a stale `-wal` beside a freshly created database of the same+ // name, which SQLite would try to replay into it.+ const removed: string[] = [];+ vi.spyOn(fs, "rmSync").mockImplementation((file) => {+ removed.push(String(file).replace(dataDirs.DOCUMENT_PATH, "<document>"));+ });++ await setupPlatform.removeDatabase();++ expect(removed).toEqual([ "<document>-wal", "<document>-shm", "<document>" ]);+ vi.restoreAllMocks();+ });++ it("comes back holding a connection even when the files would not go", async () => {+ // Reachable rather than theoretical: on Windows an antivirus scanner or a search indexer+ // holding the file is enough for EPERM. Left detached, every later request answers+ // "DB not open" until the application is restarted — including the ones the wizard needs to+ // report what went wrong and let the user try something else.+ vi.spyOn(fs, "rmSync").mockImplementation(() => {+ throw new Error("EPERM: operation not permitted");+ });++ await expect(setupPlatform.removeDatabase()).rejects.toThrow(/EPERM/);++ vi.restoreAllMocks();+ expect(getSql().getValue("SELECT 1")).toBe(1);+ });});function documentFiles(): string[] {diff --git a/apps/server/src/services/setup_marker.ts b/apps/server/src/services/setup_marker.tsindex a4ce451dca..80839da9c9 100644--- a/apps/server/src/services/setup_marker.ts+++ b/apps/server/src/services/setup_marker.ts@@ -72,18 +72,25 @@ export const setupPlatform: SetupPlatform = {async removeDatabase() {// Detached first: on Windows an open handle is enough to make the file undeletable, and- // leaving the connection attached to a file that is gone is worse than either.+ // leaving the connection attached to a file that is gone is worse than either. Closing also+ // folds the -wal back into the database, so what goes below is already spent.getSql().detachConnection();const document = dataDirs.DOCUMENT_PATH;- for (const file of [ document, `${document}-wal`, `${document}-shm` ]) {- fs.rmSync(file, { force: true });+ try {+ // The sidecars before the database itself, so a removal that stops part-way leaves a+ // whole database rather than half of one. The other order can leave a stale -wal beside+ // a freshly created database of the same name, which SQLite would try to replay into it.+ for (const file of [ `${document}-wal`, `${document}-shm`, document ]) {+ fs.rmSync(file, { force: true });+ }+ } finally {+ // Whatever happened above, this process has to come back holding a connection: opening+ // a path with nothing at it creates it empty, which is the state a first run begins in.+ // Without one, every later request answers "DB not open" until the application is+ // restarted — including the ones the wizard needs to report what went wrong and let the+ // user try again. A removal that failed leaves the database whole, and reopens onto it.+ getSql().attachFromFile(document, config.General.readOnly);}-- // And an empty one opened in its place, because everything the wizard does from here writes- // to a database: creating a document, taking a pushed sync seed, converging a sync. Opening- // a path with nothing at it creates it empty, which is the state a first run begins in — so- // this leaves the instance exactly where a machine that had never run Trilium would be.- getSql().attachFromFile(document, config.General.readOnly);}};diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex 9fd06138dd..84fed5cd50 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -442,13 +442,20 @@ async function removeStandaloneDatabase(): Promise<void> {coreModule.getSql().detachConnection();try {- pool.unlink(live);- } catch {- // Already gone, which is the state the caller asked for.- }+ try {+ pool.unlink(live);+ } catch {+ // Already gone, which is the state the caller asked for.+ }- await writeCurrentDatabaseName(DEFAULT_DATABASE_NAME);- sqlProvider.loadFromSahPool(DEFAULT_DATABASE_NAME);+ 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);+ }}/**diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 67df936e98..5b8bcff631 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -982,6 +982,14 @@ export interface SetupStatusResponse {syncVersion: number;schemaExists: boolean;isInitialized?: boolean;+ /**+ * Whether there is still a knowledge base behind the wizard.+ *+ * The same answer the bootstrap gave when the page loaded, asked again: the paths that replace a+ * knowledge base erase it on the server, so a page that has been sitting here since before one+ * of them ran would otherwise go on offering a way back to something that is gone.+ */+ hasExistingData?: boolean;/** The operation setup is busy with, or `null` when it is free. */setupOperation?: SetupOperation | null;/** Kept from a failed sync attempt so the wizard can prefill the form; pre-initialization only. */diff --git a/packages/trilium-core/src/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.tsindex 133b8a7beb..d2f3dba42e 100644--- a/packages/trilium-core/src/routes/api/setup.ts+++ b/packages/trilium-core/src/routes/api/setup.ts@@ -28,6 +28,10 @@ function getStatus() {isInitialized,schemaExists,authRequired,+ // Asked again rather than taken from the page's own start: the paths that replace a+ // knowledge base erase it here, and a wizard that failed after one of them did would go on+ // offering a way back to something that no longer exists.+ hasExistingData: hasExistingData(),syncVersion: appInfo.syncVersion,// What another tab, or this one after a reload, has already started. Lets the wizard say so// rather than only finding out by being refused.