Skip to main content

simpleplatform_sdk/
error.rs

1//! The one error type an action ever handles.
2//!
3//! # Why one hand-written enum
4//!
5//! `anyhow` erases the variant, and its backtraces are dead weight in a guest
6//! that cannot unwind. `thiserror` puts a proc-macro crate in the build graph of
7//! every action in exchange for deriving `Display` on eight variants whose
8//! strings are user-visible platform text — better read in the source than in an
9//! attribute. So: written out, once, here.
10//!
11//! # Two rules this file is written to
12//!
13//! A message travels with a budget of **1000 bytes**. So [`Error`] front-loads
14//! the actionable sentence, and [`crate::envelope`] does the cutting on a
15//! character boundary, so what arrives is valid UTF-8 and within the bound.
16//!
17//! And **nothing on the error path may panic**: a failure reaches the caller by
18//! being returned, so every function here is total.
19//!
20//! # `?` works on everything
21//!
22//! ```
23//! use simpleplatform_sdk::prelude::*;
24//!
25//! fn parse(text: String) -> Result<i64, Error> {
26//!     let number: i64 = text.trim().parse()?; // std's ParseIntError
27//!     let value: Value = serde_json::from_str("{}")?; // serde_json's Error
28//!     let _ = value;
29//!     Ok(number)
30//! }
31//!
32//! assert_eq!(parse(" 41 ".to_string()).unwrap(), 41);
33//! assert!(parse("x".to_string()).is_err());
34//! ```
35//!
36//! That works because of a blanket `From<E: std::error::Error>`, which the
37//! standard library's reflexive `From<T> for T` forbids unless `Error` itself
38//! does *not* implement `std::error::Error`. It does not, for exactly that
39//! reason — the same trade `anyhow` makes. In an action this type is terminal,
40//! so nothing downstream needs to convert *out* of it.
41
42use std::fmt;
43
44use serde_json::{Map, Value};
45
46use crate::codes::{Category, Code};
47
48/// Everything a failure carries onto the wire.
49///
50/// Held by every [`Error`] variant, so the variant says where the failure came
51/// from and this says what the platform and the model are told about it.
52#[derive(Clone, Debug)]
53pub struct Fault {
54    code: Code,
55    category: Category,
56    retryable: bool,
57    message: String,
58    details: Value,
59    hint: String,
60}
61
62impl Fault {
63    /// A fault carrying this code, with the code's own category and
64    /// retryability, an empty details object, and no hint.
65    pub fn new(code: Code, message: impl Into<String>) -> Fault {
66        Fault {
67            category: code.category(),
68            retryable: code.retryable(),
69            code,
70            message: message.into(),
71            details: Value::Object(Map::new()),
72            hint: String::new(),
73        }
74    }
75
76    /// The code this failure is filed under.
77    pub fn code(&self) -> &Code {
78        &self.code
79    }
80
81    /// The class this failure is reported under.
82    pub fn category(&self) -> Category {
83        self.category
84    }
85
86    /// Whether repeating an identical call could plausibly succeed.
87    pub fn retryable(&self) -> bool {
88        self.retryable
89    }
90
91    /// The sentence the model is shown. Cut at 1000 bytes on the way out.
92    pub fn message(&self) -> &str {
93        &self.message
94    }
95
96    /// Structured evidence beside the message. Always a JSON object.
97    pub fn details(&self) -> &Value {
98        &self.details
99    }
100
101    /// What to do about it. Cut at 1000 bytes on the way out.
102    pub fn hint(&self) -> &str {
103        &self.hint
104    }
105}
106
107/// Everything that can go wrong inside an action.
108///
109/// The variant is the coarse triage — where the failure came from — and the
110/// [`Fault`] inside it is what reaches the platform. Match on the variant when
111/// you care where it happened; read [`Error::code`] when you care what it was.
112///
113/// It is `#[non_exhaustive]`: a `match` on it needs a `_` arm, so a variant
114/// added later does not break an action that was already written.
115#[non_exhaustive]
116#[derive(Clone, Debug)]
117pub enum Error {
118    /// The payload the host sent does not match the handler's input type.
119    Input(Fault),
120    /// A JSON document could not be read or written.
121    Json(Fault),
122    /// The host could not be asked, or answered with a refusal.
123    Host(Fault),
124    /// A GraphQL read failed. Nothing was written.
125    Query(Fault),
126    /// A GraphQL write failed, and may already have landed.
127    Mutation(Fault),
128    /// The action decided the request cannot be satisfied.
129    Domain(Fault),
130    /// The handler panicked and the panic was turned into this.
131    Panic(Fault),
132    /// Converted from another error type by `?`.
133    Other(Fault),
134}
135
136impl Error {
137    // --- Constructors an action reaches for -------------------------------
138
139    /// The input cannot be accepted as written.
140    ///
141    /// ```
142    /// use simpleplatform_sdk::prelude::*;
143    ///
144    /// let error = Error::invalid("'ids' must contain at least one id.")
145    ///     .hint("Pass one or more KNOW... ids.");
146    ///
147    /// assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
148    /// ```
149    pub fn invalid(message: impl Into<String>) -> Error {
150        Error::Input(Fault::new(Code::InvalidToolInput, message))
151    }
152
153    /// The current user may not do this. Never retried.
154    pub fn denied(message: impl Into<String>) -> Error {
155        Error::Domain(Fault::new(Code::QueryForbidden, message))
156    }
157
158    /// It did not finish in time. Retryable.
159    pub fn timed_out(message: impl Into<String>) -> Error {
160        Error::Domain(Fault::new(Code::QueryTimeout, message))
161    }
162
163    /// Something it depends on is down. Retryable.
164    pub fn unavailable(message: impl Into<String>) -> Error {
165        Error::Domain(Fault::new(Code::DatabaseUnavailable, message))
166    }
167
168    /// It failed, and there is no more specific account of why.
169    pub fn failed(message: impl Into<String>) -> Error {
170        Error::Domain(Fault::new(Code::unspecified(), message))
171    }
172
173    /// A failure this action names for itself.
174    ///
175    /// The code is carried to the model verbatim and translated generically,
176    /// which the platform reads as *effect unknown*. Prefer a canonical code
177    /// where one fits; reach for this when none does.
178    ///
179    /// ```
180    /// use simpleplatform_sdk::prelude::*;
181    ///
182    /// let error = Error::domain("INVOICE_ALREADY_PAID", "This invoice is already paid.");
183    ///
184    /// assert_eq!(error.code().as_str(), "INVOICE_ALREADY_PAID");
185    /// ```
186    pub fn domain(code: impl Into<String>, message: impl Into<String>) -> Error {
187        Error::Domain(Fault::new(Code::Custom(code.into()), message))
188    }
189
190    /// Anything that is not one of ours, kept for its message.
191    pub fn other(cause: impl fmt::Display) -> Error {
192        Error::Other(Fault::new(Code::unspecified(), cause.to_string()))
193    }
194
195    // --- Builders ---------------------------------------------------------
196
197    /// What to do about it. This reaches the model; spend it on the repair.
198    pub fn hint(mut self, hint: impl Into<String>) -> Error {
199        self.fault_mut().hint = hint.into();
200        self
201    }
202
203    /// Structured evidence beside the message.
204    ///
205    /// `details` is always a JSON object on the wire, so a value that is not one
206    /// is wrapped in one under `detail` and the failure travels whole — code,
207    /// category, message and hint together with the evidence.
208    pub fn details(mut self, details: Value) -> Error {
209        self.fault_mut().details = match details {
210            object @ Value::Object(_) => object,
211            other => {
212                let mut wrapper = Map::new();
213                wrapper.insert("detail".to_string(), other);
214                Value::Object(wrapper)
215            }
216        };
217        self
218    }
219
220    /// File this failure under a different code, taking that code's category
221    /// and retryability with it.
222    pub fn code_of(mut self, code: Code) -> Error {
223        let fault = self.fault_mut();
224        fault.category = code.category();
225        fault.retryable = code.retryable();
226        fault.code = code;
227        self
228    }
229
230    /// Report this failure under a different category, leaving the code alone.
231    pub fn category_of(mut self, category: Category) -> Error {
232        self.fault_mut().category = category;
233        self
234    }
235
236    /// Narrow the retryability verdict.
237    ///
238    /// It can only be narrowed: a code that is not retryable stays that way, so
239    /// an action cannot talk the platform into repeating a write.
240    pub fn retryable(mut self, retryable: bool) -> Error {
241        let fault = self.fault_mut();
242        fault.retryable = fault.retryable && retryable;
243        self
244    }
245
246    // --- Readers ----------------------------------------------------------
247
248    /// Everything this failure carries onto the wire.
249    pub fn fault(&self) -> &Fault {
250        match self {
251            Error::Input(fault)
252            | Error::Json(fault)
253            | Error::Host(fault)
254            | Error::Query(fault)
255            | Error::Mutation(fault)
256            | Error::Domain(fault)
257            | Error::Panic(fault)
258            | Error::Other(fault) => fault,
259        }
260    }
261
262    /// The code this failure is filed under.
263    pub fn code(&self) -> &Code {
264        self.fault().code()
265    }
266
267    /// The class this failure is reported under.
268    pub fn category(&self) -> Category {
269        self.fault().category()
270    }
271
272    /// The sentence the model is shown.
273    pub fn message(&self) -> &str {
274        self.fault().message()
275    }
276
277    /// Whether repeating an identical call could plausibly succeed.
278    pub fn is_retryable(&self) -> bool {
279        self.fault().retryable()
280    }
281
282    /// The canonical failure body, exactly as the platform reads it.
283    ///
284    /// Returning this from a handler instead of returning `Err` is what an
285    /// action does when a failure is a *result* rather than a fault — the call
286    /// worked, and the answer is that it cannot be satisfied.
287    pub fn body(&self) -> Value {
288        crate::envelope::error_body(self)
289    }
290
291    fn fault_mut(&mut self) -> &mut Fault {
292        match self {
293            Error::Input(fault)
294            | Error::Json(fault)
295            | Error::Host(fault)
296            | Error::Query(fault)
297            | Error::Mutation(fault)
298            | Error::Domain(fault)
299            | Error::Panic(fault)
300            | Error::Other(fault) => fault,
301        }
302    }
303}
304
305impl fmt::Display for Error {
306    /// The actionable sentence, and nothing else.
307    ///
308    /// This is the string that travels within the 1000-byte budget and that the
309    /// model reads, so it carries no `Debug` decoration, no variant name and no
310    /// code prefix. All of those are available from the accessors, and the
311    /// budget is spent on what whoever reads it has to act on.
312    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313        formatter.write_str(self.message())
314    }
315}
316
317/// Everything `?` can reach, in one impl.
318///
319/// This is why `Error` does not implement `std::error::Error`: the standard
320/// library's reflexive `impl<T> From<T> for T` would overlap with this one the
321/// moment it did.
322impl<E> From<E> for Error
323where
324    E: std::error::Error + 'static,
325{
326    fn from(cause: E) -> Error {
327        Error::Other(Fault::new(Code::unspecified(), cause.to_string()))
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use serde_json::json;
334
335    use super::*;
336
337    #[test]
338    fn a_constructor_takes_its_codes_category_and_verdict() {
339        let timeout = Error::timed_out("The read timed out.");
340
341        assert_eq!(timeout.code().as_str(), "QUERY_TIMEOUT");
342        assert_eq!(timeout.category(), Category::Timeout);
343        assert!(timeout.is_retryable());
344    }
345
346    #[test]
347    fn retryability_narrows_and_never_widens() {
348        let narrowed = Error::timed_out("x").retryable(false);
349        assert!(!narrowed.is_retryable());
350
351        let widened = Error::invalid("x").retryable(true);
352        assert!(!widened.is_retryable());
353    }
354
355    #[test]
356    fn details_that_are_not_an_object_are_wrapped_in_one() {
357        let error = Error::invalid("x").details(json!(["a", "b"]));
358
359        assert_eq!(
360            error.fault().details(),
361            &json!({ "detail": ["a", "b"] }),
362            "details is always a JSON object on the wire"
363        );
364    }
365
366    #[test]
367    fn a_foreign_error_converts_through_the_question_mark() {
368        fn convert() -> Result<(), Error> {
369            let _: i64 = "nope".parse()?;
370            Ok(())
371        }
372
373        let error = convert().unwrap_err();
374
375        assert!(matches!(error, Error::Other(_)));
376        assert_eq!(error.code().as_str(), crate::codes::UNSPECIFIED);
377    }
378
379    #[test]
380    fn display_is_the_message_alone() {
381        let error = Error::invalid("'ids' is required.").hint("Pass one id.");
382
383        assert_eq!(error.to_string(), "'ids' is required.");
384    }
385}