Skip to main content

nevo_messaging/
error.rs

1use std::fmt;
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4use serde_json::{Map, Value};
5
6/// Stable numeric error codes shared with the TypeScript implementation.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum ErrorCode {
10    Unknown,
11    Unauthorized,
12    Timeout,
13    MethodNotFound,
14    ServiceNotFound,
15    ServiceUnavailable,
16    BadRequest,
17    ValidationFailed,
18    RateLimited,
19    CircuitOpen,
20    PayloadTooLarge,
21    ParseError,
22    ReplayDetected,
23    IdempotentReplay,
24    ConnectionLost,
25    Internal,
26    Cancelled,
27    UnsupportedVersion,
28    AckFailed,
29    RemoteError,
30    IdempotencyKeyConflict,
31    /// A code this crate does not know about; preserved verbatim on the wire.
32    Other(u16),
33}
34
35impl ErrorCode {
36    pub const fn as_u16(self) -> u16 {
37        match self {
38            Self::Unknown => 0,
39            Self::Unauthorized => 1,
40            Self::Timeout => 2,
41            Self::MethodNotFound => 3,
42            Self::ServiceNotFound => 4,
43            Self::ServiceUnavailable => 5,
44            Self::BadRequest => 6,
45            Self::ValidationFailed => 7,
46            Self::RateLimited => 8,
47            Self::CircuitOpen => 9,
48            Self::PayloadTooLarge => 10,
49            Self::ParseError => 11,
50            Self::ReplayDetected => 12,
51            Self::IdempotentReplay => 13,
52            Self::ConnectionLost => 14,
53            Self::Internal => 15,
54            Self::Cancelled => 16,
55            Self::UnsupportedVersion => 17,
56            Self::AckFailed => 18,
57            Self::RemoteError => 19,
58            Self::IdempotencyKeyConflict => 20,
59            Self::Other(code) => code,
60        }
61    }
62
63    pub const fn from_u16(code: u16) -> Self {
64        match code {
65            0 => Self::Unknown,
66            1 => Self::Unauthorized,
67            2 => Self::Timeout,
68            3 => Self::MethodNotFound,
69            4 => Self::ServiceNotFound,
70            5 => Self::ServiceUnavailable,
71            6 => Self::BadRequest,
72            7 => Self::ValidationFailed,
73            8 => Self::RateLimited,
74            9 => Self::CircuitOpen,
75            10 => Self::PayloadTooLarge,
76            11 => Self::ParseError,
77            12 => Self::ReplayDetected,
78            13 => Self::IdempotentReplay,
79            14 => Self::ConnectionLost,
80            15 => Self::Internal,
81            16 => Self::Cancelled,
82            17 => Self::UnsupportedVersion,
83            18 => Self::AckFailed,
84            19 => Self::RemoteError,
85            20 => Self::IdempotencyKeyConflict,
86            other => Self::Other(other),
87        }
88    }
89
90    /// Codes that are transient by default (`INTERNAL` is deliberately excluded).
91    pub const fn is_retryable(self) -> bool {
92        matches!(
93            self,
94            Self::Timeout | Self::ServiceUnavailable | Self::ConnectionLost
95        )
96    }
97
98    pub const fn default_message(self) -> &'static str {
99        match self {
100            Self::Unknown | Self::Other(_) => "An unknown error occurred",
101            Self::Unauthorized => "Access denied",
102            Self::Timeout => "Request timed out",
103            Self::MethodNotFound => "Method not found",
104            Self::ServiceNotFound => "Service not registered",
105            Self::ServiceUnavailable => "Service unavailable",
106            Self::BadRequest => "Bad request",
107            Self::ValidationFailed => "Validation failed",
108            Self::RateLimited => "Rate limit exceeded",
109            Self::CircuitOpen => "Circuit breaker is open",
110            Self::PayloadTooLarge => "Payload exceeds size limit",
111            Self::ParseError => "Failed to parse message",
112            Self::ReplayDetected => "Replay attack detected",
113            Self::IdempotentReplay => "Idempotent request already processed",
114            Self::ConnectionLost => "Connection to broker lost",
115            Self::Internal => "Internal error",
116            Self::Cancelled => "Request cancelled",
117            Self::UnsupportedVersion => "Unsupported method version",
118            Self::AckFailed => "Failed to acknowledge message",
119            Self::RemoteError => "Remote returned an error response",
120            Self::IdempotencyKeyConflict => "Idempotency key reused with a different payload",
121        }
122    }
123}
124
125impl From<u16> for ErrorCode {
126    fn from(code: u16) -> Self {
127        Self::from_u16(code)
128    }
129}
130
131impl From<ErrorCode> for u16 {
132    fn from(code: ErrorCode) -> Self {
133        code.as_u16()
134    }
135}
136
137impl fmt::Display for ErrorCode {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        write!(f, "{self:?}({})", self.as_u16())
140    }
141}
142
143impl Serialize for ErrorCode {
144    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
145        serializer.serialize_u16(self.as_u16())
146    }
147}
148
149impl<'de> Deserialize<'de> for ErrorCode {
150    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
151        let raw = f64::deserialize(deserializer)?;
152        if raw.is_finite() && raw >= 0.0 && raw <= f64::from(u16::MAX) {
153            Ok(Self::from_u16(raw as u16))
154        } else {
155            Ok(Self::Unknown)
156        }
157    }
158}
159
160/// Wire representation of an error inside a response envelope.
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
162pub struct ErrorDetails {
163    pub code: ErrorCode,
164    #[serde(default)]
165    pub message: String,
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub details: Option<Map<String, Value>>,
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub service: Option<String>,
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub stack: Option<String>,
172}
173
174/// The error type used across the crate and carried inside response envelopes.
175#[derive(thiserror::Error)]
176pub struct Error {
177    code: ErrorCode,
178    message: String,
179    details: Map<String, Value>,
180    service: Option<String>,
181    retryable: Option<bool>,
182    #[source]
183    source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
184}
185
186impl Error {
187    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
188        Self {
189            code,
190            message: message.into(),
191            details: Map::new(),
192            service: None,
193            retryable: None,
194            source: None,
195        }
196    }
197
198    pub fn from_code(code: ErrorCode) -> Self {
199        Self::new(code, code.default_message())
200    }
201
202    pub fn internal(message: impl Into<String>) -> Self {
203        Self::new(ErrorCode::Internal, message)
204    }
205
206    pub fn bad_request(message: impl Into<String>) -> Self {
207        Self::new(ErrorCode::BadRequest, message)
208    }
209
210    pub fn validation(message: impl Into<String>) -> Self {
211        Self::new(ErrorCode::ValidationFailed, message)
212    }
213
214    pub fn unauthorized(message: impl Into<String>) -> Self {
215        Self::new(ErrorCode::Unauthorized, message)
216    }
217
218    pub fn parse(message: impl Into<String>) -> Self {
219        Self::new(ErrorCode::ParseError, message)
220    }
221
222    pub fn timeout(service: &str, method: &str, after: std::time::Duration) -> Self {
223        Self::new(
224            ErrorCode::Timeout,
225            format!(
226                "Request to {service}.{method} timed out after {}ms",
227                after.as_millis()
228            ),
229        )
230        .with_service(service)
231        .with_retryable(true)
232    }
233
234    pub fn circuit_open(service: &str, method: &str) -> Self {
235        Self::new(
236            ErrorCode::CircuitOpen,
237            format!("Circuit breaker open for {service}.{method}"),
238        )
239        .with_service(service)
240        .with_retryable(false)
241    }
242
243    pub fn payload_too_large(size: usize, limit: usize) -> Self {
244        Self::new(
245            ErrorCode::PayloadTooLarge,
246            format!("Payload size {size}B exceeds limit {limit}B"),
247        )
248        .with_detail("size", size)
249        .with_detail("limit", limit)
250    }
251
252    pub fn with_detail(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
253        self.details.insert(key.into(), value.into());
254        self
255    }
256
257    pub fn with_details(mut self, details: Map<String, Value>) -> Self {
258        self.details.extend(details);
259        self
260    }
261
262    pub fn with_service(mut self, service: impl Into<String>) -> Self {
263        self.service = Some(service.into());
264        self
265    }
266
267    pub fn with_retryable(mut self, retryable: bool) -> Self {
268        self.retryable = Some(retryable);
269        self
270    }
271
272    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
273        self.source = Some(Box::new(source));
274        self
275    }
276
277    pub fn code(&self) -> ErrorCode {
278        self.code
279    }
280
281    pub fn message(&self) -> &str {
282        &self.message
283    }
284
285    pub fn details(&self) -> &Map<String, Value> {
286        &self.details
287    }
288
289    pub fn detail(&self, key: &str) -> Option<&Value> {
290        self.details.get(key)
291    }
292
293    pub fn service(&self) -> Option<&str> {
294        self.service.as_deref()
295    }
296
297    /// Explicit retry hint, when one was set locally or received from the peer.
298    pub fn retryable_hint(&self) -> Option<bool> {
299        self.retryable
300    }
301
302    /// Whether a retry policy should consider this error transient.
303    pub fn is_retryable(&self) -> bool {
304        self.retryable.unwrap_or_else(|| self.code.is_retryable())
305    }
306
307    /// Server-provided `retryAfterMs` hint, capped to 30 seconds.
308    pub fn retry_after(&self) -> Option<std::time::Duration> {
309        let hint = self.details.get("retryAfterMs")?.as_f64()?;
310        if !hint.is_finite() || hint <= 0.0 {
311            return None;
312        }
313        Some(std::time::Duration::from_millis(hint.min(30_000.0) as u64))
314    }
315
316    pub fn is_code(&self, code: ErrorCode) -> bool {
317        self.code == code
318    }
319
320    pub fn to_wire(&self) -> ErrorDetails {
321        let mut details = self.details.clone();
322        if let Some(retryable) = self.retryable {
323            details.insert("retryable".into(), Value::Bool(retryable));
324        }
325        ErrorDetails {
326            code: self.code,
327            message: self.message.clone(),
328            details: Some(details),
329            service: self.service.clone(),
330            stack: None,
331        }
332    }
333
334    pub fn from_wire(wire: ErrorDetails, fallback_service: Option<&str>) -> Self {
335        let mut details = wire.details.unwrap_or_default();
336        let retryable = details.remove("retryable").and_then(|v| v.as_bool());
337        let message = if wire.message.is_empty() {
338            wire.code.default_message().to_owned()
339        } else {
340            wire.message
341        };
342        Self {
343            code: wire.code,
344            message,
345            details,
346            service: wire.service.or_else(|| fallback_service.map(str::to_owned)),
347            retryable,
348            source: None,
349        }
350    }
351}
352
353impl fmt::Debug for Error {
354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355        let mut dbg = f.debug_struct("Error");
356        dbg.field("code", &self.code)
357            .field("message", &self.message);
358        if !self.details.is_empty() {
359            dbg.field("details", &self.details);
360        }
361        if let Some(service) = &self.service {
362            dbg.field("service", service);
363        }
364        if let Some(retryable) = self.retryable {
365            dbg.field("retryable", &retryable);
366        }
367        if let Some(source) = &self.source {
368            dbg.field("source", source);
369        }
370        dbg.finish()
371    }
372}
373
374impl fmt::Display for Error {
375    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376        match &self.service {
377            Some(service) => write!(f, "[{}] {} ({service})", self.code, self.message),
378            None => write!(f, "[{}] {}", self.code, self.message),
379        }
380    }
381}
382
383impl From<ErrorCode> for Error {
384    fn from(code: ErrorCode) -> Self {
385        Self::from_code(code)
386    }
387}
388
389impl From<serde_json::Error> for Error {
390    fn from(err: serde_json::Error) -> Self {
391        Self::parse(format!("JSON error: {err}")).with_source(err)
392    }
393}
394
395impl From<tokio::time::error::Elapsed> for Error {
396    fn from(_: tokio::time::error::Elapsed) -> Self {
397        Self::from_code(ErrorCode::Timeout).with_retryable(true)
398    }
399}
400
401pub type Result<T, E = Error> = std::result::Result<T, E>;
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    #[test]
408    fn codes_round_trip_through_u16() {
409        for code in 0..=25u16 {
410            assert_eq!(ErrorCode::from_u16(code).as_u16(), code);
411        }
412        assert_eq!(ErrorCode::from_u16(99), ErrorCode::Other(99));
413    }
414
415    #[test]
416    fn wire_round_trip_preserves_retryable_and_details() {
417        let err = Error::new(ErrorCode::RateLimited, "slow down")
418            .with_detail("retryAfterMs", 250)
419            .with_retryable(true)
420            .with_service("user");
421        let wire = err.to_wire();
422        assert_eq!(wire.code, ErrorCode::RateLimited);
423        assert_eq!(
424            wire.details.as_ref().unwrap()["retryable"],
425            Value::Bool(true)
426        );
427        let back = Error::from_wire(wire, None);
428        assert_eq!(back.retryable_hint(), Some(true));
429        assert_eq!(
430            back.retry_after(),
431            Some(std::time::Duration::from_millis(250))
432        );
433        assert_eq!(back.service(), Some("user"));
434        assert!(back.detail("retryable").is_none());
435    }
436
437    #[test]
438    fn code_deserializes_from_float_and_int() {
439        assert_eq!(
440            serde_json::from_str::<ErrorCode>("2").unwrap(),
441            ErrorCode::Timeout
442        );
443        assert_eq!(
444            serde_json::from_str::<ErrorCode>("2.0").unwrap(),
445            ErrorCode::Timeout
446        );
447        assert_eq!(
448            serde_json::from_str::<ErrorCode>("-5").unwrap(),
449            ErrorCode::Unknown
450        );
451    }
452}