zentinel-common 0.6.9

Common utilities and types for Zentinel reverse proxy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Common type definitions for Zentinel proxy.
//!
//! This module provides shared type definitions used throughout the platform,
//! with a focus on type safety and operational clarity.
//!
//! For identifier types (CorrelationId, RequestId, etc.), see the `ids` module.

use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

/// HTTP method wrapper with validation
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HttpMethod {
    GET,
    POST,
    PUT,
    DELETE,
    HEAD,
    OPTIONS,
    PATCH,
    CONNECT,
    TRACE,
    #[serde(untagged)]
    Custom(String),
}

impl FromStr for HttpMethod {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.to_uppercase().as_str() {
            "GET" => Self::GET,
            "POST" => Self::POST,
            "PUT" => Self::PUT,
            "DELETE" => Self::DELETE,
            "HEAD" => Self::HEAD,
            "OPTIONS" => Self::OPTIONS,
            "PATCH" => Self::PATCH,
            "CONNECT" => Self::CONNECT,
            "TRACE" => Self::TRACE,
            other => Self::Custom(other.to_string()),
        })
    }
}

impl fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::GET => write!(f, "GET"),
            Self::POST => write!(f, "POST"),
            Self::PUT => write!(f, "PUT"),
            Self::DELETE => write!(f, "DELETE"),
            Self::HEAD => write!(f, "HEAD"),
            Self::OPTIONS => write!(f, "OPTIONS"),
            Self::PATCH => write!(f, "PATCH"),
            Self::CONNECT => write!(f, "CONNECT"),
            Self::TRACE => write!(f, "TRACE"),
            Self::Custom(method) => write!(f, "{}", method),
        }
    }
}

/// TLS version
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TlsVersion {
    #[serde(rename = "TLS1.2")]
    Tls12,
    #[serde(rename = "TLS1.3")]
    Tls13,
}

impl fmt::Display for TlsVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Tls12 => write!(f, "TLS1.2"),
            Self::Tls13 => write!(f, "TLS1.3"),
        }
    }
}

/// Trace ID format selection.
///
/// Controls how trace IDs are generated for request tracing.
///
/// # Formats
///
/// - **TinyFlake** (default): 11-character Base58 encoded ID with time prefix.
///   Operator-friendly format designed for easy copying and log correlation.
///   Example: `k7BxR3nVp2Ym`
///
/// - **UUID**: Standard 36-character UUID v4 format with dashes.
///   Guaranteed unique, widely compatible.
///   Example: `550e8400-e29b-41d4-a716-446655440000`
///
/// # Configuration
///
/// ```kdl
/// server {
///     trace-id-format "tinyflake"  // or "uuid"
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TraceIdFormat {
    /// TinyFlake format: 11-char Base58, time-prefixed (default)
    #[default]
    TinyFlake,

    /// UUID v4 format: 36-char with dashes
    Uuid,
}

impl TraceIdFormat {
    /// Parse format from string (case-insensitive)
    pub fn from_str_loose(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "uuid" | "uuid4" | "uuidv4" => TraceIdFormat::Uuid,
            _ => TraceIdFormat::TinyFlake, // Default to TinyFlake
        }
    }
}

impl fmt::Display for TraceIdFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TraceIdFormat::TinyFlake => write!(f, "tinyflake"),
            TraceIdFormat::Uuid => write!(f, "uuid"),
        }
    }
}

/// Load balancing algorithm
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LoadBalancingAlgorithm {
    RoundRobin,
    LeastConnections,
    Random,
    IpHash,
    Weighted,
    ConsistentHash,
    PowerOfTwoChoices,
    Adaptive,
    /// Least tokens queued - for inference/LLM workloads
    ///
    /// Selects the upstream with the fewest estimated tokens currently
    /// being processed. Useful for LLM inference backends where token
    /// throughput varies significantly between requests.
    LeastTokensQueued,
    /// Maglev consistent hashing - Google's load balancing algorithm
    ///
    /// Provides minimal disruption when backend servers are added/removed,
    /// with better load distribution than traditional consistent hashing.
    /// Uses a permutation-based lookup table for O(1) selection.
    Maglev,
    /// Locality-aware load balancing
    ///
    /// Prefers targets in the same zone/region as the proxy, falling back
    /// to other zones when local targets are unhealthy or overloaded.
    /// Useful for multi-region deployments to minimize latency.
    LocalityAware,
    /// Peak EWMA (Exponentially Weighted Moving Average)
    ///
    /// Twitter Finagle's algorithm that tracks latency using EWMA and selects
    /// the backend with the lowest predicted completion time. Reacts quickly
    /// to latency spikes by using the peak of EWMA and recent latency.
    PeakEwma,
    /// Deterministic Subsetting
    ///
    /// For very large clusters (1000+ backends), limits each proxy instance
    /// to a deterministic subset of backends. Reduces connection overhead
    /// while ensuring even distribution across all proxies.
    DeterministicSubset,
    /// Weighted Least Connections
    ///
    /// Combines weight with connection counting. Selects the backend with
    /// the lowest ratio of active connections to weight. Useful when backends
    /// have different capacities.
    WeightedLeastConnections,
    /// Cookie-based sticky sessions
    ///
    /// Routes requests to the same backend based on an affinity cookie.
    /// Falls back to a configurable algorithm when no cookie is present or
    /// the target is unavailable. Useful for stateful applications that
    /// require session affinity.
    Sticky,
}

