1use serde::{Deserialize, Serialize};
9use std::fmt;
10use std::str::FromStr;
11
12#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
14pub enum HttpMethod {
15 GET,
16 POST,
17 PUT,
18 DELETE,
19 HEAD,
20 OPTIONS,
21 PATCH,
22 CONNECT,
23 TRACE,
24 #[serde(untagged)]
25 Custom(String),
26}
27
28impl FromStr for HttpMethod {
29 type Err = std::convert::Infallible;
30
31 fn from_str(s: &str) -> Result<Self, Self::Err> {
32 Ok(match s.to_uppercase().as_str() {
33 "GET" => Self::GET,
34 "POST" => Self::POST,
35 "PUT" => Self::PUT,
36 "DELETE" => Self::DELETE,
37 "HEAD" => Self::HEAD,
38 "OPTIONS" => Self::OPTIONS,
39 "PATCH" => Self::PATCH,
40 "CONNECT" => Self::CONNECT,
41 "TRACE" => Self::TRACE,
42 other => Self::Custom(other.to_string()),
43 })
44 }
45}
46
47impl fmt::Display for HttpMethod {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 match self {
50 Self::GET => write!(f, "GET"),
51 Self::POST => write!(f, "POST"),
52 Self::PUT => write!(f, "PUT"),
53 Self::DELETE => write!(f, "DELETE"),
54 Self::HEAD => write!(f, "HEAD"),
55 Self::OPTIONS => write!(f, "OPTIONS"),
56 Self::PATCH => write!(f, "PATCH"),
57 Self::CONNECT => write!(f, "CONNECT"),
58 Self::TRACE => write!(f, "TRACE"),
59 Self::Custom(method) => write!(f, "{}", method),
60 }
61 }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
66pub enum TlsVersion {
67 #[serde(rename = "TLS1.2")]
68 Tls12,
69 #[serde(rename = "TLS1.3")]
70 Tls13,
71}
72
73impl fmt::Display for TlsVersion {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 match self {
76 Self::Tls12 => write!(f, "TLS1.2"),
77 Self::Tls13 => write!(f, "TLS1.3"),
78 }
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
104#[serde(rename_all = "lowercase")]
105pub enum TraceIdFormat {
106 #[default]
108 TinyFlake,
109
110 Uuid,
112}
113
114impl TraceIdFormat {
115 pub fn from_str_loose(s: &str) -> Self {
117 match s.to_lowercase().as_str() {
118 "uuid" | "uuid4" | "uuidv4" => TraceIdFormat::Uuid,
119 _ => TraceIdFormat::TinyFlake, }
121 }
122}
123
124impl fmt::Display for TraceIdFormat {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 match self {
127 TraceIdFormat::TinyFlake => write!(f, "tinyflake"),
128 TraceIdFormat::Uuid => write!(f, "uuid"),
129 }
130 }
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136pub enum LoadBalancingAlgorithm {
137 RoundRobin,
138 LeastConnections,
139 Random,
140 IpHash,
141 Weighted,
142 ConsistentHash,
143 PowerOfTwoChoices,
144 Adaptive,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(rename_all = "snake_case")]
150pub enum HealthCheckType {
151 Http {
152 path: String,
153 expected_status: u16,
154 #[serde(skip_serializing_if = "Option::is_none")]
155 host: Option<String>,
156 },
157 Tcp,
158 Grpc {
159 service: String,
160 },
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct RetryPolicy {
166 pub max_attempts: u32,
167 pub timeout_ms: u64,
168 pub backoff_base_ms: u64,
169 pub backoff_max_ms: u64,
170 pub retryable_status_codes: Vec<u16>,
171}
172
173impl Default for RetryPolicy {
174 fn default() -> Self {
175 Self {
176 max_attempts: 3,
177 timeout_ms: 30000,
178 backoff_base_ms: 100,
179 backoff_max_ms: 10000,
180 retryable_status_codes: vec![502, 503, 504],
181 }
182 }
183}
184
185#[derive(Debug, Clone, Serialize, Deserialize)]
187pub struct CircuitBreakerConfig {
188 pub failure_threshold: u32,
189 pub success_threshold: u32,
190 pub timeout_seconds: u64,
191 pub half_open_max_requests: u32,
192}
193
194impl Default for CircuitBreakerConfig {
195 fn default() -> Self {
196 Self {
197 failure_threshold: 5,
198 success_threshold: 2,
199 timeout_seconds: 30,
200 half_open_max_requests: 1,
201 }
202 }
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
207#[serde(rename_all = "snake_case")]
208pub enum CircuitBreakerState {
209 Closed,
210 Open,
211 HalfOpen,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
216#[serde(rename_all = "snake_case")]
217pub enum Priority {
218 Low = 0,
219 #[default]
220 Normal = 1,
221 High = 2,
222 Critical = 3,
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
227pub struct TimeWindow {
228 pub seconds: u64,
229}
230
231impl TimeWindow {
232 pub fn new(seconds: u64) -> Self {
233 Self { seconds }
234 }
235
236 pub fn as_duration(&self) -> std::time::Duration {
237 std::time::Duration::from_secs(self.seconds)
238 }
239}
240
241#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
243pub struct ByteSize(pub usize);
244
245impl ByteSize {
246 pub const KB: usize = 1024;
247 pub const MB: usize = 1024 * 1024;
248 pub const GB: usize = 1024 * 1024 * 1024;
249
250 pub fn from_kb(kb: usize) -> Self {
251 Self(kb * Self::KB)
252 }
253
254 pub fn from_mb(mb: usize) -> Self {
255 Self(mb * Self::MB)
256 }
257
258 pub fn from_gb(gb: usize) -> Self {
259 Self(gb * Self::GB)
260 }
261
262 pub fn as_bytes(&self) -> usize {
263 self.0
264 }
265}
266
267impl fmt::Display for ByteSize {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 if self.0 >= Self::GB {
270 write!(f, "{:.2}GB", self.0 as f64 / Self::GB as f64)
271 } else if self.0 >= Self::MB {
272 write!(f, "{:.2}MB", self.0 as f64 / Self::MB as f64)
273 } else if self.0 >= Self::KB {
274 write!(f, "{:.2}KB", self.0 as f64 / Self::KB as f64)
275 } else {
276 write!(f, "{}B", self.0)
277 }
278 }
279}
280
281impl Serialize for ByteSize {
282 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
283 where
284 S: serde::Serializer,
285 {
286 serializer.serialize_str(&self.to_string())
287 }
288}
289
290impl<'de> Deserialize<'de> for ByteSize {
291 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
292 where
293 D: serde::Deserializer<'de>,
294 {
295 let s = String::deserialize(deserializer)?;
296 Self::from_str(&s).map_err(serde::de::Error::custom)
297 }
298}
299
300impl FromStr for ByteSize {
301 type Err = String;
302
303 fn from_str(s: &str) -> Result<Self, Self::Err> {
304 let s = s.trim();
305 if s.is_empty() {
306 return Err("Empty byte size string".to_string());
307 }
308
309 if let Ok(bytes) = s.parse::<usize>() {
311 return Ok(Self(bytes));
312 }
313
314 let (num_part, unit_part) = s
316 .chars()
317 .position(|c| c.is_alphabetic())
318 .map(|i| s.split_at(i))
319 .ok_or_else(|| format!("Invalid byte size format: {}", s))?;
320
321 let value: f64 = num_part
322 .trim()
323 .parse()
324 .map_err(|_| format!("Invalid number: {}", num_part))?;
325
326 let multiplier = match unit_part.to_uppercase().as_str() {
327 "B" => 1,
328 "KB" | "K" => Self::KB,
329 "MB" | "M" => Self::MB,
330 "GB" | "G" => Self::GB,
331 _ => return Err(format!("Invalid unit: {}", unit_part)),
332 };
333
334 Ok(Self((value * multiplier as f64) as usize))
335 }
336}
337
338#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
340pub struct ClientIp {
341 pub address: std::net::IpAddr,
342 #[serde(skip_serializing_if = "Option::is_none")]
343 pub forwarded_for: Option<Vec<std::net::IpAddr>>,
344}
345
346impl fmt::Display for ClientIp {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 write!(f, "{}", self.address)
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn test_http_method_parsing() {
358 assert_eq!(HttpMethod::from_str("GET").unwrap(), HttpMethod::GET);
359 assert_eq!(HttpMethod::from_str("post").unwrap(), HttpMethod::POST);
360 assert_eq!(
361 HttpMethod::from_str("PROPFIND").unwrap(),
362 HttpMethod::Custom("PROPFIND".to_string())
363 );
364 }
365
366 #[test]
367 fn test_byte_size_parsing() {
368 assert_eq!(ByteSize::from_str("1024").unwrap().0, 1024);
369 assert_eq!(ByteSize::from_str("10KB").unwrap().0, 10 * 1024);
370 assert_eq!(
371 ByteSize::from_str("5.5MB").unwrap().0,
372 (5.5 * 1024.0 * 1024.0) as usize
373 );
374 assert_eq!(ByteSize::from_str("2GB").unwrap().0, 2 * 1024 * 1024 * 1024);
375 assert_eq!(ByteSize::from_str("100 B").unwrap().0, 100);
376 }
377
378 #[test]
379 fn test_byte_size_display() {
380 assert_eq!(ByteSize(512).to_string(), "512B");
381 assert_eq!(ByteSize(2048).to_string(), "2.00KB");
382 assert_eq!(ByteSize(1024 * 1024).to_string(), "1.00MB");
383 assert_eq!(ByteSize(1024 * 1024 * 1024).to_string(), "1.00GB");
384 }
385
386 #[test]
387 fn test_trace_id_format() {
388 assert_eq!(TraceIdFormat::from_str_loose("uuid"), TraceIdFormat::Uuid);
389 assert_eq!(
390 TraceIdFormat::from_str_loose("tinyflake"),
391 TraceIdFormat::TinyFlake
392 );
393 assert_eq!(
394 TraceIdFormat::from_str_loose("unknown"),
395 TraceIdFormat::TinyFlake
396 );
397 }
398}