Files
faunosteo/crates/core/src/facade.rs
T

91 lines
2.9 KiB
Rust

//! 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":…}`.
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use crate::domain::{ReportZone, SheetRef};
use crate::json::pretty_js_round_trip;
/// 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).
pub fn call(op: &str, input: &str) -> String {
let outcome = match op {
"core_version" => Ok(Value::String(crate::CORE_VERSION.to_owned())),
"pretty_json" => pretty_js_round_trip(input)
.map(Value::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}"),
)),
};
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))
}
struct Failure {
kind: &'static str,
detail: String,
}
impl Failure {
fn new(kind: &'static str, detail: impl std::fmt::Display) -> Self {
Self {
kind,
detail: detail.to_string(),
}
}
}
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(|_| {
r#"{"ok":false,"kind":"internal","detail":"outcome serialisation failed"}"#.to_owned()
})
}
#[cfg(test)]
mod tests {
use super::call;
#[test]
fn unknown_operation_is_a_closed_kind() {
let outcome = call("nope", "{}");
assert!(outcome.contains(r#""ok":false"#));
assert!(outcome.contains(r#""kind":"unknown_op""#));
}
#[test]
fn invalid_json_never_panics() {
let outcome = call("pretty_json", "{ not json");
assert!(outcome.contains(r#""kind":"invalid_json""#));
}
#[test]
fn report_zone_round_trip_keeps_the_declared_order() {
let outcome = call(
"report_zone",
r#"{"viewId":"v","side":"left","annotationId":"a"}"#,
);
assert_eq!(
outcome,
r#"{"ok":true,"value":{"annotationId":"a","viewId":"v","side":"left"}}"#
);
}
}