1use crate::{Id, Model, Resource};
10
11pub const TYPE: &str = "tilo.resource.read";
13
14#[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
28const JSON_ENTRY_VALUE: &str = "value";
31
32fn 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#[must_use]
72pub fn spec(item: Option<&str>) -> tilo_actions::ActionSpec {
73 spec_on(None, item)
74}
75
76#[must_use]
80pub fn resource_spec(record: &str) -> tilo_actions::ActionSpec {
81 spec_on(Some(record), None)
82}
83
84#[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 .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
193pub const PAGE_SIZE: usize = 25;
195pub const MAX_PAGE_SIZE: usize = 200;
197
198pub 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
249pub 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#[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#[derive(Clone, Copy, Debug, Default, serde::Deserialize, crate::JsonSchema)]
290pub struct NoReadParams {}
291
292#[derive(Clone)]
298pub struct Declared(tilo_actions::ActionSpec);
299
300impl Declared {
301 #[must_use]
303 pub fn into_spec(self) -> tilo_actions::ActionSpec {
304 self.0
305 }
306
307 #[must_use]
310 pub fn reads_document(mut self) -> Self {
311 self.0 = self.0.reads_document();
312 self
313 }
314}
315
316#[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
362pub 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}