Skip to main content

byob_protocol/
view.rs

1//! Open view payloads: something for a client to show that the protocol doesn't need to know.
2//!
3//! A [`View`] is a namespaced `kind` (`byob.plugin_card`, `<plugin>.<name>`), a schema
4//! version `v` of its `data`, the `data` itself (any JSON) and a markdown `fallback`. A client
5//! draws a kind it has a renderer for (and whose `v` it understands); any other view shows its
6//! fallback. So a newer engine, or a plugin, can put new things on a step without a protocol
7//! bump, and an older client still shows something sensible.
8//!
9//! Built-in views keep a typed struct as the `data` schema ([`ViewData`]): encode with
10//! [`View::of`], decode with [`View::get`]. Bump a kind's `V` only for changes an older
11//! renderer can't read (new optional fields don't need it); a renderer takes `v <= V`.
12//!
13//! `byob.*` kinds are byob's own.
14
15use serde::de::DeserializeOwned;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19/// Longest view kind.
20pub const MAX_VIEW_KIND_CHARS: usize = 64;
21/// Largest view `data` (its JSON).
22pub const MAX_VIEW_DATA_BYTES: usize = 256 * 1024;
23/// Longest fallback (characters).
24pub const MAX_VIEW_FALLBACK_CHARS: usize = 16 * 1024;
25/// Most views on one step.
26pub const MAX_STEP_VIEWS: usize = 16;
27
28/// Something to show, by kind; see the module docs.
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30pub struct View {
31    pub kind: String,
32    /// Schema version of `data` for this kind.
33    #[serde(default)]
34    pub v: u32,
35    #[serde(default)]
36    pub data: Value,
37    /// Markdown shown by a client that can't draw this kind.
38    #[serde(default)]
39    pub fallback: String,
40    /// A live view this is a snapshot of (13.3+): a client that can (cap
41    /// [`crate::sites::CAP_VIEW_SITES`]) shows the live one and sends its events to the owner.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub owner: Option<crate::ViewRef>,
44}
45
46/// A typed view: the struct is the `data` schema of kind [`ViewData::KIND`].
47pub trait ViewData: Serialize + DeserializeOwned {
48    const KIND: &'static str;
49    /// Current schema version.
50    const V: u32;
51    /// What a client without a renderer shows.
52    fn fallback(&self) -> String;
53}
54
55/// A view kind is ASCII lowercase letters, digits, `_`, `-`, separated by dots, and starts
56/// with a namespace: `byob.plugin_card`, `sheets.grid`.
57pub fn kind_ok(kind: &str) -> bool {
58    (3..=MAX_VIEW_KIND_CHARS).contains(&kind.len())
59        && kind.contains('.')
60        && kind.split('.').all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-')))
61}
62
63impl View {
64    /// A typed view (unchecked: built-in data is small).
65    pub fn of<T: ViewData>(data: &T) -> Self {
66        Self { kind: T::KIND.to_owned(), v: T::V, data: serde_json::to_value(data).unwrap_or(Value::Null), fallback: data.fallback(), owner: None }
67    }
68
69    /// The typed data, if this view is a `T` this build can read.
70    pub fn get<T: ViewData>(&self) -> Option<T> {
71        (self.kind == T::KIND && self.v <= T::V).then(|| serde_json::from_value(self.data.clone()).ok()).flatten()
72    }
73
74    /// Check an untrusted view's kind and sizes.
75    pub fn check(&self) -> Result<(), String> {
76        if !kind_ok(&self.kind) {
77            return Err(format!("bad view kind {:?}", self.kind.chars().take(MAX_VIEW_KIND_CHARS).collect::<String>()));
78        }
79        if self.fallback.chars().count() > MAX_VIEW_FALLBACK_CHARS {
80            return Err(format!("a view's fallback can be at most {MAX_VIEW_FALLBACK_CHARS} characters"));
81        }
82        let size = serde_json::to_string(&self.data).map_or(usize::MAX, |s| s.len());
83        if size > MAX_VIEW_DATA_BYTES {
84            return Err(format!("view data too large ({size} bytes, at most {MAX_VIEW_DATA_BYTES})"));
85        }
86        Ok(())
87    }
88
89    /// The fallback, cut to [`MAX_VIEW_FALLBACK_CHARS`] (for clients drawing untrusted views).
90    pub fn fallback_bounded(&self) -> &str {
91        match self.fallback.char_indices().nth(MAX_VIEW_FALLBACK_CHARS) {
92            Some((at, _)) => self.fallback.get(..at).unwrap_or_default(),
93            None => &self.fallback,
94        }
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[derive(Debug, PartialEq, Serialize, Deserialize)]
103    struct Gauge {
104        value: u32,
105        #[serde(default)]
106        label: String,
107    }
108
109    impl ViewData for Gauge {
110        const KIND: &'static str = "test.gauge";
111        const V: u32 = 2;
112        fn fallback(&self) -> String {
113            format!("**{}**: {}", self.label, self.value)
114        }
115    }
116
117    #[test]
118    fn typed_views_round_trip_and_other_kinds_or_versions_dont_decode() {
119        let g = Gauge { value: 3, label: "load".into() };
120        let v = View::of(&g);
121        assert_eq!((v.kind.as_str(), v.v, v.fallback.as_str()), ("test.gauge", 2, "**load**: 3"));
122        assert!(v.check().is_ok());
123        let back: View = serde_json::from_str(&serde_json::to_string(&v).unwrap()).unwrap();
124        assert_eq!(back.get::<Gauge>(), Some(g));
125        // A newer schema than this build knows: fallback, not a misread.
126        assert_eq!(View { v: 3, ..v.clone() }.get::<Gauge>(), None);
127        assert_eq!(View { kind: "test.other".into(), ..v.clone() }.get::<Gauge>(), None);
128        // Data that doesn't fit the schema doesn't decode.
129        assert_eq!(View { data: serde_json::json!({"value": "x"}), ..v }.get::<Gauge>(), None);
130        // A minimal view from anyone parses.
131        let min: View = serde_json::from_str(r#"{"kind":"x.y"}"#).unwrap();
132        assert_eq!((min.v, min.data.is_null(), min.fallback.is_empty()), (0, true, true));
133    }
134
135    #[test]
136    fn kinds_and_sizes_are_checked() {
137        for ok in ["byob.plugin_card", "sheets.grid", "a.b-c.d_2"] {
138            assert!(kind_ok(ok), "{ok}");
139        }
140        for bad in ["", "plain", ".x", "x.", "a..b", "Byob.card", "a.b c", &format!("a.{}", "x".repeat(MAX_VIEW_KIND_CHARS))] {
141            assert!(!kind_ok(bad), "{bad}");
142        }
143        let v = |data: Value, fallback: String| View { kind: "x.y".into(), v: 0, data, fallback, owner: None };
144        assert!(v(Value::String("x".repeat(MAX_VIEW_DATA_BYTES)), String::new()).check().is_err());
145        let long = "é".repeat(MAX_VIEW_FALLBACK_CHARS + 5);
146        let big = v(Value::Null, long);
147        assert!(big.check().is_err());
148        assert_eq!(big.fallback_bounded().chars().count(), MAX_VIEW_FALLBACK_CHARS);
149    }
150}