use serde::{Deserialize, Serialize};
pub const CONTENT_RESOURCE_KIND: &str = "tilo.content";
pub fn content_resource(hash: &str) -> Option<String> {
(!hash.is_empty() && !hash.contains(':')).then(|| format!("{CONTENT_RESOURCE_KIND}:{hash}"))
}
pub fn content_hash(address: &str) -> Option<&str> {
address
.strip_prefix(CONTENT_RESOURCE_KIND)?
.strip_prefix(':')
.filter(|hash| !hash.is_empty() && !hash.contains(':'))
}
pub fn named_reference(value: &str) -> Option<&str> {
let value = value.trim();
let reference = content_hash(value).unwrap_or(value);
tilo_content::valid_reference(reference).then_some(reference)
}
pub use tilo_action_types::InvocationId;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub struct ActionOutput {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub resources: Vec<String>,
}
read_through_json_value!(ActionOutput);
impl ActionOutput {
#[must_use]
pub fn wrote(&self) -> Option<crate::InteractionAnchor> {
serde_json::from_value(self.value.as_ref()?.get("wrote")?.clone()).ok()
}
#[must_use]
pub fn noting_wrote(
value: Option<serde_json::Value>,
wrote: &crate::InteractionAnchor,
) -> Option<serde_json::Value> {
let mut fields = match value {
None | Some(serde_json::Value::Null) => serde_json::Map::new(),
Some(serde_json::Value::Object(fields)) => fields,
other => return other,
};
fields.insert("wrote".into(), serde_json::to_value(wrote).ok()?);
Some(serde_json::Value::Object(fields))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self")]
pub struct ActionFailure {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<serde_json::Value>,
#[serde(default)]
pub retryable: bool,
}
read_through_json_value!(ActionFailure);
impl ActionFailure {
#[must_use]
pub fn asks(message: impl Into<String>, facts: &crate::remote::asked::AskedFacts) -> Self {
Self {
code: crate::remote::CONFIRMATION_REQUIRED_CODE.to_owned(),
message: message.into(),
details: Some(facts.to_details()),
retryable: false,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "state", rename_all = "snake_case")]
pub enum InvocationUpdate {
Accepted {
invocation: InvocationId,
},
Progress {
invocation: InvocationId,
sequence: u64,
phase: String,
completed: Option<u64>,
total: Option<u64>,
message: Option<String>,
},
Item {
invocation: InvocationId,
sequence: u64,
value: serde_json::Value,
},
Succeeded {
invocation: InvocationId,
output: ActionOutput,
},
Failed {
invocation: InvocationId,
error: ActionFailure,
},
Cancelled {
invocation: InvocationId,
message: Option<String>,
},
}
read_through_json_value!(InvocationUpdate);
impl InvocationUpdate {
pub fn invocation(&self) -> InvocationId {
match self {
Self::Accepted { invocation }
| Self::Progress { invocation, .. }
| Self::Item { invocation, .. }
| Self::Succeeded { invocation, .. }
| Self::Failed { invocation, .. }
| Self::Cancelled { invocation, .. } => *invocation,
}
}
pub fn is_terminal(&self) -> bool {
matches!(
self,
Self::Succeeded { .. } | Self::Failed { .. } | Self::Cancelled { .. }
)
}
#[must_use]
pub fn asks_again(&self) -> bool {
matches!(self, Self::Failed { error, .. } if error.retryable)
}
#[must_use]
pub fn with_invocation(mut self, id: InvocationId) -> Self {
match &mut self {
Self::Accepted { invocation }
| Self::Progress { invocation, .. }
| Self::Item { invocation, .. }
| Self::Succeeded { invocation, .. }
| Self::Failed { invocation, .. }
| Self::Cancelled { invocation, .. } => *invocation = id,
}
self
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum EffectReceiptStatus {
Succeeded,
Failed { code: String },
Cancelled,
}
impl EffectReceiptStatus {
pub fn from_terminal(update: &InvocationUpdate) -> Option<Self> {
match update {
InvocationUpdate::Succeeded { .. } => Some(Self::Succeeded),
InvocationUpdate::Failed { error, .. } => Some(Self::Failed {
code: bounded_identifier(&error.code, "action_failed"),
}),
InvocationUpdate::Cancelled { .. } => Some(Self::Cancelled),
InvocationUpdate::Accepted { .. }
| InvocationUpdate::Progress { .. }
| InvocationUpdate::Item { .. } => None,
}
}
pub const fn label(&self) -> &'static str {
match self {
Self::Succeeded => "Completed",
Self::Failed { .. } => "Failed",
Self::Cancelled => "Cancelled",
}
}
}
fn bounded_identifier(value: &str, fallback: &str) -> String {
let safe = value
.chars()
.filter(|character| {
character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '.')
})
.take(96)
.collect::<String>();
if safe.is_empty() {
fallback.to_string()
} else {
safe
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn outcomes_address_content_exactly_and_redact_terminal_payloads() {
content_resource_addresses_round_trip_without_guessing();
effect_receipt_redacts_terminal_payloads();
an_invocation_id_is_read_back_as_the_caller_wrote_it();
}
fn an_invocation_id_is_read_back_as_the_caller_wrote_it() {
let invocation = InvocationId::new();
let text = invocation.0.to_string();
assert_eq!(
text.parse::<InvocationId>().expect("its own id reads back"),
invocation
);
assert_eq!(
format!(" {text} ")
.parse::<InvocationId>()
.expect("spaced text reads"),
invocation
);
assert!("not an invocation".parse::<InvocationId>().is_err());
}
fn content_resource_addresses_round_trip_without_guessing() {
let address = content_resource("abc123").expect("a content hash has an address");
assert_eq!(address, "tilo.content:abc123");
assert_eq!(content_hash(&address), Some("abc123"));
assert_eq!(content_resource(""), None);
assert_eq!(content_resource("two:parts"), None);
assert_eq!(content_hash("files.entry:/tmp/a"), None);
}
fn effect_receipt_redacts_terminal_payloads() {
let invocation = InvocationId::new();
let update = InvocationUpdate::Failed {
invocation,
error: ActionFailure {
code: "smtp.secret\ncode".into(),
message: "password=hunter2".into(),
details: Some(serde_json::json!({"token": "private"})),
retryable: true,
},
};
let receipt = EffectReceiptStatus::from_terminal(&update).expect("terminal receipt");
assert_eq!(
receipt,
EffectReceiptStatus::Failed {
code: "smtp.secretcode".into()
}
);
let json = serde_json::to_string(&receipt).expect("encode receipt");
assert!(!json.contains("hunter2"));
assert!(!json.contains("private"));
}
}