/// Health check type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HealthCheckType {
    Http {
        path: String,
        expected_status: u16,
        #[serde(skip_serializing_if = "Option::is_none")]
        host: Option<String>,
    },
    Tcp,
    Grpc {
        service: String,
    },
    /// Inference health check for LLM/AI backends
    ///
    /// Probes the `/v1/models` endpoint (or custom endpoint) to verify
    /// the inference server is running and expected models are available.
    /// Optionally includes enhanced readiness checks for model availability.
    Inference {
        /// Endpoint to probe (default: "/v1/models")
        endpoint: String,
        /// Expected models that must be available (optional)
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        expected_models: Vec<String>,
        /// Enhanced readiness checks (optional)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        readiness: Option<Box<crate::inference::InferenceReadinessConfig>>,
    },
}

/// Retry policy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryPolicy {
    pub max_attempts: u32,
    pub timeout_ms: u64,
    pub backoff_base_ms: u64,
    pub backoff_max_ms: u64,
    pub retryable_status_codes: Vec<u16>,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            timeout_ms: 30000,
            backoff_base_ms: 100,
            backoff_max_ms: 10000,
            retryable_status_codes: vec![502, 503, 504],
        }
    }
}

/// Circuit breaker configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CircuitBreakerConfig {
    pub failure_threshold: u32,
    pub success_threshold: u32,
    pub timeout_seconds: u64,
    pub half_open_max_requests: u32,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            success_threshold: 2,
            timeout_seconds: 30,
            half_open_max_requests: 1,
        }
    }
}

/// Circuit breaker state
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CircuitBreakerState {
    Closed,
    Open,
    HalfOpen,
}

/// Route evaluation priority.
///
/// Routes are sorted in descending priority order — higher values are
/// evaluated first. Any `i32` value is accepted; the named constants
/// ([`LOW`](Self::LOW), [`NORMAL`](Self::NORMAL), [`HIGH`](Self::HIGH),
/// [`CRITICAL`](Self::CRITICAL)) exist as conveniences for common cases, but
/// gap-based values like `Priority(500)` are fully supported so routes can be
/// finely ordered between named tiers.
///
/// KDL syntax accepts either an integer (`priority 100`) or one of the named
/// string aliases (`priority "high"`), with the aliases resolving to the
/// matching constant defined below.
///
/// # Examples
///
/// ```
/// use zentinel_common::types::Priority;
///
/// assert!(Priority::HIGH > Priority::NORMAL);
/// assert!(Priority(500) > Priority::HIGH);
/// assert_eq!(Priority::default(), Priority::NORMAL);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Priority(pub i32);

impl Priority {
    /// Low-priority routes (default weight: `10`). Evaluated after normal routes.
    pub const LOW: Self = Self(10);
    /// Normal-priority routes (default weight: `50`). The default for routes
    /// that do not specify an explicit priority.
    pub const NORMAL: Self = Self(50);
    /// High-priority routes (default weight: `100`). Evaluated before normal routes.
    pub const HIGH: Self = Self(100);
    /// Critical-priority routes (default weight: `1000`). Evaluated first; intended
    /// for health checks and other infrastructure-critical routes.
    pub const CRITICAL: Self = Self(1000);

    /// Returns the underlying integer weight.
    #[inline]
    pub const fn as_i32(self) -> i32 {
        self.0
    }
}

impl Default for Priority {
    fn default() -> Self {
        Self::NORMAL
    }
}

impl std::fmt::Display for Priority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<i32> for Priority {
    fn from(value: i32) -> Self {
        Self(value)
    }
}

/// Time window for rate limiting and metrics
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeWindow {
    pub seconds: u64,
}

