Skip to main content

tilo_resource/
child.rs

1//! Resources nested inside another: a note's rich-text body, a draft's
2//! message, a saved query's SQL.
3//!
4//! A child is a resource type of its own — it has its own actions, views and
5//! search — stored at a place inside its parent's document. Its edits are
6//! the parent's: the parent has an action that carries one child action and
7//! names where it applies (`EditBody { page, edit }`), so history, undo,
8//! permissions and replay stay the parent's, and a member replays the
9//! edit exactly as it was made.
10//!
11//! [`publish_child`] publishes such a child beneath its parent with every
12//! document action re-encoded as the parent's, so the palette, agents and
13//! scripts address the child like any resource — its own named actions,
14//! [`APPLY`](crate::APPLY) and [`GROUP`](crate::GROUP) — and every invocation
15//! applies as the parent's action. A view edits such a child through its
16//! dispatcher, which publishes it there; a field the record itself declares
17//! (`#[model(resource)]`) is published for it.
18
19use std::sync::Arc;
20
21use tilo_actions::EncodedAction;
22
23use crate::group::{ActionGroup, group_type};
24use crate::resource::{Resource, publish_parts};
25
26/// The id a child resource named `name` of `R` is published under:
27/// `<kind>/<name>`, beside the item resources of `R`'s collections.
28pub fn child_resource_id<R: Resource>(name: &str) -> String {
29    format!("{}/{name}", R::KIND)
30}
31
32/// The child resource `C` at `id`, inside a resource `R`: `C`'s whole
33/// published tree (its declared actions,
34/// [`APPLY`](crate::resource::APPLY), [`GROUP`](crate::GROUP), and given its `state` its views and
35/// its own children), each document action building `R`'s action
36/// `wrap(edit)` instead of `C`'s. A group of `C`'s edits becomes one group
37/// of `R`'s, so it is still one step. A parent that does not keep the
38/// child's state passes `None`: the child's edits are still all there.
39pub fn publish_child<C, R>(
40    id: &str,
41    label: &str,
42    state: Option<&C::State>,
43    wrap: impl Fn(C::Action) -> R::Action + Send + Sync + 'static,
44) -> tilo_actions::ResourceSpec
45where
46    C: Resource,
47    R: Resource,
48{
49    let wrap: Arc<dyn Fn(C::Action) -> R::Action + Send + Sync> = Arc::new(wrap);
50    let resource = {
51        let _phase = crate::profiling::Phase::start("child.publish_parts");
52        publish_parts::<C>(id, label, state)
53    };
54    let _phase = crate::profiling::Phase::start("child.rewrap");
55    rewrap::<C, R>(resource, &wrap)
56}
57
58fn rewrap<C: Resource, R: Resource>(
59    mut resource: tilo_actions::ResourceSpec,
60    wrap: &Arc<dyn Fn(C::Action) -> R::Action + Send + Sync>,
61) -> tilo_actions::ResourceSpec {
62    resource.actions = std::mem::take(&mut resource.actions)
63        .into_iter()
64        .map(|spec| {
65            let wrap = Arc::clone(wrap);
66            spec.rewrapped(R::ACTION_TYPE, move |encoded| {
67                wrap_encoded::<C, R>(&encoded, wrap.as_ref())
68            })
69            .applied_as(R::KIND, R::LABEL)
70        })
71        .collect();
72    resource.children = std::mem::take(&mut resource.children)
73        .into_iter()
74        .map(|child| rewrap::<C, R>(child, wrap))
75        .collect();
76    resource
77}
78
79/// `C`'s encoded action (or group) as `R`'s; anything that does not decode
80/// as one is refused with the reason.
81fn wrap_encoded<C: Resource, R: Resource>(
82    encoded: &EncodedAction,
83    wrap: &(dyn Fn(C::Action) -> R::Action + Send + Sync),
84) -> EncodedAction {
85    let wrapped = if encoded.type_id == C::ACTION_TYPE {
86        tilo_actions::decode_json::<C::Action>(&encoded.payload)
87            .map_err(|error| error.to_string())
88            .and_then(|action| {
89                crate::resource::encode::<R>(&wrap(action)).map_err(|error| error.to_string())
90            })
91    } else if encoded.type_id == group_type::<C>() {
92        tilo_actions::decode_payload::<ActionGroup<C::Action>>(&encoded.type_id, &encoded.payload)
93            .map_err(|error| error.to_string())
94            .and_then(|group| {
95                let group = ActionGroup {
96                    actions: group.actions.into_iter().map(wrap).collect::<Vec<_>>(),
97                };
98                EncodedAction::encode(group_type::<R>(), &group).map_err(|error| error.to_string())
99            })
100    } else {
101        Err(format!(
102            "`{}` is not an action of {}",
103            encoded.type_id,
104            C::LABEL
105        ))
106    };
107    wrapped.unwrap_or_else(|reason| EncodedAction {
108        type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
109        payload: reason.into_bytes(),
110    })
111}
112
113/// A field that holds a resource of its own type (`#[model(resource)]`): a
114/// note's rich-text body. `#[resource]` publishes it beneath the resource
115/// of the record that holds it — the item resource of an item of a
116/// collection (`<kind>/pages/<page>/body`), or the record itself
117/// (`<kind>/body`) — with every document action of the field's type applied
118/// as the record's field edit at the field's path. So the field is
119/// addressed like any resource, with its own named actions, and nothing
120/// about it is repeated on the record: no copy of its verbs taking an item
121/// id, no second write path. The record's history, undo, permissions and
122/// replay are the ones that apply.
123#[derive(Clone, Copy)]
124pub struct NestedResource {
125    /// The field type's [`Resource::KIND`].
126    pub kind: &'static str,
127    publish: fn(&str, &str) -> tilo_actions::ResourceSpec,
128    ops: fn(&EncodedAction) -> Result<Vec<serde_json::Value>, String>,
129}
130
131impl std::fmt::Debug for NestedResource {
132    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        formatter
134            .debug_struct("NestedResource")
135            .field("kind", &self.kind)
136            .finish_non_exhaustive()
137    }
138}
139
140impl NestedResource {
141    /// The nested resource of a field of type `C`, whose own operations are
142    /// its actions: what `#[model(resource)]` records in the field's
143    /// [`FieldShape`](crate::FieldShape).
144    #[must_use]
145    pub const fn of<C>() -> Self
146    where
147        C: Resource + crate::Operations<Op = <C as Resource>::Action>,
148    {
149        Self {
150            kind: C::KIND,
151            publish: publish_nested::<C>,
152            ops: nested_ops::<C>,
153        }
154    }
155}
156
157/// `C`'s published tree at `id`, labelled `label`, its actions still `C`'s.
158fn publish_nested<C: Resource>(id: &str, label: &str) -> tilo_actions::ResourceSpec {
159    publish_parts::<C>(id, label, None)
160}
161
162/// The operations an encoded action (or group) of `C` carries, as the JSON a
163/// field edit of a `C` field takes ([`crate::EditOp::Rich`]).
164fn nested_ops<C>(encoded: &EncodedAction) -> Result<Vec<serde_json::Value>, String>
165where
166    C: Resource + crate::Operations<Op = <C as Resource>::Action>,
167{
168    let actions: Vec<C::Action> = if encoded.type_id == C::ACTION_TYPE {
169        vec![
170            tilo_actions::decode_json::<C::Action>(&encoded.payload)
171                .map_err(|error| error.to_string())?,
172        ]
173    } else if encoded.type_id == group_type::<C>() {
174        tilo_actions::decode_payload::<ActionGroup<C::Action>>(&encoded.type_id, &encoded.payload)
175            .map_err(|error| error.to_string())?
176            .actions
177    } else {
178        return Err(format!(
179            "`{}` is not an action of {}",
180            encoded.type_id,
181            C::LABEL
182        ));
183    };
184    let mut ops = Vec::with_capacity(actions.len());
185    for action in &actions {
186        ops.push(crate::__private::json_via_bytes(action).map_err(|error| error.to_string())?);
187    }
188    Ok(ops)
189}
190
191/// The id of the resource the field `key` of the record at `parent` (a
192/// published resource id) is published as: `<parent>/<key>`.
193#[must_use]
194pub fn nested_resource_id(parent: &str, key: &str) -> String {
195    format!("{parent}/{key}")
196}
197
198/// The fields of the record shaped `shape` that hold resources of their own,
199/// each published beneath `parent` (the record's published id) with its
200/// actions applied as field edits of the resource `vocabulary` at `prefix`
201/// (the record's path) followed by the field's key.
202///
203/// A field of an item is labelled with its item's (`item`): "Body of
204/// Review v1". Every note's body would otherwise read "Body", and an agent
205/// choosing where to write, shown only the labels, could not tell one
206/// note's body from another's.
207pub(crate) fn nested_children(
208    vocabulary: &'static crate::Vocabulary,
209    shape: crate::Shape,
210    parent: &str,
211    prefix: &[crate::Segment],
212    item: Option<&str>,
213) -> Vec<tilo_actions::ResourceSpec> {
214    let mut children = Vec::new();
215    for field in shape.fields() {
216        let Some(nested) = field.resource else {
217            continue;
218        };
219        let mut path = prefix.to_vec();
220        path.push(crate::Segment::Field(field.key.to_owned()));
221        let id = nested_resource_id(parent, field.key);
222        let label = item.filter(|label| !label.trim().is_empty()).map_or_else(
223            || field.title.to_owned(),
224            |item| format!("{} of {item}", field.title),
225        );
226        let resource = (nested.publish)(&id, &label);
227        children.push(as_field_edits(
228            resource,
229            vocabulary,
230            nested.ops,
231            &Arc::new(path),
232        ));
233    }
234    children
235}
236
237/// The children `nested_children` publishes for the record itself
238/// (`#[model(resource)]` fields of `R`, not of its items).
239#[must_use]
240pub fn record_nested_children<R: Resource>() -> Vec<tilo_actions::ResourceSpec> {
241    nested_children_of(crate::vocabulary::<R>())
242}
243
244/// [`record_nested_children`] of the record whose vocabulary is `vocabulary`.
245pub(crate) fn nested_children_of(
246    vocabulary: &'static crate::Vocabulary,
247) -> Vec<tilo_actions::ResourceSpec> {
248    match (vocabulary.shape)() {
249        Some(shape) => nested_children(vocabulary, shape, vocabulary.kind, &[], None),
250        None => Vec::new(),
251    }
252}
253
254type NestedOps = fn(&EncodedAction) -> Result<Vec<serde_json::Value>, String>;
255
256/// `resource` with every document action re-encoded as the field edit of
257/// the resource `vocabulary` at `path` carrying the operations it carried.
258fn as_field_edits(
259    mut resource: tilo_actions::ResourceSpec,
260    vocabulary: &'static crate::Vocabulary,
261    ops: NestedOps,
262    path: &Arc<Vec<crate::Segment>>,
263) -> tilo_actions::ResourceSpec {
264    resource.actions = std::mem::take(&mut resource.actions)
265        .into_iter()
266        .map(|spec| {
267            let path = Arc::clone(path);
268            spec.rewrapped(vocabulary.action_type, move |encoded| {
269                field_edits(vocabulary, ops, &path, &encoded)
270            })
271            .applied_as(vocabulary.kind, vocabulary.label)
272        })
273        .collect();
274    resource.children = std::mem::take(&mut resource.children)
275        .into_iter()
276        .map(|child| as_field_edits(child, vocabulary, ops, path))
277        .collect();
278    resource
279}
280
281/// The field edits at `path` carrying the operations of `encoded`: one edit,
282/// or a group of them that is still one step. Refused with the reason when
283/// `encoded` is no action of the field's type.
284fn field_edits(
285    vocabulary: &'static crate::Vocabulary,
286    ops: NestedOps,
287    path: &[crate::Segment],
288    encoded: &EncodedAction,
289) -> EncodedAction {
290    let built = ops(encoded).and_then(|ops| {
291        let now_ms = crate::resource::origin_now_ms();
292        let mut members = Vec::with_capacity(ops.len());
293        for rich in ops {
294            let edit = crate::Edit::<()>::new(path.to_vec(), crate::EditOp::Rich { rich });
295            members.push(crate::resource::stamped_edit(vocabulary, edit, now_ms)?);
296        }
297        Ok(members)
298    });
299    match built {
300        Ok(members) => crate::resource::encode_group(vocabulary, &members),
301        Err(reason) => crate::resource::encode_built(Err(reason)),
302    }
303}