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: show saving estimates for vacuuming the DB
Adorian Doran1817cf4aa3fc
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 49d0811acd..400021ae19 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2892,8 +2892,7 @@"cleanup_clean": "Clean","cleanup_confirm": "This permanently deletes the selected data. It cannot be undone.","cleanup_done": "Cleanup completed, reclaiming {{size}}.",- "cleanup_compact_database": "Compact database",- "cleanup_amount_unknown": "??? B"+ "cleanup_compact_database": "Compact database"},"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 b0a4bc37b9..f9658da896 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@@ -6,6 +6,9 @@--cleanup-deleted-color: color-mix(in srgb, var(--accented-background-color) 55%, #d9645b 45%);--cleanup-attachments-color: color-mix(in srgb, var(--accented-background-color) 55%, #d9a93d 45%);--cleanup-revisions-color: color-mix(in srgb, var(--accented-background-color) 55%, #8f959c 45%);+ /* Blue, as the browse donut paints a note's own body: this segment is the file itself rather+ than any of the content in it. */+ --cleanup-compact-color: color-mix(in srgb, var(--accented-background-color) 55%, #5b8dd9 45%);/* Sized by its content rather than to the floor the component sets: no item title wraps, so along one has to widen the dialog. Capped at the viewport, past which there is nowhere to grow. */@@ -84,6 +87,10 @@--donut-segment-color: var(--cleanup-revisions-color);}+ .cleanup-segment-compactDatabase {+ --donut-segment-color: var(--cleanup-compact-color);+ }+/* Left in place rather than removed: the ring stands for everything reclaimable, so an unpickeditem keeps its share of it and only stops being claimed. */.cleanup-segment-unpicked {@@ -110,10 +117,8 @@--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-color: var(--cleanup-compact-color);}.cleanup-item-swatch {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 c55a15abcd..81a1473a19 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@@ -7,11 +7,15 @@ import { t } from "../../../../../services/i18n";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, MEASURED_BEFORE, MEASURED_AFTER } = vi.hoisted(() => ({+const {+ REVISIONS_ALL, REVISIONS_TRIMMED, DELETED, UNUSED, FREE_PAGES, MEASURED_BEFORE, MEASURED_AFTER+} = vi.hoisted(() => ({REVISIONS_ALL: 900,REVISIONS_TRIMMED: 300,DELETED: 100,UNUSED: 20,+ /** Pages already free in the file, which only a rebuild returns. */+ FREE_PAGES: 640,// Deliberately unlike any estimate above, so a toast quoting a prediction cannot pass for one// quoting the measurement.MEASURED_BEFORE: 7777,@@ -46,6 +50,10 @@ vi.mock("../../../../../services/server", () => ({get: (url: string) => {mocks.get(url);+ if (url === "database/compaction-estimate") {+ return Promise.resolve({ reclaimableBytes: FREE_PAGES });+ }+if (!url.startsWith("space-usage/")) {return Promise.resolve(url === "keyboard-actions" ? [] : {});}@@ -213,32 +221,33 @@ 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 () => {+ it("offers compacting as a row of its own, with a figure and an arc to match", 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);+ // The pages already free inside the file, standing for space as surely as the content+ // above — so it takes an arc, which is what its swatch beside it names.+ expect(compact?.querySelector(".cleanup-item-size")?.textContent).toBe(formatSize(FREE_PAGES));+ expect(document.body.querySelectorAll(".donut-segment").length).toBe(4);+ expect(document.body.querySelector(".cleanup-segment-compactDatabase")).not.toBeNull();});- it("gives no figure for a run that only compacts, rather than answering zero", async () => {- mocks.storedOption = JSON.stringify({ compactDatabase: true });+ it("counts a rebuild into the whole, and into the offer once it is picked", async () => {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);+ // Present in the whole from the start: it is reclaimable whether or not it is asked for.+ expect(textOf(".cleanup-chart-total")).toBe(t("space_usage.cleanup_amount_of", {+ total: formatSize(REVISIONS_ALL + DELETED + UNUSED + FREE_PAGES)+ }) ?? "");+ expect(textOf(".cleanup-chart-amount")).toBe(formatSize(0));- // 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();+ // Picked on its own, it is the whole of the offer — and worth running, though it erases+ // nothing, so the button has to allow it.+ await toggle(document.body.querySelector<HTMLElement>(".cleanup-item-compact") ?? undefined);+ expect(textOf(".cleanup-chart-amount")).toBe(formatSize(FREE_PAGES));+ expect(cleanButton()?.disabled).toBe(false);});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 fe604a7d47..c84862fb47 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@@ -21,6 +21,7 @@ import {type CleanupToolOptions,computeCleanupSizes,hasWorkToDo,+ measureCompactionEstimate,readCleanupOptions,runCleanup} from "./cleanup_operation";@@ -78,14 +79,20 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)const trimmed = useSpaceUsageFetch<SpaceUsageNoteResponse>(`${ROOT_USAGE_URL}?snapshotsToKeep=${settledSnapshotsToKeep}&keepNamedSnapshots=${options.keepNamedSnapshots}`);- const sizes = computeCleanupSizes(everything.data, trimmed.data, options);+ // 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);+ useEffect(() => {+ if (!isStandalone) {+ void measureCompactionEstimate().then(setCompaction).catch(() => setCompaction(0));+ }+ }, []);++ const sizes = computeCleanupSizes(everything.data, trimmed.data, options, compaction);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 || !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",@@ -94,15 +101,28 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)// A database with nothing to reclaim draws no segment at all; the track is what keeps the// reading in its hole from floating in an empty square.track: true,- segments: CLEANUP_ITEMS.map((item) => ({- id: item.id,- value: sizes.perItem[item.id],- className: clsx(`cleanup-segment-${item.id}`, !options[item.id] && "cleanup-segment-unpicked"),- tooltip: t(item.labelKey)- }))+ segments: [+ ...CLEANUP_ITEMS.map((item) => ({+ id: item.id,+ value: sizes.perItem[item.id],+ className: clsx(`cleanup-segment-${item.id}`, !options[item.id] && "cleanup-segment-unpicked"),+ tooltip: t(item.labelKey)+ })),+ // The free pages a rebuild would return stand for space as surely as the content above+ // does, so they take an arc of their own — which is what lets the row's swatch beside+ // them be read as naming one.+ ...(isStandalone ? [] : [ {+ id: "compactDatabase",+ value: sizes.compaction,+ className: clsx("cleanup-segment-compactDatabase",+ !options.compactDatabase && "cleanup-segment-unpicked"),+ tooltip: t("space_usage.cleanup_compact_database")+ } ])+ ]// eslint-disable-next-line react-hooks/exhaustive-deps}), [ sizes.perItem.deletedEntities, sizes.perItem.unusedAttachments, sizes.perItem.revisionSnapshots,- options.deletedEntities, options.unusedAttachments, options.revisionSnapshots ]);+ sizes.compaction, options.deletedEntities, options.unusedAttachments, options.revisionSnapshots,+ options.compactDatabase ]);// What the run was asked to do, held across the close: the operation starts once the dialog is// out of the way, by which time the state it was configured from is on its way out too.@@ -162,18 +182,11 @@ 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">- {unmeasurable ? t("space_usage.cleanup_amount_unknown") : formatSize(sizes.selected)}+ <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>- {/* 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>@@ -218,14 +231,15 @@ 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. */}+ {/* Its figure is the pages already free inside the file, which only a rebuild+ returns — no part of any content figure, and so an arc and a color of its own.+ 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>+ <span className="cleanup-item-size">{formatSize(sizes.compaction)}</span><FormTogglecurrentValue={options.compactDatabase}onChange={(value) => update({ compactDatabase: value })}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 6c47aa18be..be48a2ea63 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@@ -3,7 +3,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({getInt: vi.fn<(name: string) => number | null>(() => -1),- post: vi.fn(async (_url: string, _body?: object) => {}),+ post: vi.fn(async (url: string, _body?: object) => (+ url === "database/vacuum-database" ? { sizeBefore: 9000, sizeAfter: 2000 } : undefined+ )),/** Occupied bytes, read once before the erasures and once after; shifted per test. */occupied: [ 5000, 3000 ],get: vi.fn()@@ -102,10 +104,24 @@ describe("computeCleanupSizes", () => {// Keeping snapshots can only take away from what erasing the history outright would free,// so the whole stays put while the item's own figure follows the settings.expect(sizes.total).toBe(900 + 100 + 20);+ expect(sizes.compaction).toBe(0);expect(sizes.perItem).toEqual({ deletedEntities: 100, unusedAttachments: 20, revisionSnapshots: 300 });expect(sizes.selected).toBe(300 + 100 + 20);});+ it("adds what a rebuild would return, which no content figure describes", () => {+ const withCompaction = computeCleanupSizes(usage(900, 100, 20), usage(300), ALL_PICKED, 500);++ // Free pages are what erasing already finished with; the figures above weigh content still+ // to be erased. Neither ever describes the same byte, so the whole is their sum.+ expect(withCompaction.compaction).toBe(500);+ expect(withCompaction.total).toBe(900 + 100 + 20 + 500);+ // Not on offer until compacting is picked, though.+ expect(withCompaction.selected).toBe(300 + 100 + 20);+ expect(computeCleanupSizes(usage(900, 100, 20), usage(300),+ { ...ALL_PICKED, compactDatabase: true }, 500).selected).toBe(300 + 100 + 20 + 500);+ });+it("counts only what is picked, and nothing at all before the measurements arrive", () => {const sizes = computeCleanupSizes(usage(900, 100, 20), usage(300),{ ...ALL_PICKED, deletedEntities: false, revisionSnapshots: false });@@ -149,8 +165,10 @@ 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 });+ it("rebuilds the file last, and reports the file's own before and after", async () => {+ // The rebuild returns 9000 → 2000; the content readings would have said 2000. The file is+ // the truer figure and subsumes the erasures, whose pages the rebuild is what hands back.+ await expect(runCleanup({ ...ALL_PICKED, compactDatabase: true })).resolves.toBe(7000);expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual(["revisions/erase-all-excess-revisions",@@ -159,6 +177,10 @@ describe("runCleanup", () => {"database/vacuum-database","space-usage/cleanup-completed"]);+ expect(mocks.post).toHaveBeenCalledWith("space-usage/cleanup-completed", { reclaimedBytes: 7000 });+ // And the content weighings are skipped entirely, being two readings of the whole database+ // for a figure that is not going to be used.+ expect(mocks.get).not.toHaveBeenCalled();});it("compacts on its own, for a run that erases nothing at all", async () => {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 58cf9250f1..55874ce795 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@@ -1,4 +1,9 @@-import type { SpaceUsageNoteResponse, SpaceUsageOverviewResponse } from "@triliumnext/commons";+import type {+ CompactionEstimateResponse,+ SpaceUsageNoteResponse,+ SpaceUsageOverviewResponse,+ VacuumDatabaseResponse+} from "@triliumnext/commons";import optionService from "../../../../../services/options";import server from "../../../../../services/server";@@ -77,6 +82,8 @@ export function defaultSnapshotsToKeep(): number {export interface CleanupSizes {/** What erasing each item would free, the revisions measured as the settings would trim them. */perItem: Record<CleanupItemId, number>;+ /** What a rebuild would return on top: the pages already free inside the file. */+ compaction: number;/** Everything reclaimable, the revisions measured at their most aggressive — see below. */total: number;/** What the picked items would free. */@@ -97,18 +104,26 @@ export interface CleanupSizes {export function computeCleanupSizes(everything: SpaceUsageNoteResponse | null,trimmed: SpaceUsageNoteResponse | null,- options: CleanupToolOptions+ options: CleanupToolOptions,+ compaction = 0): CleanupSizes {const perItem: Record<CleanupItemId, number> = {deletedEntities: everything?.deletedNotes?.size ?? 0,unusedAttachments: everything?.unusedAttachments?.size ?? 0,revisionSnapshots: trimmed?.subtreeRevisionsContentSize ?? 0};+ const contentTotal = perItem.deletedEntities + perItem.unusedAttachments+ + (everything?.subtreeRevisionsContentSize ?? 0);return {perItem,- total: perItem.deletedEntities + perItem.unusedAttachments + (everything?.subtreeRevisionsContentSize ?? 0),+ compaction,+ // Added rather than folded in: the free pages a rebuild returns are ones erasing already+ // finished with, while the figures above weigh content still to be erased. The two never+ // describe the same byte.+ total: contentTotal + compaction,selected: CLEANUP_ITEMS.reduce((sum, item) => sum + (options[item.id] ? perItem[item.id] : 0), 0)+ + (options.compactDatabase ? compaction : 0)};}@@ -128,7 +143,9 @@ export function computeCleanupSizes(* the cleanup having given space back.*/export async function runCleanup(options: CleanupToolOptions): Promise<number> {- const before = await measureOccupiedBytes();+ // Only weighed when the file is not being rebuilt afterwards; a rebuild reports its own figure,+ // which is the better one and makes these two readings of the whole database wasted work.+ const before = options.compactDatabase ? 0 : await measureOccupiedBytes();if (options.revisionSnapshots) {await server.post("revisions/erase-all-excess-revisions", {@@ -145,13 +162,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);+ const reclaimed = options.compactDatabase+ // Last, with everything already erased: the rebuild closes around whatever is left, and its+ // own before/after is the truest figure there is — the file itself, rather than an account+ // of what the file holds. It subsumes the erasures above, whose pages it is what returns.+ ? await compactDatabase()+ : Math.max(before - await measureOccupiedBytes(), 0);// Recorded on the server as well as shown here: this erased content past recovery, and the log// is where that is answerable for afterwards.@@ -160,6 +176,24 @@ export async function runCleanup(options: CleanupToolOptions): Promise<number> {return reclaimed;}+/** Rebuilds the database file, reporting what it handed back to the disk. */+async function compactDatabase(): Promise<number> {+ const { sizeBefore, sizeAfter } = await server.post<VacuumDatabaseResponse>("database/vacuum-database");++ return Math.max(sizeBefore - sizeAfter, 0);+}++/**+ * 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.+ */+export async function measureCompactionEstimate(): Promise<number> {+ const { reclaimableBytes } = await server.get<CompactionEstimateResponse>("database/compaction-estimate");++ return reclaimableBytes;+}+/*** Every blob the space report accounts for: the live content plus what deleted entities still hold.* Blobs referenced by nothing at all are outside both, which is what makes this the right thing to