Skip to main content

tilo_actions/remote/
resource_read.rs

1//! Record reads outside their app: how an agent reads a workspace's records
2//! (`docs/designs/app-language/agents.md`, "Reading records outside their app").
3//!
4//! A workspace's records are sealed per app: a connection holding that app's launch ownership opens
5//! them. An agent is not an app. It is admitted acting for the person whose session it works in,
6//! never session-delegated and holding no app's route, and reads one record at a time through
7//! this API. Each read is decided by the check every reader of a record goes through (the lesser
8//! of the agent's grants and the person's), again for every read, so a grant revoked or a member
9//! removed in the middle of a session cuts the reads that follow. A read carries the record's
10//! committed content and nothing that writes to it: the agent changes a record only by invoking
11//! actions.
12//!
13//! A provider publishes resources itself too, which no app's record holds: a desktop's device,
14//! its windows and its styles, Settings' sections. Those are answered on this same API as a
15//! reading, the JSON the service reads, so a program, an agent and a view read one resource one
16//! way.
17
18use super::{ActionCallError, Caller};
19
20/// What a provider without record reads answers.
21pub const RESOURCE_READS_UNAVAILABLE: &str = "this provider reads no records outside their apps";
22
23/// What a caller is told about a record it may not read.
24pub const RESOURCE_READ_REFUSED: &str = "not allowed to read this record";
25
26/// What a caller is told about a record it may not change.
27pub const RESOURCE_WRITE_REFUSED: &str = "not allowed to change this record";
28
29/// What a caller that is neither a person nor an agent acting for its person is told.
30pub 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/// One record of a workspace, by the workspace it is in, its app (the id whose records it is) and
35/// its id there (empty for the app's record of the workspace).
36#[derive(Clone, Debug, PartialEq, Eq, Hash)]
37pub struct ResourceAddress {
38    pub workspace: String,
39    pub app: String,
40    pub record: String,
41}
42
43/// A record a listing names: where it is, and the kind the workspace's store keeps it as. A
44/// document that is no record of the store (the workspace's tree, a device's settings) names no
45/// kind.
46#[derive(Clone, Debug, PartialEq, Eq, Hash)]
47pub struct ListedResource {
48    pub address: ResourceAddress,
49    pub kind: Option<String>,
50}
51
52impl ListedResource {
53    /// `address`, a document that is no record of the workspace's store.
54    #[must_use]
55    pub fn document(address: ResourceAddress) -> Self {
56        Self {
57            address,
58            kind: None,
59        }
60    }
61
62    /// The records a listing of `workspace` answered ([`answer_read`]), each of `app` where it
63    /// names none.
64    #[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
89/// The app a device's own settings are read under ([`device_record_space`]): the record
90/// `keymap` there is `devices/<device>/settings/keymap`.
91pub const DEVICE_SETTINGS: &str = "settings";
92
93/// The record space a device that no person is founded on keeps its own records in, as the
94/// `workspace` of a [`ResourceAddress`]: `devices/<device hex>`. No workspace has this id (a
95/// workspace's is a UUID), so a read naming it is a read of the device's own records, decided by
96/// the device alone rather than by a workspace's governance.
97///
98/// This is the device case of the one record API: the same [`super::RemoteActionMessage::ResourceRead`],
99/// follow and wake answer the records as any workspace's, so the greeter and the launcher read
100/// the settings the device kept before anyone claimed it the way their views read any record.
101#[must_use]
102pub fn device_record_space(device: &[u8; 32]) -> String {
103    format!("devices/{}", hex::encode(device))
104}
105
106/// What a caller that may not read a device's own settings is told: who may.
107pub 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
110/// The app a device's engine jobs are read under ([`device_record_space`]): the record `job`
111/// there is the job the device runs, at `devices/<device>/jobs/<job>`. A job is the device's,
112/// never a workspace's: it lives only as long as the process that runs it.
113pub const DEVICE_JOBS: &str = "jobs";
114
115/// The address of the engine job `job` the device `device` runs, in the space
116/// [`device_record_space`] names.
117#[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/// The text form of a job's address, `devices/<device hex>/jobs/<job>`: the one form a view, a
127/// script or a link writes a job in, and [`parse_job_path`] reads back.
128#[must_use]
129pub fn device_job_path(device: &[u8; 32], job: &str) -> String {
130    format!("devices/{}/jobs/{job}", hex::encode(device))
131}
132
133/// Read the text form of a job's address ([`device_job_path`]) back: the device that runs it and
134/// the job's id there. `None` for any other text, including a path whose job is empty or names
135/// more than one part.
136#[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/// The device key `space` names, when it is a device record space
148/// ([`device_record_space`]): `devices/<device hex>`.
149#[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/// The address of the device record `record` the device `device` keeps: its settings, in the
161/// space [`device_record_space`] names.
162#[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/// What a read of one record answers.
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub enum ResourceCopy {
174    /// The record's committed content: an Automerge document, whole.
175    Document(Vec<u8>),
176    /// The resource as its app's package reads it: what the core read answers of it, who
177    /// made each item and when included. A tilolang app's records are read this way, never as
178    /// the documents that keep them.
179    Read(serde_json::Value),
180    /// A resource the provider publishes itself rather than from an app's record (device state, a
181    /// desktop's windows and styles): its reading as the JSON its service reads, and the revision
182    /// it stands at when the provider names one. A provider with no revision of its own leaves it
183    /// `None`, and a reader's revision is the hash of the JSON then.
184    Reading {
185        value: serde_json::Value,
186        revision: Option<String>,
187    },
188    /// The workspace holds no such record: nothing was ever written to it.
189    Absent,
190}
191
192impl ResourceCopy {
193    /// A reading of a resource the provider publishes, at the revision it names (or none).
194    #[must_use]
195    pub const fn reading(value: serde_json::Value, revision: Option<String>) -> Self {
196        Self::Reading { value, revision }
197    }
198}
199
200/// Whether a caller may read or change a record: allowed, or why not
201/// ([`ResourceReads::may_read`], [`ResourceReads::may_write`]).
202pub type Decided = Result<(), ActionCallError>;
203
204/// What a reader answers, once it has it: a read may wait on a lock, a store or another device
205/// over its link, so it is awaited where it is asked and never holds the thread that asked.
206pub type ReadsAnswer<'a, T> =
207    std::pin::Pin<Box<dyn std::future::Future<Output = Result<T, ActionCallError>> + Send + 'a>>;
208
209/// A read asked over the API, answered once its reader has it ([`ResourceReads::answer_read`]).
210pub type ReadingAnswer =
211    std::pin::Pin<Box<dyn std::future::Future<Output = super::RemoteActionMessage> + Send>>;
212
213/// `answer`, as a reader answers: its result's type is the one the reader answers, so a body
214/// that answers at once is written as an `async move` block, with `?` and `return` as usual.
215pub 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
221/// What a provider without record reads answers any of them.
222fn 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
228/// A provider's API for reading records outside their app.
229pub trait ResourceReads: Send + Sync {
230    /// The record `address`, in the workspace it names, as `caller` may read it now: decided at
231    /// that workspace's record node with the caller's actor, whichever workspace the caller's
232    /// connection was admitted to. A provider that publishes a resource itself answers its
233    /// reading here, as it answers an app's record.
234    ///
235    /// # Errors
236    ///
237    /// [`ActionCallError::NotPermitted`] for a caller that is not an agent task acting for its
238    /// person, [`ActionCallError::Refused`] for a record the caller may not read,
239    /// [`ActionCallError::Unavailable`] when the workspace's records cannot be read now (still
240    /// arriving, or held nowhere on this device), or by a reader that answers only
241    /// [`Self::answer_read`], the device on the other end of a session.
242    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    /// Whether `caller` may read `address` now, decided as [`Self::read`] is, without the copy:
252    /// what a reader that keeps the record another way (an app's live route to it) asks first.
253    /// [`ActionCallError::ConfirmationRequired`] where the person is to be asked first.
254    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    /// Whether `caller` may change `address` now, decided there as a write is: what a reader that
263    /// keeps the record another way (an app's live route to it) asks before it changes it. An app
264    /// changes its own records; another app's record it changes only where the caller's grants
265    /// there allow a change, so a grant that reads alone answers [`ActionCallError::Refused`].
266    /// [`ActionCallError::ConfirmationRequired`] where the person is to be asked first.
267    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    /// Answer a read of one of this provider's records, asked as `correlation` over the API
276    /// ([`super::RemoteActionMessage::ResourceRead`]), with what every reader of it is answered:
277    /// [`answer_read`], from this provider's own reads, unless the provider answers reads another
278    /// way (the desktop answers its windows' reads on its own turn).
279    ///
280    /// The API posts a read here rather than to code of its own, so what a reading is made of —
281    /// every copy as JSON, and the record format behind it — is reached only from the reader's
282    /// code. A provider that serves an app's windows and reads no record through the API leaves
283    /// [`super::ActionProvider::resource_reads`] `None` and carries none of it.
284    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    /// Wake `wake` once the next write to `address` lands on this provider, or what it publishes
297    /// of the resource moves, decided as a read is: what a reader holding a copy waits on before
298    /// it reads again. Watched before the read it guards, so no write between the two is missed.
299    ///
300    /// # Errors
301    ///
302    /// As [`Self::read`]; a provider that cannot tell when a record changes answers
303    /// [`ActionCallError::Unavailable`].
304    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    /// The resources of `workspace` that `caller` may read now: `app`'s, or every app's where
315    /// `app` is empty, each decided as its read would be. What a reader that keeps every resource
316    /// of a workspace (an index, search) reads before it reads each.
317    ///
318    /// # Errors
319    ///
320    /// As [`Self::read`]; a provider that lists nothing answers [`ActionCallError::Unavailable`].
321    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    /// The device's store's answer to `read`, a read command of the store's wire (a resource, a
332    /// page of a query, a count, a content), asked of the resources the app `app` keeps in
333    /// `address`'s workspace as `caller` may read them now, decided as [`Self::read`] is. The command
334    /// and its answer travel as JSON, so a reader of resources needs no store of its own.
335    ///
336    /// # Errors
337    ///
338    /// As [`Self::read`]; [`ActionCallError::InvalidRequest`] for a command that writes or does
339    /// not parse. A provider whose resources are in no store answers
340    /// [`ActionCallError::Unavailable`].
341    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/// Copies of records already in hand, by id, read as they are: what a reader planning with what
353/// it holds reads. Any other record is absent, and nothing wakes a wait for a write.
354#[derive(Clone, Debug, Default, PartialEq, Eq)]
355pub struct HeldCopies(pub std::collections::HashMap<String, Vec<u8>>);
356
357impl HeldCopies {
358    /// `asks` read from these copies by `caller` now, as every reader is answered
359    /// ([`ResourceReadings::readable`]).
360    ///
361    /// # Errors
362    ///
363    /// As [`read_resources`] and [`ResourceReadings::readable`].
364    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    /// The copy of `address` in hand, or absent.
377    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/// One record a reader asks for: alone, or `joined`, the chain of parts whose base it is
406/// ([`crate::document_sync`]): part `0`, `1`, … up to the first the workspace holds none of. A
407/// chain's head ([`crate::document_sync::chain_head`]) asked alone reads its newest part, under
408/// that part's id: what a reader that follows a chain reads, whatever its length.
409#[derive(Clone, Debug, PartialEq, Eq)]
410pub struct ResourceAsk {
411    pub address: ResourceAddress,
412    pub joined: bool,
413}
414
415/// What a read of several records answered: each record read (a joined one as its parts), its
416/// copy or `None` while it is still arriving, and the revision of them all, which changes with
417/// any write to any of them.
418#[derive(Clone, Debug, PartialEq, Eq)]
419pub struct ResourceReadings {
420    pub revision: String,
421    pub records: Vec<(String, Option<ResourceCopy>)>,
422}
423
424/// One pass over `asks`: each record `read` answers (a joined one as its parts) and the revision of
425/// them all, which changes with any write to any of them. A record `read` answers
426/// [`ActionCallError::Unavailable`] for is still arriving and reads as `None`. A provider that waits on
427/// writes watches a record inside `read`, before it reads it, so no write between the two is missed.
428///
429/// This walks records already in hand, which answer at once: the desktop's, which it reads on its
430/// own turn. A reader that awaits its records walks them with [`readings_from`].
431///
432/// # Errors
433///
434/// What `read` refuses a record with, other than [`ActionCallError::Unavailable`].
435pub 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
451/// [`readings_of`], over records `read` answers once it has them.
452///
453/// # Errors
454///
455/// What `read` refuses a record with, other than [`ActionCallError::Unavailable`].
456pub 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
476/// A record's copy as a reading holds it: `None` while it is still arriving, whose write wakes
477/// the reader.
478fn 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/// The records a walk over several asks read so far, and the revision of them all.
489#[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
504/// One ask's records as they are read: the record alone, or the parts of its chain one after
505/// another up to the first that holds no document.
506struct Asking<'a> {
507    ask: &'a ResourceAsk,
508    /// The chain's base, for an ask that reads one.
509    base: Option<&'a str>,
510    /// Whether the ask is a chain's head read alone: it answers the newest part.
511    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    /// The record to read next, `None` once the ask is read.
535    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    /// `address`, the record [`Self::next`] named, read as `copy`.
551    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        // A reading's revision is the one its provider names; one naming none, and a record its
559        // app reads for itself, are hashed by their JSON, which is all a reader can tell about
560        // them.
561        let hashed;
562        let bytes: &[u8] = match &copy {
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        // The part after a chain's last is watched, not answered: its first write wakes.
587        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    /// What the ask answers: a head the newest part alone, every part read staying in the
598    /// revision, so a write to any of them, or a new part, wakes its reader.
599    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
613/// Read `asks` for `caller` once they differ from the revision `after` or `deadline` passed:
614/// each record is watched before it is read, so the next write to any of them wakes the wait.
615///
616/// # Errors
617///
618/// As [`ResourceReads::read`], but a record still arriving answers `None` rather than failing.
619pub 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        // A build without a runtime (a model module, or one that answers no reads) has no timer: it
642        // only waits for the write.
643        #[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
656/// Answer `read`, asked as `correlation`, for `caller` from `reads`, the provider's record API:
657/// awaited where it is asked, through the wait for a write past `read.after` and the record's
658/// capture.
659///
660/// Every provider that reads records answers [`ResourceReads::answer_read`] with this, and the API
661/// posts a read through that method rather than here: the reading, the JSON every reader is
662/// answered and the record format behind it are reached only from a reader's own code, so a provider
663/// that serves an app's windows and reads no record does not carry them.
664pub 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
676/// What `reads` answers `read` for `caller` through the record API's read message, as JSON
677/// ([`ResourceReadings::readable`], or a listing): wherever the record is, and with `after`
678/// once it moves past that revision or the wait went by.
679///
680/// # Errors
681///
682/// The reader's refusal, or an answer that is no reading.
683pub 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/// `reading`, answered where it is completed: polled first in the call that asked, so a reader
699/// that has the record answers it there, and again on the thread each wait of it ends on, so a
700/// reader that answers on its own turn — the desktop reading its windows' records — is delivered
701/// inside that turn, and a follow asks again in it. No thread is parked on the read: whoever ends
702/// a wait runs the rest of it.
703///
704/// A read is polled within a runtime's context ([`tilo_rt::Handle`]), so one that waits on a timer
705/// has one wherever it is resumed.
706#[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/// What a [`Driven`] holds between polls, if anything.
720#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
721enum Slot {
722    /// The reading and the answer it completes.
723    Held(Held),
724    /// This thread polls it now: a wake meanwhile asks for one more poll.
725    Polling,
726    /// It answered, or the client went.
727    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/// A read answered on the thread that ends its wait: [`Driven::drive`] polls it, and its waker —
737/// given to whatever the read awaits — drives it again on the thread that completes that wait.
738#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
739struct Driven {
740    slot: std::sync::Mutex<Slot>,
741    /// A wake that came while the reading was polled on another thread.
742    again: std::sync::atomic::AtomicBool,
743}
744
745#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
746impl Driven {
747    /// Poll the held reading as far as it goes. Called in the call that asked and on every wake,
748    /// on whichever thread that is.
749    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                    // Another thread polls it: that poll ends with one more.
761                    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            // A read may wait on a timer, and resumed on a thread that runs no runtime it would
777            // fail to find one: poll it in the context of this thread's runtime, or the app's.
778            #[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
814/// What a provider that reads no records answers a read of one: the API posts every read through
815/// [`ResourceReads::answer_read`], and a provider whose [`super::ActionProvider::resource_reads`] is `None`
816/// answers as this one does.
817pub(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
868/// The resources of `workspace` `caller` may read of `app` (every app's, empty), as a listing
869/// answers them: `{"records": [{"app", "record", "kind"}]}`, `kind` only for a record the
870/// workspace's store keeps.
871async 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    /// The readings as a reader that keeps the documents is answered: as `readable`, with
896    /// each document `{"record", "document"}`, whole, in hex. A reading a provider publishes
897    /// itself, which is no document, is answered as `readable` answers it.
898    ///
899    /// # Panics
900    /// Never: a reading's JSON always encodes.
901    #[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    /// The readings as every reader is answered: `{"revision", "records": [...]}`, each record
921    /// `{"record", "value"}` ([`ResourceCopy::readable`], a document or a reading alike),
922    /// `{"record", "absent": true}` for one the workspace holds none of, or `{"record",
923    /// "arriving": true}` for one still arriving.
924    ///
925    /// # Errors
926    ///
927    /// When a copy is a document this build reads none of (feature `document-read`).
928    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    /// The record as any reader reads it, whatever app keeps it: its maps as objects, lists as
943    /// arrays, text as strings, counters and scalars as numbers, strings and booleans, bytes as
944    /// their count, a data enum as its `$variant` beside its fields by name; a reading as the JSON
945    /// its provider publishes; `null` for a record the workspace holds none of.
946    ///
947    /// A rich text reads with its paragraphs as lists in their order, each paragraph with its
948    /// id, its kind, its words and its attributes, and without the key of bytes that places
949    /// it: its body, its page header and footer, a note's and a comment's lines, and what a
950    /// paragraph holds (`tilo_automerge::rich_text`). So every reader shows a text in order
951    /// and none orders it again.
952    ///
953    /// # Errors
954    ///
955    /// When the copy is no Automerge document, or is one this build reads none of (feature
956    /// `document-read` carries the reader).
957    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/// Each data enum in `value` with its fields by name: a record keeps a variant's fields under
982/// `$field/<variant>/<field>` (`%` and `/` escaped), so no two variants' fields share a key.
983#[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/// Woken once, by the first write to any record it watches ([`ResourceReads::watch`]).
1017#[derive(Clone)]
1018pub struct ResourceWake(std::sync::Arc<std::sync::Mutex<Option<super::Completer<()>>>>);
1019
1020impl ResourceWake {
1021    /// A wake, and what its reader waits on.
1022    #[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    /// A write landed: wake the reader, once.
1032    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    /// Whether this wake can still wake anyone: not woken yet, and its reader still waits.
1039    #[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    /// [`super::read_resources`], waited for on a runtime of its own.
1078    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            // A rich text under a field, as the word processor keeps a document's body: three
1143            // paragraphs, written in another order than they stand in.
1144            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            // The head is the newest part alone, its revision moved by a new part.
1207            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            /// A resource a provider publishes itself: its JSON, the revision it names, and the
1227            /// follows watching it, woken when it moves.
1228            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            // The first read watched too; only what the follow watches is woken here.
1298            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}