Skip to main content

aion_client/
error.rs

1//! `ClientError` taxonomy and transport/proto error mapping.
2//!
3//! Every variant carries an [`ErrorDetail`]: the server's human detail
4//! message plus, when the wire carried one, the structured `error_type`
5//! discriminator. Nothing the server sends is dropped on the client side —
6//! callers branch on the variant, render `detail.message`, and may surface
7//! `detail.error_type` for diagnostics.
8
9use aion_proto::{ProtoWireError, WireError, WireErrorCode};
10use prost::Message;
11use tonic::Code;
12
13/// Diagnostic payload carried by every [`ClientError`] variant.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ErrorDetail {
16    /// Human-readable detail: the server's wire `message` when the error
17    /// crossed the wire, a precise local description otherwise.
18    pub message: String,
19    /// Concrete typed server error variant (the wire `error_type` field),
20    /// when the server exposed one.
21    pub error_type: Option<String>,
22}
23
24impl ErrorDetail {
25    /// Creates a detail with a message and no typed discriminator.
26    #[must_use]
27    pub fn new(message: impl Into<String>) -> Self {
28        Self {
29            message: message.into(),
30            error_type: None,
31        }
32    }
33
34    /// Creates a detail carrying a typed `error_type` discriminator.
35    #[must_use]
36    pub fn with_type(message: impl Into<String>, error_type: impl Into<String>) -> Self {
37        Self {
38            message: message.into(),
39            error_type: Some(error_type.into()),
40        }
41    }
42}
43
44impl std::fmt::Display for ErrorDetail {
45    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        match &self.error_type {
47            Some(error_type) => write!(formatter, "{} [{error_type}]", self.message),
48            None => formatter.write_str(&self.message),
49        }
50    }
51}
52
53impl From<String> for ErrorDetail {
54    fn from(message: String) -> Self {
55        Self::new(message)
56    }
57}
58
59impl From<&str> for ErrorDetail {
60    fn from(message: &str) -> Self {
61        Self::new(message)
62    }
63}
64
65impl From<WireError> for ErrorDetail {
66    fn from(error: WireError) -> Self {
67        Self {
68            message: error.message,
69            error_type: error.error_type,
70        }
71    }
72}
73
74/// Branchable caller-side error taxonomy shared by every aion client SDK.
75///
76/// Display renders `<class>: <detail>` where `<class>` is the stable string
77/// returned by [`ClientError::class`], aligned with the wire error codes
78/// (`not_found`, `namespace_denied`, `invalid_input`, `backend`, ...).
79#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
80pub enum ClientError {
81    /// The requested workflow or run does not exist.
82    #[error("not_found: {detail}")]
83    NotFound {
84        /// Server-supplied detail message.
85        detail: ErrorDetail,
86    },
87    /// A caller-supplied idempotency key conflicts with a different request.
88    #[error("already_exists: {detail}")]
89    AlreadyExists {
90        /// Conflict detail message.
91        detail: ErrorDetail,
92    },
93    /// The workflow query handler ran and reported an application failure.
94    #[error("query_failed: {detail}")]
95    QueryFailed {
96        /// Handler failure detail reported by the workflow.
97        detail: ErrorDetail,
98    },
99    /// The workflow query exceeded its deadline.
100    #[error("query_timeout: {detail}")]
101    QueryTimeout {
102        /// Deadline detail (server window or local deadline).
103        detail: ErrorDetail,
104    },
105    /// The requested workflow query name is not registered.
106    #[error("unknown_query: {detail}")]
107    UnknownQuery {
108        /// Server-supplied detail naming the unknown query.
109        detail: ErrorDetail,
110    },
111    /// The target workflow is terminal or otherwise not running.
112    #[error("not_running: {detail}")]
113    NotRunning {
114        /// Server-supplied detail about the non-running target.
115        detail: ErrorDetail,
116    },
117    /// The call or target workflow was cancelled.
118    #[error("cancelled: {detail}")]
119    Cancelled {
120        /// Cancellation detail message.
121        detail: ErrorDetail,
122    },
123    /// The server or network transport is unavailable.
124    #[error("unavailable: {detail}")]
125    Unavailable {
126        /// Transport/connection failure detail.
127        detail: ErrorDetail,
128    },
129    /// Authentication credentials were rejected.
130    #[error("unauthenticated: {detail}")]
131    Unauthenticated {
132        /// Credential rejection detail.
133        detail: ErrorDetail,
134    },
135    /// The caller's credential was accepted, but the caller has no grant for
136    /// the requested namespace.
137    ///
138    /// This is exactly a namespace-grant failure. Workflow-level invisibility
139    /// — the workflow does not exist, or is owned by another namespace — is
140    /// reported as [`ClientError::NotFound`] so a cross-tenant probe is
141    /// indistinguishable from a nonexistent workflow.
142    ///
143    /// Maps from the AW wire error code `namespace_denied` and gRPC
144    /// `PERMISSION_DENIED`. Distinct from [`ClientError::Unauthenticated`]
145    /// (credential rejected or unvalidatable) and from
146    /// [`ClientError::InvalidArgument`] (malformed or invalid request). Not
147    /// retryable until the caller's grants change.
148    #[error("namespace_denied: {detail}")]
149    NamespaceDenied {
150        /// Server-supplied denial detail message.
151        detail: ErrorDetail,
152    },
153    /// The request was malformed or targets an unsupported operation state.
154    #[error("invalid_input: {detail}")]
155    InvalidArgument {
156        /// Precise description of what was invalid and how to fix it.
157        detail: ErrorDetail,
158    },
159    /// A precondition on the target's current state was not met (e.g. a reopen
160    /// of a run that is not a reopenable terminal). Distinct from
161    /// [`ClientError::NotFound`] (absent) and [`ClientError::InvalidArgument`]
162    /// (malformed request): the target exists but is in the wrong state.
163    ///
164    /// Maps from the wire error code `invalid_state` / gRPC `FailedPrecondition`
165    /// with the typed detail present. Not retryable until the target's state
166    /// changes.
167    #[error("invalid_state: {detail}")]
168    InvalidState {
169        /// Server-supplied precondition-failure detail naming the actual state.
170        detail: ErrorDetail,
171    },
172    /// The request reached a server that is not the current owner of the
173    /// target's shard, so it could not be served there.
174    ///
175    /// A ROUTING signal, not a connectivity one: the endpoint answered. It is
176    /// transient — cluster ownership moves on failover and the caller may retry
177    /// or re-resolve — which is why it is retryable, but it must not be
178    /// confused with [`ClientError::Unavailable`], whose remedy ("check your
179    /// endpoint") is wrong here and sends the operator hunting a network fault
180    /// that does not exist.
181    ///
182    /// Maps from the wire error code `not_owner` / gRPC `ABORTED` with the typed
183    /// detail present.
184    #[error("not_owner: {detail}")]
185    NotOwner {
186        /// Server-supplied detail naming the shard and what owns it.
187        detail: ErrorDetail,
188    },
189    /// The server reported an unexpected internal failure.
190    #[error("backend: {detail}")]
191    Server {
192        /// Informational server detail.
193        detail: ErrorDetail,
194    },
195}
196
197macro_rules! detail_constructors {
198    ($(($constructor:ident, $variant:ident, $doc:literal)),+ $(,)?) => {
199        $(
200            #[doc = $doc]
201            #[must_use]
202            pub fn $constructor(detail: impl Into<ErrorDetail>) -> Self {
203                Self::$variant {
204                    detail: detail.into(),
205                }
206            }
207        )+
208    };
209}
210
211impl ClientError {
212    detail_constructors!(
213        (not_found, NotFound, "Creates a not-found error."),
214        (
215            already_exists,
216            AlreadyExists,
217            "Creates an idempotency-conflict error."
218        ),
219        (
220            query_failed,
221            QueryFailed,
222            "Creates a query-handler failure."
223        ),
224        (query_timeout, QueryTimeout, "Creates a query timeout."),
225        (
226            unknown_query,
227            UnknownQuery,
228            "Creates an unknown-query error."
229        ),
230        (not_running, NotRunning, "Creates a not-running error."),
231        (cancelled, Cancelled, "Creates a cancellation error."),
232        (
233            unavailable,
234            Unavailable,
235            "Creates a transport-unavailable error."
236        ),
237        (
238            unauthenticated,
239            Unauthenticated,
240            "Creates a credential-rejection error."
241        ),
242        (
243            namespace_denied,
244            NamespaceDenied,
245            "Creates a namespace-grant denial."
246        ),
247        (
248            invalid_argument,
249            InvalidArgument,
250            "Creates an [`ClientError::InvalidArgument`] carrying a precise message."
251        ),
252        (
253            invalid_state,
254            InvalidState,
255            "Creates an [`ClientError::InvalidState`] precondition failure."
256        ),
257        (
258            not_owner,
259            NotOwner,
260            "Creates a wrong-shard-owner routing refusal."
261        ),
262        (
263            server,
264            Server,
265            "Creates an unexpected-server-failure error from a local conversion or server detail."
266        ),
267    );
268
269    /// Stable taxonomy class string, aligned with the wire error codes.
270    #[must_use]
271    pub const fn class(&self) -> &'static str {
272        match self {
273            Self::NotFound { .. } => "not_found",
274            Self::AlreadyExists { .. } => "already_exists",
275            Self::QueryFailed { .. } => "query_failed",
276            Self::QueryTimeout { .. } => "query_timeout",
277            Self::UnknownQuery { .. } => "unknown_query",
278            Self::NotRunning { .. } => "not_running",
279            Self::Cancelled { .. } => "cancelled",
280            Self::Unavailable { .. } => "unavailable",
281            Self::Unauthenticated { .. } => "unauthenticated",
282            Self::NamespaceDenied { .. } => "namespace_denied",
283            Self::InvalidArgument { .. } => "invalid_input",
284            Self::InvalidState { .. } => "invalid_state",
285            Self::NotOwner { .. } => "not_owner",
286            Self::Server { .. } => "backend",
287        }
288    }
289
290    /// The diagnostic detail carried by this error.
291    #[must_use]
292    pub const fn detail(&self) -> &ErrorDetail {
293        match self {
294            Self::NotFound { detail }
295            | Self::AlreadyExists { detail }
296            | Self::QueryFailed { detail }
297            | Self::QueryTimeout { detail }
298            | Self::UnknownQuery { detail }
299            | Self::NotRunning { detail }
300            | Self::Cancelled { detail }
301            | Self::Unavailable { detail }
302            | Self::Unauthenticated { detail }
303            | Self::NamespaceDenied { detail }
304            | Self::InvalidArgument { detail }
305            | Self::InvalidState { detail }
306            | Self::NotOwner { detail }
307            | Self::Server { detail } => detail,
308        }
309    }
310
311    /// Converts an AW wire error into the client SDK taxonomy, preserving the
312    /// server's message and `error_type` in the carried [`ErrorDetail`].
313    #[must_use]
314    pub fn from_wire_error(error: WireError) -> Self {
315        let code = error.code;
316        let detail = ErrorDetail::from(error);
317        match code {
318            WireErrorCode::NotFound => Self::NotFound { detail },
319            WireErrorCode::NamespaceDenied => Self::NamespaceDenied { detail },
320            WireErrorCode::UnknownQuery => Self::UnknownQuery { detail },
321            WireErrorCode::NotRunning => Self::NotRunning { detail },
322            WireErrorCode::InvalidInput => Self::InvalidArgument { detail },
323            WireErrorCode::InvalidState => Self::InvalidState { detail },
324            // `sequence_conflict` is emitted solely for the server's internal
325            // single-writer invariant violation (a double-writer bug). The
326            // server has no idempotency-key feature, so this is never
327            // AlreadyExists; it is an unexpected server failure.
328            // `deploy_denied` / `version_pinned` belong to the operator
329            // deploy surface, which the caller SDK contract deliberately
330            // excludes (CLIENT-CONTRACT scope); they can never be returned
331            // by a caller SDK operation, so they fall into the generic
332            // server bucket rather than growing the caller taxonomy.
333            WireErrorCode::SequenceConflict
334            | WireErrorCode::Backend
335            | WireErrorCode::DeployDenied
336            | WireErrorCode::VersionPinned => Self::Server { detail },
337            WireErrorCode::QueryFailed => Self::QueryFailed { detail },
338            WireErrorCode::QueryTimeout => Self::QueryTimeout { detail },
339            WireErrorCode::Lagged => Self::Unavailable { detail },
340            // `not_owner` (wrong-shard-owner fence) is a retryable ROUTING
341            // signal: the request reached a node that does not own the
342            // target's shard. It used to collapse into `Unavailable`, which
343            // made every CLI surface tell the operator to "check --endpoint" —
344            // a wrong hint that cost the failover investigation real diagnosis
345            // time. It is its own class now, typed at the taxonomy so no
346            // surface has to read message text to tell the two apart.
347            WireErrorCode::NotOwner => Self::NotOwner { detail },
348        }
349    }
350
351    /// Converts a proto-encoded wire error into the client SDK taxonomy.
352    #[must_use]
353    pub fn from_proto_wire_error(error: ProtoWireError) -> Self {
354        match WireError::try_from(error) {
355            Ok(error) | Err(error) => Self::from_wire_error(error),
356        }
357    }
358
359    /// Converts a tonic status into the client SDK taxonomy.
360    ///
361    /// The server encodes the full typed `WireError` (code, message,
362    /// `error_type`) into the status details; when present it is
363    /// authoritative. Without decodable details the gRPC code is mapped and
364    /// the status message becomes the detail, so the server's human detail is
365    /// never dropped.
366    #[must_use]
367    pub fn from_status(status: &tonic::Status) -> Self {
368        if let Some(error) = decode_status_details(status) {
369            return Self::from_proto_wire_error(error);
370        }
371
372        let detail = ErrorDetail::new(status.message());
373        match status.code() {
374            Code::NotFound => Self::NotFound { detail },
375            Code::AlreadyExists => Self::AlreadyExists { detail },
376            Code::DeadlineExceeded => Self::QueryTimeout { detail },
377            Code::Cancelled => Self::Cancelled { detail },
378            Code::Unavailable | Code::ResourceExhausted => Self::Unavailable { detail },
379            Code::Unauthenticated => Self::Unauthenticated { detail },
380            Code::PermissionDenied => Self::NamespaceDenied { detail },
381            Code::InvalidArgument => Self::InvalidArgument { detail },
382            // FAILED_PRECONDITION carries both the `not_running` and
383            // `invalid_state` wire codes; the server always attaches the typed
384            // ProtoWireError detail (decoded above), so this bare-code fallback
385            // is only reached without detail. `not_running` is the historical
386            // default kept for that degenerate case.
387            Code::FailedPrecondition => Self::NotRunning { detail },
388            // ABORTED deliberately falls through to Server: the server sends
389            // it only for `sequence_conflict`, an internal single-writer
390            // invariant violation (a double-writer bug), never an
391            // idempotency conflict — so it must not map to AlreadyExists.
392            _ => Self::Server { detail },
393        }
394    }
395
396    /// Converts a tonic transport failure into the client SDK taxonomy,
397    /// preserving the full transport error chain as the detail message.
398    #[must_use]
399    pub fn from_transport_error(error: &tonic::transport::Error) -> Self {
400        Self::Unavailable {
401            detail: ErrorDetail::new(source_chain(error)),
402        }
403    }
404}
405
406/// Joins an error's Display with every `source()` cause, so transport errors
407/// like tonic's bare "transport error" keep their underlying connect/DNS/TLS
408/// detail.
409fn source_chain(error: &(dyn std::error::Error + 'static)) -> String {
410    let mut message = error.to_string();
411    let mut source = error.source();
412    while let Some(cause) = source {
413        message.push_str(": ");
414        message.push_str(&cause.to_string());
415        source = cause.source();
416    }
417    message
418}
419
420fn decode_status_details(status: &tonic::Status) -> Option<ProtoWireError> {
421    let details = status.details();
422    if details.is_empty() {
423        return None;
424    }
425    ProtoWireError::decode(details).ok()
426}
427
428/// Unit tests live in a sibling file so this module stays under the 500-line
429/// law with the test bodies intact rather than thinned.
430#[cfg(test)]
431#[path = "error_tests.rs"]
432mod tests;