use super::{ActionCallError, Caller};
pub const RESOURCE_READS_UNAVAILABLE: &str = "this provider reads no records outside their apps";
pub const RESOURCE_READ_REFUSED: &str = "not allowed to read this record";
pub const RESOURCE_WRITE_REFUSED: &str = "not allowed to change this record";
pub const RESOURCE_READS_FOR_AGENTS: &str = "only a person, an app acting for its person, or an agent \
acting for the person who admitted it, reads records outside their app; a session a person's \
device handed to an agent reads nothing here";
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ResourceAddress {
pub workspace: String,
pub app: String,
pub record: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ListedResource {
pub address: ResourceAddress,
pub kind: Option<String>,
}
impl ListedResource {
#[must_use]
pub fn document(address: ResourceAddress) -> Self {
Self {
address,
kind: None,
}
}
#[must_use]
pub fn read_listing(workspace: &str, app: &str, listing: &serde_json::Value) -> Vec<Self> {
let text = |record: &serde_json::Value, key: &str| {
record
.get(key)
.and_then(serde_json::Value::as_str)
.map(str::to_owned)
};
listing
.get("records")
.and_then(serde_json::Value::as_array)
.into_iter()
.flatten()
.map(|record| Self {
address: ResourceAddress {
workspace: workspace.to_owned(),
app: text(record, "app").unwrap_or_else(|| app.to_owned()),
record: text(record, "record").unwrap_or_default(),
},
kind: text(record, "kind"),
})
.collect()
}
}
pub const DEVICE_SETTINGS: &str = "settings";
#[must_use]
pub fn device_record_space(device: &[u8; 32]) -> String {
format!("devices/{}", hex::encode(device))
}
pub const DEVICE_SETTINGS_REFUSED: &str = "Only this device's person, from any of their devices, and whoever they granted there, read \
its settings";
pub const DEVICE_JOBS: &str = "jobs";
#[must_use]
pub fn device_job_address(device: &[u8; 32], job: &str) -> ResourceAddress {
ResourceAddress {
workspace: device_record_space(device),
app: DEVICE_JOBS.to_owned(),
record: job.to_owned(),
}
}
#[must_use]
pub fn device_job_path(device: &[u8; 32], job: &str) -> String {
format!("devices/{}/jobs/{job}", hex::encode(device))
}
#[must_use]
pub fn parse_job_path(path: &str) -> Option<([u8; 32], String)> {
let (device, job) = path.strip_prefix("devices/")?.split_once("/jobs/")?;
if job.is_empty() || job.contains('/') || device.contains('/') {
return None;
}
let mut key = [0; 32];
hex::decode_to_slice(device, &mut key).ok()?;
Some((key, job.to_owned()))
}
#[must_use]
pub fn parse_device_record_space(space: &str) -> Option<[u8; 32]> {
let hex = space.strip_prefix("devices/")?;
if hex.len() != 64 || hex.contains('/') {
return None;
}
let mut key = [0; 32];
hex::decode_to_slice(hex, &mut key).ok()?;
Some(key)
}
#[must_use]
pub fn device_record_address(device: &[u8; 32], record: &str) -> ResourceAddress {
ResourceAddress {
workspace: device_record_space(device),
app: DEVICE_SETTINGS.to_owned(),
record: record.to_owned(),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResourceCopy {
Document(Vec<u8>),
Read(serde_json::Value),
Reading {
value: serde_json::Value,
revision: Option<String>,
},
Absent,
}
impl ResourceCopy {
#[must_use]
pub const fn reading(value: serde_json::Value, revision: Option<String>) -> Self {
Self::Reading { value, revision }
}
}
pub type Decided = Result<(), ActionCallError>;
pub type ReadsAnswer<'a, T> =
std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, ActionCallError>> + Send + 'a>>;
pub type ReadingAnswer =
std::pin::Pin<Box<dyn std::future::Future<Output = super::RemoteActionMessage> + Send>>;
pub fn reads_answer<'a, T>(
answer: impl std::future::Future<Output = Result<T, ActionCallError>> + Send + 'a,
) -> ReadsAnswer<'a, T> {
Box::pin(answer)
}
fn unavailable<'a, T: Send + 'a>() -> ReadsAnswer<'a, T> {
Box::pin(std::future::ready(Err(ActionCallError::Unavailable {
reason: RESOURCE_READS_UNAVAILABLE.into(),
})))
}
pub trait ResourceReads: Send + Sync {
fn read<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
) -> ReadsAnswer<'a, ResourceCopy> {
let _ = (caller, address);
unavailable()
}
fn may_read<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
) -> ReadsAnswer<'a, ()> {
Box::pin(async move { self.read(caller, address).await.map(|_| ()) })
}
fn may_write<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
) -> ReadsAnswer<'a, ()> {
Box::pin(async move { self.read(caller, address).await.map(|_| ()) })
}
fn answer_read(
self: std::sync::Arc<Self>,
caller: &Caller,
correlation: u64,
read: super::ResourceReadRequest,
) -> ReadingAnswer
where
Self: 'static,
{
Box::pin(answer_read(self, caller.clone(), correlation, read))
}
fn watch<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
wake: &'a ResourceWake,
) -> ReadsAnswer<'a, ()> {
let _ = (caller, address, wake);
unavailable()
}
fn list<'a>(
&'a self,
caller: &'a Caller,
workspace: &'a str,
app: &'a str,
) -> ReadsAnswer<'a, Vec<ListedResource>> {
let _ = (caller, workspace, app);
unavailable()
}
fn store_read<'a>(
&'a self,
caller: &'a Caller,
address: &'a ResourceAddress,
read: serde_json::Value,
) -> ReadsAnswer<'a, serde_json::Value> {
let _ = (caller, address, read);
unavailable()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HeldCopies(pub std::collections::HashMap<String, Vec<u8>>);
impl HeldCopies {
pub fn readable(
&self,
_caller: &Caller,
asks: &[ResourceAsk],
) -> Result<serde_json::Value, String> {
readings_of(asks, |address| Ok(self.held(address)))
.map_err(|error| error.to_string())?
.readable()
}
}
impl HeldCopies {
fn held(&self, address: &ResourceAddress) -> ResourceCopy {
self.0
.get(&address.record)
.map_or(ResourceCopy::Absent, |bytes| {
ResourceCopy::Document(bytes.clone())
})
}
}
impl ResourceReads for HeldCopies {
fn read<'a>(
&'a self,
_: &'a Caller,
address: &'a ResourceAddress,
) -> ReadsAnswer<'a, ResourceCopy> {
Box::pin(std::future::ready(Ok(self.held(address))))
}
fn watch<'a>(
&'a self,
_: &'a Caller,
_: &'a ResourceAddress,
_: &'a ResourceWake,
) -> ReadsAnswer<'a, ()> {
Box::pin(std::future::ready(Ok(())))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResourceAsk {
pub address: ResourceAddress,
pub joined: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResourceReadings {
pub revision: String,
pub records: Vec<(String, Option<ResourceCopy>)>,
}
pub fn readings_of(
asks: &[ResourceAsk],
mut read: impl FnMut(&ResourceAddress) -> Result<ResourceCopy, ActionCallError>,
) -> Result<ResourceReadings, ActionCallError> {
let mut walk = Walk::default();
for ask in asks {
let mut asking = Asking::of(ask);
while let Some(address) = asking.next() {
let copy = held(read(&address))?;
asking.took(&mut walk.revision, address, copy);
}
walk.records.extend(asking.answered());
}
Ok(walk.readings())
}
pub async fn readings_from<Read, Answer>(
asks: &[ResourceAsk],
mut read: Read,
) -> Result<ResourceReadings, ActionCallError>
where
Read: FnMut(ResourceAddress) -> Answer,
Answer: std::future::Future<Output = Result<ResourceCopy, ActionCallError>>,
{
let mut walk = Walk::default();
for ask in asks {
let mut asking = Asking::of(ask);
while let Some(address) = asking.next() {
let copy = held(read(address.clone()).await)?;
asking.took(&mut walk.revision, address, copy);
}
walk.records.extend(asking.answered());
}
Ok(walk.readings())
}
fn held(
read: Result<ResourceCopy, ActionCallError>,
) -> Result<Option<ResourceCopy>, ActionCallError> {
match read {
Ok(copy) => Ok(Some(copy)),
Err(ActionCallError::Unavailable { .. }) => Ok(None),
Err(error) => Err(error),
}
}
#[derive(Default)]
struct Walk {
revision: blake3::Hasher,
records: Vec<(String, Option<ResourceCopy>)>,
}
impl Walk {
fn readings(self) -> ResourceReadings {
ResourceReadings {
revision: self.revision.finalize().to_hex().to_string(),
records: self.records,
}
}
}
struct Asking<'a> {
ask: &'a ResourceAsk,
base: Option<&'a str>,
newest_only: bool,
part: u64,
done: bool,
held: Vec<(String, Option<ResourceCopy>)>,
}
impl<'a> Asking<'a> {
fn of(ask: &'a ResourceAsk) -> Self {
let newest = match crate::document_sync::document_sync(&ask.address.record) {
crate::document_sync::DocumentSync::ChainHead { base } if !ask.joined => Some(base),
_ => None,
};
let base = newest.or_else(|| ask.joined.then_some(ask.address.record.as_str()));
Self {
ask,
base,
newest_only: newest.is_some(),
part: 0,
done: false,
held: Vec::new(),
}
}
fn next(&self) -> Option<ResourceAddress> {
if self.done {
return None;
}
let record = match self.base {
Some(base) => crate::document_sync::document_part(base, self.part),
None => self.ask.address.record.clone(),
};
Some(ResourceAddress {
workspace: self.ask.address.workspace.clone(),
app: self.ask.address.app.clone(),
record,
})
}
fn took(
&mut self,
revision: &mut blake3::Hasher,
address: ResourceAddress,
copy: Option<ResourceCopy>,
) {
let chained = self.base.is_some();
let hashed;
let bytes: &[u8] = match © {
Some(ResourceCopy::Document(bytes)) => bytes,
Some(ResourceCopy::Reading {
revision: Some(revision),
..
}) => revision.as_bytes(),
Some(
ResourceCopy::Read(value)
| ResourceCopy::Reading {
value,
revision: None,
},
) => {
hashed = value.to_string();
hashed.as_bytes()
}
Some(ResourceCopy::Absent) => b"",
None => b"unavailable",
};
for bytes in [address.record.as_bytes(), bytes] {
revision.update(&(bytes.len() as u64).to_le_bytes());
revision.update(bytes);
}
let last = !chained || !matches!(copy, Some(ResourceCopy::Document(_)));
if !(chained && self.part > 0 && matches!(copy, Some(ResourceCopy::Absent))) {
self.held.push((address.record, copy));
}
if last {
self.done = true;
} else {
self.part = self.part.saturating_add(1);
}
}
fn answered(mut self) -> Vec<(String, Option<ResourceCopy>)> {
if self.newest_only
&& let Some(newest) = self
.held
.iter()
.rposition(|(_, copy)| matches!(copy, Some(ResourceCopy::Document(_))))
.or_else(|| self.held.len().checked_sub(1))
{
self.held = vec![self.held.swap_remove(newest)];
}
self.held
}
}
pub async fn read_resources<Reads: ResourceReads + ?Sized>(
reads: &Reads,
caller: &Caller,
asks: &[ResourceAsk],
after: Option<&str>,
deadline: tilo_clock::time::Instant,
) -> Result<ResourceReadings, ActionCallError> {
loop {
let (wake, woken) = ResourceWake::new();
let wake = &wake;
let readings = readings_from(asks, |address| async move {
reads.watch(caller, &address, wake).await?;
reads.read(caller, &address).await
})
.await?;
let now = tilo_clock::now();
if after != Some(readings.revision.as_str()) || now >= deadline {
return Ok(readings);
}
let mut woken = std::pin::pin!(woken);
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
let mut passed = std::pin::pin!(tilo_rt::sleep(deadline.saturating_duration_since(now)));
#[cfg(not(all(feature = "answer-reads", not(tilo_no_js))))]
let mut passed = std::pin::pin!(std::future::pending::<()>());
std::future::poll_fn(|cx| {
if woken.as_mut().poll(cx).is_ready() || passed.as_mut().poll(cx).is_ready() {
std::task::Poll::Ready(())
} else {
std::task::Poll::Pending
}
})
.await;
}
}
pub async fn answer_read<Reads: ResourceReads + ?Sized>(
reads: std::sync::Arc<Reads>,
caller: Caller,
correlation: u64,
read: super::ResourceReadRequest,
) -> super::RemoteActionMessage {
super::RemoteActionMessage::ResourceReading {
correlation,
result: serve_readings(reads.as_ref(), &caller, read).await,
}
}
pub async fn answered(
reads: std::sync::Arc<dyn ResourceReads>,
caller: &Caller,
read: super::ResourceReadRequest,
) -> Result<serde_json::Value, ActionCallError> {
match reads.answer_read(caller, 0, read).await {
super::RemoteActionMessage::ResourceReading { result, .. } => {
serde_json::from_str(&result?).map_err(|error| ActionCallError::Unavailable {
reason: format!("the reading does not read: {error}"),
})
}
_ => Err(ActionCallError::Unanswered),
}
}
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
pub(crate) fn answered_where_it_ends(
reading: ReadingAnswer,
) -> super::Pending<super::RemoteActionMessage> {
let (answer, answered) = super::pending();
let driven = std::sync::Arc::new(Driven {
slot: std::sync::Mutex::new(Slot::Held(Held { reading, answer })),
again: std::sync::atomic::AtomicBool::new(false),
});
driven.drive();
answered
}
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
enum Slot {
Held(Held),
Polling,
Done,
}
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
struct Held {
reading: ReadingAnswer,
answer: super::Completer<super::RemoteActionMessage>,
}
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
struct Driven {
slot: std::sync::Mutex<Slot>,
again: std::sync::atomic::AtomicBool,
}
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
impl Driven {
fn drive(self: &std::sync::Arc<Self>) {
use std::sync::atomic::Ordering;
use tilo_lock::MutexRecover as _;
loop {
let mut slot = self.slot.lock_recover();
let taken = std::mem::replace(&mut *slot, Slot::Polling);
drop(slot);
let held = match taken {
Slot::Held(held) => held,
Slot::Polling => {
self.again.store(true, Ordering::Release);
return;
}
Slot::Done => {
*self.slot.lock_recover() = Slot::Done;
return;
}
};
self.again.store(false, Ordering::Release);
let Held {
mut reading,
answer,
} = held;
let waker = std::task::Waker::from(std::sync::Arc::clone(self));
let mut context = std::task::Context::from_waker(&waker);
#[cfg(not(target_family = "wasm"))]
let polled = {
let runtime = tilo_rt::Handle::try_current()
.unwrap_or_else(|_| tilo_rt::app().handle().clone());
let _entered = runtime.enter();
reading.as_mut().poll(&mut context)
};
#[cfg(target_family = "wasm")]
let polled = reading.as_mut().poll(&mut context);
if let std::task::Poll::Ready(message) = polled {
*self.slot.lock_recover() = Slot::Done;
answer.complete(message);
return;
}
let mut slot = self.slot.lock_recover();
*slot = Slot::Held(Held { reading, answer });
let again = self.again.swap(false, Ordering::Acquire);
drop(slot);
if !again {
return;
}
}
}
}
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
impl std::task::Wake for Driven {
fn wake(self: std::sync::Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &std::sync::Arc<Self>) {
self.drive();
}
}
pub(crate) fn unanswered(correlation: u64) -> super::Pending<super::RemoteActionMessage> {
super::Pending::ready(super::RemoteActionMessage::ResourceReading {
correlation,
result: Err(ActionCallError::Unavailable {
reason: RESOURCE_READS_UNAVAILABLE.into(),
}),
})
}
async fn serve_readings<Reads: ResourceReads + ?Sized>(
reads: &Reads,
caller: &Caller,
read: super::ResourceReadRequest,
) -> Result<String, ActionCallError> {
let write = read.answer == super::ReadAnswer::WriteDecision;
if write || read.answer == super::ReadAnswer::Decision {
let address = ResourceAddress {
workspace: read.workspace,
app: read.app,
record: read.record,
};
let decided = if write {
reads.may_write(caller, &address).await
} else {
reads.may_read(caller, &address).await
};
return decided.map(|()| "null".to_owned());
}
if read.answer == super::ReadAnswer::Listing {
return listing(reads, caller, &read.workspace, &read.app).await;
}
let document = read.answer == super::ReadAnswer::Document;
let deadline = super::wait::deadline(read.wait_ms.unwrap_or(0));
let ask = [ResourceAsk {
address: ResourceAddress {
workspace: read.workspace,
app: read.app,
record: read.record,
},
joined: read.joined,
}];
let readings = read_resources(reads, caller, &ask, read.after.as_deref(), deadline).await?;
if document {
return Ok(readings.documents().to_string());
}
readings
.readable()
.map(|answer| answer.to_string())
.map_err(|reason| ActionCallError::Refused { reason })
}
async fn listing<Reads: ResourceReads + ?Sized>(
reads: &Reads,
caller: &Caller,
workspace: &str,
app: &str,
) -> Result<String, ActionCallError> {
let listed: Vec<serde_json::Value> = reads
.list(caller, workspace, app)
.await?
.into_iter()
.map(|listed| {
let mut entry = serde_json::Map::new();
entry.insert("app".into(), listed.address.app.into());
entry.insert("record".into(), listed.address.record.into());
if let Some(kind) = listed.kind {
entry.insert("kind".into(), kind.into());
}
serde_json::Value::Object(entry)
})
.collect();
Ok(serde_json::json!({ "records": listed }).to_string())
}
impl ResourceReadings {
#[must_use]
pub fn documents(self) -> serde_json::Value {
let records: Vec<serde_json::Value> = self
.records
.into_iter()
.map(|(record, copy)| match copy {
None => serde_json::json!({"record": record, "arriving": true}),
Some(ResourceCopy::Absent) => serde_json::json!({"record": record, "absent": true}),
Some(ResourceCopy::Document(bytes)) => {
serde_json::json!({"record": record, "document": hex::encode(bytes)})
}
Some(ResourceCopy::Read(value) | ResourceCopy::Reading { value, .. }) => {
serde_json::json!({"record": record, "value": value})
}
})
.collect();
serde_json::json!({"revision": self.revision, "records": records})
}
pub fn readable(self) -> Result<serde_json::Value, String> {
let mut records = Vec::with_capacity(self.records.len());
for (record, copy) in self.records {
records.push(match copy {
None => serde_json::json!({"record": record, "arriving": true}),
Some(ResourceCopy::Absent) => serde_json::json!({"record": record, "absent": true}),
Some(copy) => serde_json::json!({"record": record, "value": copy.readable()?}),
});
}
Ok(serde_json::json!({"revision": self.revision, "records": records}))
}
}
impl ResourceCopy {
pub fn readable(&self) -> Result<serde_json::Value, String> {
match self {
Self::Absent => Ok(serde_json::Value::Null),
Self::Read(value) | Self::Reading { value, .. } => Ok(value.clone()),
Self::Document(bytes) => {
#[cfg(feature = "document-read")]
{
let doc =
automerge::Automerge::load(bytes).map_err(|error| error.to_string())?;
let mut value = tilo_automerge::json::read_document(&doc)
.map_err(|error| error.to_string())?;
name_variant_fields(&mut value);
Ok(value)
}
#[cfg(not(feature = "document-read"))]
{
let _ = bytes;
Err("this build reads no record as a document".to_owned())
}
}
}
}
}
#[cfg(feature = "document-read")]
fn name_variant_fields(value: &mut serde_json::Value) {
match value {
serde_json::Value::Array(items) => items.iter_mut().for_each(name_variant_fields),
serde_json::Value::Object(map) => {
map.values_mut().for_each(name_variant_fields);
let Some(variant) = map.get("$variant").and_then(serde_json::Value::as_str) else {
return;
};
let prefix = format!(
"$field/{}/",
variant.replace('%', "%25").replace('/', "%2F")
);
let stored: Vec<String> = map
.keys()
.filter(|key| key.starts_with(&prefix))
.cloned()
.collect();
for key in stored {
if let Some(field) = map.remove(&key) {
let name = key
.get(prefix.len()..)
.unwrap_or_default()
.replace("%2F", "/")
.replace("%25", "%");
map.insert(name, field);
}
}
}
_ => {}
}
}
#[derive(Clone)]
pub struct ResourceWake(std::sync::Arc<std::sync::Mutex<Option<super::Completer<()>>>>);
impl ResourceWake {
#[must_use]
pub fn new() -> (Self, super::Pending<()>) {
let (woken, waiting) = super::pending();
(
Self(std::sync::Arc::new(std::sync::Mutex::new(Some(woken)))),
waiting,
)
}
pub fn wake(&self) {
if let Some(woken) = self.0.lock().ok().and_then(|mut woken| woken.take()) {
woken.complete(());
}
}
#[must_use]
pub fn waiting(&self) -> bool {
self.0
.lock()
.is_ok_and(|woken| woken.as_ref().is_some_and(|woken| !woken.is_abandoned()))
}
}
#[cfg(test)]
mod tests {
use automerge::transaction::Transactable as _;
use automerge::{AutoCommit, ObjType, ROOT};
use super::*;
fn message(text: &str) -> Vec<u8> {
let mut doc = AutoCommit::new();
let messages = doc.put_object(ROOT, "messages", ObjType::List).unwrap();
let first = doc.insert_object(&messages, 0, ObjType::Map).unwrap();
let body = doc.put_object(&first, "text", ObjType::Text).unwrap();
doc.splice_text(&body, 0, 0, text).unwrap();
doc.put(&first, "likes", automerge::ScalarValue::counter(2))
.unwrap();
doc.put(&first, "avatar", vec![1u8, 2, 3]).unwrap();
doc.save()
}
fn ask(record: &str, joined: bool) -> ResourceAsk {
ResourceAsk {
address: ResourceAddress {
workspace: "w".into(),
app: "so.tilo.chat".into(),
record: record.into(),
},
joined,
}
}
fn read_resources(
reads: &(impl ResourceReads + ?Sized),
caller: &Caller,
asks: &[ResourceAsk],
after: Option<&str>,
deadline: tilo_clock::time::Instant,
) -> Result<ResourceReadings, ActionCallError> {
tilo_rt::block_on(super::read_resources(reads, caller, asks, after, deadline)).unwrap()
}
fn values(readings: &ResourceReadings) -> Vec<(String, serde_json::Value)> {
readings
.records
.iter()
.map(|(record, copy)| (record.clone(), copy.as_ref().unwrap().readable().unwrap()))
.collect()
}
tilo_test_env::scenario! {
fn a_record_reads_as_plain_data;
phase a_record_reads_as_plain_data_with_its_text_counters_and_bytes;
{
let mut held = HeldCopies::default();
held.0.insert("note".into(), message("hello"));
let caller = Caller::local_person("me");
let now = tilo_clock::now();
let read = read_resources(
&held,
&caller,
&[ask("note", false), ask("gone", false)],
None,
now,
)
.unwrap();
assert_eq!(
values(&read),
[
(
"note".to_owned(),
serde_json::json!({"messages": [
{"text": "hello", "likes": 2, "avatar": {"bytes": 3}}
]})
),
("gone".to_owned(), serde_json::Value::Null),
]
);
}
phase a_data_enum_reads_with_its_fields_by_name;
{
let mut doc = AutoCommit::new();
let attached = doc.put_object(ROOT, "attached", ObjType::Map).unwrap();
doc.put(&attached, "$variant", "file").unwrap();
doc.put(&attached, "$field/file/blob", "ab").unwrap();
doc.put(&attached, "$field/file/a%2Fb", 3).unwrap();
assert_eq!(
ResourceCopy::Document(doc.save()).readable().unwrap(),
serde_json::json!({"attached": {"$variant": "file", "blob": "ab", "a/b": 3}})
);
}
phase a_rich_text_reads_as_its_paragraphs_in_their_order;
{
let mut doc = AutoCommit::new();
doc.put(ROOT, "title", "A poem").unwrap();
let body = doc.put_object(ROOT, "body", ObjType::Map).unwrap();
doc.put(&body, "schema", "tilo.richtext").unwrap();
let blocks = doc.put_object(&body, "blocks", ObjType::Map).unwrap();
for (id, place, kind, words) in [
("p1", vec![192_u8], "list_item", "and so are you"),
("p2", vec![64], "heading", "A poem"),
("p3", vec![128], "paragraph", "Roses are red"),
] {
let block = doc.put_object(&blocks, id, ObjType::Map).unwrap();
doc.put(&block, "order", place).unwrap();
doc.put(&block, "kind", kind).unwrap();
let text = doc.put_object(&block, "text", ObjType::Text).unwrap();
doc.splice_text(&text, 0, 0, words).unwrap();
}
assert_eq!(
ResourceCopy::Document(doc.save()).readable().unwrap(),
serde_json::json!({"title": "A poem", "body": {
"schema": "tilo.richtext",
"blocks": [
{"id": "p2", "kind": "heading", "text": "A poem"},
{"id": "p3", "kind": "paragraph", "text": "Roses are red"},
{"id": "p1", "kind": "list_item", "text": "and so are you"},
],
}})
);
}
phase a_chain_reads_joined_up_to_its_last_part_and_a_new_part_changes_its_revision;
{
let mut held = HeldCopies::default();
let part = |index| crate::document_sync::document_part("chain", index);
held.0.insert(part(0), message("first"));
held.0.insert(part(1), message("second"));
let caller = Caller::local_person("me");
let now = tilo_clock::now();
let read = read_resources(&held, &caller, &[ask("chain", true)], None, now).unwrap();
let texts: Vec<_> = values(&read)
.into_iter()
.map(|(record, value)| (record, value["messages"][0]["text"].clone()))
.collect();
assert_eq!(
texts,
[
(part(0), serde_json::json!("first")),
(part(1), serde_json::json!("second")),
]
);
let same = read_resources(&held, &caller, &[ask("chain", true)], None, now).unwrap();
assert_eq!(same.revision, read.revision);
held.0.insert(part(2), message("third"));
let grown = read_resources(
&held,
&caller,
&[ask("chain", true)],
Some(&read.revision),
now,
)
.unwrap();
assert_ne!(grown.revision, read.revision);
assert_eq!(grown.records.len(), 3);
let newest_part = crate::document_sync::chain_head("chain");
let newest = read_resources(&held, &caller, &[ask(&newest_part, false)], None, now).unwrap();
assert_eq!(
values(&newest),
[(
part(2),
serde_json::json!({"messages": [
{"text": "third", "likes": 2, "avatar": {"bytes": 3}}
]})
)]
);
held.0.insert(part(3), message("fourth"));
let moved = read_resources(&held, &caller, &[ask(&newest_part, false)], None, now).unwrap();
assert_ne!(moved.revision, newest.revision);
assert_eq!(moved.records[0].0, part(3));
}
phase a_reading_reads_as_its_json_and_a_change_wakes_the_follow;
{
struct Published {
value: std::sync::Mutex<serde_json::Value>,
revision: std::sync::Mutex<String>,
wakers: std::sync::Mutex<Vec<ResourceWake>>,
}
impl Published {
fn move_to(&self, value: serde_json::Value, revision: &str) {
*self.value.lock().unwrap() = value;
*self.revision.lock().unwrap() = revision.to_owned();
let woken = std::mem::take(&mut *self.wakers.lock().unwrap());
for wake in woken {
wake.wake();
}
}
}
impl ResourceReads for Published {
fn read<'a>(
&'a self,
_: &'a Caller,
_: &'a ResourceAddress,
) -> ReadsAnswer<'a, ResourceCopy> {
Box::pin(async move {
Ok(ResourceCopy::reading(
self.value.lock().unwrap().clone(),
Some(self.revision.lock().unwrap().clone()),
))
})
}
fn watch<'a>(
&'a self,
_: &'a Caller,
_: &'a ResourceAddress,
wake: &'a ResourceWake,
) -> ReadsAnswer<'a, ()> {
Box::pin(async move {
self.wakers.lock().unwrap().push(wake.clone());
Ok(())
})
}
}
let published = std::sync::Arc::new(Published {
value: std::sync::Mutex::new(serde_json::json!({"playing": false})),
revision: std::sync::Mutex::new("a".into()),
wakers: std::sync::Mutex::default(),
});
let caller = Caller::local_person("me");
let asks = [ResourceAsk {
address: ResourceAddress {
workspace: "w".into(),
app: "shell".into(),
record: "session:media".into(),
},
joined: false,
}];
let now = tilo_clock::now();
let read = read_resources(&*published, &caller, &asks, None, now).unwrap();
assert_eq!(
values(&read),
[(
"session:media".to_owned(),
serde_json::json!({"playing": false})
)],
"a reading reads as the JSON its provider publishes"
);
assert!(!read.revision.is_empty(), "the reading has a revision");
published.wakers.lock().unwrap().clear();
let changed = std::thread::scope(|scope| {
let waiting = scope.spawn(|| {
read_resources(
&*published,
&caller,
&asks,
Some(&read.revision),
tilo_clock::now()
.checked_add(std::time::Duration::from_secs(30))
.unwrap(),
)
});
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
if published.wakers.lock().unwrap().is_empty() {
assert!(
std::time::Instant::now() < deadline,
"the follow watched nothing"
);
std::thread::yield_now();
continue;
}
break;
}
published.move_to(serde_json::json!({"playing": true}), "b");
waiting.join().expect("the follow")
})
.unwrap();
assert_eq!(
values(&changed),
[(
"session:media".to_owned(),
serde_json::json!({"playing": true})
)],
"the change woke the follow, which read the new reading"
);
assert_ne!(changed.revision, read.revision);
}
phase a_reading_its_provider_names_no_revision_for_is_hashed_by_its_json;
{
struct Unversioned(std::sync::Mutex<serde_json::Value>);
impl ResourceReads for Unversioned {
fn read<'a>(
&'a self,
_: &'a Caller,
_: &'a ResourceAddress,
) -> ReadsAnswer<'a, ResourceCopy> {
Box::pin(async move {
Ok(ResourceCopy::reading(
self.0.lock().unwrap().clone(),
None,
))
})
}
fn watch<'a>(
&'a self,
_: &'a Caller,
_: &'a ResourceAddress,
_: &'a ResourceWake,
) -> ReadsAnswer<'a, ()> {
Box::pin(async move {
Ok(())
})
}
}
let published = Unversioned(std::sync::Mutex::new(serde_json::json!({"level": 1})));
let caller = Caller::local_person("me");
let asks = [ask("session:volume", false)];
let now = tilo_clock::now();
let first = read_resources(&published, &caller, &asks, None, now).unwrap();
let again = read_resources(&published, &caller, &asks, None, now).unwrap();
assert_eq!(first.revision, again.revision, "the same JSON is one revision");
*published.0.lock().unwrap() = serde_json::json!({"level": 2});
let moved = read_resources(&published, &caller, &asks, None, now).unwrap();
assert_ne!(moved.revision, first.revision, "another JSON is another");
}
}
}