zentinel-common 0.6.21

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
# Patterns

Circuit breakers, registries, and budget tracking patterns.

## Circuit Breaker

Failure isolation pattern to prevent cascade failures.

### State Machine

```
┌─────────────────────────────────────────────────────────┐
│                  Circuit Breaker FSM                     │
├─────────────────────────────────────────────────────────┤
│                                                          │
│      ┌────────┐                              ┌────────┐ │
│      │ CLOSED │─── failures >= threshold ───▶│  OPEN  │ │
│      │        │                              │        │ │
│      │ Normal │                              │ Reject │ │
│      │ traffic│                              │  all   │ │
│      └────────┘                              └────────┘ │
│          ▲                                       │      │
│          │                              timeout  │      │
│          │                                       ▼      │
│          │                               ┌────────────┐ │
│          │                               │ HALF-OPEN  │ │
│          │                               │   Test     │ │
│          └─── success >= threshold ──────│  traffic   │ │
│                                          └────────────┘ │
│                                                 │       │
│                                   failure ──────┘       │
│                                   (back to OPEN)        │
│                                                          │
└──────────────────────────────────────────────────────────┘
```

### Basic Usage

```rust
use zentinel_common::{CircuitBreaker, CircuitBreakerConfig};

// Configure thresholds
let config = CircuitBreakerConfig {
    failure_threshold: 5,      // Open after 5 failures
    success_threshold: 2,      // Close after 2 successes
    timeout_seconds: 30,       // Wait 30s before half-open
    half_open_max_requests: 1, // Allow 1 request in half-open
};

let breaker = CircuitBreaker::new(config);
```

### Request Flow

```rust
async fn call_upstream(breaker: &CircuitBreaker) -> Result<Response, Error> {
    // Check if circuit is closed (requests allowed)
    if !breaker.is_closed() {
        return Err(Error::CircuitOpen);
    }

    // Make the call
    match upstream_request().await {
        Ok(response) => {
            breaker.record_success();
            Ok(response)
        }
        Err(e) => {
            breaker.record_failure();
            Err(e)
        }
    }
}
```

### State Inspection

```rust
use zentinel_common::CircuitBreakerState;

// Get current state
match breaker.state() {
    CircuitBreakerState::Closed => println!("Normal operation"),
    CircuitBreakerState::Open => println!("Circuit open, rejecting"),
    CircuitBreakerState::HalfOpen => println!("Testing recovery"),
}

// Get counters
let failures = breaker.consecutive_failures();
let successes = breaker.consecutive_successes();

// Manual reset
breaker.reset();
```

### Named Circuit Breakers

```rust
// Create with name for logging
let breaker = CircuitBreaker::with_name(config, "payment-gateway");
```

## Registry

Generic thread-safe component storage.

### Basic Usage

```rust
use zentinel_common::Registry;

// Create registry
let routes: Registry<Route> = Registry::new();

// Or with initial capacity
let routes: Registry<Route> = Registry::with_capacity(100);
```

### Operations

```rust
// Insert item
routes.insert("api-v1".to_string(), Arc::new(route)).await;

// Get item
if let Some(route) = routes.get("api-v1").await {
    // Use route
}

// Check existence
if routes.contains("api-v1").await {
    // Route exists
}

// Remove item
let removed = routes.remove("api-v1").await;

// Get all keys
let keys = routes.keys().await;

// Get count
let count = routes.len().await;
```

### Atomic Replacement (Hot Reload)

```rust
// Build new configuration
let mut new_routes = HashMap::new();
new_routes.insert("api-v1".to_string(), Arc::new(new_route));
new_routes.insert("api-v2".to_string(), Arc::new(new_route_v2));

// Atomic swap - returns old routes
let old_routes = routes.replace(new_routes).await;

// Old routes continue serving in-flight requests
// New routes used for new requests
```

### Snapshot

```rust
// Get a point-in-time snapshot
let snapshot = routes.snapshot().await;

// Iterate over snapshot
for (id, route) in &snapshot {
    println!("{}: {:?}", id, route);
}
```

