1use super::{ActionCallError, Caller};
19
20pub const RESOURCE_READS_UNAVAILABLE: &str = "this provider reads no records outside their apps";
22
23pub const RESOURCE_READ_REFUSED: &str = "not allowed to read this record";
25
26pub const RESOURCE_WRITE_REFUSED: &str = "not allowed to change this record";
28
29pub const RESOURCE_READS_FOR_AGENTS: &str = "only a person, an app acting for its person, or an agent \
31 acting for the person who admitted it, reads records outside their app; a session a person's \
32 device handed to an agent reads nothing here";
33
34#[derive(Clone, Debug, PartialEq, Eq, Hash)]
37pub struct ResourceAddress {
38 pub workspace: String,
39 pub app: String,
40 pub record: String,
41}
42
43#[derive(Clone, Debug, PartialEq, Eq, Hash)]
47pub struct ListedResource {
48 pub address: ResourceAddress,
49 pub kind: Option<String>,
50}
51
52impl ListedResource {
53 #[must_use]
55 pub fn document(address: ResourceAddress) -> Self {
56 Self {
57 address,
58 kind: None,
59 }
60 }
61
62 #[must_use]
65 pub fn read_listing(workspace: &str, app: &str, listing: &serde_json::Value) -> Vec<Self> {
66 let text = |record: &serde_json::Value, key: &str| {
67 record
68 .get(key)
69 .and_then(serde_json::Value::as_str)
70 .map(str::to_owned)
71 };
72 listing
73 .get("records")
74 .and_then(serde_json::Value::as_array)
75 .into_iter()
76 .flatten()
77 .map(|record| Self {
78 address: ResourceAddress {
79 workspace: workspace.to_owned(),
80 app: text(record, "app").unwrap_or_else(|| app.to_owned()),
81 record: text(record, "record").unwrap_or_default(),
82 },
83 kind: text(record, "kind"),
84 })
85 .collect()
86 }
87}
88
89pub const DEVICE_SETTINGS: &str = "settings";
92
93#[must_use]
102pub fn device_record_space(device: &[u8; 32]) -> String {
103 format!("devices/{}", hex::encode(device))
104}
105
106pub const DEVICE_SETTINGS_REFUSED: &str = "Only this device's person, from any of their devices, and whoever they granted there, read \
108 its settings";
109
110pub const DEVICE_JOBS: &str = "jobs";
114
115#[must_use]
118pub fn device_job_address(device: &[u8; 32], job: &str) -> ResourceAddress {
119 ResourceAddress {
120 workspace: device_record_space(device),
121 app: DEVICE_JOBS.to_owned(),
122 record: job.to_owned(),
123 }
124}
125
126#[must_use]
129pub fn device_job_path(device: &[u8; 32], job: &str) -> String {
130 format!("devices/{}/jobs/{job}", hex::encode(device))
131}
132
133#[must_use]
137pub fn parse_job_path(path: &str) -> Option<([u8; 32], String)> {
138 let (device, job) = path.strip_prefix("devices/")?.split_once("/jobs/")?;
139 if job.is_empty() || job.contains('/') || device.contains('/') {
140 return None;
141 }
142 let mut key = [0; 32];
143 hex::decode_to_slice(device, &mut key).ok()?;
144 Some((key, job.to_owned()))
145}
146
147#[must_use]
150pub fn parse_device_record_space(space: &str) -> Option<[u8; 32]> {
151 let hex = space.strip_prefix("devices/")?;
152 if hex.len() != 64 || hex.contains('/') {
153 return None;
154 }
155 let mut key = [0; 32];
156 hex::decode_to_slice(hex, &mut key).ok()?;
157 Some(key)
158}
159
160#[must_use]
163pub fn device_record_address(device: &[u8; 32], record: &str) -> ResourceAddress {
164 ResourceAddress {
165 workspace: device_record_space(device),
166 app: DEVICE_SETTINGS.to_owned(),
167 record: record.to_owned(),
168 }
169}
170
171#[derive(Clone, Debug, PartialEq, Eq)]
173pub enum ResourceCopy {
174 Document(Vec<u8>),
176 Read(serde_json::Value),
180 Reading {
185 value: serde_json::Value,
186 revision: Option<String>,
187 },
188 Absent,
190}
191
192impl ResourceCopy {
193 #[must_use]
195 pub const fn reading(value: serde_json::Value, revision: Option<String>) -> Self {
196 Self::Reading { value, revision }
197 }
198}
199
200pub type Decided = Result<(), ActionCallError>;
203
204pub type ReadsAnswer<'a, T> =
207 std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, ActionCallError>> + Send + 'a>>;
208
209pub type ReadingAnswer =
211 std::pin::Pin<Box<dyn std::future::Future<Output = super::RemoteActionMessage> + Send>>;
212
213pub fn reads_answer<'a, T>(
216 answer: impl std::future::Future<Output = Result<T, ActionCallError>> + Send + 'a,
217) -> ReadsAnswer<'a, T> {
218 Box::pin(answer)
219}
220
221fn unavailable<'a, T: Send + 'a>() -> ReadsAnswer<'a, T> {
223 Box::pin(std::future::ready(Err(ActionCallError::Unavailable {
224 reason: RESOURCE_READS_UNAVAILABLE.into(),
225 })))
226}
227
228pub trait ResourceReads: Send + Sync {
230 fn read<'a>(
243 &'a self,
244 caller: &'a Caller,
245 address: &'a ResourceAddress,
246 ) -> ReadsAnswer<'a, ResourceCopy> {
247 let _ = (caller, address);
248 unavailable()
249 }
250
251 fn may_read<'a>(
255 &'a self,
256 caller: &'a Caller,
257 address: &'a ResourceAddress,
258 ) -> ReadsAnswer<'a, ()> {
259 Box::pin(async move { self.read(caller, address).await.map(|_| ()) })
260 }
261
262 fn may_write<'a>(
268 &'a self,
269 caller: &'a Caller,
270 address: &'a ResourceAddress,
271 ) -> ReadsAnswer<'a, ()> {
272 Box::pin(async move { self.read(caller, address).await.map(|_| ()) })
273 }
274
275 fn answer_read(
285 self: std::sync::Arc<Self>,
286 caller: &Caller,
287 correlation: u64,
288 read: super::ResourceReadRequest,
289 ) -> ReadingAnswer
290 where
291 Self: 'static,
292 {
293 Box::pin(answer_read(self, caller.clone(), correlation, read))
294 }
295
296 fn watch<'a>(
305 &'a self,
306 caller: &'a Caller,
307 address: &'a ResourceAddress,
308 wake: &'a ResourceWake,
309 ) -> ReadsAnswer<'a, ()> {
310 let _ = (caller, address, wake);
311 unavailable()
312 }
313
314 fn list<'a>(
322 &'a self,
323 caller: &'a Caller,
324 workspace: &'a str,
325 app: &'a str,
326 ) -> ReadsAnswer<'a, Vec<ListedResource>> {
327 let _ = (caller, workspace, app);
328 unavailable()
329 }
330
331 fn store_read<'a>(
342 &'a self,
343 caller: &'a Caller,
344 address: &'a ResourceAddress,
345 read: serde_json::Value,
346 ) -> ReadsAnswer<'a, serde_json::Value> {
347 let _ = (caller, address, read);
348 unavailable()
349 }
350}
351
352#[derive(Clone, Debug, Default, PartialEq, Eq)]
355pub struct HeldCopies(pub std::collections::HashMap<String, Vec<u8>>);
356
357impl HeldCopies {
358 pub fn readable(
365 &self,
366 _caller: &Caller,
367 asks: &[ResourceAsk],
368 ) -> Result<serde_json::Value, String> {
369 readings_of(asks, |address| Ok(self.held(address)))
370 .map_err(|error| error.to_string())?
371 .readable()
372 }
373}
374
375impl HeldCopies {
376 fn held(&self, address: &ResourceAddress) -> ResourceCopy {
378 self.0
379 .get(&address.record)
380 .map_or(ResourceCopy::Absent, |bytes| {
381 ResourceCopy::Document(bytes.clone())
382 })
383 }
384}
385
386impl ResourceReads for HeldCopies {
387 fn read<'a>(
388 &'a self,
389 _: &'a Caller,
390 address: &'a ResourceAddress,
391 ) -> ReadsAnswer<'a, ResourceCopy> {
392 Box::pin(std::future::ready(Ok(self.held(address))))
393 }
394
395 fn watch<'a>(
396 &'a self,
397 _: &'a Caller,
398 _: &'a ResourceAddress,
399 _: &'a ResourceWake,
400 ) -> ReadsAnswer<'a, ()> {
401 Box::pin(std::future::ready(Ok(())))
402 }
403}
404
405#[derive(Clone, Debug, PartialEq, Eq)]
410pub struct ResourceAsk {
411 pub address: ResourceAddress,
412 pub joined: bool,
413}
414
415#[derive(Clone, Debug, PartialEq, Eq)]
419pub struct ResourceReadings {
420 pub revision: String,
421 pub records: Vec<(String, Option<ResourceCopy>)>,
422}
423
424pub fn readings_of(
436 asks: &[ResourceAsk],
437 mut read: impl FnMut(&ResourceAddress) -> Result<ResourceCopy, ActionCallError>,
438) -> Result<ResourceReadings, ActionCallError> {
439 let mut walk = Walk::default();
440 for ask in asks {
441 let mut asking = Asking::of(ask);
442 while let Some(address) = asking.next() {
443 let copy = held(read(&address))?;
444 asking.took(&mut walk.revision, address, copy);
445 }
446 walk.records.extend(asking.answered());
447 }
448 Ok(walk.readings())
449}
450
451pub async fn readings_from<Read, Answer>(
457 asks: &[ResourceAsk],
458 mut read: Read,
459) -> Result<ResourceReadings, ActionCallError>
460where
461 Read: FnMut(ResourceAddress) -> Answer,
462 Answer: std::future::Future<Output = Result<ResourceCopy, ActionCallError>>,
463{
464 let mut walk = Walk::default();
465 for ask in asks {
466 let mut asking = Asking::of(ask);
467 while let Some(address) = asking.next() {
468 let copy = held(read(address.clone()).await)?;
469 asking.took(&mut walk.revision, address, copy);
470 }
471 walk.records.extend(asking.answered());
472 }
473 Ok(walk.readings())
474}
475
476fn held(
479 read: Result<ResourceCopy, ActionCallError>,
480) -> Result<Option<ResourceCopy>, ActionCallError> {
481 match read {
482 Ok(copy) => Ok(Some(copy)),
483 Err(ActionCallError::Unavailable { .. }) => Ok(None),
484 Err(error) => Err(error),
485 }
486}
487
488#[derive(Default)]
490struct Walk {
491 revision: blake3::Hasher,
492 records: Vec<(String, Option<ResourceCopy>)>,
493}
494
495impl Walk {
496 fn readings(self) -> ResourceReadings {
497 ResourceReadings {
498 revision: self.revision.finalize().to_hex().to_string(),
499 records: self.records,
500 }
501 }
502}
503
504struct Asking<'a> {
507 ask: &'a ResourceAsk,
508 base: Option<&'a str>,
510 newest_only: bool,
512 part: u64,
513 done: bool,
514 held: Vec<(String, Option<ResourceCopy>)>,
515}
516
517impl<'a> Asking<'a> {
518 fn of(ask: &'a ResourceAsk) -> Self {
519 let newest = match crate::document_sync::document_sync(&ask.address.record) {
520 crate::document_sync::DocumentSync::ChainHead { base } if !ask.joined => Some(base),
521 _ => None,
522 };
523 let base = newest.or_else(|| ask.joined.then_some(ask.address.record.as_str()));
524 Self {
525 ask,
526 base,
527 newest_only: newest.is_some(),
528 part: 0,
529 done: false,
530 held: Vec::new(),
531 }
532 }
533
534 fn next(&self) -> Option<ResourceAddress> {
536 if self.done {
537 return None;
538 }
539 let record = match self.base {
540 Some(base) => crate::document_sync::document_part(base, self.part),
541 None => self.ask.address.record.clone(),
542 };
543 Some(ResourceAddress {
544 workspace: self.ask.address.workspace.clone(),
545 app: self.ask.address.app.clone(),
546 record,
547 })
548 }
549
550 fn took(
552 &mut self,
553 revision: &mut blake3::Hasher,
554 address: ResourceAddress,
555 copy: Option<ResourceCopy>,
556 ) {
557 let chained = self.base.is_some();
558 let hashed;
562 let bytes: &[u8] = match © {
563 Some(ResourceCopy::Document(bytes)) => bytes,
564 Some(ResourceCopy::Reading {
565 revision: Some(revision),
566 ..
567 }) => revision.as_bytes(),
568 Some(
569 ResourceCopy::Read(value)
570 | ResourceCopy::Reading {
571 value,
572 revision: None,
573 },
574 ) => {
575 hashed = value.to_string();
576 hashed.as_bytes()
577 }
578 Some(ResourceCopy::Absent) => b"",
579 None => b"unavailable",
580 };
581 for bytes in [address.record.as_bytes(), bytes] {
582 revision.update(&(bytes.len() as u64).to_le_bytes());
583 revision.update(bytes);
584 }
585 let last = !chained || !matches!(copy, Some(ResourceCopy::Document(_)));
586 if !(chained && self.part > 0 && matches!(copy, Some(ResourceCopy::Absent))) {
588 self.held.push((address.record, copy));
589 }
590 if last {
591 self.done = true;
592 } else {
593 self.part = self.part.saturating_add(1);
594 }
595 }
596
597 fn answered(mut self) -> Vec<(String, Option<ResourceCopy>)> {
600 if self.newest_only
601 && let Some(newest) = self
602 .held
603 .iter()
604 .rposition(|(_, copy)| matches!(copy, Some(ResourceCopy::Document(_))))
605 .or_else(|| self.held.len().checked_sub(1))
606 {
607 self.held = vec![self.held.swap_remove(newest)];
608 }
609 self.held
610 }
611}
612
613pub async fn read_resources<Reads: ResourceReads + ?Sized>(
620 reads: &Reads,
621 caller: &Caller,
622 asks: &[ResourceAsk],
623 after: Option<&str>,
624 deadline: tilo_clock::time::Instant,
625) -> Result<ResourceReadings, ActionCallError> {
626 loop {
627 let (wake, woken) = ResourceWake::new();
628 let wake = &wake;
629 let readings = readings_from(asks, |address| async move {
630 reads.watch(caller, &address, wake).await?;
631 reads.read(caller, &address).await
632 })
633 .await?;
634 let now = tilo_clock::now();
635 if after != Some(readings.revision.as_str()) || now >= deadline {
636 return Ok(readings);
637 }
638 let mut woken = std::pin::pin!(woken);
639 #[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
640 let mut passed = std::pin::pin!(tilo_rt::sleep(deadline.saturating_duration_since(now)));
641 #[cfg(not(all(feature = "answer-reads", not(tilo_no_js))))]
644 let mut passed = std::pin::pin!(std::future::pending::<()>());
645 std::future::poll_fn(|cx| {
646 if woken.as_mut().poll(cx).is_ready() || passed.as_mut().poll(cx).is_ready() {
647 std::task::Poll::Ready(())
648 } else {
649 std::task::Poll::Pending
650 }
651 })
652 .await;
653 }
654}
655
656pub async fn answer_read<Reads: ResourceReads + ?Sized>(
665 reads: std::sync::Arc<Reads>,
666 caller: Caller,
667 correlation: u64,
668 read: super::ResourceReadRequest,
669) -> super::RemoteActionMessage {
670 super::RemoteActionMessage::ResourceReading {
671 correlation,
672 result: serve_readings(reads.as_ref(), &caller, read).await,
673 }
674}
675
676pub async fn answered(
684 reads: std::sync::Arc<dyn ResourceReads>,
685 caller: &Caller,
686 read: super::ResourceReadRequest,
687) -> Result<serde_json::Value, ActionCallError> {
688 match reads.answer_read(caller, 0, read).await {
689 super::RemoteActionMessage::ResourceReading { result, .. } => {
690 serde_json::from_str(&result?).map_err(|error| ActionCallError::Unavailable {
691 reason: format!("the reading does not read: {error}"),
692 })
693 }
694 _ => Err(ActionCallError::Unanswered),
695 }
696}
697
698#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
707pub(crate) fn answered_where_it_ends(
708 reading: ReadingAnswer,
709) -> super::Pending<super::RemoteActionMessage> {
710 let (answer, answered) = super::pending();
711 let driven = std::sync::Arc::new(Driven {
712 slot: std::sync::Mutex::new(Slot::Held(Held { reading, answer })),
713 again: std::sync::atomic::AtomicBool::new(false),
714 });
715 driven.drive();
716 answered
717}
718
719#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
721enum Slot {
722 Held(Held),
724 Polling,
726 Done,
728}
729
730#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
731struct Held {
732 reading: ReadingAnswer,
733 answer: super::Completer<super::RemoteActionMessage>,
734}
735
736#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
739struct Driven {
740 slot: std::sync::Mutex<Slot>,
741 again: std::sync::atomic::AtomicBool,
743}
744
745#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
746impl Driven {
747 fn drive(self: &std::sync::Arc<Self>) {
750 use std::sync::atomic::Ordering;
751 use tilo_lock::MutexRecover as _;
752
753 loop {
754 let mut slot = self.slot.lock_recover();
755 let taken = std::mem::replace(&mut *slot, Slot::Polling);
756 drop(slot);
757 let held = match taken {
758 Slot::Held(held) => held,
759 Slot::Polling => {
760 self.again.store(true, Ordering::Release);
762 return;
763 }
764 Slot::Done => {
765 *self.slot.lock_recover() = Slot::Done;
766 return;
767 }
768 };
769 self.again.store(false, Ordering::Release);
770 let Held {
771 mut reading,
772 answer,
773 } = held;
774 let waker = std::task::Waker::from(std::sync::Arc::clone(self));
775 let mut context = std::task::Context::from_waker(&waker);
776 #[cfg(not(target_family = "wasm"))]
779 let polled = {
780 let runtime = tilo_rt::Handle::try_current()
781 .unwrap_or_else(|_| tilo_rt::app().handle().clone());
782 let _entered = runtime.enter();
783 reading.as_mut().poll(&mut context)
784 };
785 #[cfg(target_family = "wasm")]
786 let polled = reading.as_mut().poll(&mut context);
787 if let std::task::Poll::Ready(message) = polled {
788 *self.slot.lock_recover() = Slot::Done;
789 answer.complete(message);
790 return;
791 }
792 let mut slot = self.slot.lock_recover();
793 *slot = Slot::Held(Held { reading, answer });
794 let again = self.again.swap(false, Ordering::Acquire);
795 drop(slot);
796 if !again {
797 return;
798 }
799 }
800 }
801}
802
803#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
804impl std::task::Wake for Driven {
805 fn wake(self: std::sync::Arc<Self>) {
806 self.wake_by_ref();
807 }
808
809 fn wake_by_ref(self: &std::sync::Arc<Self>) {
810 self.drive();
811 }
812}
813
814pub(crate) fn unanswered(correlation: u64) -> super::Pending<super::RemoteActionMessage> {
818 super::Pending::ready(super::RemoteActionMessage::ResourceReading {
819 correlation,
820 result: Err(ActionCallError::Unavailable {
821 reason: RESOURCE_READS_UNAVAILABLE.into(),
822 }),
823 })
824}
825
826async fn serve_readings<Reads: ResourceReads + ?Sized>(
827 reads: &Reads,
828 caller: &Caller,
829 read: super::ResourceReadRequest,
830) -> Result<String, ActionCallError> {
831 let write = read.answer == super::ReadAnswer::WriteDecision;
832 if write || read.answer == super::ReadAnswer::Decision {
833 let address = ResourceAddress {
834 workspace: read.workspace,
835 app: read.app,
836 record: read.record,
837 };
838 let decided = if write {
839 reads.may_write(caller, &address).await
840 } else {
841 reads.may_read(caller, &address).await
842 };
843 return decided.map(|()| "null".to_owned());
844 }
845 if read.answer == super::ReadAnswer::Listing {
846 return listing(reads, caller, &read.workspace, &read.app).await;
847 }
848 let document = read.answer == super::ReadAnswer::Document;
849 let deadline = super::wait::deadline(read.wait_ms.unwrap_or(0));
850 let ask = [ResourceAsk {
851 address: ResourceAddress {
852 workspace: read.workspace,
853 app: read.app,
854 record: read.record,
855 },
856 joined: read.joined,
857 }];
858 let readings = read_resources(reads, caller, &ask, read.after.as_deref(), deadline).await?;
859 if document {
860 return Ok(readings.documents().to_string());
861 }
862 readings
863 .readable()
864 .map(|answer| answer.to_string())
865 .map_err(|reason| ActionCallError::Refused { reason })
866}
867
868async fn listing<Reads: ResourceReads + ?Sized>(
872 reads: &Reads,
873 caller: &Caller,
874 workspace: &str,
875 app: &str,
876) -> Result<String, ActionCallError> {
877 let listed: Vec<serde_json::Value> = reads
878 .list(caller, workspace, app)
879 .await?
880 .into_iter()
881 .map(|listed| {
882 let mut entry = serde_json::Map::new();
883 entry.insert("app".into(), listed.address.app.into());
884 entry.insert("record".into(), listed.address.record.into());
885 if let Some(kind) = listed.kind {
886 entry.insert("kind".into(), kind.into());
887 }
888 serde_json::Value::Object(entry)
889 })
890 .collect();
891 Ok(serde_json::json!({ "records": listed }).to_string())
892}
893
894impl ResourceReadings {
895 #[must_use]
902 pub fn documents(self) -> serde_json::Value {
903 let records: Vec<serde_json::Value> = self
904 .records
905 .into_iter()
906 .map(|(record, copy)| match copy {
907 None => serde_json::json!({"record": record, "arriving": true}),
908 Some(ResourceCopy::Absent) => serde_json::json!({"record": record, "absent": true}),
909 Some(ResourceCopy::Document(bytes)) => {
910 serde_json::json!({"record": record, "document": hex::encode(bytes)})
911 }
912 Some(ResourceCopy::Read(value) | ResourceCopy::Reading { value, .. }) => {
913 serde_json::json!({"record": record, "value": value})
914 }
915 })
916 .collect();
917 serde_json::json!({"revision": self.revision, "records": records})
918 }
919
920 pub fn readable(self) -> Result<serde_json::Value, String> {
929 let mut records = Vec::with_capacity(self.records.len());
930 for (record, copy) in self.records {
931 records.push(match copy {
932 None => serde_json::json!({"record": record, "arriving": true}),
933 Some(ResourceCopy::Absent) => serde_json::json!({"record": record, "absent": true}),
934 Some(copy) => serde_json::json!({"record": record, "value": copy.readable()?}),
935 });
936 }
937 Ok(serde_json::json!({"revision": self.revision, "records": records}))
938 }
939}
940
941impl ResourceCopy {
942 pub fn readable(&self) -> Result<serde_json::Value, String> {
958 match self {
959 Self::Absent => Ok(serde_json::Value::Null),
960 Self::Read(value) | Self::Reading { value, .. } => Ok(value.clone()),
961 Self::Document(bytes) => {
962 #[cfg(feature = "document-read")]
963 {
964 let doc =
965 automerge::Automerge::load(bytes).map_err(|error| error.to_string())?;
966 let mut value = tilo_automerge::json::read_document(&doc)
967 .map_err(|error| error.to_string())?;
968 name_variant_fields(&mut value);
969 Ok(value)
970 }
971 #[cfg(not(feature = "document-read"))]
972 {
973 let _ = bytes;
974 Err("this build reads no record as a document".to_owned())
975 }
976 }
977 }
978 }
979}
980
981#[cfg(feature = "document-read")]
984fn name_variant_fields(value: &mut serde_json::Value) {
985 match value {
986 serde_json::Value::Array(items) => items.iter_mut().for_each(name_variant_fields),
987 serde_json::Value::Object(map) => {
988 map.values_mut().for_each(name_variant_fields);
989 let Some(variant) = map.get("$variant").and_then(serde_json::Value::as_str) else {
990 return;
991 };
992 let prefix = format!(
993 "$field/{}/",
994 variant.replace('%', "%25").replace('/', "%2F")
995 );
996 let stored: Vec<String> = map
997 .keys()
998 .filter(|key| key.starts_with(&prefix))
999 .cloned()
1000 .collect();
1001 for key in stored {
1002 if let Some(field) = map.remove(&key) {
1003 let name = key
1004 .get(prefix.len()..)
1005 .unwrap_or_default()
1006 .replace("%2F", "/")
1007 .replace("%25", "%");
1008 map.insert(name, field);
1009 }
1010 }
1011 }
1012 _ => {}
1013 }
1014}
1015
1016#[derive(Clone)]
1018pub struct ResourceWake(std::sync::Arc<std::sync::Mutex<Option<super::Completer<()>>>>);
1019
1020impl ResourceWake {
1021 #[must_use]
1023 pub fn new() -> (Self, super::Pending<()>) {
1024 let (woken, waiting) = super::pending();
1025 (
1026 Self(std::sync::Arc::new(std::sync::Mutex::new(Some(woken)))),
1027 waiting,
1028 )
1029 }
1030
1031 pub fn wake(&self) {
1033 if let Some(woken) = self.0.lock().ok().and_then(|mut woken| woken.take()) {
1034 woken.complete(());
1035 }
1036 }
1037
1038 #[must_use]
1040 pub fn waiting(&self) -> bool {
1041 self.0
1042 .lock()
1043 .is_ok_and(|woken| woken.as_ref().is_some_and(|woken| !woken.is_abandoned()))
1044 }
1045}
1046
1047#[cfg(test)]
1048mod tests {
1049 use automerge::transaction::Transactable as _;
1050 use automerge::{AutoCommit, ObjType, ROOT};
1051
1052 use super::*;
1053
1054 fn message(text: &str) -> Vec<u8> {
1055 let mut doc = AutoCommit::new();
1056 let messages = doc.put_object(ROOT, "messages", ObjType::List).unwrap();
1057 let first = doc.insert_object(&messages, 0, ObjType::Map).unwrap();
1058 let body = doc.put_object(&first, "text", ObjType::Text).unwrap();
1059 doc.splice_text(&body, 0, 0, text).unwrap();
1060 doc.put(&first, "likes", automerge::ScalarValue::counter(2))
1061 .unwrap();
1062 doc.put(&first, "avatar", vec![1u8, 2, 3]).unwrap();
1063 doc.save()
1064 }
1065
1066 fn ask(record: &str, joined: bool) -> ResourceAsk {
1067 ResourceAsk {
1068 address: ResourceAddress {
1069 workspace: "w".into(),
1070 app: "so.tilo.chat".into(),
1071 record: record.into(),
1072 },
1073 joined,
1074 }
1075 }
1076
1077 fn read_resources(
1079 reads: &(impl ResourceReads + ?Sized),
1080 caller: &Caller,
1081 asks: &[ResourceAsk],
1082 after: Option<&str>,
1083 deadline: tilo_clock::time::Instant,
1084 ) -> Result<ResourceReadings, ActionCallError> {
1085 tilo_rt::block_on(super::read_resources(reads, caller, asks, after, deadline)).unwrap()
1086 }
1087
1088 fn values(readings: &ResourceReadings) -> Vec<(String, serde_json::Value)> {
1089 readings
1090 .records
1091 .iter()
1092 .map(|(record, copy)| (record.clone(), copy.as_ref().unwrap().readable().unwrap()))
1093 .collect()
1094 }
1095
1096 tilo_test_env::scenario! {
1097 fn a_record_reads_as_plain_data;
1098
1099 phase a_record_reads_as_plain_data_with_its_text_counters_and_bytes;
1100 {
1101 let mut held = HeldCopies::default();
1102 held.0.insert("note".into(), message("hello"));
1103 let caller = Caller::local_person("me");
1104 let now = tilo_clock::now();
1105 let read = read_resources(
1106 &held,
1107 &caller,
1108 &[ask("note", false), ask("gone", false)],
1109 None,
1110 now,
1111 )
1112 .unwrap();
1113 assert_eq!(
1114 values(&read),
1115 [
1116 (
1117 "note".to_owned(),
1118 serde_json::json!({"messages": [
1119 {"text": "hello", "likes": 2, "avatar": {"bytes": 3}}
1120 ]})
1121 ),
1122 ("gone".to_owned(), serde_json::Value::Null),
1123 ]
1124 );
1125 }
1126
1127 phase a_data_enum_reads_with_its_fields_by_name;
1128 {
1129 let mut doc = AutoCommit::new();
1130 let attached = doc.put_object(ROOT, "attached", ObjType::Map).unwrap();
1131 doc.put(&attached, "$variant", "file").unwrap();
1132 doc.put(&attached, "$field/file/blob", "ab").unwrap();
1133 doc.put(&attached, "$field/file/a%2Fb", 3).unwrap();
1134 assert_eq!(
1135 ResourceCopy::Document(doc.save()).readable().unwrap(),
1136 serde_json::json!({"attached": {"$variant": "file", "blob": "ab", "a/b": 3}})
1137 );
1138 }
1139
1140 phase a_rich_text_reads_as_its_paragraphs_in_their_order;
1141 {
1142 let mut doc = AutoCommit::new();
1145 doc.put(ROOT, "title", "A poem").unwrap();
1146 let body = doc.put_object(ROOT, "body", ObjType::Map).unwrap();
1147 doc.put(&body, "schema", "tilo.richtext").unwrap();
1148 let blocks = doc.put_object(&body, "blocks", ObjType::Map).unwrap();
1149 for (id, place, kind, words) in [
1150 ("p1", vec![192_u8], "list_item", "and so are you"),
1151 ("p2", vec![64], "heading", "A poem"),
1152 ("p3", vec![128], "paragraph", "Roses are red"),
1153 ] {
1154 let block = doc.put_object(&blocks, id, ObjType::Map).unwrap();
1155 doc.put(&block, "order", place).unwrap();
1156 doc.put(&block, "kind", kind).unwrap();
1157 let text = doc.put_object(&block, "text", ObjType::Text).unwrap();
1158 doc.splice_text(&text, 0, 0, words).unwrap();
1159 }
1160 assert_eq!(
1161 ResourceCopy::Document(doc.save()).readable().unwrap(),
1162 serde_json::json!({"title": "A poem", "body": {
1163 "schema": "tilo.richtext",
1164 "blocks": [
1165 {"id": "p2", "kind": "heading", "text": "A poem"},
1166 {"id": "p3", "kind": "paragraph", "text": "Roses are red"},
1167 {"id": "p1", "kind": "list_item", "text": "and so are you"},
1168 ],
1169 }})
1170 );
1171 }
1172
1173 phase a_chain_reads_joined_up_to_its_last_part_and_a_new_part_changes_its_revision;
1174 {
1175 let mut held = HeldCopies::default();
1176 let part = |index| crate::document_sync::document_part("chain", index);
1177 held.0.insert(part(0), message("first"));
1178 held.0.insert(part(1), message("second"));
1179 let caller = Caller::local_person("me");
1180 let now = tilo_clock::now();
1181 let read = read_resources(&held, &caller, &[ask("chain", true)], None, now).unwrap();
1182 let texts: Vec<_> = values(&read)
1183 .into_iter()
1184 .map(|(record, value)| (record, value["messages"][0]["text"].clone()))
1185 .collect();
1186 assert_eq!(
1187 texts,
1188 [
1189 (part(0), serde_json::json!("first")),
1190 (part(1), serde_json::json!("second")),
1191 ]
1192 );
1193 let same = read_resources(&held, &caller, &[ask("chain", true)], None, now).unwrap();
1194 assert_eq!(same.revision, read.revision);
1195 held.0.insert(part(2), message("third"));
1196 let grown = read_resources(
1197 &held,
1198 &caller,
1199 &[ask("chain", true)],
1200 Some(&read.revision),
1201 now,
1202 )
1203 .unwrap();
1204 assert_ne!(grown.revision, read.revision);
1205 assert_eq!(grown.records.len(), 3);
1206 let newest_part = crate::document_sync::chain_head("chain");
1208 let newest = read_resources(&held, &caller, &[ask(&newest_part, false)], None, now).unwrap();
1209 assert_eq!(
1210 values(&newest),
1211 [(
1212 part(2),
1213 serde_json::json!({"messages": [
1214 {"text": "third", "likes": 2, "avatar": {"bytes": 3}}
1215 ]})
1216 )]
1217 );
1218 held.0.insert(part(3), message("fourth"));
1219 let moved = read_resources(&held, &caller, &[ask(&newest_part, false)], None, now).unwrap();
1220 assert_ne!(moved.revision, newest.revision);
1221 assert_eq!(moved.records[0].0, part(3));
1222 }
1223
1224 phase a_reading_reads_as_its_json_and_a_change_wakes_the_follow;
1225 {
1226 struct Published {
1229 value: std::sync::Mutex<serde_json::Value>,
1230 revision: std::sync::Mutex<String>,
1231 wakers: std::sync::Mutex<Vec<ResourceWake>>,
1232 }
1233
1234 impl Published {
1235 fn move_to(&self, value: serde_json::Value, revision: &str) {
1236 *self.value.lock().unwrap() = value;
1237 *self.revision.lock().unwrap() = revision.to_owned();
1238 let woken = std::mem::take(&mut *self.wakers.lock().unwrap());
1239 for wake in woken {
1240 wake.wake();
1241 }
1242 }
1243 }
1244
1245 impl ResourceReads for Published {
1246 fn read<'a>(
1247 &'a self,
1248 _: &'a Caller,
1249 _: &'a ResourceAddress,
1250 ) -> ReadsAnswer<'a, ResourceCopy> {
1251 Box::pin(async move {
1252 Ok(ResourceCopy::reading(
1253 self.value.lock().unwrap().clone(),
1254 Some(self.revision.lock().unwrap().clone()),
1255 ))
1256 })
1257 }
1258
1259 fn watch<'a>(
1260 &'a self,
1261 _: &'a Caller,
1262 _: &'a ResourceAddress,
1263 wake: &'a ResourceWake,
1264 ) -> ReadsAnswer<'a, ()> {
1265 Box::pin(async move {
1266 self.wakers.lock().unwrap().push(wake.clone());
1267 Ok(())
1268 })
1269 }
1270 }
1271
1272 let published = std::sync::Arc::new(Published {
1273 value: std::sync::Mutex::new(serde_json::json!({"playing": false})),
1274 revision: std::sync::Mutex::new("a".into()),
1275 wakers: std::sync::Mutex::default(),
1276 });
1277 let caller = Caller::local_person("me");
1278 let asks = [ResourceAsk {
1279 address: ResourceAddress {
1280 workspace: "w".into(),
1281 app: "shell".into(),
1282 record: "session:media".into(),
1283 },
1284 joined: false,
1285 }];
1286 let now = tilo_clock::now();
1287 let read = read_resources(&*published, &caller, &asks, None, now).unwrap();
1288 assert_eq!(
1289 values(&read),
1290 [(
1291 "session:media".to_owned(),
1292 serde_json::json!({"playing": false})
1293 )],
1294 "a reading reads as the JSON its provider publishes"
1295 );
1296 assert!(!read.revision.is_empty(), "the reading has a revision");
1297 published.wakers.lock().unwrap().clear();
1299 let changed = std::thread::scope(|scope| {
1300 let waiting = scope.spawn(|| {
1301 read_resources(
1302 &*published,
1303 &caller,
1304 &asks,
1305 Some(&read.revision),
1306 tilo_clock::now()
1307 .checked_add(std::time::Duration::from_secs(30))
1308 .unwrap(),
1309 )
1310 });
1311 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1312 loop {
1313 if published.wakers.lock().unwrap().is_empty() {
1314 assert!(
1315 std::time::Instant::now() < deadline,
1316 "the follow watched nothing"
1317 );
1318 std::thread::yield_now();
1319 continue;
1320 }
1321 break;
1322 }
1323 published.move_to(serde_json::json!({"playing": true}), "b");
1324 waiting.join().expect("the follow")
1325 })
1326 .unwrap();
1327 assert_eq!(
1328 values(&changed),
1329 [(
1330 "session:media".to_owned(),
1331 serde_json::json!({"playing": true})
1332 )],
1333 "the change woke the follow, which read the new reading"
1334 );
1335 assert_ne!(changed.revision, read.revision);
1336 }
1337
1338 phase a_reading_its_provider_names_no_revision_for_is_hashed_by_its_json;
1339 {
1340 struct Unversioned(std::sync::Mutex<serde_json::Value>);
1341
1342 impl ResourceReads for Unversioned {
1343 fn read<'a>(
1344 &'a self,
1345 _: &'a Caller,
1346 _: &'a ResourceAddress,
1347 ) -> ReadsAnswer<'a, ResourceCopy> {
1348 Box::pin(async move {
1349 Ok(ResourceCopy::reading(
1350 self.0.lock().unwrap().clone(),
1351 None,
1352 ))
1353 })
1354 }
1355
1356 fn watch<'a>(
1357 &'a self,
1358 _: &'a Caller,
1359 _: &'a ResourceAddress,
1360 _: &'a ResourceWake,
1361 ) -> ReadsAnswer<'a, ()> {
1362 Box::pin(async move {
1363 Ok(())
1364 })
1365 }
1366 }
1367
1368 let published = Unversioned(std::sync::Mutex::new(serde_json::json!({"level": 1})));
1369 let caller = Caller::local_person("me");
1370 let asks = [ask("session:volume", false)];
1371 let now = tilo_clock::now();
1372 let first = read_resources(&published, &caller, &asks, None, now).unwrap();
1373 let again = read_resources(&published, &caller, &asks, None, now).unwrap();
1374 assert_eq!(first.revision, again.revision, "the same JSON is one revision");
1375 *published.0.lock().unwrap() = serde_json::json!({"level": 2});
1376 let moved = read_resources(&published, &caller, &asks, None, now).unwrap();
1377 assert_ne!(moved.revision, first.revision, "another JSON is another");
1378 }
1379 }
1380}