Andrey Antukh aeedb96260
Add media-processor service for image and font processing (#10767)
*  Add media-processor service for image and font processing

Externalizes ImageMagick and FontForge subprocess invocations into a
separate Node.js HTTP service (media-processor/). Backend dispatches
via feature flag :use-remote-media-processing.

Key changes:
- media-processor module (TypeScript, Express 5, Sharp, FontForge/woff)
  - POST /api/image/info, /api/image/thumbnail, /api/font/generate
  - Resource limits: 128MP rejection, prlimit (512MB + 30s CPU)
  - Streaming multipart via SequenceInputStream
- app.media split into validation (leaf), local (shell impls), remote (HTTP)
- Schema enforcement: :upload and :input schemas in validation namespace
- Configurable timeout (PENPOT_MEDIA_PROCESSING_SERVICE_TIMEOUT)
- 78 tests across 4 files (image, font, middleware, config)
- FontForge path escaping for command injection prevention
- Parallel font variant conversions with Promise.all

AI-assisted-by: mimo-v2.5-pro

* 🐳 Revert docker-compose changes from media-processor commit

Remove docker-compose.yaml modifications that were part of the media-processor
service commit. The media-processor service definition, flags, and environment
variables are reverted to their previous state.

AI-assisted-by: qwen3.7-plus

* ⬆️ Update dependencies

* 🐛 Fix PR review issues in media-processor

- Font path bug: sfntToWoff and woff2ToSfnt now copy input to temp dir
  when input is a file path, ensuring output lands in expected location
- Error preservation: execCommand preserves killed/signal/code properties
  from child process errors for OOM detection
- Content-Length: service-multipart-request calculates and includes
  Content-Length header for streaming multipart requests

AI-assisted-by: qwen3.7-plus

* 🐛 Fix code review issues in media-processor

- Rename PENPOT_MEDIA_PROCESSOR_SECRET_KEY to PENPOT_MEDIA_PROCESSOR_SHARED_KEY
  in devenv to match backend config key
- Fix timeout middleware to destroy request AFTER response finishes,
  preventing truncated 504 responses
- Fix quality=0 parsing to preserve explicit zero (was silently overridden to 85)
- Replace require('fs') with proper ES module import in upload-storage.ts
- Refactor font conversion temp-dir boilerplate into withTempInput helper
- Document FontForge escaping limitations (single quotes only)
- Fix misleading comment in image.ts about sharp metadata decoding

AI-assisted-by: qwen3.7-plus

* 🐛 Fix code review issues in media-processor (round 2)

- Fix queue middleware to skip next() when response already ended,
  preventing orphaned work after timeout
- Fix hybrid storage to use disk when Content-Length is absent (chunked
  transfer), preventing unbounded memory allocation
- Add source image format validation in generateThumbnail to reject
  unsupported formats (TIFF, BMP, etc.) with 400 instead of 500
- Remove dead code in convertFont for unreachable woff→woff path
- Remove unused isEnabled() method from LokiLogTransport
- Fix sfntToWoff to use correct extension (.ttf/.otf) based on source type
- Extract queue middleware to separate file for testability
- Add comprehensive tests for queue middleware and upload storage

AI-assisted-by: qwen3.7-plus

* 🐛 Fix code review issues in media-processor (round 3)

- Fix disk-backed upload cleanup after successful requests by adding
  cleanup middleware that removes temp files on response finish/close
- Wrap sharp metadata/decoding errors as 400 validation errors instead
  of 500 internal errors
- Only apply flatten() for JPEG output to preserve alpha channel in
  PNG and WebP outputs

AI-assisted-by: qwen3.7-plus

*  Add comprehensive tests for media-processor

Phase 1 - Cleanup verification:
- Add cleanup middleware unit tests (6 tests)
- Add HTTP upload cleanup integration tests (5 tests)

Phase 2 - Error handling & alpha preservation:
- Add sharp error wrapping tests (4 tests)
- Add HTTP malformed image tests (2 tests)
- Add alpha preservation tests (3 tests)

Phase 3 - Edge cases:
- Add upload storage edge case tests (3 tests)
- Add queue middleware edge case tests (4 tests)

Phase 4 - Backend mock verification:
- Fix backend mocks to include :mtype field in image info responses
- Verify all error codes match actual service behavior

Total: 27 new tests added (160 tests passing)

AI-assisted-by: qwen3.7-plus

* 🐛 Fix code review issues in media-processor (round 4)

- Add Zod validation constraints for config values (int, positive, min)
- Fix auth middleware to compare Buffer byte lengths instead of string lengths
- Validate requested output dimensions in generateThumbnail (crop mode)
- Change queue middleware to release slot via callback in finally block
- Add comprehensive tests for all fixes

AI-assisted-by: qwen3.7-plus

* 🐛 Close HTTP response streams in backend media remote

- Wrap stream consumption in try/finally with .close() calls
- Add tests to verify stream closure for info, font-convert, and thumbnail

AI-assisted-by: qwen3.7-plus

* 🐛 Fix queue slot leak on upload failures

Make releaseQueue idempotent and attach fallback listener to release
slot when response finishes. This covers Multer errors that bypass
the route handler's finally block, preventing permanent queue stall.

AI-assisted-by: qwen3.7-plus

* 🐛 Cancel processing on timeout

Create AbortController in timeout middleware and abort signal when
timeout fires. Pass signal to Sharp and FontForge to cancel ongoing
processing and release resources when request is cancelled.

AI-assisted-by: qwen3.7-plus

* 🐛 Fix code review issues in media-processor (round 6)

- Error handler: check headersSent before writing response to prevent
  ERR_HTTP_HEADERS_SENT when timeout already sent 504
- Timeout config: increase default requestTimeout from 60s to 180s to
  match font processing timeout (120s) and backend request timeout
- Image processing: check abort signal before starting Sharp operations
  to cancel processing when timeout fires
- Queue lifecycle: remove res.on('close', release) fallback to hold
  queue slot until processing completes, preventing concurrency limit
  violation when client disconnects

AI-assisted-by: qwen3.7-plus

* 🐛 Close HTTP response stream in download-image

Wrap response body in with-open to ensure stream is closed after
writing to temp file, preventing HTTP connection leaks on repeated
URL imports.

AI-assisted-by: qwen3.7-plus

* 🐛 Close HTTP response stream on validation errors in download-image

Move with-open to wrap the entire validation and processing block,
ensuring the response body stream is closed even when validation fails
(non-2xx status, missing size, invalid media type). This prevents
HTTP connection leaks on repeated failed downloads.

Add test to verify stream closure on validation errors.

AI-assisted-by: qwen3.7-plus

* 🐛 Pass abort signal to Sharp toBuffer for timeout cancellation

Wrap Sharp's toBuffer() with Promise.race to check abort signal during
processing. This ensures large thumbnails stop processing when the
request times out, preventing wasted CPU/memory and queue capacity.

Add test to verify abort during toBuffer operation.

AI-assisted-by: qwen3.7-plus

* 🐛 Hold queue slot until Sharp completes and handle client disconnect

- Remove Promise.race from generateThumbnail — Sharp processing now
  completes fully before queue slot is released, preventing concurrency
  limit violations under timeout conditions
- Remove res.on("finish", release) fallback from queue middleware —
  error handler now explicitly calls releaseQueue in all error paths
- Add res.on("close") handler in timeout middleware to abort signal
  when client disconnects, ensuring processing stops early
- Add tests for client disconnect handling and queue slot lifecycle

AI-assisted-by: qwen3.7-plus

* 🐛 Address round 9 review findings

- Document Sharp 0.35.3 cancellation limitation in image.ts
- Add integration test for timeout cleanup with large images
- Fix font tools (sfntToWoff, woffToSfnt, woff2ToSfnt) to throw
  ProcessingError on resource limit kills instead of returning null
- Validate font signatures for same-format conversions to prevent
  arbitrary files from being persisted as valid fonts
- Fix concurrent mkdtemp race in upload-storage by using shared
  initialization promise

AI-assisted-by: qwen3.7-plus

* 🐛 Address round 10 review findings

- Add tmpdir assertion in font.ts to prevent path injection
- Preserve original error in queue middleware catch handler
- Change auth middleware response type from "internal" to "authorization"
- Add cleanup flag to prevent double cleanup in cleanup middleware
- Move quality clamping into parseQuality function for consistency
- Add integration tests for quality parameter clamping at route level
- Update existing tests to match new auth response type

AI-assisted-by: qwen3.7-plus

* 🐛 Address round 11 review findings

- Extract releaseSlot helper in error-handler to reduce duplication
- Remove redundant try/catch in font.ts withTempDir cleanup
- Improve font path validation error message for clarity
- Move path validation before try/catch to prevent swallowing
- Add debug logging for cleanup failures in cleanup middleware
- Inline TransportTargetSpec type alias in logger.ts
- Extract logging middleware to separate file for consistency
- Remove duplicate MIME validation in image thumbnail route
- Add test for font path validation (outside tmpdir rejection)
- Add tests for error handler queue release across all branches

AI-assisted-by: qwen3.7-plus

* 🐛 Remove Content-Length header from multipart requests

The JDK's HttpClient rejects Content-Length as a restricted header,
causing IllegalArgumentException when sending multipart requests to the
media-processor. Remove the explicit Content-Length header and let the
JDK use chunked transfer encoding. The media-processor will use disk
storage for all multipart requests (safe default behavior).

Remove unused size computations (file-size, header-bytes, footer-bytes,
total-size) that were only used for Content-Length.

Update test to verify Content-Length is not present in request headers.

AI-assisted-by: qwen3.7-plus

* 🐛 Fix pino ESM bundling for media-processor

Mark pino and its transports (pino-pretty, pino-loki) as external to
avoid bundling issues with worker thread modules that reference
__dirname (not available in ES modules).

AI-assisted-by: qwen3.7-plus
2026-08-05 09:41:48 +02:00

205 lines
6.2 KiB
TypeScript

import sharp from "sharp";
import type { FileInput, ImageInfo, ThumbnailParams } from "../types.js";
import { throwValidation, throwRestriction } from "./errors.js";
import { createLogger } from "../logger.js";
const logger = createLogger("image");
const SUPPORTED_MIMES = new Set(["image/jpeg", "image/png", "image/webp", "image/gif"]);
function orientationSwapDimensions(
width: number,
height: number,
orientation: number
): { width: number; height: number } {
if (orientation === 6 || orientation === 8) {
return { width: height, height: width };
}
return { width, height };
}
let imageMaxPixels = 128_000_000;
let imageMaxWidth = 16384;
let imageMaxHeight = 16384;
export function configureImageLimits(opts: { maxPixels: number; maxWidth: number; maxHeight: number }): void {
imageMaxPixels = opts.maxPixels;
imageMaxWidth = opts.maxWidth;
imageMaxHeight = opts.maxHeight;
}
function validateImageDimensions(width: number, height: number): void {
if (width > imageMaxWidth || height > imageMaxHeight) {
throwRestriction(
"image-dimensions-exceeded",
`Image dimensions ${width}x${height} exceed maximum ${imageMaxWidth}x${imageMaxHeight}`
);
}
const pixels = width * height;
if (pixels > imageMaxPixels) {
throwRestriction("image-pixel-count-exceeded", `Image pixel count ${pixels} exceeds maximum ${imageMaxPixels}`);
}
}
function validateOutputDimensions(width: number, height: number): void {
if (width > imageMaxWidth || height > imageMaxHeight) {
throwRestriction(
"output-dimensions-exceeded",
`Requested output dimensions ${width}x${height} exceed maximum ${imageMaxWidth}x${imageMaxHeight}`
);
}
const pixels = width * height;
if (pixels > imageMaxPixels) {
throwRestriction(
"output-pixel-count-exceeded",
`Requested output pixel count ${pixels} exceeds maximum ${imageMaxPixels}`
);
}
}
export async function getImageInfo(input: FileInput, size: number, signal?: AbortSignal): Promise<ImageInfo> {
if (signal?.aborted) {
throw new Error("Request cancelled");
}
let metadata;
try {
metadata = await sharp(input).metadata();
} catch (err) {
throwValidation("invalid-image", `Failed to decode image: ${(err as Error).message}`);
}
if (!metadata.width || !metadata.height) {
throwValidation("invalid-image", "Could not read image dimensions");
}
const mtype = metadata.format ? `image/${metadata.format}` : undefined;
if (!mtype || !SUPPORTED_MIMES.has(mtype)) {
throwValidation("invalid-image", `Unsupported image format: ${metadata.format}`);
}
const orientation = metadata.orientation ?? 1;
const { width, height } = orientationSwapDimensions(metadata.width!, metadata.height!, orientation);
validateImageDimensions(width, height);
logger.debug({ width, height, mtype: mtype!, size }, "Image info extracted");
return {
width,
height,
mtype: mtype!,
size,
orientation,
};
}
const FORMAT_MIMES: Record<string, string> = {
jpeg: "image/jpeg",
webp: "image/webp",
png: "image/png",
};
export async function generateThumbnail(
input: FileInput,
params: ThumbnailParams,
signal?: AbortSignal
): Promise<{ data: Buffer; mtype: string }> {
// Check if request was cancelled before starting
if (signal?.aborted) {
throw new Error("Request cancelled");
}
// Pre-validate source image dimensions using the same sharp instance
// that will be used for the resize pipeline. Sharp reads metadata
// (dimensions, orientation) from the image header without fully decoding
// the pixel data, then reuses the instance for the resize operations.
const source = sharp(input);
let srcMeta;
try {
srcMeta = await source.metadata();
} catch (err) {
throwValidation("invalid-image", `Failed to decode image: ${(err as Error).message}`);
}
// Check again after metadata read
if (signal?.aborted) {
throw new Error("Request cancelled");
}
if (srcMeta.width == null || srcMeta.height == null) {
throwValidation("invalid-image", "Could not read source image dimensions");
}
// Validate source image format
if (srcMeta.format && !SUPPORTED_MIMES.has(`image/${srcMeta.format}`)) {
throwValidation("unsupported-image-format", `Unsupported image format: ${srcMeta.format}`);
}
const orientation = srcMeta.orientation ?? 1;
const { width: displayWidth, height: displayHeight } = orientationSwapDimensions(
srcMeta.width,
srcMeta.height,
orientation
);
validateImageDimensions(displayWidth, displayHeight);
// Validate requested output dimensions (important for crop mode which can enlarge)
validateOutputDimensions(params.width, params.height);
logger.debug(
{ width: params.width, height: params.height, format: params.format, mode: params.mode },
"Generating thumbnail"
);
let pipeline = source.rotate();
// Only flatten for JPEG output (which doesn't support transparency).
// PNG and WebP support alpha, so preserve it.
if (params.format === "jpeg") {
pipeline = pipeline.flatten({ background: { r: 255, g: 255, b: 255 } });
}
if (params.mode === "fit") {
pipeline = pipeline.resize(params.width, params.height, {
fit: "inside",
withoutEnlargement: true,
});
} else {
pipeline = pipeline.resize(params.width, params.height, {
fit: "cover",
position: "center",
});
}
switch (params.format) {
case "jpeg":
pipeline = pipeline.jpeg({ quality: params.quality });
break;
case "webp":
pipeline = pipeline.webp({ quality: params.quality });
break;
case "png":
pipeline = pipeline.png();
break;
}
let data: Buffer;
try {
// Sharp 0.35.3 does not support cancellation of native libvips operations.
// toBuffer() only accepts { resolveWithObject: boolean }, no AbortSignal.
// We hold the queue slot until Sharp completes fully, then check signal
// to throw if the request was cancelled during processing. This prevents
// concurrency limit violations and handles timeouts gracefully.
data = await pipeline.toBuffer();
} catch (err) {
throwValidation("invalid-image", `Failed to process image: ${(err as Error).message}`);
}
if (signal?.aborted) {
throw new Error("Request cancelled");
}
return { data, mtype: FORMAT_MIMES[params.format] };
}