Skip to main content

tilo_resource/
read.rs

1//! `read`: what a readable resource holds, as typed data. With no `item` it
2//! answers the resource itself; with an `item` id, the nested resource of that
3//! id; with a `version`, frozen historical content. It is a view: it changes
4//! nothing, needs only read permission and is checked like every other action.
5//!
6//! Every app publishes the same `read`: a framework app's root, and a tilolang
7//! host for each of its instances.
8
9use crate::{Id, Model, Resource};
10
11/// The operation type of `read`.
12pub const TYPE: &str = "tilo.resource.read";
13
14/// What `state` reads as to a view of another language that does not run its
15/// app: the record's JSON ([`Model::to_json`]) with each collection a list of
16/// its items, their ids dropped, and each keyed collection a list of its
17/// values. A reading names no item by id — the surface's fields are the item's
18/// — so what a view reads it as is what the runtime hands it (a runtime's
19/// `set_reading`).
20#[must_use]
21pub fn reading<R: Resource>(state: &R::State) -> serde_json::Value {
22    let (Some(shape), Some(json)) = (R::shape(), R::state_json(state)) else {
23        return serde_json::Value::Null;
24    };
25    projected(&shape, &json)
26}
27
28/// The key a collection's entry holds its value under in the record's JSON form
29/// ([`crate::Model::to_json`]): its document key is [`crate::shape::ENTRY_VALUE_KEY`].
30const JSON_ENTRY_VALUE: &str = "value";
31
32/// `json`, the record's JSON form, as [`reading`] reads it of `shape`.
33fn projected(shape: &crate::Shape, json: &serde_json::Value) -> serde_json::Value {
34    match (shape, json) {
35        (crate::Shape::Record(fields), serde_json::Value::Object(map)) => {
36            let fields: serde_json::Map<_, _> = fields
37                .iter()
38                .filter_map(|field| {
39                    map.get(field.key)
40                        .map(|value| (field.key.to_owned(), projected(&field.shape, value)))
41                })
42                .collect();
43            serde_json::Value::Object(fields)
44        }
45        (crate::Shape::Collection(inner), serde_json::Value::Array(entries)) => {
46            let items = entries
47                .iter()
48                .map(|entry| {
49                    let item = entry.get(JSON_ENTRY_VALUE).unwrap_or(entry);
50                    projected(inner, item)
51                })
52                .collect();
53            serde_json::Value::Array(items)
54        }
55        (crate::Shape::Keyed(item), serde_json::Value::Array(values)) => {
56            serde_json::Value::Array(values.iter().map(|value| projected(item, value)).collect())
57        }
58        (crate::Shape::Map(item), serde_json::Value::Object(entries)) => {
59            let entries: serde_json::Map<_, _> = entries
60                .iter()
61                .map(|(key, value)| (key.clone(), projected(item, value)))
62                .collect();
63            serde_json::Value::Object(entries)
64        }
65        (_, json) => json.clone(),
66    }
67}
68
69/// The `read` action, bound to the nested resource `item` when one is named
70/// (its own `read`, without an `item` parameter).
71#[must_use]
72pub fn spec(item: Option<&str>) -> tilo_actions::ActionSpec {
73    spec_on(None, item)
74}
75
76/// The `read` of `record`, a record an app keeps beside its own (the
77/// person's own record of a kind): the read names it, and the app's process
78/// answers it from that record.
79#[must_use]
80pub fn resource_spec(record: &str) -> tilo_actions::ActionSpec {
81    spec_on(Some(record), None)
82}
83
84/// The record a `read` asked as `payload` names, when it is not the app's
85/// own ([`resource_spec`]).
86#[must_use]
87pub fn resource_of(payload: &[u8]) -> Option<String> {
88    let args: serde_json::Value = tilo_actions::decode_json(payload).ok()?;
89    args.get("record")?.as_str().map(str::to_owned)
90}
91
92fn spec_on(record: Option<&str>, item: Option<&str>) -> tilo_actions::ActionSpec {
93    let (record, item) = (record.map(str::to_owned), item.map(str::to_owned));
94    let mut spec = tilo_actions::ActionSpec::typed_operation(
95        "read",
96        "Read the content",
97        "Read the content",
98        tilo_actions::OperationKind::View,
99        TYPE,
100        vec![
101            tilo_actions::ActionParam::optional(
102                "item",
103                tilo_actions::ParamType::Text,
104                "A nested resource's id, as the first read lists it (default: the whole resource)",
105            )
106            .nullable(),
107            tilo_actions::ActionParam::optional(
108                "version",
109                tilo_actions::ParamType::Text,
110                "A change id, exact causal frontier, or checkpoint name (default: current)",
111            )
112            .nullable(),
113            tilo_actions::ActionParam::optional(
114                "cursor",
115                tilo_actions::ParamType::Text,
116                "The next_cursor an earlier read answered, for the next page of its lists",
117            )
118            .nullable(),
119            tilo_actions::ActionParam::optional(
120                "pageSize",
121                tilo_actions::ParamType::Integer,
122                "How many entries of each list a page holds (default 25, at most 200)",
123            )
124            .nullable(),
125            tilo_actions::ActionParam::optional(
126                "field",
127                tilo_actions::ParamType::Text,
128                "The collection to read a page of, by field name (default: the one collection it has)",
129            )
130            .nullable(),
131            tilo_actions::ActionParam::optional(
132                "where",
133                tilo_actions::ParamType::Object,
134                "Only the collection's items whose fields hold these values, by field name, a reference by its id; `from`: the items made from that resource",
135            )
136            .nullable(),
137            tilo_actions::ActionParam::optional(
138                "after",
139                tilo_actions::ParamType::Text,
140                "The page starts after this item: the `next` an earlier page answered",
141            )
142            .nullable(),
143            tilo_actions::ActionParam::optional(
144                "limit",
145                tilo_actions::ParamType::Integer,
146                "How many items of the collection the page holds (default 25, at most 200)",
147            )
148            .nullable(),
149        ]
150        .into_iter()
151        .filter(|param| item.is_none() || !matches!(param.name.as_ref(), "item" | "cursor" | "pageSize"))
152        .collect(),
153        move |args| {
154            let mut asked = serde_json::Map::new();
155            asked.insert("item".into(), item.as_deref().or_else(|| args.text("item")).into());
156            asked.insert("version".into(), args.text("version").into());
157            asked.insert("cursor".into(), args.text("cursor").into());
158            asked.insert("pageSize".into(), args.integer("pageSize").into());
159            asked.insert("field".into(), args.text("field").into());
160            asked.insert(
161                "where".into(),
162                match args.get("where") {
163                    Some(tilo_actions::ArgValue::Object(matching)) => matching.clone().into(),
164                    _ => serde_json::Value::Null,
165                },
166            );
167            asked.insert("after".into(), args.text("after").into());
168            asked.insert("limit".into(), args.integer("limit").into());
169            if let Some(record) = &record {
170                asked.insert("record".into(), record.as_str().into());
171            }
172            tilo_actions::EncodedAction::encode_operation(TYPE, &asked)
173            .unwrap_or_else(|_| tilo_actions::EncodedAction {
174                type_id: TYPE.into(),
175                payload: Vec::new(),
176            })
177        },
178    )
179    .of_kind(tilo_actions::ActionKind::Read)
180    .with_description(
181        "What this holds as typed data: with no item, the resource and the ids of what it contains; with an item id, that item's content, each resource with who made it, when and what from (`created`). With field, where, after and limit, a page of one collection's items: those whose fields hold the values `where` names, or that were made from its `from`. With version, read frozen historical content and its exact heads without changing the live resource.",
182    )
183    // Typed data for a program to reason about; a person reads what the
184    // app shows.
185    .for_audience(tilo_actions::Audience::Agents);
186    spec.type_mut().contract.result = tilo_actions::ResultSpec::Json {
187        schema: serde_json::json!({"type": "object"}),
188    };
189    spec.type_mut().contract.step = Some(tilo_actions::StepKind::Read);
190    spec.reads_document()
191}
192
193/// Entries of each list a page of a read holds when the caller names none.
194pub const PAGE_SIZE: usize = 25;
195/// Most entries of each list a page of a read holds.
196pub const MAX_PAGE_SIZE: usize = 200;
197
198/// One page of `value`, a read of a whole resource: each list it holds at
199/// its top level cut to the `size` entries from `cursor` on (the cursor a
200/// page before answered), so a read costs a page however much the resource
201/// holds. A page that leaves entries out says how many each list holds
202/// (`totals`) and where the next page starts (`next_cursor`); one that cut
203/// nothing answers `value` as it was.
204///
205/// # Errors
206/// `cursor` is not one a read answered.
207pub fn page(
208    value: serde_json::Value,
209    cursor: Option<&str>,
210    size: Option<i64>,
211) -> Result<serde_json::Value, String> {
212    let offset = match cursor.filter(|cursor| !cursor.is_empty()) {
213        None => 0,
214        Some(cursor) => cursor
215            .parse::<usize>()
216            .map_err(|_| format!("`{cursor}` is not a cursor a read answered"))?,
217    };
218    let size = size
219        .and_then(|size| usize::try_from(size).ok())
220        .unwrap_or(PAGE_SIZE)
221        .clamp(1, MAX_PAGE_SIZE);
222    let serde_json::Value::Object(mut fields) = value else {
223        return Ok(value);
224    };
225    let end = offset.saturating_add(size);
226    let mut totals = serde_json::Map::new();
227    let mut more = false;
228    for (name, entries) in &mut fields {
229        let serde_json::Value::Array(entries) = entries else {
230            continue;
231        };
232        if offset == 0 && entries.len() <= size {
233            continue;
234        }
235        totals.insert(name.clone(), entries.len().into());
236        more |= entries.len() > end;
237        let kept: Vec<serde_json::Value> = entries.drain(..).skip(offset).take(size).collect();
238        *entries = kept;
239    }
240    if !totals.is_empty() {
241        fields.insert("totals".into(), serde_json::Value::Object(totals));
242    }
243    if more {
244        fields.insert("next_cursor".into(), end.to_string().into());
245    }
246    Ok(serde_json::Value::Object(fields))
247}
248
249/// What a record holds, as the record's own model's JSON
250/// ([`Model::to_json`]): every field it keeps, in the shape its own type
251/// gives them. Name it directly as `read_content` on a record whose fields are
252/// all it holds, so a caller with no window open — an agent, a script, the
253/// SDK — reads it through the framework's `read`, as it reads any app's
254/// record:
255///
256/// ```ignore
257/// #[resource(kind = "calculator.document", read_content = tilo_resource::read::fields)]
258/// impl Calculator {
259///     // ...
260/// }
261/// ```
262///
263/// # Errors
264/// A named `item` is not this read's to answer: the record reads whole, and
265/// whatever its table reads of an item is answered from the table after this
266/// read declines it ([`Resource::read_content`](crate::Resource::read_content)).
267/// A record whose items it answers itself says so in a read of its own.
268pub fn fields<M: Model>(record: &M, item: Option<&Id>) -> Result<serde_json::Value, String> {
269    if item.is_some() {
270        return Err(
271            "this record reads whole; its items are read from its table, or by the read its own \
272             type gives them"
273                .into(),
274        );
275    }
276    Ok(record.to_json())
277}
278
279/// What a registered read's published action is called: its id, its label and the line
280/// that says what it takes.
281#[derive(Clone, Copy, Debug)]
282pub struct ReadName<'a> {
283    pub id: &'a str,
284    pub label: &'a str,
285    pub description: &'a str,
286}
287
288/// The parameters of a read that takes none.
289#[derive(Clone, Copy, Debug, Default, serde::Deserialize, crate::JsonSchema)]
290pub struct NoReadParams {}
291
292/// A read an app declared: the published action of a registered reader, made
293/// by [`read_action`] from its name, parameters and result schema. What a
294/// surface publishes as the reads of its items (`Publishes::item_reads`) is
295/// one of these, so a row's reads are a declaration's and never a spec the
296/// app shaped.
297#[derive(Clone)]
298pub struct Declared(tilo_actions::ActionSpec);
299
300impl Declared {
301    /// The published action, for the framework that merges it into a row.
302    #[must_use]
303    pub fn into_spec(self) -> tilo_actions::ActionSpec {
304        self.0
305    }
306
307    /// The read takes the document as its input: the framework answers it from
308    /// the committed document a member may read.
309    #[must_use]
310    pub fn reads_document(mut self) -> Self {
311        self.0 = self.0.reads_document();
312        self
313    }
314}
315
316/// The published action of the registered read whose operation is `operation`. Its
317/// parameters are the fields of `P` as `P`'s JSON Schema describes them (doc comments,
318/// `#[schema(range(..))]` bounds, choices); a caller's arguments, bound strictly to them,
319/// become a `P` with serde, and `request` turns that into the reader's request.
320#[must_use]
321pub fn read_action<P, Q>(
322    name: ReadName<'_>,
323    operation: &'static str,
324    schema: fn() -> &'static serde_json::Value,
325    request: impl Fn(P) -> Q + Send + Sync + 'static,
326) -> Declared
327where
328    P: serde::de::DeserializeOwned + crate::JsonSchema,
329    Q: serde::Serialize,
330{
331    use tilo_actions::{ActionContract, EncodedAction, OperationKind, ResultSpec};
332    let params = crate::__private::flat_params(&P::json_schema());
333    Declared(
334        tilo_actions::ActionSpec::typed_operation(
335            name.id,
336            name.label,
337            name.description,
338            OperationKind::Effect,
339            operation,
340            params,
341            move |args| {
342                serde_json::from_value::<P>(serde_json::Value::Object(args.to_json()))
343                    .ok()
344                    .and_then(|params| {
345                        EncodedAction::encode_operation(operation, &request(params)).ok()
346                    })
347                    .unwrap_or_else(|| EncodedAction {
348                        type_id: operation.into(),
349                        payload: Vec::new(),
350                    })
351            },
352        )
353        .with_contract(ActionContract {
354            result: ResultSpec::Json {
355                schema: schema().clone(),
356            },
357            ..ActionContract::view()
358        }),
359    )
360}
361
362/// What `state`, an `R` in `doc`, holds, or the part of it `item` names:
363/// through `R`'s own [`Resource::read_content`] where it reads itself, else
364/// from the record's model tables. The one way `read` is answered, by the
365/// app's process and by a host that reads the record without it.
366///
367/// # Errors
368/// Why the record, or the part named, does not answer reads.
369pub fn content<R: Resource>(
370    state: &R::State,
371    doc: &crate::Doc,
372    item: Option<&str>,
373) -> Result<serde_json::Value, String> {
374    let reads_item = |item: &str| {
375        R::RESOURCE_TABLE.is_some_and(|table| crate::table::reads_item(table, R::KIND, item))
376    };
377    if R::READABLE {
378        tilo_failure::ignored!(
379            "the record table answers what the typed read did not",
380            match R::read_content(state, doc, item) {
381                Ok(content) => return Ok(content),
382                Err(error) if !item.is_some_and(reads_item) => return Err(error),
383                Err(_) => {}
384            }
385        )
386    }
387    let table = R::RESOURCE_TABLE
388        .ok_or_else(|| format!("a {} does not answer reads of its parts", R::LABEL))?;
389    crate::table::item_json(table, state, R::KIND, item.unwrap_or_default())
390}