Skip to main content

toddstack_frontend_engine/
effect.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6/// How a [`Effect::Navigate`] changes the history.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum NavigateOp {
10    Push,
11    Replace,
12    Back,
13}
14
15/// The app-defined effect type of an app that needs none.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub enum NoEffect {}
18
19/// A capability the shell implements. The built-in set is small and universal; anything else
20/// (haptics, sound, share sheets, push registration, review prompts) is the app's own effect type
21/// `X`, carried by [`Effect::App`] and serialized flat next to the built-ins, so a shell
22/// matches on one key: `{"id":3,"Http":{...}}` or `{"id":4,"Vibrate":{"ms":20}}`.
23///
24/// Unit-like variants are empty structs so they stay JSON objects and flatten next to the request id.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub enum Effect<X = NoEffect> {
27    Http {
28        method: String,
29        path: String,
30        #[serde(default, skip_serializing_if = "Option::is_none")]
31        body: Option<Value>,
32        /// Attach the session's credential; the shell owns the token.
33        #[serde(default)]
34        auth: bool,
35        /// Extra request headers the shell adds as given (for example the core's version stamp).
36        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
37        headers: BTreeMap<String, String>,
38    },
39    /// Resolves with `{"fired":true}` after `after_ms`.
40    Timer {
41        after_ms: u64,
42    },
43    CancelTimer {
44        timer_id: u64,
45    },
46    /// Set when `value` is present, otherwise read (resolves with the value or null).
47    Store {
48        key: String,
49        #[serde(default, skip_serializing_if = "Option::is_none")]
50        value: Option<Value>,
51    },
52    /// Like `Store` for secrets: Keychain / Keystore on native, never plain browser storage.
53    Secure {
54        key: String,
55        #[serde(default, skip_serializing_if = "Option::is_none")]
56        value: Option<String>,
57    },
58    /// Resolves with `n` random bytes as a hex string.
59    Random {
60        n: u32,
61    },
62    /// Change the address / screen stack.
63    Navigate {
64        op: NavigateOp,
65        #[serde(default)]
66        url: String,
67    },
68    /// Open the sign-in page in a system browser session. Resolves with the callback URL.
69    OpenAuthBrowser {
70        url: String,
71    },
72    /// Web only: reload the page to fetch the latest bundle.
73    Reload {},
74    /// The shell fetches the named blob and calls `provide_blob(name, bytes)`.
75    LoadBlob {
76        name: String,
77    },
78    /// A timing for telemetry. Fire and forget: the shell reports a span of `ms` named `name`.
79    Span {
80        name: String,
81        ms: u64,
82        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
83        tags: BTreeMap<String, String>,
84    },
85    /// Fire and forget.
86    Log {
87        level: String,
88        msg: String,
89    },
90    /// Fire and forget: send an error to the shell's error tracker.
91    Report {
92        error: String,
93    },
94    /// An effect the app defined.
95    #[serde(untagged)]
96    App(X),
97}
98
99impl<X> Effect<X> {
100    /// An `Http` effect with no body, no credential and no extra headers.
101    #[must_use]
102    pub fn http(method: &str, path: &str) -> Self {
103        Self::Http {
104            method: method.to_owned(),
105            path: path.to_owned(),
106            body: None,
107            auth: false,
108            headers: BTreeMap::new(),
109        }
110    }
111}
112
113/// The variant names of the built-in effects. An app effect serialized under one of these reads
114/// back as the built-in (the untagged [`Effect::App`] is tried last), so app effect names must
115/// avoid them. [`Runtime`](crate::Runtime) checks this in debug builds and tests.
116pub const BUILT_IN_EFFECT_NAMES: [&str; 13] = [
117    "Http",
118    "Timer",
119    "CancelTimer",
120    "Store",
121    "Secure",
122    "Random",
123    "Navigate",
124    "OpenAuthBrowser",
125    "Reload",
126    "LoadBlob",
127    "Span",
128    "Log",
129    "Report",
130];
131
132/// The built-in name an app effect collides with, if any.
133#[must_use]
134pub fn builtin_collision<X: Serialize>(effect: &X) -> Option<String> {
135    let name: String = match serde_json::to_value(effect).ok()? {
136        Value::String(name) => name,
137        Value::Object(map) if map.len() == 1 => map.keys().next()?.clone(),
138        _ => return None,
139    };
140    BUILT_IN_EFFECT_NAMES
141        .contains(&name.as_str())
142        .then_some(name)
143}
144
145/// An effect with its request id, serialized flat: `{"id":3,"Http":{...}}`.
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub struct EffectReq<X = NoEffect> {
148    pub id: u64,
149    #[serde(flatten)]
150    pub effect: Effect<X>,
151}
152
153/// The `ok` payload of an answered [`Effect::Http`]. `sent` and `recv` are local wall-clock ms.
154#[derive(Debug, Clone, PartialEq, Deserialize)]
155pub struct HttpReply {
156    pub status: u16,
157    #[serde(default)]
158    pub body: Value,
159    #[serde(default)]
160    pub sent: u64,
161    #[serde(default)]
162    pub recv: u64,
163}
164
165#[cfg(test)]
166mod tests {
167    use serde_json::json;
168
169    use super::*;
170
171    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172    enum Mine {
173        Vibrate { ms: u32 },
174        Beep,
175    }
176
177    #[test]
178    fn built_in_and_app_effects_serialize_flat_next_to_the_id() {
179        let built_in: EffectReq<Mine> = EffectReq {
180            id: 3,
181            effect: Effect::http("GET", "/x"),
182        };
183        let mine: EffectReq<Mine> = EffectReq {
184            id: 4,
185            effect: Effect::App(Mine::Vibrate { ms: 20 }),
186        };
187        assert_eq!(
188            json!({"id": 3, "Http": {"method": "GET", "path": "/x", "auth": false}}),
189            serde_json::to_value(&built_in).unwrap()
190        );
191        assert_eq!(
192            json!({"id": 4, "Vibrate": {"ms": 20}}),
193            serde_json::to_value(&mine).unwrap()
194        );
195    }
196
197    #[test]
198    fn app_effects_named_like_a_built_in_are_detected() {
199        #[derive(Serialize)]
200        enum Clash {
201            Timer { after_ms: u64 },
202            Log,
203        }
204        assert_eq!(
205            Some("Timer".to_owned()),
206            builtin_collision(&Clash::Timer { after_ms: 1 })
207        );
208        assert_eq!(Some("Log".to_owned()), builtin_collision(&Clash::Log));
209        assert_eq!(None, builtin_collision(&Mine::Beep));
210        assert_eq!(None, builtin_collision(&Mine::Vibrate { ms: 1 }));
211    }
212
213    #[test]
214    fn a_flat_effect_reads_back_to_the_same_variant() {
215        let built_in: EffectReq<Mine> =
216            serde_json::from_value(json!({"id": 1, "Timer": {"after_ms": 5}})).unwrap();
217        let mine: EffectReq<Mine> = serde_json::from_value(json!({"id": 2, "Beep": null})).unwrap();
218        assert_eq!(Effect::Timer { after_ms: 5 }, built_in.effect);
219        assert_eq!(Effect::App(Mine::Beep), mine.effect);
220    }
221}