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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Built-in handlers for Zentinel proxy
//!
//! These handlers provide default responses for common endpoints like
//! status pages, health checks, and metrics. They are used when routes
//! are configured with `service-type: builtin`.

use bytes::Bytes;
use http::{Response, StatusCode};
use http_body_util::Full;
use serde::Serialize;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{debug, info, trace};

use zentinel_config::{BuiltinHandler, Config};

use crate::cache::{CacheManager, HttpCacheStats};

/// Application state for builtin handlers
pub struct BuiltinHandlerState {
    /// Application start time
    start_time: Instant,
    /// Application version
    version: String,
    /// Instance ID
    instance_id: String,
}

impl BuiltinHandlerState {
    /// Create new handler state
    pub fn new(version: String, instance_id: String) -> Self {
        Self {
            start_time: Instant::now(),
            version,
            instance_id,
        }
    }

    /// Get uptime as a Duration
    pub fn uptime(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Format uptime as human-readable string
    pub fn uptime_string(&self) -> String {
        let uptime = self.uptime();
        let secs = uptime.as_secs();
        let days = secs / 86400;
        let hours = (secs % 86400) / 3600;
        let mins = (secs % 3600) / 60;
        let secs = secs % 60;

        if days > 0 {
            format!("{}d {}h {}m {}s", days, hours, mins, secs)
        } else if hours > 0 {
            format!("{}h {}m {}s", hours, mins, secs)
        } else if mins > 0 {
            format!("{}m {}s", mins, secs)
        } else {
            format!("{}s", secs)
        }
    }
}

/// Status response payload
#[derive(Debug, Serialize)]
pub struct StatusResponse {
    /// Service status
    pub status: &'static str,
    /// Service version
    pub version: String,
    /// Service uptime
    pub uptime: String,
    /// Uptime in seconds
    pub uptime_secs: u64,
    /// Instance identifier
    pub instance_id: String,
    /// Timestamp
    pub timestamp: String,
}

/// Health check response
#[derive(Debug, Serialize)]
pub struct HealthResponse {
    /// Health status
    pub status: &'static str,
    /// Timestamp
    pub timestamp: String,
}

/// Upstream health snapshot for the upstreams handler
#[derive(Debug, Clone, Default)]
pub struct UpstreamHealthSnapshot {
    /// Health status per upstream, keyed by upstream ID
    pub upstreams: HashMap<String, UpstreamStatus>,
}

/// Status of a single upstream
#[derive(Debug, Clone, Serialize)]
pub struct UpstreamStatus {
    /// Upstream ID
    pub id: String,
    /// Load balancing algorithm
    pub load_balancing: String,
    /// Target statuses
    pub targets: Vec<TargetStatus>,
}

/// Status of a single target within an upstream
#[derive(Debug, Clone, Serialize)]
pub struct TargetStatus {
    /// Target address
    pub address: String,
    /// Weight
    pub weight: u32,
    /// Health status
    pub status: TargetHealthStatus,
    /// Failure rate (0.0 - 1.0)
    pub failure_rate: Option<f64>,
    /// Last error message if unhealthy
    pub last_error: Option<String>,
}

/// Health status of a target
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TargetHealthStatus {
    /// Target is healthy
    Healthy,
    /// Target is unhealthy
    Unhealthy,
    /// Health status unknown (no checks yet)
    Unknown,
}

/// Cache purge request details
#[derive(Debug, Clone)]
pub struct CachePurgeRequest {
    /// Pattern to purge (URL path or wildcard pattern)
    pub pattern: String,
    /// Whether this is a wildcard purge (purge all matching pattern)
    pub wildcard: bool,
}

/// Execute a builtin handler
pub fn execute_handler(
    handler: BuiltinHandler,
    state: &BuiltinHandlerState,
    request_id: &str,
    config: Option<Arc<Config>>,
    upstreams: Option<UpstreamHealthSnapshot>,
    cache_stats: Option<Arc<HttpCacheStats>>,
    cache_purge: Option<CachePurgeRequest>,
    cache_manager: Option<&Arc<CacheManager>>,
) -> Response<Full<Bytes>> {
    trace!(
        handler = ?handler,
        request_id = %request_id,
        "Executing builtin handler"
    );

    let response = match handler {
        BuiltinHandler::Status => status_handler(state, request_id),
        BuiltinHandler::Health => health_handler(request_id),
        BuiltinHandler::Metrics => metrics_handler(request_id, cache_stats.as_ref()),
        BuiltinHandler::NotFound => not_found_handler(request_id),
        BuiltinHandler::Config => config_handler(config, request_id),
        BuiltinHandler::Upstreams => upstreams_handler(upstreams, request_id),
        BuiltinHandler::CachePurge => cache_purge_handler(cache_purge, cache_manager, request_id),
        BuiltinHandler::CacheStats => cache_stats_handler(cache_stats, request_id),
    };

    debug!(
        handler = ?handler,
        request_id = %request_id,
        status = response.status().as_u16(),
        "Builtin handler completed"
    );

    response
}

/// JSON status page handler
fn status_handler(state: &BuiltinHandlerState, request_id: &str) -> Response<Full<Bytes>> {
    trace!(
        request_id = %request_id,
        uptime_secs = state.uptime().as_secs(),
        "Generating status response"
    );

    let response = StatusResponse {
        status: "ok",
        version: state.version.clone(),
        uptime: state.uptime_string(),
        uptime_secs: state.uptime().as_secs(),
        instance_id: state.instance_id.clone(),
        timestamp: chrono::Utc::now().to_rfc3339(),
    };

    let body =
        serde_json::to_vec_pretty(&response).unwrap_or_else(|_| b"{\"status\":\"ok\"}".to_vec());

    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "application/json; charset=utf-8")
        .header("X-Request-Id", request_id)
        .header("Cache-Control", "no-cache, no-store, must-revalidate")
        .body(Full::new(Bytes::from(body)))
        .expect("static response builder with valid headers cannot fail")
}

