zentinel-proxy 0.6.11

A security-first reverse proxy built on Pingora with sleepable ops at the edge
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
# Module Reference

Comprehensive documentation for all modules in the Zentinel proxy crate.

## Core Modules

### `proxy`

The main proxy implementation using Pingora's `ProxyHttp` trait.

**Sub-modules:**
- `context` - Request context maintained throughout lifecycle
- `fallback` - Fallback handling when upstreams fail
- `handlers` - HTTP request handlers
- `http_trait` - `ProxyHttp` trait implementation
- `model_routing` - Model-based routing for inference

**Key Struct:** `ZentinelProxy`

```rust
pub struct ZentinelProxy {
    config_manager: Arc<ConfigManager>,
    route_matcher: Arc<RouteMatcher>,
    upstream_pool: Arc<UpstreamPool>,
    agent_manager: Arc<AgentManager>,
    rate_limit_manager: Arc<RateLimitManager>,
    cache_manager: Arc<CacheManager>,
    log_manager: Arc<LogManager>,
    // ...
}
```

### `app`

Application entry point and server lifecycle management.

**Key Struct:** `ZentinelApp`

```rust
impl ZentinelApp {
    pub fn new(config: Config) -> Result<Self, Error>;
    pub async fn run(self) -> Result<(), Error>;
    pub fn shutdown(&self);
}
```

### `routing`

Route matching with multiple match conditions.

**Match Types:**
- `Path` - Exact path match
- `PathPrefix` - Path prefix match
- `PathRegex` - Regex pattern match
- `Host` - Exact or wildcard host match
- `Header` - Header presence or value match
- `Method` - HTTP method match
- `QueryParam` - Query parameter match

**Key Struct:** `RouteMatcher`

```rust
impl RouteMatcher {
    pub fn match_request(&self, req: &Request) -> Option<&Route>;
    pub fn route_by_id(&self, id: &str) -> Option<&Route>;
    pub fn cache_stats(&self) -> CacheStats;
}
```

### `scoped_routing`

Scope-aware route matching for multi-tenant deployments.

**Visibility Rules:**
- Global routes: Visible from all scopes
- Namespace routes: Visible from that namespace and its services
- Service routes: Only visible from that service

**Key Struct:** `ScopedRouteMatcher`

```rust
impl ScopedRouteMatcher {
    pub fn match_request(&self, req: &Request, scope: &Scope) -> Option<&Route>;
    pub fn load_from_flattened(&mut self, config: &FlattenedConfig);
}
```

---

## Upstream Management

### `upstream`

Load balancing and upstream pool management.

**Sub-modules:**
- `p2c` - Power of Two Choices algorithm
- `least_tokens` - Token-aware load balancing
- `consistent_hash` - Consistent hashing for sticky sessions
- `adaptive` - Latency-weighted adaptive balancing
- `health` - Health checking integration
- `inference_health` - Inference-specific health checks

**Load Balancing Algorithms:**

| Algorithm | Description | Use Case |
|-----------|-------------|----------|
| `P2cBalancer` | Power of Two Choices | General purpose (default) |
| `LeastTokensQueuedBalancer` | Least queued tokens | LLM inference endpoints |
| `ConsistentHashBalancer` | Consistent hashing | Session affinity |
| `AdaptiveBalancer` | Latency-weighted | Mixed workloads |

**Key Struct:** `UpstreamPool`

```rust
impl UpstreamPool {
    pub fn select(&self, ctx: &RequestContext) -> Result<TargetSelection, Error>;
    pub fn report_health(&self, target: &Target, healthy: bool);
    pub fn healthy_targets(&self) -> Vec<&Target>;
    pub fn report_result(&self, target: &Target, result: &RequestResult);
}
```

### `health`

Active and passive health checking.

**Check Types:**
- `Http` - GET request with expected status
- `Tcp` - TCP connection attempt
- `Grpc` - gRPC health check
- `Inference` - Query `/v1/models` endpoint
- `InferenceProbe` - Send minimal completion request
- `ModelStatus` - Provider-specific status endpoints
- `QueueDepth` - Monitor queue depth

**Key Structs:**

```rust
pub struct ActiveHealthChecker {
    pub fn check(&self, target: &Target) -> HealthStatus;
}

pub struct PassiveHealthChecker {
    pub fn record_success(&self, target: &Target);
    pub fn record_failure(&self, target: &Target);
    pub fn is_healthy(&self, target: &Target) -> bool;
}
```

