use std::sync::Arc;
use tilo_actions::EncodedAction;
use crate::group::{ActionGroup, group_type};
use crate::resource::{Resource, publish_parts};
pub fn child_resource_id<R: Resource>(name: &str) -> String {
format!("{}/{name}", R::KIND)
}
pub fn publish_child<C, R>(
id: &str,
label: &str,
state: Option<&C::State>,
wrap: impl Fn(C::Action) -> R::Action + Send + Sync + 'static,
) -> tilo_actions::ResourceSpec
where
C: Resource,
R: Resource,
{
let wrap: Arc<dyn Fn(C::Action) -> R::Action + Send + Sync> = Arc::new(wrap);
let resource = {
let _phase = crate::profiling::Phase::start("child.publish_parts");
publish_parts::<C>(id, label, state)
};
let _phase = crate::profiling::Phase::start("child.rewrap");
rewrap::<C, R>(resource, &wrap)
}
fn rewrap<C: Resource, R: Resource>(
mut resource: tilo_actions::ResourceSpec,
wrap: &Arc<dyn Fn(C::Action) -> R::Action + Send + Sync>,
) -> tilo_actions::ResourceSpec {
resource.actions = std::mem::take(&mut resource.actions)
.into_iter()
.map(|spec| {
let wrap = Arc::clone(wrap);
spec.rewrapped(R::ACTION_TYPE, move |encoded| {
wrap_encoded::<C, R>(&encoded, wrap.as_ref())
})
.applied_as(R::KIND, R::LABEL)
})
.collect();
resource.children = std::mem::take(&mut resource.children)
.into_iter()
.map(|child| rewrap::<C, R>(child, wrap))
.collect();
resource
}
fn wrap_encoded<C: Resource, R: Resource>(
encoded: &EncodedAction,
wrap: &(dyn Fn(C::Action) -> R::Action + Send + Sync),
) -> EncodedAction {
let wrapped = if encoded.type_id == C::ACTION_TYPE {
tilo_actions::decode_json::<C::Action>(&encoded.payload)
.map_err(|error| error.to_string())
.and_then(|action| {
crate::resource::encode::<R>(&wrap(action)).map_err(|error| error.to_string())
})
} else if encoded.type_id == group_type::<C>() {
tilo_actions::decode_payload::<ActionGroup<C::Action>>(&encoded.type_id, &encoded.payload)
.map_err(|error| error.to_string())
.and_then(|group| {
let group = ActionGroup {
actions: group.actions.into_iter().map(wrap).collect::<Vec<_>>(),
};
EncodedAction::encode(group_type::<R>(), &group).map_err(|error| error.to_string())
})
} else {
Err(format!(
"`{}` is not an action of {}",
encoded.type_id,
C::LABEL
))
};
wrapped.unwrap_or_else(|reason| EncodedAction {
type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
payload: reason.into_bytes(),
})
}
#[derive(Clone, Copy)]
pub struct NestedResource {
pub kind: &'static str,
publish: fn(&str, &str) -> tilo_actions::ResourceSpec,
ops: fn(&EncodedAction) -> Result<Vec<serde_json::Value>, String>,
}
impl std::fmt::Debug for NestedResource {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("NestedResource")
.field("kind", &self.kind)
.finish_non_exhaustive()
}
}
impl NestedResource {
#[must_use]
pub const fn of<C>() -> Self
where
C: Resource + crate::Operations<Op = <C as Resource>::Action>,
{
Self {
kind: C::KIND,
publish: publish_nested::<C>,
ops: nested_ops::<C>,
}
}
}
fn publish_nested<C: Resource>(id: &str, label: &str) -> tilo_actions::ResourceSpec {
publish_parts::<C>(id, label, None)
}
fn nested_ops<C>(encoded: &EncodedAction) -> Result<Vec<serde_json::Value>, String>
where
C: Resource + crate::Operations<Op = <C as Resource>::Action>,
{
let actions: Vec<C::Action> = if encoded.type_id == C::ACTION_TYPE {
vec![
tilo_actions::decode_json::<C::Action>(&encoded.payload)
.map_err(|error| error.to_string())?,
]
} else if encoded.type_id == group_type::<C>() {
tilo_actions::decode_payload::<ActionGroup<C::Action>>(&encoded.type_id, &encoded.payload)
.map_err(|error| error.to_string())?
.actions
} else {
return Err(format!(
"`{}` is not an action of {}",
encoded.type_id,
C::LABEL
));
};
let mut ops = Vec::with_capacity(actions.len());
for action in &actions {
ops.push(crate::__private::json_via_bytes(action).map_err(|error| error.to_string())?);
}
Ok(ops)
}
#[must_use]
pub fn nested_resource_id(parent: &str, key: &str) -> String {
format!("{parent}/{key}")
}
pub(crate) fn nested_children(
vocabulary: &'static crate::Vocabulary,
shape: crate::Shape,
parent: &str,
prefix: &[crate::Segment],
item: Option<&str>,
) -> Vec<tilo_actions::ResourceSpec> {
let mut children = Vec::new();
for field in shape.fields() {
let Some(nested) = field.resource else {
continue;
};
let mut path = prefix.to_vec();
path.push(crate::Segment::Field(field.key.to_owned()));
let id = nested_resource_id(parent, field.key);
let label = item.filter(|label| !label.trim().is_empty()).map_or_else(
|| field.title.to_owned(),
|item| format!("{} of {item}", field.title),
);
let resource = (nested.publish)(&id, &label);
children.push(as_field_edits(
resource,
vocabulary,
nested.ops,
&Arc::new(path),
));
}
children
}
#[must_use]
pub fn record_nested_children<R: Resource>() -> Vec<tilo_actions::ResourceSpec> {
nested_children_of(crate::vocabulary::<R>())
}
pub(crate) fn nested_children_of(
vocabulary: &'static crate::Vocabulary,
) -> Vec<tilo_actions::ResourceSpec> {
match (vocabulary.shape)() {
Some(shape) => nested_children(vocabulary, shape, vocabulary.kind, &[], None),
None => Vec::new(),
}
}
type NestedOps = fn(&EncodedAction) -> Result<Vec<serde_json::Value>, String>;
fn as_field_edits(
mut resource: tilo_actions::ResourceSpec,
vocabulary: &'static crate::Vocabulary,
ops: NestedOps,
path: &Arc<Vec<crate::Segment>>,
) -> tilo_actions::ResourceSpec {
resource.actions = std::mem::take(&mut resource.actions)
.into_iter()
.map(|spec| {
let path = Arc::clone(path);
spec.rewrapped(vocabulary.action_type, move |encoded| {
field_edits(vocabulary, ops, &path, &encoded)
})
.applied_as(vocabulary.kind, vocabulary.label)
})
.collect();
resource.children = std::mem::take(&mut resource.children)
.into_iter()
.map(|child| as_field_edits(child, vocabulary, ops, path))
.collect();
resource
}
fn field_edits(
vocabulary: &'static crate::Vocabulary,
ops: NestedOps,
path: &[crate::Segment],
encoded: &EncodedAction,
) -> EncodedAction {
let built = ops(encoded).and_then(|ops| {
let now_ms = crate::resource::origin_now_ms();
let mut members = Vec::with_capacity(ops.len());
for rich in ops {
let edit = crate::Edit::<()>::new(path.to_vec(), crate::EditOp::Rich { rich });
members.push(crate::resource::stamped_edit(vocabulary, edit, now_ms)?);
}
Ok(members)
});
match built {
Ok(members) => crate::resource::encode_group(vocabulary, &members),
Err(reason) => crate::resource::encode_built(Err(reason)),
}
}