/// Health check handler
fn health_handler(request_id: &str) -> Response<Full<Bytes>> {
    let response = HealthResponse {
        status: "healthy",
        timestamp: chrono::Utc::now().to_rfc3339(),
    };

    let body =
        serde_json::to_vec(&response).unwrap_or_else(|_| b"{\"status\":\"healthy\"}".to_vec());

    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "application/json; charset=utf-8")
        .header("X-Request-Id", request_id)
        .header("Cache-Control", "no-cache, no-store, must-revalidate")
        .body(Full::new(Bytes::from(body)))
        .expect("static response builder with valid headers cannot fail")
}

/// Prometheus metrics handler
fn metrics_handler(
    request_id: &str,
    cache_stats: Option<&Arc<HttpCacheStats>>,
) -> Response<Full<Bytes>> {
    use prometheus::{Encoder, TextEncoder};

    // Create encoder for Prometheus text format
    let encoder = TextEncoder::new();

    // Gather all metrics from the default registry
    let metric_families = prometheus::gather();

    // Encode metrics to text format
    let mut buffer = Vec::new();
    match encoder.encode(&metric_families, &mut buffer) {
        Ok(()) => {
            // Add zentinel_up and build_info metrics
            let extra_metrics = format!(
                "# HELP zentinel_up Zentinel proxy is up and running\n\
                 # TYPE zentinel_up gauge\n\
                 zentinel_up 1\n\
                 # HELP zentinel_build_info Build information\n\
                 # TYPE zentinel_build_info gauge\n\
                 zentinel_build_info{{version=\"{}\"}} 1\n",
                env!("CARGO_PKG_VERSION")
            );
            buffer.extend_from_slice(extra_metrics.as_bytes());

            // Add HTTP cache metrics if available
            if let Some(stats) = cache_stats {
                let cache_metrics = format!(
                    "# HELP zentinel_cache_hits_total Total number of cache hits\n\
                     # TYPE zentinel_cache_hits_total counter\n\
                     zentinel_cache_hits_total {}\n\
                     # HELP zentinel_cache_misses_total Total number of cache misses\n\
                     # TYPE zentinel_cache_misses_total counter\n\
                     zentinel_cache_misses_total {}\n\
                     # HELP zentinel_cache_stores_total Total number of cache stores\n\
                     # TYPE zentinel_cache_stores_total counter\n\
                     zentinel_cache_stores_total {}\n\
                     # HELP zentinel_cache_hit_ratio Cache hit ratio (0.0 to 1.0)\n\
                     # TYPE zentinel_cache_hit_ratio gauge\n\
                     zentinel_cache_hit_ratio {:.4}\n\
                     # HELP zentinel_cache_memory_hits_total Cache hits from memory tier\n\
                     # TYPE zentinel_cache_memory_hits_total counter\n\
                     zentinel_cache_memory_hits_total {}\n\
                     # HELP zentinel_cache_disk_hits_total Cache hits from disk tier\n\
                     # TYPE zentinel_cache_disk_hits_total counter\n\
                     zentinel_cache_disk_hits_total {}\n",
                    stats.hits(),
                    stats.misses(),
                    stats.stores(),
                    stats.hit_ratio(),
                    stats.memory_hits(),
                    stats.disk_hits()
                );
                buffer.extend_from_slice(cache_metrics.as_bytes());
            }

            Response::builder()
                .status(StatusCode::OK)
                .header("Content-Type", encoder.format_type())
                .header("X-Request-Id", request_id)
                .body(Full::new(Bytes::from(buffer)))
                .expect("static response builder with valid headers cannot fail")
        }
        Err(e) => {
            tracing::error!(error = %e, "Failed to encode Prometheus metrics");
            let error_body = format!("# ERROR: Failed to encode metrics: {}\n", e);
            Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .header("Content-Type", "text/plain; charset=utf-8")
                .header("X-Request-Id", request_id)
                .body(Full::new(Bytes::from(error_body)))
                .expect("static response builder with valid headers cannot fail")
        }
    }
}