**Configuration:**

```kdl
upstream "api" {
    health-check {
        type "http"
        path "/health"
        interval-secs 10
        timeout-secs 5
        healthy-threshold 2
        unhealthy-threshold 3
        expected-status 200
    }
}
```

---

## Rate Limiting

### `rate_limit`

Local token bucket rate limiting.

**Key Struct:** `RateLimitManager`

```rust
impl RateLimitManager {
    pub fn register_route(&self, route_id: &str, config: &RateLimitConfig);
    pub fn check(&self, route_id: &str, key: &str) -> RateLimitOutcome;
    pub fn cleanup(&self);  // Remove idle limiters
}

pub enum RateLimitOutcome {
    Allowed,
    Limited,
}
```

### `distributed_rate_limit`

Redis-backed distributed rate limiting using sliding window.

**Algorithm:**
1. Store timestamp in Redis sorted set
2. Remove timestamps older than window
3. Count remaining timestamps
4. Allow if count <= max_rps

**Key Struct:** `RedisRateLimiter`

```rust
impl RedisRateLimiter {
    pub async fn check(&self, key: &str, max_rps: u32) -> RateLimitOutcome;
}
```

**Requires Feature:** `distributed-rate-limit`

### `memcached_rate_limit`

Memcached-backed fixed window rate limiting.

**Key Struct:** `MemcachedRateLimiter`

**Requires Feature:** `distributed-rate-limit-memcached`

### `scoped_rate_limit`

Scope-aware rate limiting with inheritance.

**Key Struct:** `ScopedRateLimitManager`

```rust
impl ScopedRateLimitManager {
    pub fn set_scope_limits(&self, scope: &Scope, limits: &RateLimitConfig);
    pub fn register_route(&self, route_id: &str, scope: &Scope, config: &RateLimitConfig);
    pub fn check(&self, route_id: &str, scope: &Scope, key: &str) -> RateLimitOutcome;
}
```

---

## Circuit Breakers

### `scoped_circuit_breaker`

Scope-aware circuit breakers for failure isolation.

**States:**
- `Closed` - Normal operation
- `Open` - Fast-fail after threshold
- `HalfOpen` - Testing if service recovered

**Key Struct:** `ScopedCircuitBreakerManager`

```rust
impl ScopedCircuitBreakerManager {
    pub fn set_scope_config(&self, scope: &Scope, config: &CircuitBreakerConfig);
    pub fn get_breaker(&self, scope: &Scope, upstream: &str) -> CircuitBreaker;
    pub fn record_success(&self, scope: &Scope, upstream: &str);
    pub fn record_failure(&self, scope: &Scope, upstream: &str);
}
```

**Configuration:**

```kdl
scope "namespace/service" {
    circuit-breaker {
        failure-threshold 5
        success-threshold 2
        timeout-secs 30
    }
}
```

---

## Caching

### `cache`

HTTP response caching using Pingora's cache infrastructure.

**Key Struct:** `CacheManager`

```rust
impl CacheManager {
    pub fn configure_cache(&self, config: &CacheConfig);
    pub fn is_cache_enabled(&self, route_id: &str) -> bool;
    pub fn is_path_cacheable(&self, route_id: &str, path: &str) -> bool;
    pub fn register_route(&self, route_id: &str, config: &RouteCacheConfig);
}
```

**Features:**
- Per-route cache configuration
- Cache-Control header parsing
- TTL calculation with defaults
- Stale-while-revalidate support
- Stale-if-error support
- Path and extension-based cache exclusions (`exclude-extensions`, `exclude-paths`)

### `memory_cache`

Fast in-memory caching with S3-FIFO + TinyLFU eviction.

**Key Struct:** `MemoryCacheManager`

```rust
impl MemoryCacheManager {
    pub fn get<K, V>(&self, key: &K) -> Option<V>;
    pub fn insert<K, V>(&self, key: K, value: V);
    pub fn stats(&self) -> CacheStats;
}
```

**Configuration:**

```rust
MemoryCacheConfig {
    max_items: 10_000,
    default_ttl: Duration::from_secs(60),
    enable_stats: true,
}
```

---

## Static Files

### `static_files`

Static file serving with compression and caching.

**Sub-modules:**
- `cache` - File caching with pre-computed compression
- `compression` - Content encoding negotiation
- `range` - HTTP Range request handling

**Key Struct:** `StaticFileServer`

