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. */ /** What the wasm-bindgen glue (`--target web`) exports. */ export interface GlueModule { default(input: { module_or_path: WebAssembly.Module }): Promise core_version(): string call(op: string, input: string): string SheetHandle: new (bundle: string) => GlueSheetHandle } export interface GlueSheetHandle { call(op: string, input: string): string } /** 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 /** * 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 } 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 | null = null private spare: Promise | null = null private pending: Promise | null = null private imports = 0 private recoveries = 0 private readonly maxRecoveries: number /** 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 } /** Loads the module on first use; true when calls can be made. */ ready(): Promise { if (this.state === 'ready') return Promise.resolve(true) 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 { if (this.state !== 'unavailable') return this.ready() if (this.recoveries >= this.maxRecoveries) return Promise.resolve(false) this.state = 'idle' this.compiled = null this.pending = null return this.ready() } /** Runs a free operation. */ call(op: string, input: string): CoreOutcome { return this.invoke((glue) => parseOutcome(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(fn: (glue: GlueModule) => CoreOutcome): CoreOutcome { const glue = this.glue if (this.state !== 'ready' || !glue) return CORE_UNAVAILABLE try { return fn(glue) } catch (error) { this.poison() return failure('internal', error instanceof Error ? error.name : 'error') } } private async load(): Promise { this.state = 'loading' try { await this.instantiate(await this.source.importGlue(this.nextImport())) return true } catch { this.state = 'unavailable' this.pending = null return false } } private async instantiate(glue: GlueModule): Promise { this.compiled ??= this.source.compile() await glue.default({ module_or_path: await this.compiled }) this.glue = glue this.generation += 1 this.state = 'ready' this.spare = this.source .importGlue(this.nextImport()) .catch(() => null) } private nextImport(): number { this.imports += 1 return this.imports } private poison(): void { this.glue = null if (this.recoveries >= this.maxRecoveries) { this.state = 'unavailable' return } this.recoveries += 1 this.state = 'recovering' this.pending = this.recover() } private async recover(): Promise { try { const spare = await this.spare await this.instantiate( spare ?? (await this.source.importGlue(this.nextImport())), ) return true } catch { this.state = 'unavailable' return false } finally { this.pending = null } } } /** 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 { const handle = this.current() return handle.ok ? { ok: true, value: null } : handle } call(op: string, input: string): CoreOutcome { const handle = this.current() if (!handle.ok) return handle return this.runtime.invoke(() => parseOutcome(handle.value.call(op, input)), ) } /** The handle of the live instance; a handle of a dropped instance is never called. */ private current(): CoreOutcome { if (this.handle && this.handleGeneration === this.runtime.generation) { return this.runtime.status === 'ready' ? { ok: true, value: this.handle } : CORE_UNAVAILABLE } this.handle = null return this.runtime.invoke((glue) => { try { this.handle = new glue.SheetHandle(this.bundleText) } catch (error) { if (error instanceof WebAssembly.RuntimeError) throw error const message = error instanceof Error ? error.message : '' return failure('invalid_sheet', message.replace(/^invalid_sheet: /, '')) } this.handleGeneration = this.runtime.generation return { ok: true, value: this.handle } }) } }