oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1//! Scenes (scenes and clips spec §2): the deck-level `scenes` map, the
2//! checks its ops make, its tolerant view, the `scene` and `clip` block
3//! props, and a scene's version (plan call R1).
4//!
5//! In the document, `scenes` is a root Y.Map of scene id to one Y.Map
6//! per scene holding `name`, `author` and `code` (strings), `states` (a
7//! plain list of `{id, name, description}`), `words` (a Y.Map of key to
8//! text, so two people's edits to different words merge), `data` (one
9//! plain JSON value, replaced whole) and `stills` (a Y.Map of state id
10//! to a plain `{ref, made}`). fixtures/scenes.mjs is the twin, message
11//! for message.
12//!
13//! A scene's version is not stored. It is the SHA-256, in lowercase hex,
14//! of the canonical JSON of the object `{"code", "data", "words"}`.
15//! Canonical JSON is JSON.stringify's, made deterministic: no white
16//! space, object keys sorted by code point at every level, numbers as
17//! JavaScript prints them (so `5.0` is `5`, `-0` is `0`, `1e21` is
18//! `1e+21`), strings escaped only where JSON must be, UTF-8. Absent code
19//! is `""`, absent data `null`, absent words `{}`. Being JSON, no word
20//! can be spelled to look like two (a line encoding could). Rust, the
21//! browser (fixtures/scenes.mjs) and the server
22//! (internal/slides/deck/scenes.go) agree on
23//! fixtures/vectors/scene-version.json.
24
25use serde_json::{Map as JsonMap, Value};
26use std::collections::HashSet;
27
28/// The largest `data` a scene may hold, measured on its canonical JSON:
29/// 960 KiB. That alone does not make a `set_scene` fit one live-sync
30/// update: a number takes nine bytes in the update and as few as two in
31/// JSON, so a batch with a scene op is also measured (`MAX_UPDATE_BYTES`,
32/// ops.rs `apply_ops`).
33pub const MAX_SCENE_DATA: usize = 960 * 1024;
34
35/// The most one posted update may be (internal/slides/live.go
36/// `maxUpdateBytes`): 1 MiB. A batch carrying `add_scene` or `set_scene`
37/// whose update would be larger is refused, so no deck holds a scene an
38/// editor could not save again.
39pub const MAX_UPDATE_BYTES: usize = 1 << 20;
40
41/// A clip block's `play`: one press, a loop from arrival, or once from
42/// arrival.
43pub const CLIP_PLAYS: &[&str] = &["press", "loop", "once"];
44
45/// The key no scene may use as an id, a state id, a word key or anywhere
46/// in its data: JavaScript's decoder for plain values (lib0, under Yjs)
47/// assigns it through the prototype setter, so a browser would lose it.
48pub const PROTO: &str = "__proto__";
49
50/// A scene id: the document's id pattern, 12 lowercase base32 characters
51/// (spec §2.2), as slide and block ids are minted.
52pub fn scene_id(id: &str) -> bool {
53 id.len() == 12 && id.bytes().all(|b| matches!(b, b'a'..=b'z' | b'2'..=b'7'))
54}
55
56/// Whether `v` has an object key `__proto__` at any depth.
57fn holds_proto(v: &Value) -> bool {
58 match v {
59 Value::Array(items) => items.iter().any(holds_proto),
60 Value::Object(m) => m.contains_key(PROTO) || m.values().any(holds_proto),
61 _ => false,
62 }
63}
64
65/// 64 lowercase hex digits: a stored object's ref, or a version.
66pub fn hex64(s: &str) -> bool {
67 s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
68}
69
70// --- canonical JSON and the version ---
71
72/// A number as JavaScript's Number::toString prints it, which is what
73/// JSON.stringify writes.
74pub fn es_number(f: f64) -> String {
75 if f == 0.0 {
76 return "0".into();
77 }
78 if !f.is_finite() {
79 return "null".into();
80 }
81 // `{:e}` is the shortest representation that reads back as `f`:
82 // the same digits JavaScript chooses, in another layout.
83 let s = format!("{:e}", f.abs());
84 let (mantissa, exp) = s.split_once('e').unwrap_or((&s, "0"));
85 let exp: i32 = exp.parse().unwrap_or(0);
86 let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
87 let k = digits.len() as i32;
88 let n = exp + 1;
89 let body = if k <= n && n <= 21 {
90 format!("{digits}{}", "0".repeat((n - k) as usize))
91 } else if 0 < n && n <= 21 {
92 format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
93 } else if -6 < n && n <= 0 {
94 format!("0.{}{digits}", "0".repeat((-n) as usize))
95 } else {
96 let e = n - 1;
97 let sign = if e < 0 { '-' } else { '+' };
98 if k == 1 {
99 format!("{digits}e{sign}{}", e.abs())
100 } else {
101 format!("{}.{}e{sign}{}", &digits[..1], &digits[1..], e.abs())
102 }
103 };
104 if f < 0.0 {
105 format!("-{body}")
106 } else {
107 body
108 }
109}
110
111fn push_string(out: &mut String, s: &str) {
112 out.push('"');
113 for c in s.chars() {
114 match c {
115 '"' => out.push_str("\\\""),
116 '\\' => out.push_str("\\\\"),
117 '\u{8}' => out.push_str("\\b"),
118 '\u{c}' => out.push_str("\\f"),
119 '\n' => out.push_str("\\n"),
120 '\r' => out.push_str("\\r"),
121 '\t' => out.push_str("\\t"),
122 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
123 c => out.push(c),
124 }
125 }
126 out.push('"');
127}
128
129fn push_canonical(out: &mut String, v: &Value) {
130 match v {
131 Value::Null => out.push_str("null"),
132 Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
133 Value::Number(n) => out.push_str(&es_number(n.as_f64().unwrap_or(0.0))),
134 Value::String(s) => push_string(out, s),
135 Value::Array(items) => {
136 out.push('[');
137 for (i, item) in items.iter().enumerate() {
138 if i > 0 {
139 out.push(',');
140 }
141 push_canonical(out, item);
142 }
143 out.push(']');
144 }
145 Value::Object(entries) => {
146 // Byte order of UTF-8 is code point order.
147 let mut keys: Vec<&String> = entries.keys().collect();
148 keys.sort();
149 out.push('{');
150 for (i, k) in keys.into_iter().enumerate() {
151 if i > 0 {
152 out.push(',');
153 }
154 push_string(out, k);
155 out.push(':');
156 push_canonical(out, &entries[k]);
157 }
158 out.push('}');
159 }
160 }
161}
162
163/// `v` as canonical JSON (see the module comment).
164pub fn canonical_json(v: &Value) -> String {
165 let mut out = String::new();
166 push_canonical(&mut out, v);
167 out
168}
169
170/// What a scene's version hashes: the canonical JSON of its `code`,
171/// `data` and `words`, from the view's scene object.
172pub fn scene_canonical(scene: &Value) -> String {
173 let code = scene
174 .get("code")
175 .and_then(Value::as_str)
176 .unwrap_or_default();
177 let words: JsonMap<String, Value> = scene
178 .get("words")
179 .and_then(Value::as_object)
180 .map(|w| {
181 w.iter()
182 .filter(|(_, v)| v.is_string())
183 .map(|(k, v)| (k.clone(), v.clone()))
184 .collect()
185 })
186 .unwrap_or_default();
187 canonical_json(&serde_json::json!({
188 "code": code,
189 "data": scene.get("data").unwrap_or(&Value::Null),
190 "words": words,
191 }))
192}
193
194/// A scene's version: SHA-256 of `scene_canonical`, lowercase hex.
195pub fn scene_version(scene: &Value) -> String {
196 sha256(scene_canonical(scene).as_bytes())
197 .iter()
198 .map(|b| format!("{b:02x}"))
199 .collect()
200}
201
202/// FIPS 180-4 SHA-256. Written out rather than taken from a crate: the
203/// core's dependencies are pinned and few, and this is the one hash it
204/// needs. The vectors hold it to Go's crypto/sha256.
205fn sha256(input: &[u8]) -> [u8; 32] {
206 const K: [u32; 64] = [
207 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
208 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
209 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
210 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
211 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
212 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
213 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
214 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
215 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
216 0xc67178f2,
217 ];
218 let mut h: [u32; 8] = [
219 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
220 0x5be0cd19,
221 ];
222 let mut msg = input.to_vec();
223 let bits = (input.len() as u64).wrapping_mul(8);
224 msg.push(0x80);
225 while msg.len() % 64 != 56 {
226 msg.push(0);
227 }
228 msg.extend_from_slice(&bits.to_be_bytes());
229 for chunk in msg.as_chunks::<64>().0 {
230 let mut w = [0u32; 64];
231 for (i, word) in chunk.as_chunks::<4>().0.iter().enumerate() {
232 w[i] = u32::from_be_bytes(*word);
233 }
234 for i in 16..64 {
235 let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
236 let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
237 w[i] = w[i - 16]
238 .wrapping_add(s0)
239 .wrapping_add(w[i - 7])
240 .wrapping_add(s1);
241 }
242 let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
243 for i in 0..64 {
244 let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
245 let ch = (e & f) ^ (!e & g);
246 let t1 = hh
247 .wrapping_add(s1)
248 .wrapping_add(ch)
249 .wrapping_add(K[i])
250 .wrapping_add(w[i]);
251 let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
252 let maj = (a & b) ^ (a & c) ^ (b & c);
253 let t2 = s0.wrapping_add(maj);
254 hh = g;
255 g = f;
256 f = e;
257 e = d.wrapping_add(t1);
258 d = c;
259 c = b;
260 b = a;
261 a = t1.wrapping_add(t2);
262 }
263 for (slot, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
264 *slot = slot.wrapping_add(v);
265 }
266 }
267 let mut out = [0u8; 32];
268 for (i, v) in h.iter().enumerate() {
269 out[i * 4..i * 4 + 4].copy_from_slice(&v.to_be_bytes());
270 }
271 out
272}
273
274// --- what the ops take ---
275
276fn text_field(o: &JsonMap<String, Value>, key: &str, at: &str) -> Result<String, String> {
277 match o.get(key) {
278 None | Some(Value::Null) => Ok(String::new()),
279 Some(Value::String(s)) => Ok(s.clone()),
280 Some(_) => Err(format!("{at}.{key} must be a string")),
281 }
282}
283
284/// A scene's `states` checked and rebuilt from its known fields — one
285/// or more `{id, name?, description?}` with distinct, non-empty ids —
286/// and the ids in order.
287pub fn states(v: &Value) -> Result<(Value, Vec<String>), String> {
288 let list = v.as_array().ok_or("states must be a list")?;
289 if list.is_empty() {
290 return Err("states must have at least one state".into());
291 }
292 let mut ids = Vec::with_capacity(list.len());
293 let mut out = Vec::with_capacity(list.len());
294 for (i, s) in list.iter().enumerate() {
295 let at = format!("states[{i}]");
296 let s = s.as_object().ok_or(format!("{at} must be a map"))?;
297 let id = match s.get("id") {
298 Some(Value::String(id)) if !id.is_empty() => id.clone(),
299 Some(Value::String(_)) => return Err(format!("{at}.id is empty")),
300 _ => return Err(format!("{at}.id must be a string")),
301 };
302 if id == PROTO {
303 return Err(format!("{at}.id may not be \"{PROTO}\""));
304 }
305 if ids.contains(&id) {
306 return Err(format!("state {id:?} is used twice"));
307 }
308 let name = text_field(s, "name", &at)?;
309 let description = text_field(s, "description", &at)?;
310 out.push(serde_json::json!({"id": id, "name": name, "description": description}));
311 ids.push(id);
312 }
313 Ok((Value::Array(out), ids))
314}
315
316/// `words` as an op sends it: a map of key to text, or on `set_scene`
317/// to text or null (which removes the word).
318pub fn words(v: &Value, patch: bool) -> Result<(), String> {
319 let m = v.as_object().ok_or("words must be a map")?;
320 if m.contains_key(PROTO) {
321 return Err(format!("words may not have the key \"{PROTO}\""));
322 }
323 for (k, w) in m {
324 match w {
325 Value::String(_) => {}
326 Value::Null if patch => {}
327 _ if patch => return Err(format!("words.{k} must be a string or null")),
328 _ => return Err(format!("words.{k} must be a string")),
329 }
330 }
331 Ok(())
332}
333
334/// `data` within MAX_SCENE_DATA, measured on its canonical JSON.
335pub fn data(v: &Value) -> Result<(), String> {
336 if holds_proto(v) {
337 return Err(format!("data may not hold the key \"{PROTO}\""));
338 }
339 if canonical_json(v).len() > MAX_SCENE_DATA {
340 return Err("data is larger than 960 KiB".into());
341 }
342 Ok(())
343}
344
345/// `stills` as `set_scene` sends it: state id to `{ref, made}` (both 64
346/// lowercase hex digits) or null, each naming one of `ids`.
347pub fn stills(v: &Value, scene: &str, ids: &[String]) -> Result<(), String> {
348 let m = v.as_object().ok_or("stills must be a map")?;
349 for (state, still) in m {
350 // Null removes, and may name a state the scene no longer has:
351 // that is how a still left behind by a removed state goes.
352 if still.is_null() {
353 continue;
354 }
355 if !ids.iter().any(|i| i == state) {
356 return Err(format!("scene {scene:?} has no state {state:?}"));
357 }
358 let o = still
359 .as_object()
360 .ok_or(format!("stills.{state} must be a map or null"))?;
361 for key in ["ref", "made"] {
362 if !o.get(key).and_then(Value::as_str).is_some_and(hex64) {
363 return Err(format!(
364 "stills.{state}.{key} is not 64 lowercase hex digits"
365 ));
366 }
367 }
368 }
369 Ok(())
370}
371
372/// A still rebuilt from its two fields, as the document keeps it.
373pub fn still(v: &Value) -> Value {
374 serde_json::json!({"ref": v["ref"], "made": v["made"]})
375}
376
377// --- scene and clip blocks ---
378
379/// What a scene block points at: `props.scene`, `from` and `to`.
380#[derive(Clone, Default)]
381pub struct SceneRef {
382 pub scene: Option<String>,
383 pub from: Option<String>,
384 pub to: Option<String>,
385}
386
387const SCENE_KEYS: [&str; 3] = ["scene", "from", "to"];
388
389impl SceneRef {
390 /// The strings among a block's props (anything else reads as unset).
391 pub fn of(props: &Value) -> SceneRef {
392 let s = |k: &str| props.get(k).and_then(Value::as_str).map(str::to_string);
393 SceneRef {
394 scene: s("scene"),
395 from: s("from"),
396 to: s("to"),
397 }
398 }
399
400 fn slot(&mut self, key: &str) -> &mut Option<String> {
401 match key {
402 "scene" => &mut self.scene,
403 "from" => &mut self.from,
404 _ => &mut self.to,
405 }
406 }
407
408 /// Applies an op's props to this one, checking each key it sets: a
409 /// string or null. Answers whether the op touched any of the three.
410 pub fn patch(&mut self, props: &JsonMap<String, Value>) -> Result<bool, String> {
411 let mut touched = false;
412 for key in SCENE_KEYS {
413 match props.get(key) {
414 None => {}
415 Some(Value::Null) => {
416 *self.slot(key) = None;
417 touched = true;
418 }
419 Some(Value::String(s)) => {
420 *self.slot(key) = Some(s.clone());
421 touched = true;
422 }
423 Some(_) => return Err(format!("scene block props.{key} must be a string")),
424 }
425 }
426 Ok(touched)
427 }
428
429 /// Whether the block names a scene the deck has and two of its
430 /// states in order. `states` finds a scene's state ids.
431 pub fn check<'a>(&self, states: impl Fn(&str) -> Option<&'a [String]>) -> Result<(), String> {
432 let Some(scene) = &self.scene else {
433 if self.from.is_some() || self.to.is_some() {
434 return Err("scene block props.from and props.to need props.scene".into());
435 }
436 return Ok(());
437 };
438 let ids = states(scene).ok_or(format!("no scene {scene:?}"))?;
439 let at = |state: &Option<String>| -> Result<Option<usize>, String> {
440 match state {
441 None => Ok(None),
442 Some(s) => ids
443 .iter()
444 .position(|i| i == s)
445 .map(Some)
446 .ok_or(format!("scene {scene:?} has no state {s:?}")),
447 }
448 };
449 if let (Some(f), Some(t)) = (at(&self.from)?, at(&self.to)?) {
450 if f > t {
451 return Err(format!(
452 "from {:?} comes after to {:?} in scene {scene:?}",
453 ids[f], ids[t]
454 ));
455 }
456 }
457 Ok(())
458 }
459}
460
461/// A clip block's props as an op sets them: `play` one of CLIP_PLAYS,
462/// `asset` a string (an asset id), either null to remove it.
463pub fn clip_props(props: &JsonMap<String, Value>) -> Result<(), String> {
464 match props.get("play") {
465 None | Some(Value::Null) => {}
466 Some(Value::String(p)) if CLIP_PLAYS.contains(&p.as_str()) => {}
467 Some(other) => {
468 return Err(format!(
469 "play {other} is not one of {}",
470 CLIP_PLAYS.join(", ")
471 ))
472 }
473 }
474 match props.get("asset") {
475 None | Some(Value::Null) | Some(Value::String(_)) => Ok(()),
476 Some(_) => Err("clip block props.asset must be a string".into()),
477 }
478}
479
480// --- the view ---
481
482/// One scene as the view shows it, rebuilt from the fields that have
483/// the right type (view.rs, "typed leaves"); None for an entry that is
484/// not a map. `entry` is the scene's map already read as JSON.
485pub fn scene_view(entry: Value) -> Option<Value> {
486 let Value::Object(o) = entry else {
487 return None;
488 };
489 let text = |key: &str| match o.get(key) {
490 Some(Value::String(s)) => s.clone(),
491 _ => String::new(),
492 };
493 let states = view_states(o.get("states"));
494 let words: JsonMap<String, Value> = match o.get("words") {
495 Some(Value::Object(m)) => m
496 .iter()
497 .filter(|(_, v)| v.is_string())
498 .map(|(k, v)| (k.clone(), v.clone()))
499 .collect(),
500 _ => JsonMap::new(),
501 };
502 let stills: JsonMap<String, Value> = match o.get("stills") {
503 Some(Value::Object(m)) => m
504 .iter()
505 .filter(|(_, v)| {
506 v.get("ref").is_some_and(Value::is_string)
507 && v.get("made").is_some_and(Value::is_string)
508 })
509 .map(|(k, v)| (k.clone(), still(v)))
510 .collect(),
511 _ => JsonMap::new(),
512 };
513 Some(serde_json::json!({
514 "name": text("name"),
515 "author": text("author"),
516 "code": text("code"),
517 "states": states,
518 "words": words,
519 "data": o.get("data").cloned().unwrap_or(Value::Null),
520 "stills": stills,
521 }))
522}
523
524/// A scene's `states` as the view shows them: the maps with a
525/// non-empty string id, the first of each id, name and description
526/// strings or empty.
527fn view_states(v: Option<&Value>) -> Vec<Value> {
528 let Some(Value::Array(list)) = v else {
529 return Vec::new();
530 };
531 let mut seen = HashSet::new();
532 list.iter()
533 .filter_map(|s| {
534 let s = s.as_object()?;
535 let id = s.get("id")?.as_str().filter(|id| !id.is_empty())?;
536 if !seen.insert(id.to_string()) {
537 return None;
538 }
539 let field = |k: &str| s.get(k).and_then(Value::as_str).unwrap_or_default();
540 Some(serde_json::json!({
541 "id": id, "name": field("name"), "description": field("description")
542 }))
543 })
544 .collect()
545}
546
547/// The state ids the view shows for a scene's `states`, in order: what
548/// the ops' model checks a scene block against.
549pub fn state_ids(states: Option<&Value>) -> Vec<String> {
550 view_states(states)
551 .iter()
552 .filter_map(|s| s["id"].as_str().map(str::to_string))
553 .collect()
554}
555
556#[cfg(test)]
557mod tests {
558 use super::*;
559
560 #[test]
561 fn sha256_known_answers() {
562 let hex = |b: &[u8]| -> String { sha256(b).iter().map(|x| format!("{x:02x}")).collect() };
563 assert_eq!(
564 hex(b""),
565 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
566 );
567 assert_eq!(
568 hex(b"abc"),
569 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
570 );
571 assert_eq!(
572 hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
573 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
574 );
575 }
576
577 #[test]
578 fn numbers_print_as_javascript_prints_them() {
579 for (f, want) in [
580 (0.0, "0"),
581 (-0.0, "0"),
582 (5.0, "5"),
583 (-2.5, "-2.5"),
584 (0.1, "0.1"),
585 (1e21, "1e+21"),
586 (1e20, "100000000000000000000"),
587 (1.5e-7, "1.5e-7"),
588 (1e-6, "0.000001"),
589 (1e-7, "1e-7"),
590 (123.456, "123.456"),
591 (0.30000000000000004, "0.30000000000000004"),
592 (1.7976931348623157e308, "1.7976931348623157e+308"),
593 (5e-324, "5e-324"),
594 (9007199254740993.0, "9007199254740992"),
595 ] {
596 assert_eq!(es_number(f), want, "{f}");
597 }
598 }
599}
600