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
core/space usage: add API for retrieving the amount of unused attachments
Adorian Doranb5f04902b7fa
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsxindex 99deacfef5..7b713c7167 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx@@ -62,6 +62,7 @@ const OVERVIEW: SpaceUsageOverviewResponse = {otherNotes: { size: 0, revisionsSize: 0, noteCount: 0 },hiddenNotes: { size: 0, revisionsSize: 0, noteCount: 0 },deletedNotes: { size: 900, noteCount: 3, attachmentCount: 2 },+ unusedAttachments: { size: 0, attachmentCount: 0 },total: { size: 3500, revisionsSize: 0, noteCount: 12 }};diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsxindex 35fead1d21..80a1179c9f 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx@@ -48,6 +48,7 @@ const OVERVIEW: SpaceUsageOverviewResponse = {otherNotes: { size: 50, revisionsSize: 0, noteCount: 2 },hiddenNotes: { size: 80, revisionsSize: 0, noteCount: 10 },deletedNotes: { size: 70, noteCount: 1, attachmentCount: 0 },+ unusedAttachments: { size: 0, attachmentCount: 0 },total: { size: 250, revisionsSize: 0, noteCount: 3 }};diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.tsindex 49674814be..2b98c44330 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts@@ -15,6 +15,7 @@ function response(notes: SpaceUsageOverviewNote[], overrides: Partial<SpaceUsageotherNotes: { size: 0, revisionsSize: 0, noteCount: 0 },hiddenNotes: { size: 0, revisionsSize: 0, noteCount: 0 },deletedNotes: { size: 0, noteCount: 0, attachmentCount: 0 },+ unusedAttachments: { size: 0, attachmentCount: 0 },total: { size: 0, revisionsSize: 0, noteCount: 0 },...overrides};diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 4e84d8ad18..32e60a1ef8 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -277,6 +277,24 @@ export interface SpaceUsageDeletedNotes {attachmentCount: number;}+/**+ * Space held by attachments a live note still owns but no longer references from its content —+ * an image or file inserted and then removed. Saving the note schedules those for erasure, and the+ * scheduled cleanup erases them once `eraseUnusedAttachmentsAfterSeconds` has passed.+ *+ * Every scheduled attachment counts, not only those already past that delay, so the figure is what+ * erasing unused attachments *now* would remove.+ */+export interface SpaceUsageUnusedAttachments {+ /**+ * What erasing them would actually reclaim: their blobs, counted once, minus any still held by+ * a live note body, a still-referenced attachment or a revision.+ */+ size: number;+ /** Attachments scheduled for erasure, whether or not something else shares their content. */+ attachmentCount: number;+}+/*** What the live content actually occupies — every blob referenced by a live note, attachment or* revision, hidden subtree included, counted once however many entities share it through@@ -306,6 +324,7 @@ export interface SpaceUsageOverviewResponse {/** Notes reachable only through the hidden subtree, plus any note not reachable at all. */hiddenNotes: SpaceUsageBucket;deletedNotes: SpaceUsageDeletedNotes;+ unusedAttachments: SpaceUsageUnusedAttachments;/** Every note of the visible tree: {@link notes} and {@link otherNotes} combined. */total: SpaceUsageBucket;}@@ -346,6 +365,8 @@ export interface SpaceUsageNoteResponse extends SpaceUsageSizes {children: SpaceUsageChild[];/** Only present on the root, deleted notes having no place in the tree. */deletedNotes?: SpaceUsageDeletedNotes;+ /** Only present on the root: a database-wide figure, like the deleted one beside it. */+ unusedAttachments?: SpaceUsageUnusedAttachments;}export interface SimilarNote {diff --git a/packages/trilium-core/src/routes/api/space_usage.spec.ts b/packages/trilium-core/src/routes/api/space_usage.spec.tsindex 71b2ce1af8..93fa83573d 100644--- a/packages/trilium-core/src/routes/api/space_usage.spec.ts+++ b/packages/trilium-core/src/routes/api/space_usage.spec.ts@@ -247,6 +247,62 @@ describe("Space usage API (core)", () => {expect(after.deletedNotes.size - before.deletedNotes.size).toBeGreaterThanOrEqual(content.length);});+ it("reports attachments a live note no longer references, and what erasing them would free", async () => {+ const content = "space-usage-unused-attachment-".repeat(100);+ const host = await createTextNote(api, { title: "Space usage unused host", content: "<p>host</p>" });++ const createRes = await api.post(`/api/notes/${host.noteId}/attachments`, {+ body: { role: "file", mime: "text/plain", title: "Space usage unused attachment", content }+ });+ expect(createRes.status).toBe(204);++ const before = await getOverview({ limit: 1 });++ // Nothing in the body links to it, so saving the note schedules the attachment for erasure.+ const saveRes = await api.put(`/api/notes/${host.noteId}/data`, {+ body: { content: "<p>host, edited</p>" }+ });+ expect(saveRes.status).toBe(204);++ const after = await getOverview({ limit: 1 });+ const { unusedAttachments } = after;+ expect(unusedAttachments.attachmentCount).toBe(before.unusedAttachments.attachmentCount + 1);+ expect(unusedAttachments.size - before.unusedAttachments.size)+ .toBeGreaterThanOrEqual(content.length);+ // Awaiting cleanup is not being deleted: the attachment is still live content, and the+ // deleted figure beside it must not move.+ expect(after.deletedNotes.attachmentCount).toBe(before.deletedNotes.attachmentCount);++ // Database-wide, like the deleted figure, so it surfaces at the root and nowhere else.+ const rootUsage = await getNoteUsage("root");+ expect(rootUsage.unusedAttachments?.size).toBeGreaterThanOrEqual(content.length);+ expect((await getNoteUsage(host.noteId)).unusedAttachments).toBeUndefined();+ });++ it("counts an unused attachment's space only where nothing live still holds it", async () => {+ const shared = "space-usage-shared-attachment-".repeat(100);+ // A live note whose body is that very content, so both end up on one deduplicated blob.+ await createTextNote(api, { title: "Space usage shared body", content: shared });+ const host = await createTextNote(api, { title: "Space usage shared host", content: "<p>host</p>" });++ const createRes = await api.post(`/api/notes/${host.noteId}/attachments`, {+ body: { role: "file", mime: "text/plain", title: "Space usage shared attachment", content: shared }+ });+ expect(createRes.status).toBe(204);++ const before = await getOverview({ limit: 1 });+ const saveRes = await api.put(`/api/notes/${host.noteId}/data`, {+ body: { content: "<p>host, edited</p>" }+ });+ expect(saveRes.status).toBe(204);++ const { unusedAttachments } = await getOverview({ limit: 1 });+ // One more attachment to erase, yet erasing it would free nothing at all: the blob it holds+ // is the live note's body too.+ expect(unusedAttachments.attachmentCount).toBe(before.unusedAttachments.attachmentCount + 1);+ expect(unusedAttachments.size).toBe(before.unusedAttachments.size);+ });+it("defaults and clamps the overview limit", async () => {// No limit → the server default applies and the request just works.const defaulted = await getOverview();diff --git a/packages/trilium-core/src/services/space_usage.ts b/packages/trilium-core/src/services/space_usage.tsindex 7da4f62fa7..ca4fea5072 100644--- a/packages/trilium-core/src/services/space_usage.ts+++ b/packages/trilium-core/src/services/space_usage.ts@@ -4,7 +4,8 @@ import {SpaceUsageDeletedNotes,SpaceUsageNoteResponse,SpaceUsageOverviewResponse,- SpaceUsageSizes+ SpaceUsageSizes,+ SpaceUsageUnusedAttachments} from "@triliumnext/commons";import becca from "../becca/becca.js";@@ -26,8 +27,9 @@ import { getSql } from "./sql/index.js";** Sizes are `LENGTH(blobs.content)` like the existing per-note stats endpoints, so the numbers match* what the note info widget already shows. Blobs shared between entities through deduplication are- * counted at each entity, so per-note numbers stay meaningful; the deleted-notes aggregate is the- * exception — it only counts blobs no live entity still uses, i.e. what erasing would reclaim.+ * counted at each entity, so per-note numbers stay meaningful; the reclaimable aggregates — deleted+ * notes and unused attachments — are the exception, counting only blobs nothing else would keep+ * alive, i.e. what erasing would really free.*/export const DEFAULT_OVERVIEW_LIMIT = 500;@@ -99,6 +101,7 @@ function buildOverview({ includeRevisions, limit }: { includeRevisions: boolean,otherNotes: bucketOf(others),hiddenNotes: bucketOf(forest.hiddenNoteIds.map((noteId) => sizesOf(noteId, sizes))),deletedNotes: collectDeletedNotes(),+ unusedAttachments: collectUnusedAttachments(),total: bucketOf(ranked)};}@@ -163,8 +166,12 @@ function buildNoteUsage(noteId: string): SpaceUsageNoteResponse {subtreeRevisionsContentSize: collectRevisionsSizeOf(subtreeNoteIds),attachments,children,- // Deleted notes have no place in the tree, so they surface once, at its root.- ...(noteId === ROOT_NOTE_ID ? { deletedNotes: collectDeletedNotes() } : {})+ // Deleted notes have no place in the tree, so they surface once, at its root. Unused+ // attachments do have one, but the figure is what erasing *all* of them would reclaim —+ // a database-wide number like the deleted one, so it belongs in the same place.+ ...(noteId === ROOT_NOTE_ID+ ? { deletedNotes: collectDeletedNotes(), unusedAttachments: collectUnusedAttachments() }+ : {})};}@@ -415,6 +422,25 @@ const LIVE_NOTE_ATTACHMENT_BLOBS = `JOIN notes ON notes.noteId = attachments.ownerIdWHERE attachments.isDeleted = 0 AND notes.isDeleted = 0 AND attachments.blobId IS NOT NULL`;+/**+ * Attachments a live note owns but whose content no longer mentions them, which saving the note+ * marked for erasure (see `checkImageAttachments`). They are live rows, so the tagging above counts+ * them among the live attachments — measuring what erasing them frees takes {@link+ * collectUnusedAttachments}.+ */+const UNUSED_ATTACHMENT_BLOBS = `+ SELECT attachments.blobId FROM attachments+ JOIN notes ON notes.noteId = attachments.ownerId+ WHERE attachments.isDeleted = 0 AND notes.isDeleted = 0 AND attachments.blobId IS NOT NULL+ AND attachments.utcDateScheduledForErasureSince IS NOT NULL`;++/** The rest of {@link LIVE_NOTE_ATTACHMENT_BLOBS}: those a note still references. */+const USED_NOTE_ATTACHMENT_BLOBS = `+ SELECT attachments.blobId FROM attachments+ JOIN notes ON notes.noteId = attachments.ownerId+ WHERE attachments.isDeleted = 0 AND notes.isDeleted = 0 AND attachments.blobId IS NOT NULL+ AND attachments.utcDateScheduledForErasureSince IS NULL`;+const LIVE_REVISION_BLOBS = `SELECT revisions.blobId FROM revisionsJOIN notes ON notes.noteId = revisions.noteId@@ -604,6 +630,42 @@ function collectDeletedNotes(): SpaceUsageDeletedNotes {};}+/**+ * What erasing the unused attachments would reclaim, deduplicated by blobId — several of them+ * holding the same content free it once.+ *+ * The blob tags cannot answer this on their own: an unused attachment is still a live attachment,+ * so it claims its blob as {@link BLOB_ATTACHMENT} and hides whatever else holds it. Every other+ * live claim is therefore re-checked here, the body one off the tag (bodies outrank attachments, so+ * a shared blob still reads as one) and the two the tag swallowed by subquery.+ *+ * A blob a *deleted* entity also holds counts here rather than in {@link collectDeletedNotes},+ * whose figure the same live-attachment claim already excludes it from: erasing both cleanups frees+ * it, and it is reported once, under the strongest claim on it.+ */+function collectUnusedAttachments(): SpaceUsageUnusedAttachments {+ const sql = getSql();++ return {+ size: sql.getValue<number | null>(`+ SELECT SUM(blob_usage.size)+ FROM blob_usage+ WHERE blob_usage.blobId IN (${UNUSED_ATTACHMENT_BLOBS})+ AND blob_usage.kind != ${BLOB_BODY}+ AND blob_usage.blobId NOT IN (${USED_NOTE_ATTACHMENT_BLOBS})+ AND blob_usage.blobId NOT IN (${LIVE_REVISION_BLOBS})`) ?? 0,+ // Every scheduled attachment, shared content included: the count says how many the cleanup+ // would remove, the size how much that would actually free.+ attachmentCount: sql.getValue<number>(`+ SELECT COUNT(*)+ FROM attachments+ JOIN notes ON notes.noteId = attachments.ownerId+ JOIN blob_usage ON blob_usage.blobId = attachments.blobId+ WHERE attachments.isDeleted = 0 AND notes.isDeleted = 0+ AND attachments.utcDateScheduledForErasureSince IS NOT NULL`)+ };+}+function buildForestFromBecca(): CanonicalForest {return buildCanonicalForest((noteId) => {