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
client/cleanup tool: add extra notices about the vacuuming process
Adorian Doranb25b0e3512ee
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 3d33e2049e..88f4bca089 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2895,9 +2895,10 @@"cleanup_compact_database": "Compact database","cleanup_running": "Cleaning up…","cleanup_compacting": "Compacting the database. This may take several minutes.",- "cleanup_confirm_interrupted": "If something interrupts it (such as a crash, a restart or a power cut) nothing beyond the selected items is lost.",+ "cleanup_confirm_interrupted": "If something interrupts it, such as a crash, a restart or a power cut, nothing beyond the selected items is lost.","cleanup_confirm_compacting_title": "Compacting database is a slow operation",- "cleanup_confirm_compacting": "Rebuilding the database can take several minutes, depending on its size. Trilium will not respond until it finishes."+ "cleanup_confirm_compacting": "Compacting the database can take several minutes, depending on its size and on the performance of the machine running Trilium. Also, up to {{space}} of free disk space on the machine is temporarily needed (in the data directory and the system's temporary directory).",+ "cleanup_compact_notice": "This operation may take several minutes and Trilium will not respond until it completes."},"note_language": {"not_set": "No language set",diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.cssindex f9658da896..29e45c6296 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.css+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.css@@ -153,6 +153,17 @@color: var(--muted-text-color);}+ /* Prose rather than a row of controls, so none of the item layout applies to it.+ A fit-content dialog takes its width from the longest unbroken line in it, and this sentence+ would otherwise be that line. Containment says the part that is actually true — this row's+ width does not depend on what is written in it — so the dialog is sized by the rows that+ should size it, and the sentence wraps to whatever width that leaves. The row still stretches+ to the card, and still grows downwards for as many lines as it takes. */+ .cleanup-compact-notice {+ contain: inline-size;+ font-size: 0.85em;+ }+.cleanup-item-number {flex: 0 0 auto;width: 5em;diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsxindex 0f89bee32c..d188bcc466 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx@@ -8,7 +8,7 @@ import { formatSize } from "../../../../../services/utils";// Hoisted with the mocks that read them: a `vi.mock` factory runs before any plain module constant.const {- REVISIONS_ALL, REVISIONS_TRIMMED, DELETED, UNUSED, FREE_PAGES,+ REVISIONS_ALL, REVISIONS_TRIMMED, DELETED, UNUSED, FREE_PAGES, DATABASE_BYTES,VACUUM_BEFORE, VACUUM_AFTER, MEASURED_BEFORE, MEASURED_AFTER} = vi.hoisted(() => ({REVISIONS_ALL: 900,@@ -17,6 +17,8 @@ const {UNUSED: 20,/** Pages already free in the file, which only a rebuild returns. */FREE_PAGES: 640,+ /** What the file occupies now — the headroom a rebuild wants, quoted in the confirmation. */+ DATABASE_BYTES: 52000,/** What the rebuild reports for itself, which is the figure a compacting run goes by. */VACUUM_BEFORE: 8000,VACUUM_AFTER: 3000,@@ -59,7 +61,7 @@ vi.mock("../../../../../services/server", () => {mocks.get(url);if (url === "database/compaction-estimate") {- return Promise.resolve({ reclaimableBytes: FREE_PAGES });+ return Promise.resolve({ reclaimableBytes: FREE_PAGES, databaseBytes: DATABASE_BYTES });}if (!url.startsWith("space-usage/")) {@@ -261,6 +263,17 @@ describe("showCleanupDialog", () => {expect(document.body.querySelector(".cleanup-segment-compactDatabase")).not.toBeNull();});+ it("says what compacting costs beneath its switch, once it is switched on", async () => {+ await openDialog();++ // Unpicked, the cost is beside the point, exactly as the revision qualifiers are.+ expect(document.body.querySelector(".cleanup-compact-notice")).toBeNull();++ await toggle(document.body.querySelector<HTMLElement>(".cleanup-item-compact") ?? undefined);+ expect(document.body.querySelector(".cleanup-compact-notice")?.textContent)+ .toBe(t("space_usage.cleanup_compact_notice") ?? "");+ });+it("counts a rebuild into the whole, and into the offer once it is picked", async () => {await openDialog();@@ -340,6 +353,12 @@ describe("showCleanupDialog", () => {const warned = await confirmationHtml();expect(warned).toContain("admonition");expect(warned).toContain("warning");++ // The headroom quoted is twice the database, which is SQLite's own ceiling for a rebuild.+ // Read off the element rather than the rendered text: the wording is interpolated inside+ // t(), which the test i18n answers with nothing at all.+ const [ message ] = mocks.confirm.mock.calls.at(-1) ?? [];+ expect((message as VNode<{ headroomBytes: number }>)?.props.headroomBytes).toBe(DATABASE_BYTES * 2);});it("erases nothing when the confirmation is declined, and stays open to be reconsidered", async () => {diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsxindex 1e2d473990..efc9fb869f 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx@@ -1,6 +1,6 @@import "./cleanup_dialog.css";-import type { SpaceUsageNoteResponse } from "@triliumnext/commons";+import type { CompactionEstimateResponse, SpaceUsageNoteResponse } from "@triliumnext/commons";import clsx from "clsx";import { render } from "preact";import { useEffect, useMemo, useRef, useState } from "preact/hooks";@@ -81,16 +81,16 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)const trimmed = useSpaceUsageFetch<SpaceUsageNoteResponse>(`${ROOT_USAGE_URL}?snapshotsToKeep=${settledSnapshotsToKeep}&keepNamedSnapshots=${options.keepNamedSnapshots}`);- // What a rebuild would return, read once on open: only erasures move it, and none run while the- // dialog is up. Absent in the build that cannot rebuild at all.- const [ compaction, setCompaction ] = useState(0);+ // What a rebuild would return, and what the file occupies now — read once on open: only erasures+ // move either, and none run while the dialog is up. Absent in the build that cannot rebuild.+ const [ compaction, setCompaction ] = useState(NO_COMPACTION);useEffect(() => {if (!isStandalone) {- void measureCompactionEstimate().then(setCompaction).catch(() => setCompaction(0));+ void measureCompactionEstimate().then(setCompaction).catch(() => setCompaction(NO_COMPACTION));}}, []);- const sizes = computeCleanupSizes(everything.data, trimmed.data, options, compaction);+ const sizes = computeCleanupSizes(everything.data, trimmed.data, options, compaction.reclaimableBytes);const measuring = everything.loading || trimmed.loading;// Nothing picked, or nothing to gain from what is: either way the run would be a no-op, and a// button that erases without recourse must not be offered for one.@@ -131,7 +131,14 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)const pending = useRef<{ options: CleanupToolOptions, reclaimed: number } | null>(null);async function confirmAndClose() {- if (!await dialogService.confirm(<CleanupConfirmation compacting={options.compactDatabase} />)) {+ const confirmation = (+ <CleanupConfirmation+ compacting={options.compactDatabase}+ headroomBytes={compaction.databaseBytes * VACUUM_HEADROOM_FACTOR}+ />+ );++ if (!await dialogService.confirm(confirmation)) {return;}@@ -240,7 +247,17 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)Absent where the endpoint is: vacuuming lives in the server build, not in theone that runs the database in-process. */}{!isStandalone && (- <CardSection className="cleanup-item cleanup-item-compact">+ <CardSection+ className="cleanup-item cleanup-item-compact"+ // Said here as well as in the confirmation: this is where the choice is+ // actually made, and the cost belongs beside the switch that incurs it.+ subSectionsVisible={options.compactDatabase}+ subSections={[+ <CardSection key="compact-notice" className="cleanup-compact-notice">+ {t("space_usage.cleanup_compact_notice")}+ </CardSection>+ ]}+ ><span className="cleanup-item-swatch" aria-hidden="true" /><span className="cleanup-item-title">{t("space_usage.cleanup_compact_database")}</span><span className="cleanup-item-size">{formatSize(sizes.compaction)}</span>@@ -260,7 +277,7 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)* qualifies rather than repeats — what compacting costs, when it is being asked for, and the one* reassurance worth giving about an operation whose first sentence is that it deletes.*/-function CleanupConfirmation({ compacting }: { compacting: boolean }) {+function CleanupConfirmation({ compacting, headroomBytes }: { compacting: boolean, headroomBytes: number }) {return (<><p>{t("space_usage.cleanup_confirm")}</p>@@ -271,7 +288,9 @@ function CleanupConfirmation({ compacting }: { compacting: boolean }) {icon="bx bx-time-five"title={t("space_usage.cleanup_confirm_compacting_title")}>- {t("space_usage.cleanup_confirm_compacting")}+ {/* The headroom is the database's own size: a rebuild writes a fresh copy of it+ before the original is replaced, so that much has to be free meanwhile. */}+ {t("space_usage.cleanup_confirm_compacting", { space: formatSize(headroomBytes) })}</ExtendedAdmonition>)}@@ -286,6 +305,18 @@ function CleanupConfirmation({ compacting }: { compacting: boolean }) {/** Both figures come from the root, whose subtree is the whole visible database. */const ROOT_USAGE_URL = "space-usage/note/root";+/** Stands in until the reading lands, and where there is no rebuilding to be had at all. */+const NO_COMPACTION: CompactionEstimateResponse = { reclaimableBytes: 0, databaseBytes: 0 };++/**+ * How much room a rebuild wants beside the database, as a multiple of it. SQLite's own guidance for+ * VACUUM is "as much as twice the size of the original database file … in free disk space": it writes+ * a fresh copy while the original is still there, and in WAL mode the copy-back goes through a log+ * that grows to match. Quoted as a ceiling on purpose — a disk filling up mid-rebuild is a far worse+ * outcome than a warning that asked for more than it took.+ */+const VACUUM_HEADROOM_FACTOR = 2;+/** Shared by every phase of a run, so the message is swapped in place rather than stacked. */export const CLEANUP_TOAST_ID = "content-manager-cleanup";diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.tsindex a091d2805a..1bca20bc44 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts@@ -211,14 +211,15 @@ export async function runCleanup(}/**- * Bytes a rebuild would return: the pages already free inside the file, which erasing content puts- * there and only a rebuild takes back. Disjoint from the content figures — those weigh live content- * that is *about* to be freed, this weighs what already has been.+ * What a rebuild would return, and what the database occupies now.+ *+ * The first is the pages already free inside the file, which erasing content puts there and only a+ * rebuild takes back — disjoint from the content figures, since those weigh live content that is+ * *about* to be freed and this weighs what already has been. The second is what the operation wants+ * as headroom while it runs, a rebuild being a fresh copy written before the original is replaced.*/-export async function measureCompactionEstimate(): Promise<number> {- const { reclaimableBytes } = await server.get<CompactionEstimateResponse>("database/compaction-estimate");-- return reclaimableBytes;+export async function measureCompactionEstimate(): Promise<CompactionEstimateResponse> {+ return await server.get<CompactionEstimateResponse>("database/compaction-estimate");}/**diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.tsindex 530213d96e..bc535f4362 100644--- a/apps/server/src/routes/api/database.spec.ts+++ b/apps/server/src/routes/api/database.spec.ts@@ -58,6 +58,9 @@ describe("Database API", () => {it("estimates what a rebuild would return, which is nothing right after one", () => {const before = databaseRoute.getCompactionEstimate();expect(before.reclaimableBytes).toBeGreaterThanOrEqual(0);+ // The database's own size comes back alongside: it is the headroom a rebuild wants while it+ // runs, and free pages are part of what it currently occupies.+ expect(before.databaseBytes).toBeGreaterThan(before.reclaimableBytes);// A vacuum leaves no free pages behind, so the estimate that follows one is zero — which is// what ties this figure to the thing it claims to predict.diff --git a/apps/server/src/routes/api/database.ts b/apps/server/src/routes/api/database.tsindex b57ed0bb2c..9e87227250 100644--- a/apps/server/src/routes/api/database.ts+++ b/apps/server/src/routes/api/database.ts@@ -51,7 +51,10 @@ function vacuumDatabase() {* until a vacuum returns it.*/function getCompactionEstimate() {- return { reclaimableBytes: reclaimableBytes() } satisfies CompactionEstimateResponse;+ return {+ reclaimableBytes: reclaimableBytes(),+ databaseBytes: databaseBytes()+ } satisfies CompactionEstimateResponse;}/**diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex f984f09de4..9896f1cf04 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -124,6 +124,11 @@ export interface CompactionEstimateResponse {* a promise: a rebuild also recovers the slack left inside pages still in use.*/reclaimableBytes: number;+ /**+ * What the database occupies now, free pages included. Rebuilding writes a fresh copy of it+ * before replacing the original, so this is also the headroom the operation wants while it runs.+ */+ databaseBytes: number;}export interface DatabaseAnonymizeResponse {