use serde::{Deserialize, Serialize};
use crate::PathStep;
pub use crate::field_type::{FieldType, NamedType, TypeCase, TypeField, TypeSet};
use tilo_action_policy::ActionKind;
#[allow(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if passes the field by reference"
)]
const fn is_false(value: &bool) -> bool {
!*value
}
pub const RESOURCE_UNIT: &str = "record";
pub const TYPE_VERB: &str = "type";
pub const MIGRATE_VERB: &str = "migrate";
pub const CONTENT_VERBS: [&str; 2] = [TYPE_VERB, MIGRATE_VERB];
pub const ADDRESS_KEY: &str = "$address";
pub const CHAIN_UNSENT_KIND: &str = "tilo.chain-unsent";
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Surface {
pub kind: String,
pub label: String,
pub version: u32,
#[serde(default, skip_serializing_if = "is_false")]
pub person: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub readers: Option<ReaderRule>,
#[serde(default)]
pub verbs: Vec<VerbSurface>,
#[serde(default)]
pub fields: Vec<FieldSurface>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub types: Vec<NamedType>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub shows: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub live: Option<LiveSurface>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub setters: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LiveSurface {
pub when: serde_json::Value,
pub view: String,
}
pub use tilo_action_policy::ReaderRule;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VerbSurface {
pub id: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub kind: ActionKind,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub destructive: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub incoming_message: bool,
#[serde(default)]
pub params: Vec<ParamSurface>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub returns: Option<ReturnsSurface>,
#[serde(default = "record_unit", skip_serializing_if = "only_resource")]
pub writes: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
}
fn stored_value() -> String {
STORED_VALUE.to_owned()
}
impl VerbSurface {
#[must_use]
pub fn offered(&self) -> &str {
if self.name.is_empty() {
&self.id
} else {
&self.name
}
}
}
pub const STORED_VALUE: &str = "value";
fn record_unit() -> Vec<String> {
vec![RESOURCE_UNIT.to_owned()]
}
fn only_resource(units: &[String]) -> bool {
units == [RESOURCE_UNIT]
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ParamSurface {
pub name: String,
pub required: bool,
#[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
pub schema: serde_json::Value,
#[serde(
rename = "type",
default,
skip_serializing_if = "FieldType::is_any",
deserialize_with = "crate::field_type::field_type_or_text"
)]
pub ty: FieldType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub within: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReturnsSurface {
#[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
pub schema: serde_json::Value,
#[serde(
rename = "type",
default,
skip_serializing_if = "FieldType::is_any",
deserialize_with = "crate::field_type::field_type_or_text"
)]
pub ty: FieldType,
}
#[must_use]
pub fn param_type(param: &crate::ActionParam) -> FieldType {
use crate::ParamType;
match param.ty {
ParamType::Text | ParamType::DateTime => FieldType::Text,
ParamType::Secret => FieldType::Secret,
ParamType::Resource => {
FieldType::Resource(param.resource_kind().unwrap_or_default().to_owned())
}
ParamType::Integer => FieldType::Int,
ParamType::Number => FieldType::Float,
ParamType::Boolean => FieldType::Bool,
ParamType::Object | ParamType::Array => param
.schema
.as_deref()
.map_or(FieldType::Any, FieldType::from_schema),
}
}
#[must_use]
pub fn verb_of(action: &crate::ActionSpec, params: Vec<ParamSurface>) -> VerbSurface {
VerbSurface {
id: action.id.clone(),
name: String::new(),
label: String::new(),
description: None,
kind: action.contract.settled_kind(),
destructive: action.contract.risk == crate::RiskLevel::Destructive,
incoming_message: false,
params,
returns: result_of(&action.contract.result),
writes: record_unit(),
field: None,
tags: Vec::new(),
}
}
fn result_of(result: &crate::ResultSpec) -> Option<ReturnsSurface> {
match result {
crate::ResultSpec::Json { schema } => Some(ReturnsSurface {
schema: schema.clone(),
ty: crate::field_type::FieldType::from_schema(schema),
}),
crate::ResultSpec::None | crate::ResultSpec::Resource { .. } | crate::ResultSpec::Job => {
None
}
}
}
#[must_use]
pub fn of_resource(spec: &crate::ResourceSpec) -> Surface {
let verbs = spec
.actions
.iter()
.map(|action| {
let params = action
.params()
.iter()
.map(|param| ParamSurface {
name: param.name.to_string(),
required: param.required,
schema: serde_json::Value::Null,
ty: param_type(param),
within: None,
})
.collect();
verb_of(action, params)
})
.collect();
Surface {
kind: spec.kind.clone(),
label: String::new(),
version: 0,
person: false,
readers: None,
verbs,
fields: Vec::new(),
types: Vec::new(),
shows: Vec::new(),
live: None,
setters: false,
}
}
#[must_use]
pub fn nest_arguments(
verb: &VerbSurface,
arguments: Vec<(String, serde_json::Value)>,
) -> serde_json::Map<String, serde_json::Value> {
let mut out = serde_json::Map::new();
for (name, value) in arguments {
let within = verb
.params
.iter()
.find(|param| param.name == name)
.and_then(|param| param.within.clone());
match within {
Some(outer) => {
let nested = out
.entry(outer)
.or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
if let serde_json::Value::Object(fields) = nested {
fields.insert(name, value);
}
}
None => {
out.insert(name, value);
}
}
}
out
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[expect(
clippy::struct_excessive_bools,
reason = "each flag is one mark a committed surface file writes for the field, read on its own"
)]
pub struct FieldSurface {
pub path: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub owner: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub title: String,
#[serde(default = "stored_value")]
pub stored: String,
#[serde(
rename = "type",
deserialize_with = "crate::field_type::field_type_or_text"
)]
pub ty: FieldType,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub readonly: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub unit: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub label: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub whole: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ops: Option<serde_json::Value>,
}
#[must_use]
pub fn setter_id(key: &str) -> String {
format!("set-{}", key.replace('_', "-"))
}
impl Surface {
#[must_use]
pub fn with_setters(mut self) -> Self {
let setters: Vec<VerbSurface> = self
.fields
.iter()
.filter(|field| !field.readonly && !field.path.contains('.'))
.map(|field| (setter_id(&field.path), field))
.filter(|(id, _)| !self.verbs.iter().any(|verb| verb.id == *id))
.map(|(id, field)| {
let param = |name: &str, ty: FieldType| ParamSurface {
name: name.to_owned(),
required: false,
schema: serde_json::Value::Null,
ty,
within: None,
};
let mut params = Vec::new();
if !matches!(field.stored.as_str(), "collection" | "keyed") {
params.push(param("value", field.ty.clone()));
}
if !field.whole {
params.push(param("edit", FieldType::Any));
}
VerbSurface {
id,
name: String::new(),
label: format!("Set {}", field.path.replace('_', " ")),
description: None,
kind: ActionKind::Undoable,
destructive: false,
incoming_message: false,
params,
returns: None,
writes: vec![RESOURCE_UNIT.to_owned()],
field: None,
tags: Vec::new(),
}
})
.collect();
self.verbs.extend(setters);
self
}
#[must_use]
pub fn named(&self, name: &str) -> Option<&NamedType> {
self.types.iter().find(|ty| ty.name == name)
}
#[must_use]
pub fn verb(&self, action: &str) -> Option<(ActionKind, Option<String>)> {
self.verbs
.iter()
.find(|verb| verb.id == action)
.map(|verb| (verb.kind, verb.field.clone()))
}
fn field_at(&self, path: &[PathStep]) -> Option<&FieldSurface> {
let mut dotted = String::new();
let mut found = None;
for step in path {
let part = match step {
PathStep::Field(key) => key.as_str(),
PathStep::Item(_) | PathStep::Key(_) | PathStep::Cell(..) => "*",
};
if !dotted.is_empty() {
dotted.push('.');
}
dotted.push_str(part);
if let Some(field) = self.fields.iter().find(|field| field.path == dotted) {
found = Some(field);
}
}
found
}
#[must_use]
pub fn editable(&self, path: &[PathStep]) -> bool {
let Some(field) = self.field_at(path) else {
return false;
};
if field.ty.is_reactions() {
return true;
}
!self.fields.iter().any(|candidate| {
candidate.readonly
&& (field.path == candidate.path
|| field.path.starts_with(&format!("{}.", candidate.path)))
})
}
#[must_use]
pub fn edit_unit(&self, path: &[PathStep]) -> Vec<PathStep> {
let mut dotted = String::new();
let mut unit = Vec::new();
for (index, step) in path.iter().enumerate() {
let PathStep::Field(key) = step else {
if !dotted.is_empty() {
dotted.push('.');
}
dotted.push('*');
continue;
};
if !dotted.is_empty() {
dotted.push('.');
}
dotted.push_str(key);
let Some(field) = self.fields.iter().find(|field| field.path == dotted) else {
continue;
};
if field.unit {
let through = if matches!(field.stored.as_str(), "collection" | "keyed") {
index.saturating_add(2)
} else {
index.saturating_add(1)
};
unit = path.iter().take(through).cloned().collect();
}
}
unit
}
#[must_use]
pub fn footprint(&self, action: &str, item: Option<&str>) -> Vec<Vec<PathStep>> {
let Some(verb) = self.verbs.iter().find(|verb| verb.id == action) else {
return Vec::new();
};
verb.writes
.iter()
.map(|unit| {
if unit == RESOURCE_UNIT {
return Vec::new();
}
match unit.strip_suffix(".*") {
Some(field) => vec![
PathStep::Field(field.to_owned()),
PathStep::Item(item.unwrap_or("*").to_owned()),
],
None => vec![PathStep::Field(unit.clone())],
}
})
.collect()
}
}