Skip to main content

vlo_kernel/
api.rs

1//! String-in / string-out surface: exactly what crosses the wasm boundary.
2//!
3//! `kernel-wasm` is a one-line shim over this module and the golden fixtures exercise
4//! it directly, so the native tests and the wasm build can never drift apart.
5
6use serde::Serialize;
7use serde_json::Value;
8use vlo_types::{
9    DeriveIdsInput, KernelError, KernelResult, KernelVersion, PlanRetryInput, PrepareEventInput,
10    ReduceStepInput, RefoldCheckInput, StateHashInput, StateHashOutput, ValidateEventOutput,
11    PROTOCOL_VERSION,
12};
13
14use crate::error::{code, KResult};
15use crate::{hash, ids, prepare, reduce, refold, retry, validate};
16
17/// Capabilities the host may branch on. Additive only.
18pub const FEATURES: &[&str] = &["canonical_json_v1", "state_hash_v1", "refold_v1"];
19
20/// The [`KernelVersion`] of this build: crate version, [`PROTOCOL_VERSION`], [`FEATURES`].
21pub fn version() -> KernelVersion {
22    KernelVersion {
23        version: env!("CARGO_PKG_VERSION").to_string(),
24        protocol: PROTOCOL_VERSION,
25        features: FEATURES.iter().map(|f| f.to_string()).collect(),
26    }
27}
28
29/// `kernel_version` export. Value: [`KernelVersion`].
30pub fn version_json() -> String {
31    render(Ok(version()))
32}
33
34/// `validate_event` export. Input: [`EventInput`](vlo_types::EventInput); value: [`ValidateEventOutput`].
35pub fn validate_event_json(input: &str) -> String {
36    render(parse::<vlo_types::EventInput>(input).and_then(|event| {
37        validate::validate_event(&event).map(|normalized| ValidateEventOutput { normalized })
38    }))
39}
40
41/// `prepare_event` export. Input: [`PrepareEventInput`]; value: [`Prepared`](vlo_types::Prepared).
42pub fn prepare_event_json(input: &str) -> String {
43    render(parse::<PrepareEventInput>(input).and_then(|i| prepare::prepare_event(&i)))
44}
45
46/// `reduce_step` export. Input: [`ReduceStepInput`]; value: [`Transition`](vlo_types::Transition).
47pub fn reduce_step_json(input: &str) -> String {
48    render(parse::<ReduceStepInput>(input).and_then(|i| reduce::reduce_step(&i)))
49}
50
51/// `compute_state_hash` export. Input: [`StateHashInput`]; value: [`StateHashOutput`].
52pub fn compute_state_hash_json(input: &str) -> String {
53    render(parse::<StateHashInput>(input).and_then(|i| {
54        hash::state_hash(&i.kernel_state, &i.state).map(|hash| StateHashOutput { hash })
55    }))
56}
57
58/// `plan_retry` export. Input: [`PlanRetryInput`]; value: [`RetryPlan`](vlo_types::RetryPlan).
59pub fn plan_retry_json(input: &str) -> String {
60    render(parse::<PlanRetryInput>(input).and_then(|i| retry::plan_retry(&i)))
61}
62
63/// `refold_check` export. Input: [`RefoldCheckInput`]; value: [`RefoldCheckOutput`](vlo_types::RefoldCheckOutput).
64pub fn refold_check_json(input: &str) -> String {
65    render(parse::<RefoldCheckInput>(input).map(|i| refold::refold_check(&i)))
66}
67
68/// `derive_ids` export. Input: [`DeriveIdsInput`]; value: [`DeriveIdsOutput`](vlo_types::DeriveIdsOutput).
69pub fn derive_ids_json(input: &str) -> String {
70    render(parse::<DeriveIdsInput>(input).map(|i| ids::derive_ids(&i)))
71}
72
73fn parse<T: serde::de::DeserializeOwned>(input: &str) -> KResult<T> {
74    serde_json::from_str(input).map_err(|e| crate::error::err(code::MALFORMED_JSON, e.to_string()))
75}
76
77/// Serialization of a `KernelResult` cannot fail for our own types; if it somehow did,
78/// fall back to a hand-written error object rather than panicking in wasm.
79fn render<T: Serialize>(result: KResult<T>) -> String {
80    let result = match result {
81        Ok(value) => KernelResult::ok(value),
82        Err(error) => KernelResult::err(error),
83    };
84    serde_json::to_string(&result).unwrap_or_else(|e| {
85        let fallback: KernelResult<Value> = KernelResult::err(KernelError {
86            code: code::MALFORMED_JSON.to_string(),
87            message: format!("kernel output is not serialisable: {e}"),
88            seq: None,
89            step_id: None,
90        });
91        serde_json::to_string(&fallback)
92            .unwrap_or_else(|_| r#"{"ok":false,"error":{"code":"malformed_json","message":"kernel output is not serialisable"}}"#.to_string())
93    })
94}