#[cfg(any(test, feature = "test-support"))]
pub use tilo_actions::content::register_for_resources;
pub use tilo_actions::content::{current, register};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ContentRefusal {
#[error(
"{0:?} is not a content reference: give the tilo.content:<hash> a put or another step answered"
)]
NotAReference(String),
#[error("this window has no content store to read {0} from")]
NoStore(String),
#[error("{0} cannot be read here: this window's content store does not name a workspace")]
NotInWorkspace(String),
#[error("{0} is not readable in this workspace: put the content into this workspace first")]
NotReadable(String),
}
#[must_use]
pub fn reference_hash(value: &str) -> Option<&str> {
tilo_actions::content_hash(value.trim()).filter(|hash| tilo_content::valid_reference(hash))
}
#[must_use]
pub fn named(value: &str) -> Option<String> {
let value = value.trim();
let reference = tilo_actions::named_reference(value)
.map(str::to_owned)
.or_else(|| {
<crate::Bytes as crate::model::Model>::from_json(&value.into())
.ok()?
.reference()
})?;
tilo_content::ContentRef::parse(&reference).map(|parsed| parsed.to_string())
}
pub fn read_reference(address: &str) -> Result<Vec<u8>, ContentRefusal> {
let hash =
reference_hash(address).ok_or_else(|| ContentRefusal::NotAReference(address.to_owned()))?;
read_hash(hash)
}
pub fn read_hash(hash: &str) -> Result<Vec<u8>, ContentRefusal> {
let named = tilo_actions::content_resource(hash).unwrap_or_else(|| hash.to_owned());
if !tilo_content::valid_reference(hash) {
return Err(ContentRefusal::NotAReference(named));
}
let store = current().ok_or_else(|| ContentRefusal::NoStore(named.clone()))?;
if !store.workspace_scoped() {
return Err(ContentRefusal::NotInWorkspace(named));
}
store.read(hash).ok_or(ContentRefusal::NotReadable(named))
}
thread_local! {
static INVOKING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn invoking<T>(build: impl FnOnce() -> T) -> T {
let before = INVOKING.with(|invoking| invoking.replace(true));
let action = build();
INVOKING.with(|invoking| invoking.set(before));
action
}
pub(crate) fn is_invoking() -> bool {
INVOKING.with(std::cell::Cell::get)
}
thread_local! {
static GIVEN: std::cell::RefCell<std::collections::HashMap<String, String>> =
std::cell::RefCell::new(std::collections::HashMap::new());
}
pub fn given<T>(stored: &[(String, String)], build: impl FnOnce() -> T) -> T {
let before = GIVEN.with(|given| {
std::mem::replace(&mut *given.borrow_mut(), stored.iter().cloned().collect())
});
let made = build();
GIVEN.with(|given| *given.borrow_mut() = before);
made
}
pub(crate) fn given_form(reference: &str) -> Option<String> {
GIVEN.with(|given| given.borrow().get(reference).cloned())
}
#[cfg(test)]
mod tests {
use super::*;
use tilo_content::ContentStore;
#[test]
fn each_window_reads_its_own_store() {
let (one, two) = (tilo_wake::WakeScope::new(), tilo_wake::WakeScope::new());
let (first, second) = (ContentStore::memory(), ContentStore::memory());
register(&one.handle(), first.clone());
register(&two.handle(), second);
let hash = first.put(b"in the first window").unwrap();
assert!(current().is_none(), "no window runs");
{
let _entered = one.enter();
assert!(current().unwrap().has(&hash));
}
{
let _entered = two.enter();
assert!(!current().unwrap().has(&hash));
}
}
fn decode(value: serde_json::Value) -> Result<crate::Bytes, String> {
serde_json::from_value(value).map_err(|error| error.to_string())
}
#[test]
fn a_bytes_argument_is_kept_sealed_where_the_action_is_invoked() {
let window = tilo_wake::WakeScope::new();
let workspace = ContentStore::memory_in_workspace().sealing();
register(&window.handle(), workspace.clone());
let picture = vec![9_u8; 4096];
let held = workspace.put(&picture).unwrap();
let reference = tilo_actions::content_resource(&held).unwrap();
let elsewhere = tilo_content::hash_bytes(b"content kept elsewhere");
let _entered = window.enter();
assert_eq!(
invoking(|| decode(serde_json::json!([1, 2, 3]))).unwrap(),
crate::Bytes::Inline(vec![1, 2, 3])
);
let kept = invoking(|| decode(serde_json::json!(picture))).unwrap();
let sealed = kept.reference().unwrap();
assert!(tilo_content::is_sealed(&sealed), "{sealed}");
assert_eq!(kept.read(&workspace), Some(picture.clone()));
assert!(
!workspace.has(&tilo_content::hash_bytes(&picture)),
"never kept in the clear"
);
let named = invoking(|| decode(serde_json::json!(reference))).unwrap();
assert_eq!(named.reference().as_deref(), Some(held.as_str()));
assert_eq!(named.hash(), *blake3::hash(&picture).as_bytes());
let bare = invoking(|| decode(serde_json::json!(held))).unwrap();
assert_eq!(bare.hash(), *blake3::hash(&picture).as_bytes());
assert_eq!(bare.read(&workspace), Some(picture.clone()));
let plain = ContentStore::memory_in_workspace();
let plain_hash = plain.put(b"kept in the clear").unwrap();
register(&window.handle(), plain.clone());
let earlier = invoking(|| decode(serde_json::json!(plain_hash))).unwrap();
assert_eq!(earlier.read(&plain), Some(b"kept in the clear".to_vec()));
let missing = format!("tilo.content:{elsewhere}");
let refused = invoking(|| decode(serde_json::json!(missing.clone()))).unwrap_err();
assert!(
refused.contains(&ContentRefusal::NotReadable(missing).to_string()),
"{refused}"
);
let stored = serde_json::to_value(&kept).unwrap();
assert_eq!(decode(stored).unwrap(), kept);
assert!(decode(serde_json::json!(reference)).is_err());
assert_eq!(
decode(serde_json::json!(picture)).unwrap(),
crate::Bytes::of(&picture)
);
}
#[test]
fn a_store_outside_a_workspace_resolves_no_reference() {
let window = tilo_wake::WakeScope::new();
let machine = ContentStore::memory();
register(&window.handle(), machine.clone());
let held = machine.put(b"on this machine").unwrap();
let reference = tilo_actions::content_resource(&held).unwrap();
assert_eq!(
read_reference(&reference),
Err(ContentRefusal::NoStore(reference.clone())),
"outside the window"
);
let _entered = window.enter();
assert_eq!(
read_reference(&reference),
Err(ContentRefusal::NotInWorkspace(reference.clone()))
);
}
}