Skip to main content

use_api_request/
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!(RequestId);
109text_newtype!(CorrelationId);
110text_newtype!(TraceId);
111text_newtype!(RequestTimestampLabel);
112text_newtype!(RequestSource);
113
114/// Request context kind labels.
115#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
116pub enum RequestContextKind {
117    /// A stable label variant.
118    User,
119    /// A stable label variant.
120    Service,
121    /// A stable label variant.
122    Job,
123    /// A stable label variant.
124    Test,
125    /// A stable label variant.
126    Unknown,
127}
128
129impl RequestContextKind {
130    /// Returns the stable label.
131    #[must_use]
132    pub const fn as_str(self) -> &'static str {
133        match self {
134            Self::User => "user",
135            Self::Service => "service",
136            Self::Job => "job",
137            Self::Test => "test",
138            Self::Unknown => "unknown",
139        }
140    }
141}
142
143impl Default for RequestContextKind {
144    fn default() -> Self {
145        Self::User
146    }
147}
148
149impl fmt::Display for RequestContextKind {
150    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
151        formatter.write_str(self.as_str())
152    }
153}
154
155impl FromStr for RequestContextKind {
156    type Err = ApiPrimitiveError;
157
158    fn from_str(value: &str) -> Result<Self, Self::Err> {
159        let trimmed = value.trim();
160        if trimmed.is_empty() {
161            return Err(ApiPrimitiveError::Empty);
162        }
163        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
164        match normalized.as_str() {
165            "user" => Ok(Self::User),
166            "service" => Ok(Self::Service),
167            "job" => Ok(Self::Job),
168            "test" => Ok(Self::Test),
169            "unknown" => Ok(Self::Unknown),
170            _ => Err(ApiPrimitiveError::Unknown),
171        }
172    }
173}
174
175/// Lightweight metadata tying this crate's primary text and label together.
176#[derive(Clone, Debug, Eq, PartialEq)]
177pub struct PrimitiveMetadata {
178    name: RequestId,
179    kind: RequestContextKind,
180}
181
182impl PrimitiveMetadata {
183    /// Creates primitive metadata.
184    #[must_use]
185    pub const fn new(name: RequestId, kind: RequestContextKind) -> Self {
186        Self { name, kind }
187    }
188
189    /// Returns the primary text value.
190    #[must_use]
191    pub const fn name(&self) -> &RequestId {
192        &self.name
193    }
194
195    /// Returns the primary label.
196    #[must_use]
197    pub const fn kind(&self) -> RequestContextKind {
198        self.kind
199    }
200}
201
202/// Protocol-neutral request envelope.
203#[derive(Clone, Debug, Eq, PartialEq)]
204pub struct ApiRequest<T> {
205    id: RequestId,
206    context: RequestContextKind,
207    body: T,
208}
209
210impl<T> ApiRequest<T> {
211    /// Creates a request envelope.
212    #[must_use]
213    pub const fn new(id: RequestId, body: T) -> Self {
214        Self {
215            id,
216            context: RequestContextKind::Unknown,
217            body,
218        }
219    }
220
221    /// Sets request context metadata.
222    #[must_use]
223    pub const fn with_context(mut self, context: RequestContextKind) -> Self {
224        self.context = context;
225        self
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
235        let value = RequestId::new("req_123")?;
236
237        assert_eq!(value.as_str(), "req_123");
238        assert_eq!(value.to_string(), "req_123");
239        assert_eq!("req_123".parse::<RequestId>()?, value);
240        Ok(())
241    }
242
243    #[test]
244    fn rejects_empty_text() {
245        assert_eq!(RequestId::new(""), Err(ApiPrimitiveError::Empty));
246    }
247
248    #[test]
249    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
250        let kind = "user".parse::<RequestContextKind>()?;
251
252        assert_eq!(kind, RequestContextKind::User);
253        assert_eq!(kind.to_string(), "user");
254        Ok(())
255    }
256
257    #[test]
258    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
259        let metadata =
260            PrimitiveMetadata::new(RequestId::new("req_123")?, RequestContextKind::default());
261
262        assert_eq!(metadata.name().as_str(), "req_123");
263        assert_eq!(metadata.kind(), RequestContextKind::default());
264        Ok(())
265    }
266}