Skip to main content

tilo_actions/
content.rs

1//! Large parts of a recorded action, kept as content and named by reference.
2//!
3//! Every change records the action it ran ([`crate::ActionContext::action`])
4//! so a receiver can replay it. An action larger than a change documents
5//! whole (a paste with images inline) still records it: each long
6//! text or byte run of its payload is kept, sealed, in the content store of
7//! the window whose code records the action ([`register`]), and the recorded
8//! payload names it by the reference that store answered. Only the record's
9//! readers hold the key a reference carries; whoever stores or carries the
10//! part holds ciphertext. Where no store would keep a part, the action is
11//! refused rather than recorded naming content nothing holds.
12//!
13//! A receiver resolves those references from its own content store before it
14//! replays: the record's ([`crate::ActionRegistry`] keeps it), which asks the
15//! record's route and holds the change until the part arrives, as it holds
16//! one whose app surface has not.
17//!
18//! A reference is the JSON object `{"tilo.content/1": "<reference>", "as":
19//! "text" | "bytes" | "json"}` in place of the string, byte array, or
20//! array or object (a long list of small parts: a pasted book's
21//! paragraphs) it stands for.
22
23use serde_json::{Map, Value};
24use tilo_content::ContentStore;
25use tilo_wake::WakeHandle;
26
27use crate::{ActionError, EncodedAction};
28
29pub const CONTENT_REFERENCE_KEY: &str = "tilo.content/1";
30
31/// The shortest text or byte run kept as content rather than inline.
32pub const CONTENT_PART_THRESHOLD: usize = 16 * 1024;
33
34const AS: &str = "as";
35const TEXT: &str = "text";
36const BYTES: &str = "bytes";
37const JSON: &str = "json";
38
39/// Content a recorded action names that is not here yet.
40#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
41#[error("the recorded action names content {0} that is not here yet")]
42pub struct MissingContent(pub String);
43
44/// The parts of a recorded action kept as content: each part's bytes, by the
45/// reference the recorded action names it by.
46pub type ContentParts = Vec<(String, Vec<u8>)>;
47
48thread_local! {
49    /// The content stores of this process's windows, by the wake scope their
50    /// code runs in.
51    static WINDOW_STORES: std::cell::RefCell<Vec<(WakeHandle, ContentStore)>> =
52        const { std::cell::RefCell::new(Vec::new()) };
53}
54
55/// Keep `store` as the content store of the window whose wake scope `window`
56/// names: where the large parts of the actions its code records are kept,
57/// sealed, and where a recorded action's parts are read from, so recorded
58/// actions replay wherever their content reaches. The host sets it once per
59/// window, with the store it lent the window
60/// ([`crate::ActionRegistry::connect_content`]); windows that closed are
61/// forgotten.
62pub fn register(window: &WakeHandle, store: ContentStore) {
63    WINDOW_STORES.with(|stores| {
64        let mut stores = stores.borrow_mut();
65        stores.retain(|(handle, _)| handle.is_active() && !handle.same_open_scope(window));
66        stores.push((window.clone(), store));
67    });
68}
69
70/// The content store of the window whose code is running: the one registered
71/// for the wake scope entered now. `None` outside a window, or for one whose
72/// host lent no store.
73#[must_use]
74pub fn current() -> Option<ContentStore> {
75    let here = WakeHandle::new();
76    WINDOW_STORES.with(|stores| {
77        stores
78            .borrow()
79            .iter()
80            .find(|(handle, _)| handle.same_open_scope(&here))
81            .map(|(_, store)| store.clone())
82    })
83}
84
85/// The store this thread's window records its actions in: the entered scope's
86/// ([`current`]), else the last one this thread registered for a window. A
87/// window's callback runs on its own thread and may dispatch an action
88/// outside the scope its toolkit enters for a pass; what it records is still
89/// that window's.
90pub(crate) fn recording_store() -> Option<ContentStore> {
91    current().or_else(|| {
92        WINDOW_STORES.with(|stores| stores.borrow().last().map(|(_, store)| store.clone()))
93    })
94}
95
96/// Keep a content store of this thread's own for the records it writes, where a window keeps its
97/// own: a replica a test or a headless tool runs has no window to lend one, and an action larger
98/// than a change documents whole is refused when nothing keeps its large parts. The returned
99/// scope must stay alive for as long as records are written.
100#[cfg(any(test, feature = "test-support"))]
101#[must_use]
102pub fn register_for_resources() -> tilo_wake::WakeScope {
103    let window = tilo_wake::WakeScope::new();
104    register(&window.handle(), ContentStore::memory());
105    window
106}
107
108/// Keep `bytes` in the content store of the window whose code records them,
109/// answering the reference the recorded action names them by: sealed under a
110/// key of their own when the store seals. Where no store keeps content, the
111/// action is refused rather than recorded with a reference nothing holds.
112fn put_here(bytes: &[u8]) -> Result<String, ActionError> {
113    let Some(store) = recording_store() else {
114        return Err(ActionError::Refused(format!(
115            "a large part of the action ({} bytes) would be lost: no content store keeps content \
116             where the action is recorded",
117            bytes.len()
118        )));
119    };
120    store.put(bytes).map_err(|error| {
121        ActionError::Refused(format!(
122            "a large part of the action could not be kept: {error}"
123        ))
124    })
125}
126
127/// Keep, in `store` — the content store of the record whose action `env`
128/// applies, or the running window's when none is named — the parts `env`'s
129/// recorded action names, sealed exactly as its writer sealed them: what a
130/// device that applies a received action holds of it afterwards.
131pub(crate) fn keep(env: &crate::ActionEnvelope, store: Option<&ContentStore>) {
132    let Ok(content) = env.recorded_content() else {
133        return;
134    };
135    let Some(store) = store.cloned().or_else(recording_store) else {
136        return;
137    };
138    for (reference, bytes) in content {
139        if store.has(&reference) {
140            continue;
141        }
142        if let Err(error) = store.put_as(&reference, &bytes) {
143            tracing::warn!(%error, "an action's content could not be kept");
144        }
145    }
146}
147
148impl EncodedAction {
149    /// This action as its change records it: every text or byte run of at
150    /// least `threshold` bytes, and every long list of small parts, kept as
151    /// content in the store of the window whose code records it
152    /// ([`register`]) and named by the reference it answered. Run once,
153    /// where the action is invoked: a sealing store draws a fresh key for
154    /// each part.
155    ///
156    /// # Errors
157    ///
158    /// [`ActionError::Refused`] when a part has nowhere to be kept: a
159    /// reference nothing holds would lose it.
160    pub(crate) fn with_content_parts(&self, threshold: usize) -> Result<Self, ActionError> {
161        let mut value = self.payload_value()?;
162        if holds_reserved(&value) {
163            return Err(reserved());
164        }
165        // The payload's own shape stays inline; only its parts are kept.
166        match &mut value {
167            Value::Object(object) => {
168                for item in object.values_mut() {
169                    externalize(item, threshold)?;
170                }
171            }
172            Value::Array(items) => {
173                for item in items {
174                    externalize(item, threshold)?;
175                }
176            }
177            other => {
178                externalize(other, threshold)?;
179            }
180        }
181        let payload = serde_json::to_vec(&value).map_err(ActionError::Encode)?;
182        Ok(Self {
183            type_id: self.type_id.clone(),
184            payload,
185        })
186    }
187
188    /// The content this recorded action names, in payload order.
189    #[must_use]
190    pub fn content_parts(&self) -> Vec<String> {
191        let mut references = Vec::new();
192        if let Ok(value) = serde_json::from_slice::<Value>(&self.payload) {
193            collect(&value, &mut references);
194        }
195        references
196    }
197
198    /// The parts this recorded action names, read from `action`, the action
199    /// as it ran: `None` when this is not `action` with its large parts kept
200    /// as content (another shape, or a part that is not what its reference
201    /// names).
202    #[must_use]
203    pub fn recorded_parts_of(&self, action: &Self) -> Option<ContentParts> {
204        if self.type_id != action.type_id {
205            return None;
206        }
207        if self.payload == action.payload {
208            return Some(ContentParts::new());
209        }
210        let recorded = self.payload_value().ok()?;
211        let ran = action.payload_value().ok()?;
212        let mut parts = ContentParts::new();
213        pair(&recorded, &ran, &mut parts).then_some(())?;
214        parts
215            .iter()
216            .all(|(reference, bytes)| tilo_content::names(reference, bytes))
217            .then_some(parts)
218    }
219
220    /// The action as it ran, with every content reference replaced by the
221    /// content `read` returns for it, checked against its reference.
222    pub fn resolve_content(
223        &self,
224        read: &dyn Fn(&str) -> Option<Vec<u8>>,
225    ) -> Result<Result<Self, MissingContent>, ActionError> {
226        let mut value = self.payload_value()?;
227        if let Err(missing) = internalize(&mut value, read) {
228            return Ok(Err(missing));
229        }
230        let payload = serde_json::to_vec(&value).map_err(ActionError::Encode)?;
231        Ok(Ok(Self {
232            type_id: self.type_id.clone(),
233            payload,
234        }))
235    }
236
237    fn payload_value(&self) -> Result<Value, ActionError> {
238        serde_json::from_slice(&self.payload).map_err(|source| ActionError::Decode {
239            type_id: self.type_id.clone(),
240            source,
241        })
242    }
243}
244
245fn reference(reference: String, kind: &str) -> Value {
246    let mut object = Map::new();
247    object.insert(CONTENT_REFERENCE_KEY.into(), Value::String(reference));
248    object.insert(AS.into(), Value::String(kind.into()));
249    Value::Object(object)
250}
251
252/// The bytes of an array that holds only bytes.
253fn byte_run(items: &[Value]) -> Option<Vec<u8>> {
254    items
255        .iter()
256        .map(|item| item.as_u64().and_then(|byte| u8::try_from(byte).ok()))
257        .collect()
258}
259
260fn reserved() -> ActionError {
261    ActionError::Refused(format!(
262        "an action payload may not use the key {CONTENT_REFERENCE_KEY}"
263    ))
264}
265
266fn holds_reserved(value: &Value) -> bool {
267    match value {
268        Value::Object(object) => {
269            object.contains_key(CONTENT_REFERENCE_KEY) || object.values().any(holds_reserved)
270        }
271        Value::Array(items) => items.iter().any(holds_reserved),
272        _ => false,
273    }
274}
275
276/// Keep each text or byte run of `value` that is at least `threshold` bytes
277/// as content, answering whether it kept one here or below.
278fn externalize(value: &mut Value, threshold: usize) -> Result<bool, ActionError> {
279    match value {
280        Value::String(text) if text.len() >= threshold => {
281            *value = reference(put_here(text.as_bytes())?, TEXT);
282            return Ok(true);
283        }
284        Value::Array(items) => {
285            if let Some(bytes) = byte_run(items).filter(|bytes| bytes.len() >= threshold) {
286                *value = reference(put_here(&bytes)?, BYTES);
287                return Ok(true);
288            }
289            let mut kept = false;
290            for item in items {
291                kept |= externalize(item, threshold)?;
292            }
293            if kept {
294                return Ok(true);
295            }
296        }
297        Value::Object(object) => {
298            let mut kept = false;
299            for item in object.values_mut() {
300                kept |= externalize(item, threshold)?;
301            }
302            if kept {
303                return Ok(true);
304            }
305        }
306        _ => return Ok(false),
307    }
308    // A long list of small parts is long all the same: kept whole, as it is,
309    // so its bytes follow from the action alone.
310    let encoded = serde_json::to_vec(value).map_err(ActionError::Encode)?;
311    if encoded.len() >= threshold {
312        *value = reference(put_here(&encoded)?, JSON);
313        return Ok(true);
314    }
315    Ok(false)
316}
317
318/// The reference and kind of a content reference.
319fn referenced(object: &Map<String, Value>) -> Option<(&str, &str)> {
320    if object.len() != 2 {
321        return None;
322    }
323    let reference = object.get(CONTENT_REFERENCE_KEY)?.as_str()?;
324    let kind = object.get(AS)?.as_str()?;
325    (tilo_content::valid_reference(reference) && matches!(kind, TEXT | BYTES | JSON))
326        .then_some((reference, kind))
327}
328
329fn collect(value: &Value, references: &mut Vec<String>) {
330    match value {
331        Value::Object(object) => match referenced(object) {
332            Some((reference, _)) => references.push(reference.to_owned()),
333            None => object.values().for_each(|item| collect(item, references)),
334        },
335        Value::Array(items) => items.iter().for_each(|item| collect(item, references)),
336        _ => {}
337    }
338}
339
340/// Collect into `parts` the bytes of `ran` each reference in `recorded`
341/// stands for; whether the two are otherwise the same.
342fn pair(recorded: &Value, ran: &Value, parts: &mut ContentParts) -> bool {
343    match (recorded, ran) {
344        (Value::Object(object), _) if referenced(object).is_some() => {
345            let Some((reference, kind)) = referenced(object) else {
346                return false;
347            };
348            let bytes = match (kind, ran) {
349                (TEXT, Value::String(text)) => text.as_bytes().to_vec(),
350                (BYTES, Value::Array(items)) => match byte_run(items) {
351                    Some(bytes) => bytes,
352                    None => return false,
353                },
354                (JSON, Value::Array(_) | Value::Object(_)) => match serde_json::to_vec(ran) {
355                    Ok(bytes) => bytes,
356                    Err(_) => return false,
357                },
358                _ => return false,
359            };
360            parts.push((reference.to_owned(), bytes));
361            true
362        }
363        (Value::Object(recorded), Value::Object(ran)) => {
364            recorded.len() == ran.len()
365                && recorded
366                    .iter()
367                    .all(|(key, item)| ran.get(key).is_some_and(|other| pair(item, other, parts)))
368        }
369        (Value::Array(recorded), Value::Array(ran)) => {
370            recorded.len() == ran.len()
371                && recorded
372                    .iter()
373                    .zip(ran)
374                    .all(|(item, other)| pair(item, other, parts))
375        }
376        _ => recorded == ran,
377    }
378}
379
380fn internalize(
381    value: &mut Value,
382    read: &dyn Fn(&str) -> Option<Vec<u8>>,
383) -> Result<(), MissingContent> {
384    match value {
385        Value::Object(object) => {
386            if let Some((named, kind)) = referenced(object) {
387                let missing = || MissingContent(named.to_owned());
388                let bytes = read(named)
389                    .filter(|bytes| tilo_content::names(named, bytes))
390                    .ok_or_else(missing)?;
391                *value = match kind {
392                    TEXT => Value::String(String::from_utf8(bytes).map_err(|_| missing())?),
393                    JSON => {
394                        let mut part: Value =
395                            serde_json::from_slice(&bytes).map_err(|_| missing())?;
396                        // A part an earlier version kept whole may hold
397                        // parts kept on their own.
398                        internalize(&mut part, read)?;
399                        part
400                    }
401                    _ => Value::Array(bytes.into_iter().map(Value::from).collect()),
402                };
403                return Ok(());
404            }
405            for item in object.values_mut() {
406                internalize(item, read)?;
407            }
408        }
409        Value::Array(items) => {
410            for item in items {
411                internalize(item, read)?;
412            }
413        }
414        _ => {}
415    }
416    Ok(())
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    fn action(payload: &Value) -> EncodedAction {
424        EncodedAction {
425            type_id: "note".into(),
426            payload: serde_json::to_vec(payload).unwrap(),
427        }
428    }
429
430    /// `action` as a window whose content store is `store` records it: its
431    /// parts kept, sealed, in that store.
432    fn recorded(action: &EncodedAction, store: &ContentStore) -> EncodedAction {
433        let window = tilo_wake::WakeScope::new();
434        register(&window.handle(), store.clone());
435        let _in_the_window = window.enter();
436        action.with_content_parts(CONTENT_PART_THRESHOLD).unwrap()
437    }
438
439    fn read(store: &ContentStore) -> impl Fn(&str) -> Option<Vec<u8>> + '_ {
440        |reference| store.read(reference)
441    }
442
443    /// A long list of small parts (a pasted book's paragraphs) is kept
444    /// whole and comes back exactly; the payload's own shape stays inline.
445    #[test]
446    fn a_long_list_of_small_parts_is_kept_whole() {
447        let paragraphs: Vec<Value> = (0..4_000)
448            .map(|n| serde_json::json!({ "kind": "paragraph", "text": format!("Paragraph {n}") }))
449            .collect();
450        let original = action(&serde_json::json!({ "paste": { "blocks": paragraphs }, "at": 1 }));
451        let store = ContentStore::memory().sealing();
452        let recorded = recorded(&original, &store);
453        assert!(recorded.payload.len() < 1024, "the payload names its parts");
454        let shape: Value = serde_json::from_slice(&recorded.payload).unwrap();
455        assert_eq!(shape["at"], 1);
456        assert_eq!(recorded.content_parts().len(), 1);
457        let resolved = recorded.resolve_content(&read(&store)).unwrap().unwrap();
458        let back: Value = serde_json::from_slice(&resolved.payload).unwrap();
459        let want: Value = serde_json::from_slice(&original.payload).unwrap();
460        assert_eq!(back, want);
461        assert!(recorded.recorded_parts_of(&original).is_some());
462    }
463
464    tilo_test_env::scenario! {
465        fn large_parts_of_an_action_are_kept_as_content;
466
467        phase large_parts_are_kept_sealed_and_resolve_back;
468        // Long text and byte runs leave the payload as sealed references and
469        // come back exactly; short values stay inline; a missing part holds.
470        {
471            let image: Vec<u8> = (0..40_000u32).map(|i| (i % 251) as u8).collect();
472            let original = action(&serde_json::json!({
473                "paste": { "text": "short", "body": "x".repeat(20_000), "image": image },
474                "count": 3,
475            }));
476            let store = ContentStore::memory().sealing();
477            let recorded = recorded(&original, &store);
478            assert!(recorded.payload.len() < 1024, "the payload names its parts");
479            let parts = recorded.content_parts();
480            assert_eq!(parts.len(), 2);
481            assert!(
482                parts
483                    .iter()
484                    .all(|reference| tilo_content::is_sealed(reference))
485            );
486            assert!(
487                !store.has(blake3::hash(&image).to_hex().as_ref()),
488                "nothing kept in the clear"
489            );
490            let resolved = recorded.resolve_content(&read(&store)).unwrap().unwrap();
491            let back: Value = serde_json::from_slice(&resolved.payload).unwrap();
492            let want: Value = serde_json::from_slice(&original.payload).unwrap();
493            assert_eq!(back, want);
494            assert_eq!(
495                recorded.resolve_content(&|_| None).unwrap(),
496                Err(MissingContent(parts[0].clone()))
497            );
498            // Other bytes than the reference names are not the content.
499            assert!(
500                recorded
501                    .resolve_content(&|_| Some(vec![1]))
502                    .unwrap()
503                    .is_err()
504            );
505        }
506
507        phase the_action_as_it_ran_yields_its_parts_exactly;
508        // A device holding the action as it ran finds, from the recorded form
509        // alone, each part's bytes, and keeps them exactly as the writer
510        // sealed them; a recorded form that is not of that action is refused.
511        {
512            let original = action(&serde_json::json!({ "body": "y".repeat(30_000), "at": 2 }));
513            let writer = ContentStore::memory().sealing();
514            let recorded = recorded(&original, &writer);
515            let parts = recorded.recorded_parts_of(&original).unwrap();
516            assert_eq!(parts.len(), 1);
517            let elsewhere = ContentStore::memory();
518            for (reference, bytes) in parts {
519                elsewhere.put_as(&reference, &bytes).unwrap();
520                assert_eq!(elsewhere.read(&reference), writer.read(&reference));
521            }
522            let other = action(&serde_json::json!({ "body": "z".repeat(30_000), "at": 2 }));
523            assert!(recorded.recorded_parts_of(&other).is_none());
524            let moved = action(&serde_json::json!({ "body": "y".repeat(30_000), "at": 3 }));
525            assert!(recorded.recorded_parts_of(&moved).is_none());
526            assert_eq!(
527                original.recorded_parts_of(&original),
528                Some(ContentParts::new())
529            );
530        }
531
532        phase the_reserved_key_is_refused_in_a_payload;
533        {
534            let forged =
535                action(&serde_json::json!({ "nested": { CONTENT_REFERENCE_KEY: "x", "as": "text" } }));
536            assert!(matches!(
537                forged.with_content_parts(CONTENT_PART_THRESHOLD),
538                Err(ActionError::Refused(_))
539            ));
540        }
541    }
542}