//! Scenes (scenes and clips spec §2): the deck-level `scenes` map, the //! checks its ops make, its tolerant view, the `scene` and `clip` block //! props, and a scene's version (plan call R1). //! //! In the document, `scenes` is a root Y.Map of scene id to one Y.Map //! per scene holding `name`, `author` and `code` (strings), `states` (a //! plain list of `{id, name, description}`), `words` (a Y.Map of key to //! text, so two people's edits to different words merge), `data` (one //! plain JSON value, replaced whole) and `stills` (a Y.Map of state id //! to a plain `{ref, made}`). fixtures/scenes.mjs is the twin, message //! for message. //! //! A scene's version is not stored. It is the SHA-256, in lowercase hex, //! of the canonical JSON of the object `{"code", "data", "words"}`. //! Canonical JSON is JSON.stringify's, made deterministic: no white //! space, object keys sorted by code point at every level, numbers as //! JavaScript prints them (so `5.0` is `5`, `-0` is `0`, `1e21` is //! `1e+21`), strings escaped only where JSON must be, UTF-8. Absent code //! is `""`, absent data `null`, absent words `{}`. Being JSON, no word //! can be spelled to look like two (a line encoding could). Rust, the //! browser (fixtures/scenes.mjs) and the server //! (internal/slides/deck/scenes.go) agree on //! fixtures/vectors/scene-version.json. use serde_json::{Map as JsonMap, Value}; use std::collections::HashSet; /// The largest `data` a scene may hold, measured on its canonical JSON: /// 960 KiB. That alone does not make a `set_scene` fit one live-sync /// update: a number takes nine bytes in the update and as few as two in /// JSON, so a batch with a scene op is also measured (`MAX_UPDATE_BYTES`, /// ops.rs `apply_ops`). pub const MAX_SCENE_DATA: usize = 960 * 1024; /// The most one posted update may be (internal/slides/live.go /// `maxUpdateBytes`): 1 MiB. A batch carrying `add_scene` or `set_scene` /// whose update would be larger is refused, so no deck holds a scene an /// editor could not save again. pub const MAX_UPDATE_BYTES: usize = 1 << 20; /// A clip block's `play`: one press, a loop from arrival, or once from /// arrival. pub const CLIP_PLAYS: &[&str] = &["press", "loop", "once"]; /// The key no scene may use as an id, a state id, a word key or anywhere /// in its data: JavaScript's decoder for plain values (lib0, under Yjs) /// assigns it through the prototype setter, so a browser would lose it. pub const PROTO: &str = "__proto__"; /// A scene id: the document's id pattern, 12 lowercase base32 characters /// (spec §2.2), as slide and block ids are minted. pub fn scene_id(id: &str) -> bool { id.len() == 12 && id.bytes().all(|b| matches!(b, b'a'..=b'z' | b'2'..=b'7')) } /// Whether `v` has an object key `__proto__` at any depth. fn holds_proto(v: &Value) -> bool { match v { Value::Array(items) => items.iter().any(holds_proto), Value::Object(m) => m.contains_key(PROTO) || m.values().any(holds_proto), _ => false, } } /// 64 lowercase hex digits: a stored object's ref, or a version. pub fn hex64(s: &str) -> bool { s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) } // --- canonical JSON and the version --- /// A number as JavaScript's Number::toString prints it, which is what /// JSON.stringify writes. pub fn es_number(f: f64) -> String { if f == 0.0 { return "0".into(); } if !f.is_finite() { return "null".into(); } // `{:e}` is the shortest representation that reads back as `f`: // the same digits JavaScript chooses, in another layout. let s = format!("{:e}", f.abs()); let (mantissa, exp) = s.split_once('e').unwrap_or((&s, "0")); let exp: i32 = exp.parse().unwrap_or(0); let digits: String = mantissa.chars().filter(|c| *c != '.').collect(); let k = digits.len() as i32; let n = exp + 1; let body = if k <= n && n <= 21 { format!("{digits}{}", "0".repeat((n - k) as usize)) } else if 0 < n && n <= 21 { format!("{}.{}", &digits[..n as usize], &digits[n as usize..]) } else if -6 < n && n <= 0 { format!("0.{}{digits}", "0".repeat((-n) as usize)) } else { let e = n - 1; let sign = if e < 0 { '-' } else { '+' }; if k == 1 { format!("{digits}e{sign}{}", e.abs()) } else { format!("{}.{}e{sign}{}", &digits[..1], &digits[1..], e.abs()) } }; if f < 0.0 { format!("-{body}") } else { body } } fn push_string(out: &mut String, s: &str) { out.push('"'); for c in s.chars() { match c { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\u{8}' => out.push_str("\\b"), '\u{c}' => out.push_str("\\f"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), '\t' => out.push_str("\\t"), c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), c => out.push(c), } } out.push('"'); } fn push_canonical(out: &mut String, v: &Value) { match v { Value::Null => out.push_str("null"), Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }), Value::Number(n) => out.push_str(&es_number(n.as_f64().unwrap_or(0.0))), Value::String(s) => push_string(out, s), Value::Array(items) => { out.push('['); for (i, item) in items.iter().enumerate() { if i > 0 { out.push(','); } push_canonical(out, item); } out.push(']'); } Value::Object(entries) => { // Byte order of UTF-8 is code point order. let mut keys: Vec<&String> = entries.keys().collect(); keys.sort(); out.push('{'); for (i, k) in keys.into_iter().enumerate() { if i > 0 { out.push(','); } push_string(out, k); out.push(':'); push_canonical(out, &entries[k]); } out.push('}'); } } } /// `v` as canonical JSON (see the module comment). pub fn canonical_json(v: &Value) -> String { let mut out = String::new(); push_canonical(&mut out, v); out } /// What a scene's version hashes: the canonical JSON of its `code`, /// `data` and `words`, from the view's scene object. pub fn scene_canonical(scene: &Value) -> String { let code = scene .get("code") .and_then(Value::as_str) .unwrap_or_default(); let words: JsonMap = scene .get("words") .and_then(Value::as_object) .map(|w| { w.iter() .filter(|(_, v)| v.is_string()) .map(|(k, v)| (k.clone(), v.clone())) .collect() }) .unwrap_or_default(); canonical_json(&serde_json::json!({ "code": code, "data": scene.get("data").unwrap_or(&Value::Null), "words": words, })) } /// A scene's version: SHA-256 of `scene_canonical`, lowercase hex. pub fn scene_version(scene: &Value) -> String { sha256(scene_canonical(scene).as_bytes()) .iter() .map(|b| format!("{b:02x}")) .collect() } /// FIPS 180-4 SHA-256. Written out rather than taken from a crate: the /// core's dependencies are pinned and few, and this is the one hash it /// needs. The vectors hold it to Go's crypto/sha256. fn sha256(input: &[u8]) -> [u8; 32] { const K: [u32; 64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; let mut h: [u32; 8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ]; let mut msg = input.to_vec(); let bits = (input.len() as u64).wrapping_mul(8); msg.push(0x80); while msg.len() % 64 != 56 { msg.push(0); } msg.extend_from_slice(&bits.to_be_bytes()); for chunk in msg.as_chunks::<64>().0 { let mut w = [0u32; 64]; for (i, word) in chunk.as_chunks::<4>().0.iter().enumerate() { w[i] = u32::from_be_bytes(*word); } for i in 16..64 { let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); w[i] = w[i - 16] .wrapping_add(s0) .wrapping_add(w[i - 7]) .wrapping_add(s1); } let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; for i in 0..64 { let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); let ch = (e & f) ^ (!e & g); let t1 = hh .wrapping_add(s1) .wrapping_add(ch) .wrapping_add(K[i]) .wrapping_add(w[i]); let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); let maj = (a & b) ^ (a & c) ^ (b & c); let t2 = s0.wrapping_add(maj); hh = g; g = f; f = e; e = d.wrapping_add(t1); d = c; c = b; b = a; a = t1.wrapping_add(t2); } for (slot, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { *slot = slot.wrapping_add(v); } } let mut out = [0u8; 32]; for (i, v) in h.iter().enumerate() { out[i * 4..i * 4 + 4].copy_from_slice(&v.to_be_bytes()); } out } // --- what the ops take --- fn text_field(o: &JsonMap, key: &str, at: &str) -> Result { match o.get(key) { None | Some(Value::Null) => Ok(String::new()), Some(Value::String(s)) => Ok(s.clone()), Some(_) => Err(format!("{at}.{key} must be a string")), } } /// A scene's `states` checked and rebuilt from its known fields — one /// or more `{id, name?, description?}` with distinct, non-empty ids — /// and the ids in order. pub fn states(v: &Value) -> Result<(Value, Vec), String> { let list = v.as_array().ok_or("states must be a list")?; if list.is_empty() { return Err("states must have at least one state".into()); } let mut ids = Vec::with_capacity(list.len()); let mut out = Vec::with_capacity(list.len()); for (i, s) in list.iter().enumerate() { let at = format!("states[{i}]"); let s = s.as_object().ok_or(format!("{at} must be a map"))?; let id = match s.get("id") { Some(Value::String(id)) if !id.is_empty() => id.clone(), Some(Value::String(_)) => return Err(format!("{at}.id is empty")), _ => return Err(format!("{at}.id must be a string")), }; if id == PROTO { return Err(format!("{at}.id may not be \"{PROTO}\"")); } if ids.contains(&id) { return Err(format!("state {id:?} is used twice")); } let name = text_field(s, "name", &at)?; let description = text_field(s, "description", &at)?; out.push(serde_json::json!({"id": id, "name": name, "description": description})); ids.push(id); } Ok((Value::Array(out), ids)) } /// `words` as an op sends it: a map of key to text, or on `set_scene` /// to text or null (which removes the word). pub fn words(v: &Value, patch: bool) -> Result<(), String> { let m = v.as_object().ok_or("words must be a map")?; if m.contains_key(PROTO) { return Err(format!("words may not have the key \"{PROTO}\"")); } for (k, w) in m { match w { Value::String(_) => {} Value::Null if patch => {} _ if patch => return Err(format!("words.{k} must be a string or null")), _ => return Err(format!("words.{k} must be a string")), } } Ok(()) } /// `data` within MAX_SCENE_DATA, measured on its canonical JSON. pub fn data(v: &Value) -> Result<(), String> { if holds_proto(v) { return Err(format!("data may not hold the key \"{PROTO}\"")); } if canonical_json(v).len() > MAX_SCENE_DATA { return Err("data is larger than 960 KiB".into()); } Ok(()) } /// `stills` as `set_scene` sends it: state id to `{ref, made}` (both 64 /// lowercase hex digits) or null, each naming one of `ids`. pub fn stills(v: &Value, scene: &str, ids: &[String]) -> Result<(), String> { let m = v.as_object().ok_or("stills must be a map")?; for (state, still) in m { // Null removes, and may name a state the scene no longer has: // that is how a still left behind by a removed state goes. if still.is_null() { continue; } if !ids.iter().any(|i| i == state) { return Err(format!("scene {scene:?} has no state {state:?}")); } let o = still .as_object() .ok_or(format!("stills.{state} must be a map or null"))?; for key in ["ref", "made"] { if !o.get(key).and_then(Value::as_str).is_some_and(hex64) { return Err(format!( "stills.{state}.{key} is not 64 lowercase hex digits" )); } } } Ok(()) } /// A still rebuilt from its two fields, as the document keeps it. pub fn still(v: &Value) -> Value { serde_json::json!({"ref": v["ref"], "made": v["made"]}) } // --- scene and clip blocks --- /// What a scene block points at: `props.scene`, `from` and `to`. #[derive(Clone, Default)] pub struct SceneRef { pub scene: Option, pub from: Option, pub to: Option, } const SCENE_KEYS: [&str; 3] = ["scene", "from", "to"]; impl SceneRef { /// The strings among a block's props (anything else reads as unset). pub fn of(props: &Value) -> SceneRef { let s = |k: &str| props.get(k).and_then(Value::as_str).map(str::to_string); SceneRef { scene: s("scene"), from: s("from"), to: s("to"), } } fn slot(&mut self, key: &str) -> &mut Option { match key { "scene" => &mut self.scene, "from" => &mut self.from, _ => &mut self.to, } } /// Applies an op's props to this one, checking each key it sets: a /// string or null. Answers whether the op touched any of the three. pub fn patch(&mut self, props: &JsonMap) -> Result { let mut touched = false; for key in SCENE_KEYS { match props.get(key) { None => {} Some(Value::Null) => { *self.slot(key) = None; touched = true; } Some(Value::String(s)) => { *self.slot(key) = Some(s.clone()); touched = true; } Some(_) => return Err(format!("scene block props.{key} must be a string")), } } Ok(touched) } /// Whether the block names a scene the deck has and two of its /// states in order. `states` finds a scene's state ids. pub fn check<'a>(&self, states: impl Fn(&str) -> Option<&'a [String]>) -> Result<(), String> { let Some(scene) = &self.scene else { if self.from.is_some() || self.to.is_some() { return Err("scene block props.from and props.to need props.scene".into()); } return Ok(()); }; let ids = states(scene).ok_or(format!("no scene {scene:?}"))?; let at = |state: &Option| -> Result, String> { match state { None => Ok(None), Some(s) => ids .iter() .position(|i| i == s) .map(Some) .ok_or(format!("scene {scene:?} has no state {s:?}")), } }; if let (Some(f), Some(t)) = (at(&self.from)?, at(&self.to)?) { if f > t { return Err(format!( "from {:?} comes after to {:?} in scene {scene:?}", ids[f], ids[t] )); } } Ok(()) } } /// A clip block's props as an op sets them: `play` one of CLIP_PLAYS, /// `asset` a string (an asset id), either null to remove it. pub fn clip_props(props: &JsonMap) -> Result<(), String> { match props.get("play") { None | Some(Value::Null) => {} Some(Value::String(p)) if CLIP_PLAYS.contains(&p.as_str()) => {} Some(other) => { return Err(format!( "play {other} is not one of {}", CLIP_PLAYS.join(", ") )) } } match props.get("asset") { None | Some(Value::Null) | Some(Value::String(_)) => Ok(()), Some(_) => Err("clip block props.asset must be a string".into()), } } // --- the view --- /// One scene as the view shows it, rebuilt from the fields that have /// the right type (view.rs, "typed leaves"); None for an entry that is /// not a map. `entry` is the scene's map already read as JSON. pub fn scene_view(entry: Value) -> Option { let Value::Object(o) = entry else { return None; }; let text = |key: &str| match o.get(key) { Some(Value::String(s)) => s.clone(), _ => String::new(), }; let states = view_states(o.get("states")); let words: JsonMap = match o.get("words") { Some(Value::Object(m)) => m .iter() .filter(|(_, v)| v.is_string()) .map(|(k, v)| (k.clone(), v.clone())) .collect(), _ => JsonMap::new(), }; let stills: JsonMap = match o.get("stills") { Some(Value::Object(m)) => m .iter() .filter(|(_, v)| { v.get("ref").is_some_and(Value::is_string) && v.get("made").is_some_and(Value::is_string) }) .map(|(k, v)| (k.clone(), still(v))) .collect(), _ => JsonMap::new(), }; Some(serde_json::json!({ "name": text("name"), "author": text("author"), "code": text("code"), "states": states, "words": words, "data": o.get("data").cloned().unwrap_or(Value::Null), "stills": stills, })) } /// A scene's `states` as the view shows them: the maps with a /// non-empty string id, the first of each id, name and description /// strings or empty. fn view_states(v: Option<&Value>) -> Vec { let Some(Value::Array(list)) = v else { return Vec::new(); }; let mut seen = HashSet::new(); list.iter() .filter_map(|s| { let s = s.as_object()?; let id = s.get("id")?.as_str().filter(|id| !id.is_empty())?; if !seen.insert(id.to_string()) { return None; } let field = |k: &str| s.get(k).and_then(Value::as_str).unwrap_or_default(); Some(serde_json::json!({ "id": id, "name": field("name"), "description": field("description") })) }) .collect() } /// The state ids the view shows for a scene's `states`, in order: what /// the ops' model checks a scene block against. pub fn state_ids(states: Option<&Value>) -> Vec { view_states(states) .iter() .filter_map(|s| s["id"].as_str().map(str::to_string)) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn sha256_known_answers() { let hex = |b: &[u8]| -> String { sha256(b).iter().map(|x| format!("{x:02x}")).collect() }; assert_eq!( hex(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ); assert_eq!( hex(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" ); assert_eq!( hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" ); } #[test] fn numbers_print_as_javascript_prints_them() { for (f, want) in [ (0.0, "0"), (-0.0, "0"), (5.0, "5"), (-2.5, "-2.5"), (0.1, "0.1"), (1e21, "1e+21"), (1e20, "100000000000000000000"), (1.5e-7, "1.5e-7"), (1e-6, "0.000001"), (1e-7, "1e-7"), (123.456, "123.456"), (0.30000000000000004, "0.30000000000000004"), (1.7976931348623157e308, "1.7976931348623157e+308"), (5e-324, "5e-324"), (9007199254740993.0, "9007199254740992"), ] { assert_eq!(es_number(f), want, "{f}"); } } }