Skip to content

Build your personal knowledge base with Trilium Notes

client/image compression tool: fix some issues

Adorian Doran389815d2f3e7
diff --git a/apps/server/src/routes/api/clipper.spec.ts b/apps/server/src/routes/api/clipper.spec.ts
index 02ffa68ee6..e86d55c844 100644
--- a/apps/server/src/routes/api/clipper.spec.ts
+++ b/apps/server/src/routes/api/clipper.spec.ts
@@ -21,32 +21,35 @@ describe("processContent", () => {
attachmentId: "foo",
title: "encodedTitle",
};
- }
+ },
+ // The clipping is read as soon as this answers, so the picture has to be stored by
+ // then; nothing here defers, so there is nothing for the wait to do.
+ awaitImageWrite: async () => {}
}
}));
});
- it("processes basic note", () => {
- const processed = cls.init(() => processContent([], note, "<p>Hello world.</p>"));
+ it("processes basic note", async () => {
+ const processed = await cls.init(() => processContent([], note, "<p>Hello world.</p>"));
expect(processed).toStrictEqual("<p>Hello world.</p>");
});
- it("processes plain text", () => {
- const processed = cls.init(() => processContent([], note, "Hello world."));
+ it("processes plain text", async () => {
+ const processed = await cls.init(() => processContent([], note, "Hello world."));
expect(processed).toStrictEqual("<p>Hello world.</p>");
});
- it("replaces images", () => {
- const processed = cls.init(() => processContent(
+ it("replaces images", async () => {
+ const processed = await cls.init(() => processContent(
[{"imageId":"OKZxZA3MonZJkwFcEhId","src":"inline.png","dataUrl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAF0lEQVQoU2P8DwQMBADjqKLRIGAgKggAzHs/0SoYCGwAAAAASUVORK5CYII="}],
note, `<img src="OKZxZA3MonZJkwFcEhId">`
));
expect(processed).toStrictEqual(`<img src="api/attachments/foo/image/encodedTitle" >`);
});
- it("skips over non-data images", () => {
+ it("skips over non-data images", async () => {
for (const url of [ "foo", "" ]) {
- const processed = cls.init(() => processContent(
+ const processed = await cls.init(() => processContent(
[{"imageId":"OKZxZA3MonZJkwFcEhId","src":"inline.png","dataUrl": url}],
note, `<img src="OKZxZA3MonZJkwFcEhId">`
));
diff --git a/apps/server/src/routes/api/clipper.ts b/apps/server/src/routes/api/clipper.ts
index cb80914777..0b7f94fbae 100644
--- a/apps/server/src/routes/api/clipper.ts
+++ b/apps/server/src/routes/api/clipper.ts
@@ -38,7 +38,7 @@ async function addClipping(req: Request) {
clippingNote.setLabel("iconClass", "bx bx-globe");
}
- const rewrittenContent = processContent(images, clippingNote, content);
+ const rewrittenContent = await processContent(images, clippingNote, content);
const existingContent = clippingNote.getContent();
if (typeof existingContent !== "string") {
@@ -125,7 +125,7 @@ async function createNote(req: Request) {
if (typeof existingContent !== "string") {
throw new ValidationError("Invalid note content type.");
}
- const rewrittenContent = processContent(images, note, content);
+ const rewrittenContent = await processContent(images, note, content);
const newContent = `${existingContent}${existingContent.trim() ? "<br/>" : ""}${rewrittenContent}`;
note.setContent(newContent);
@@ -136,7 +136,7 @@ async function createNote(req: Request) {
};
}
-export function processContent(images: Image[], note: BNote, content: string) {
+export async function processContent(images: Image[], note: BNote, content: string) {
let rewrittenContent = sanitize.sanitizeHtml(content);
if (images) {
@@ -154,6 +154,11 @@ export function processContent(images: Image[], note: BNote, content: string) {
const attachment = imageService.saveImageToAttachment(note.noteId, buffer, filename, true);
+ // The URL below goes into the note as an image source, and the note is opened as soon
+ // as this answers. Waiting for the bytes is what stops the clipping from being read
+ // with a hole where its picture should be.
+ await imageService.awaitImageWrite(attachment.attachmentId);
+
const encodedTitle = encodeURIComponent(attachment.title);
const url = `api/attachments/${attachment.attachmentId}/image/${encodedTitle}`;
diff --git a/apps/server/src/routes/api/sender.ts b/apps/server/src/routes/api/sender.ts
index 4bbb5a7e7b..d38f16f432 100644
--- a/apps/server/src/routes/api/sender.ts
+++ b/apps/server/src/routes/api/sender.ts
@@ -35,6 +35,9 @@ async function uploadImage(req: Request) {
const { note, noteId } = imageService.saveImage(parentNote.noteId, file.buffer, originalName, true);
+ // The sender opens the note it is told about, so the picture should be in it by then.
+ await imageService.awaitImageWrite(noteId);
+
const labelsStr = req.headers["x-labels"];
if (labelsStr?.trim()) {
diff --git a/apps/server/src/services/concurrency_gate.spec.ts b/apps/server/src/services/concurrency_gate.spec.ts
new file mode 100644
index 0000000000..a368a7377c
--- /dev/null
+++ b/apps/server/src/services/concurrency_gate.spec.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from "vitest";
+
+import { createConcurrencyGate } from "./concurrency_gate.js";
+
+/**
+ * The gate exists for work that arrives rather than work that is scheduled — images on their way
+ * into the database, handed over one call at a time by callers that know nothing of each other.
+ * What matters is that the count it keeps is exactly the number running, whoever is looking, and
+ * that nothing put into it is ever left there.
+ */
+describe("a concurrency gate", () => {
+ it("runs up to the limit at once and holds the rest back, in the order they arrived", async () => {
+ const gate = createConcurrencyGate(() => 2);
+ const started: number[] = [];
+ const finish: (() => void)[] = [];
+ const done = Array.from({ length: 5 }, (_, index) => gate.run(async () => {
+ started.push(index);
+ await new Promise<void>((resolve) => finish.push(resolve));
+
+ return index;
+ }));
+
+ await flush();
+ // Two in, three waiting — and the waiting three have not so much as begun.
+ expect(started).toEqual([ 0, 1 ]);
+ expect(gate.running()).toBe(2);
+
+ // Each one that finishes lets exactly one more through, in turn.
+ finish[0]();
+ await flush();
+ expect(started).toEqual([ 0, 1, 2 ]);
+ expect(gate.running()).toBe(2);
+
+ finish.forEach((release) => release());
+ await flush();
+ finish.forEach((release) => release());
+
+ await expect(Promise.all(done)).resolves.toEqual([ 0, 1, 2, 3, 4 ]);
+ // Nothing left holding a place once the work is over.
+ expect(gate.running()).toBe(0);
+ });
+
+ it("gives up the place of work that threw, rather than closing a little further each time", async () => {
+ const gate = createConcurrencyGate(() => 1);
+
+ for (let attempt = 0; attempt < 3; attempt++) {
+ await expect(gate.run(() => Promise.reject(new Error("boom")))).rejects.toThrow("boom");
+ }
+
+ expect(gate.running()).toBe(0);
+ // Still lets work through after all that: a gate that leaked on failure would be shut by now.
+ await expect(gate.run(async () => "through")).resolves.toBe("through");
+ });
+
+ it("follows a limit that changes, and never narrows to nothing", async () => {
+ let limit = 1;
+ const gate = createConcurrencyGate(() => limit);
+ const finish: (() => void)[] = [];
+ const start = () => gate.run(() => new Promise<void>((resolve) => finish.push(resolve)));
+
+ void start();
+ void start();
+ await flush();
+ expect(gate.running()).toBe(1);
+
+ // Widened between admissions: the next one in takes the room that has just appeared.
+ limit = 3;
+ finish[0]();
+ await flush();
+ expect(gate.running()).toBe(1);
+ void start();
+ await flush();
+ expect(gate.running()).toBe(2);
+
+ // A limit of none would admit nothing at all and stall every image behind it, so one is
+ // the floor — the same floor the pool applies to its own worker count.
+ limit = 0;
+ finish.forEach((release) => release());
+ await flush();
+ await expect(gate.run(async () => "through")).resolves.toBe("through");
+ });
+});
+
+/** Lets the admissions released in this turn actually start. */
+async function flush() {
+ await new Promise((resolve) => setImmediate(resolve));
+ await new Promise((resolve) => setImmediate(resolve));
+}
diff --git a/apps/server/src/services/concurrency_gate.ts b/apps/server/src/services/concurrency_gate.ts
new file mode 100644
index 0000000000..1dc9511afd
--- /dev/null
+++ b/apps/server/src/services/concurrency_gate.ts
@@ -0,0 +1,64 @@
+/**
+ * Lets a fixed number of pieces of work run at once, and queues the rest.
+ *
+ * For work that arrives rather than work that is scheduled. A caller with a list in hand can decide
+ * how much of it to start — that is what the compression tool's budget does — but images arriving on
+ * their way into the database come one call at a time from callers that know nothing of each other,
+ * and an import of a thousand notes hands over a thousand of them at once. Something has to say how
+ * many of those are acted on at a time, and this is it.
+ *
+ * The limit is read at each admission rather than fixed at construction, so a gate follows whatever
+ * its owner currently answers.
+ */
+export interface ConcurrencyGate {
+ /** Runs `work` once there is room for it, and gives up its place however `work` ends. */
+ run<T>(work: () => Promise<T>): Promise<T>;
+ /** How many are running right now. For tests and for anything that reports on itself. */
+ running(): number;
+}
+
+export function createConcurrencyGate(limit: () => number): ConcurrencyGate {
+ let running = 0;
+ const waiting: (() => void)[] = [];
+
+ /**
+ * The place is handed from one holder to the next rather than given up and taken again: with a
+ * count to decrement and re-increment, two callers released in the same turn can both see room
+ * and both take it. Passing the place itself means there is never a moment where it is free and
+ * unclaimed, so the count is exactly the number running whoever is looking.
+ */
+ function leave() {
+ const next = waiting.shift();
+
+ if (next) {
+ next();
+ } else {
+ running--;
+ }
+ }
+
+ async function enter() {
+ if (running < Math.max(limit(), 1)) {
+ running++;
+
+ return;
+ }
+
+ await new Promise<void>((resolve) => waiting.push(resolve));
+ }
+
+ return {
+ running: () => running,
+ async run<T>(work: () => Promise<T>): Promise<T> {
+ await enter();
+
+ try {
+ return await work();
+ } finally {
+ // However it ended. Work that throws still has to give up its place, or a gate
+ // closes a little further with every failure until nothing gets through at all.
+ leave();
+ }
+ }
+ };
+}
diff --git a/apps/server/src/services/image.ts b/apps/server/src/services/image.ts
index e4da4bf776..aa256e63fd 100644
--- a/apps/server/src/services/image.ts
+++ b/apps/server/src/services/image.ts
@@ -57,6 +57,9 @@ function updateImage(noteId: string, uploadBuffer: Uint8Array, originalName: str
}
export default {
+ // Passed straight through: waiting for an image to be stored is the same act whether or not
+ // this layer had OCR to schedule for it.
+ awaitImageWrite: imageService.awaitImageWrite,
saveImage,
saveImageToAttachment,
updateImage
diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.ts
index 1025976bd8..6b517e0892 100644
--- a/apps/server/src/services/image_provider.spec.ts
+++ b/apps/server/src/services/image_provider.spec.ts
@@ -1,8 +1,9 @@
import { cls, estimateJpegQuality, type ImageCompressionRequest, options } from '@triliumnext/core';
import { Jimp } from 'jimp';
-import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { serverImageProvider } from './image_provider.js';
+import { compressionConcurrency } from './image_worker_pool.js';
// is-svg / image-type / is-animated / jimp are all loaded by spec/setup.ts (which
// imports serverImageProvider to initialise core), so they cannot be re-mocked
@@ -146,6 +147,33 @@ describe('serverImageProvider.getImageType', () => {
});
describe('serverImageProvider.processImage', () => {
+ it('compresses no more arriving images at once than it has room for', async () => {
+ // An import hands over one image per note as it reads them, hundreds at a time, from calls
+ // that know nothing of each other. Nothing there says how many may be acted on at once, so
+ // the provider has to — or, on an installation with no workers to take them, that is
+ // hundreds of decodes interleaved on the thread serving the application.
+ const inFlight = { now: 0, most: 0 };
+ const compressing = vi.spyOn(serverImageProvider, 'compressImage').mockImplementation(async () => {
+ inFlight.now++;
+ inFlight.most = Math.max(inFlight.most, inFlight.now);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ inFlight.now--;
+
+ return { compressed: false, reason: 'no-gain' };
+ });
+
+ try {
+ const answered = await Promise.all(Array.from({ length: 20 },
+ () => serverImageProvider.processImage(smallPng, 'a.png', true)));
+
+ // Every one of them answered, and never more than the pool's own figure at a time.
+ expect(answered).toHaveLength(20);
+ expect(inFlight.most).toBeLessThanOrEqual(compressionConcurrency());
+ } finally {
+ compressing.mockRestore();
+ }
+ });
+
it('returns the original buffer and detected format when compression is disabled', async () => {
// An image that genuinely does compress when the option is on, so what this proves is the
// switch rather than the image: a picture nothing could shrink comes back untouched either
diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.ts
index bc8244bdee..c9902ff39c 100644
--- a/apps/server/src/services/image_provider.ts
+++ b/apps/server/src/services/image_provider.ts
@@ -9,6 +9,7 @@
import { getLog, imageCompressionService, options as optionService } from "@triliumnext/core";
import type { ImageCompressionOutcome, ImageCompressionPlan, ImageCompressionRequest, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";
+import { createConcurrencyGate } from "./concurrency_gate.js";
import {
compressImageBytes,
DECODE_MEMORY_MB,
@@ -33,6 +34,22 @@ const toBackendLog = (message: string, detail?: boolean) => {
}
};
+/**
+ * How many arriving images are compressed at once.
+ *
+ * The compression tool decides this for itself: it holds the whole list and schedules it against a
+ * memory budget. Images on their way *in* have nobody doing that — an import hands over one per
+ * note as it reads them, hundreds of them, each call knowing nothing of the others. Left ungoverned
+ * that is hundreds of decodes wanting to run at once, which on an installation with no workers to
+ * take them is hundreds of them interleaved on the thread that serves the application, each holding
+ * a decoded bitmap.
+ *
+ * Sized to the same figure the pool uses, so the queue in front of the workers stays short and the
+ * fallback path — where there are no workers and the decoding happens here — is bounded by exactly
+ * the same number.
+ */
+const automaticCompression = createConcurrencyGate(compressionConcurrency);
+
export const serverImageProvider: ImageProvider = {
getImageType(buffer: Uint8Array): ImageFormat | null {
@@ -66,8 +83,8 @@ export const serverImageProvider: ImageProvider = {
}
try {
- const outcome = await this.compressImage(
- buffer, imageCompressionService.automaticCompressionRequest());
+ const outcome = await automaticCompression.run(() =>
+ this.compressImage(buffer, imageCompressionService.automaticCompressionRequest()));
return outcome.compressed ? { buffer: outcome.buffer, format: outcome.format } : original();
} catch (e: unknown) {
diff --git a/apps/server/src/services/image_worker_pool.ts b/apps/server/src/services/image_worker_pool.ts
index b9f89c2355..1e1d02e580 100644
--- a/apps/server/src/services/image_worker_pool.ts
+++ b/apps/server/src/services/image_worker_pool.ts
@@ -237,8 +237,15 @@ async function acquire(): Promise<PooledWorker | null> {
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.
+ // Every worker is busy, so this one queues for the next to come free. That queue is ordinary
+ // and can be deep: images arriving into the database are handed over one call at a time by
+ // callers that know nothing of each other, and an import produces hundreds at once.
+ //
+ // Which makes it the pool's business to answer every caller in it. Whoever waits here is past
+ // the point where they could have started a worker for themselves, so from here they are
+ // answered by `release`, by `retire`, or by `disable` — and if any of those three forgets
+ // them, they wait for the life of the process. An image whose compression never comes back is
+ // an image never written: the note was created empty and is filled in when the answer arrives.
return new Promise((resolve) => waiting.push(resolve));
}