Verifier ECARTS(3) and security PASS on 8294d54: one indexed walk per
view chain in sheet.edit, a set for referenced drawings, released
preview parses, xml:base and CSS loaders refused, fail-closed PI scan,
PI drawings rejected by the preview, the builder naming its cap.
361 lines
13 KiB
TypeScript
361 lines
13 KiB
TypeScript
import {
|
|
CORE_UNAVAILABLE,
|
|
failure,
|
|
parseOutcome,
|
|
type CoreOutcome,
|
|
} from './outcome'
|
|
|
|
/**
|
|
* Browser and Node runtime of the core module (RUST_ARCHITECTURE_REVIEW III.3 rules 5 and
|
|
* 6, R2 plan P9 rev 2). The module is loaded on first need only; calls are synchronous once
|
|
* it is ready. A `WebAssembly.RuntimeError` (a Rust panic or a stack overflow) poisons the
|
|
* instance: the failing call answers `internal`, no further call reaches that instance, and
|
|
* a fresh one is created from the compiled module kept in memory and a glue module record
|
|
* imported in advance (a trap needs no network). Calls made while it is re-created answer
|
|
* `core_unavailable`; after `maxRecoveries` traps the page stays unavailable until reload.
|
|
* A recovery or restart that fails below the cap is not final: the next call or `ready()`
|
|
* restarts the runtime (a restart is not a recovery and does not touch the counter).
|
|
*/
|
|
|
|
/** What the wasm-bindgen glue (`--target web`) exports. */
|
|
export interface GlueModule {
|
|
default(input: { module_or_path: WebAssembly.Module }): Promise<unknown>
|
|
core_version(): string
|
|
call(op: string, input: string): string
|
|
SheetHandle: new (bundle: string) => GlueSheetHandle
|
|
FileBytes: new (expected: number) => GlueFileBytes
|
|
/** R4.6: the incremental export; the constructor throws `<kind>: <detail>` on a refused input. */
|
|
ExportSession: new (inputJson: string) => GlueExportSession
|
|
/** V1-2.2: a stored version gathered for preview (drawings first, then `build`). */
|
|
PreviewBuilder: new () => GluePreviewBuilder
|
|
/** V1-2.2: the cleaning answer for a file picked for upload (`SvgCleaning` envelope). */
|
|
clean_svg(bytes: Uint8Array): string
|
|
}
|
|
|
|
/** A stored version being gathered (crates/wasm `PreviewBuilder`). */
|
|
export interface GluePreviewBuilder {
|
|
/** `false` past 16 drawings or a drawing over 2 MiB; the build then throws `caps: drawing_bytes` or `caps: drawings`. */
|
|
add_drawing(assetId: string, sha256: string, bytes: Uint8Array): boolean
|
|
/** Consumes the builder; throws `<kind>: <detail>` (`invalid_document`, `drawing_missing`,
|
|
* `drawing_hash_mismatch`, `fingerprint_mismatch`, `caps`, `invalid_shape`, `invalid_json`). */
|
|
build(inputJson: string): GluePreviewSheet
|
|
free(): void
|
|
}
|
|
|
|
/** A stored version loaded for the catalogue, the preview and the editor (crates/wasm
|
|
* `PreviewSheet`): no report migration map, never a report session. */
|
|
export interface GluePreviewSheet {
|
|
/** `preview.state` or `view.canvas`; outcome envelopes out. */
|
|
call(op: string, input: string): string
|
|
/** A draft's document after an edit, the drawings kept as read. */
|
|
replace_document(text: string): string
|
|
add_drawing(assetId: string, sha256: string, bytes: Uint8Array): string
|
|
free(): void
|
|
}
|
|
|
|
/** The export session of the module (crates/wasm `ExportSession`): outcome envelopes out. */
|
|
export interface GlueExportSession {
|
|
next_step(): string
|
|
add_raster(key: string, png: Uint8Array): string
|
|
raster_failed(key: string): string
|
|
/** Throws `<kind>: <detail>` (`out_of_order`, `self_check_failed`); the parts count otherwise. */
|
|
finish(): number
|
|
/** The next part of the finished file (copied out, freed in the module), `undefined` at the end. */
|
|
take_part(): Uint8Array | undefined
|
|
warnings(): string
|
|
written(): number
|
|
free(): void
|
|
}
|
|
|
|
export interface GlueSheetHandle {
|
|
call(op: string, input: string): string
|
|
/** R4: the PDF import, bytes in, the same envelope out (`PdfImportKind` on failure). */
|
|
import_pdf(bytes: Uint8Array): string
|
|
/** R4.3: the same import on bytes streamed into the module's memory (consumed). */
|
|
import_pdf_bytes(bytes: GlueFileBytes): string
|
|
/** R4.3: a rescue copy streamed into the module's memory (consumed): `draft.restore`'s kinds. */
|
|
restore_copy_bytes(bytes: GlueFileBytes): string
|
|
/** wasm-bindgen's: the page's session keeps its handle for the instance's life, a worker
|
|
* dies with its own; the tests' throwaway handles free theirs. */
|
|
free(): void
|
|
}
|
|
|
|
/** A file gathered chunk by chunk in the module's memory (crates/wasm `FileBytes`). */
|
|
export interface GlueFileBytes {
|
|
push(chunk: Uint8Array): boolean
|
|
len(): number
|
|
free(): void
|
|
}
|
|
|
|
/** Where the module comes from: the browser (Vite asset URLs) or Node (files). */
|
|
export interface CoreSource {
|
|
/** Compiles the `.wasm` once; the runtime keeps the result for every instance. */
|
|
compile(): Promise<WebAssembly.Module>
|
|
/**
|
|
* Imports a NEW glue module record: the glue keeps its instance in a module variable and
|
|
* the ESM cache returns the same record for the same URL, so each `instance` number must
|
|
* give a distinct URL (cache-busting query).
|
|
*/
|
|
importGlue(instance: number): Promise<GlueModule>
|
|
}
|
|
|
|
export type CoreStatus =
|
|
| 'idle'
|
|
| 'loading'
|
|
| 'ready'
|
|
| 'recovering'
|
|
| 'unavailable'
|
|
|
|
export interface CoreRuntimeOptions {
|
|
/** Re-creations after a trap allowed for the page's lifetime. */
|
|
maxRecoveries?: number
|
|
}
|
|
|
|
export class CoreRuntime {
|
|
private state: CoreStatus = 'idle'
|
|
private glue: GlueModule | null = null
|
|
private compiled: Promise<WebAssembly.Module> | null = null
|
|
private spare: Promise<GlueModule | null> | null = null
|
|
private pending: Promise<boolean> | null = null
|
|
private imports = 0
|
|
private recoveries = 0
|
|
private readonly maxRecoveries: number
|
|
private readonly listeners = new Set<() => void>()
|
|
/** Increments with every instance; sheet handles of an older generation are dropped. */
|
|
generation = 0
|
|
|
|
constructor(
|
|
private readonly source: CoreSource,
|
|
options: CoreRuntimeOptions = {},
|
|
) {
|
|
this.maxRecoveries = options.maxRecoveries ?? 3
|
|
}
|
|
|
|
get status(): CoreStatus {
|
|
return this.state
|
|
}
|
|
|
|
/**
|
|
* The recovery cap is spent: no retry can bring the module back on this page (owner
|
|
* decision 2026-10-15: three attempts, then a clear failure state; a reload starts again).
|
|
*/
|
|
get stopped(): boolean {
|
|
return this.state === 'unavailable' && this.recoveries >= this.maxRecoveries
|
|
}
|
|
|
|
/**
|
|
* Unavailable after an instance already ran (a failed recovery or restart) with
|
|
* recoveries left: the next call may bring it back. A failed FIRST load is not restarted
|
|
* implicitly, only by `retry()`.
|
|
*/
|
|
private get restartable(): boolean {
|
|
return this.state === 'unavailable' && !this.stopped && this.generation > 0
|
|
}
|
|
|
|
/**
|
|
* Calls `listener` (after a microtask, never inside a load or recovery) each time the
|
|
* status changes; returns the unsubscribe function.
|
|
*/
|
|
subscribe(listener: () => void): () => void {
|
|
this.listeners.add(listener)
|
|
return () => {
|
|
this.listeners.delete(listener)
|
|
}
|
|
}
|
|
|
|
/** Loads the module on first use; true when calls can be made. */
|
|
ready(): Promise<boolean> {
|
|
if (this.state === 'ready') return Promise.resolve(true)
|
|
if (this.restartable) return this.retry()
|
|
if (this.state === 'unavailable') return Promise.resolve(false)
|
|
this.pending ??= this.load()
|
|
return this.pending
|
|
}
|
|
|
|
/** After a load failure: forgets it and loads again (traps already spent stay spent). */
|
|
retry(): Promise<boolean> {
|
|
if (this.state !== 'unavailable') return this.ready()
|
|
if (this.recoveries >= this.maxRecoveries) return Promise.resolve(false)
|
|
this.setState('idle')
|
|
// Only a failed first load clears the compiled module: once an instance ran, it is sound.
|
|
if (this.generation === 0) this.compiled = null
|
|
this.pending = null
|
|
return this.ready()
|
|
}
|
|
|
|
/** Starts a restart when the next call may succeed (the current call still answers). */
|
|
kickRestart(): void {
|
|
if (this.restartable) void this.retry()
|
|
}
|
|
|
|
/**
|
|
* The compiled module of this runtime, when a load has started: posted to the import
|
|
* worker (R4.3, structured clone) so an import needs no second fetch, offline included;
|
|
* `null` before the first load, the worker then fetches the asset itself.
|
|
*/
|
|
compiledModule(): Promise<WebAssembly.Module> | null {
|
|
return this.compiled
|
|
}
|
|
|
|
/** Runs a free operation. */
|
|
call<T>(op: string, input: string): CoreOutcome<T> {
|
|
return this.invoke((glue) => parseOutcome<T>(glue.call(op, input)))
|
|
}
|
|
|
|
/** A session bound to one sheet payload; the handle is rebuilt per instance. */
|
|
sheet(bundleText: string): SheetSession {
|
|
return new SheetSession(this, bundleText)
|
|
}
|
|
|
|
/**
|
|
* Runs `fn` on the live instance. Any exception from the module poisons the instance:
|
|
* the result is `internal`, and the next calls wait for a fresh one.
|
|
*/
|
|
invoke<T>(fn: (glue: GlueModule) => CoreOutcome<T>): CoreOutcome<T> {
|
|
const glue = this.glue
|
|
if (this.state !== 'ready' || !glue) {
|
|
this.kickRestart()
|
|
return CORE_UNAVAILABLE
|
|
}
|
|
try {
|
|
return fn(glue)
|
|
} catch (error) {
|
|
this.poison()
|
|
return failure('internal', error instanceof Error ? error.name : 'error')
|
|
}
|
|
}
|
|
|
|
private async load(): Promise<boolean> {
|
|
this.setState('loading')
|
|
try {
|
|
await this.instantiate(await this.source.importGlue(this.nextImport()))
|
|
return true
|
|
} catch {
|
|
this.setState('unavailable')
|
|
this.pending = null
|
|
return false
|
|
}
|
|
}
|
|
|
|
private async instantiate(glue: GlueModule): Promise<void> {
|
|
this.compiled ??= this.source.compile()
|
|
await glue.default({ module_or_path: await this.compiled })
|
|
this.glue = glue
|
|
this.generation += 1
|
|
this.setState('ready')
|
|
this.spare = this.source.importGlue(this.nextImport()).catch(() => null)
|
|
}
|
|
|
|
private setState(next: CoreStatus): void {
|
|
if (next === this.state) return
|
|
this.state = next
|
|
queueMicrotask(() => this.notify())
|
|
}
|
|
|
|
private notify(): void {
|
|
for (const listener of [...this.listeners]) {
|
|
try {
|
|
listener()
|
|
} catch {
|
|
// A listener never changes the state machine.
|
|
}
|
|
}
|
|
}
|
|
|
|
private nextImport(): number {
|
|
this.imports += 1
|
|
return this.imports
|
|
}
|
|
|
|
private poison(): void {
|
|
this.glue = null
|
|
if (this.recoveries >= this.maxRecoveries) {
|
|
this.setState('unavailable')
|
|
return
|
|
}
|
|
this.recoveries += 1
|
|
this.setState('recovering')
|
|
this.pending = this.recover()
|
|
}
|
|
|
|
private async recover(): Promise<boolean> {
|
|
try {
|
|
const spare = await this.spare
|
|
await this.instantiate(
|
|
spare ?? (await this.source.importGlue(this.nextImport())),
|
|
)
|
|
return true
|
|
} catch {
|
|
this.setState('unavailable')
|
|
return false
|
|
} finally {
|
|
this.pending = null
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The detail of a refusal the module's `SheetHandle` constructor threw (crates/wasm: a
|
|
* `JsError` worded `<kind>: <detail>`), without its `invalid_sheet: ` kind; `null` when the
|
|
* error is anything else.
|
|
*/
|
|
export function closedRefusal(error: unknown): string | null {
|
|
if (!(error instanceof Error) || error.name !== 'Error') return null
|
|
const match = /^([a-z_]+): /.exec(error.message)
|
|
if (!match) return null
|
|
return match[1] === 'invalid_sheet'
|
|
? error.message.slice(match[0].length)
|
|
: error.message
|
|
}
|
|
|
|
/** The calls that need the session's sheet (`SheetHandle` in the module's memory). */
|
|
export class SheetSession {
|
|
private handle: GlueSheetHandle | null = null
|
|
private handleGeneration = -1
|
|
|
|
constructor(
|
|
private readonly runtime: CoreRuntime,
|
|
/** The bundled sheet payload, kept to rebuild the handle on a new instance. */
|
|
readonly bundleText: string,
|
|
) {}
|
|
|
|
/** Builds the handle now: `invalid_sheet` when the payload is refused. */
|
|
open(): CoreOutcome<null> {
|
|
const handle = this.current()
|
|
return handle.ok ? { ok: true, value: null } : handle
|
|
}
|
|
|
|
call<T>(op: string, input: string): CoreOutcome<T> {
|
|
const handle = this.current()
|
|
if (!handle.ok) return handle
|
|
return this.runtime.invoke(() =>
|
|
parseOutcome<T>(handle.value.call(op, input)),
|
|
)
|
|
}
|
|
|
|
/** The handle of the live instance; a handle of a dropped instance is never called. */
|
|
private current(): CoreOutcome<GlueSheetHandle> {
|
|
if (this.handle && this.handleGeneration === this.runtime.generation) {
|
|
if (this.runtime.status === 'ready')
|
|
return { ok: true, value: this.handle }
|
|
this.runtime.kickRestart()
|
|
return CORE_UNAVAILABLE
|
|
}
|
|
this.handle = null
|
|
return this.runtime.invoke((glue) => {
|
|
try {
|
|
this.handle = new glue.SheetHandle(this.bundleText)
|
|
} catch (error) {
|
|
// Only the module's closed refusal (a plain Error worded `<kind>: <detail>`) is a
|
|
// refused sheet; anything else (a trap, an engine stack overflow surfacing as
|
|
// RangeError or InternalError) poisons the instance.
|
|
const refusal = closedRefusal(error)
|
|
if (refusal === null) throw error
|
|
return failure('invalid_sheet', refusal)
|
|
}
|
|
this.handleGeneration = this.runtime.generation
|
|
return { ok: true, value: this.handle }
|
|
})
|
|
}
|
|
}
|