feat(app): R4.3b/c import worker, client, controller; HomeRoute on the disposable worker

Protocol v1 (task → ready → result | failed with phase and kind), the worker entry with
the glue bundled statically and the page's compiled Module posted, the file streamed into
the module's memory; client with start and task timers (paused while hidden), settle-once,
terminate always, error events never masked; module-level controller (one import at a
time, cancel on leaving Home, worker chunk prefetched once the engine is loaded); the
settlement mapped to the B.1.8 messages (OD-5: a trap, a timeout or an unreadable file is
« Erreur de lecture du PDF. », never a corrupt PDF). HomeRoute keeps its routing and size
pre-checks, loads its own index after acceptance, drops a result when the session changed.
Tests: handler and client in-process, the corpus message test (O8 51, O7 stored inputs,
O2/O3/Step 5), the six existing suites migrated to the real worker logic.
This commit is contained in:
bchanot committed 2026-10-18 18:10:42 +02:00
1 parent 52471dbbc0
commit 6d1cce6e06
26 files changed
+2164 -247

No files matched your search

+1
View File
@@ -55,6 +55,7 @@ export async function trappingCoreRuntime(marker: string) {
core_version: glue.core_version,
call: glue.call,
SheetHandle: Trapping,
FileBytes: glue.FileBytes,
}
},
}
+115
View File
@@ -0,0 +1,115 @@
import { nodeCoreSource } from '@faunosteo/core-wasm/node'
import type { WorkerLike } from '@/core/worker/client'
import { setImportWorkerSpawn } from '@/core/worker/controller'
import {
createWorkerHandler,
type EngineLoader,
type WorkerEngine,
} from '@/core/worker/handler'
import type { WorkerMessage } from '@/core/worker/protocol'
/**
* The import worker run in-process (happy-dom has no `Worker`): a `WorkerLike` whose
* `postMessage` feeds the worker handler and whose answers come back through `onmessage`
* on a later tick, as a real worker's would; `terminate` drops every later answer. The
* engine is the Node module by default; a test passes its own loader for failures.
*/
let instances = 0
/** The shipped module instantiated afresh (one instance per worker, as in the browser). */
export const nodeEngineLoader: EngineLoader = async (module) => {
const source = nodeCoreSource('pkg')
instances += 1
const glue = await source.importGlue(1000 + instances)
const compiled = module ?? (await source.compile())
const exports = (await glue.default({ module_or_path: compiled })) as {
memory?: WebAssembly.Memory
}
return {
SheetHandle: glue.SheetHandle,
FileBytes: glue.FileBytes,
memory: exports.memory ?? null,
}
}
export interface FakeWorker extends WorkerLike {
terminated: boolean
/** Every message the page posted to the worker (the task, as the worker receives it). */
received: unknown[]
/** Every message the worker posted, dropped or delivered. */
posted: WorkerMessage[]
}
export function inProcessWorker(
load: EngineLoader = nodeEngineLoader,
): FakeWorker {
const worker: FakeWorker = {
terminated: false,
received: [],
posted: [],
onmessage: null,
onerror: null,
onmessageerror: null,
terminate() {
worker.terminated = true
},
postMessage(message) {
worker.received.push(message)
void handle(message)
},
}
const handle = createWorkerHandler(load, (message) => {
worker.posted.push(message)
setTimeout(() => {
if (!worker.terminated)
worker.onmessage?.({ data: message } as MessageEvent)
}, 0)
})
return worker
}
/** Routes the page's imports through in-process workers; returns the spawned ones. */
export function useInProcessImportWorker(
load: EngineLoader = nodeEngineLoader,
): { workers: FakeWorker[]; restore: () => void } {
const workers: FakeWorker[] = []
setImportWorkerSpawn(() => {
const worker = inProcessWorker(load)
workers.push(worker)
return worker
})
return { workers, restore: () => setImportWorkerSpawn(null) }
}
/** An engine whose `SheetHandle` throws `error` on every import call (a trap, say). */
export function throwingEngineLoader(error: Error): EngineLoader {
return async (module) => {
const engine = await nodeEngineLoader(module)
class Throwing extends engine.SheetHandle {
import_pdf_bytes(): string {
throw error
}
restore_copy_bytes(): string {
throw error
}
}
return { ...engine, SheetHandle: Throwing } as WorkerEngine
}
}
/** An engine whose import calls answer the envelope text `out` (a core refusal, say). */
export function answeringEngineLoader(out: string): EngineLoader {
return async (module) => {
const engine = await nodeEngineLoader(module)
class Answering extends engine.SheetHandle {
import_pdf_bytes(): string {
return out
}
restore_copy_bytes(): string {
return out
}
}
return { ...engine, SheetHandle: Answering } as WorkerEngine
}
}
+86
View File
@@ -0,0 +1,86 @@
/**
* Minimal PDFs for the import tests, byte for byte as `pdfWith` of
* `scripts/browser/lib/hostile-classes.mjs` writes them (uncompressed streams, no
* padding): the core's scanner reads the objects in clear, so an archive is a
* `/Type /EmbeddedFile` stream, a `/Filespec` naming it, and the
* `/Keywords (faunosteo-archive/1)` stamp.
*/
const ATTACHMENT_NAME = 'osteo-report.json'
const STAMP = '<< /Keywords (faunosteo-archive/1) >>'
const OTHER_PRODUCER = '<< /Producer (another tool) >>'
const utf8 = (text: string) => new TextEncoder().encode(text)
/** Bytes a `File` accepts as a part (never a shared buffer). */
type Bytes = Uint8Array<ArrayBuffer>
interface EmbeddedStream {
bytes: Bytes
/** The Filespec name; none leaves the stream unnamed. */
name?: string
}
function concat(parts: Bytes[]): Bytes {
const out = new Uint8Array(parts.reduce((sum, p) => sum + p.byteLength, 0))
let at = 0
for (const part of parts) {
out.set(part, at)
at += part.byteLength
}
return out
}
/** One EmbeddedFile object (number `n`) and its Filespec (`n + 1`) when named. */
function streamObjects(stream: EmbeddedStream, n: number): Bytes[] {
const length = stream.bytes.byteLength
const parts = [
utf8(`${n} 0 obj\n<< /Type /EmbeddedFile /Length ${length}`),
utf8(' >>\nstream\n'),
stream.bytes,
utf8('\nendstream\nendobj\n'),
]
if (stream.name) {
parts.push(
utf8(`${n + 1} 0 obj\n<< /Type /Filespec /F (${stream.name})`),
utf8(` /EF << /F ${n} 0 R >> >>\nendobj\n`),
)
}
return parts
}
/** A PDF holding `streams`, then the Faunosteo stamp (or another producer's info). */
export function pdfWith(
streams: EmbeddedStream[],
{ stamp = true }: { stamp?: boolean } = {},
): Bytes {
const parts = [utf8('%PDF-1.7\n%\xE2\xE3\xCF\xD3\n')]
let n = 1
for (const stream of streams) {
parts.push(...streamObjects(stream, n))
n += 2
}
const info = stamp ? STAMP : OTHER_PRODUCER
parts.push(utf8(`${n} 0 obj\n${info}\nendobj\n%%EOF\n`))
return concat(parts)
}
/** A Faunosteo PDF whose `osteo-report.json` attachment holds `json`. */
export function archivePdf(json: string): Bytes {
return pdfWith([{ bytes: utf8(json), name: ATTACHMENT_NAME }])
}
/** The stamp without its attachment: a Faunosteo PDF a tool stripped. */
export function strippedPdf(): Bytes {
return pdfWith([])
}
/** A PDF of another producer: no stamp, no attachment. */
export function foreignPdf(): Bytes {
return pdfWith([], { stamp: false })
}
/** `bytes` as the file the practitioner picks. */
export function pdfFile(bytes: Bytes, name = 'bilan.pdf'): File {
return new File([bytes], name, { type: 'application/pdf' })
}