1use std::sync::Arc;
20
21use tilo_actions::EncodedAction;
22
23use crate::group::{ActionGroup, group_type};
24use crate::resource::{Resource, publish_parts};
25
26pub fn child_resource_id<R: Resource>(name: &str) -> String {
29 format!("{}/{name}", R::KIND)
30}
31
32pub 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
79fn 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#[derive(Clone, Copy)]
124pub struct NestedResource {
125 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 #[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
157fn publish_nested<C: Resource>(id: &str, label: &str) -> tilo_actions::ResourceSpec {
159 publish_parts::<C>(id, label, None)
160}
161
162fn 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#[must_use]
194pub fn nested_resource_id(parent: &str, key: &str) -> String {
195 format!("{parent}/{key}")
196}
197
198pub(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#[must_use]
240pub fn record_nested_children<R: Resource>() -> Vec<tilo_actions::ResourceSpec> {
241 nested_children_of(crate::vocabulary::<R>())
242}
243
244pub(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
256fn 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
281fn 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}