```rust
impl StaticFileServer {
    pub async fn serve(&self, path: &Path, req: &Request) -> Response;
    pub fn clear_cache(&self);
    pub fn cache_stats(&self) -> CacheStats;
}
```

**Features:**
- Range requests (206 Partial Content)
- Zero-copy with mmap (files > 10MB)
- On-the-fly gzip/brotli compression
- In-memory cache (files < 1MB)
- Directory listing
- SPA fallback routing

**Configuration:**

```kdl
route "/static" {
    service-type "static"
    static-files {
        root "/var/www/static"
        index "index.html"
        fallback "index.html"
        cache-control "public, max-age=3600"
        compress true
    }
}
```

---

## WebSocket

### `websocket`

WebSocket frame-level handling per RFC 6455.

**Sub-modules:**
- `codec` - Frame parsing/encoding
- `inspector` - Frame inspection logic
- `proxy` - WebSocket proxying

**Key Structs:**

```rust
pub struct WebSocketFrame {
    pub opcode: Opcode,
    pub fin: bool,
    pub payload: Bytes,
}

pub struct WebSocketHandler {
    pub async fn proxy(&self, client: &mut Stream, upstream: &mut Stream);
}

pub struct WebSocketInspector {
    pub fn inspect(&self, frame: &WebSocketFrame) -> InspectionResult;
}
```

**Configuration:**

```kdl
route "/ws" {
    upstream "websocket-backend"
    websocket true
    websocket-inspection false
}
```

---

## Traffic Management

### `shadow`

Fire-and-forget request mirroring for canary testing.

**Key Struct:** `ShadowManager`

```rust
impl ShadowManager {
    pub fn should_shadow(&self, route: &Route) -> bool;
    pub async fn shadow_request(&self, req: Request, config: &ShadowConfig);
}
```

**Configuration:**

```kdl
route "/api" {
    shadow {
        upstream "canary-pool"
        percentage 10.0
        sample-header "X-Shadow" "true"
        buffer-body true
    }
}
```

### `discovery`

Service discovery backends.

**Discovery Methods:**
- `Static` - Fixed list of backends
- `Dns` - A/AAAA record resolution
- `DnsSrv` - SRV record resolution
- `Consul` - Consul service catalog
- `Kubernetes` - Kubernetes endpoints
- `File` - Watch config file

**Key Struct:** `DiscoveryManager`

```rust
impl DiscoveryManager {
    pub async fn get_backends(&self, upstream: &str) -> Vec<Backend>;
    pub async fn refresh(&self, upstream: &str);
}
```

**Configuration:**

```kdl
upstream "api" {
    discovery "kubernetes" {
        namespace "default"
        service "my-service"
        port-name "http"
        refresh-interval 10
    }
}
```

---

## Security

### `tls`

TLS termination and certificate management.

**Features:**
- SNI-based certificate selection
- Wildcard certificate matching
- mTLS client verification
- Certificate hot-reload
- OCSP stapling

**Key Structs:**

```rust
pub struct SniResolver {
    pub fn resolve(&self, server_name: &str) -> Option<&CertifiedKey>;
}

pub struct HotReloadableSniResolver {
    pub fn reload(&self) -> Result<(), Error>;
}
```

**Configuration:**

```kdl
listener "https" {
    tls {
        cert-file "/etc/certs/default.crt"
        key-file "/etc/certs/default.key"
        min-version "tls1.2"

        sni "api.example.com" "*.api.example.com" {
            cert-file "/etc/certs/api.crt"
            key-file "/etc/certs/api.key"
        }

        client-auth true
        ca-file "/etc/certs/ca.crt"
        ocsp-stapling true
    }
}
```

### `geo_filter`

GeoIP-based request filtering.

**Database Backends:**
- MaxMind (GeoLite2/GeoIP2)
- IP2Location

**Key Struct:** `GeoFilterManager`

```rust
impl GeoFilterManager {
    pub fn register_filter(&self, id: &str, config: &GeoFilterConfig);
    pub fn check(&self, filter_id: &str, ip: IpAddr) -> GeoFilterResult;
    pub fn clear_expired_caches(&self);
}

pub enum GeoFilterResult {
    Allowed,
    Blocked { country: String },
    Error,
}
```

**Configuration:**

```kdl
filter "geo-block" {
    type "geo"
    database-path "/var/lib/GeoLite2-Country.mmdb"
    database-type "maxmind"
    action "block"
    countries ["CN", "RU", "KP"]
    fail-mode "open"
    cache-ttl 3600
}
```