impl TimeWindow {
    pub fn new(seconds: u64) -> Self {
        Self { seconds }
    }

    pub fn as_duration(&self) -> std::time::Duration {
        std::time::Duration::from_secs(self.seconds)
    }
}

/// Byte size with human-readable serialization
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ByteSize(pub usize);

impl ByteSize {
    pub const KB: usize = 1024;
    pub const MB: usize = 1024 * 1024;
    pub const GB: usize = 1024 * 1024 * 1024;

    pub fn from_kb(kb: usize) -> Self {
        Self(kb * Self::KB)
    }

    pub fn from_mb(mb: usize) -> Self {
        Self(mb * Self::MB)
    }

    pub fn from_gb(gb: usize) -> Self {
        Self(gb * Self::GB)
    }

    pub fn as_bytes(&self) -> usize {
        self.0
    }
}

impl fmt::Display for ByteSize {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.0 >= Self::GB {
            write!(f, "{:.2}GB", self.0 as f64 / Self::GB as f64)
        } else if self.0 >= Self::MB {
            write!(f, "{:.2}MB", self.0 as f64 / Self::MB as f64)
        } else if self.0 >= Self::KB {
            write!(f, "{:.2}KB", self.0 as f64 / Self::KB as f64)
        } else {
            write!(f, "{}B", self.0)
        }
    }
}

impl Serialize for ByteSize {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for ByteSize {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::from_str(&s).map_err(serde::de::Error::custom)
    }
}

impl FromStr for ByteSize {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        if s.is_empty() {
            return Err("Empty byte size string".to_string());
        }

        // Try to parse as plain number (bytes)
        if let Ok(bytes) = s.parse::<usize>() {
            return Ok(Self(bytes));
        }

        // Parse with unit suffix
        let (num_part, unit_part) = s
            .chars()
            .position(|c| c.is_alphabetic())
            .map(|i| s.split_at(i))
            .ok_or_else(|| format!("Invalid byte size format: {}", s))?;

        let value: f64 = num_part
            .trim()
            .parse()
            .map_err(|_| format!("Invalid number: {}", num_part))?;

        let multiplier = match unit_part.to_uppercase().as_str() {
            "B" => 1,
            "KB" | "K" => Self::KB,
            "MB" | "M" => Self::MB,
            "GB" | "G" => Self::GB,
            _ => return Err(format!("Invalid unit: {}", unit_part)),
        };

        Ok(Self((value * multiplier as f64) as usize))
    }
}

/// IP address wrapper with additional metadata
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ClientIp {
    pub address: std::net::IpAddr,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub forwarded_for: Option<Vec<std::net::IpAddr>>,
}

impl fmt::Display for ClientIp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.address)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_http_method_parsing() {
        assert_eq!(HttpMethod::from_str("GET").unwrap(), HttpMethod::GET);
        assert_eq!(HttpMethod::from_str("post").unwrap(), HttpMethod::POST);
        assert_eq!(
            HttpMethod::from_str("PROPFIND").unwrap(),
            HttpMethod::Custom("PROPFIND".to_string())
        );
    }

    #[test]
    fn test_byte_size_parsing() {
        assert_eq!(ByteSize::from_str("1024").unwrap().0, 1024);
        assert_eq!(ByteSize::from_str("10KB").unwrap().0, 10 * 1024);
        assert_eq!(
            ByteSize::from_str("5.5MB").unwrap().0,
            (5.5 * 1024.0 * 1024.0) as usize
        );
        assert_eq!(ByteSize::from_str("2GB").unwrap().0, 2 * 1024 * 1024 * 1024);
        assert_eq!(ByteSize::from_str("100 B").unwrap().0, 100);
    }

    #[test]
    fn test_byte_size_display() {
        assert_eq!(ByteSize(512).to_string(), "512B");
        assert_eq!(ByteSize(2048).to_string(), "2.00KB");
        assert_eq!(ByteSize(1024 * 1024).to_string(), "1.00MB");
        assert_eq!(ByteSize(1024 * 1024 * 1024).to_string(), "1.00GB");
    }

    #[test]
    fn test_trace_id_format() {
        assert_eq!(TraceIdFormat::from_str_loose("uuid"), TraceIdFormat::Uuid);
        assert_eq!(
            TraceIdFormat::from_str_loose("tinyflake"),
            TraceIdFormat::TinyFlake
        );
        assert_eq!(
            TraceIdFormat::from_str_loose("unknown"),
            TraceIdFormat::TinyFlake
        );
    }
}