/// 404 Not Found handler
fn not_found_handler(request_id: &str) -> Response<Full<Bytes>> {
    let body = serde_json::json!({
        "error": "Not Found",
        "status": 404,
        "message": "The requested resource could not be found.",
        "request_id": request_id,
        "timestamp": chrono::Utc::now().to_rfc3339(),
    });

    let body_bytes = serde_json::to_vec_pretty(&body)
        .unwrap_or_else(|_| b"{\"error\":\"Not Found\",\"status\":404}".to_vec());

    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .header("Content-Type", "application/json; charset=utf-8")
        .header("X-Request-Id", request_id)
        .body(Full::new(Bytes::from(body_bytes)))
        .expect("static response builder with valid headers cannot fail")
}

/// Configuration dump handler
///
/// Returns the current running configuration as JSON. Sensitive fields like
/// TLS private keys are redacted for security.
fn config_handler(config: Option<Arc<Config>>, request_id: &str) -> Response<Full<Bytes>> {
    let body = match &config {
        Some(cfg) => {
            // Build a response with configuration details
            // The Config struct derives Serialize, so we can serialize directly
            // Note: sensitive fields should be redacted in production
            let response = serde_json::json!({
                "timestamp": chrono::Utc::now().to_rfc3339(),
                "request_id": request_id,
                "config": {
                    "server": &cfg.server,
                    "listeners": cfg.listeners.iter().map(|l| {
                        serde_json::json!({
                            "id": l.id,
                            "address": l.address,
                            "protocol": l.protocol,
                            "default_route": l.default_route,
                            "request_timeout_secs": l.request_timeout_secs,
                            "keepalive_timeout_secs": l.keepalive_timeout_secs,
                            // TLS config is redacted - only show if enabled
                            "tls_enabled": l.tls.is_some(),
                        })
                    }).collect::<Vec<_>>(),
                    "routes": cfg.routes.iter().map(|r| {
                        serde_json::json!({
                            "id": r.id,
                            "priority": r.priority,
                            "matches": r.matches,
                            "upstream": r.upstream,
                            "service_type": r.service_type,
                            "builtin_handler": r.builtin_handler,
                            "filters": r.filters,
                            "waf_enabled": r.waf_enabled,
                        })
                    }).collect::<Vec<_>>(),
                    "upstreams": cfg.upstreams.iter().map(|(id, u)| {
                        serde_json::json!({
                            "id": id,
                            "targets": u.targets.iter().map(|t| {
                                serde_json::json!({
                                    "address": t.address,
                                    "weight": t.weight,
                                })
                            }).collect::<Vec<_>>(),
                            "load_balancing": u.load_balancing,
                            "health_check": u.health_check.as_ref().map(|h| {
                                serde_json::json!({
                                    "interval_secs": h.interval_secs,
                                    "timeout_secs": h.timeout_secs,
                                    "healthy_threshold": h.healthy_threshold,
                                    "unhealthy_threshold": h.unhealthy_threshold,
                                })
                            }),
                            // TLS config redacted
                            "tls_enabled": u.tls.is_some(),
                        })
                    }).collect::<Vec<_>>(),
                    "agents": cfg.agents.iter().map(|a| {
                        serde_json::json!({
                            "id": a.id,
                            "agent_type": a.agent_type,
                            "timeout_ms": a.timeout_ms,
                        })
                    }).collect::<Vec<_>>(),
                    "filters": cfg.filters.keys().collect::<Vec<_>>(),
                    "waf": cfg.waf.as_ref().map(|w| {
                        serde_json::json!({
                            "mode": w.mode,
                            "engine": w.engine,
                            "audit_log": w.audit_log,
                        })
                    }),
                    "limits": &cfg.limits,
                }
            });

            serde_json::to_vec_pretty(&response).unwrap_or_else(|e| {
                serde_json::to_vec(&serde_json::json!({
                    "error": "Failed to serialize config",
                    "message": e.to_string(),
                }))
                .unwrap_or_default()
            })
        }
        None => serde_json::to_vec_pretty(&serde_json::json!({
            "error": "Configuration unavailable",
            "status": 503,
            "message": "Config manager not available",
            "request_id": request_id,
            "timestamp": chrono::Utc::now().to_rfc3339(),
        }))
        .unwrap_or_default(),
    };

    let status = if config.is_some() {
        StatusCode::OK
    } else {
        StatusCode::SERVICE_UNAVAILABLE
    };

    Response::builder()
        .status(status)
        .header("Content-Type", "application/json; charset=utf-8")
        .header("X-Request-Id", request_id)
        .header("Cache-Control", "no-cache, no-store, must-revalidate")
        .body(Full::new(Bytes::from(body)))
        .expect("static response builder with valid headers cannot fail")
}

