1use serde::{Deserialize, Serialize};
21use serde_json::{Map, Value};
22
23use crate::tree::{Event, Node, Patch};
24
25pub const CAP_VIEW_SITES: &str = "view_sites";
28
29pub const MAX_VIEWS: usize = 16;
31pub const MAX_VIEW_ID_CHARS: usize = 48;
33pub const MAX_VIEW_KEY_CHARS: usize = 128;
35pub const MAX_EVENT_BYTES: usize = 256 * 1024;
37pub const MAX_TITLE_CHARS: usize = 80;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Site {
44 Pane,
46 Settings,
48 Status,
51 Card,
53 Artifact,
57 #[serde(other)]
59 Other,
60}
61
62impl Site {
63 pub const ALL: [Site; 5] = [Site::Pane, Site::Settings, Site::Status, Site::Card, Site::Artifact];
64
65 pub fn label(self) -> &'static str {
66 match self {
67 Self::Pane => "pane",
68 Self::Settings => "settings",
69 Self::Status => "status",
70 Self::Card => "card",
71 Self::Artifact => "artifact",
72 Self::Other => "other",
73 }
74 }
75
76 pub fn parse(s: &str) -> Option<Self> {
77 Self::ALL.into_iter().find(|x| x.label() == s)
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct ViewDecl {
84 pub id: String,
86 pub site: Site,
87 #[serde(default)]
88 pub title: String,
89 #[serde(default, skip_serializing_if = "String::is_empty")]
91 pub icon: String,
92 #[serde(default, skip_serializing_if = "String::is_empty")]
95 pub html: String,
96}
97
98#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
100pub struct ViewRef {
101 pub plugin: String,
102 pub view: String,
104 #[serde(default, skip_serializing_if = "String::is_empty")]
106 pub key: String,
107}
108
109impl ViewRef {
110 pub fn new(plugin: impl Into<String>, view: impl Into<String>, key: impl Into<String>) -> Self {
111 Self { plugin: plugin.into(), view: view.into(), key: key.into() }
112 }
113
114 pub fn check(&self) -> Result<(), String> {
116 if !byob_types::config::plugin_id_ok(&self.plugin) {
117 return Err(format!("{:?} isn't a plugin id", self.plugin.chars().take(60).collect::<String>()));
118 }
119 if !view_id_ok(&self.view) {
120 return Err(format!("{:?} isn't a view id", self.view.chars().take(60).collect::<String>()));
121 }
122 if self.key.chars().count() > MAX_VIEW_KEY_CHARS {
123 return Err(format!("a view key can be at most {MAX_VIEW_KEY_CHARS} characters"));
124 }
125 Ok(())
126 }
127}
128
129pub fn artifact_key(id: &str, version: u32) -> String {
131 format!("{id}@{version}")
132}
133
134pub fn parse_artifact_key(key: &str) -> Option<(&str, u32)> {
136 let (id, v) = key.rsplit_once('@')?;
137 let v: u32 = v.parse().ok()?;
138 (crate::artifact::valid_id(id) && v > 0).then_some((id, v))
139}
140
141pub fn view_id_ok(id: &str) -> bool {
143 (1..=MAX_VIEW_ID_CHARS).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'))
144}
145
146#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
153pub struct LiveView {
154 pub view: ViewRef,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub tree: Option<Node>,
157 #[serde(default, skip_serializing_if = "Vec::is_empty")]
158 pub patch: Vec<Patch>,
159 #[serde(default, skip_serializing_if = "Map::is_empty")]
160 pub values: Map<String, Value>,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub error: Option<String>,
163 #[serde(default, skip_serializing_if = "Vec::is_empty")]
164 pub faults: Vec<String>,
165 #[serde(default, skip_serializing_if = "is_false")]
166 pub reset: bool,
167}
168
169fn is_false(b: &bool) -> bool {
170 !*b
171}
172
173pub(crate) fn check_sizes(msg: &crate::ClientMsg) -> Result<(), String> {
175 use crate::ClientMsg;
176 match msg {
177 ClientMsg::OpenView { view } | ClientMsg::CloseView { view } => view.check(),
178 ClientMsg::ViewEvent { view, event } => {
179 view.check()?;
180 check_event(event)
181 }
182 _ => Ok(()),
183 }
184}
185
186fn check_event(e: &Event) -> Result<(), String> {
187 if e.action.chars().count() > crate::tree::MAX_TEXT_CHARS {
188 return Err("the event's action is too long".into());
189 }
190 if e.values.len() > crate::tree::MAX_VALUES {
191 return Err(format!("an event carries at most {} values", crate::tree::MAX_VALUES));
192 }
193 let size = serde_json::to_string(e).map_or(usize::MAX, |s| s.len());
194 if size > MAX_EVENT_BYTES {
195 return Err(format!("event too large ({size} bytes, at most {MAX_EVENT_BYTES})"));
196 }
197 Ok(())
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use crate::tree::{Kind, Target};
204 use crate::{ClientMsg, ServerMsg};
205
206 #[test]
207 fn view_messages_round_trip_and_are_checked() {
208 let r = ViewRef::new("todo", "list", "");
209 let event = Event { action: "add".into(), values: serde_json::json!({"new": "milk"}).as_object().cloned().unwrap_or_default(), edit: None, grid: None };
210 for m in [ClientMsg::OpenView { view: r.clone() }, ClientMsg::CloseView { view: r.clone() }, ClientMsg::ViewEvent { view: r.clone(), event }] {
211 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
212 assert!(m.check_sizes().is_ok());
213 }
214 assert_eq!(ClientMsg::OpenView { view: r.clone() }.to_json(), r#"{"type":"open_view","view":{"plugin":"todo","view":"list"}}"#);
215 for bad in [ViewRef::new("Todo", "list", ""), ViewRef::new("todo", "a b", ""), ViewRef::new("todo", "list", "k".repeat(MAX_VIEW_KEY_CHARS + 1))] {
216 assert!(ClientMsg::OpenView { view: bad }.check_sizes().is_err());
217 }
218 let big =
219 Event { action: "x".into(), values: [("t".to_owned(), Value::String("x".repeat(MAX_EVENT_BYTES)))].into_iter().collect(), edit: None, grid: None };
220 assert!(ClientMsg::ViewEvent { view: r.clone(), event: big }.check_sizes().is_err());
221
222 let tree = Node::new(Kind::Text { text: "3 left".into(), style: Default::default(), tone: Default::default() });
223 let msgs = [
224 ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), faults: vec!["/x: y".into()], ..Default::default() }),
225 ServerMsg::LiveView(LiveView {
226 view: r.clone(),
227 patch: vec![Patch::Remove { at: Target::key("a") }],
228 values: serde_json::json!({"new": ""}).as_object().cloned().unwrap_or_default(),
229 ..Default::default()
230 }),
231 ServerMsg::LiveView(LiveView { view: r.clone(), error: Some("no backend".into()), ..Default::default() }),
232 ServerMsg::LiveView(LiveView { view: r, reset: true, ..Default::default() }),
233 ];
234 for m in msgs {
235 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
236 }
237 }
238
239 #[test]
240 fn sites_and_ids() {
241 for s in Site::ALL {
242 assert_eq!(Site::parse(s.label()), Some(s));
243 }
244 assert_eq!(serde_json::from_str::<Site>(r#""sidebar""#).unwrap(), Site::Other);
245 assert!(view_id_ok("todo_list-2") && !view_id_ok("") && !view_id_ok("Todo") && !view_id_ok(&"x".repeat(49)));
246 let d: ViewDecl = serde_json::from_str(r#"{"id":"list","site":"pane"}"#).unwrap();
248 assert_eq!((d.title.as_str(), d.icon.as_str()), ("", ""));
249 }
250
251 #[test]
254 fn minor_3_is_compatible_with_minor_2() {
255 let card = crate::PluginCard {
256 plugin: "p".into(),
257 scope: crate::PluginScope::Chat,
258 action: crate::PluginAction::Made,
259 tools: vec![],
260 added: vec![],
261 removed: vec![],
262 test: None,
263 problems: vec![],
264 missing_settings: vec![],
265 };
266 let v = crate::View::of(&card);
267 assert!(!serde_json::to_string(&v).unwrap().contains("owner"));
268 let old: crate::View = serde_json::from_str(r#"{"kind":"byob.tree","v":1,"data":{"type":"text","text":"x"},"fallback":"x"}"#).unwrap();
269 assert_eq!(old.owner, None);
270 let mut owned = old.clone();
271 owned.owner = Some(ViewRef::new("todo", "item", "3"));
272 let back: crate::View = serde_json::from_str(&serde_json::to_string(&owned).unwrap()).unwrap();
273 assert_eq!(back, owned);
274 let lv = ServerMsg::LiveView(LiveView { view: ViewRef::new("todo", "list", ""), reset: true, ..Default::default() }).to_json();
276 assert!(lv.starts_with(r#"{"type":"live_view""#), "{lv}");
277 }
278}