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!(WebhookEventName);
109text_newtype!(WebhookEndpointUrl);
110text_newtype!(DeliveryId);
111text_newtype!(SignatureHeaderName);
112
113#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115pub enum DeliveryStatus {
116 Pending,
118 Delivered,
120 Failed,
122 Retrying,
124 Abandoned,
126}
127
128impl DeliveryStatus {
129 #[must_use]
131 pub const fn as_str(self) -> &'static str {
132 match self {
133 Self::Pending => "pending",
134 Self::Delivered => "delivered",
135 Self::Failed => "failed",
136 Self::Retrying => "retrying",
137 Self::Abandoned => "abandoned",
138 }
139 }
140}
141
142impl Default for DeliveryStatus {
143 fn default() -> Self {
144 Self::Pending
145 }
146}
147
148impl fmt::Display for DeliveryStatus {
149 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150 formatter.write_str(self.as_str())
151 }
152}
153
154impl FromStr for DeliveryStatus {
155 type Err = ApiPrimitiveError;
156
157 fn from_str(value: &str) -> Result<Self, Self::Err> {
158 let trimmed = value.trim();
159 if trimmed.is_empty() {
160 return Err(ApiPrimitiveError::Empty);
161 }
162 let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
163 match normalized.as_str() {
164 "pending" => Ok(Self::Pending),
165 "delivered" => Ok(Self::Delivered),
166 "failed" => Ok(Self::Failed),
167 "retrying" => Ok(Self::Retrying),
168 "abandoned" => Ok(Self::Abandoned),
169 _ => Err(ApiPrimitiveError::Unknown),
170 }
171 }
172}
173
174#[derive(Clone, Debug, Eq, PartialEq)]
176pub struct PrimitiveMetadata {
177 name: WebhookEventName,
178 kind: DeliveryStatus,
179}
180
181impl PrimitiveMetadata {
182 #[must_use]
184 pub const fn new(name: WebhookEventName, kind: DeliveryStatus) -> Self {
185 Self { name, kind }
186 }
187
188 #[must_use]
190 pub const fn name(&self) -> &WebhookEventName {
191 &self.name
192 }
193
194 #[must_use]
196 pub const fn kind(&self) -> DeliveryStatus {
197 self.kind
198 }
199}
200
201#[derive(Clone, Debug, Eq, PartialEq)]
203pub struct WebhookEvent {
204 event: WebhookEventName,
205 delivery_id: DeliveryId,
206 status: DeliveryStatus,
207}
208
209impl WebhookEvent {
210 #[must_use]
212 pub const fn new(event: WebhookEventName, delivery_id: DeliveryId) -> Self {
213 Self {
214 event,
215 delivery_id,
216 status: DeliveryStatus::Pending,
217 }
218 }
219
220 #[must_use]
222 pub const fn with_status(mut self, status: DeliveryStatus) -> Self {
223 self.status = status;
224 self
225 }
226}
227
228#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
230pub struct DeliveryAttempt(u32);
231
232impl DeliveryAttempt {
233 pub const fn new(value: u32) -> Result<Self, ApiPrimitiveError> {
235 if value == 0 {
236 Err(ApiPrimitiveError::Invalid)
237 } else {
238 Ok(Self(value))
239 }
240 }
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246
247 #[test]
248 fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
249 let value = WebhookEventName::new("user.created")?;
250
251 assert_eq!(value.as_str(), "user.created");
252 assert_eq!(value.to_string(), "user.created");
253 assert_eq!("user.created".parse::<WebhookEventName>()?, value);
254 Ok(())
255 }
256
257 #[test]
258 fn rejects_empty_text() {
259 assert_eq!(WebhookEventName::new(""), Err(ApiPrimitiveError::Empty));
260 }
261
262 #[test]
263 fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
264 let kind = "pending".parse::<DeliveryStatus>()?;
265
266 assert_eq!(kind, DeliveryStatus::Pending);
267 assert_eq!(kind.to_string(), "pending");
268 Ok(())
269 }
270
271 #[test]
272 fn creates_metadata() -> Result<(), ApiPrimitiveError> {
273 let metadata = PrimitiveMetadata::new(
274 WebhookEventName::new("user.created")?,
275 DeliveryStatus::default(),
276 );
277
278 assert_eq!(metadata.name().as_str(), "user.created");
279 assert_eq!(metadata.kind(), DeliveryStatus::default());
280 Ok(())
281 }
282}