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:
1 parent
52471dbbc0
commit
6d1cce6e06
26 files changed
+2164
-247
No files matched your search
@@ -0,0 +1,137 @@
|
||||
import {
|
||||
isWorkerMessage,
|
||||
PROTOCOL_VERSION,
|
||||
type ImportDiag,
|
||||
type ImportTaskKind,
|
||||
} from './protocol'
|
||||
import { PausableTimer, type Visibility, documentVisibility } from './timers'
|
||||
|
||||
/**
|
||||
* The page side of one import (R4.3, plan §B.1.5 items 1, 3 and 5): creates the worker
|
||||
* in a try/catch (a `SecurityError` is synchronous), installs the listeners before posting,
|
||||
* arms the start timer until `ready` then the task timer, settles once on the first of
|
||||
* `result`, `failed`, an `error` event, a timer, or a cancel, and terminates the worker in
|
||||
* every case. Everything after the first settlement is ignored.
|
||||
*/
|
||||
|
||||
/** What `new Worker(…)` gives, narrowed to what the client uses (a test fake fits). */
|
||||
export interface WorkerLike {
|
||||
postMessage(message: unknown): void
|
||||
terminate(): void
|
||||
onmessage: ((event: MessageEvent) => void) | null
|
||||
onerror: ((event: ErrorEvent) => void) | null
|
||||
onmessageerror: ((event: MessageEvent) => void) | null
|
||||
}
|
||||
|
||||
export interface ImportTaskInput {
|
||||
task: ImportTaskKind
|
||||
file: File
|
||||
sheet: string
|
||||
module: WebAssembly.Module | null
|
||||
}
|
||||
|
||||
/**
|
||||
* `worker_unavailable`: the worker could not be created, failed before `ready`, or did not
|
||||
* answer `ready` in time; `crashed`: a trap or an `error` event during the task;
|
||||
* `timeout`: the task timer; `read`: the file could not be read; `engine`: the module
|
||||
* refused the sheet or failed otherwise during the task; `cancelled`: the page gave up.
|
||||
*/
|
||||
export type ImportFailureReason =
|
||||
| 'worker_unavailable'
|
||||
| 'crashed'
|
||||
| 'timeout'
|
||||
| 'read'
|
||||
| 'engine'
|
||||
| 'cancelled'
|
||||
|
||||
export type ImportSettlement =
|
||||
| { kind: 'result'; out: string; diag: ImportDiag }
|
||||
| { kind: 'failed'; reason: ImportFailureReason; detail: string }
|
||||
|
||||
export interface ImportClientOptions {
|
||||
spawn: () => WorkerLike
|
||||
/** Until `ready`: the module's fetch, compile and instantiation. */
|
||||
startTimeoutMs: number
|
||||
/** From `ready` to the result (plan §B.3: 20 s hypothesis, set at J1). */
|
||||
taskTimeoutMs: number
|
||||
visibility?: Visibility
|
||||
}
|
||||
|
||||
export interface ImportRun {
|
||||
settled: Promise<ImportSettlement>
|
||||
/** Terminates the worker and settles `cancelled` unless already settled. */
|
||||
cancel(): void
|
||||
}
|
||||
|
||||
/** The failure reason of a `failed` message, per §B.1.8. */
|
||||
function reasonOf(phase: 'start' | 'task', kind: string): ImportFailureReason {
|
||||
if (phase === 'start') return 'worker_unavailable'
|
||||
if (kind === 'trap') return 'crashed'
|
||||
if (kind === 'read') return 'read'
|
||||
return 'engine'
|
||||
}
|
||||
|
||||
export function runImportTask(
|
||||
input: ImportTaskInput,
|
||||
options: ImportClientOptions,
|
||||
): ImportRun {
|
||||
let worker: WorkerLike | null = null
|
||||
let timer: PausableTimer | null = null
|
||||
let ready = false
|
||||
let done = false
|
||||
let resolve!: (settlement: ImportSettlement) => void
|
||||
const settled = new Promise<ImportSettlement>((r) => {
|
||||
resolve = r
|
||||
})
|
||||
const visibility = options.visibility ?? documentVisibility
|
||||
|
||||
const settle = (settlement: ImportSettlement) => {
|
||||
if (done) return
|
||||
done = true
|
||||
timer?.clear()
|
||||
timer = null
|
||||
worker?.terminate()
|
||||
worker = null
|
||||
resolve(settlement)
|
||||
}
|
||||
const fail = (reason: ImportFailureReason, detail: string) =>
|
||||
settle({ kind: 'failed', reason, detail })
|
||||
const arm = (ms: number, reason: ImportFailureReason) => {
|
||||
timer?.clear()
|
||||
timer = new PausableTimer(
|
||||
ms,
|
||||
() => fail(reason, `${reason} after ${ms} ms`),
|
||||
visibility,
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
worker = options.spawn()
|
||||
} catch (error) {
|
||||
fail(
|
||||
'worker_unavailable',
|
||||
error instanceof Error ? error.name : 'spawn failed',
|
||||
)
|
||||
return { settled, cancel: () => fail('cancelled', 'cancelled') }
|
||||
}
|
||||
worker.onmessage = (event) => {
|
||||
const data: unknown = event.data
|
||||
if (!isWorkerMessage(data)) return
|
||||
if (data.type === 'ready') {
|
||||
ready = true
|
||||
arm(options.taskTimeoutMs, 'timeout')
|
||||
} else if (data.type === 'result') {
|
||||
settle({ kind: 'result', out: data.out, diag: data.diag })
|
||||
} else {
|
||||
fail(reasonOf(data.phase, data.kind), data.detail)
|
||||
}
|
||||
}
|
||||
// An `error` event is never masked: it settles the import (and reaches the console).
|
||||
worker.onerror = (event) =>
|
||||
fail(ready ? 'crashed' : 'worker_unavailable', event.message)
|
||||
worker.onmessageerror = () =>
|
||||
fail(ready ? 'engine' : 'worker_unavailable', 'messageerror')
|
||||
arm(options.startTimeoutMs, 'worker_unavailable')
|
||||
worker.postMessage({ v: PROTOCOL_VERSION, type: 'task', ...input })
|
||||
return { settled, cancel: () => fail('cancelled', 'cancelled') }
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import workerUrl from './import.worker?worker&url'
|
||||
import {
|
||||
runImportTask,
|
||||
type ImportRun,
|
||||
type ImportSettlement,
|
||||
type ImportTaskInput,
|
||||
} from './client'
|
||||
import type { WorkerLike } from './client'
|
||||
|
||||
/**
|
||||
* One import at a time for the page (R4.3, plan §B.1.5 items 6 and 7): a new start
|
||||
* cancels the running one, leaving Home cancels it, and the worker script is prefetched
|
||||
* once the editor has loaded the engine so that a later offline import can start.
|
||||
*/
|
||||
|
||||
/** Until `ready`: a cold fetch, compile and instantiation on a slow device. */
|
||||
export const IMPORT_START_TIMEOUT_MS = 10_000
|
||||
/** From `ready` to the result (plan §B.3: 20 s hypothesis, confirmed or moved at J1). */
|
||||
export const IMPORT_TIMEOUT_MS = 20_000
|
||||
|
||||
type Spawn = () => WorkerLike
|
||||
|
||||
const spawnWorker: Spawn = () =>
|
||||
new Worker(workerUrl, { type: 'module', name: 'faunosteo-import' })
|
||||
|
||||
let spawn: Spawn = spawnWorker
|
||||
let running: ImportRun | null = null
|
||||
let prefetched = false
|
||||
|
||||
/** Starts an import; a running one is cancelled first (its result dropped). */
|
||||
export function startImport(input: ImportTaskInput): Promise<ImportSettlement> {
|
||||
running?.cancel()
|
||||
const run = runImportTask(input, {
|
||||
spawn,
|
||||
startTimeoutMs: IMPORT_START_TIMEOUT_MS,
|
||||
taskTimeoutMs: IMPORT_TIMEOUT_MS,
|
||||
})
|
||||
running = run
|
||||
void run.settled.then(() => {
|
||||
if (running === run) running = null
|
||||
})
|
||||
return run.settled
|
||||
}
|
||||
|
||||
/** Cancels the running import, if any (leaving Home, a second pick). */
|
||||
export function cancelImport(): void {
|
||||
running?.cancel()
|
||||
running = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Warms the HTTP cache with the worker chunk (an immutable `/assets/` file) so that an
|
||||
* import works offline once the editor has loaded the engine, as it does today. Best
|
||||
* effort: a failure changes nothing.
|
||||
*/
|
||||
export function prefetchImportWorker(): void {
|
||||
if (
|
||||
prefetched ||
|
||||
typeof Worker === 'undefined' ||
|
||||
typeof fetch !== 'function'
|
||||
)
|
||||
return
|
||||
prefetched = true
|
||||
fetch(workerUrl, { credentials: 'same-origin' })
|
||||
.then((response) => response.body?.cancel())
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
/** Test seam: run the worker logic in-process instead of a real `Worker`. */
|
||||
export function setImportWorkerSpawn(next: Spawn | null): void {
|
||||
spawn = next ?? spawnWorker
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import type { GlueFileBytes, GlueSheetHandle } from '@faunosteo/core-wasm'
|
||||
import { closedRefusal } from '@faunosteo/core-wasm'
|
||||
import {
|
||||
describeError,
|
||||
failureKindOf,
|
||||
PROTOCOL_VERSION,
|
||||
type ImportTaskKind,
|
||||
type ImportTaskMessage,
|
||||
type WorkerFailurePhase,
|
||||
type WorkerMessage,
|
||||
} from './protocol'
|
||||
|
||||
/**
|
||||
* The import worker's logic (R4.3, plan §B.1.5 items 2 and 4), apart from the worker
|
||||
* global so that vitest runs it in-process on the Node module: the engine is injected.
|
||||
* One task per worker: instantiate, answer `ready`, build the sheet handle, stream the
|
||||
* file into the module's memory (the file lives once, never as an ArrayBuffer here), run
|
||||
* the core, answer `result`; every throwable becomes one `failed` with its phase and kind.
|
||||
*/
|
||||
|
||||
/** What the glue gives once instantiated. */
|
||||
export interface WorkerEngine {
|
||||
SheetHandle: new (bundle: string) => GlueSheetHandle
|
||||
FileBytes: new (expected: number) => GlueFileBytes
|
||||
/** The instance's linear memory, for the diag. */
|
||||
memory: WebAssembly.Memory | null
|
||||
}
|
||||
|
||||
export type EngineLoader = (
|
||||
module: WebAssembly.Module | null,
|
||||
) => Promise<WorkerEngine>
|
||||
|
||||
/** The caps the worker checks before reading a byte (the core enforces the same). */
|
||||
export const MAX_PDF_BYTES = 50 * 1024 * 1024
|
||||
export const MAX_COPY_BYTES = 16 * 1024 * 1024
|
||||
|
||||
/** The core's failure envelope, for the caps the worker applies itself. */
|
||||
function refusal(kind: string, detail: string): string {
|
||||
return JSON.stringify({ ok: false, kind, detail })
|
||||
}
|
||||
|
||||
/** The sheet handle, or an error named `SheetRefused` carrying the module's refusal. */
|
||||
function sheetHandle(engine: WorkerEngine, sheet: string): GlueSheetHandle {
|
||||
try {
|
||||
return new engine.SheetHandle(sheet)
|
||||
} catch (error) {
|
||||
const detail = closedRefusal(error)
|
||||
if (detail === null) throw error
|
||||
const refused = new Error(detail)
|
||||
refused.name = 'SheetRefused'
|
||||
throw refused
|
||||
}
|
||||
}
|
||||
|
||||
interface Gathered {
|
||||
bytes: GlueFileBytes
|
||||
chunks: number
|
||||
}
|
||||
|
||||
/** Streams the file into the module's memory, one chunk live at a time. */
|
||||
async function gather(
|
||||
engine: WorkerEngine,
|
||||
file: File,
|
||||
): Promise<Gathered | null> {
|
||||
const bytes = new engine.FileBytes(file.size)
|
||||
const reader = file.stream().getReader()
|
||||
let chunks = 0
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) return { bytes, chunks }
|
||||
chunks += 1
|
||||
// A push refused means the file is not the size it announced: not a Faunosteo file.
|
||||
if (!bytes.push(value)) {
|
||||
await reader.cancel()
|
||||
bytes.free()
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The task's outcome envelope text and the chunk count. */
|
||||
async function runTask(
|
||||
engine: WorkerEngine,
|
||||
handle: GlueSheetHandle,
|
||||
task: ImportTaskKind,
|
||||
file: File,
|
||||
): Promise<{ out: string; chunks: number }> {
|
||||
const cap = task === 'pdf' ? MAX_PDF_BYTES : MAX_COPY_BYTES
|
||||
const kind = task === 'pdf' ? 'invalid_pdf' : 'invalid'
|
||||
if (file.size > cap)
|
||||
return { out: refusal(kind, 'over the size cap'), chunks: 0 }
|
||||
const gathered = await gather(engine, file)
|
||||
if (!gathered)
|
||||
return { out: refusal(kind, 'size changed while reading'), chunks: 0 }
|
||||
const out =
|
||||
task === 'pdf'
|
||||
? handle.import_pdf_bytes(gathered.bytes)
|
||||
: handle.restore_copy_bytes(gathered.bytes)
|
||||
return { out, chunks: gathered.chunks }
|
||||
}
|
||||
|
||||
/**
|
||||
* The handler of the task message: `load` instantiates the module (the posted one, or
|
||||
* fetched), `post` sends the answers. Resolves once the task has settled either way.
|
||||
*/
|
||||
export function createWorkerHandler(
|
||||
load: EngineLoader,
|
||||
post: (message: WorkerMessage) => void,
|
||||
): (data: unknown) => Promise<void> {
|
||||
const fail = (phase: WorkerFailurePhase, error: unknown) =>
|
||||
post({
|
||||
v: PROTOCOL_VERSION,
|
||||
type: 'failed',
|
||||
phase,
|
||||
kind: failureKindOf(error),
|
||||
detail: describeError(error),
|
||||
})
|
||||
return async (data) => {
|
||||
if (!isTaskMessage(data)) return
|
||||
let phase: WorkerFailurePhase = 'start'
|
||||
try {
|
||||
const engine = await load(data.module)
|
||||
post({ v: PROTOCOL_VERSION, type: 'ready' })
|
||||
phase = 'task'
|
||||
const started = performance.now()
|
||||
const handle = sheetHandle(engine, data.sheet)
|
||||
const { out, chunks } = await runTask(
|
||||
engine,
|
||||
handle,
|
||||
data.task,
|
||||
data.file,
|
||||
)
|
||||
const linearBytes = engine.memory?.buffer.byteLength ?? null
|
||||
const diag = { ms: performance.now() - started, linearBytes, chunks }
|
||||
post({ v: PROTOCOL_VERSION, type: 'result', out, diag })
|
||||
} catch (error) {
|
||||
fail(phase, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isTaskMessage(data: unknown): data is ImportTaskMessage {
|
||||
if (typeof data !== 'object' || data === null) return false
|
||||
const record = data as { v?: unknown; type?: unknown; task?: unknown }
|
||||
return (
|
||||
record.v === PROTOCOL_VERSION &&
|
||||
record.type === 'task' &&
|
||||
(record.task === 'pdf' || record.task === 'copy')
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/// <reference lib="webworker" />
|
||||
import init, {
|
||||
FileBytes,
|
||||
SheetHandle,
|
||||
} from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js'
|
||||
import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url'
|
||||
import { createWorkerHandler, type WorkerEngine } from './handler'
|
||||
import { describeError, PROTOCOL_VERSION } from './protocol'
|
||||
|
||||
/**
|
||||
* The import worker entry (R4.3, plan §B.1.5 item 2): the glue is imported statically and
|
||||
* bundled into this chunk (a same-origin hashed asset the production CSP allows, no
|
||||
* `import()`, no recovery logic); the module is the compiled one the page posts, else the
|
||||
* asset fetched here. The listener is installed before any await; the whole life runs
|
||||
* inside the handler's try/catch, with `unhandledrejection` as a backstop: every throwable
|
||||
* reaches the page as one `failed` message. The page terminates the worker in every case.
|
||||
*/
|
||||
|
||||
const scope = self as unknown as DedicatedWorkerGlobalScope
|
||||
|
||||
const loadEngine = async (
|
||||
module: WebAssembly.Module | null,
|
||||
): Promise<WorkerEngine> => {
|
||||
const exports = (await init({ module_or_path: module ?? wasmUrl })) as {
|
||||
memory?: WebAssembly.Memory
|
||||
}
|
||||
return { SheetHandle, FileBytes, memory: exports.memory ?? null }
|
||||
}
|
||||
|
||||
const handle = createWorkerHandler(loadEngine, (message) =>
|
||||
scope.postMessage(message),
|
||||
)
|
||||
|
||||
scope.onmessage = (event: MessageEvent<unknown>) => {
|
||||
void handle(event.data)
|
||||
}
|
||||
|
||||
scope.onunhandledrejection = (event: PromiseRejectionEvent) => {
|
||||
scope.postMessage({
|
||||
v: PROTOCOL_VERSION,
|
||||
type: 'failed',
|
||||
phase: 'task',
|
||||
kind: 'other',
|
||||
detail: describeError(event.reason),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { ArchiveImport, DraftRestore } from '@faunosteo/core-wasm/types'
|
||||
import type { ImportSettlement, ImportTaskInput } from './client'
|
||||
|
||||
/**
|
||||
* What the import worker's settlement means for the page (R4.3, plan §B.1.8): the core's
|
||||
* outcome envelope mapped to the page's import error kinds, and the worker's own failures
|
||||
* classified so that a technical error, a resource overflow or a timeout is never shown as
|
||||
* a corrupt PDF (OD-5: `generic` for a PDF crash or timeout, `core_unavailable` for a copy).
|
||||
*/
|
||||
|
||||
export type ImportErrorKind =
|
||||
| 'invalid_pdf'
|
||||
| 'no_attachment'
|
||||
| 'attachment_stripped'
|
||||
| 'incompatible_version'
|
||||
| 'lone_surrogate'
|
||||
| 'invalid_copy'
|
||||
| 'core_unavailable'
|
||||
| 'generic'
|
||||
|
||||
export class ImportError extends Error {
|
||||
constructor(
|
||||
readonly kind: ImportErrorKind,
|
||||
/** The report version found, for `incompatible_version`. */
|
||||
readonly foundVersion: number | null = null,
|
||||
/** The technical reason, for the DEV console only. */
|
||||
readonly detail = '',
|
||||
) {
|
||||
super(kind)
|
||||
this.name = 'ImportError'
|
||||
}
|
||||
}
|
||||
|
||||
interface Envelope<T> {
|
||||
ok: boolean
|
||||
value?: T
|
||||
kind?: string
|
||||
found?: number
|
||||
detail?: string
|
||||
}
|
||||
|
||||
/** The envelope text, or `core_unavailable` when it is not one (never a trusted shape). */
|
||||
function parseEnvelope<T>(out: string): Envelope<T> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(out)
|
||||
if (typeof parsed === 'object' && parsed !== null && 'ok' in parsed) {
|
||||
return parsed as Envelope<T>
|
||||
}
|
||||
} catch {
|
||||
// Not JSON: the module answered garbage, treated as an engine failure below.
|
||||
}
|
||||
throw new ImportError('core_unavailable', null, 'unreadable envelope')
|
||||
}
|
||||
|
||||
/** `SheetHandle.import_pdf` failures, one to one with today's kinds. */
|
||||
function pdfError(envelope: Envelope<unknown>): ImportError {
|
||||
switch (envelope.kind) {
|
||||
case 'invalid_pdf':
|
||||
case 'no_attachment':
|
||||
case 'attachment_stripped':
|
||||
case 'lone_surrogate':
|
||||
return new ImportError(envelope.kind, null, envelope.detail)
|
||||
case 'incompatible_version':
|
||||
return new ImportError('incompatible_version', envelope.found ?? null)
|
||||
case 'invalid':
|
||||
// The rebase refused the loaded sheet's reference: today's generic message.
|
||||
return new ImportError('generic', null, envelope.detail)
|
||||
default:
|
||||
return new ImportError('core_unavailable', null, envelope.detail)
|
||||
}
|
||||
}
|
||||
|
||||
/** Kinds that mean the copy itself cannot be read (`reportStore.UNREADABLE_DRAFT_KINDS`). */
|
||||
const UNREADABLE_COPY = new Set([
|
||||
'invalid',
|
||||
'unsupported_version',
|
||||
'lone_surrogate',
|
||||
])
|
||||
|
||||
function copyError(envelope: Envelope<unknown>): ImportError {
|
||||
if (UNREADABLE_COPY.has(envelope.kind ?? '')) {
|
||||
return new ImportError('invalid_copy', null, envelope.detail)
|
||||
}
|
||||
return new ImportError('core_unavailable', null, envelope.detail)
|
||||
}
|
||||
|
||||
/** The worker's own failures, by task (OD-5). */
|
||||
function workerError(
|
||||
task: ImportTaskInput['task'],
|
||||
settlement: ImportSettlement,
|
||||
): ImportError {
|
||||
if (settlement.kind !== 'failed') throw new Error('not a failure')
|
||||
const { reason, detail } = settlement
|
||||
if (reason === 'read') return new ImportError('generic', null, detail)
|
||||
if (task === 'pdf' && (reason === 'crashed' || reason === 'timeout')) {
|
||||
return new ImportError('generic', null, detail)
|
||||
}
|
||||
return new ImportError('core_unavailable', null, detail)
|
||||
}
|
||||
|
||||
/** The imported archive, or the ImportError the page shows. */
|
||||
export function pdfImportOf(settlement: ImportSettlement): ArchiveImport {
|
||||
if (settlement.kind === 'failed') throw workerError('pdf', settlement)
|
||||
const envelope = parseEnvelope<ArchiveImport>(settlement.out)
|
||||
if (!envelope.ok || envelope.value === undefined) throw pdfError(envelope)
|
||||
return envelope.value
|
||||
}
|
||||
|
||||
/** The restored copy, or the ImportError the page shows. */
|
||||
export function copyRestoreOf(settlement: ImportSettlement): DraftRestore {
|
||||
if (settlement.kind === 'failed') throw workerError('copy', settlement)
|
||||
const envelope = parseEnvelope<DraftRestore>(settlement.out)
|
||||
if (!envelope.ok || envelope.value === undefined) throw copyError(envelope)
|
||||
return envelope.value
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Messages between the page and the import worker (R4.3, plan §B.1.5), tagged `v: 1`.
|
||||
* The page posts one task; the worker answers `ready` once its instance runs, then one
|
||||
* `result` or one `failed`. Anything after the first settlement is ignored by the page.
|
||||
*/
|
||||
|
||||
export const PROTOCOL_VERSION = 1
|
||||
|
||||
export type ImportTaskKind = 'pdf' | 'copy'
|
||||
|
||||
export interface ImportTaskMessage {
|
||||
v: typeof PROTOCOL_VERSION
|
||||
type: 'task'
|
||||
task: ImportTaskKind
|
||||
/** The picked file, never read on the page's thread. */
|
||||
file: File
|
||||
/** The bundled sheet payload text the page's runtime builds its handle from. */
|
||||
sheet: string
|
||||
/** The compiled module of the page's runtime when it holds one; else the worker fetches. */
|
||||
module: WebAssembly.Module | null
|
||||
}
|
||||
|
||||
export interface WorkerReadyMessage {
|
||||
v: typeof PROTOCOL_VERSION
|
||||
type: 'ready'
|
||||
}
|
||||
|
||||
export interface WorkerResultMessage {
|
||||
v: typeof PROTOCOL_VERSION
|
||||
type: 'result'
|
||||
/** The outcome envelope text of the core (`{"ok":true,…}` or `{"ok":false,"kind":…}`). */
|
||||
out: string
|
||||
diag: ImportDiag
|
||||
}
|
||||
|
||||
/** Printed in DEV only, never sent anywhere. */
|
||||
export interface ImportDiag {
|
||||
ms: number
|
||||
linearBytes: number | null
|
||||
chunks: number
|
||||
}
|
||||
|
||||
export type WorkerFailurePhase = 'start' | 'task'
|
||||
|
||||
/**
|
||||
* `trap`: a `WebAssembly.RuntimeError`, or an engine stack overflow (`RangeError`,
|
||||
* `InternalError`); `read`: the file could not be read; `sheet`: the bundled sheet was
|
||||
* refused by the module; `other`: anything else (a glue or network failure at start).
|
||||
*/
|
||||
export type WorkerFailureKind = 'trap' | 'read' | 'sheet' | 'other'
|
||||
|
||||
export interface WorkerFailedMessage {
|
||||
v: typeof PROTOCOL_VERSION
|
||||
type: 'failed'
|
||||
phase: WorkerFailurePhase
|
||||
kind: WorkerFailureKind
|
||||
/** Error name and first message line, for the DEV console only. */
|
||||
detail: string
|
||||
}
|
||||
|
||||
export type WorkerMessage =
|
||||
| WorkerReadyMessage
|
||||
| WorkerResultMessage
|
||||
| WorkerFailedMessage
|
||||
|
||||
/** True for a message of this protocol, from a worker of the same build. */
|
||||
export function isWorkerMessage(data: unknown): data is WorkerMessage {
|
||||
if (typeof data !== 'object' || data === null) return false
|
||||
const record = data as { v?: unknown; type?: unknown }
|
||||
return (
|
||||
record.v === PROTOCOL_VERSION &&
|
||||
(record.type === 'ready' ||
|
||||
record.type === 'result' ||
|
||||
record.type === 'failed')
|
||||
)
|
||||
}
|
||||
|
||||
/** Error name and first message line, bounded, for a `failed` message. */
|
||||
export function describeError(error: unknown): string {
|
||||
const name = error instanceof Error ? error.name : 'Error'
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return `${name}: ${message}`.split('\n')[0]!.slice(0, 200)
|
||||
}
|
||||
|
||||
/** The failure kind of a throwable, per §B.1.5 item 2. */
|
||||
export function failureKindOf(error: unknown): WorkerFailureKind {
|
||||
if (error instanceof WebAssembly.RuntimeError) return 'trap'
|
||||
if (!(error instanceof Error)) return 'other'
|
||||
if (error.name === 'RangeError' || error.name === 'InternalError')
|
||||
return 'trap'
|
||||
if (error.name === 'NotReadableError' || error.name === 'NotFoundError')
|
||||
return 'read'
|
||||
if (error.name === 'SheetRefused') return 'sheet'
|
||||
return 'other'
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* A one-shot timer that stops counting while the page is hidden (R4.3, plan §B.1.5 item
|
||||
* 3): a phone that backgrounds the tab must not time an import out on return. The
|
||||
* visibility source is injected so tests drive it.
|
||||
*/
|
||||
|
||||
export interface Visibility {
|
||||
hidden(): boolean
|
||||
/** Calls `listener` on every change; returns the unsubscribe function. */
|
||||
onChange(listener: () => void): () => void
|
||||
}
|
||||
|
||||
export const documentVisibility: Visibility = {
|
||||
hidden: () =>
|
||||
typeof document !== 'undefined' && document.visibilityState === 'hidden',
|
||||
onChange: (listener) => {
|
||||
if (typeof document === 'undefined') return () => {}
|
||||
document.addEventListener('visibilitychange', listener)
|
||||
return () => document.removeEventListener('visibilitychange', listener)
|
||||
},
|
||||
}
|
||||
|
||||
export class PausableTimer {
|
||||
private remainingMs: number
|
||||
private startedAt: number | null = null
|
||||
private handle: ReturnType<typeof setTimeout> | null = null
|
||||
private readonly unsubscribe: () => void
|
||||
|
||||
constructor(
|
||||
durationMs: number,
|
||||
private readonly onElapsed: () => void,
|
||||
private readonly visibility: Visibility = documentVisibility,
|
||||
private readonly now: () => number = () => performance.now(),
|
||||
) {
|
||||
this.remainingMs = durationMs
|
||||
this.unsubscribe = visibility.onChange(() => this.sync())
|
||||
this.sync()
|
||||
}
|
||||
|
||||
/** Stops the timer for good; a timer never fires after it. */
|
||||
clear(): void {
|
||||
this.pause()
|
||||
this.unsubscribe()
|
||||
this.remainingMs = Number.POSITIVE_INFINITY
|
||||
}
|
||||
|
||||
private sync(): void {
|
||||
if (this.visibility.hidden()) this.pause()
|
||||
else this.resume()
|
||||
}
|
||||
|
||||
private resume(): void {
|
||||
if (this.handle !== null || !Number.isFinite(this.remainingMs)) return
|
||||
this.startedAt = this.now()
|
||||
this.handle = setTimeout(() => {
|
||||
this.handle = null
|
||||
this.remainingMs = 0
|
||||
this.unsubscribe()
|
||||
this.onElapsed()
|
||||
}, this.remainingMs)
|
||||
}
|
||||
|
||||
private pause(): void {
|
||||
if (this.handle === null) return
|
||||
clearTimeout(this.handle)
|
||||
this.handle = null
|
||||
if (this.startedAt !== null) {
|
||||
this.remainingMs = Math.max(
|
||||
0,
|
||||
this.remainingMs - (this.now() - this.startedAt),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user