Files
faunosteo/crates/wasm/src/lib.rs
T

280 lines
11 KiB
Rust

//! wasm-bindgen facade over `faunosteo-core` (review III.3): JSON strings in and out, closed
//! outcome kinds. Built by `scripts/wasm-build.sh` into `packages/core-wasm/pkg` (shipped)
//! and `packages/core-wasm/pkg-proofs` (with the trap exports, tests only); loaded lazily by
//! the application behind the sheet and import paths (`packages/core-wasm/src/runtime.ts`).
use faunosteo_core::domain::sheet::LoadedSheet;
use faunosteo_core::pdf::read::MAX_PDF_BYTES;
use wasm_bindgen::prelude::{JsError, wasm_bindgen};
/// Version of the core compiled into this module.
#[wasm_bindgen]
pub fn core_version() -> String {
faunosteo_core::CORE_VERSION.to_owned()
}
/// Runs one core operation: `op` names it, `input` is its JSON text, the result is the
/// JSON text of the outcome envelope (`{"ok":true,"value":…}` or `{"ok":false,"kind":…}`).
#[wasm_bindgen]
pub fn call(op: &str, input: &str) -> String {
faunosteo_core::facade::call(op, input)
}
/// The session's anatomical sheet, held in the module's memory and built once from the
/// bundled payload, so the per-action calls carry only the observation or the report.
#[wasm_bindgen]
pub struct SheetHandle {
sheet: LoadedSheet,
}
#[wasm_bindgen]
impl SheetHandle {
/// Loads the bundled sheet payload; throws an `Error` whose message is
/// `invalid_sheet: <detail>` when the payload, the document or the map is refused.
#[wasm_bindgen(constructor)]
pub fn new(bundle: &str) -> Result<SheetHandle, JsError> {
faunosteo_core::facade::load_sheet(bundle)
.map(|sheet| SheetHandle { sheet })
.map_err(|failure| JsError::new(&format!("{}: {}", failure.kind, failure.detail)))
}
/// Runs one operation on this sheet; same envelope as `call`.
pub fn call(&self, op: &str, input: &str) -> String {
faunosteo_core::facade::call_with_sheet(&self.sheet, op, input)
}
/// Reads `bytes` as a Faunosteo PDF and imports its attachment onto this sheet (R4, plan
/// §B.1.4): the envelope of `archive.import`, plus the reader's kinds (`PdfImportKind`).
/// The bytes are copied once into the module's memory by the glue.
pub fn import_pdf(&self, bytes: &[u8]) -> String {
faunosteo_core::facade::import_pdf(&self.sheet, bytes)
}
/// The same import on bytes streamed into the module's memory (`FileBytes`), consumed:
/// the file lives once, in linear memory, never as a JavaScript ArrayBuffer (R4.3a).
pub fn import_pdf_bytes(&self, bytes: FileBytes) -> String {
faunosteo_core::facade::import_pdf(&self.sheet, &bytes.data)
}
/// A rescue copy streamed into the module's memory, consumed: strict UTF-8, one BOM,
/// the value budget, then `draft.restore` without an archive (R4.3a).
pub fn restore_copy_bytes(&self, bytes: FileBytes) -> String {
faunosteo_core::facade::restore_copy(&self.sheet, bytes.data)
}
}
/// The incremental PDF export (R4.6, plan §B.1.4, OD-2): the application opens a session on
/// its `ExportInput` JSON, then alternates `next()` (the rasters the next step needs) with
/// `add_raster` or `raster_failed` per key, and closes with `finish()`. Every answer is the
/// outcome envelope of the calls; a view raster is decoded and written into the file as it
/// arrives (its bytes are copied into linear memory for the call by the glue, and freed
/// with the decode before the call returns), so the session holds the file being written
/// and nothing of the rasters. `free()` (the driver's `finally`) drops everything it holds.
#[wasm_bindgen]
pub struct ExportSession {
inner: faunosteo_core::pdf::write::session::ExportSession,
}
#[wasm_bindgen]
impl ExportSession {
/// Every check of the input, the envelope under its cap, the file opened; throws an
/// `Error` worded `<kind>: <detail>` with today's export kinds when the input is refused.
#[wasm_bindgen(constructor)]
pub fn new(input: &str) -> Result<ExportSession, JsError> {
faunosteo_core::facade::export::open(input)
.map(|inner| ExportSession { inner })
.map_err(|failure| JsError::new(&format!("{}: {}", failure.kind, failure.detail)))
}
/// `{"ok":true,"value":<ExportStep>}`: the next batch of raster requests, or `done`.
pub fn next_step(&mut self) -> String {
faunosteo_core::facade::export::next_step(&mut self.inner)
}
/// The raster of `key` (a PNG); `{"ok":true}` or a closed refusal.
pub fn add_raster(&mut self, key: &str, png: &[u8]) -> String {
faunosteo_core::facade::export::add_raster(&mut self.inner, key, png)
}
/// `key` could not be rasterised (its warning); `{"ok":true}` or a closed refusal.
pub fn raster_failed(&mut self, key: &str) -> String {
faunosteo_core::facade::export::raster_failed(&mut self.inner, key)
}
/// Closes the file: the number of parts `take_part()` then gives; throws an `Error`
/// worded `<kind>: <detail>` (`out_of_order`, `self_check_failed`).
pub fn finish(&mut self) -> Result<u32, JsError> {
faunosteo_core::facade::export::finish(&mut self.inner)
.map(|parts| u32::try_from(parts).unwrap_or(u32::MAX))
.map_err(|failure| JsError::new(&format!("{}: {}", failure.kind, failure.detail)))
}
/// The next part of the finished file, front to back, `undefined` once every part is
/// out. Each part is copied out of linear memory by the glue and freed here, so the
/// file is never held twice (`new Blob(parts)` takes them as they are).
pub fn take_part(&mut self) -> Option<Vec<u8>> {
self.inner.take_part()
}
/// `{"ok":true,"value":[<ExportWarning>…]}`, complete after `finish()`.
pub fn warnings(&self) -> String {
faunosteo_core::facade::export::warnings(&self.inner)
}
/// Bytes of the file written so far (DEV diagnostics only).
pub fn written(&self) -> u32 {
u32::try_from(self.inner.written()).unwrap_or(u32::MAX)
}
}
/// A file's bytes gathered chunk by chunk in the module's memory (R4.3a): the worker reads
/// `file.stream()` and pushes each chunk, so the only whole copy of the file is this one.
/// The capacity is reserved up front from the file size the worker announces, capped at the
/// PDF limit; a push past the announced size is refused (`false`) and the bytes dropped.
#[wasm_bindgen]
pub struct FileBytes {
data: Vec<u8>,
expected: usize,
}
#[wasm_bindgen]
impl FileBytes {
/// `expected` is the file size; above the PDF cap nothing is reserved and every push
/// is refused, so the caller's own size check stays the only one that reads a file.
#[wasm_bindgen(constructor)]
pub fn new(expected: u32) -> FileBytes {
let expected = expected as usize;
let expected = if expected > MAX_PDF_BYTES {
0
} else {
expected
};
FileBytes {
data: Vec::with_capacity(expected),
expected,
}
}
/// Appends a chunk; `false` (nothing appended) once the announced size would be passed.
pub fn push(&mut self, chunk: &[u8]) -> bool {
if self.data.len().saturating_add(chunk.len()) > self.expected {
return false;
}
self.data.extend_from_slice(chunk);
true
}
pub fn len(&self) -> u32 {
u32::try_from(self.data.len()).unwrap_or(u32::MAX)
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
}
/// R4.2e proof: the import with the OD-3 value cap off, so that a token-dense document runs
/// into the linear memory ceiling and traps (never in the module the application ships).
#[cfg(feature = "proofs")]
#[wasm_bindgen]
pub fn import_pdf_unbounded_for_test(bundle: &str, bytes: &[u8]) -> Result<String, JsError> {
use faunosteo_core::pdf::import::import_pdf;
use faunosteo_core::pdf::read::probe::ProbeLimits;
let sheet = faunosteo_core::facade::load_sheet(bundle)
.map_err(|failure| JsError::new(&format!("{}: {}", failure.kind, failure.detail)))?;
Ok(match import_pdf(&sheet, bytes, ProbeLimits::UNBOUNDED) {
Ok(_) => "ok".to_owned(),
Err(failure) => format!("{failure:?}"),
})
}
/// R4.5 proof: one export through the module from an `ExportInput` JSON and the rasters
/// as `{ "headerLogo"|"footerLogo"|"poweredBy"|"partner": base64|null, "views": [{
/// "observationId", "viewId", "png": base64 }] }`, so the wasm output can be compared to the
/// native digests and the module's size with the writer linked be measured. Never shipped:
/// the application's export goes through the R4.6 session.
#[cfg(feature = "proofs")]
#[wasm_bindgen]
pub fn export_pdf_for_test(input: &str, rasters: &str) -> Result<Vec<u8>, JsError> {
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::pdf::write::export::export_pdf;
use faunosteo_core::pdf::write::input::{ExportInput, Rasters};
use faunosteo_core::pdf::write::layout::png::base64_bytes;
let input: ExportInput = parse_json(input)
.ok()
.and_then(|v| serde_json::from_value(v).ok())
.ok_or_else(|| JsError::new("invalid input"))?;
let spec = parse_json(rasters).map_err(|e| JsError::new(&e.to_string()))?;
let slot = |key: &str| {
spec.get(key)
.and_then(|v| v.as_str())
.and_then(base64_bytes)
};
let mut set = Rasters {
header_logo: slot("headerLogo"),
footer_logo: slot("footerLogo"),
powered_by: slot("poweredBy"),
partner: slot("partner"),
views: Default::default(),
};
for view in spec
.get("views")
.and_then(|v| v.as_array())
.into_iter()
.flatten()
{
let key = (
view["observationId"].as_str().unwrap_or("").to_owned(),
view["viewId"].as_str().unwrap_or("").to_owned(),
);
if let Some(png) = view["png"].as_str().and_then(base64_bytes) {
set.views.insert(key, png);
}
}
export_pdf(input, &set)
.map(|result| result.pdf)
.map_err(|error| JsError::new(&format!("{}: {}", error.kind.as_str(), error.detail)))
}
/// R4.2e proof: the linear memory ceiling (`--max-memory`, `.cargo/config.toml`). Allocates
/// and touches `mib` MiB; past the ceiling the allocation fails and Rust aborts, a trap.
#[cfg(feature = "proofs")]
#[wasm_bindgen]
pub fn allocate_for_test(mib: u32) -> u32 {
let bytes = vec![1u8; (mib as usize) * 1024 * 1024];
std::hint::black_box(&bytes);
bytes
.iter()
.step_by(1024 * 1024)
.map(|b| u32::from(*b))
.sum()
}
/// R0 proof: on wasm32 a panic is a trap (panic = abort), reaching JavaScript as a
/// `WebAssembly.RuntimeError`; the caller re-instantiates the module.
#[cfg(feature = "proofs")]
#[wasm_bindgen]
pub fn panic_for_test() {
panic!("deliberate panic for the R0 proof");
}
/// R0 proof: exhausting the shadow stack traps instead of corrupting memory.
#[cfg(feature = "proofs")]
#[wasm_bindgen]
pub fn recurse_for_test(depth: u32) -> u32 {
recurse(depth)
}
#[cfg(feature = "proofs")]
#[inline(never)]
fn recurse(depth: u32) -> u32 {
let mut frame = [depth; 32];
if depth == 0 {
return std::hint::black_box(&frame)[0];
}
let below = recurse(depth - 1);
frame[(below as usize) % 32] ^= below;
std::hint::black_box(&frame);
below.wrapping_add(1)
}