feat(workspace): R2.4 core runtime — lazy load, poison on trap, offline re-instantiation, per-generation sheet handles

packages/core-wasm: browser-safe CoreRuntime (synchronous calls once ready;
a WebAssembly.RuntimeError poisons the instance, the call answers internal,
a fresh instance comes from the kept compiled module and a glue record
imported in advance; at most 3 recoveries per page; retry after a load
failure), SheetSession (handle rebuilt per instance generation, never
called on a dropped one; invalid_sheet without poisoning), Node source.
crates/wasm: SheetHandle (sheet held in the module memory). Two builds:
pkg/ shipped without trap exports (checked), pkg-proofs/ for the trap
tests; BUILD_STAMP (hash of the Rust sources) refused when missing or
stale by the vitest global setup instead of skipping. Failure envelope
carries a numeric found version; compact JS-number output.
This commit is contained in:
bchanot committed 2026-10-14 00:12:04 +02:00
1 parent 22fea8736d
commit 343d6f4c1f
22 files changed
+783 -180

No files matched your search

+90 -32
View File
@@ -1,18 +1,39 @@
//! The call surface the wasm facade and the tools expose (review III.3): one operation
//! name, one JSON text in, one JSON text out, closed outcome kinds, never a panic on
//! content. The envelope is `{"ok":true,"value":…}` or `{"ok":false,"kind":…,"detail":…}`.
//! content. The envelope is `{"ok":true,"value":…}` or `{"ok":false,"kind":…,"detail":…}`,
//! plus `"found":<number>` when a failure names a document version.
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use serde_json::{Map, Value};
use crate::domain::js::parse_json;
use crate::domain::sheet::{BundledSheetData, LoadError, LoadedSheet};
use crate::domain::{ReportZone, SheetRef};
use crate::json::pretty_js_round_trip;
use crate::json::{pretty_js_round_trip, to_js_compact};
/// Runs the operation `op` on the JSON text `input` and returns the outcome envelope.
///
/// Operations of R0: `core_version`, `pretty_json` (JavaScript pretty form of any JSON
/// text), `sheet_ref` and `report_zone` (parse and re-emit a contract type).
/// A closed failure of an operation.
#[derive(Debug, Clone, PartialEq)]
pub struct Failure {
pub kind: &'static str,
pub detail: String,
/// The document version a reader refused, as the JavaScript number it was.
pub found: Option<f64>,
}
impl Failure {
pub fn new(kind: &'static str, detail: impl std::fmt::Display) -> Self {
Self {
kind,
detail: detail.to_string(),
found: None,
}
}
}
type Outcome = Result<Value, Failure>;
/// Runs the free operation `op` on the JSON text `input` and returns the outcome envelope.
pub fn call(op: &str, input: &str) -> String {
let outcome = match op {
"core_version" => Ok(Value::String(crate::CORE_VERSION.to_owned())),
@@ -21,47 +42,72 @@ pub fn call(op: &str, input: &str) -> String {
.map_err(|error| Failure::new("invalid_json", error)),
"sheet_ref" => echo::<SheetRef>(input),
"report_zone" => echo::<ReportZone>(input),
_ => Err(Failure::new(
"unknown_op",
format!("no operation named {op}"),
)),
_ => Err(unknown(op)),
};
render(outcome)
}
fn echo<T: DeserializeOwned + Serialize>(input: &str) -> Result<Value, Failure> {
let parsed: T =
serde_json::from_str(input).map_err(|error| Failure::new("invalid_shape", error))?;
serde_json::to_value(parsed).map_err(|error| Failure::new("internal", error))
/// Reads the bundled sheet payload (`BundledSheetData` JSON) into a loaded, indexed sheet.
pub fn load_sheet(bundle: &str) -> Result<LoadedSheet, Failure> {
let data: BundledSheetData = parse_input(bundle)?;
LoadedSheet::from_bundle(data).map_err(|error| match error {
LoadError::Shape(error) => Failure::new("invalid_sheet", error),
LoadError::NoMainView => Failure::new("invalid_sheet", "the sheet has no main view"),
})
}
struct Failure {
kind: &'static str,
detail: String,
/// Runs the operation `op` that needs the session's sheet.
pub fn call_with_sheet(sheet: &LoadedSheet, op: &str, _input: &str) -> String {
let outcome = match op {
"sheet.ref" => to_value(&sheet.reference),
_ => Err(unknown(op)),
};
render(outcome)
}
impl Failure {
fn new(kind: &'static str, detail: impl std::fmt::Display) -> Self {
Self {
kind,
detail: detail.to_string(),
fn unknown(op: &str) -> Failure {
Failure::new("unknown_op", format!("no operation named {op}"))
}
/// Parses the JSON text of an operation input into its contract type.
pub(crate) fn parse_input<T: DeserializeOwned>(input: &str) -> Result<T, Failure> {
let value = parse_json(input).map_err(|error| Failure::new("invalid_json", error))?;
serde_json::from_value(value).map_err(|error| Failure::new("invalid_shape", error))
}
pub(crate) fn to_value<T: Serialize>(value: &T) -> Outcome {
serde_json::to_value(value).map_err(|error| Failure::new("internal", error))
}
fn echo<T: DeserializeOwned + Serialize>(input: &str) -> Outcome {
let parsed: T = parse_input(input)?;
to_value(&parsed)
}
fn render(outcome: Outcome) -> String {
let mut envelope = Map::new();
match outcome {
Ok(value) => {
envelope.insert("ok".to_owned(), Value::Bool(true));
envelope.insert("value".to_owned(), value);
}
Err(failure) => {
envelope.insert("ok".to_owned(), Value::Bool(false));
envelope.insert("kind".to_owned(), Value::from(failure.kind));
envelope.insert("detail".to_owned(), Value::from(failure.detail));
if let Some(found) = failure.found.and_then(serde_json::Number::from_f64) {
envelope.insert("found".to_owned(), Value::Number(found));
}
}
}
}
fn render(outcome: Result<Value, Failure>) -> String {
let envelope = match outcome {
Ok(value) => json!({ "ok": true, "value": value }),
Err(failure) => json!({ "ok": false, "kind": failure.kind, "detail": failure.detail }),
};
serde_json::to_string(&envelope).unwrap_or_else(|_| {
to_js_compact(&Value::Object(envelope)).unwrap_or_else(|_| {
r#"{"ok":false,"kind":"internal","detail":"outcome serialisation failed"}"#.to_owned()
})
}
#[cfg(test)]
mod tests {
use super::call;
use super::{Failure, call, render};
#[test]
fn unknown_operation_is_a_closed_kind() {
@@ -87,4 +133,16 @@ mod tests {
r#"{"ok":true,"value":{"annotationId":"a","viewId":"v","side":"left"}}"#
);
}
#[test]
fn a_found_version_is_printed_as_a_javascript_number() {
let failure = Failure {
found: Some(4.0),
..Failure::new("incompatible_version", "v4")
};
assert_eq!(
render(Err(failure)),
r#"{"ok":false,"kind":"incompatible_version","detail":"v4","found":4}"#
);
}
}