/// Upstream health status handler
///
/// Returns the health status of all configured upstreams and their targets.
fn upstreams_handler(
    snapshot: Option<UpstreamHealthSnapshot>,
    request_id: &str,
) -> Response<Full<Bytes>> {
    let body = match snapshot {
        Some(data) => {
            // Count healthy/unhealthy/unknown targets
            let mut total_healthy = 0;
            let mut total_unhealthy = 0;
            let mut total_unknown = 0;

            for upstream in data.upstreams.values() {
                for target in &upstream.targets {
                    match target.status {
                        TargetHealthStatus::Healthy => total_healthy += 1,
                        TargetHealthStatus::Unhealthy => total_unhealthy += 1,
                        TargetHealthStatus::Unknown => total_unknown += 1,
                    }
                }
            }

            let response = serde_json::json!({
                "timestamp": chrono::Utc::now().to_rfc3339(),
                "request_id": request_id,
                "summary": {
                    "total_upstreams": data.upstreams.len(),
                    "total_targets": total_healthy + total_unhealthy + total_unknown,
                    "healthy": total_healthy,
                    "unhealthy": total_unhealthy,
                    "unknown": total_unknown,
                },
                "upstreams": data.upstreams.values().collect::<Vec<_>>(),
            });

            serde_json::to_vec_pretty(&response).unwrap_or_else(|e| {
                serde_json::to_vec(&serde_json::json!({
                    "error": "Failed to serialize upstreams",
                    "message": e.to_string(),
                }))
                .unwrap_or_default()
            })
        }
        None => {
            // No upstreams configured or data unavailable
            serde_json::to_vec_pretty(&serde_json::json!({
                "timestamp": chrono::Utc::now().to_rfc3339(),
                "request_id": request_id,
                "summary": {
                    "total_upstreams": 0,
                    "total_targets": 0,
                    "healthy": 0,
                    "unhealthy": 0,
                    "unknown": 0,
                },
                "upstreams": [],
                "message": "No upstreams configured",
            }))
            .unwrap_or_default()
        }
    };

    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "application/json; charset=utf-8")
        .header("X-Request-Id", request_id)
        .header("Cache-Control", "no-cache, no-store, must-revalidate")
        .body(Full::new(Bytes::from(body)))
        .expect("static response builder with valid headers cannot fail")
}