### Custom Operations

```rust
// Execute with read lock
routes.with_read(|map| {
    // Read-only access to internal map
    map.len()
}).await;

// Execute with write lock
routes.with_write(|map| {
    // Mutable access to internal map
    map.retain(|k, _| k.starts_with("api-"));
}).await;
```

## ScopedRegistry

Hierarchical registry with scope-based resolution.

### Setup

```rust
use zentinel_common::{ScopedRegistry, QualifiedId, Scope};

let registry: ScopedRegistry<Policy> = ScopedRegistry::new();
```

### Inserting Items

```rust
// Insert at global scope
registry.insert(
    QualifiedId::global("default-timeout"),
    Arc::new(Policy::timeout(30000)),
).await;

// Insert at namespace scope
registry.insert(
    QualifiedId::namespaced("production", "timeout"),
    Arc::new(Policy::timeout(10000)),
).await;

// Insert at service scope
registry.insert(
    QualifiedId::in_service("production", "payments", "timeout"),
    Arc::new(Policy::timeout(5000)),
).await;

// Insert and export (visible from all scopes)
registry.insert_exported(
    QualifiedId::namespaced("production", "shared-auth"),
    Arc::new(Policy::auth()),
).await;
```

### Resolution

```rust
// Resolve from service scope
let scope = Scope::Service {
    namespace: "production".to_string(),
    service: "payments".to_string(),
};

// Finds "production:payments:timeout" (5000ms)
let policy = registry.resolve("timeout", &scope).await;

// Resolution chain:
// 1. production:payments:timeout (found!)
// 2. production:timeout
// 3. Exported names
// 4. timeout (global)
```

### Direct Lookup

```rust
// By canonical ID
let policy = registry.get_by_canonical("production:payments:timeout").await;

// By QualifiedId
let qid = QualifiedId::in_service("production", "payments", "timeout");
let policy = registry.get(&qid).await;
```

## Token Budgets

Usage limits for inference endpoints.

### Configuration

```rust
use zentinel_common::{TokenBudgetConfig, BudgetPeriod};

let config = TokenBudgetConfig {
    period: BudgetPeriod::Daily,
    limit: 1_000_000,                      // 1M tokens/day
    alert_thresholds: vec![0.80, 0.90, 0.95],
    enforce: true,                         // Block when exhausted
    rollover: false,                       // No rollover
    burst_allowance: Some(0.10),          // 10% burst allowed
};
```

### Budget Periods

```rust
use zentinel_common::BudgetPeriod;

// Predefined periods
let hourly = BudgetPeriod::Hourly;   // Resets every hour
let daily = BudgetPeriod::Daily;     // Resets at midnight UTC
let monthly = BudgetPeriod::Monthly; // Resets on 1st

// Custom period
let custom = BudgetPeriod::Custom { seconds: 3600 * 4 }; // 4 hours

// Get duration
let duration = daily.as_duration(); // 86400 seconds
```

### Checking Budget

```rust
use zentinel_common::BudgetCheckResult;

match tracker.check(estimated_tokens) {
    BudgetCheckResult::Allowed { remaining } => {
        println!("Allowed, {} tokens remaining", remaining);
    }
    BudgetCheckResult::Exhausted { retry_after_secs } => {
        println!("Budget exhausted, retry after {}s", retry_after_secs);
    }
    BudgetCheckResult::Soft { remaining, over_by } => {
        println!("Allowed via burst, {} over limit", over_by);
    }
}

// Check if allowed
if result.is_allowed() {
    // Process request
}
```

### Budget Status

```rust
use zentinel_common::TenantBudgetStatus;

let status = tracker.status();
println!("Used: {} / {}", status.tokens_used, status.tokens_limit);
println!("Remaining: {}", status.tokens_remaining);
println!("Usage: {:.1}%", status.usage_percent * 100.0);
println!("Exhausted: {}", status.exhausted);
println!("Period: {} to {}", status.period_start, status.period_end);
```

### Alerts

