Skip to main content

use_idempotency/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7/// Error returned when API primitive text or labels are invalid.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10    /// The supplied value was empty after trimming.
11    Empty,
12    /// The supplied value used syntax this crate rejects.
13    Invalid,
14    /// The supplied label was not recognized.
15    Unknown,
16}
17
18impl fmt::Display for ApiPrimitiveError {
19    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::Empty => formatter.write_str("API primitive value cannot be empty"),
22            Self::Invalid => formatter.write_str("invalid API primitive value"),
23            Self::Unknown => formatter.write_str("unknown API primitive label"),
24        }
25    }
26}
27
28impl Error for ApiPrimitiveError {}
29
30fn validate_api_text(value: &str) -> Result<&str, ApiPrimitiveError> {
31    let trimmed = value.trim();
32    if trimmed.is_empty() {
33        return Err(ApiPrimitiveError::Empty);
34    }
35    if trimmed.chars().any(char::is_control) {
36        return Err(ApiPrimitiveError::Invalid);
37    }
38    Ok(trimmed)
39}
40
41macro_rules! text_newtype {
42    ($name:ident) => {
43        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44        pub struct $name(String);
45
46        impl $name {
47            /// Creates validated text metadata.
48            ///
49            /// # Errors
50            ///
51            /// Returns [ApiPrimitiveError] when the value is empty or contains control characters.
52            pub fn new(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
53                validate_api_text(value.as_ref()).map(|value| Self(value.to_owned()))
54            }
55
56            /// Parses validated text metadata.
57            ///
58            /// # Errors
59            ///
60            /// Returns [ApiPrimitiveError] when validation fails.
61            pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62                Self::new(value)
63            }
64
65            /// Returns the stored text.
66            #[must_use]
67            pub fn as_str(&self) -> &str {
68                &self.0
69            }
70
71            /// Consumes the value and returns the stored text.
72            #[must_use]
73            pub fn into_string(self) -> String {
74                self.0
75            }
76        }
77
78        impl AsRef<str> for $name {
79            fn as_ref(&self) -> &str {
80                self.as_str()
81            }
82        }
83
84        impl fmt::Display for $name {
85            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86                formatter.write_str(self.as_str())
87            }
88        }
89
90        impl FromStr for $name {
91            type Err = ApiPrimitiveError;
92
93            fn from_str(value: &str) -> Result<Self, Self::Err> {
94                Self::new(value)
95            }
96        }
97
98        impl TryFrom<&str> for $name {
99            type Error = ApiPrimitiveError;
100
101            fn try_from(value: &str) -> Result<Self, Self::Error> {
102                Self::new(value)
103            }
104        }
105    };
106}
107
108text_newtype!(IdempotencyKey);
109text_newtype!(IdempotencyScope);
110text_newtype!(RequestFingerprintLabel);
111
112/// Idempotency replay status labels.
113#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
114pub enum ReplayStatus {
115    /// A stable label variant.
116    Original,
117    /// A stable label variant.
118    Replayed,
119    /// A stable label variant.
120    Unknown,
121}
122
123impl ReplayStatus {
124    /// Returns the stable label.
125    #[must_use]
126    pub const fn as_str(self) -> &'static str {
127        match self {
128            Self::Original => "original",
129            Self::Replayed => "replayed",
130            Self::Unknown => "unknown",
131        }
132    }
133}
134
135impl Default for ReplayStatus {
136    fn default() -> Self {
137        Self::Original
138    }
139}
140
141impl fmt::Display for ReplayStatus {
142    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
143        formatter.write_str(self.as_str())
144    }
145}
146
147impl FromStr for ReplayStatus {
148    type Err = ApiPrimitiveError;
149
150    fn from_str(value: &str) -> Result<Self, Self::Err> {
151        let trimmed = value.trim();
152        if trimmed.is_empty() {
153            return Err(ApiPrimitiveError::Empty);
154        }
155        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
156        match normalized.as_str() {
157            "original" => Ok(Self::Original),
158            "replayed" => Ok(Self::Replayed),
159            "unknown" => Ok(Self::Unknown),
160            _ => Err(ApiPrimitiveError::Unknown),
161        }
162    }
163}
164/// Idempotency conflict status labels.
165#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
166pub enum ConflictStatus {
167    /// A stable label variant.
168    None,
169    /// A stable label variant.
170    SameKeyDifferentRequest,
171    /// A stable label variant.
172    InProgress,
173}
174
175impl ConflictStatus {
176    /// Returns the stable label.
177    #[must_use]
178    pub const fn as_str(self) -> &'static str {
179        match self {
180            Self::None => "none",
181            Self::SameKeyDifferentRequest => "same-key-different-request",
182            Self::InProgress => "in-progress",
183        }
184    }
185}
186
187impl Default for ConflictStatus {
188    fn default() -> Self {
189        Self::None
190    }
191}
192
193impl fmt::Display for ConflictStatus {
194    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
195        formatter.write_str(self.as_str())
196    }
197}
198
199impl FromStr for ConflictStatus {
200    type Err = ApiPrimitiveError;
201
202    fn from_str(value: &str) -> Result<Self, Self::Err> {
203        let trimmed = value.trim();
204        if trimmed.is_empty() {
205            return Err(ApiPrimitiveError::Empty);
206        }
207        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
208        match normalized.as_str() {
209            "none" => Ok(Self::None),
210            "same-key-different-request" => Ok(Self::SameKeyDifferentRequest),
211            "in-progress" => Ok(Self::InProgress),
212            _ => Err(ApiPrimitiveError::Unknown),
213        }
214    }
215}
216
217/// Lightweight metadata tying this crate's primary text and label together.
218#[derive(Clone, Debug, Eq, PartialEq)]
219pub struct PrimitiveMetadata {
220    name: IdempotencyKey,
221    kind: ReplayStatus,
222}
223
224impl PrimitiveMetadata {
225    /// Creates primitive metadata.
226    #[must_use]
227    pub const fn new(name: IdempotencyKey, kind: ReplayStatus) -> Self {
228        Self { name, kind }
229    }
230
231    /// Returns the primary text value.
232    #[must_use]
233    pub const fn name(&self) -> &IdempotencyKey {
234        &self.name
235    }
236
237    /// Returns the primary label.
238    #[must_use]
239    pub const fn kind(&self) -> ReplayStatus {
240        self.kind
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
250        let value = IdempotencyKey::new("checkout:abc123")?;
251
252        assert_eq!(value.as_str(), "checkout:abc123");
253        assert_eq!(value.to_string(), "checkout:abc123");
254        assert_eq!("checkout:abc123".parse::<IdempotencyKey>()?, value);
255        Ok(())
256    }
257
258    #[test]
259    fn rejects_empty_text() {
260        assert_eq!(IdempotencyKey::new(""), Err(ApiPrimitiveError::Empty));
261    }
262
263    #[test]
264    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
265        let kind = "original".parse::<ReplayStatus>()?;
266
267        assert_eq!(kind, ReplayStatus::Original);
268        assert_eq!(kind.to_string(), "original");
269        Ok(())
270    }
271
272    #[test]
273    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
274        let metadata = PrimitiveMetadata::new(
275            IdempotencyKey::new("checkout:abc123")?,
276            ReplayStatus::default(),
277        );
278
279        assert_eq!(metadata.name().as_str(), "checkout:abc123");
280        assert_eq!(metadata.kind(), ReplayStatus::default());
281        Ok(())
282    }
283}