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: fix some issues
Adorian Doran1a8e513d246b
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex 4ea4a9ce2e..d428cd9479 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -1,6 +1,6 @@import type { ImageCompressionResponse } from "@triliumnext/commons";import { becca, cls, getSql, options } from "@triliumnext/core";-import { collectNoteTargets, HEADER_BYTES } from "@triliumnext/core/src/services/image_compression.js";+import { collectNoteTargets, HEADER_BYTES, writeImage } from "@triliumnext/core/src/services/image_compression.js";import { getImageProvider, initImageProvider } from "@triliumnext/core/src/services/image_provider.js";import { createTextNote } from "@triliumnext/core/src/test/api_fixtures.js";import { CoreApiTester } from "@triliumnext/core/src/test/api_tester.js";@@ -292,6 +292,44 @@ describe("compression parameters", () => {expect(await compressedSize({}, noisyJpeg)).toBe(explicitLow);});+ it("leaves the cached format alone when the image behind it could not be written", () => {+ // The write is wrapped in a transaction, so a failure takes the database back — but the+ // entity is a cached object no rollback touches. Left changed, it would advertise a format+ // whose bytes were never written, and hand that mime to whatever saved the note next.+ const entity = {+ mime: "image/png",+ setContent() {+ throw new Error("content is too large to store");+ }+ };++ expect(() => writeImage(entity, smallPng, "image/jpeg")).toThrow(/too large/);+ expect(entity.mime).toBe("image/png");+ });++ it("falls back to a usable bound when the stored one could not be resized to", async () => {+ const noteId = await createImageNote(noisyPng);++ // A stored option is not a validated one — it arrives by synchronisation from another+ // instance, or from a database edited by hand. Zero would reach the encoder as "scale every+ // image to nothing", and a value that is not a number would abort the request where it was+ // read, so neither is allowed to stand in for a bound the request did not name.+ for (const stored of [ "0", "-100", "not a number" ]) {+ cls.init(() => options.setOption("imageMaxWidthHeight", stored));++ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {+ body: { resize: true, pngHandling: "keep", jpegHandling: "keep" }+ });++ // 600x400 sits inside the 2000 fallback, so nothing is resized and the image is left be+ // — where a bound of zero would have made every image oversized.+ expect(res.status, stored).toBe(200);+ expect(res.body.items[0], stored).toMatchObject({ compressed: false, skipReason: "no-gain" });+ }++ expect(readNote(noteId).size).toBe(noisyPng.byteLength);+ });+it("falls back to the default recompression quality when the stored option is out of range", async () => {cls.init(() => options.setOption("imageJpegQuality", "75"));const at75 = await compressedSize({}, noisyJpeg);diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex 8aac327e46..baa04d15be 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -98,7 +98,7 @@ export function resolveCompressionRequest(options: ImageCompressionOptions = {})*/export function resolveMaxWidthHeight(maxWidthHeight: number | undefined): number {if (maxWidthHeight === undefined) {- return optionService.getOptionInt("imageMaxWidthHeight");+ return defaultMaxWidthHeight();}if (!Number.isInteger(maxWidthHeight) || maxWidthHeight < MIN_MAX_WIDTH_HEIGHT) {@@ -137,6 +137,25 @@ export function resolveRecursive(options: ImageCompressionOptions = {}): booleanreturn options.recursive === true;}+/**+ * The bound a request that named none opens on: whatever the automatic shrinking is set to, so an+ * unqualified request compresses the way an import would.+ *+ * Read defensively, exactly as {@link defaultQuality} reads its own option. A stored setting is not+ * a validated one — it arrives by synchronisation from another instance, or from a database edited+ * by hand — and neither a value that is not a number nor one at or below zero can be resized to.+ * The first would abort the request where it was read; the second would reach the encoder as an+ * instruction to scale every image to nothing.+ */+function defaultMaxWidthHeight(): number {+ const configured = optionService.getOptionInt("imageMaxWidthHeight", 0);++ return configured >= MIN_MAX_WIDTH_HEIGHT ? configured : FALLBACK_MAX_WIDTH_HEIGHT;+}++/** What the option ships as, and so what an unusable stored value falls back to. */+const FALLBACK_MAX_WIDTH_HEIGHT = 2000;+function defaultQuality(): number {const configured = optionService.getOptionInt("imageJpegQuality", 0);@@ -286,9 +305,7 @@ function noteTarget(note: BNote): CompressionTarget {return false;}- current.mime = mime;- current.save();- current.setContent(buffer, { forceSave: true });+ writeImage(current, buffer, mime);return true;}@@ -317,14 +334,45 @@ function attachmentTarget(attachment: BAttachment): CompressionTarget {return false;}- current.mime = mime;- current.setContent(buffer, { forceSave: true });+ writeImage(current, buffer, mime);return true;}};}+/**+ * Writes the compressed image and the format it is now in, as one act.+ *+ * The format is set on the entity before the content because writing the content is what persists+ * the row — mime included — so there is nothing to save separately, and nothing at all reaches the+ * database until the new blob is in it.+ *+ * The failure is the reason this is a function rather than two lines. A write that throws is taken+ * back by the transaction around it, but the entity is a cached object that no rollback touches: it+ * would go on advertising a format whose bytes were never written, and hand that mime to whatever+ * saved the note next. So the field is put back by hand, the cache and the database ending up+ * agreeing either way.+ */+export interface WritableImage {+ mime: string;+ setContent(content: Uint8Array, opts: { forceSave: boolean }): void;+}++export function writeImage(entity: WritableImage, buffer: Uint8Array, mime: string) {+ const previousMime = entity.mime;++ entity.mime = mime;++ try {+ entity.setContent(buffer, { forceSave: true });+ } catch (e: unknown) {+ entity.mime = previousMime;++ throw e;+ }+}+/*** Reads an image's weight and its opening bytes straight out of the blob, leaving the body of it in* the database. One statement answers both, so the saving is a smaller read rather than a second