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 support for vacuuming the database
Adorian Doran2927b55be353
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex abe5be3845..49d0811acd 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2891,7 +2891,9 @@"cleanup_cancel": "Cancel","cleanup_clean": "Clean","cleanup_confirm": "This permanently deletes the selected data. It cannot be undone.",- "cleanup_done": "Cleanup completed, reclaiming {{size}}."+ "cleanup_done": "Cleanup completed, reclaiming {{size}}.",+ "cleanup_compact_database": "Compact database",+ "cleanup_amount_unknown": "??? B"},"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 dade99fa32..b0a4bc37b9 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@@ -110,6 +110,12 @@--cleanup-item-color: var(--cleanup-revisions-color);}+ /* Nothing on the ring stands for this one, so its swatch names no color — kept rather than+ dropped so the title starts where every title above it does. */+ .cleanup-item-compact {+ --cleanup-item-color: transparent;+ }+.cleanup-item-swatch {flex: 0 0 auto;width: 4px;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 6ab383bc82..c55a15abcd 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@@ -213,6 +213,34 @@ describe("showCleanupDialog", () => {expect(document.body.querySelector(".modal-stub")).toBeNull();});+ it("offers compacting as a row of its own, with neither a figure nor a color", async () => {+ await openDialog();++ const compact = document.body.querySelector<HTMLElement>(".cleanup-item-compact");+ expect(compact?.querySelector(".cleanup-item-title")?.textContent)+ .toBe(t("space_usage.cleanup_compact_database") ?? "");+ // It frees no content, so it states no amount and stands for nothing on the ring.+ expect(compact?.querySelector(".cleanup-item-size")).toBeNull();+ expect(document.body.querySelectorAll(".donut-segment").length).toBe(3);+ });++ it("gives no figure for a run that only compacts, rather than answering zero", async () => {+ mocks.storedOption = JSON.stringify({ compactDatabase: true });+ await openDialog();++ // How much a rebuild hands back is not something the content figures can answer.+ expect(textOf(".cleanup-chart-amount")).toBe(t("space_usage.cleanup_amount_unknown") ?? "");+ expect(document.body.querySelector(".cleanup-chart-total")).toBeNull();+ expect(document.body.querySelector(".cleanup-chart-rule")).toBeNull();+ // Still worth running, though it erases nothing: the button has to allow it.+ expect(cleanButton()?.disabled).toBe(false);++ // Picking something with a size restores the reading it can now give.+ await toggle(rows()[0]);+ expect(textOf(".cleanup-chart-amount")).toBe(formatSize(DELETED));+ expect(document.body.querySelector(".cleanup-chart-total")).not.toBeNull();+ });+it("erases nothing when the confirmation is declined, and stays open to be reconsidered", async () => {mocks.storedOption = JSON.stringify({ unusedAttachments: true });await openDialog();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 89401fa4e0..fe604a7d47 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@@ -8,7 +8,7 @@ import { useEffect, useMemo, useRef, useState } from "preact/hooks";import dialogService from "../../../../../services/dialog";import { t } from "../../../../../services/i18n";import toast from "../../../../../services/toast";-import { formatSize } from "../../../../../services/utils";+import { formatSize, isStandalone } from "../../../../../services/utils";import Button from "../../../../react/Button";import { Card, CardSection } from "../../../../react/Card";import DonutChart, { type DonutRing } from "../../../../react/charts/DonutChart";@@ -20,6 +20,7 @@ import {CLEANUP_ITEMS,type CleanupToolOptions,computeCleanupSizes,+ hasWorkToDo,readCleanupOptions,runCleanup} from "./cleanup_operation";@@ -81,7 +82,10 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)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.- const nothingToDo = measuring || sizes.selected <= 0;+ const nothingToDo = measuring || !hasWorkToDo(options, sizes.selected);+ // A run that only compacts frees nothing the content figures can see, so the reading has no+ // number to give — stating "0" would be answering a question it cannot answer.+ const unmeasurable = options.compactDatabase && sizes.selected <= 0;const ring: DonutRing = useMemo(() => ({id: "cleanup",@@ -158,11 +162,18 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)<DonutChart rings={[ ring ]}><div className="cleanup-chart-center"><span className="cleanup-chart-caption">{t("space_usage.cleanup_estimated")}</span>- <span className="cleanup-chart-amount">{formatSize(sizes.selected)}</span>- <div className="cleanup-chart-rule" aria-hidden="true" />- <span className="cleanup-chart-total">- {t("space_usage.cleanup_amount_of", { total: formatSize(sizes.total) })}+ <span className="cleanup-chart-amount">+ {unmeasurable ? t("space_usage.cleanup_amount_unknown") : formatSize(sizes.selected)}</span>+ {/* Only compacting is picked, and how much a rebuild hands back is not+ something the content figures can answer — so there is no share of the+ whole to state, and nothing for the rule to divide. */}+ {!unmeasurable && <>+ <div className="cleanup-chart-rule" aria-hidden="true" />+ <span className="cleanup-chart-total">+ {t("space_usage.cleanup_amount_of", { total: formatSize(sizes.total) })}+ </span>+ </>}</div></DonutChart></div>@@ -206,6 +217,21 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)/></CardSection>))}++ {/* Frees no content, so it carries no figure and no arc — its swatch is a blank+ holding the titles in line with the rows above. Absent where the endpoint is:+ vacuuming lives in the server build, not in the one that runs the database+ in-process. */}+ {!isStandalone && (+ <CardSection className="cleanup-item cleanup-item-compact">+ <span className="cleanup-item-swatch" aria-hidden="true" />+ <span className="cleanup-item-title">{t("space_usage.cleanup_compact_database")}</span>+ <FormToggle+ currentValue={options.compactDatabase}+ onChange={(value) => update({ compactDatabase: value })}+ />+ </CardSection>+ )}</Card></Modal>);diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.tsindex 2d4f51ede2..6c47aa18be 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts@@ -42,7 +42,8 @@ const ALL_PICKED: CleanupToolOptions = {unusedAttachments: true,revisionSnapshots: true,snapshotsToKeep: 3,- keepNamedSnapshots: true+ keepNamedSnapshots: true,+ compactDatabase: false};beforeEach(() => {@@ -61,7 +62,8 @@ describe("readCleanupOptions", () => {unusedAttachments: false,revisionSnapshots: false,snapshotsToKeep: 4,- keepNamedSnapshots: false+ keepNamedSnapshots: false,+ compactDatabase: false});}});@@ -84,7 +86,8 @@ describe("readCleanupOptions", () => {unusedAttachments: false,revisionSnapshots: true,snapshotsToKeep: 0,- keepNamedSnapshots: true+ keepNamedSnapshots: true,+ compactDatabase: false});// A retention that could not have been written by the dialog falls back rather than through.@@ -146,6 +149,34 @@ describe("runCleanup", () => {await expect(runCleanup(ALL_PICKED)).resolves.toBe(0);});+ it("rebuilds the file last, once there is nothing further to erase out of it", async () => {+ await runCleanup({ ...ALL_PICKED, compactDatabase: true });++ expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([+ "revisions/erase-all-excess-revisions",+ "notes/erase-unused-attachments-now",+ "notes/erase-deleted-notes-now",+ "database/vacuum-database",+ "space-usage/cleanup-completed"+ ]);+ });++ it("compacts on its own, for a run that erases nothing at all", async () => {+ mocks.occupied = [ 5000, 5000 ];+ const nothingErased = {+ ...ALL_PICKED,+ deletedEntities: false,+ unusedAttachments: false,+ revisionSnapshots: false,+ compactDatabase: true+ };++ await runCleanup(nothingErased);++ expect(mocks.post.mock.calls.map(([ url ]) => url))+ .toEqual([ "database/vacuum-database", "space-usage/cleanup-completed" ]);+ });+it("asks for nothing that was not picked", async () => {await runCleanup({ ...ALL_PICKED, revisionSnapshots: false, deletedEntities: false });expect(mocks.post.mock.calls.map(([ url ]) => url))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 546c9f4b00..58cf9250f1 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@@ -23,6 +23,11 @@ export interface CleanupToolOptions {/** Revision snapshots kept per note; 0 erases the history outright. */snapshotsToKeep: number;keepNamedSnapshots: boolean;+ /**+ * Rebuild the database file afterwards. Erasing hands pages back to the database, which reuses+ * them but never shrinks the file; only this returns the space to the disk.+ */+ compactDatabase: boolean;}/** Where the snapshots field starts when no useful limit is configured. */@@ -43,10 +48,20 @@ export function readCleanupOptions(stored: Partial<CleanupToolOptions> | null |snapshotsToKeep: Number.isInteger(snapshotsToKeep) && Number(snapshotsToKeep) >= 0? Number(snapshotsToKeep): defaultSnapshotsToKeep(),- keepNamedSnapshots: stored?.keepNamedSnapshots === true+ keepNamedSnapshots: stored?.keepNamedSnapshots === true,+ compactDatabase: stored?.compactDatabase === true};}+/**+ * Whether the settings amount to anything worth running. Compacting counts on its own: it frees no+ * *accounted* bytes — the figures are about content, and it moves none — but it is the only step+ * that hands space back to the disk, so a run asking for nothing else is still a run.+ */+export function hasWorkToDo(options: CleanupToolOptions, selectedBytes: number): boolean {+ return selectedBytes > 0 || options.compactDatabase;+}+/*** How many snapshots the field offers to keep before anything has been stored: whatever the note* revision limit is set to, so the cleanup opens proposing the retention the user already chose. A@@ -130,6 +145,12 @@ export async function runCleanup(options: CleanupToolOptions): Promise<number> {await server.post("notes/erase-deleted-notes-now");}+ if (options.compactDatabase) {+ // Last, with everything already erased: this rebuilds the file around whatever is left, so+ // anything erased afterwards would leave a hole it has just been rebuilt to close.+ await server.post("database/vacuum-database");+ }+const reclaimed = Math.max(before - await measureOccupiedBytes(), 0);// Recorded on the server as well as shown here: this erased content past recovery, and the log