Skip to main content

dataexcept/
failure.rs

1//! Machine-readable recovery metadata.
2
3use serde::{Deserialize, Deserializer, Serialize};
4use thiserror::Error;
5
6/// Classification of the underlying failure condition.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
8#[serde(rename_all = "lowercase")]
9pub enum FailureKind {
10    /// The same operation may succeed later.
11    Transient,
12    /// The same operation and payload are expected to fail again.
13    Permanent,
14    /// The library has no justified classification.
15    #[default]
16    Unknown,
17}
18
19/// Recovery-relevant metadata attached to an operational error.
20#[derive(Debug, Clone, PartialEq, Serialize, Default)]
21pub struct FailureMetadata {
22    /// Whether the failure is transient, permanent, or unclassified.
23    pub kind: FailureKind,
24    /// Whether retrying the same operation can succeed.
25    pub retryable: Option<bool>,
26    /// Backend-provided retry delay, in seconds.
27    pub retry_after_seconds: Option<f64>,
28}
29
30impl FailureMetadata {
31    /// Creates validated failure metadata.
32    ///
33    /// # Errors
34    ///
35    /// Returns [`InvalidFailureMetadata`] when `retry_after_seconds` is
36    /// negative, NaN, or infinite.
37    pub fn new(
38        kind: FailureKind,
39        retryable: Option<bool>,
40        retry_after_seconds: Option<f64>,
41    ) -> Result<Self, InvalidFailureMetadata> {
42        if let Some(seconds) = retry_after_seconds {
43            if !seconds.is_finite() || seconds < 0.0 {
44                return Err(InvalidFailureMetadata::InvalidRetryAfter(seconds));
45            }
46        }
47
48        Ok(Self {
49            kind,
50            retryable,
51            retry_after_seconds,
52        })
53    }
54
55    /// Metadata for an unclassified failure.
56    #[must_use]
57    pub const fn unknown() -> Self {
58        Self {
59            kind: FailureKind::Unknown,
60            retryable: None,
61            retry_after_seconds: None,
62        }
63    }
64
65    /// Metadata for a transient failure.
66    ///
67    /// # Errors
68    ///
69    /// Returns [`InvalidFailureMetadata`] when `retry_after_seconds` is
70    /// negative, NaN, or infinite.
71    pub fn transient(retry_after_seconds: Option<f64>) -> Result<Self, InvalidFailureMetadata> {
72        Self::new(FailureKind::Transient, Some(true), retry_after_seconds)
73    }
74
75    /// Metadata for a permanent failure.
76    #[must_use]
77    pub const fn permanent() -> Self {
78        Self {
79            kind: FailureKind::Permanent,
80            retryable: Some(false),
81            retry_after_seconds: None,
82        }
83    }
84}
85
86impl<'de> Deserialize<'de> for FailureMetadata {
87    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
88    where
89        D: Deserializer<'de>,
90    {
91        #[derive(Deserialize)]
92        struct RawFailureMetadata {
93            kind: FailureKind,
94            retryable: Option<bool>,
95            retry_after_seconds: Option<f64>,
96        }
97
98        let raw = RawFailureMetadata::deserialize(deserializer)?;
99        Self::new(raw.kind, raw.retryable, raw.retry_after_seconds)
100            .map_err(serde::de::Error::custom)
101    }
102}
103
104/// Validation failure for [`FailureMetadata`].
105#[derive(Debug, Clone, Copy, PartialEq, Error)]
106pub enum InvalidFailureMetadata {
107    /// Retry delay was not finite and non-negative.
108    #[error("retry_after_seconds must be finite and non-negative, got {0}")]
109    InvalidRetryAfter(f64),
110}
111
112#[cfg(test)]
113mod tests {
114    use super::{FailureKind, FailureMetadata};
115
116    #[test]
117    fn rejects_negative_retry_delay_during_deserialization() {
118        let result = serde_json::from_str::<FailureMetadata>(
119            r#"{"kind":"transient","retryable":true,"retry_after_seconds":-1.0}"#,
120        );
121
122        assert!(result.is_err());
123    }
124
125    #[test]
126    fn accepts_valid_retry_delay_during_deserialization() {
127        let metadata = serde_json::from_str::<FailureMetadata>(
128            r#"{"kind":"transient","retryable":true,"retry_after_seconds":2.5}"#,
129        )
130        .expect("valid failure metadata should deserialize");
131
132        assert_eq!(metadata.kind, FailureKind::Transient);
133        assert_eq!(metadata.retryable, Some(true));
134        assert_eq!(metadata.retry_after_seconds, Some(2.5));
135    }
136
137    #[test]
138    fn rejects_negative_retry_delay() {
139        let result = FailureMetadata::new(FailureKind::Transient, Some(true), Some(-1.0));
140        assert!(result.is_err());
141    }
142
143    #[test]
144    fn rejects_non_finite_retry_delay() {
145        let result = FailureMetadata::transient(Some(f64::INFINITY));
146        assert!(result.is_err());
147    }
148
149    #[test]
150    fn permanent_failures_are_not_retryable() {
151        let metadata = FailureMetadata::permanent();
152        assert_eq!(metadata.kind, FailureKind::Permanent);
153        assert_eq!(metadata.retryable, Some(false));
154    }
155}