screentinker/server/lib/content-ingest.js
screentinker 13c9c67335
Drop sharp: pure-JS image ops on a worker thread (#263)
* spike: replace sharp with pure-JS image ops (jimp + jsquash WASM)

Removes the last native dependency from the ingest path, so the server no longer
needs a per-platform/per-ABI prebuilt to thumbnail an image. Motivated by getting
the server onto hardware with no toolchain, but the ABI tax is paid on every
install — it is the same failure class lib/preflight-deps.js exists to explain.

lib/image-ops.js is the whole surface: metadata() and writeThumbnail(), which are
the only two things ingest ever asked sharp for.

Format parity holds. jpeg/png/gif/tiff/bmp are native to Jimp; webp and avif go
through @jsquash WASM, whose bundled .wasm must be compiled by hand because the
packages locate it with fetch(file://) and Node has no file:// fetch — the only
symptom otherwise is a bare "fetch failed". heic is unsupported, as it already
was: sharp advertises heif but its prebuilt libvips refuses HEVC.

#170 is preserved by a different mechanism. Jimp applies EXIF orientation at
decode and rewrites the tag to 1, so metadata() reports display dimensions and
imageDisplayDims() runs as a no-op instead of swapping W/H a second time. The
helper stays in the path so the rule keeps living in one place.

Verified: 1643/1643 tests pass, and ingest was exercised in a child process with
node_modules/sharp moved aside — jpeg, EXIF-rotated jpeg, png, webp, avif, gif
all measured and thumbnailed correctly, corrupt input still yields nulls with no
phantom thumbnail_path.

KNOWN BLOCKER, do not ship as-is: Jimp is pure JS on the main thread, where sharp
handed work to a libvips threadpool. A 12MP photo goes 65ms -> 1079ms, and the
event loop stalls for 1003ms of it (sharp: zero stalls). thumbnail-backfill.js
walks a whole library at boot, so this reproduces #240 exactly — blocked loop,
missed heartbeats, panels marked offline, reconnect churn. Needs a worker_thread
offload before this is viable; image-ops.js is the seam for it.

* 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.

* Measure and thumbnail an image from a single decode

Ingest asked for metadata() then writeThumbnail(), which decoded the file twice.
That pairing was free under sharp, whose .metadata() only parses the header, but
every decode here is a full one — ~1s for a 12MP photo — so the naive translation
doubled the most expensive thing on the ingest path.

image-ops.measureAndThumbnail() returns both from one decode. Full ingest of a
12MP photo: 2 decodes/~1.9s -> 1150ms, still with zero event-loop stalls.

The subtlety is the failure contract. In the two-call version width and height
were assigned BEFORE the thumbnail was attempted, so a failed thumbnail still left
usable dimensions on the row — the player needs them to letterbox. Merging naively
would have turned any thumbnail failure into total metadata loss. So a WRITE
failure is reported ({thumbnailWritten:false, thumbnailError}) with the dimensions
intact, and the caller sets thumbnail_path only when the write succeeded, keeping
the phantom-path discipline. A DECODE failure still throws — there is nothing to
report about an unreadable image.

backfill-rotation-dims.js deliberately keeps the separate calls: it probes every
image row but regenerates a thumbnail only for the few whose dimensions changed,
so pairing them there would decode files it has no reason to thumbnail.

Tests count decodes rather than timing them — an exact property, and a wall-clock
comparison would be flaky under load. The count filters for reads of the file under
test: Node's ESM loader also goes through fs.promises.readFile, so a raw call count
picks up jimp's and the WASM codecs' lazy loading and reads 30 instead of 1.

1649/1649 pass. Ingest re-verified across all 7 formats with sharp moved aside.

* Dockerfile: sharp is no longer a production dependency

--omit=dev now leaves it out entirely; better-sqlite3 is the only native module
the builder stage still needs a toolchain for.
2026-08-13 11:40:13 -05:00

132 lines
7.6 KiB
JavaScript

'use strict';
// #73: shared content-ingest core. Extracted from routes/content.js POST / so the agency
// upload (routes/agency.js) produces BYTE-IDENTICAL first-class content (same thumbnail/
// dimensions/duration/insert) - an agency asset is indistinguishable from a dashboard
// upload. routes/content.js POST / is now a thin caller; behavior is unchanged (its
// existing tests are the regression guard).
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const { db } = require('../db/database');
const config = require('../config');
const { sanitizeString } = require('../middleware/sanitize');
const { videoDisplayDims, imageDisplayDims } = require('./media-orientation');
const { finalizeUpload } = require('./upload-sniff');
// Multer takes file.originalname from the multipart header, bypassing sanitizeBody, so
// HTML-escape here (renders as text in every UI sink). .normalize('NFC') first: macOS
// sends NFD-decomposed names; Linux/renderers expect NFC. Single point - every filename
// storage site flows through here.
function safeFilename(name) {
return sanitizeString((name || '').normalize('NFC'));
}
/*
* Everything we can learn from the BYTES: thumbnail, display dimensions, duration.
*
* Extracted so PUT /api/content/:id/replace derives them the same way an upload does. It used
* to carry its own shorter copy that handled images only — so replacing a video wiped the row's
* duration, dimensions and thumbnail, and replacing a portrait photo re-introduced the EXIF
* orientation bug (#170) that the ingest path fixes with imageDisplayDims + .rotate(). A second
* copy of this logic is a second place for it to rot; there is now one.
*
* Best-effort by contract: a missing ffprobe or a decode failure yields nulls and a warning, never
* a throw — the file itself is already stored and is worth more than its metadata.
*
* @returns {{width:number|null, height:number|null, durationSec:number|null, thumbnailPath:string|null}}
*/
async function deriveMediaMetadata(sourcePath, filepath, mime) {
let width = null, height = null, durationSec = null, thumbnailPath = null;
try {
// SVG is deliberately NOT rasterised: it is already its own thumbnail. (It also used to be
// the one format kept away from sharp, because rasterising went through librsvg — where the
// outstanding libvips CVEs live. Nothing rasterises it now either.)
if (mime === 'image/svg+xml') {
thumbnailPath = filepath;
} else if (mime.startsWith('image/')) {
const imageOps = require('./image-ops');
const thumbName = `thumb_${filepath}`;
// Measure and thumbnail from ONE decode. Asking separately costs two, and a decode is the
// single most expensive thing on this path (~1s for a 12MP photo — unlike sharp, whose
// .metadata() only read the header). #170: rotation is implicit, the decoder auto-orients,
// so the recorded dimensions and the thumbnail agree without an explicit rotate.
const metadata = await imageOps.measureAndThumbnail(
sourcePath, path.join(config.contentDir, thumbName), config.thumbnailWidth, 70);
// #170: honor EXIF orientation so a portrait photo isn't stored as landscape. The decoder
// applies it and reports orientation 1, so this is a no-op pass-through today — kept so the
// rule lives in one place regardless of which decoder is underneath.
({ width, height } = imageDisplayDims(metadata));
// Assign thumbnailPath only if the write actually succeeded: naming it unconditionally used
// to store a phantom thumbnail_path for a file that was never created, which the UI then
// requests forever as a broken image. The dimensions above survive that failure on purpose —
// they are independently useful, and losing them would letterbox the asset wrongly.
if (metadata.thumbnailWritten) thumbnailPath = thumbName;
else console.warn(`Thumbnail write failed for ${filepath}: ${metadata.thumbnailError}`);
} else if (mime.startsWith('video/')) {
try {
// execFile, NOT execFileSync. These two spawns each carry a 15s timeout, and run
// synchronously they block the event loop for their whole duration — nothing else on
// the server runs, including heartbeats and socket traffic. That was survivable while
// the only caller was a human-initiated upload; it stopped being survivable the moment
// a boot-time sweep started walking a whole library of them unattended, which is the
// #240 failure mode exactly (blocked loop -> missed heartbeats -> panels marked
// offline -> reconnect churn) arriving from our own maintenance.
//
// deriveMediaMetadata is already async and both callers already await it, so awaiting
// the subprocess instead of blocking on it is invisible to them.
const { execFile } = require('child_process');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);
const { stdout: probe } = await execFileAsync('ffprobe',
['-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', sourcePath],
{ timeout: 15000 }
);
const info = JSON.parse(probe);
if (info.format?.duration) durationSec = parseFloat(info.format.duration);
const videoStream = info.streams?.find(s => s.codec_type === 'video');
if (videoStream) {
// #170: honor the rotation/Display-Matrix so a portrait video isn't stored landscape.
// (ffmpeg auto-rotates the thumbnail below by default, so only the dims need fixing.)
({ width, height } = videoDisplayDims(videoStream));
}
// Same phantom-path discipline as the image branch above: name it only once the
// file exists, so a failed encode cannot leave the row claiming a thumbnail.
const thumbName = `thumb_${filepath.replace(/\.[^.]+$/, '.jpg')}`;
try {
await execFileAsync('ffmpeg',
['-y', '-i', sourcePath, '-ss', '2', '-vframes', '1', '-vf', `scale=${config.thumbnailWidth}:-1`, path.join(config.contentDir, thumbName)],
{ timeout: 15000 }
);
thumbnailPath = thumbName;
} catch { thumbnailPath = null; }
} catch (e) {
console.warn('ffprobe failed:', e.message);
}
}
} catch (e) {
console.warn('Thumbnail/metadata generation failed:', e.message);
}
return { width, height, durationSec, thumbnailPath };
}
// Process a multer-uploaded file (thumbnail + dimensions + duration) and insert a content
// row. Returns the content row. Throws on a hard failure (the caller maps to 500);
// thumbnail/metadata failures are best-effort (logged, non-fatal) exactly as before.
async function ingestUploadedFile({ file, userId, workspaceId, folderId = null }) {
const id = uuidv4();
// Content-derived extension + mime. Throws UnsupportedUploadError (and removes the temp
// file) when the bytes are not a supported media type; the caller maps that to a 400.
const { filepath, mime } = finalizeUpload(file);
const { width, height, durationSec, thumbnailPath } = await deriveMediaMetadata(file.path, filepath, mime);
db.prepare(`
INSERT INTO content (id, user_id, workspace_id, filename, filepath, mime_type, file_size, duration_sec, thumbnail_path, width, height, folder_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(id, userId, workspaceId, safeFilename(file.originalname), filepath, mime, file.size, durationSec, thumbnailPath, width, height, folderId || null);
return db.prepare('SELECT * FROM content WHERE id = ?').get(id);
}
module.exports = { ingestUploadedFile, safeFilename, deriveMediaMetadata };