Skip to content

Build your personal knowledge base with Trilium Notes

standalone/database: add support for integrity and consistency check

Adorian Doran5c5e0895721c
diff --git a/apps/server/src/routes/api/database.ts b/apps/server/src/routes/api/database.ts
index 0358c1eaa8..86410e67ac 100644
--- a/apps/server/src/routes/api/database.ts
+++ b/apps/server/src/routes/api/database.ts
@@ -1,11 +1,10 @@
import {
BackupDatabaseNowResponse,
CompactionEstimateResponse,
- DatabaseCheckIntegrityResponse,
ExistingAnonymizedDatabasesResponse,
VacuumDatabaseResponse
} from "@triliumnext/commons";
-import { becca_loader, consistency_checks as consistencyChecksService, getBackup, getDatabaseSizeBytes, getLog, getReclaimableBytes, utils, ValidationError } from "@triliumnext/core";
+import { becca_loader, checkIntegrity, consistency_checks as consistencyChecksService, getBackup, getDatabaseSizeBytes, getLog, getReclaimableBytes, utils, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
import fs, { readFileSync } from "fs";
import path from "path";
@@ -100,16 +99,6 @@ function deleteAnonymizedDatabase(req: Request) {
fs.rmSync(filePath, { force: true });
}
-function checkIntegrity() {
- const results = sql.getRows<{ integrity_check: string }>("PRAGMA integrity_check");
-
- getLog().info(`Integrity check result: ${JSON.stringify(results)}`);
-
- return {
- results
- } satisfies DatabaseCheckIntegrityResponse;
-}
-
function downloadBackup(req: Request, res: Response) {
downloadDatabaseFile(req, res, dataDir.BACKUP_DIR, "Backup file not found");
}
diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.ts
index 911218f878..ac91e246cb 100644
--- a/apps/standalone/src/lightweight/browser_routes.spec.ts
+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts
@@ -1,4 +1,4 @@
-import { getSql, routes, sql_init } from "@triliumnext/core";
+import { consistency_checks, getSql, routes, sql_init } from "@triliumnext/core";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BrowserRouter } from "./browser_router.js";
@@ -52,6 +52,22 @@ describe("registerRoutes (real wiring)", () => {
expect(abort.status).toBe(200);
});
+ // Registered here rather than in the shared table, so nothing else would catch their loss. Both
+ // run against the browser's own SQLite: the checks the server offers that need no file.
+ it("serves the maintenance routes, and no compaction", async () => {
+ const integrity = await router.dispatch("GET", "http://localhost/api/database/check-integrity");
+ expect(parseJson(integrity.body)).toEqual({ results: [ { integrity_check: "ok" } ] });
+
+ // Awaited rather than left running: the response arriving is what says the checks are over.
+ const consistency = vi.spyOn(consistency_checks, "runOnDemandChecks").mockResolvedValue(undefined);
+ expect((await router.dispatch("POST", "http://localhost/api/database/find-and-fix-consistency-issues", {})).status).toBe(200);
+ expect(consistency).toHaveBeenCalledWith(true);
+
+ // Compacting rebuilds through a temporary store this build keeps in memory, so it is left
+ // to the platforms that have somewhere to put it.
+ expect((await router.dispatch("POST", "http://localhost/api/database/vacuum-database", {})).status).toBe(404);
+ });
+
it("serves the compatibility dummy routes", async () => {
expect(parseJson((await router.dispatch("GET", "http://localhost/api/script/widgets")).body)).toEqual([]);
expect(parseJson((await router.dispatch("GET", "http://localhost/api/script/startup")).body)).toEqual([]);
diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.ts
index 4073511dd0..7404aea215 100644
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@ -4,7 +4,7 @@
*/
import { BootstrapDefinition } from '@triliumnext/commons';
-import { entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSql, routes, sql_init } from '@triliumnext/core';
+import { checkIntegrity, consistency_checks, entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSql, routes, sql_init } from '@triliumnext/core';
import llmRoute from '@triliumnext/core/src/routes/api/llm.js';
import packageJson from '../../package.json' with { type: 'json' };
@@ -312,6 +312,23 @@ export function registerRoutes(router: BrowserRouter): void {
apiRoute('post', '/api/llm-chat/stream-start', llmRoute.startChatStream);
apiRoute('post', '/api/llm-chat/stream-abort', llmRoute.abortChatStream);
+ // Keeping the database in order, which the server answers from its own routes (see the server's
+ // `routes.ts`). Registered here rather than in the shared table because only two of the three
+ // belong in this runtime: compacting rebuilds the database through the temporary store, which
+ // this build keeps in memory, so it would ask the browser for the size of the database again at
+ // the moment the user is short of room.
+ apiRoute("get", "/api/database/check-integrity", () => checkIntegrity());
+ // Awaited rather than left running, and without a transaction of its own: the checks write as
+ // they go and reload becca at the end, which no other request may be interleaved with. The
+ // server lets its own run on past the response, having no such connection to protect.
+ createAsyncRoute(router, { transactional: false })(
+ "post",
+ "/api/database/find-and-fix-consistency-issues",
+ [],
+ () => consistency_checks.runOnDemandChecks(true),
+ apiResultHandler
+ );
+
// Dummy routes for compatibility.
apiRoute("get", "/api/script/widgets", () => []);
apiRoute("get", "/api/script/startup", () => []);
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index 4a2ef5d11b..23a9f22af8 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -145,6 +145,7 @@ export { default as imageCompressionService } from "./services/image_compression
export { default as imageInventoryService, type ImageInventoryOptions } from "./services/image_inventory";
export { getContentCounts } from "./services/space_usage";
export { getDatabaseSizeBytes, getReclaimableBytes } from "./services/database_size";
+export { checkIntegrity } from "./services/database_maintenance";
export { default as imageInfoService } from "./services/image_info";
export { estimateJpegQuality } from "./services/jpeg_quality";
export { inspectImage, type InspectedImage, UNKNOWN_FORMAT } from "./services/image_inspect";
diff --git a/packages/trilium-core/src/services/database_maintenance.spec.ts b/packages/trilium-core/src/services/database_maintenance.spec.ts
new file mode 100644
index 0000000000..2ee1c9abb5
--- /dev/null
+++ b/packages/trilium-core/src/services/database_maintenance.spec.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { checkIntegrity } from "./database_maintenance.js";
+import { getLog } from "./log.js";
+
+describe("checking the database's integrity", () => {
+ it("asks the engine about itself, and writes down what it answered", () => {
+ const logged = vi.spyOn(getLog(), "info");
+ const { results } = checkIntegrity();
+
+ // Runs against better-sqlite3 under the server suite and against the WASM build under the
+ // standalone one: the whole point of asking the engine rather than reading a file is that
+ // both can answer.
+ expect(results).toEqual([ { integrity_check: "ok" } ]);
+
+ // The reply to a check that failed is of no use once the message carrying it is gone.
+ expect(logged).toHaveBeenCalledWith(`Integrity check result: ${JSON.stringify(results)}`);
+ logged.mockRestore();
+ });
+});
diff --git a/packages/trilium-core/src/services/database_maintenance.ts b/packages/trilium-core/src/services/database_maintenance.ts
new file mode 100644
index 0000000000..663842750f
--- /dev/null
+++ b/packages/trilium-core/src/services/database_maintenance.ts
@@ -0,0 +1,19 @@
+import type { DatabaseCheckIntegrityResponse } from "@triliumnext/commons";
+
+import { getLog } from "./log.js";
+import { getSql } from "./sql/index.js";
+
+/**
+ * Asking SQLite whether the database is sound, which every platform can do: the check is a statement
+ * the engine answers about itself, with no file to reach for.
+ *
+ * Logged as well as returned. The reply to a check that failed is a list of what was found, which is
+ * of no use once the message that carried it is gone.
+ */
+export function checkIntegrity(): DatabaseCheckIntegrityResponse {
+ const results = getSql().getRows<{ integrity_check: string }>("PRAGMA integrity_check");
+
+ getLog().info(`Integrity check result: ${JSON.stringify(results)}`);
+
+ return { results };
+}