```rust
use zentinel_common::BudgetAlert;

// Alerts triggered when thresholds crossed
fn handle_alert(alert: BudgetAlert) {
    println!(
        "Budget alert for {}: {:.0}% used ({}/{})",
        alert.tenant,
        alert.usage_percent() * 100.0,
        alert.tokens_used,
        alert.tokens_limit,
    );
}
```

## Cost Attribution

Track costs for inference requests.

### Configuration

```rust
use zentinel_common::{CostAttributionConfig, ModelPricing};

let config = CostAttributionConfig {
    enabled: true,
    pricing: vec![
        ModelPricing {
            model_pattern: "gpt-4*".to_string(),
            input_cost_per_million: 30.0,
            output_cost_per_million: 60.0,
            currency: None, // Use default
        },
        ModelPricing {
            model_pattern: "gpt-3.5-turbo*".to_string(),
            input_cost_per_million: 0.5,
            output_cost_per_million: 1.5,
            currency: None,
        },
    ],
    default_input_cost: 1.0,
    default_output_cost: 2.0,
    currency: "USD".to_string(),
};
```

### Pattern Matching

```rust
let pricing = ModelPricing {
    model_pattern: "gpt-4*".to_string(),
    input_cost_per_million: 30.0,
    output_cost_per_million: 60.0,
    currency: None,
};

// Pattern matching
assert!(pricing.matches("gpt-4"));
assert!(pricing.matches("gpt-4-turbo"));
assert!(pricing.matches("gpt-4-0125-preview"));
assert!(!pricing.matches("gpt-3.5-turbo"));
```

### Cost Calculation

```rust
use zentinel_common::CostResult;

// Calculate cost
let cost = pricing.calculate_cost(1000, 500);
// Input: 1000 tokens * $30/M = $0.03
// Output: 500 tokens * $60/M = $0.03
// Total: $0.06

let result = CostResult::new(
    "gpt-4".to_string(),
    1000,  // input tokens
    500,   // output tokens
    0.03,  // input cost
    0.03,  // output cost
    "USD".to_string(),
);

println!("Total: ${:.4} {}", result.total_cost, result.currency);
```

## Inference Health Checks

Advanced health checks for LLM backends.

### Inference Probe

Send minimal completion request:

```rust
use zentinel_common::InferenceProbeConfig;

let config = InferenceProbeConfig {
    endpoint: "/v1/completions".to_string(),
    model: "gpt-3.5-turbo".to_string(),
    prompt: ".".to_string(),
    max_tokens: 1,
    timeout_secs: 30,
    max_latency_ms: Some(5000), // Mark unhealthy if > 5s
};
```

### Model Status

Query provider status endpoints:

```rust
use zentinel_common::ModelStatusConfig;

let config = ModelStatusConfig {
    endpoint_pattern: "/v1/models/{model}/status".to_string(),
    models: vec!["gpt-4".to_string(), "gpt-3.5-turbo".to_string()],
    expected_status: "ready".to_string(),
    status_field: "status".to_string(),
    timeout_secs: 30,
};
```

### Queue Depth

Monitor backend queue depth:

```rust
use zentinel_common::QueueDepthConfig;

let config = QueueDepthConfig {
    header: Some("X-Queue-Depth".to_string()),
    body_field: None,
    endpoint: None,
    degraded_threshold: 100,   // Mark degraded if > 100
    unhealthy_threshold: 500,  // Mark unhealthy if > 500
    timeout_secs: 30,
};
```

### Warmth Detection

Detect cold models:

```rust
use zentinel_common::{WarmthDetectionConfig, ColdModelAction};

let config = WarmthDetectionConfig {
    sample_size: 10,
    cold_threshold_multiplier: 2.0,  // 2x baseline = cold
    idle_cold_timeout_secs: 300,     // Cold after 5min idle
    cold_action: ColdModelAction::MarkDegraded,
};
```

**Cold Model Actions:**
- `LogOnly` - Just log (default)
- `MarkDegraded` - Lower weight in LB
- `MarkUnhealthy` - Exclude until warmed