import { RAW_IDLE_MS, RAW_WORKERS } from './config.mjs'; import { installLibrawRuntime } from './libraw-runtime.mjs'; let ctorPromise = null; /** Load the decoder class once; installs the Node worker shim on first use. */ export function loadLibRaw() { if (!ctorPromise) { ctorPromise = (async () => { await installLibrawRuntime(); const mod = await import('libraw-wasm'); const ctor = mod.default?.default ?? mod.default; if (typeof ctor !== 'function') throw new Error('libraw-wasm did not export a constructor'); return ctor; })(); } return ctorPromise; } /** * Bounded pool of decoder instances. Each instance owns one worker thread, so * this caps how much demosaicing runs at the same time; extra jobs queue. * Idle instances are disposed after RAW_IDLE_MS to give the memory back. */ class LibRawPool { constructor(size = RAW_WORKERS) { this.size = Math.max(1, Math.floor(size)); this.free = []; this.total = 0; this.waiters = []; this.closed = false; } async acquire() { const entry = this.free.pop(); if (entry) { if (entry.timer) clearTimeout(entry.timer); return entry.lib; } if (this.total < this.size) { this.total++; try { const Ctor = await loadLibRaw(); return new Ctor(); } catch (err) { this.total--; throw err; } } return new Promise((resolve, reject) => this.waiters.push({ resolve, reject })); } release(lib, healthy = true) { if (this.closed || !healthy) { this.discard(lib); return; } const waiter = this.waiters.shift(); if (waiter) { waiter.resolve(lib); return; } const entry = { lib, timer: null }; entry.timer = setTimeout(() => { const idx = this.free.indexOf(entry); if (idx >= 0) { this.free.splice(idx, 1); this.discard(lib); } }, RAW_IDLE_MS); entry.timer.unref?.(); this.free.push(entry); } discard(lib) { try { lib.dispose(); } catch { /* worker already gone */ } this.total = Math.max(0, this.total - 1); const waiter = this.waiters.shift(); if (waiter) { this.total++; loadLibRaw() .then((Ctor) => new Ctor()) .then(waiter.resolve, waiter.reject); } } /** * Run `fn` with a decoder instance; the instance returns to the pool after. * * `timeoutMs` covers only the work, never the wait for a free worker: a job * that sat in the queue is not slow, and timing it from the call site made * parallel imports fail in waves. A timed-out worker is still chewing on the * abandoned job, so it is destroyed rather than handed to the next caller. */ async use(fn, { timeoutMs = 0, label = 'LibRaw' } = {}) { const lib = await this.acquire(); let healthy = true; let timer = null; try { if (!timeoutMs) return await fn(lib); const guard = new Promise((_, reject) => { timer = setTimeout( () => reject(new Error(`${label} timed out on this file`)), timeoutMs, ); }); try { return await Promise.race([fn(lib), guard]); } catch (err) { if (timer && /timed out/.test(String(err?.message ?? '')) && err instanceof Error) { healthy = false; } throw err; } } catch (err) { // A dead worker keeps failing, so recycle it instead of handing it back. if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false; throw err; } finally { if (timer) clearTimeout(timer); this.release(lib, healthy); } } get stats() { return { size: this.size, busy: this.total - this.free.length, idle: this.free.length, queued: this.waiters.length, }; } } export const rawPool = new LibRawPool(); export function poolSupport() { return { size: rawPool.size, workers: RAW_WORKERS }; }