1use serde::{Deserialize, Serialize};
4
5pub const CONTENT_RESOURCE_KIND: &str = "tilo.content";
11
12pub fn content_resource(hash: &str) -> Option<String> {
17 (!hash.is_empty() && !hash.contains(':')).then(|| format!("{CONTENT_RESOURCE_KIND}:{hash}"))
18}
19
20pub fn content_hash(address: &str) -> Option<&str> {
22 address
23 .strip_prefix(CONTENT_RESOURCE_KIND)?
24 .strip_prefix(':')
25 .filter(|hash| !hash.is_empty() && !hash.contains(':'))
26}
27
28pub fn named_reference(value: &str) -> Option<&str> {
31 let value = value.trim();
32 let reference = content_hash(value).unwrap_or(value);
33 tilo_content::valid_reference(reference).then_some(reference)
34}
35
36pub use tilo_action_types::InvocationId;
37
38#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
39#[serde(remote = "Self")]
40pub struct ActionOutput {
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub value: Option<serde_json::Value>,
43 #[serde(default, skip_serializing_if = "Vec::is_empty")]
45 pub resources: Vec<String>,
46}
47
48read_through_json_value!(ActionOutput);
49
50impl ActionOutput {
51 #[must_use]
54 pub fn wrote(&self) -> Option<crate::InteractionAnchor> {
55 serde_json::from_value(self.value.as_ref()?.get("wrote")?.clone()).ok()
56 }
57
58 #[must_use]
61 pub fn noting_wrote(
62 value: Option<serde_json::Value>,
63 wrote: &crate::InteractionAnchor,
64 ) -> Option<serde_json::Value> {
65 let mut fields = match value {
66 None | Some(serde_json::Value::Null) => serde_json::Map::new(),
67 Some(serde_json::Value::Object(fields)) => fields,
68 other => return other,
69 };
70 fields.insert("wrote".into(), serde_json::to_value(wrote).ok()?);
71 Some(serde_json::Value::Object(fields))
72 }
73}
74
75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76#[serde(remote = "Self")]
77pub struct ActionFailure {
78 pub code: String,
79 pub message: String,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub details: Option<serde_json::Value>,
82 #[serde(default)]
83 pub retryable: bool,
84}
85
86read_through_json_value!(ActionFailure);
87
88impl ActionFailure {
89 #[must_use]
94 pub fn asks(message: impl Into<String>, facts: &crate::remote::asked::AskedFacts) -> Self {
95 Self {
96 code: crate::remote::CONFIRMATION_REQUIRED_CODE.to_owned(),
97 message: message.into(),
98 details: Some(facts.to_details()),
99 retryable: false,
100 }
101 }
102}
103
104#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
107#[serde(remote = "Self", tag = "state", rename_all = "snake_case")]
108pub enum InvocationUpdate {
109 Accepted {
110 invocation: InvocationId,
111 },
112 Progress {
113 invocation: InvocationId,
114 sequence: u64,
115 phase: String,
116 completed: Option<u64>,
117 total: Option<u64>,
118 message: Option<String>,
119 },
120 Item {
122 invocation: InvocationId,
123 sequence: u64,
124 value: serde_json::Value,
125 },
126 Succeeded {
127 invocation: InvocationId,
128 output: ActionOutput,
129 },
130 Failed {
131 invocation: InvocationId,
132 error: ActionFailure,
133 },
134 Cancelled {
135 invocation: InvocationId,
136 message: Option<String>,
137 },
138}
139
140read_through_json_value!(InvocationUpdate);
141
142impl InvocationUpdate {
143 pub fn invocation(&self) -> InvocationId {
144 match self {
145 Self::Accepted { invocation }
146 | Self::Progress { invocation, .. }
147 | Self::Item { invocation, .. }
148 | Self::Succeeded { invocation, .. }
149 | Self::Failed { invocation, .. }
150 | Self::Cancelled { invocation, .. } => *invocation,
151 }
152 }
153
154 pub fn is_terminal(&self) -> bool {
155 matches!(
156 self,
157 Self::Succeeded { .. } | Self::Failed { .. } | Self::Cancelled { .. }
158 )
159 }
160
161 #[must_use]
165 pub fn asks_again(&self) -> bool {
166 matches!(self, Self::Failed { error, .. } if error.retryable)
167 }
168
169 #[must_use]
172 pub fn with_invocation(mut self, id: InvocationId) -> Self {
173 match &mut self {
174 Self::Accepted { invocation }
175 | Self::Progress { invocation, .. }
176 | Self::Item { invocation, .. }
177 | Self::Succeeded { invocation, .. }
178 | Self::Failed { invocation, .. }
179 | Self::Cancelled { invocation, .. } => *invocation = id,
180 }
181 self
182 }
183}
184
185#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(tag = "status", rename_all = "snake_case")]
194pub enum EffectReceiptStatus {
195 Succeeded,
196 Failed { code: String },
197 Cancelled,
198}
199
200impl EffectReceiptStatus {
201 pub fn from_terminal(update: &InvocationUpdate) -> Option<Self> {
204 match update {
205 InvocationUpdate::Succeeded { .. } => Some(Self::Succeeded),
206 InvocationUpdate::Failed { error, .. } => Some(Self::Failed {
207 code: bounded_identifier(&error.code, "action_failed"),
208 }),
209 InvocationUpdate::Cancelled { .. } => Some(Self::Cancelled),
210 InvocationUpdate::Accepted { .. }
211 | InvocationUpdate::Progress { .. }
212 | InvocationUpdate::Item { .. } => None,
213 }
214 }
215
216 pub const fn label(&self) -> &'static str {
217 match self {
218 Self::Succeeded => "Completed",
219 Self::Failed { .. } => "Failed",
220 Self::Cancelled => "Cancelled",
221 }
222 }
223}
224
225fn bounded_identifier(value: &str, fallback: &str) -> String {
226 let safe = value
227 .chars()
228 .filter(|character| {
229 character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '.')
230 })
231 .take(96)
232 .collect::<String>();
233 if safe.is_empty() {
234 fallback.to_string()
235 } else {
236 safe
237 }
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
248 fn outcomes_address_content_exactly_and_redact_terminal_payloads() {
249 content_resource_addresses_round_trip_without_guessing();
250 effect_receipt_redacts_terminal_payloads();
251 an_invocation_id_is_read_back_as_the_caller_wrote_it();
252 }
253
254 fn an_invocation_id_is_read_back_as_the_caller_wrote_it() {
257 let invocation = InvocationId::new();
258 let text = invocation.0.to_string();
259 assert_eq!(
260 text.parse::<InvocationId>().expect("its own id reads back"),
261 invocation
262 );
263 assert_eq!(
264 format!(" {text} ")
265 .parse::<InvocationId>()
266 .expect("spaced text reads"),
267 invocation
268 );
269 assert!("not an invocation".parse::<InvocationId>().is_err());
270 }
271
272 fn content_resource_addresses_round_trip_without_guessing() {
273 let address = content_resource("abc123").expect("a content hash has an address");
274 assert_eq!(address, "tilo.content:abc123");
275 assert_eq!(content_hash(&address), Some("abc123"));
276 assert_eq!(content_resource(""), None);
277 assert_eq!(content_resource("two:parts"), None);
278 assert_eq!(content_hash("files.entry:/tmp/a"), None);
279 }
280
281 fn effect_receipt_redacts_terminal_payloads() {
282 let invocation = InvocationId::new();
283 let update = InvocationUpdate::Failed {
284 invocation,
285 error: ActionFailure {
286 code: "smtp.secret\ncode".into(),
287 message: "password=hunter2".into(),
288 details: Some(serde_json::json!({"token": "private"})),
289 retryable: true,
290 },
291 };
292 let receipt = EffectReceiptStatus::from_terminal(&update).expect("terminal receipt");
293 assert_eq!(
294 receipt,
295 EffectReceiptStatus::Failed {
296 code: "smtp.secretcode".into()
297 }
298 );
299 let json = serde_json::to_string(&receipt).expect("encode receipt");
300 assert!(!json.contains("hunter2"));
301 assert!(!json.contains("private"));
302 }
303}