Files
faunosteo/packages/core-wasm/src/export.ts
T

153 lines
4.7 KiB
TypeScript

import type { ExportStep, ExportWarning } from '../types'
import { CORE_UNAVAILABLE, failure, parseOutcome, type CoreOutcome } from './outcome'
import {
closedRefusal,
type CoreRuntime,
type GlueExportSession,
type GlueModule,
} from './runtime'
/**
* The incremental PDF export (R4.6, plan §B.1.4, OD-2) on the page's runtime: every call
* goes through `CoreRuntime.invoke`, so a trap poisons the instance and answers `internal`
* like any core call, and a session opened on an instance the runtime has since dropped
* (a recovery) answers `core_unavailable` without touching the dead handle, as sheet
* handles do. The driver calls `free()` in its `finally`: the module's buffer (the file
* being written) is released whatever the outcome.
*/
export class CoreExportSession {
private handle: GlueExportSession | null
constructor(
private readonly runtime: CoreRuntime,
handle: GlueExportSession,
private readonly generation: number,
) {
this.handle = handle
}
/** The next batch of raster requests, or `done`. */
next(): CoreOutcome<ExportStep> {
return this.call((handle) => parseOutcome<ExportStep>(handle.next_step()))
}
/** The PNG of `key`: `null` on success, else a closed refusal. */
addRaster(key: string, png: Uint8Array): CoreOutcome<null> {
return this.call((handle) =>
parseOutcome<null>(handle.add_raster(key, png)),
)
}
/** `key` could not be rasterised (the session records the warning). */
rasterFailed(key: string): CoreOutcome<null> {
return this.call((handle) => parseOutcome<null>(handle.raster_failed(key)))
}
/**
* The file, as the parts the module hands out one by one (each copied out of linear
* memory and freed there, so the file is never held twice; `new Blob(parts)` takes them
* as they are). The module throws a closed `Error` worded `<kind>: <detail>` for
* `out_of_order` or `self_check_failed`; anything else is a trap.
*/
finish(): CoreOutcome<Uint8Array[]> {
return this.call((handle) => {
let count: number
try {
count = handle.finish()
} catch (error) {
const refusal = closedRefusal(error)
if (refusal === null) throw error
return closedFailure(refusal)
}
const parts: Uint8Array[] = []
for (let i = 0; i < count; i += 1) {
const part = handle.take_part()
if (!part) break
parts.push(part)
}
return { ok: true, value: parts }
})
}
/** The warnings recorded so far (complete after `finish()`). */
warnings(): CoreOutcome<ExportWarning[]> {
return this.call((handle) =>
parseOutcome<ExportWarning[]>(handle.warnings()),
)
}
/** Bytes of the file written so far (DEV diagnostics). */
written(): number {
const outcome = this.call((handle) => ({
ok: true as const,
value: handle.written(),
}))
return outcome.ok ? outcome.value : 0
}
/**
* Releases the module's buffer. Safe to call twice; a handle of a dropped instance is
* never touched (its memory went with the instance).
*/
free(): void {
const handle = this.handle
this.handle = null
if (!handle || !this.live()) return
try {
handle.free()
} catch {
// The glue refuses a double free; nothing else to do.
}
}
private live(): boolean {
return (
this.runtime.generation === this.generation &&
this.runtime.status === 'ready'
)
}
private call<T>(fn: (handle: GlueExportSession) => CoreOutcome<T>): CoreOutcome<T> {
const handle = this.handle
if (!handle) return failure('out_of_order', 'session freed')
if (!this.live()) {
this.runtime.kickRestart()
return CORE_UNAVAILABLE
}
return this.runtime.invoke(() => fn(handle))
}
}
/** `<kind>: <detail>` → the failure. */
function closedFailure(message: string): CoreOutcome<never> {
const colon = message.indexOf(': ')
return colon < 0
? failure(message)
: failure(message.slice(0, colon), message.slice(colon + 2))
}
/**
* Opens a session on the live instance: the module's checks refuse the input with today's
* export kinds (`branding_invalid`, `snapshot_invalid`, `snapshot_too_large`,
* `sheet_mismatch`, `too_many_pages`, `invalid_input`), a trap poisons the instance.
*/
export function openExportSession(
runtime: CoreRuntime,
inputJson: string,
): CoreOutcome<CoreExportSession> {
return runtime.invoke((glue: GlueModule) => {
let handle: GlueExportSession
try {
handle = new glue.ExportSession(inputJson)
} catch (error) {
const refusal = closedRefusal(error)
if (refusal === null) throw error
return closedFailure(refusal)
}
return {
ok: true,
value: new CoreExportSession(runtime, handle, runtime.generation),
}
})
}