Skip to main content

use_rpc/
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!(RpcMethodName);
109text_newtype!(RpcRequestId);
110text_newtype!(RpcErrorCode);
111text_newtype!(RpcErrorMessage);
112
113/// Protocol-neutral procedure kind labels.
114#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115pub enum ProcedureKind {
116    /// A stable label variant.
117    Method,
118    /// A stable label variant.
119    Notification,
120    /// A stable label variant.
121    Query,
122    /// A stable label variant.
123    Command,
124}
125
126impl ProcedureKind {
127    /// Returns the stable label.
128    #[must_use]
129    pub const fn as_str(self) -> &'static str {
130        match self {
131            Self::Method => "method",
132            Self::Notification => "notification",
133            Self::Query => "query",
134            Self::Command => "command",
135        }
136    }
137}
138
139impl Default for ProcedureKind {
140    fn default() -> Self {
141        Self::Method
142    }
143}
144
145impl fmt::Display for ProcedureKind {
146    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
147        formatter.write_str(self.as_str())
148    }
149}
150
151impl FromStr for ProcedureKind {
152    type Err = ApiPrimitiveError;
153
154    fn from_str(value: &str) -> Result<Self, Self::Err> {
155        let trimmed = value.trim();
156        if trimmed.is_empty() {
157            return Err(ApiPrimitiveError::Empty);
158        }
159        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
160        match normalized.as_str() {
161            "method" => Ok(Self::Method),
162            "notification" => Ok(Self::Notification),
163            "query" => Ok(Self::Query),
164            "command" => Ok(Self::Command),
165            _ => Err(ApiPrimitiveError::Unknown),
166        }
167    }
168}
169/// Protocol-neutral response status labels.
170#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
171pub enum RpcResponseStatus {
172    /// A stable label variant.
173    Success,
174    /// A stable label variant.
175    Error,
176}
177
178impl RpcResponseStatus {
179    /// Returns the stable label.
180    #[must_use]
181    pub const fn as_str(self) -> &'static str {
182        match self {
183            Self::Success => "success",
184            Self::Error => "error",
185        }
186    }
187}
188
189impl Default for RpcResponseStatus {
190    fn default() -> Self {
191        Self::Success
192    }
193}
194
195impl fmt::Display for RpcResponseStatus {
196    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
197        formatter.write_str(self.as_str())
198    }
199}
200
201impl FromStr for RpcResponseStatus {
202    type Err = ApiPrimitiveError;
203
204    fn from_str(value: &str) -> Result<Self, Self::Err> {
205        let trimmed = value.trim();
206        if trimmed.is_empty() {
207            return Err(ApiPrimitiveError::Empty);
208        }
209        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
210        match normalized.as_str() {
211            "success" => Ok(Self::Success),
212            "error" => Ok(Self::Error),
213            _ => Err(ApiPrimitiveError::Unknown),
214        }
215    }
216}
217
218/// Lightweight metadata tying this crate's primary text and label together.
219#[derive(Clone, Debug, Eq, PartialEq)]
220pub struct PrimitiveMetadata {
221    name: RpcMethodName,
222    kind: ProcedureKind,
223}
224
225impl PrimitiveMetadata {
226    /// Creates primitive metadata.
227    #[must_use]
228    pub const fn new(name: RpcMethodName, kind: ProcedureKind) -> Self {
229        Self { name, kind }
230    }
231
232    /// Returns the primary text value.
233    #[must_use]
234    pub const fn name(&self) -> &RpcMethodName {
235        &self.name
236    }
237
238    /// Returns the primary label.
239    #[must_use]
240    pub const fn kind(&self) -> ProcedureKind {
241        self.kind
242    }
243}
244
245/// Protocol-neutral RPC request envelope.
246#[derive(Clone, Debug, Eq, PartialEq)]
247pub struct RequestEnvelope<T> {
248    id: RpcRequestId,
249    method: RpcMethodName,
250    body: T,
251}
252
253impl<T> RequestEnvelope<T> {
254    /// Creates a request envelope.
255    #[must_use]
256    pub const fn new(id: RpcRequestId, method: RpcMethodName, body: T) -> Self {
257        Self { id, method, body }
258    }
259
260    /// Returns the request ID.
261    #[must_use]
262    pub const fn id(&self) -> &RpcRequestId {
263        &self.id
264    }
265
266    /// Returns the method name.
267    #[must_use]
268    pub const fn method(&self) -> &RpcMethodName {
269        &self.method
270    }
271
272    /// Returns the request body.
273    #[must_use]
274    pub const fn body(&self) -> &T {
275        &self.body
276    }
277}
278
279/// Protocol-neutral RPC response envelope.
280#[derive(Clone, Debug, Eq, PartialEq)]
281pub struct ResponseEnvelope<T> {
282    id: RpcRequestId,
283    status: RpcResponseStatus,
284    body: T,
285}
286
287impl<T> ResponseEnvelope<T> {
288    /// Creates a response envelope.
289    #[must_use]
290    pub const fn new(id: RpcRequestId, status: RpcResponseStatus, body: T) -> Self {
291        Self { id, status, body }
292    }
293
294    /// Returns the response status.
295    #[must_use]
296    pub const fn status(&self) -> RpcResponseStatus {
297        self.status
298    }
299}
300
301/// Protocol-neutral RPC error envelope.
302#[derive(Clone, Debug, Eq, PartialEq)]
303pub struct ErrorEnvelope {
304    code: RpcErrorCode,
305    message: RpcErrorMessage,
306}
307
308impl ErrorEnvelope {
309    /// Creates an error envelope.
310    #[must_use]
311    pub const fn new(code: RpcErrorCode, message: RpcErrorMessage) -> Self {
312        Self { code, message }
313    }
314
315    /// Returns the error code.
316    #[must_use]
317    pub const fn code(&self) -> &RpcErrorCode {
318        &self.code
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
328        let value = RpcMethodName::new("users.get")?;
329
330        assert_eq!(value.as_str(), "users.get");
331        assert_eq!(value.to_string(), "users.get");
332        assert_eq!("users.get".parse::<RpcMethodName>()?, value);
333        Ok(())
334    }
335
336    #[test]
337    fn rejects_empty_text() {
338        assert_eq!(RpcMethodName::new(""), Err(ApiPrimitiveError::Empty));
339    }
340
341    #[test]
342    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
343        let kind = "method".parse::<ProcedureKind>()?;
344
345        assert_eq!(kind, ProcedureKind::Method);
346        assert_eq!(kind.to_string(), "method");
347        Ok(())
348    }
349
350    #[test]
351    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
352        let metadata =
353            PrimitiveMetadata::new(RpcMethodName::new("users.get")?, ProcedureKind::default());
354
355        assert_eq!(metadata.name().as_str(), "users.get");
356        assert_eq!(metadata.kind(), ProcedureKind::default());
357        Ok(())
358    }
359}