import { DrawingError, Opened, Progress, openDrawing } from './drawing-file'; import type { WorkerReply } from './dxf.worker'; /** * Opens a drawing in a Web Worker (dxf.worker.ts), so the page stays * responsive and the work can be cancelled; on the page itself when a worker * cannot be started. */ let moduleUrl: Promise | null = null; /** * Where the bundled worker module is. A worker started from its own URL * would run under the Content Security Policy of a script file, which does * not allow the DWG converter's WebAssembly bindings; so it is started once * only to say where it is, and the real one is a blob: worker that imports * it, which runs under the page's policy instead. */ function workerModuleUrl(): Promise { moduleUrl ??= new Promise((resolve, reject) => { const w = new Worker(new URL('./dxf.worker', import.meta.url), { type: 'module' }); const timer = setTimeout(() => { w.terminate(); reject(new Error('no answer')); }, 15000); w.onmessage = (e: MessageEvent) => { if (e.data?.type !== 'where') return; clearTimeout(timer); w.terminate(); resolve(e.data.url); }; w.onerror = (e) => { clearTimeout(timer); w.terminate(); e.preventDefault?.(); reject(new Error('worker failed to start')); }; }).catch((err) => { moduleUrl = null; throw err; }); return moduleUrl; } export class CancelledError extends Error {} export interface DrawingJob { result: Promise; /** Stops the work at once; the result then fails with a CancelledError. */ cancel(): void; /** Whether it ran (or is running) in a worker rather than on the page. */ inWorker(): boolean; } /** * How long the worker may go without a word (a stage started, or the * answer) before it is taken for dead: a worker that runs out of memory can * end without any event, and one stuck in the converter never answers. * Three minutes (the converter's 10 MB download on a slow connection is part * of the first stage), plus 10 seconds per MB of file, up to 10 minutes: a * big drawing's conversion is one long silent stage. */ export function silenceLimit(size: number): number { return Math.min(600_000, 180_000 + Math.ceil(size / (1024 * 1024)) * 10_000); } /** For the tests: a stand-in worker, its module's address and the silence limit. */ export interface OffPageDeps { makeWorker?: (url: string) => Worker; moduleUrl?: () => Promise; silenceMs?: number; } /** What ended the worker without an answer: it failed to start, it failed after starting, or it went silent. */ type Ending = { type: 'died'; how: 'error' | 'message' } | { type: 'silent'; ms: number }; export function openOffPage(bytes: Uint8Array, name: string, progress: Progress, deps: OffPageDeps = {}): DrawingJob { let worker: Worker | null = null; // The silence timer, out here so Cancel can clear it (it holds the file's bytes until it fires). let silence: ReturnType | undefined; let cancelled = false; let usedWorker = false; const onPage = async (): Promise => { usedWorker = false; // Let the progress message paint before the page is busy. await new Promise((r) => setTimeout(r, 30)); return openDrawing(bytes, name, progress); }; let stop: (e: Error) => void = () => {}; const stopped = new Promise((_, reject) => (stop = reject)); stopped.catch(() => {}); const work = (async (): Promise => { let url: string; try { if (!deps.makeWorker && typeof Worker === 'undefined') throw new Error('no workers'); url = await (deps.moduleUrl ?? workerModuleUrl)(); } catch { return onPage(); } if (cancelled) return new Promise(() => {}); let started = false; const silenceMs = deps.silenceMs ?? silenceLimit(bytes.length); const reply = await new Promise((resolve) => { let blobUrl = ''; try { if (deps.makeWorker) worker = deps.makeWorker(url); else { blobUrl = URL.createObjectURL(new Blob([`import ${JSON.stringify(url)};`], { type: 'text/javascript' })); worker = new Worker(blobUrl, { type: 'module' }); } } catch { if (blobUrl) URL.revokeObjectURL(blobUrl); resolve(null); return; } usedWorker = true; // Every word from the worker starts the wait again; a long silence ends it. const listen = () => { clearTimeout(silence); silence = setTimeout(() => resolve({ type: 'silent', ms: silenceMs }), silenceMs); }; listen(); worker.onmessage = (e: MessageEvent) => { const m = e.data; // Its first message says the module loaded: from here on a failure is the file's. started = true; listen(); if (m?.type === 'progress') progress(m.stage); else if (m?.type === 'done' || m?.type === 'error') resolve(m); }; // An uncaught error or a WebAssembly trap that escaped the worker's own handler. worker.onerror = (e) => { e.preventDefault?.(); resolve({ type: 'died', how: 'error' }); }; // An answer that could not be passed back to the page. worker.onmessageerror = () => resolve({ type: 'died', how: 'message' }); worker.postMessage({ type: 'open', bytes, name }); if (blobUrl) setTimeout(() => URL.revokeObjectURL(blobUrl), 60000); }); clearTimeout(silence); (worker as Worker | null)?.terminate(); worker = null; if (cancelled) return new Promise(() => {}); if (reply?.type === 'done') return reply.opened; // Only a worker that never got going, or a converter that would not load // inside it, is worth trying again on the page. A worker that started and // then died - out of memory, most likely - would only freeze the page the // same way, and a file the converter rejected would be rejected again. if (!reply) return onPage(); if (reply.type === 'died') { if (!started && reply.how === 'error') return onPage(); if (reply.how === 'message') throw new DrawingError(`${name} could not be opened here: the drawing was read, but it could not be passed back to the page. It may be too large; try it on a computer with more memory.`); throw new DrawingError(`${name} is too large or too damaged to open here: opening it ran out of room before it finished.`); } if (reply.type === 'silent') { // Not tried again on the page: whatever stopped the worker would freeze the page instead. throw new DrawingError(`${name} could not be opened in time: nothing came back for ${Math.round(reply.ms / 1000)} seconds, so it was stopped. It may be too large or too damaged to open here.`); } if (reply.type === 'error') { if (reply.converter) return onPage(); throw new DrawingError(reply.drawing ? reply.message : `${name} is too large or too damaged to open here (${reply.message}).`); } return onPage(); })(); work.catch(() => {}); const result = Promise.race([work, stopped]); return { result, cancel: () => { cancelled = true; clearTimeout(silence); worker?.terminate(); worker = null; stop(new CancelledError('cancelled')); }, inWorker: () => usedWorker, }; }