Skip to main content

simpleplatform_sdk/
codes.rs

1//! The failure vocabulary an action may report, as a closed enum.
2//!
3//! # Why this is an enum and not a string
4//!
5//! A failure leaves an action as a code, and the platform translates that code
6//! into a canonical code, a canonical category, and — the part no action author
7//! can be trusted to declare — an *effect on stored data*. A failed read changed
8//! nothing; a failed write may have landed, and that single bit decides whether
9//! the platform may retry the call on its own.
10//!
11//! The translation table stays on the platform side. What lives here is the
12//! vocabulary the table is keyed by, so that a code with no translation is a
13//! compile error as you type rather than something to find out later, and so that
14//! there is one list to read.
15//!
16//! # A code you do not find here
17//!
18//! [`Code::Custom`] exists so an action can say "this invoice is already paid"
19//! without waiting for a platform release. A custom code is carried through to
20//! the model verbatim beside a generic canonical translation, which the platform
21//! treats as *effect unknown* — the safe reading, since nothing establishes what
22//! a code it has never seen did. Reach for a canonical variant where one fits.
23
24use std::fmt;
25
26/// Every code the platform's translation table is keyed by, in table order.
27///
28/// This is the list a cross-language conformance check reads. Keep it in step
29/// with [`Code::as_str`] — the test in this module fails otherwise.
30pub const CANONICAL: [&str; 25] = [
31    "INVALID_TOOL_INPUT",
32    "MUTATION_REQUIRED",
33    "QUERY_REQUIRED",
34    "INVALID_VARIABLES",
35    "MISSING_GRAPHQL_VARIABLES",
36    "UNDECLARED_GRAPHQL_VARIABLES",
37    "UNSUPPORTED_GRAPHQL_VARIABLE_TYPE",
38    "UNSUPPORTED_GRAPHQL_VARIABLE_DEFAULT",
39    "INVALID_GRAPHQL_VARIABLE_VALUE",
40    "INVALID_GRAPHQL_QUERY",
41    "INVALID_GRAPHQL_MUTATION",
42    "QUERY_NOT_ALLOWED",
43    "NOT_A_MUTATION",
44    "RESERVED_MUTATION_ALIAS",
45    "INVALID_DATE_FILTER",
46    "QUERY_FORBIDDEN",
47    "QUERY_TIMEOUT",
48    "DATABASE_UNAVAILABLE",
49    "QUERY_EXECUTION_FAILED",
50    "MUTATION_EXECUTION_FAILED",
51    "MUTATION_RESULT_UNREADABLE",
52    "INVALID_QUERY_RESPONSE",
53    "INVALID_MUTATION_RESPONSE",
54    "PAGINATION_FAILED",
55    "QUERY_DATA_FAILED",
56];
57
58/// What a custom code degrades to when it is not a shape the wire accepts.
59///
60/// It has no entry in the platform's table, which is the honest answer: an
61/// action failed for a reason the platform has no canonical name for.
62pub const UNSPECIFIED: &str = "ACTION_FAILED";
63
64/// The most bytes a code may spend on the wire.
65const MAX_CODE_BYTES: usize = 64;
66
67/// The fewest, below which a code names nothing.
68const MIN_CODE_BYTES: usize = 2;
69
70/// A code the platform can translate, or one this action defines for itself.
71#[non_exhaustive]
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub enum Code {
74    /// The input could not be accepted at all.
75    InvalidToolInput,
76    /// A write was asked for and no mutation document was given.
77    MutationRequired,
78    /// A read was asked for and no query document was given.
79    QueryRequired,
80    /// The variables were not an object map.
81    InvalidVariables,
82    /// The document declares variables the call did not supply.
83    MissingGraphqlVariables,
84    /// The call supplied variables the document does not declare.
85    UndeclaredGraphqlVariables,
86    /// A variable declaration uses a type the dialect does not carry.
87    UnsupportedGraphqlVariableType,
88    /// A variable declaration carries a default, which is not supported.
89    UnsupportedGraphqlVariableDefault,
90    /// A variable value does not match its declaration.
91    InvalidGraphqlVariableValue,
92    /// The query document was rejected.
93    InvalidGraphqlQuery,
94    /// The mutation document was rejected.
95    InvalidGraphqlMutation,
96    /// A mutation was sent where only a read is allowed.
97    QueryNotAllowed,
98    /// A read was sent where only a mutation is allowed.
99    NotAMutation,
100    /// A mutation root alias collides with a reserved result member.
101    ReservedMutationAlias,
102    /// A date or datetime filter is invalid.
103    InvalidDateFilter,
104    /// The current user may not run the operation.
105    QueryForbidden,
106    /// The read did not finish in time. Retryable.
107    QueryTimeout,
108    /// The data service is unavailable. Retryable.
109    DatabaseUnavailable,
110    /// The read was accepted and then failed. Nothing was written.
111    QueryExecutionFailed,
112    /// The write was accepted and then failed. It may have landed.
113    MutationExecutionFailed,
114    /// The write ran and returned a result that could not be read.
115    MutationResultUnreadable,
116    /// A read returned a response this action could not decode.
117    InvalidQueryResponse,
118    /// A write returned a response this action could not decode.
119    InvalidMutationResponse,
120    /// Pagination metadata could not be produced.
121    PaginationFailed,
122    /// A failure with no more specific account of itself.
123    QueryDataFailed,
124    /// A code this action defines. Translated generically, effect unknown.
125    Custom(String),
126}
127
128impl Code {
129    /// The code exactly as it travels on the wire.
130    ///
131    /// For [`Code::Custom`] this is the string as given, which may not be a
132    /// shape the wire accepts; [`Code::wire`] is what the envelope emits.
133    pub fn as_str(&self) -> &str {
134        match self {
135            Code::InvalidToolInput => "INVALID_TOOL_INPUT",
136            Code::MutationRequired => "MUTATION_REQUIRED",
137            Code::QueryRequired => "QUERY_REQUIRED",
138            Code::InvalidVariables => "INVALID_VARIABLES",
139            Code::MissingGraphqlVariables => "MISSING_GRAPHQL_VARIABLES",
140            Code::UndeclaredGraphqlVariables => "UNDECLARED_GRAPHQL_VARIABLES",
141            Code::UnsupportedGraphqlVariableType => "UNSUPPORTED_GRAPHQL_VARIABLE_TYPE",
142            Code::UnsupportedGraphqlVariableDefault => "UNSUPPORTED_GRAPHQL_VARIABLE_DEFAULT",
143            Code::InvalidGraphqlVariableValue => "INVALID_GRAPHQL_VARIABLE_VALUE",
144            Code::InvalidGraphqlQuery => "INVALID_GRAPHQL_QUERY",
145            Code::InvalidGraphqlMutation => "INVALID_GRAPHQL_MUTATION",
146            Code::QueryNotAllowed => "QUERY_NOT_ALLOWED",
147            Code::NotAMutation => "NOT_A_MUTATION",
148            Code::ReservedMutationAlias => "RESERVED_MUTATION_ALIAS",
149            Code::InvalidDateFilter => "INVALID_DATE_FILTER",
150            Code::QueryForbidden => "QUERY_FORBIDDEN",
151            Code::QueryTimeout => "QUERY_TIMEOUT",
152            Code::DatabaseUnavailable => "DATABASE_UNAVAILABLE",
153            Code::QueryExecutionFailed => "QUERY_EXECUTION_FAILED",
154            Code::MutationExecutionFailed => "MUTATION_EXECUTION_FAILED",
155            Code::MutationResultUnreadable => "MUTATION_RESULT_UNREADABLE",
156            Code::InvalidQueryResponse => "INVALID_QUERY_RESPONSE",
157            Code::InvalidMutationResponse => "INVALID_MUTATION_RESPONSE",
158            Code::PaginationFailed => "PAGINATION_FAILED",
159            Code::QueryDataFailed => "QUERY_DATA_FAILED",
160            Code::Custom(code) => code.as_str(),
161        }
162    }
163
164    /// The code as the envelope emits it.
165    ///
166    /// A custom code that is not `[A-Z0-9_]`, or is too short or too long,
167    /// becomes [`UNSPECIFIED`]. A code travels as an opaque key, so the one that
168    /// leaves here is always a key the failure can be filed under, and the
169    /// substitution is one line to read at the point it happens.
170    pub fn wire(&self) -> &str {
171        match self {
172            Code::Custom(code) if !wire_safe(code) => UNSPECIFIED,
173            other => other.as_str(),
174        }
175    }
176
177    /// The generic code, for a failure the platform has no canonical name for.
178    ///
179    /// A failure this SDK did not classify — a panic, an unencodable result, a
180    /// host that answered nothing — establishes nothing about what the action
181    /// had already done. This code claims exactly that much, which is why it is
182    /// used in place of a canonical one that would say more.
183    pub fn unspecified() -> Code {
184        Code::Custom(UNSPECIFIED.to_string())
185    }
186
187    /// The category this code is reported under when nothing narrower is said.
188    pub fn category(&self) -> Category {
189        match self {
190            Code::InvalidToolInput
191            | Code::MutationRequired
192            | Code::QueryRequired
193            | Code::InvalidVariables
194            | Code::MissingGraphqlVariables
195            | Code::UndeclaredGraphqlVariables
196            | Code::UnsupportedGraphqlVariableType
197            | Code::UnsupportedGraphqlVariableDefault
198            | Code::InvalidGraphqlVariableValue
199            | Code::InvalidGraphqlQuery
200            | Code::InvalidGraphqlMutation
201            | Code::QueryNotAllowed
202            | Code::NotAMutation
203            | Code::ReservedMutationAlias
204            | Code::InvalidDateFilter => Category::Validation,
205            Code::QueryForbidden => Category::Authorization,
206            Code::QueryTimeout => Category::Timeout,
207            Code::DatabaseUnavailable => Category::Availability,
208            Code::QueryExecutionFailed
209            | Code::MutationExecutionFailed
210            | Code::MutationResultUnreadable => Category::Execution,
211            Code::InvalidQueryResponse | Code::InvalidMutationResponse => Category::Response,
212            Code::PaginationFailed => Category::Pagination,
213            Code::QueryDataFailed => Category::Internal,
214            Code::Custom(_) => Category::Execution,
215        }
216    }
217
218    /// Whether repeating an identical call could plausibly succeed.
219    ///
220    /// Only a confirmed timeout and a confirmed unavailability say yes, and the
221    /// platform narrows even those with what it knows about the tool. It never
222    /// widens them, so an action claiming a write failure is retryable is not
223    /// believed — which is why this is derived here rather than asked for.
224    pub fn retryable(&self) -> bool {
225        matches!(self, Code::QueryTimeout | Code::DatabaseUnavailable)
226    }
227}
228
229impl fmt::Display for Code {
230    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
231        formatter.write_str(self.wire())
232    }
233}
234
235/// The coarse class a failure belongs to, as the action reports it.
236///
237/// The platform derives its own canonical category from the code and keeps this
238/// one beside it, so drift between the two stays visible rather than silently
239/// overriding either.
240#[non_exhaustive]
241#[derive(Clone, Copy, Debug, PartialEq, Eq)]
242pub enum Category {
243    /// The call cannot be accepted as written.
244    Validation,
245    /// The current user may not do this.
246    Authorization,
247    /// It did not finish in time.
248    Timeout,
249    /// Something it depends on is down.
250    Availability,
251    /// It was accepted and then failed.
252    Execution,
253    /// What came back could not be read.
254    Response,
255    /// Paging over the result failed.
256    Pagination,
257    /// A fault in the action itself.
258    Internal,
259}
260
261impl Category {
262    /// The category exactly as it travels on the wire.
263    pub fn as_str(&self) -> &str {
264        match self {
265            Category::Validation => "validation",
266            Category::Authorization => "authorization",
267            Category::Timeout => "timeout",
268            Category::Availability => "availability",
269            Category::Execution => "execution",
270            Category::Response => "response",
271            Category::Pagination => "pagination",
272            Category::Internal => "internal",
273        }
274    }
275}
276
277impl fmt::Display for Category {
278    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
279        formatter.write_str(self.as_str())
280    }
281}
282
283/// Whether a custom code is a shape the wire accepts.
284fn wire_safe(code: &str) -> bool {
285    (MIN_CODE_BYTES..=MAX_CODE_BYTES).contains(&code.len())
286        && code
287            .bytes()
288            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
289        && code.as_bytes()[0].is_ascii_uppercase()
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    /// Every canonical variant, so the two lists below can be checked against
297    /// each other. Adding a variant without adding it here is a compile error
298    /// in `each_variant_is_canonical`, which matches exhaustively.
299    const EVERY: [Code; 25] = [
300        Code::InvalidToolInput,
301        Code::MutationRequired,
302        Code::QueryRequired,
303        Code::InvalidVariables,
304        Code::MissingGraphqlVariables,
305        Code::UndeclaredGraphqlVariables,
306        Code::UnsupportedGraphqlVariableType,
307        Code::UnsupportedGraphqlVariableDefault,
308        Code::InvalidGraphqlVariableValue,
309        Code::InvalidGraphqlQuery,
310        Code::InvalidGraphqlMutation,
311        Code::QueryNotAllowed,
312        Code::NotAMutation,
313        Code::ReservedMutationAlias,
314        Code::InvalidDateFilter,
315        Code::QueryForbidden,
316        Code::QueryTimeout,
317        Code::DatabaseUnavailable,
318        Code::QueryExecutionFailed,
319        Code::MutationExecutionFailed,
320        Code::MutationResultUnreadable,
321        Code::InvalidQueryResponse,
322        Code::InvalidMutationResponse,
323        Code::PaginationFailed,
324        Code::QueryDataFailed,
325    ];
326
327    #[test]
328    fn every_variant_is_canonical() {
329        // An exhaustive match: a new variant fails to compile here until it is
330        // either added to `EVERY` and `CANONICAL`, or excluded on purpose.
331        for code in EVERY.iter() {
332            let known = match code {
333                Code::Custom(_) => false,
334                _ => CANONICAL.contains(&code.as_str()),
335            };
336
337            assert!(known, "{} is not in CANONICAL", code.as_str());
338        }
339
340        assert_eq!(EVERY.len(), CANONICAL.len());
341    }
342
343    #[test]
344    fn canonical_order_matches_the_enum() {
345        let listed: Vec<&str> = EVERY.iter().map(Code::as_str).collect();
346
347        assert_eq!(listed, CANONICAL.to_vec());
348    }
349
350    #[test]
351    fn only_confirmed_timeouts_and_outages_are_retryable() {
352        let retryable: Vec<&str> = EVERY
353            .iter()
354            .filter(|code| code.retryable())
355            .map(Code::as_str)
356            .collect();
357
358        assert_eq!(retryable, vec!["QUERY_TIMEOUT", "DATABASE_UNAVAILABLE"]);
359    }
360
361    #[test]
362    fn a_custom_code_the_wire_cannot_carry_is_replaced() {
363        assert_eq!(Code::Custom("INVOICE_PAID".into()).wire(), "INVOICE_PAID");
364        assert_eq!(Code::Custom("invoice paid".into()).wire(), UNSPECIFIED);
365        assert_eq!(Code::Custom(String::new()).wire(), UNSPECIFIED);
366        assert_eq!(Code::Custom("_LEADING".into()).wire(), UNSPECIFIED);
367        assert_eq!(Code::Custom("X".repeat(65)).wire(), UNSPECIFIED);
368    }
369}