### `decompression`

Safe decompression with zip bomb protection.

**Supported Encodings:**
- gzip
- deflate
- brotli

**Key Function:**

```rust
pub fn decompress_body(
    body: &[u8],
    encoding: ContentEncoding,
    config: &DecompressionConfig,
) -> Result<Vec<u8>, DecompressionError>;
```

**Protection:**

```rust
DecompressionConfig {
    max_ratio: 100.0,    // Max expansion ratio
    max_output_bytes: 10 * 1024 * 1024,  // 10MB limit
}
```

---

## Observability

### `logging`

Structured logging for access, errors, and audit.

**Log Types:**
- Access logs - Request/response with trace ID
- Error logs - Errors and warnings
- Audit logs - Security events

**Log Formats:**
- `Json` - Structured JSON
- `Combined` - Apache/nginx combined format

**Key Struct:** `LogManager`

```rust
impl LogManager {
    pub fn write_access_log(&self, entry: &AccessLogEntry);
    pub fn write_error_log(&self, entry: &ErrorLogEntry);
    pub fn write_audit_log(&self, entry: &AuditLogEntry);
}
```

### `otel`

OpenTelemetry integration for distributed tracing.

**Features:**
- W3C Trace Context propagation
- OTLP export (Jaeger, Tempo, etc.)
- Configurable sampling rates

**Headers:**
- `traceparent` - W3C trace context
- `tracestate` - Vendor-specific state

**Requires Feature:** `opentelemetry`

### `trace_id`

Trace ID generation and propagation.

**Formats:**
- `TinyFlake` - 11-character high-precision IDs (default)
- `UUID` - Standard UUID v4

**Header Priority:**
1. `X-Trace-Id`
2. `X-Correlation-Id`
3. `X-Request-Id`
4. Auto-generate if missing

---

## Error Handling

### `errors`

Error response generation.

**Key Struct:** `ErrorHandler`

```rust
impl ErrorHandler {
    pub fn generate_response(
        &self,
        status: StatusCode,
        service_type: ServiceType,
        accept: &str,
    ) -> Response;
}
```

**Response Formats:**
- JSON for API routes
- HTML for web routes
- Text for others

### `validation`

Request/response schema validation.

**Key Struct:** `SchemaValidator`

```rust
impl SchemaValidator {
    pub fn validate_request(&self, req: &Request, schema: &JsonSchema) -> ValidationResult;
    pub fn validate_response(&self, resp: &Response, schema: &JsonSchema) -> ValidationResult;
}
```

---

## Hot Reload

### `reload`

Configuration hot reload with graceful transition.

**Sub-modules:**
- `coordinator` - Graceful reload coordination
- `signals` - OS signal handling (SIGHUP, SIGTERM)
- `validators` - Configuration validators

**Key Struct:** `ConfigManager`

```rust
impl ConfigManager {
    pub async fn reload(&self) -> Result<(), ReloadError>;
    pub fn subscribe(&self) -> Receiver<ReloadEvent>;
    pub fn validate(&self, config: &Config) -> Result<(), ValidationError>;
}
```

**Reload Triggers:**
- `Manual` - API trigger
- `FileChange` - File modification
- `Signal` - SIGHUP received
- `Scheduled` - Periodic reload

---

## Built-in Handlers

### `builtin_handlers`

Built-in endpoints for operations.

**Endpoints:**
- `/status` - Service status (version, uptime)
- `/health` - Health check
- `/metrics` - Prometheus metrics
- `/upstreams` - Upstream health status
- `/config` - Current configuration

**Key Struct:** `BuiltinHandlerState`

```rust
impl BuiltinHandlerState {
    pub fn uptime_string(&self) -> String;
}
```

---

## Utilities

### `http_helpers`

HTTP request/response utilities.

**Key Functions:**

```rust
pub fn extract_request_info(req: &Request) -> RequestInfo;
pub fn get_or_create_trace_id(headers: &HeaderMap) -> String;
pub fn write_response(resp: Response, downstream: &mut Session);
pub fn write_json_error(status: StatusCode, message: &str) -> Response;
```

### `grpc_health`

gRPC health check protocol implementation.

```rust
impl GrpcHealthService {
    pub fn check(&self, service: &str) -> HealthCheckResponse;
    pub fn watch(&self, service: &str) -> Stream<HealthCheckResponse>;
}
```