Skip to content

Build your personal knowledge base with Trilium Notes

core/image compression: performance improvements

Adorian Doran5669d672f4fd
diff --git a/apps/server/src/services/image_worker_fork.spec.ts b/apps/server/src/services/image_worker_fork.spec.ts
new file mode 100644
index 0000000000..cf97a7d480
--- /dev/null
+++ b/apps/server/src/services/image_worker_fork.spec.ts
@@ -0,0 +1,70 @@
+import { initLog } from "@triliumnext/core/src/services/log.js";
+import { Jimp } from "jimp";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { compressInWorker, shutdownImageWorkers } from "./image_worker_pool.js";
+
+/**
+ * One image through a real forked worker — no mocks, the actual child process, channel and codec.
+ *
+ * This is the only automated coverage the transport has: the mocked spec beside this one pins the
+ * pool's semantics, but a renamed message field, a broken ready gate or a serialization change
+ * would sail through it. Separate from that spec because this one must NOT mock `node:child_process`.
+ */
+let jpeg: Uint8Array;
+let previousNodeOptions: string | undefined;
+
+beforeAll(async () => {
+ initLog();
+
+ // The child is plain Node and the worker entry here is TypeScript, so the loader has to reach
+ // it through the environment — exactly the road the desktop's dev launcher takes.
+ previousNodeOptions = process.env.NODE_OPTIONS;
+ process.env.NODE_OPTIONS = [ previousNodeOptions, "--import tsx" ].filter(Boolean).join(" ");
+
+ const photo = new Jimp({ width: 200, height: 150 });
+ const { data, width } = photo.bitmap;
+
+ for (let index = 0; index < data.length; index += 4) {
+ data[index] = (index / 4) % width;
+ data[index + 1] = 128;
+ data[index + 2] = 255 - ((index / 4) % width);
+ data[index + 3] = 255;
+ }
+
+ jpeg = new Uint8Array(await photo.getBuffer("image/jpeg", { quality: 95 }));
+});
+
+afterAll(() => {
+ shutdownImageWorkers();
+
+ if (previousNodeOptions === undefined) {
+ delete process.env.NODE_OPTIONS;
+ } else {
+ process.env.NODE_OPTIONS = previousNodeOptions;
+ }
+});
+
+describe("image worker fork round-trip", () => {
+ it("compresses an image in a real child process and hands the bytes back", { timeout: 30000 }, async () => {
+ const outcome = await compressInWorker(jpeg, {
+ resize: true,
+ maxWidthHeight: 100,
+ jpegHandling: "compress",
+ pngHandling: "optimize",
+ quality: 75,
+ conversionQuality: 85
+ }, 1024);
+
+ // Null would mean the pool disabled itself: the child never came up at all.
+ expect(outcome).not.toBeNull();
+
+ if (!outcome || !outcome.compressed) {
+ throw new Error(`expected the worker to compress the image, got ${JSON.stringify(outcome)}`);
+ }
+
+ expect(outcome.format.mime).toBe("image/jpeg");
+ expect(outcome.buffer.byteLength).toBeGreaterThan(0);
+ expect(outcome.buffer.byteLength).toBeLessThan(jpeg.byteLength);
+ });
+});
diff --git a/apps/server/src/services/image_worker_pool.spec.ts b/apps/server/src/services/image_worker_pool.spec.ts
index 2d8c1e5d95..4374037c4b 100644
--- a/apps/server/src/services/image_worker_pool.spec.ts
+++ b/apps/server/src/services/image_worker_pool.spec.ts
@@ -53,6 +53,9 @@ const h = vi.hoisted(() => {
return {
forked,
forkOptions,
+ // What the fake machine has; individual tests shrink these to watch the pool follow.
+ cores: 8,
+ memoryBytes: 32 * 1024 * 1024 * 1024,
fork(file: string, options: { serialization?: string; execArgv?: string[] }) {
void file;
forkOptions.push(options);
@@ -67,6 +70,7 @@ const h = vi.hoisted(() => {
});
vi.mock("node:child_process", () => ({ fork: h.fork }));
+vi.mock("node:os", () => ({ availableParallelism: () => h.cores, totalmem: () => h.memoryBytes }));
vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info() {}, error() {} }) }));
const REQUEST: ImageCompressionRequest = {
@@ -90,6 +94,8 @@ beforeEach(() => {
vi.resetModules();
h.forked.length = 0;
h.forkOptions.length = 0;
+ h.cores = 8;
+ h.memoryBytes = 32 * 1024 * 1024 * 1024;
});
describe("worker pool failure semantics", () => {
@@ -143,4 +149,22 @@ describe("worker pool failure semantics", () => {
await expect(pool.compressInWorker(BYTES, REQUEST, 1024)).resolves.toBeNull();
expect(h.forked).toHaveLength(1);
});
+
+ it("sizes the pool to the machine's memory as well as its cores", async () => {
+ const pool = await import("./image_worker_pool.js");
+
+ // A roomy machine gets the full cap; each worker below may grow a 2 GB heap, so the sum
+ // is kept inside half the memory: 8 GB carries two of them, and a small box gets the one
+ // worker that off-thread compression needs at minimum, never zero.
+ expect(pool.compressionConcurrency()).toBe(4);
+ h.memoryBytes = 8 * 1024 * 1024 * 1024;
+ expect(pool.compressionConcurrency()).toBe(2);
+ h.memoryBytes = 2 * 1024 * 1024 * 1024;
+ expect(pool.compressionConcurrency()).toBe(1);
+
+ // The core count still binds on its own.
+ h.memoryBytes = 32 * 1024 * 1024 * 1024;
+ h.cores = 2;
+ expect(pool.compressionConcurrency()).toBe(2);
+ });
});
diff --git a/apps/server/src/services/image_worker_pool.ts b/apps/server/src/services/image_worker_pool.ts
index 80338ebdcf..405ebd2017 100644
--- a/apps/server/src/services/image_worker_pool.ts
+++ b/apps/server/src/services/image_worker_pool.ts
@@ -27,7 +27,7 @@
import { type ChildProcess, fork } from "node:child_process";
import { existsSync } from "node:fs";
-import { availableParallelism } from "node:os";
+import { availableParallelism, totalmem } from "node:os";
import { join } from "node:path";
import { getLog } from "@triliumnext/core";
@@ -51,9 +51,21 @@ import type { ImageWorkerRequest, ImageWorkerResponse, ImageWorkerTrace } from "
*
* `availableParallelism` rather than the raw core count, for the machines below the cap: it follows
* the affinity the process was given, so a container pinned to two cores is answered as two.
+ *
+ * Bounded by memory besides. Each worker may grow a {@link WORKER_HEAP_MB} heap, and their sum is
+ * kept inside half of what the machine has — a four-gigabyte NAS is answered 1, not 4, because the
+ * failure past that bound is not the compression slowing down but the machine paging, which stops
+ * everything on it. Coarse on purpose: in a container `totalmem` reads the host rather than the
+ * cgroup, so this guards the obvious overcommit rather than accounting for what is genuinely free.
*/
export function compressionConcurrency(): number {
- return workerEntry() ? Math.max(1, Math.min(MAX_WORKERS, availableParallelism())) : 1;
+ if (!workerEntry()) {
+ return 1;
+ }
+
+ const byMemory = Math.floor(totalmem() / 2 / (WORKER_HEAP_MB * 1024 * 1024));
+
+ return Math.max(1, Math.min(MAX_WORKERS, availableParallelism(), byMemory));
}
/** Where decoding stops going faster for being given more workers; see above for the measurement. */
@@ -290,6 +302,17 @@ function spawn(): PooledWorker | null {
const pooled: PooledWorker = { worker, pid: worker.pid, ready };
+ // A process that comes up says so within a second, so a long silence here is not a slow
+ // boot but a hung one — and without a deadline of its own it would sit on the run for the
+ // whole of the reply timeout, which is sized for decodes, not for saying hello.
+ const bootTimer = setTimeout(() => {
+ getLog().info(`Image Compression Tool: worker ${pooled.pid} did not come up within `
+ + `${WORKER_BOOT_TIMEOUT_MS}ms; giving up on it`);
+ readiness.died?.(new Error("Image worker did not come up in time."));
+ }, WORKER_BOOT_TIMEOUT_MS);
+
+ bootTimer.unref();
+
// Rare enough to say out loud without asking: a handful of lines per process, and the ones
// that answer "did a worker ever start, and did it stay up" — which is the whole question
// when a run stops making progress.
@@ -299,6 +322,7 @@ function spawn(): PooledWorker | null {
() => getLog().info(`Image Compression Tool: worker ${pooled.pid} online in ${Date.now() - startedAt}ms`));
pooled.worker.on("message", (response: ImageWorkerResponse | ImageWorkerTrace) => {
+ clearTimeout(bootTimer);
everSpoke = true;
readiness.arrived?.();
@@ -314,11 +338,13 @@ function spawn(): PooledWorker | null {
});
// A worker that dies takes its in-flight image with it; the image is failed, not the run.
pooled.worker.on("error", (error) => {
+ clearTimeout(bootTimer);
getLog().info(`Image Compression Tool: worker ${pooled.pid} errored: ${firstLine(error)}`);
readiness.died?.(error);
pooled.failed?.(error);
});
pooled.worker.on("exit", (code, signal) => {
+ clearTimeout(bootTimer);
// A worker we stopped ourselves exits with a failure code too, so saying so plainly is
// the difference between "this is the pool tidying up" and "something died mid-image".
getLog().info(pooled.stopped
@@ -423,6 +449,16 @@ function send(
*/
const WORKER_REPLY_TIMEOUT_MS = 15 * 60 * 1000;
+/**
+ * How long a fresh process is given to announce itself before it is written off.
+ *
+ * Kept apart from the reply timeout above, which is sized for decodes that legitimately take
+ * minutes: coming up is under a second of work, and a process silent for this long past it is not
+ * going to speak. Generous all the same — a first spawn on a loaded machine, behind a virus
+ * scanner reading the binary, has taken whole seconds without anything being wrong.
+ */
+const WORKER_BOOT_TIMEOUT_MS = 30 * 1000;
+
/**
* Per-image tracing, off unless asked for: a cleanup over a large tree would otherwise write two
* lines per image into the log a user reads. Set `TRILIUM_IMAGE_WORKER_DEBUG` to follow a run image