Skip to main content

tilo_resource/
content.rs

1//! The content store of the window whose code is running.
2//!
3//! A record names its binaries (a picture, an attachment) by hash; the bytes
4//! live in the content store the host lends the window, joined to the
5//! record's route. Every window has its own: two windows of one app in two
6//! workspaces — in one process, as the shell mounts apps — keep their content
7//! apart. The host registers a window's store against the window's wake
8//! scope ([`register`]), the scope the toolkit enters whenever it runs the
9//! window's code; [`current`] answers the store of the scope entered now.
10//!
11//! That is how code no view reaches gets it: an action's arguments being
12//! built where it is invoked, the window's views and handlers, and the large
13//! parts of a recorded action ([`tilo_actions::content`]), which are kept in
14//! the same store and read back from it. Work that leaves the window's thread
15//! captures the store when it starts, as it captures its wake handle.
16
17/// A store of this thread's own, for a replica that runs without a window.
18#[cfg(any(test, feature = "test-support"))]
19pub use tilo_actions::content::register_for_resources;
20/// The one registry of window content stores: it lives beside the recorded
21/// actions that keep their parts in them.
22pub use tilo_actions::content::{current, register};
23
24/// Why a content reference an action was given does not resolve here.
25#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
26pub enum ContentRefusal {
27    /// The value is no `tilo.content:<hash>` reference.
28    #[error(
29        "{0:?} is not a content reference: give the tilo.content:<hash> a put or another step answered"
30    )]
31    NotAReference(String),
32    /// No window runs, or its host lent it no store.
33    #[error("this window has no content store to read {0} from")]
34    NoStore(String),
35    /// The window's store is not a workspace's, so a hash would name content
36    /// from anywhere on this machine.
37    #[error("{0} cannot be read here: this window's content store does not name a workspace")]
38    NotInWorkspace(String),
39    /// The workspace does not reference the content, or this device does not
40    /// hold it.
41    #[error("{0} is not readable in this workspace: put the content into this workspace first")]
42    NotReadable(String),
43}
44
45/// The content reference a `tilo.content:<reference>` names, when `value` is one.
46#[must_use]
47pub fn reference_hash(value: &str) -> Option<&str> {
48    tilo_actions::content_hash(value.trim()).filter(|hash| tilo_content::valid_reference(hash))
49}
50
51/// The content reference `value` names, as a content store reads it: a
52/// `tilo.content:<reference>` address, the reference alone, or a kept
53/// value's stored form (`blake3:<hex>:<len>[:<reference>]`). Its address is
54/// lower case; a sealed reference keeps its key. `None` for anything else.
55#[must_use]
56pub fn named(value: &str) -> Option<String> {
57    let value = value.trim();
58    let reference = tilo_actions::named_reference(value)
59        .map(str::to_owned)
60        .or_else(|| {
61            <crate::Bytes as crate::model::Model>::from_json(&value.into())
62                .ok()?
63                .reference()
64        })?;
65    tilo_content::ContentRef::parse(&reference).map(|parsed| parsed.to_string())
66}
67
68/// The bytes the content reference `address` names, read from the store of
69/// the window whose code is running.
70///
71/// A hash is never a capability by itself: only a store that answers for
72/// one workspace ([`tilo_content::ContentStore::workspace_scoped`]) resolves
73/// a reference, and it serves an address only when that workspace references
74/// it. So a caller can name only content readable in the workspace it acts
75/// in.
76///
77/// # Errors
78///
79/// A [`ContentRefusal`] saying why, in words for whoever passed it.
80pub fn read_reference(address: &str) -> Result<Vec<u8>, ContentRefusal> {
81    let hash =
82        reference_hash(address).ok_or_else(|| ContentRefusal::NotAReference(address.to_owned()))?;
83    read_hash(hash)
84}
85
86/// [`read_reference`] for the hash itself, for a caller that accepted it in
87/// another spelling.
88///
89/// # Errors
90///
91/// As [`read_reference`].
92pub fn read_hash(hash: &str) -> Result<Vec<u8>, ContentRefusal> {
93    let named = tilo_actions::content_resource(hash).unwrap_or_else(|| hash.to_owned());
94    if !tilo_content::valid_reference(hash) {
95        return Err(ContentRefusal::NotAReference(named));
96    }
97    let store = current().ok_or_else(|| ContentRefusal::NoStore(named.clone()))?;
98    if !store.workspace_scoped() {
99        return Err(ContentRefusal::NotInWorkspace(named));
100    }
101    // The store verifies what it reads against the address, and opens
102    // sealed content with the reference's key.
103    store.read(hash).ok_or(ContentRefusal::NotReadable(named))
104}
105
106thread_local! {
107    static INVOKING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
108}
109
110/// Run `build` as the side invoking an action builds it from its arguments:
111/// the data a [`Bytes`](crate::Bytes) argument carries is kept, sealed, in
112/// the window's store there, and the action carries the reference. Where an
113/// action replays, its arguments already are references.
114pub(crate) fn invoking<T>(build: impl FnOnce() -> T) -> T {
115    let before = INVOKING.with(|invoking| invoking.replace(true));
116    let action = build();
117    INVOKING.with(|invoking| invoking.set(before));
118    action
119}
120
121/// Whether an action is being built where it is invoked ([`invoking`]).
122pub(crate) fn is_invoking() -> bool {
123    INVOKING.with(std::cell::Cell::get)
124}
125
126thread_local! {
127    /// What the workspace said of the sealed content an operation is given
128    /// ([`given`]): the stored form of each reference it keeps already.
129    static GIVEN: std::cell::RefCell<std::collections::HashMap<String, String>> =
130        std::cell::RefCell::new(std::collections::HashMap::new());
131}
132
133/// Call `build` with the value of the sealed content the workspace keeps already,
134/// in the stored form a [`Bytes`](crate::Bytes) keeps: the hash, the length and
135/// the reference that opens it. An argument naming one of these references
136/// is then taken by reference, and none of its bytes is handed over for it.
137/// The content is read where it is kept; the window never holds what an
138/// operation only names.
139pub fn given<T>(stored: &[(String, String)], build: impl FnOnce() -> T) -> T {
140    let before = GIVEN.with(|given| {
141        std::mem::replace(&mut *given.borrow_mut(), stored.iter().cloned().collect())
142    });
143    let made = build();
144    GIVEN.with(|given| *given.borrow_mut() = before);
145    made
146}
147
148/// The value the sealed content `reference` names, as the service that told
149/// of it keeps it (`blake3:<hash>:<len>:<reference>`): `None`
150/// where it did not.
151pub(crate) fn given_form(reference: &str) -> Option<String> {
152    GIVEN.with(|given| given.borrow().get(reference).cloned())
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use tilo_content::ContentStore;
159
160    #[test]
161    fn each_window_reads_its_own_store() {
162        let (one, two) = (tilo_wake::WakeScope::new(), tilo_wake::WakeScope::new());
163        let (first, second) = (ContentStore::memory(), ContentStore::memory());
164        register(&one.handle(), first.clone());
165        register(&two.handle(), second);
166        let hash = first.put(b"in the first window").unwrap();
167        assert!(current().is_none(), "no window runs");
168        {
169            let _entered = one.enter();
170            assert!(current().unwrap().has(&hash));
171        }
172        {
173            let _entered = two.enter();
174            assert!(!current().unwrap().has(&hash));
175        }
176    }
177
178    fn decode(value: serde_json::Value) -> Result<crate::Bytes, String> {
179        serde_json::from_value(value).map_err(|error| error.to_string())
180    }
181
182    /// Where an action is invoked, data its argument carries inline, or by a
183    /// reference to content the window's workspace holds, is kept sealed in
184    /// the window's store and named by its reference; any other hash is
185    /// refused. Where it replays, its stored form is read as it is.
186    #[test]
187    fn a_bytes_argument_is_kept_sealed_where_the_action_is_invoked() {
188        let window = tilo_wake::WakeScope::new();
189        let workspace = ContentStore::memory_in_workspace().sealing();
190        register(&window.handle(), workspace.clone());
191        let picture = vec![9_u8; 4096];
192        let held = workspace.put(&picture).unwrap();
193        let reference = tilo_actions::content_resource(&held).unwrap();
194        let elsewhere = tilo_content::hash_bytes(b"content kept elsewhere");
195        let _entered = window.enter();
196
197        assert_eq!(
198            invoking(|| decode(serde_json::json!([1, 2, 3]))).unwrap(),
199            crate::Bytes::Inline(vec![1, 2, 3])
200        );
201        let kept = invoking(|| decode(serde_json::json!(picture))).unwrap();
202        let sealed = kept.reference().unwrap();
203        assert!(tilo_content::is_sealed(&sealed), "{sealed}");
204        assert_eq!(kept.read(&workspace), Some(picture.clone()));
205        assert!(
206            !workspace.has(&tilo_content::hash_bytes(&picture)),
207            "never kept in the clear"
208        );
209        let named = invoking(|| decode(serde_json::json!(reference))).unwrap();
210        assert_eq!(named.reference().as_deref(), Some(held.as_str()));
211        assert_eq!(named.hash(), *blake3::hash(&picture).as_bytes());
212
213        // The reference alone names the same content: an operation that
214        // collects content takes a bare reference, sealed or plain, and the
215        // hash content was named by before it was sealed still reads where
216        // the bytes were kept so.
217        let bare = invoking(|| decode(serde_json::json!(held))).unwrap();
218        assert_eq!(bare.hash(), *blake3::hash(&picture).as_bytes());
219        assert_eq!(bare.read(&workspace), Some(picture.clone()));
220        let plain = ContentStore::memory_in_workspace();
221        let plain_hash = plain.put(b"kept in the clear").unwrap();
222        register(&window.handle(), plain.clone());
223        let earlier = invoking(|| decode(serde_json::json!(plain_hash))).unwrap();
224        assert_eq!(earlier.read(&plain), Some(b"kept in the clear".to_vec()));
225
226        let missing = format!("tilo.content:{elsewhere}");
227        let refused = invoking(|| decode(serde_json::json!(missing.clone()))).unwrap_err();
228        assert!(
229            refused.contains(&ContentRefusal::NotReadable(missing).to_string()),
230            "{refused}"
231        );
232
233        // Replaying, the stored form reads back as it is; a reference to
234        // read is no stored form, and inline data is an earlier version's.
235        let stored = serde_json::to_value(&kept).unwrap();
236        assert_eq!(decode(stored).unwrap(), kept);
237        assert!(decode(serde_json::json!(reference)).is_err());
238        assert_eq!(
239            decode(serde_json::json!(picture)).unwrap(),
240            crate::Bytes::of(&picture)
241        );
242    }
243
244    /// A store that is not a workspace's resolves no reference, even to
245    /// content it holds: a hash is never a capability by itself.
246    #[test]
247    fn a_store_outside_a_workspace_resolves_no_reference() {
248        let window = tilo_wake::WakeScope::new();
249        let machine = ContentStore::memory();
250        register(&window.handle(), machine.clone());
251        let held = machine.put(b"on this machine").unwrap();
252        let reference = tilo_actions::content_resource(&held).unwrap();
253        assert_eq!(
254            read_reference(&reference),
255            Err(ContentRefusal::NoStore(reference.clone())),
256            "outside the window"
257        );
258        let _entered = window.enter();
259        assert_eq!(
260            read_reference(&reference),
261            Err(ContentRefusal::NotInWorkspace(reference.clone()))
262        );
263    }
264}