1#[cfg(any(test, feature = "test-support"))]
19pub use tilo_actions::content::register_for_resources;
20pub use tilo_actions::content::{current, register};
23
24#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
26pub enum ContentRefusal {
27 #[error(
29 "{0:?} is not a content reference: give the tilo.content:<hash> a put or another step answered"
30 )]
31 NotAReference(String),
32 #[error("this window has no content store to read {0} from")]
34 NoStore(String),
35 #[error("{0} cannot be read here: this window's content store does not name a workspace")]
38 NotInWorkspace(String),
39 #[error("{0} is not readable in this workspace: put the content into this workspace first")]
42 NotReadable(String),
43}
44
45#[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#[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
68pub 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
86pub 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 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
110pub(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
121pub(crate) fn is_invoking() -> bool {
123 INVOKING.with(std::cell::Cell::get)
124}
125
126thread_local! {
127 static GIVEN: std::cell::RefCell<std::collections::HashMap<String, String>> =
130 std::cell::RefCell::new(std::collections::HashMap::new());
131}
132
133pub 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
148pub(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 #[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 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 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 #[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}