1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10 Empty,
12 Invalid,
14 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 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 pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62 Self::new(value)
63 }
64
65 #[must_use]
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70
71 #[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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115pub enum ProcedureKind {
116 Method,
118 Notification,
120 Query,
122 Command,
124}
125
126impl ProcedureKind {
127 #[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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
171pub enum RpcResponseStatus {
172 Success,
174 Error,
176}
177
178impl RpcResponseStatus {
179 #[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#[derive(Clone, Debug, Eq, PartialEq)]
220pub struct PrimitiveMetadata {
221 name: RpcMethodName,
222 kind: ProcedureKind,
223}
224
225impl PrimitiveMetadata {
226 #[must_use]
228 pub const fn new(name: RpcMethodName, kind: ProcedureKind) -> Self {
229 Self { name, kind }
230 }
231
232 #[must_use]
234 pub const fn name(&self) -> &RpcMethodName {
235 &self.name
236 }
237
238 #[must_use]
240 pub const fn kind(&self) -> ProcedureKind {
241 self.kind
242 }
243}
244
245#[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 #[must_use]
256 pub const fn new(id: RpcRequestId, method: RpcMethodName, body: T) -> Self {
257 Self { id, method, body }
258 }
259
260 #[must_use]
262 pub const fn id(&self) -> &RpcRequestId {
263 &self.id
264 }
265
266 #[must_use]
268 pub const fn method(&self) -> &RpcMethodName {
269 &self.method
270 }
271
272 #[must_use]
274 pub const fn body(&self) -> &T {
275 &self.body
276 }
277}
278
279#[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 #[must_use]
290 pub const fn new(id: RpcRequestId, status: RpcResponseStatus, body: T) -> Self {
291 Self { id, status, body }
292 }
293
294 #[must_use]
296 pub const fn status(&self) -> RpcResponseStatus {
297 self.status
298 }
299}
300
301#[derive(Clone, Debug, Eq, PartialEq)]
303pub struct ErrorEnvelope {
304 code: RpcErrorCode,
305 message: RpcErrorMessage,
306}
307
308impl ErrorEnvelope {
309 #[must_use]
311 pub const fn new(code: RpcErrorCode, message: RpcErrorMessage) -> Self {
312 Self { code, message }
313 }
314
315 #[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}