screentinker/server/lib/image-ops-worker.js
ScreenTinker 5171f09f96 Run image decoding on a worker thread
Fixes the blocker the previous commit shipped with. Pure-JS decoding costs ~1s of
solid CPU for a 12MP photo, and in-process that is not a slow upload but a stalled
event loop — no heartbeats, no socket traffic. thumbnail-backfill.js walks a whole
library at boot, so it reproduced #240 (blocked loop -> missed heartbeats -> panels
offline -> reconnect churn) from our own maintenance. sharp never did this because
libvips works on a threadpool.

image-ops.js is now a dispatcher over image-ops-worker.js; the work moved unchanged
to image-ops-core.js, so callers and their failure contract are untouched.

Measured on a 12MP photo: 1079ms wall with the loop stalled 1003ms, to 1881ms wall
for two ops with ZERO stalls and 185 timer ticks serviced. Wall time is worse and
that is fine — it is off the main thread now.

Design notes, all load-bearing:
  - ONE JOB AT A TIME. A decoded 12MP bitmap is ~48MB of RGBA; overlapping jobs
    multiply peak memory by queue depth, which is the wrong failure on the small
    targets this change exists to reach. Costs no throughput — the work is CPU-bound
    and one busy worker already saturates its core.
  - unref'd while idle, ref'd only in flight. Otherwise scripts/backfill-rotation-
    dims.js never exits and `node --test` hangs forever. Verified: a CLI-style run
    exits in 104ms, code 0.
  - decode failures reply as messages, so one bad upload cannot tear down the worker
    and take unrelated queued jobs with it.
  - in-process fallback if a thread cannot be had, warned rather than silent.

test/image-ops.test.js pins the loop-liveness property, which no functional test
would catch. Its thresholds were mutation-tested against the inline path: the first
version passed there too (4MP stalls only ~355ms, under a non-flaky threshold), so
the fixture is 12MP and the thresholds sit in the gap between the two behaviours —
worker ~90 ticks/~0ms, inline ~3 ticks/~897ms. It now fails inline, as a guard must.

1647/1647 pass. Ingest re-verified with node_modules/sharp moved aside.
2026-08-13 11:26:47 -05:00

30 lines
1.1 KiB
JavaScript

'use strict';
/*
* Worker-thread host for image-ops-core. One job per message, one reply per job, keyed by id.
*
* Deliberately thin: every decision (queueing, lifecycle, fallback) lives in ../lib/image-ops so
* there is one place to reason about them. This end only does the work and reports what happened.
*
* Errors come back as a message rather than a thrown exception, so one undecodable upload does
* not tear down the worker and take the queued jobs of unrelated callers with it.
*/
const { parentPort } = require('worker_threads');
const core = require('./image-ops-core');
const OPS = {
metadata: (job) => core.metadata(job.src),
writeThumbnail: (job) => core.writeThumbnail(job.src, job.dest, job.width, job.quality),
};
parentPort.on('message', async (job) => {
try {
const op = OPS[job.op];
if (!op) throw new Error(`unknown image op: ${job.op}`);
parentPort.postMessage({ id: job.id, ok: true, result: await op(job) });
} catch (err) {
parentPort.postMessage({ id: job.id, ok: false, error: err && err.message ? err.message : String(err) });
}
});