Skip to main content

toddstack_frontend_engine/
runtime.rs

1use std::collections::HashMap;
2use std::hash::{DefaultHasher, Hash, Hasher};
3
4use serde_json::{Value, json};
5
6use crate::app::{App, Ctx, Pointer};
7use crate::effect::{Effect, EffectReq, builtin_collision};
8use crate::wire::{Input, Verb};
9
10/// The bridge message format (shell to core): the boot message carries `"v"` and every response
11/// echoes it. Not an app's API contract: apps version that themselves.
12pub const BRIDGE_PROTOCOL: u64 = 1;
13
14/// The surface every bridge (`UniFFI`, `wasm-bindgen`, a test harness) wraps. Bytes in, bytes out.
15pub trait Bridge {
16    /// One protocol line in, one response out.
17    fn dispatch(&mut self, input: &[u8]) -> Vec<u8>;
18    /// Typed fast path, no JSON. Returns a bitmask: bit 0 = dirty views queued, bit 1 = effects pending.
19    fn pointer(&mut self, phase: u8, x: f32, y: f32, at_ms: f64) -> u32;
20    /// The JSON of one view key (`null` when unknown).
21    fn view(&self, key: &str) -> Vec<u8>;
22    /// Large binary input off the JSON path, named by the app.
23    fn provide_blob(&mut self, name: &str, bytes: &[u8]) -> Vec<u8>;
24}
25
26/// Drives an [`App`] with the protocol. Construct with [`Runtime::new`].
27pub struct Runtime<A: App> {
28    app: A,
29    ctx: Ctx<A::Effect>,
30    /// Hash of the last bytes reported dirty per view key: an unchanged view is never sent again.
31    sent: HashMap<String, u64>,
32}
33
34impl<A: App> Runtime<A> {
35    /// Boot facts from the shell (JSON). Bad JSON boots with `null`. Boot effects stay queued
36    /// until the next response.
37    #[must_use]
38    pub fn new(boot: &[u8]) -> Self {
39        let boot: Value = serde_json::from_slice(boot).unwrap_or(Value::Null);
40        let mut ctx: Ctx<A::Effect> = Ctx {
41            at: boot.get("at").and_then(Value::as_u64).unwrap_or(0),
42            ..Ctx::default()
43        };
44        let app: A = A::boot(&boot, &mut ctx);
45        Self {
46            app,
47            ctx,
48            sent: HashMap::new(),
49        }
50    }
51
52    fn flush(&mut self) -> Value {
53        let marked = std::mem::take(&mut self.ctx.dirty);
54        let mut dirty: Vec<String> = Vec::with_capacity(marked.len());
55        for key in marked {
56            let mut hasher: DefaultHasher = DefaultHasher::new();
57            serde_json::to_vec(&self.app.view(&key))
58                .unwrap_or_default()
59                .hash(&mut hasher);
60            let hash: u64 = hasher.finish();
61            if self.sent.insert(key.clone(), hash) != Some(hash) {
62                dirty.push(key);
63            }
64        }
65        let queued: Vec<EffectReq<A::Effect>> = std::mem::take(&mut self.ctx.effects);
66        for req in &queued {
67            if let Effect::App(app_effect) = &req.effect {
68                debug_assert!(
69                    builtin_collision(app_effect).is_none(),
70                    "app effect named like a built-in ({:?}); it would read back as the built-in",
71                    builtin_collision(app_effect),
72                );
73            }
74        }
75        match serde_json::to_value(queued) {
76            Ok(effects) => json!({"dirty": dirty, "effects": effects}),
77            Err(e) => json!({"error": format!("effects not serializable: {e}")}),
78        }
79    }
80
81    fn handle(&mut self, verb: Verb) -> Value {
82        match verb {
83            Verb::Act(value) => match serde_json::from_value::<A::Action>(value) {
84                Ok(action) => {
85                    self.app.update(action, &mut self.ctx);
86                    self.flush()
87                }
88                Err(e) => json!({"error": format!("bad act: {e}")}),
89            },
90            Verb::Resolve(r) => {
91                let result: Result<Value, String> = match (r.ok, r.err) {
92                    (_, Some(err)) => Err(err),
93                    (ok, None) => Ok(ok.unwrap_or(Value::Null)),
94                };
95                self.app.resolve(r.id, result, &mut self.ctx);
96                self.flush()
97            }
98            Verb::Pointer(p) => {
99                let pointer: Pointer = Pointer {
100                    phase: p.phase,
101                    x: p.x,
102                    y: p.y,
103                    at_ms: self.ctx.at,
104                };
105                self.app.pointer(pointer, &mut self.ctx);
106                self.flush()
107            }
108            Verb::View(key) => json!({"view": key, "json": self.app.view(&key)}),
109            Verb::Introspect {} => {
110                let screen: String = self.app.screen();
111                let actions: Vec<Value> = self
112                    .app
113                    .actions()
114                    .into_iter()
115                    .map(|a| json!({"name": a.name, "schema": a.schema}))
116                    .collect();
117                json!({"screen": screen, "view": self.app.view(&screen), "actions": actions})
118            }
119            Verb::Flush {} => self.flush(),
120        }
121    }
122}
123
124fn versioned(mut out: Value) -> Value {
125    out["v"] = json!(BRIDGE_PROTOCOL);
126    out
127}
128
129impl<A: App> Bridge for Runtime<A> {
130    fn dispatch(&mut self, input: &[u8]) -> Vec<u8> {
131        let out: Value = match serde_json::from_slice::<Input>(input) {
132            Ok(parsed) => {
133                if let Some(at) = parsed.at {
134                    self.ctx.at = at;
135                }
136                self.handle(parsed.verb)
137            }
138            Err(e) => json!({"error": format!("bad input: {e}")}),
139        };
140        serde_json::to_vec(&versioned(out)).unwrap_or_default()
141    }
142
143    #[expect(
144        clippy::cast_possible_truncation,
145        clippy::cast_sign_loss,
146        reason = "a millisecond clock reading, clamped non-negative; f64 holds it exactly"
147    )]
148    fn pointer(&mut self, phase: u8, x: f32, y: f32, at_ms: f64) -> u32 {
149        let at: u64 = at_ms.max(0.0) as u64;
150        self.ctx.at = at;
151        self.app.pointer(
152            Pointer {
153                phase,
154                x,
155                y,
156                at_ms: at,
157            },
158            &mut self.ctx,
159        );
160        u32::from(!self.ctx.dirty.is_empty()) | (u32::from(!self.ctx.effects.is_empty()) << 1)
161    }
162
163    fn view(&self, key: &str) -> Vec<u8> {
164        serde_json::to_vec(&self.app.view(key)).unwrap_or_default()
165    }
166
167    fn provide_blob(&mut self, name: &str, bytes: &[u8]) -> Vec<u8> {
168        self.app.blob(name, bytes, &mut self.ctx);
169        serde_json::to_vec(&versioned(self.flush())).unwrap_or_default()
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use serde::{Serialize, Serializer};
176
177    use super::*;
178
179    struct Unserializable;
180
181    impl Serialize for Unserializable {
182        fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
183            Err(serde::ser::Error::custom("nope"))
184        }
185    }
186
187    struct Bad;
188
189    impl App for Bad {
190        type Action = String;
191        type Effect = Unserializable;
192
193        fn boot(_: &Value, _: &mut Ctx<Unserializable>) -> Self {
194            Self
195        }
196        fn update(&mut self, _: String, ctx: &mut Ctx<Unserializable>) {
197            ctx.emit_app(Unserializable);
198        }
199        fn resolve(&mut self, _: u64, _: Result<Value, String>, _: &mut Ctx<Unserializable>) {}
200        fn view(&self, _: &str) -> Option<Value> {
201            None
202        }
203        fn screen(&self) -> String {
204            String::new()
205        }
206        fn actions(&self) -> Vec<crate::app::ActionSpec> {
207            Vec::new()
208        }
209    }
210
211    #[test]
212    fn an_unserializable_effect_is_an_error_frame_not_dropped() {
213        let mut rt: Runtime<Bad> = Runtime::new(b"{}");
214        let out: Value = serde_json::from_slice(&rt.dispatch(br#"{"act":"go"}"#)).unwrap();
215        let error: &str = out["error"].as_str().unwrap();
216        assert!(error.contains("effects not serializable"), "{out}");
217        assert!(out.get("effects").is_none());
218    }
219}