import { SERVER_FAULT } from '../attachments/image/image-decoder.js'; import { InjectedFaultError } from './fault-injector.js'; export class SourceMissingError extends Error { constructor(message = 'Source object is missing') { super(message); this.name = 'SourceMissingError'; } } export class SourceMismatchError extends Error { constructor(message = 'Source object does not match its metadata') { super(message); this.name = 'SourceMismatchError'; } } export class UnsupportedPipelineError extends Error { constructor(version: number) { super(`Unsupported pipeline version: ${version}`); this.name = 'UnsupportedPipelineError'; } } export class JobTimeoutError extends Error { constructor(seconds: number) { super(`Job exceeded ${seconds}s deadline`); this.name = 'JobTimeoutError'; } } export type ErrorClass = { kind: 'permanent' | 'transient'; code: string; }; const SHARP_INPUT = /unsupported image format|input buffer|input file|bad seek|premature end|vipsjpeg|vippng|corrupt|truncated|invalid (?:image|pixel)|not a valid image|exceeded.*limit/iu; /** * Maps a processing failure to the contract's safe error class. Permanent * errors are never retried; transient ones are retried until max_attempts, * after which the job is failed as `retry_exhausted`. */ export function classifyError(error: unknown): ErrorClass { if (error instanceof InjectedFaultError) return { kind: error.kind, code: 'injected_fault' }; if (error instanceof SourceMissingError) return { kind: 'permanent', code: 'source_missing' }; if (error instanceof SourceMismatchError) return { kind: 'permanent', code: 'source_mismatch' }; if (error instanceof UnsupportedPipelineError) return { kind: 'permanent', code: 'unsupported_pipeline' }; if (error instanceof JobTimeoutError) return { kind: 'transient', code: 'processing_timeout' }; const message = error instanceof Error ? error.message : String(error); if (/pixel limit/iu.test(message)) return { kind: 'permanent', code: 'image_too_large' }; if (SERVER_FAULT.test(message)) return { kind: 'transient', code: 'processing_failed' }; if (SHARP_INPUT.test(message)) return { kind: 'permanent', code: 'invalid_image' }; return { kind: 'transient', code: 'processing_failed' }; }