/// Cache purge handler
///
/// Handles PURGE requests to invalidate cache entries. Accepts a pattern
/// and optionally purges all matching entries if wildcard is enabled.
fn cache_purge_handler(
    purge_request: Option<CachePurgeRequest>,
    cache_manager: Option<&Arc<CacheManager>>,
    request_id: &str,
) -> Response<Full<Bytes>> {
    let body = match (&purge_request, cache_manager) {
        (Some(request), Some(manager)) => {
            info!(
                pattern = %request.pattern,
                wildcard = request.wildcard,
                request_id = %request_id,
                "Processing cache purge request"
            );

            // Execute the actual purge via CacheManager
            let purged_count = if request.wildcard {
                // Wildcard purge - register pattern for matching
                manager.purge_wildcard(&request.pattern)
            } else {
                // Single entry purge
                manager.purge(&request.pattern)
            };

            info!(
                pattern = %request.pattern,
                wildcard = request.wildcard,
                purged_count = purged_count,
                request_id = %request_id,
                "Cache purge completed"
            );

            serde_json::to_vec_pretty(&serde_json::json!({
                "status": "ok",
                "message": "Cache purge request processed",
                "pattern": request.pattern,
                "wildcard": request.wildcard,
                "purged_entries": purged_count,
                "active_purges": manager.active_purge_count(),
                "request_id": request_id,
                "timestamp": chrono::Utc::now().to_rfc3339(),
            }))
            .unwrap_or_default()
        }
        (Some(request), None) => {
            // Cache manager not available - log warning and acknowledge request
            tracing::warn!(
                pattern = %request.pattern,
                request_id = %request_id,
                "Cache purge requested but cache manager not available"
            );

            serde_json::to_vec_pretty(&serde_json::json!({
                "status": "warning",
                "message": "Cache purge acknowledged but cache manager unavailable",
                "pattern": request.pattern,
                "wildcard": request.wildcard,
                "purged_entries": 0,
                "request_id": request_id,
                "timestamp": chrono::Utc::now().to_rfc3339(),
            }))
            .unwrap_or_default()
        }
        (None, _) => {
            // No purge request provided - return error
            serde_json::to_vec_pretty(&serde_json::json!({
                "error": "Bad Request",
                "status": 400,
                "message": "Cache purge requires a pattern. Use PURGE /path or X-Purge-Pattern header.",
                "request_id": request_id,
                "timestamp": chrono::Utc::now().to_rfc3339(),
            })).unwrap_or_default()
        }
    };

    let status = if purge_request.is_some() {
        StatusCode::OK
    } else {
        StatusCode::BAD_REQUEST
    };

    Response::builder()
        .status(status)
        .header("Content-Type", "application/json; charset=utf-8")
        .header("X-Request-Id", request_id)
        .header("Cache-Control", "no-cache, no-store, must-revalidate")
        .body(Full::new(Bytes::from(body)))
        .expect("static response builder with valid headers cannot fail")
}

/// Cache statistics response
#[derive(Debug, Serialize)]
struct CacheStatsResponse {
    /// Total cache hits
    hits: u64,
    /// Total cache misses
    misses: u64,
    /// Total cache stores
    stores: u64,
    /// Total cache evictions
    evictions: u64,
    /// Cache hit ratio (0.0 to 1.0)
    hit_ratio: f64,
    /// Memory-tier hits (hybrid cache)
    memory_hits: u64,
    /// Disk-tier hits (hybrid cache)
    disk_hits: u64,
    /// Request ID
    request_id: String,
    /// Timestamp
    timestamp: String,
}

