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: parallelize image operations using workers
Adorian Dorand54ebb85268a
diff --git a/apps/build-docs/src/build-docs.ts b/apps/build-docs/src/build-docs.tsindex fcff3152ed..133b2b91e4 100644--- a/apps/build-docs/src/build-docs.ts+++ b/apps/build-docs/src/build-docs.ts@@ -42,7 +42,8 @@ const stubImageProvider: ImageProvider = {throw new Error("Image processing not supported in build-docs");},compressImage: async () => ({ compressed: false, reason: "unsupported-platform" }),- planCompression: async () => "unsupported-platform"+ planCompression: async () => ({ skip: "unsupported-platform" as const, decodeCost: null }),+ compressionConcurrency: () => 1};import { ZipArchive } from "archiver";import { execSync } from "child_process";diff --git a/apps/desktop/scripts/build.ts b/apps/desktop/scripts/build.tsindex e760d5a5fe..b4935c276c 100644--- a/apps/desktop/scripts/build.ts+++ b/apps/desktop/scripts/build.ts@@ -14,6 +14,9 @@ async function main() {// built after, leaves the final meta.json.await build.buildBackend([ "src/preload.ts" ], { importMetaUrlShim: false });await build.buildBackend([ "src/main.ts" ]);+ // The image compression worker, which lives in the server it embeds. Built here too so the+ // desktop app can compress off-thread rather than falling back to doing it in the main process.+ await build.buildBackend([ "../server/src/services/image_worker.ts" ]);// Copy assets.build.copy("src/assets", "assets/");diff --git a/apps/server/scripts/build.ts b/apps/server/scripts/build.tsindex 52d0219fd9..d2f32d8e4a 100644--- a/apps/server/scripts/build.ts+++ b/apps/server/scripts/build.ts@@ -4,6 +4,9 @@ const build = new BuildHelper("apps/server");async function main() {await build.buildBackend([ "src/main.ts", "src/docker_healthcheck.ts" ])+ // Its own call so it lands beside the bundle rather than under a `services/` path: the pool+ // looks for it next to whatever is running, and desktop builds it the same way.+ await build.buildBackend([ "src/services/image_worker.ts" ]);// Copy assetsbuild.copy("src/assets", "assets/");diff --git a/apps/server/src/services/image_codec.ts b/apps/server/src/services/image_codec.tsnew file mode 100644index 0000000000..7063cf5047--- /dev/null+++ b/apps/server/src/services/image_codec.ts@@ -0,0 +1,393 @@+/**+ * The image codec: decoding, resizing and re-encoding, and the reasoning about whether any of that+ * is worth doing to a given image.+ *+ * Deliberately knows nothing about Trilium. No options, no logger, no database — what it is given+ * is bytes and what it answers is bytes, which is what lets the very same code run on this thread+ * and inside a worker without the worker having to stand up half a server to host it.+ *+ * Logging is passed in for the same reason: a worker has no logger of its own to reach for, and+ * lines it wants written have to travel back to the thread that has one.+ */++import { IMAGE_COMPRESSIBLE_FORMATS, type ImageCompressionSkipReason } from "@triliumnext/commons";+import { type InspectedImage, inspectImage } from "@triliumnext/core/src/services/image_inspect.js";+import type { ImageCompressionOutcome, ImageCompressionRequest, ImageFormat } from "@triliumnext/core/src/services/image_provider.js";+import { estimateJpegQuality } from "@triliumnext/core/src/services/jpeg_quality.js";+import imageType from "image-type";+import isAnimated from "is-animated";+import isSvg from "is-svg";+import { Jimp } from "jimp";+import * as UPNG from "upng-js";++/** Where a line the codec wants written goes. Dropped by default, since nothing here needs it. */+export type CodecLog = (message: string) => void;++const IGNORE_LOG: CodecLog = () => {};++const JPEG_FORMAT: ImageFormat = { ext: "jpg", mime: "image/jpeg" };+const PNG_FORMAT: ImageFormat = { ext: "png", mime: "image/png" };++/** The only formats JIMP can both decode and re-encode here; everything else is left untouched. */+const COMPRESSIBLE_EXTENSIONS = new Set<string>(IMAGE_COMPRESSIBLE_FORMATS);++/**+ * What one JPEG decode may allocate.+ *+ * jpeg-js budgets 512 MB and refuses outright to decode anything needing more, which a photograph+ * off a modern camera or a flatbed scan exceeds on its own — and those are exactly the images worth+ * compressing, so the default withholds the feature precisely where it was wanted. A decode holds+ * the coefficient blocks, the per-component planes and the RGBA bitmap at once, on the order of a+ * dozen bytes per pixel, so this reaches into the tens of megapixels.+ *+ * Raised rather than lifted: it is still what stops a malformed header claiming a size no machine+ * has, and images are decoded one at a time, so this is the peak rather than a budget shared out.+ */+export const DECODE_MEMORY_MB = 1024;++/**+ * What a decode is taken to want, per pixel of the image.+ *+ * jpeg-js counts every allocation it makes and credits none of them back, so what it weighs against+ * its budget is the sum of all of them: the coefficient blocks it holds per component (4 bytes a+ * pixel each), the per-component planes (1 each), the interleaved component data (1 a component)+ * and the RGBA bitmap at the end (4). For an ordinary photograph, whose chroma planes are stored at+ * a quarter resolution, that comes to about 15.+ *+ * Rounded up from there, so the ceiling below sits inside the budget rather than exactly on it. An+ * image stored without chroma subsampling wants nearer 22 and can still exceed the budget while+ * under this ceiling; that decode fails as it always did, reported against the one image.+ */+const DECODE_BYTES_PER_PIXEL = 16;++export type CompressionPlan =+ | { verdict: "skip"; reason: ImageCompressionSkipReason }+ | { verdict: "proceed"; isLossless: boolean; worthReencoding: boolean; declared: InspectedImage };++/**+ * What is to become of an image, decided from as much of it as the caller had.+ *+ * Every question here is answered from the header, which is what lets the same reasoning serve a+ * run deciding whether an image is worth reading at all and the compression that follows once it+ * has been. Given only the front of a file it errs one way: a dimension it cannot reach leaves the+ * image to be read in full, never leaves it skipped on a reading that was never taken.+ */+export function planFromBytes(+ format: ImageFormat | null,+ bytes: Uint8Array,+ request: ImageCompressionRequest,+ log: CodecLog = IGNORE_LOG+): CompressionPlan {+ if (!format || !COMPRESSIBLE_EXTENSIONS.has(format.ext)) {+ return { verdict: "skip", reason: "unsupported-format" };+ }++ /* v8 ignore start -- the same rare defensive guard as in processImage above: spec-compliant+ 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 its+ acTL chunk reaches here, and recompressing it would keep the first frame alone. */+ if (isAnimated(asBuffer(bytes))) {+ return { verdict: "skip", reason: "animated" };+ }+ /* v8 ignore stop */++ const isLossless = format.ext === "png";++ // Whether re-encoding alone is worth doing to *this* image, each kind answering for itself:+ // a lossy source when its handling asks for it, a lossless one when its handling asks for+ // anything at all — rewriting a PNG as the same PNG at its own size gains nothing.+ //+ // A PNG's transparency does not enter into it, though it decides *which* re-encoding happens:+ // an image `jpeg` cannot take is quantized instead, so either way there is one to do. That is+ // what lets this be answered before the image is decoded.+ const worthReencoding = isLossless ? request.pngHandling !== "keep" : request.jpegHandling === "compress";++ // Read off the header rather than from the pixels: deciding whether anything is going to happen+ // to an image should not cost more than doing it. Dimensions the header does not give up — past+ // the end of a prefix, or behind metadata — leave this open, and the decode settles it.+ const declared = inspectImage(bytes);+ const declaredEdge = Math.max(declared.width ?? 0, declared.height ?? 0);+ const mayNeedResize = request.resize && (declaredEdge === 0 || declaredEdge > request.maxWidthHeight);++ if (!mayNeedResize && !worthReencoding) {+ return { verdict: "skip", reason: "no-gain" };+ }++ if (exceedsDecodeCeiling(declared)) {+ log(`Image of ${declared.width}x${declared.height} is too large to decode; leaving it alone.`);++ return { verdict: "skip", reason: "too-large" };+ }++ return { verdict: "proceed", isLossless, worthReencoding, declared };+}++/**+ * Whether decoding this would want more than one decode is allowed.+ *+ * Applied to PNG as well, which has no budget of its own at all: pngjs decodes whatever it is given+ * until the process runs out of memory, and a ceiling refused here is the only guard it gets.+ *+ * A header that says nothing about its dimensions is not evidence of anything, so it is allowed+ * through: the decoder's own budget is still there to stop it, and refusing on a reading that was+ * never taken would withhold the feature from images that are perfectly ordinary.+ */+function exceedsDecodeCeiling(declared: InspectedImage): boolean {+ const cost = decodeCostOf(declared);++ return cost !== null && cost > DECODE_MEMORY_MB * 1024 * 1024;+}++/**+ * What decoding an image of this size is expected to want at its peak, in bytes.+ *+ * `null` where the header would not give up its dimensions, which the caller reads as "unknown and+ * therefore assume the worst" rather than as "free".+ */+export function decodeCostOf({ width, height }: InspectedImage): number | null {+ return width !== null && height !== null ? width * height * DECODE_BYTES_PER_PIXEL : null;+}++/**+ * Decodes an image, refusing to allocate more than it was allowed.+ *+ * The allowance is a parameter rather than a constant because a caller running several decodes at+ * once has already decided how much of the total each of them may have. Passing that same figure+ * down makes the reservation and its enforcement one number instead of two that can disagree.+ *+ * Not `Jimp.read`: it takes decode options in its signature and then calls `fromBuffer` without+ * them, so passing a memory budget there reads as correct and does nothing at all.+ */+export function decodeImage(buffer: Uint8Array, budgetMb: number = DECODE_MEMORY_MB) {+ return Jimp.fromBuffer(asBuffer(buffer), { "image/jpeg": { maxMemoryUsageInMB: budgetMb } });+}++/**+ * 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.+ */+export 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. */+type DecodedImage = Awaited<ReturnType<typeof decodeImage>>;++/**+ * How large a palette the PNG quantizer may keep — deliberately the largest an indexed PNG can+ * hold, which makes this the gentlest lossy setting there is while still doing the work.+ *+ * The saving comes from storing one index per pixel rather than 24-bit colour, so a screenshot or+ * a diagram — what most PNGs in a note actually are — typically loses half its weight or better+ * with nothing visible to show for it. Going lower (64, 128) starts to band across gradients, and+ * encoding losslessly instead (0) rarely reaches a fifth. Neither extreme is the trade this tool+ * is for.+ */+const PNG_PALETTE_COLORS = 256;++/**+ * What the buffer holds, read from its bytes.+ *+ * The binary formats are asked first, being identifiable from the few bytes of a magic number. SVG+ * has none — it is text, and the only way to recognise it is to read it — so it is asked last, of+ * whatever nothing else claimed, and only once the opening bytes suggest markup at all.+ *+ * That order is the whole point. `isSvg` validates the document it is given, so it needs the file+ * as a string in full; building one out of a photograph costs hundreds of milliseconds an image and+ * answers "no" every time. Asked in this order, no image ever pays for it.+ */+export async function getImageTypeFromBuffer(buffer: Uint8Array): Promise<ImageFormat | null> {+ const detected = await imageType(buffer);++ if (detected) {+ return { ext: detected.ext, mime: detected.mime };+ }++ return detectSvg(buffer);+}++/**+ * SVG, or nothing. Guarded by a look at the opening bytes: `isSvg` takes a string, and turning a+ * buffer into one is the expensive part, so it is only worth doing for a buffer that begins the way+ * a document does.+ *+ * The guard is deliberately about the bytes rather than the content — anything opening with `<`,+ * declaration or comment or root element alike, goes through to `isSvg` and is judged there exactly+ * as it always was.+ */+export function detectSvg(buffer: Uint8Array): ImageFormat | null {+ if (!opensLikeMarkup(buffer) || !isSvg(asBuffer(buffer).toString())) {+ return null;+ }++ return { ext: "svg", mime: "image/svg+xml" };+}++/** How far in to look for the first meaningful character; a document declares itself well inside this. */+const MARKUP_PROBE_BYTES = 64;++function opensLikeMarkup(buffer: Uint8Array): boolean {+ // A byte-order mark, which an editor may have written ahead of the declaration.+ let index = buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf ? 3 : 0;+ const limit = Math.min(buffer.byteLength, MARKUP_PROBE_BYTES);++ for (; index < limit; index++) {+ const byte = buffer[index];++ // Space, tab, line feed, carriage return: leading whitespace `isSvg` would trim anyway.+ if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {+ continue;+ }++ return byte === 0x3c;+ }++ return false;+}+/**+ * Which quality a JPEG about to be written is owed. Converting a pristine original and recompressing+ * an already-lossy one are different trades, so each has a setting of its own.+ *+ * The third case has neither: a JPEG only being scaled, its handling left on `keep`. It has to be+ * re-encoded all the same — there is no way to write scaled pixels without one — so it goes out at+ * whatever quality it was already stored at, read off its own quantization table. Anything fixed+ * would be wrong in both directions: below the source it degrades an image nobody asked to degrade,+ * and above it the bytes-per-pixel rise can outweigh the pixels removed, leaving a modest resize+ * *larger* than it started and rejected by the size guard — the resize silently undone.+ */+function jpegQualityFor(request: ImageCompressionRequest, isLossless: boolean, source: Uint8Array): number {+ if (isLossless) {+ return request.conversionQuality;+ }++ if (request.jpegHandling === "compress") {+ return request.quality;+ }++ return estimateJpegQuality(source) ?? FALLBACK_RESIZE_QUALITY;+}++/**+ * Stands in when a JPEG's own quality cannot be read — an unusual table, or an encoder that scales+ * the standard one its own way. High enough that "keep" is not quietly made to mean "degrade",+ * accepting that a mild resize of a heavily compressed original may then not pay for itself.+ */+const FALLBACK_RESIZE_QUALITY = 92;++/**+ * Rewrites the image as a palette PNG, which is where a PNG's weight actually goes: the saving+ * comes from storing an index per pixel instead of 24-bit colour, not from discarding detail. The+ * alpha channel survives it, so this is the only step that can shrink a transparent image at all.+ *+ * @param originalByteLength the source file, for the ratio in the log line. After a resize the two+ * are not measuring the same picture, which is the reading that matters+ * anyway — how much smaller the stored image ends up.+ */+function quantizePng(image: DecodedImage, originalByteLength: number, log: CodecLog): Uint8Array {+ const start = Date.now();+ const { width, height, data } = image.bitmap;+ // A tightly packed copy: UPNG reads the whole ArrayBuffer, so a view carrying a byte offset or+ // slack past the pixels would be read as image data.+ const rgba = new Uint8Array(data);+ const encoded = new Uint8Array(UPNG.encode([ rgba.buffer ], width, height, PNG_PALETTE_COLORS));+ const saved = Math.round((1 - encoded.byteLength / originalByteLength) * 100);++ log(+ `PNG optimization of ${width}x${height} to ${PNG_PALETTE_COLORS} colors: `+ + `${originalByteLength} -> ${encoded.byteLength} bytes (${saved}% smaller) in ${Date.now() - start}ms`+ );++ return encoded;+}++/** True when any pixel is less than fully opaque, read off the decoded RGBA bitmap. */+function hasTransparency(image: DecodedImage): boolean {+ const { data } = image.bitmap;++ for (let i = 3; i < data.length; i += 4) {+ if (data[i] !== 255) {+ return true;+ }+ }++ return false;+}+++/**+ * Compresses one image, given all of its bytes.+ *+ * The plan is taken again here whatever a caller already decided from a header: this is the reading+ * that has the bytes the other one was missing, and the only one that can be acted on.+ */+export async function compressImageBytes(+ buffer: Uint8Array,+ request: ImageCompressionRequest,+ log: CodecLog = IGNORE_LOG,+ budgetMb: number = DECODE_MEMORY_MB+): Promise<ImageCompressionOutcome> {+ const plan = planFromBytes(await getImageTypeFromBuffer(buffer), buffer, request, log);++ if (plan.verdict === "skip") {+ return { compressed: false, reason: plan.reason };+ }++ const { isLossless, worthReencoding } = plan;+ const start = Date.now();+ const image = await decodeImage(buffer, budgetMb);+ const { width, height } = image.bitmap;+ const needsResize = request.resize && Math.max(width, height) > request.maxWidthHeight;++ // Only consulted where it changes the answer. JPEG has no alpha channel, so a transparent+ // image cannot be converted — it is optimized instead, that being the best still available+ // to it. The check reads the decoded pixels, so it is exact rather than a guess from the+ // header, and it is skipped entirely where nothing is going to be converted anyway.+ const convertible = isLossless && request.pngHandling === "jpeg" && !hasTransparency(image);++ // What the image will be written back as. A JPEG can only ever be written back as one.+ const toJpeg = !isLossless || convertible;+ // A PNG that is staying a PNG is quantized unless it was to be left alone outright — which+ // covers both `optimize` and a transparent image that `jpeg` could not take.+ const quantize = isLossless && !toJpeg && request.pngHandling !== "keep";++ // Reached only where the header would not say how large the image was: everything else was+ // settled above without decoding.+ if (!needsResize && !worthReencoding) {+ return { compressed: false, reason: "no-gain" };+ }++ if (needsResize) {+ if (width >= height) {+ image.resize({ w: request.maxWidthHeight });+ } else {+ image.resize({ h: request.maxWidthHeight });+ }+ }++ let result: Uint8Array;++ if (toJpeg) {+ // Reached either by conversion, which has already established there is no transparency+ // to lose, or by a JPEG source, which never had any to begin with.+ image.background = 0xffffffff;+ result = await image.getBuffer("image/jpeg", { quality: jpegQualityFor(request, isLossless, buffer) });+ } else if (quantize) {+ result = quantizePng(image, buffer.byteLength, log);+ } else {+ result = await image.getBuffer("image/png");+ }++ log(`Compressing image of ${buffer.byteLength} bytes took ${Date.now() - start}ms`);++ if (result.byteLength >= buffer.byteLength) {+ // A small or already well-compressed image can grow; the original stays.+ return { compressed: false, reason: "no-gain" };+ }++ return { compressed: true, buffer: result, format: toJpeg ? JPEG_FORMAT : PNG_FORMAT };+}+diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex b92dedf3ec..4ea4a9ce2e 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -430,6 +430,33 @@ describe("compression parameters", () => {expect(readAttachment(attachmentId).size).toBeLessThan(padded.byteLength);});+ it("falls back to reading an image in full when it cannot be judged from its header", async () => {+ const { noteId } = await createTextNote(api);+ const attachmentId = await addAttachment(noteId, "photo.png", noisyPng);+ const real = getImageProvider();++ // The header pass is an optimization of the read, never a precondition for it — so when it+ // cannot answer, the run must go the long way round rather than report a failure.+ initImageProvider({+ getImageType: (buffer) => real.getImageType(buffer),+ processImage: (buffer, name, shrink) => real.processImage(buffer, name, shrink),+ compressImage: (buffer, compressionRequest) => real.compressImage(buffer, compressionRequest),+ compressionConcurrency: () => real.compressionConcurrency(),+ planCompression: () => Promise.reject(new Error("planner unavailable"))+ });++ try {+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {+ body: { pngHandling: "jpeg" }+ });++ expect(res.body.items[0]).toMatchObject({ entityId: attachmentId, compressed: true });+ expect(readAttachment(attachmentId).mime).toBe("image/jpeg");+ } finally {+ initImageProvider(real);+ }+ });+it("refuses an image too large to decode rather than failing part-way through one", async () => {const { noteId } = await createTextNote(api);// 400 megapixels by its own header — well past what one decode is allowed. The bytes behind@@ -688,6 +715,7 @@ async function whileCompressing<T>(interfere: () => void, request: () => PromisegetImageType: (buffer) => real.getImageType(buffer),processImage: (buffer, originalName, shrink) => real.processImage(buffer, originalName, shrink),planCompression: (header, compressionRequest) => real.planCompression(header, compressionRequest),+ compressionConcurrency: () => real.compressionConcurrency(),compressImage: (buffer, compressionRequest) => {interfere();return real.compressImage(buffer, compressionRequest);diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex 88a3e74d08..512f4c63fe 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -1,230 +1,30 @@/*** Server-side image provider implementation.- * Uses JIMP for image processing with full compression support.- */--import { IMAGE_COMPRESSIBLE_FORMATS, type ImageCompressionSkipReason } from "@triliumnext/commons";-import { estimateJpegQuality, getLog, type InspectedImage, inspectImage, options as optionService } from "@triliumnext/core";-import type { ImageCompressionOutcome, ImageCompressionRequest, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";-import imageType from "image-type";-import isAnimated from "is-animated";-import isSvg from "is-svg";-import { Jimp } from "jimp";-import * as UPNG from "upng-js";--const JPEG_FORMAT: ImageFormat = { ext: "jpg", mime: "image/jpeg" };-const PNG_FORMAT: ImageFormat = { ext: "png", mime: "image/png" };--/** The only formats JIMP can both decode and re-encode here; everything else is left untouched. */-const COMPRESSIBLE_EXTENSIONS = new Set<string>(IMAGE_COMPRESSIBLE_FORMATS);--/**- * What one JPEG decode may allocate.- *- * jpeg-js budgets 512 MB and refuses outright to decode anything needing more, which a photograph- * off a modern camera or a flatbed scan exceeds on its own — and those are exactly the images worth- * compressing, so the default withholds the feature precisely where it was wanted. A decode holds- * the coefficient blocks, the per-component planes and the RGBA bitmap at once, on the order of a- * dozen bytes per pixel, so this reaches into the tens of megapixels.- *- * Raised rather than lifted: it is still what stops a malformed header claiming a size no machine- * has, and images are decoded one at a time, so this is the peak rather than a budget shared out.- */-const DECODE_MEMORY_MB = 1024;-const DECODE_OPTIONS = { "image/jpeg": { maxMemoryUsageInMB: DECODE_MEMORY_MB } };--/**- * What a decode is taken to want, per pixel of the image.- *- * jpeg-js counts every allocation it makes and credits none of them back, so what it weighs against- * its budget is the sum of all of them: the coefficient blocks it holds per component (4 bytes a- * pixel each), the per-component planes (1 each), the interleaved component data (1 a component)- * and the RGBA bitmap at the end (4). For an ordinary photograph, whose chroma planes are stored at- * a quarter resolution, that comes to about 15.- *- * Rounded up from there, so the ceiling below sits inside the budget rather than exactly on it. An- * image stored without chroma subsampling wants nearer 22 and can still exceed the budget while- * under this ceiling; that decode fails as it always did, reported against the one image.- */-const DECODE_BYTES_PER_PIXEL = 16;--/**- * The most pixels an image may have and still be worth attempting.- *- * Derived from the budget rather than chosen beside it, so raising one raises the other. Applied to- * PNG as well, which has no budget of its own at all: pngjs decodes whatever it is given until the- * process runs out of memory, and a ceiling refused here is the only guard it gets.- */-const MAX_DECODE_PIXELS = Math.floor((DECODE_MEMORY_MB * 1024 * 1024) / DECODE_BYTES_PER_PIXEL);--type CompressionPlan =- | { verdict: "skip"; reason: ImageCompressionSkipReason }- | { verdict: "proceed"; isLossless: boolean; worthReencoding: boolean };--/**- * What is to become of an image, decided from as much of it as the caller had.- *- * Every question here is answered from the header, which is what lets the same reasoning serve a- * run deciding whether an image is worth reading at all and the compression that follows once it- * has been. Given only the front of a file it errs one way: a dimension it cannot reach leaves the- * image to be read in full, never leaves it skipped on a reading that was never taken.- */-function planFromBytes(- format: ImageFormat | null,- bytes: Uint8Array,- request: ImageCompressionRequest-): CompressionPlan {- if (!format || !COMPRESSIBLE_EXTENSIONS.has(format.ext)) {- return { verdict: "skip", reason: "unsupported-format" };- }-- /* v8 ignore start -- the same rare defensive guard as in processImage above: spec-compliant- 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 its- acTL chunk reaches here, and recompressing it would keep the first frame alone. */- if (isAnimated(asBuffer(bytes))) {- return { verdict: "skip", reason: "animated" };- }- /* v8 ignore stop */-- const isLossless = format.ext === "png";-- // Whether re-encoding alone is worth doing to *this* image, each kind answering for itself:- // a lossy source when its handling asks for it, a lossless one when its handling asks for- // anything at all — rewriting a PNG as the same PNG at its own size gains nothing.- //- // A PNG's transparency does not enter into it, though it decides *which* re-encoding happens:- // an image `jpeg` cannot take is quantized instead, so either way there is one to do. That is- // what lets this be answered before the image is decoded.- const worthReencoding = isLossless ? request.pngHandling !== "keep" : request.jpegHandling === "compress";-- // Read off the header rather than from the pixels: deciding whether anything is going to happen- // to an image should not cost more than doing it. Dimensions the header does not give up — past- // the end of a prefix, or behind metadata — leave this open, and the decode settles it.- const declared = inspectImage(bytes);- const declaredEdge = Math.max(declared.width ?? 0, declared.height ?? 0);- const mayNeedResize = request.resize && (declaredEdge === 0 || declaredEdge > request.maxWidthHeight);-- if (!mayNeedResize && !worthReencoding) {- return { verdict: "skip", reason: "no-gain" };- }-- if (exceedsDecodeCeiling(declared)) {- getLog().info(`Image of ${declared.width}x${declared.height} is too large to decode; leaving it alone.`);-- return { verdict: "skip", reason: "too-large" };- }-- return { verdict: "proceed", isLossless, worthReencoding };-}--/**- * Whether the header claims more pixels than {@link MAX_DECODE_PIXELS} allows.- *- * A header that says nothing about its dimensions is not evidence of anything, so it is allowed- * through: the decoder's own budget is still there to stop it, and refusing on a reading that was- * never taken would withhold the feature from images that are perfectly ordinary.- */-function exceedsDecodeCeiling({ width, height }: InspectedImage): boolean {- return width !== null && height !== null && width * height > MAX_DECODE_PIXELS;-}--/**- * Decodes an image with {@link DECODE_OPTIONS} applied.- *- * Not `Jimp.read`: it takes decode options in its signature and then calls `fromBuffer` without- * them, so passing a memory budget there reads as correct and does nothing at all.- */-function decodeImage(buffer: Uint8Array) {- 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. */-type DecodedImage = Awaited<ReturnType<typeof decodeImage>>;--/**- * How large a palette the PNG quantizer may keep — deliberately the largest an indexed PNG can- * hold, which makes this the gentlest lossy setting there is while still doing the work.- *- * The saving comes from storing one index per pixel rather than 24-bit colour, so a screenshot or- * a diagram — what most PNGs in a note actually are — typically loses half its weight or better- * with nothing visible to show for it. Going lower (64, 128) starts to band across gradients, and- * encoding losslessly instead (0) rarely reaches a fifth. Neither extreme is the trade this tool- * is for.- */-const PNG_PALETTE_COLORS = 256;--/**- * What the buffer holds, read from its bytes.*- * The binary formats are asked first, being identifiable from the few bytes of a magic number. SVG- * has none — it is text, and the only way to recognise it is to read it — so it is asked last, of- * whatever nothing else claimed, and only once the opening bytes suggest markup at all.- *- * That order is the whole point. `isSvg` validates the document it is given, so it needs the file- * as a string in full; building one out of a photograph costs hundreds of milliseconds an image and- * answers "no" every time. Asked in this order, no image ever pays for it.+ * The compression itself lives in {@link image_codec}, which knows nothing about Trilium so that a+ * worker can run it. What is left here is everything that does: the options the automatic shrinking+ * reads, the logger the codec has no way to reach, and the platform interface core calls through.*/-async function getImageTypeFromBuffer(buffer: Uint8Array): Promise<ImageFormat | null> {- const detected = await imageType(buffer);-- if (detected) {- return { ext: detected.ext, mime: detected.mime };- }-- return detectSvg(buffer);-}-/**- * SVG, or nothing. Guarded by a look at the opening bytes: `isSvg` takes a string, and turning a- * buffer into one is the expensive part, so it is only worth doing for a buffer that begins the way- * a document does.- *- * The guard is deliberately about the bytes rather than the content — anything opening with `<`,- * declaration or comment or root element alike, goes through to `isSvg` and is judged there exactly- * as it always was.- */-function detectSvg(buffer: Uint8Array): ImageFormat | null {- if (!opensLikeMarkup(buffer) || !isSvg(asBuffer(buffer).toString())) {- return null;- }-- return { ext: "svg", mime: "image/svg+xml" };-}--/** How far in to look for the first meaningful character; a document declares itself well inside this. */-const MARKUP_PROBE_BYTES = 64;--function opensLikeMarkup(buffer: Uint8Array): boolean {- // A byte-order mark, which an editor may have written ahead of the declaration.- let index = buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf ? 3 : 0;- const limit = Math.min(buffer.byteLength, MARKUP_PROBE_BYTES);-- for (; index < limit; index++) {- const byte = buffer[index];+import { getLog, options as optionService } from "@triliumnext/core";+import type { ImageCompressionOutcome, ImageCompressionPlan, ImageCompressionRequest, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";+import isAnimated from "is-animated";- // Space, tab, line feed, carriage return: leading whitespace `isSvg` would trim anyway.- if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {- continue;- }+import { compressInWorker, compressionConcurrency } from "./image_worker_pool.js";- return byte === 0x3c;- }+import {+ asBuffer,+ DECODE_MEMORY_MB,+ compressImageBytes,+ decodeCostOf,+ decodeImage,+ detectSvg,+ getImageTypeFromBuffer,+ planFromBytes+} from "./image_codec.js";- return false;-}+/** Lines the codec produced, written where the rest of the server's logging goes. */+const toBackendLog = (message: string) => getLog().info(message);async function shrinkImage(buffer: Uint8Array, originalName: string): Promise<Uint8Array> {let jpegQuality = optionService.getOptionInt("imageJpegQuality", 0);@@ -316,143 +116,31 @@ export const serverImageProvider: ImageProvider = {return { buffer: finalBuffer, format };},- async planCompression(header: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionSkipReason | null> {- const plan = planFromBytes(await getImageTypeFromBuffer(header), header, request);+ async planCompression(header: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionPlan> {+ const plan = planFromBytes(await getImageTypeFromBuffer(header), header, request, toBackendLog);- return plan.verdict === "skip" ? plan.reason : null;+ return plan.verdict === "skip"+ ? { skip: plan.reason, decodeCost: null }+ : { decodeCost: decodeCostOf(plan.declared) };},async compressImage(buffer: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionOutcome> {- // Asked again of the whole image, whatever a header was already judged on: the caller may- // have skipped that step entirely, and where it did not, this is the reading that had the- // bytes the other one was missing.- const plan = planFromBytes(await getImageTypeFromBuffer(buffer), buffer, request);-- if (plan.verdict === "skip") {- return { compressed: false, reason: plan.reason };- }-- const { isLossless, worthReencoding } = plan;- const start = Date.now();- const image = await decodeImage(buffer);- const { width, height } = image.bitmap;- const needsResize = request.resize && Math.max(width, height) > request.maxWidthHeight;-- // Only consulted where it changes the answer. JPEG has no alpha channel, so a transparent- // image cannot be converted — it is optimized instead, that being the best still available- // to it. The check reads the decoded pixels, so it is exact rather than a guess from the- // header, and it is skipped entirely where nothing is going to be converted anyway.- const convertible = isLossless && request.pngHandling === "jpeg" && !hasTransparency(image);-- // What the image will be written back as. A JPEG can only ever be written back as one.- const toJpeg = !isLossless || convertible;- // A PNG that is staying a PNG is quantized unless it was to be left alone outright — which- // covers both `optimize` and a transparent image that `jpeg` could not take.- const quantize = isLossless && !toJpeg && request.pngHandling !== "keep";+ try {+ const offThread = await compressInWorker(buffer, request, DECODE_MEMORY_MB);- // Reached only where the header would not say how large the image was: everything else was- // settled above without decoding.- if (!needsResize && !worthReencoding) {- return { compressed: false, reason: "no-gain" };- }-- if (needsResize) {- if (width >= height) {- image.resize({ w: request.maxWidthHeight });- } else {- image.resize({ h: request.maxWidthHeight });+ if (offThread) {+ return offThread;}+ } catch (e: unknown) {+ // The image is not given up on because a thread was: the work is perfectly possible+ // here, only slower and in the way. Said per image, since a worker dying mid-run is a+ // different matter from there being no workers at all — which is said once, by the pool.+ getLog().info(+ `Image Compression Tool: a worker failed (${(e as Error).message}); compressing here instead.`);}- let result: Uint8Array;-- if (toJpeg) {- // Reached either by conversion, which has already established there is no transparency- // to lose, or by a JPEG source, which never had any to begin with.- image.background = 0xffffffff;- result = await image.getBuffer("image/jpeg", { quality: jpegQualityFor(request, isLossless, buffer) });- } else if (quantize) {- result = quantizePng(image, buffer.byteLength);- } else {- result = await image.getBuffer("image/png");- }-- getLog().info(`Compressing image of ${buffer.byteLength} bytes took ${Date.now() - start}ms`);-- if (result.byteLength >= buffer.byteLength) {- // A small or already well-compressed image can grow; the original stays.- return { compressed: false, reason: "no-gain" };- }+ return compressImageBytes(buffer, request, toBackendLog);+ },- return { compressed: true, buffer: result, format: toJpeg ? JPEG_FORMAT : PNG_FORMAT };- }+ compressionConcurrency};--/**- * Which quality a JPEG about to be written is owed. Converting a pristine original and recompressing- * an already-lossy one are different trades, so each has a setting of its own.- *- * The third case has neither: a JPEG only being scaled, its handling left on `keep`. It has to be- * re-encoded all the same — there is no way to write scaled pixels without one — so it goes out at- * whatever quality it was already stored at, read off its own quantization table. Anything fixed- * would be wrong in both directions: below the source it degrades an image nobody asked to degrade,- * and above it the bytes-per-pixel rise can outweigh the pixels removed, leaving a modest resize- * *larger* than it started and rejected by the size guard — the resize silently undone.- */-function jpegQualityFor(request: ImageCompressionRequest, isLossless: boolean, source: Uint8Array): number {- if (isLossless) {- return request.conversionQuality;- }-- if (request.jpegHandling === "compress") {- return request.quality;- }-- return estimateJpegQuality(source) ?? FALLBACK_RESIZE_QUALITY;-}--/**- * Stands in when a JPEG's own quality cannot be read — an unusual table, or an encoder that scales- * the standard one its own way. High enough that "keep" is not quietly made to mean "degrade",- * accepting that a mild resize of a heavily compressed original may then not pay for itself.- */-const FALLBACK_RESIZE_QUALITY = 92;--/**- * Rewrites the image as a palette PNG, which is where a PNG's weight actually goes: the saving- * comes from storing an index per pixel instead of 24-bit colour, not from discarding detail. The- * alpha channel survives it, so this is the only step that can shrink a transparent image at all.- *- * @param originalByteLength the source file, for the ratio in the log line. After a resize the two- * are not measuring the same picture, which is the reading that matters- * anyway — how much smaller the stored image ends up.- */-function quantizePng(image: DecodedImage, originalByteLength: number): Uint8Array {- const start = Date.now();- const { width, height, data } = image.bitmap;- // A tightly packed copy: UPNG reads the whole ArrayBuffer, so a view carrying a byte offset or- // slack past the pixels would be read as image data.- const rgba = new Uint8Array(data);- const encoded = new Uint8Array(UPNG.encode([ rgba.buffer ], width, height, PNG_PALETTE_COLORS));- const saved = Math.round((1 - encoded.byteLength / originalByteLength) * 100);-- getLog().info(- `PNG optimization of ${width}x${height} to ${PNG_PALETTE_COLORS} colors: `- + `${originalByteLength} -> ${encoded.byteLength} bytes (${saved}% smaller) in ${Date.now() - start}ms`- );-- return encoded;-}--/** True when any pixel is less than fully opaque, read off the decoded RGBA bitmap. */-function hasTransparency(image: DecodedImage): boolean {- const { data } = image.bitmap;-- for (let i = 3; i < data.length; i += 4) {- if (data[i] !== 255) {- return true;- }- }-- return false;-}diff --git a/apps/server/src/services/image_worker.ts b/apps/server/src/services/image_worker.tsnew file mode 100644index 0000000000..1942ee0b4e--- /dev/null+++ b/apps/server/src/services/image_worker.ts@@ -0,0 +1,63 @@+/**+ * The worker side of image compression: decodes and re-encodes one image at a time, off the thread+ * that has to keep answering requests.+ *+ * Deliberately tiny, and importing only {@link image_codec}. Everything Trilium — options, the+ * database, the logger — stays on the other side of the message, so this bundles to jimp and a few+ * hundred lines rather than to a second copy of the server.+ *+ * Nothing here decides anything. It is handed the bytes, the settings and the memory it may use,+ * and answers with what came out; a caller that never hears back falls back to doing it itself.+ */++import type { ImageCompressionOutcome, ImageCompressionRequest } from "@triliumnext/core/src/services/image_provider.js";+import { parentPort } from "node:worker_threads";++import { compressImageBytes } from "./image_codec.js";++export interface ImageWorkerRequest {+ /** Matches the answer to the question, the two being in flight together with others. */+ id: number;+ buffer: Uint8Array;+ request: ImageCompressionRequest;+ /** The most this decode may allocate — what the caller set aside for it. */+ budgetMb: number;+}++export interface ImageWorkerResponse {+ id: number;+ outcome?: ImageCompressionOutcome;+ /** Set when the image could not be compressed at all; the caller reports it against that image. */+ error?: string;+ /** What the codec wanted written, carried back to the thread that has somewhere to write it. */+ logs: string[];+}++/* v8 ignore start -- runs only inside a worker thread, where the harness does not follow. What it+ does is exercised through the codec directly; what is left here is the message plumbing. */+parentPort?.on("message", (message: ImageWorkerRequest) => {+ const logs: string[] = [];++ compressImageBytes(message.buffer, message.request, (line) => logs.push(line), message.budgetMb)+ .then(+ (outcome) => reply({ id: message.id, outcome, logs }),+ (error: unknown) => reply({ id: message.id, error: describe(error), logs })+ );+});++/**+ * Sends the answer back, letting the bytes be copied rather than handed over.+ *+ * Transferring them would save the copy, but an encoder's output does not necessarily own the+ * memory behind it — jimp returns a Node buffer, which is commonly a window onto a shared pool, and+ * handing that over fails outright. The copy is of the compressed image, which is the smaller of+ * the two and the one already worth the least; paying it buys a path that cannot fail this way.+ */+function reply(response: ImageWorkerResponse) {+ parentPort?.postMessage(response);+}++function describe(error: unknown): string {+ return error instanceof Error ? (error.stack ?? error.message) : String(error);+}+/* v8 ignore stop */diff --git a/apps/server/src/services/image_worker_pool.ts b/apps/server/src/services/image_worker_pool.tsnew file mode 100644index 0000000000..f30ee40938--- /dev/null+++ b/apps/server/src/services/image_worker_pool.ts@@ -0,0 +1,272 @@+/**+ * A small pool of worker threads that compress images, so the decoding stops holding the thread+ * that serves the application.+ *+ * Decoding is synchronous from beginning to end — jpeg-js, pngjs and UPNG all run to completion+ * without yielding — so an image being compressed on the main thread is an application that has+ * stopped answering for as long as it takes. Moving that off-thread is worth more than the extra+ * cores it also buys.+ *+ * Nothing here is load-bearing. Every way this can fail — a worker file that is not where it was+ * expected, a thread that will not start, one that dies mid-image — ends in the same place: the+ * caller is told so once and compresses in this process instead, exactly as it always did.+ */++import { getLog } from "@triliumnext/core";+import type { ImageCompressionOutcome, ImageCompressionRequest } from "@triliumnext/core/src/services/image_provider.js";+import { existsSync } from "node:fs";+import { availableParallelism } from "node:os";+import { join } from "node:path";+import { Worker } from "node:worker_threads";++import type { ImageWorkerRequest, ImageWorkerResponse } from "./image_worker.js";++/**+ * How many images may be compressed at once, or 1 where they cannot be compressed off-thread at+ * all — which is the same answer as "do it here", and is what the caller schedules against.+ *+ * A core is left for the thread being freed up: it still has requests to answer, and a machine+ * given entirely to a maintenance job is not obviously better off than one that was never asked.+ * Capped low besides, this being work nobody is waiting on.+ */+export function compressionConcurrency(): number {+ return workerEntry() ? Math.max(1, Math.min(MAX_WORKERS, availableParallelism() - 1)) : 1;+}++const MAX_WORKERS = 4;++/**+ * Compresses one image in a worker, or answers `null` if there is no worker to do it in — which the+ * caller reads as "then do it yourself" rather than as a failure of the image.+ *+ * @param budgetMb the most this decode may allocate, which the caller has already set aside for it.+ */+export async function compressInWorker(+ buffer: Uint8Array,+ request: ImageCompressionRequest,+ budgetMb: number+): Promise<ImageCompressionOutcome | null> {+ if (!workerEntry()) {+ return disable("no worker entry point was found");+ }++ const worker = await acquire();++ if (!worker) {+ return null;+ }++ try {+ const response = await send(worker, buffer, request, budgetMb);++ everSucceeded = true;++ // The worker's own logging, written here because here is where a logger exists.+ response.logs.forEach((line) => getLog().info(line));++ if (response.error) {+ throw new Error(response.error);+ }++ return response.outcome ?? null;+ } catch (e: unknown) {+ // A thread that failed us once is not trusted with the next image: it may have died, and a+ // pool of one bad worker would fail every image in the run rather than none.+ discard(worker);++ // Nothing has ever come back from a worker here, so this is not one thread having died but+ // this installation being unable to run them — an environment whose loader cannot read the+ // entry point, say. Trying again per image would fail a thousand times over.+ if (!everSucceeded) {+ disable(`they do not work here (${firstLine(e)})`);+ }++ throw e;+ } finally {+ release(worker);+ }+}++/** Stops the pool between runs, so an idle Trilium is not holding threads it is not using. */+export function shutdownImageWorkers() {+ idle.forEach((pooled) => void pooled.worker.terminate());+ idle.length = 0;+}++interface PooledWorker {+ worker: Worker;+ pending?: (response: ImageWorkerResponse) => void;+ failed?: (error: unknown) => void;+}++const idle: PooledWorker[] = [];+const waiting: ((worker: PooledWorker | null) => void)[] = [];+let started = 0;+let disabled = false;+let everSucceeded = false;++async function acquire(): Promise<PooledWorker | null> {+ if (disabled) {+ return null;+ }++ const free = idle.pop();++ if (free) {+ return free;+ }++ if (started < compressionConcurrency()) {+ const spawned = spawn();++ if (spawned) {+ started++;++ return spawned;+ }++ return null;+ }++ // Every worker is busy. The caller's own scheduling normally prevents this, so rather than+ // queue indefinitely this waits for the next one to come free.+ return new Promise((resolve) => waiting.push(resolve));+}++function release(worker: PooledWorker) {+ const next = waiting.shift();++ if (next) {+ next(worker);++ return;+ }++ idle.push(worker);+}++function discard(worker: PooledWorker) {+ started--;+ void worker.worker.terminate();++ const at = idle.indexOf(worker);++ if (at >= 0) {+ idle.splice(at, 1);+ }+}++function spawn(): PooledWorker | null {+ const entry = workerEntry();++ /* v8 ignore next 3 -- guarded by compressionConcurrency() answering 1 when there is no entry,+ which stops the caller ever asking. Kept because "no entry" and "cannot spawn" are one+ fallback, and this is the one that must not throw. */+ if (!entry) {+ return disable("no worker entry point was found");+ }++ try {+ const pooled: PooledWorker = { worker: new Worker(entry.file, { execArgv: entry.execArgv }) };++ pooled.worker.on("message", (response: ImageWorkerResponse) => pooled.pending?.(response));+ // A worker that dies takes its in-flight image with it; the image is failed, not the run.+ pooled.worker.on("error", (error) => pooled.failed?.(error));+ pooled.worker.on("exit", () => pooled.failed?.(new Error("Image worker exited.")));+ pooled.worker.unref();++ return pooled;+ } catch (e: unknown) {+ return disable(`they could not be started (${(e as Error).message})`);+ }+}++/**+ * Gives up on workers for the rest of the process, saying so once.+ *+ * Once rather than per image: a run over a subtree would otherwise write the same line a thousand+ * times, and the condition is a property of this installation rather than of any one image.+ */+/** The gist of a failure. A worker's error arrives with its stack attached, which a log line is not. */+function firstLine(error: unknown): string {+ return String(error instanceof Error ? error.message : error).split(/\r?\n/)[0];+}++function disable(reason: string): null {+ if (!disabled) {+ disabled = true;+ getLog().info(+ `Image Compression Tool: compressing in this process because ${reason}.`);+ }++ return null;+}++function send(+ worker: PooledWorker,+ buffer: Uint8Array,+ request: ImageCompressionRequest,+ budgetMb: number+): Promise<ImageWorkerResponse> {+ const message: ImageWorkerRequest = { id: ++lastRequestId, buffer, request, budgetMb };++ return new Promise<ImageWorkerResponse>((resolve, reject) => {+ // A thread that took an image and went quiet would otherwise hold the run open with nothing+ // to show for it. Generous, because a large decode legitimately takes minutes; expiring is+ // treated as the worker having failed, and the image is compressed here instead.+ const expiry = setTimeout(+ () => reject(new Error("Image worker did not answer in time.")), WORKER_REPLY_TIMEOUT_MS);++ worker.pending = (response) => {+ clearTimeout(expiry);+ resolve(response);+ };+ worker.failed = (error) => {+ clearTimeout(expiry);+ reject(error);+ };+ // Copied rather than transferred: these bytes were read from the database and the caller+ // still holds them to report the original size, and to fall back on if this goes wrong.+ worker.worker.postMessage(message);+ }).finally(() => {+ worker.pending = undefined;+ worker.failed = undefined;+ });+}++const WORKER_REPLY_TIMEOUT_MS = 5 * 60 * 1000;++let lastRequestId = 0;++interface WorkerEntry {+ file: string;+ execArgv?: string[];+}++/**+ * Where the worker's code is, which differs by how the server was started.+ *+ * Bundled, the worker sits beside the bundle as an entry point of its own. Running from sources it+ * is the TypeScript, started with this process's own loader flags — which works wherever those+ * flags are what makes TypeScript readable, and fails harmlessly wherever they are not.+ *+ * Answered once and remembered, including the answer that there is none: this is a question about+ * an installation, and asking the filesystem it per image would be its own small waste.+ */+function workerEntry(): WorkerEntry | null {+ if (resolvedEntry === undefined) {+ resolvedEntry = [+ { file: join(__dirname, "services", "image_worker.cjs") },+ { file: join(__dirname, "image_worker.cjs") },+ // Running from sources, where a thread can only read TypeScript through the loader that+ // is already reading it here. Inherited rather than named: whatever started this process+ // is by definition able to start one more like it, and guessing at a loader by name+ // would be a guess about how someone chose to run the server.+ { file: join(__dirname, "image_worker.ts"), execArgv: process.execArgv }+ ].find((candidate) => existsSync(candidate.file)) ?? null;+ }++ return resolvedEntry;+}++let resolvedEntry: WorkerEntry | null | undefined;diff --git a/apps/standalone/src/services/image_provider.ts b/apps/standalone/src/services/image_provider.tsindex 61d052c40d..3e6e920ddf 100644--- a/apps/standalone/src/services/image_provider.ts+++ b/apps/standalone/src/services/image_provider.ts@@ -4,8 +4,7 @@* Images are saved as-is without resizing.*/-import type { ImageCompressionSkipReason } from "@triliumnext/commons";-import type { ImageCompressionOutcome, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core";+import type { ImageCompressionOutcome, ImageCompressionPlan, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core";import { inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";/**@@ -39,9 +38,14 @@ export const standaloneImageProvider: ImageProvider = {return { compressed: false, reason: "unsupported-platform" };},- async planCompression(): Promise<ImageCompressionSkipReason> {+ compressionConcurrency(): number {+ // Nothing to compress with, so nothing to spread over threads.+ return 1;+ },++ async planCompression(): Promise<ImageCompressionPlan> {// Settled before an image is so much as weighed: nothing here is going to compress it// whatever its header says, so a run over a tree reads none of them.- return "unsupported-platform";+ return { skip: "unsupported-platform", decodeCost: null };}};diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex ed5d2194c9..8aac327e46 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -20,6 +20,7 @@ import { NotFoundError, ValidationError } from "../errors.js";import { getImageProvider, type ImageCompressionRequest } from "./image_provider.js";import { getLog } from "./log.js";import optionService from "./options.js";+import { runWithinBudget } from "./parallel_budget.js";import { getSql } from "./sql/index.js";import { wrapStringOrBuffer } from "./utils/binary.js";@@ -369,26 +370,91 @@ function resolveAttachmentSkip(attachment: BAttachment): ImageCompressionSkipReareturn undefined;}+/**+ * Visits every image, in two passes.+ *+ * The first settles what it can from headers alone, which over a tree is most of the images there+ * are, and costs a small query each. What survives it has to be read and decoded, which is the+ * expensive part and the only part worth scheduling — so the second pass hands those to the budget,+ * each with what its decode is expected to want.+ *+ * The passes are not an optimization of each other: the first exists because deciding should not+ * cost what doing costs, the second because doing should not be allowed to cost everything at once.+ */async function compressTargets(targets: CompressionTarget[], request: ImageCompressionRequest): Promise<ImageCompressionResponse> {- const items: ImageCompressionItem[] = [];+ const concurrency = getImageProvider().compressionConcurrency();++ logRunStart(targets.length, concurrency);- for (const target of targets) {- items.push(await compressTarget(target, request));+ const items = new Array<ImageCompressionItem>(targets.length);+ const worthReading: { at: number; target: CompressionTarget; cost: number | null }[] = [];++ for (const [ at, target ] of targets.entries()) {+ const foreseen = await foreseeTarget(target, request);++ if (foreseen.item) {+ items[at] = foreseen.item;+ } else {+ worthReading.push({ at, target, cost: foreseen.cost });+ }}+ const compressed = await runWithinBudget(+ worthReading.map(({ target, cost }) => ({ cost, run: () => compressTarget(target, request) })),+ { totalBytes: COMPRESSION_BUDGET_BYTES, maxConcurrent: concurrency }+ );++ // Back into the order they were visited in, which is the order they are reported in — the+ // schedule above is free to have run them in any other.+ worthReading.forEach(({ at }, index) => {+ items[at] = compressed[index];+ });+return summarize(items);}-async function compressTarget(target: CompressionTarget, request: ImageCompressionRequest): Promise<ImageCompressionItem> {- const skipped = (originalSize: number, skipReason: ImageCompressionSkipReason): ImageCompressionItem => ({- entityType: target.entityType,- entityId: target.entityId,- title: target.title,- mime: target.mime,- originalSize,- newSize: originalSize,- compressed: false,- skipReason+/**+ * The most all decodes running at once may be holding between them.+ *+ * Conservative on purpose: this is a maintenance job running behind whatever the user is actually+ * doing, and a gigabyte is enough for one photograph of any size beside a good many screenshots.+ */+const COMPRESSION_BUDGET_BYTES = 1024 * 1024 * 1024;++/**+ * Announces a run before it begins, since it is otherwise silent until it ends: a subtree of+ * thousands is minutes of work whose only trace, until now, was the images it changed.+ *+ * Says what it is actually running on rather than a figure that reads as one — a single slot is+ * this thread doing the decoding, not a worker sitting somewhere. Nothing is announced for a note+ * holding no images at all; there is no operation to have started.+ */+function logRunStart(imageCount: number, concurrency: number) {+ if (imageCount === 0) {+ return;+ }++ const images = `${imageCount} image${imageCount === 1 ? "" : "s"}`;+ const how = concurrency > 1 ? `using ${concurrency} workers` : "on this thread";++ getLog().info(`Image Compression Tool: started operation over ${images} ${how}.`);+}++/**+ * What is already known about a target before reading it: the finished item where its fate was+ * settled from the header, otherwise what its decode is expected to want.+ *+ * Nothing here is allowed to fail the run. A header that cannot be read, or a provider that cannot+ * answer for one, leaves the image to be read in full at an unknown cost — the slow path, which is+ * exactly what this pass is an optimization of, so falling back to it is always safe.+ */+async function foreseeTarget(target: CompressionTarget, request: ImageCompressionRequest): Promise<{+ item?: ImageCompressionItem;+ cost: number | null;+}> {+ const skipped = (originalSize: number, skipReason: ImageCompressionSkipReason) => ({+ item: skippedItem(target, originalSize, skipReason),+ cost: null});// Protected content cannot even be read without a session, so it is the one skip decided@@ -397,27 +463,43 @@ async function compressTarget(target: CompressionTarget, request: ImageCompressireturn skipped(0, "protected");}- // One image failing is reported as that image's own skip and nothing more: the images after it- // in the same run are still worth compressing.- let content: Uint8Array | undefined;-try {- // The front of the image and what it weighs, without the body of it. Most images a run- // visits are settled from this alone, and never read any further.+ // The front of the image and what it weighs, without the body of it.const peeked = target.peek();if (target.skip) {return skipped(peeked?.size ?? target.getContent().byteLength, target.skip);}- if (peeked) {- const foreseen = await getImageProvider().planCompression(peeked.header, request);-- if (foreseen) {- return skipped(peeked.size, foreseen);- }+ if (!peeked) {+ return { cost: null };}+ const plan = await getImageProvider().planCompression(peeked.header, request);++ return plan.skip ? skipped(peeked.size, plan.skip) : { cost: plan.decodeCost };+ } catch (e: unknown) {+ logFailure(target, e);++ // Not reported as a failure: nothing was attempted yet, and the read below may well succeed+ // where the glance at its header did not.+ return { cost: null };+ }+}++/**+ * Reads one image in full and compresses it. Reached only for images {@link foreseeTarget} could+ * not settle from the header, so the reading and the decoding are both known to be worth doing.+ */+async function compressTarget(target: CompressionTarget, request: ImageCompressionRequest): Promise<ImageCompressionItem> {+ const skipped = (originalSize: number, skipReason: ImageCompressionSkipReason) =>+ skippedItem(target, originalSize, skipReason);++ // One image failing is reported as that image's own skip and nothing more: the images after it+ // in the same run are still worth compressing.+ let content: Uint8Array | undefined;++ try {content = target.getContent();// Read in the same turn as the content itself, so it names exactly the bytes just read.const sourceBlobId = target.blobId();@@ -462,6 +544,27 @@ async function compressTarget(target: CompressionTarget, request: ImageCompressi}}+/**+ * An image the run visited and left as it was. Weighed the same on both sides, so a skipped image+ * contributes nothing to what the run reports as saved while still being counted as visited.+ */+function skippedItem(+ target: CompressionTarget,+ originalSize: number,+ skipReason: ImageCompressionSkipReason+): ImageCompressionItem {+ return {+ entityType: target.entityType,+ entityId: target.entityId,+ title: target.title,+ mime: target.mime,+ originalSize,+ newSize: originalSize,+ compressed: false,+ skipReason+ };+}+function logFailure(target: CompressionTarget, e: unknown) {const error = e as Error;diff --git a/packages/trilium-core/src/services/image_provider.spec.ts b/packages/trilium-core/src/services/image_provider.spec.tsindex c8c6a3bd80..54a216f58e 100644--- a/packages/trilium-core/src/services/image_provider.spec.ts+++ b/packages/trilium-core/src/services/image_provider.spec.ts@@ -21,7 +21,8 @@ describe("image provider (core)", () => {compressed: false,reason: "no-gain"})),- planCompression: vi.fn(async () => null)+ planCompression: vi.fn(async () => ({ decodeCost: null })),+ compressionConcurrency: vi.fn(() => 1)};mod.initImageProvider(fake);expect(mod.getImageProvider()).toBe(fake);diff --git a/packages/trilium-core/src/services/image_provider.ts b/packages/trilium-core/src/services/image_provider.tsindex 1324a6d09f..618791e33f 100644--- a/packages/trilium-core/src/services/image_provider.ts+++ b/packages/trilium-core/src/services/image_provider.ts@@ -67,6 +67,15 @@ export interface ImageProvider {*/compressImage(buffer: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionOutcome>;+ /**+ * How many images this platform can usefully compress at once.+ *+ * One means "on the calling thread", which is not a limitation to work around: decoding is+ * synchronous, so without somewhere else to run it, more at once is the same work interleaved+ * and more memory held while it happens.+ */+ compressionConcurrency(): number;+/*** Why an image with this header would be left alone, decided without the rest of it.*@@ -83,7 +92,26 @@ export interface ImageProvider {* @param header - The opening bytes of the image; may be the whole of it.* @param request - Fully resolved compression parameters*/- planCompression(header: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionSkipReason | null>;+ planCompression(header: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionPlan>;+}++/** What a provider makes of an image from its header alone. */+export interface ImageCompressionPlan {+ /** Set when the image is to be left alone, and why; absent when it has to be read in full. */+ skip?: ImageCompressionSkipReason;+ /**+ * What decoding this is expected to want at its peak, in bytes, so a caller can decide how many+ * such decodes to have running at once. `null` where the header would not say — an unknown cost+ * is treated as the largest there is, rather than as a small one.+ *+ * A working figure for scheduling, not a limit to hold a decode to: it is what an ordinary image+ * of this size wants, and an unusually encoded one wants half as much again. What stops a decode+ * running away is the implementation's own ceiling, which does not move with this.+ *+ * Platform knowledge: what a decoder allocates is a fact about that decoder, which is why this+ * is answered here rather than estimated by the caller.+ */+ decodeCost: number | null;}let imageProvider: ImageProvider | null = null;diff --git a/packages/trilium-core/src/services/parallel_budget.spec.ts b/packages/trilium-core/src/services/parallel_budget.spec.tsnew file mode 100644index 0000000000..6ec4eb1136--- /dev/null+++ b/packages/trilium-core/src/services/parallel_budget.spec.ts@@ -0,0 +1,199 @@+import { describe, expect, it } from "vitest";++import { type BudgetedTask, runWithinBudget } from "./parallel_budget";++const MB = 1024 * 1024;++/**+ * A task that records when it starts and stops, and finishes only when told to. Nothing here waits+ * on a timer: the schedule is driven by resolving these by hand, so what the tests assert is the+ * order the scheduler chose rather than one a delay happened to produce.+ */+function task(name: string, cost: number | null, log: string[]) {+ let release = () => {};+ const finished = new Promise<void>((resolve) => { release = resolve; });++ const entry: BudgetedTask<string> & { release: () => void; reservation?: number } = {+ cost,+ async run(reservation: number) {+ entry.reservation = reservation;+ log.push(`start ${name}`);+ await finished;+ log.push(`end ${name}`);++ return name;+ },+ release+ };++ return entry;+}++/** Lets every microtask settle, so anything the scheduler was free to start has started. */+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++describe("runWithinBudget", () => {+ it("runs what fits at once and answers in the order it was given", async () => {+ const log: string[] = [];+ const tasks = [ task("a", 100 * MB, log), task("b", 100 * MB, log), task("c", 100 * MB, log) ];++ const run = runWithinBudget(tasks, { totalBytes: 300 * MB, maxConcurrent: 4 });+ await settle();++ expect(log).toEqual([ "start a", "start b", "start c" ]);++ // Finished out of order on purpose: the answer follows the list, not the finishing.+ tasks[2].release();+ tasks[0].release();+ tasks[1].release();+ await expect(run).resolves.toEqual([ "a", "b", "c" ]);+ });++ it("holds a task back until the budget it needs has been handed back", async () => {+ const log: string[] = [];+ const tasks = [ task("first", 700 * MB, log), task("second", 700 * MB, log) ];++ const run = runWithinBudget(tasks, { totalBytes: 1024 * MB, maxConcurrent: 4 });+ await settle();++ // Two of these would be 1400 MB against a 1024 MB ceiling, so the second waits — which is+ // the whole point: the cap is on what is held at once, not on how many are held.+ expect(log).toEqual([ "start first" ]);++ tasks[0].release();+ await settle();+ expect(log).toEqual([ "start first", "end first", "start second" ]);++ tasks[1].release();+ await run;+ });++ it("steps over a task too large to fit and keeps the smaller ones behind it moving", async () => {+ const log: string[] = [];+ // The second photograph is what makes this a test: it sits at the front of the queue and+ // cannot fit beside the first, so taking the queue strictly in order would idle every core+ // but one. The screenshot behind it fits in what is left and must be reached.+ const tasks = [+ task("photo-1", 900 * MB, log),+ task("photo-2", 900 * MB, log),+ task("shot", 30 * MB, log)+ ];++ const run = runWithinBudget(tasks, { totalBytes: 1024 * MB, maxConcurrent: 4 });+ await settle();++ expect(log).toEqual([ "start photo-1", "start shot" ]);++ // And the one that was stepped over goes as soon as the room it needed comes back.+ tasks[0].release();+ await settle();+ expect(log).toContain("start photo-2");++ tasks[1].release();+ tasks[2].release();+ await expect(run).resolves.toEqual([ "photo-1", "photo-2", "shot" ]);+ });++ it("admits a queued task the moment enough has been handed back, without waiting for the rest", async () => {+ const log: string[] = [];+ const tasks = [ task("big", 800 * MB, log), task("small", 100 * MB, log), task("mid", 500 * MB, log) ];++ const run = runWithinBudget(tasks, { totalBytes: 1024 * MB, maxConcurrent: 4 });+ await settle();+ expect(log).toEqual([ "start big", "start small" ]);++ // 800 back leaves room for the 500 that would not fit before, while the 100 runs on.+ tasks[0].release();+ await settle();+ expect(log).toEqual([ "start big", "start small", "end big", "start mid" ]);++ tasks[1].release();+ tasks[2].release();+ await run;+ });++ it("runs a task larger than the whole budget on its own rather than deadlocking", async () => {+ const log: string[] = [];+ const tasks = [ task("enormous", 4096 * MB, log), task("after", 10 * MB, log) ];++ const run = runWithinBudget(tasks, { totalBytes: 1024 * MB, maxConcurrent: 4 });+ await settle();++ // It cannot fit and never will, so it goes alone with the whole budget set aside for it —+ // and is told so, which is what the decoder downstream is given as its own ceiling.+ expect(log).toEqual([ "start enormous" ]);+ expect(tasks[0].reservation).toBe(1024 * MB);++ tasks[0].release();+ await settle();+ expect(log).toContain("start after");++ tasks[1].release();+ await expect(run).resolves.toEqual([ "enormous", "after" ]);+ });++ it("treats an unforeseeable cost as needing everything, so it never runs beside anything", async () => {+ const log: string[] = [];+ const tasks = [ task("unknown", null, log), task("known", 10 * MB, log) ];++ const run = runWithinBudget(tasks, { totalBytes: 1024 * MB, maxConcurrent: 4 });+ await settle();++ expect(log).toEqual([ "start unknown" ]);+ expect(tasks[0].reservation).toBe(1024 * MB);++ tasks.forEach((entry) => entry.release());+ await run;+ });++ it("never runs more at once than it was allowed, however small they are", async () => {+ const log: string[] = [];+ const tasks = Array.from({ length: 5 }, (_unused, index) => task(`t${index}`, MB, log));++ const run = runWithinBudget(tasks, { totalBytes: 1024 * MB, maxConcurrent: 2 });+ await settle();++ expect(log).toEqual([ "start t0", "start t1" ]);++ tasks.forEach((entry) => entry.release());+ await expect(run).resolves.toHaveLength(5);+ });++ it("lets the rest finish when one fails, and raises the failure once they have", async () => {+ const log: string[] = [];+ const failing: BudgetedTask<string> = { cost: MB, run: async () => { throw new Error("decode failed"); } };+ const survivor = task("survivor", MB, log);++ const run = runWithinBudget([ failing, survivor ], { totalBytes: 1024 * MB, maxConcurrent: 2 });+ await settle();++ // The failure has already happened, but the task beside it is still running and is left to+ // finish — abandoning it would leave a worker's result with nobody to receive it.+ expect(log).toEqual([ "start survivor" ]);++ survivor.release();+ await expect(run).rejects.toThrow("decode failed");+ expect(log).toEqual([ "start survivor", "end survivor" ]);+ });++ it("hands the reservation to the task, and frees it again for the next one", async () => {+ const log: string[] = [];+ const tasks = [ task("one", 600 * MB, log), task("two", 600 * MB, log) ];++ const run = runWithinBudget(tasks, { totalBytes: 1024 * MB, maxConcurrent: 4 });+ await settle();+ expect(tasks[0].reservation).toBe(600 * MB);++ // Freed on completion rather than held to the end of the run, or the second would never go.+ tasks[0].release();+ await settle();+ expect(tasks[1].reservation).toBe(600 * MB);++ tasks[1].release();+ await run;+ });++ it("answers an empty list without running anything", async () => {+ await expect(runWithinBudget([], { totalBytes: 1024 * MB, maxConcurrent: 4 })).resolves.toEqual([]);+ });+});diff --git a/packages/trilium-core/src/services/parallel_budget.ts b/packages/trilium-core/src/services/parallel_budget.tsnew file mode 100644index 0000000000..87211713fa--- /dev/null+++ b/packages/trilium-core/src/services/parallel_budget.ts@@ -0,0 +1,114 @@+/**+ * Runs a fixed list of tasks several at a time, under a ceiling on how much memory they may be+ * holding between them.+ *+ * Written for image compression, where the work is measured in the hundreds of megabytes a decode+ * wants rather than in how long it takes: four decoders each free to allocate a gigabyte is four+ * gigabytes, whatever the machine happens to have. Bounding the *sum* instead of the count lets a+ * photograph run beside a dozen screenshots, and keeps two photographs from running at once.+ *+ * Nothing here knows what a task does or what thread it runs on. That is deliberate — the platform+ * supplies the execution, this decides only what may be in flight, so the same reasoning serves a+ * pool of worker threads and a browser's workers alike.+ */++/** One unit of work, with what running it is expected to cost while it runs. */+export interface BudgetedTask<T> {+ /**+ * Bytes this is expected to want at its peak, or `null` where that cannot be foreseen — an+ * image whose header never gave up its dimensions, say. Unforeseeable is treated as needing+ * everything, so such a task runs on its own rather than beside something it might crowd out.+ */+ cost: number | null;+ /**+ * @param reservation what was set aside for this task: its cost, or the whole budget where that+ * was larger or unknown. Worth passing on to whatever enforces a limit+ * downstream, so the reservation and the enforcement are the same number.+ */+ run(reservation: number): Promise<T>;+}++export interface BudgetOptions {+ /** The most all running tasks may be holding at once. A single task may reserve all of it. */+ totalBytes: number;+ /** The most tasks that may run at once, whatever the budget would otherwise allow. */+ maxConcurrent: number;+}++/**+ * Runs everything and answers in the order it was given, however the order it ran in worked out.+ *+ * Admission is first-fit from the front: the earliest task whose reservation fits what is left of+ * the budget goes next. A task too large to fit is stepped over rather than waited for, so the+ * cores keep working on whatever does fit — and it goes as soon as enough has been handed back,+ * which on a finite list is a bound rather than a hope.+ *+ * A task larger than the entire budget is not a deadlock. Its reservation is clamped to the whole+ * budget, so it always fits once nothing else is running — which makes progress a property of the+ * arithmetic rather than a case to be handled, and holds however badly a single item was measured.+ *+ * Every task is run to completion even if one of them fails; the first failure is raised once the+ * rest have settled, rather than abandoning work already in flight to an unobserved rejection.+ */+export async function runWithinBudget<T>(tasks: BudgetedTask<T>[], options: BudgetOptions): Promise<T[]> {+ const { totalBytes, maxConcurrent } = options;+ const results = new Array<T>(tasks.length);+ const waiting = tasks.map((task, index) => ({ task, index }));+ const running = new Map<number, Promise<number>>();+ let reserved = 0;+ let failure: unknown;++ // Settled rather than awaited directly: one task failing must not leave the others running with+ // nobody watching, so every outcome is recorded and the first failure raised at the end.+ const start = (task: BudgetedTask<T>, index: number, reservation: number) => {+ reserved += reservation;+ running.set(index, task.run(reservation).then(+ (value) => {+ results[index] = value;+ return index;+ },+ (error: unknown) => {+ failure ??= error;+ return index;+ }+ ).finally(() => {+ reserved -= reservation;+ }) as Promise<number>);+ };++ // At least one at a time, whatever was asked for: a concurrency of none would admit nothing and+ // then wait for it.+ const concurrency = Math.max(1, maxConcurrent);++ while (waiting.length > 0 || running.size > 0) {+ while (waiting.length > 0 && running.size < concurrency) {+ const remaining = totalBytes - reserved;+ const next = waiting.findIndex(({ task }) => reservationFor(task, totalBytes) <= remaining);++ // Nothing fits alongside what is already running; waiting for one of those to finish is+ // what frees the room. It cannot mean nothing will ever fit — with none running the+ // whole budget is free, and no reservation is ever larger than that.+ if (next < 0) {+ break;+ }++ const [ { task, index } ] = waiting.splice(next, 1);+ start(task, index, reservationFor(task, totalBytes));+ }++ // Never awaited empty: reaching here with nothing running means something was just admitted,+ // by the same reasoning.+ running.delete(await Promise.race(running.values()));+ }++ if (failure !== undefined) {+ throw failure;+ }++ return results;+}++/** What a task is set aside, never more than the whole budget — which is what lets anything run. */+function reservationFor<T>(task: BudgetedTask<T>, totalBytes: number): number {+ return Math.min(task.cost ?? totalBytes, totalBytes);+}