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/image compression: performance improvements
Adorian Doran26f577c83f15
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex 5058b5859e..b92dedf3ec 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -134,6 +134,31 @@ describe("compress note images (POST /api/notes/:noteId/compress-images)", () =>expect(readAttachment(small).size).toBe(smallPng.byteLength);});+ it("keeps each note's images with that note, in the order that note holds them", async () => {+ const { noteId: parentId } = await createTextNote(api);+ const { noteId: firstId } = await createTextNote(api, { parentNoteId: parentId });+ const { noteId: secondId } = await createTextNote(api, { parentNoteId: parentId });++ // Positions deliberately at odds with the order they are created in, so the run has to be+ // following the note's own ordering rather than whatever the database hands back.+ const firstLate = await addAttachment(firstId, "a.png", smallPng, { position: 20 });+ const firstEarly = await addAttachment(firstId, "b.png", smallPng, { position: 10 });+ const second = [+ await addAttachment(secondId, "c.png", smallPng, { position: 10 }),+ await addAttachment(secondId, "d.png", smallPng, { position: 20 })+ ];+ const first = [ firstEarly, firstLate ];++ const res = await api.post<ImageCompressionResponse>(`/api/notes/${parentId}/compress-images`, {+ body: { recursive: true }+ });++ // The subtree's attachments are fetched in one query and grouped back by owner, so this is+ // what says the grouping is right: every image with the note that holds it, notes in the+ // order the subtree gave them, images in the order the note keeps them.+ expect(res.body.items.map((item) => item.entityId)).toEqual([ ...first, ...second ]);+ });+it("reports an empty run for a note holding no images", async () => {const { noteId } = await createTextNote(api);@@ -617,10 +642,11 @@ async function addAttachment(noteId: string,title: string,content: Uint8Array,- { role = "image", mime = "image/png" } = {}+ { role = "image", mime = "image/png", position }: { role?: string, mime?: string, position?: number } = {}): Promise<string> {return cls.init(() => getSql().transactional(() => {- const attachment = becca.getNoteOrThrow(noteId).saveAttachment({ role, mime, title, content }, "title");+ const attachment = becca.getNoteOrThrow(noteId)+ .saveAttachment({ role, mime, title, content, position }, "title");return attachment.attachmentId ?? "";}));}diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.tsindex 8110d6bfd4..fd52ef44a9 100644--- a/apps/server/src/services/image_provider.spec.ts+++ b/apps/server/src/services/image_provider.spec.ts@@ -300,6 +300,20 @@ describe('serverImageProvider.compressImage', () => {expect(outcome).toEqual({ compressed: false, reason: 'unsupported-format' });});+ it('reads an image that is a window onto a larger buffer, not the buffer behind it', async () => {+ // The bytes handed around are Uint8Arrays, which the libraries below want as Buffers. Taking+ // a view rather than a copy is what keeps a run from duplicating every photograph in a tree+ // — but a view carries an offset, and forgetting it would read whatever sits in front of the+ // image. Every other fixture here starts at zero, where that mistake looks like it works.+ const padded = new Uint8Array(64 + noisyPng.byteLength + 64).fill(0xab);+ padded.set(noisyPng, 64);++ const outcome = await serverImageProvider.compressImage(+ padded.subarray(64, 64 + noisyPng.byteLength), request({ maxWidthHeight: 100 }));++ expect(outcome).toMatchObject({ compressed: true });+ });+it('ignores the compressImages option, which only governs automatic shrinking', async () => {setOptions({ compressImages: 'false' });diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex 1691c37dff..88a3e74d08 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -82,7 +82,7 @@ function planFromBytes(animated images already fail the format gate (file-type reports animated PNG as "apng"and animated GIF/WebP as gif/webp). Only a pathological PNG with 512+ chunks before itsacTL chunk reaches here, and recompressing it would keep the first frame alone. */- if (isAnimated(Buffer.from(bytes))) {+ if (isAnimated(asBuffer(bytes))) {return { verdict: "skip", reason: "animated" };}/* v8 ignore stop */@@ -136,7 +136,19 @@ function exceedsDecodeCeiling({ width, height }: InspectedImage): boolean {* them, so passing a memory budget there reads as correct and does nothing at all.*/function decodeImage(buffer: Uint8Array) {- return Jimp.fromBuffer(Buffer.from(buffer), DECODE_OPTIONS);+ return Jimp.fromBuffer(asBuffer(buffer), DECODE_OPTIONS);+}++/**+ * The same bytes as a `Buffer`, over the same memory.+ *+ * `Buffer.from(uint8Array)` duplicates what it is given, and the libraries below each want one —+ * so an image was being copied whole several times on its way through, for readers that only ever+ * read. On a run over a tree that is a second copy of every photograph in it, allocated and thrown+ * away again, which costs more in collection than the copying does outright.+ */+function asBuffer(bytes: Uint8Array): Buffer {+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);}/** What {@link decodeImage} hands back, for the helpers that work on a decoded image. */@@ -185,7 +197,7 @@ async function getImageTypeFromBuffer(buffer: Uint8Array): Promise<ImageFormat |* as it always was.*/function detectSvg(buffer: Uint8Array): ImageFormat | null {- if (!opensLikeMarkup(buffer) || !isSvg(Buffer.from(buffer).toString())) {+ if (!opensLikeMarkup(buffer) || !isSvg(asBuffer(buffer).toString())) {return null;}@@ -282,7 +294,7 @@ export const serverImageProvider: ImageProvider = {GIF/WebP as gif/webp). Only a pathological PNG with 512+ chunks before its acTLchunk slips through (file-type bails to "png" at its chunk-scan limit whileis-animated still flags it), so this guard correctly skips recompressing it. */- } else if (isAnimated(Buffer.from(buffer))) {+ } else if (isAnimated(asBuffer(buffer))) {// Recompression of animated images would make them static.shouldShrink = false;}diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex 678da69311..ed5d2194c9 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -11,10 +11,10 @@* recompressed belongs to the platform's {@link ImageProvider}.*/-import { getImageAttachmentTitle, IMAGE_JPEG_HANDLINGS, IMAGE_PNG_HANDLINGS, type ImageCompressionItem, type ImageCompressionOptions, type ImageCompressionResponse, type ImageCompressionSkipReason } from "@triliumnext/commons";+import { type AttachmentRow, getImageAttachmentTitle, IMAGE_JPEG_HANDLINGS, IMAGE_PNG_HANDLINGS, type ImageCompressionItem, type ImageCompressionOptions, type ImageCompressionResponse, type ImageCompressionSkipReason } from "@triliumnext/commons";import becca from "../becca/becca.js";-import type BAttachment from "../becca/entities/battachment.js";+import BAttachment from "../becca/entities/battachment.js";import type BNote from "../becca/entities/bnote.js";import { NotFoundError, ValidationError } from "../errors.js";import { getImageProvider, type ImageCompressionRequest } from "./image_provider.js";@@ -142,13 +142,6 @@ function defaultQuality(): number {return configured >= MIN_QUALITY && configured <= MAX_QUALITY ? configured : DEFAULT_QUALITY;}-/**- * One image the run can act on, hiding whether it lives in a note's content or in an attachment.- *- * Neither kind is renamed when its format changes: an attachment's title is a reference elsewhere- * (a canvas addresses its images by the Excalidraw file id stored as the title), and download and- * export filenames already derive their extension from the mime when the title disagrees.- *//** What an image weighs, and enough of its front to say what it is. */export interface TargetPeek {/** The stored image's size in bytes — the whole of it, not of {@link header}. */@@ -166,6 +159,13 @@ export interface TargetPeek {*/export const HEADER_BYTES = 64 * 1024;+/**+ * One image the run can act on, hiding whether it lives in a note's content or in an attachment.+ *+ * Neither kind is renamed when its format changes: an attachment's title is a reference elsewhere+ * (a canvas addresses its images by the Excalidraw file id stored as the title), and download and+ * export filenames already derive their extension from the mime when the title disagrees.+ */export interface CompressionTarget {entityType: "note" | "attachment";entityId: string;@@ -213,23 +213,61 @@ export function collectNoteTargets(note: BNote, recursive: boolean): Compression*/export function collectNoteImages(note: BNote, recursive: boolean): { notes: BNote[]; targets: CompressionTarget[] } {const notes = recursive ? note.getSubtree().notes : [ note ];+ // An image note *is* its image and stands alone, so it is never asked what it has attached.+ const attachments = imageAttachmentsOf(notes.filter((candidate) => candidate.type !== "image"));- return { notes, targets: notes.flatMap(ownTargetsOf) };+ // Note by note, in the order the subtree gave them, each note's own images in position order —+ // the order a run reports on and the user reads back.+ const targets = notes.flatMap((candidate) => candidate.type === "image"+ ? [ noteTarget(candidate) ]+ : (attachments.get(candidate.noteId) ?? []).map((attachment) => attachmentTarget(attachment)));++ return { notes, targets };}/**- * The images one note holds. An image note *is* its image, so it stands alone; for anything else- * the images are the attachments it owns — which is where a text note's pictures live, and where- * the weight the user is trying to shed actually sits.+ * Every image attachment the given notes own, gathered in one query and grouped by owner.+ *+ * Asked note by note this was a round trip each: cheap on its own, and ten thousand of them for a+ * subtree of that many notes. Once the images themselves stopped being read to decide their fate,+ * that was most of what collecting them cost.*/-function ownTargetsOf(note: BNote): CompressionTarget[] {- if (note.type === "image") {- return [ noteTarget(note) ];+function imageAttachmentsOf(notes: BNote[]): Map<string, BAttachment[]> {+ const byOwner = new Map<string, BAttachment[]>();++ if (!notes.length) {+ return byOwner;}- return note.getAttachmentsByRole("image").map((attachment) => attachmentTarget(attachment));+ const sql = getSql();+ // Through the parameter table rather than an `IN` list: a subtree runs to more note ids than a+ // statement is allowed parameters, and this is how the rest of core asks the same kind of+ // question.+ sql.fillParamList(notes.map((candidate) => candidate.noteId));++ const rows = sql.getRows<AttachmentRow>(/*sql*/`+ SELECT attachments.*+ FROM attachments+ JOIN param_list ON param_list.paramId = attachments.ownerId+ WHERE attachments.role = 'image'+ AND attachments.isDeleted = 0+ ORDER BY attachments.ownerId, attachments.position`);++ for (const row of rows) {+ const owned = byOwner.get(row.ownerId);+ const attachment = new BAttachment(row);++ if (owned) {+ owned.push(attachment);+ } else {+ byOwner.set(row.ownerId, [ attachment ]);+ }+ }++ return byOwner;}+function noteTarget(note: BNote): CompressionTarget {return {entityType: "note",