/// Cache statistics handler
///
/// Returns current cache statistics including hits, misses, and hit ratio.
fn cache_stats_handler(
    cache_stats: Option<Arc<HttpCacheStats>>,
    request_id: &str,
) -> Response<Full<Bytes>> {
    let body = match cache_stats {
        Some(stats) => {
            let response = CacheStatsResponse {
                hits: stats.hits(),
                misses: stats.misses(),
                stores: stats.stores(),
                evictions: stats.evictions(),
                hit_ratio: stats.hit_ratio(),
                memory_hits: stats.memory_hits(),
                disk_hits: stats.disk_hits(),
                request_id: request_id.to_string(),
                timestamp: chrono::Utc::now().to_rfc3339(),
            };

            serde_json::to_vec_pretty(&response)
                .unwrap_or_else(|_| b"{\"error\":\"Failed to serialize stats\"}".to_vec())
        }
        None => serde_json::to_vec_pretty(&serde_json::json!({
            "hits": 0,
            "misses": 0,
            "stores": 0,
            "evictions": 0,
            "hit_ratio": 0.0,
            "memory_hits": 0,
            "disk_hits": 0,
            "message": "Cache statistics not available",
            "request_id": request_id,
            "timestamp": chrono::Utc::now().to_rfc3339(),
        }))
        .unwrap_or_default(),
    };

    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "application/json; charset=utf-8")
        .header("X-Request-Id", request_id)
        .header("Cache-Control", "no-cache, no-store, must-revalidate")
        .body(Full::new(Bytes::from(body)))
        .expect("static response builder with valid headers cannot fail")
}

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

    #[test]
    fn test_status_handler() {
        let state = BuiltinHandlerState::new("0.1.0".to_string(), "test-instance".to_string());

        let response = status_handler(&state, "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);

        let content_type = response.headers().get("Content-Type").unwrap();
        assert_eq!(content_type, "application/json; charset=utf-8");
    }

    #[test]
    fn test_health_handler() {
        let response = health_handler("test-request-id");
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_metrics_handler() {
        let response = metrics_handler("test-request-id", None);
        assert_eq!(response.status(), StatusCode::OK);

        let content_type = response.headers().get("Content-Type").unwrap();
        assert!(content_type.to_str().unwrap().contains("text/plain"));
    }

    #[test]
    fn test_metrics_handler_with_cache_stats() {
        let stats = Arc::new(HttpCacheStats::default());
        stats.record_hit();
        stats.record_miss();
        stats.record_store();

        let response = metrics_handler("test-request-id", Some(&stats));
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_cache_purge_handler_with_request() {
        let cache_manager = Arc::new(CacheManager::new());
        let request = CachePurgeRequest {
            pattern: "/api/users/*".to_string(),
            wildcard: true,
        };
        let response = cache_purge_handler(Some(request), Some(&cache_manager), "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);

        // Verify the purge was actually registered
        assert!(cache_manager.active_purge_count() > 0);
    }

    #[test]
    fn test_cache_purge_handler_single_entry() {
        let cache_manager = Arc::new(CacheManager::new());
        let request = CachePurgeRequest {
            pattern: "/api/users/123".to_string(),
            wildcard: false,
        };
        let response = cache_purge_handler(Some(request), Some(&cache_manager), "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);

        // Verify the purge was registered
        assert!(cache_manager.should_invalidate("/api/users/123"));
    }

    #[test]
    fn test_cache_purge_handler_without_request() {
        let cache_manager = Arc::new(CacheManager::new());
        let response = cache_purge_handler(None, Some(&cache_manager), "test-request-id");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn test_cache_purge_handler_without_manager() {
        let request = CachePurgeRequest {
            pattern: "/api/users/*".to_string(),
            wildcard: true,
        };
        // Without cache manager, should still return OK but with warning
        let response = cache_purge_handler(Some(request), None, "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_cache_stats_handler_with_stats() {
        let stats = Arc::new(HttpCacheStats::default());
        stats.record_hit();
        stats.record_hit();
        stats.record_miss();

        let response = cache_stats_handler(Some(stats), "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);

        let content_type = response.headers().get("Content-Type").unwrap();
        assert_eq!(content_type, "application/json; charset=utf-8");
    }

    #[test]
    fn test_cache_stats_handler_without_stats() {
        let response = cache_stats_handler(None, "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_not_found_handler() {
        let response = not_found_handler("test-request-id");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_config_handler_with_config() {
        let config = Arc::new(Config::default_for_testing());
        let response = config_handler(Some(config), "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);

        let content_type = response.headers().get("Content-Type").unwrap();
        assert_eq!(content_type, "application/json; charset=utf-8");
    }

    #[test]
    fn test_config_handler_without_config() {
        let response = config_handler(None, "test-request-id");
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[test]
    fn test_upstreams_handler_with_data() {
        let mut upstreams = HashMap::new();
        upstreams.insert(
            "backend".to_string(),
            UpstreamStatus {
                id: "backend".to_string(),
                load_balancing: "round_robin".to_string(),
                targets: vec![
                    TargetStatus {
                        address: "10.0.0.1:8080".to_string(),
                        weight: 1,
                        status: TargetHealthStatus::Healthy,
                        failure_rate: Some(0.0),
                        last_error: None,
                    },
                    TargetStatus {
                        address: "10.0.0.2:8080".to_string(),
                        weight: 1,
                        status: TargetHealthStatus::Unhealthy,
                        failure_rate: Some(0.8),
                        last_error: Some("connection refused".to_string()),
                    },
                ],
            },
        );

        let snapshot = UpstreamHealthSnapshot { upstreams };
        let response = upstreams_handler(Some(snapshot), "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);

        let content_type = response.headers().get("Content-Type").unwrap();
        assert_eq!(content_type, "application/json; charset=utf-8");
    }

    #[test]
    fn test_upstreams_handler_no_upstreams() {
        let response = upstreams_handler(None, "test-request-id");
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_uptime_formatting() {
        let state = BuiltinHandlerState::new("0.1.0".to_string(), "test".to_string());

        // Just verify it doesn't panic and returns a string
        let uptime = state.uptime_string();
        assert!(!uptime.is_empty());
    }
}