elif-http 0.8.8

HTTP server core for the elif.rs LLM-friendly web framework
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
//! # Maintenance Mode Middleware
//!
//! Provides maintenance mode functionality to temporarily disable application access.
//! Supports custom responses, whitelisted paths, and dynamic enable/disable.

use crate::middleware::v2::{Middleware, Next, NextFuture};
use crate::request::{ElifMethod, ElifRequest};
use crate::response::{ElifResponse, ElifStatusCode};
use std::collections::HashSet;
use std::path::Path;
use std::sync::{Arc, RwLock};

/// Maintenance mode response type
#[derive(Debug, Clone)]
pub enum MaintenanceResponse {
    /// Simple text response
    Text(String),
    /// JSON response with error details
    Json(serde_json::Value),
    /// HTML response (e.g., maintenance page)
    Html(String),
    /// Custom response with status code and body
    Custom {
        status_code: ElifStatusCode,
        content_type: String,
        body: Vec<u8>,
    },
    /// Load response from file
    File(String),
}

impl Default for MaintenanceResponse {
    fn default() -> Self {
        Self::Json(serde_json::json!({
            "error": {
                "code": "maintenance_mode",
                "message": "Service temporarily unavailable due to maintenance",
                "hint": "Please try again later"
            }
        }))
    }
}

impl MaintenanceResponse {
    /// Convert to ElifResponse
    pub async fn to_elif_response(&self) -> ElifResponse {
        match self {
            Self::Text(text) => {
                ElifResponse::with_status(ElifStatusCode::SERVICE_UNAVAILABLE).text(text.clone())
            }
            Self::Json(json) => ElifResponse::with_status(ElifStatusCode::SERVICE_UNAVAILABLE)
                .json_value(json.clone()),
            Self::Html(html) => ElifResponse::with_status(ElifStatusCode::SERVICE_UNAVAILABLE)
                .content_type("text/html")
                .unwrap_or_else(|_| ElifResponse::with_status(ElifStatusCode::SERVICE_UNAVAILABLE))
                .text(html.clone()),
            Self::Custom {
                status_code,
                content_type,
                body,
            } => ElifResponse::with_status(*status_code)
                .content_type(content_type)
                .unwrap_or_else(|_| ElifResponse::with_status(*status_code))
                .bytes(axum::body::Bytes::copy_from_slice(body)),
            Self::File(path) => {
                // Try to load file content
                match tokio::fs::read(path).await {
                    Ok(content) => {
                        // Determine content type from file extension
                        let content_type =
                            match Path::new(path).extension().and_then(|ext| ext.to_str()) {
                                Some("html") => "text/html",
                                Some("json") => "application/json",
                                Some("txt") => "text/plain",
                                _ => "text/plain",
                            };

                        ElifResponse::with_status(ElifStatusCode::SERVICE_UNAVAILABLE)
                            .content_type(content_type)
                            .unwrap_or_else(|_| {
                                ElifResponse::with_status(ElifStatusCode::SERVICE_UNAVAILABLE)
                            })
                            .bytes(axum::body::Bytes::from(content))
                    }
                    Err(_) => {
                        // File not found, return default response
                        ElifResponse::with_status(ElifStatusCode::SERVICE_UNAVAILABLE).json_value(
                            serde_json::json!({
                                "error": {
                                    "code": "maintenance_mode",
                                    "message": "Service temporarily unavailable"
                                }
                            }),
                        )
                    }
                }
            }
        }
    }
}

/// Path matching strategy
#[derive(Debug)]
pub enum PathMatch {
    /// Exact path match
    Exact(String),
    /// Path prefix match
    Prefix(String),
    /// Regex pattern match (stores compiled regex for performance)
    Regex(regex::Regex),
    /// Custom matcher function
    Custom(fn(&str) -> bool),
}

impl PathMatch {
    /// Create a new regex path matcher (compiles the regex once)
    pub fn regex(pattern: &str) -> Result<Self, regex::Error> {
        Ok(Self::Regex(regex::Regex::new(pattern)?))
    }

    /// Check if this matcher matches the given path
    pub fn matches(&self, path: &str) -> bool {
        match self {
            Self::Exact(exact_path) => path == exact_path,
            Self::Prefix(prefix) => path.starts_with(prefix),
            Self::Regex(compiled_regex) => compiled_regex.is_match(path),
            Self::Custom(matcher) => matcher(path),
        }
    }
}

impl Clone for PathMatch {
    fn clone(&self) -> Self {
        match self {
            Self::Exact(s) => Self::Exact(s.clone()),
            Self::Prefix(s) => Self::Prefix(s.clone()),
            Self::Regex(regex) => Self::Regex(regex.clone()),
            Self::Custom(f) => Self::Custom(*f),
        }
    }
}

impl PartialEq for PathMatch {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Exact(a), Self::Exact(b)) => a == b,
            (Self::Prefix(a), Self::Prefix(b)) => a == b,
            (Self::Regex(a), Self::Regex(b)) => a.as_str() == b.as_str(),
            (Self::Custom(a), Self::Custom(b)) => std::ptr::eq(a as *const _, b as *const _),
            _ => false,
        }
    }
}

/// Maintenance mode configuration
#[derive(Debug)]
pub struct MaintenanceModeConfig {
    /// Whether maintenance mode is currently enabled
    pub enabled: Arc<RwLock<bool>>,
    /// Response to send during maintenance mode
    pub response: MaintenanceResponse,
    /// Paths that should be allowed during maintenance mode
    pub allowed_paths: Vec<PathMatch>,
    /// HTTP methods that should be allowed during maintenance mode
    pub allowed_methods: HashSet<ElifMethod>,
    /// IP addresses that should bypass maintenance mode
    pub allowed_ips: HashSet<String>,
    /// Custom header to bypass maintenance mode
    pub bypass_header: Option<(String, String)>,
    /// Whether to add Retry-After header
    pub add_retry_after: Option<u64>,
}

impl Default for MaintenanceModeConfig {
    fn default() -> Self {
        let mut allowed_methods = HashSet::new();
        allowed_methods.insert(ElifMethod::GET); // Allow health checks by default

        Self {
            enabled: Arc::new(RwLock::new(false)),
            response: MaintenanceResponse::default(),
            allowed_paths: vec![
                PathMatch::Exact("/health".to_string()),
                PathMatch::Exact("/ping".to_string()),
                PathMatch::Prefix("/status".to_string()),
            ],
            allowed_methods,
            allowed_ips: HashSet::new(),
            bypass_header: None,
            add_retry_after: Some(3600), // 1 hour
        }
    }
}

/// Maintenance mode middleware
#[derive(Debug)]
pub struct MaintenanceModeMiddleware {
    config: MaintenanceModeConfig,
}

impl MaintenanceModeMiddleware {
    /// Create new maintenance mode middleware
    pub fn new() -> Self {
        Self {
            config: MaintenanceModeConfig::default(),
        }
    }

    /// Create with custom configuration
    pub fn with_config(config: MaintenanceModeConfig) -> Self {
        Self { config }
    }

    /// Enable maintenance mode
    pub fn enable(
        &self,
    ) -> Result<(), std::sync::PoisonError<std::sync::RwLockWriteGuard<'_, bool>>> {
        let mut enabled = self.config.enabled.write()?;
        *enabled = true;
        Ok(())
    }

    /// Disable maintenance mode
    pub fn disable(
        &self,
    ) -> Result<(), std::sync::PoisonError<std::sync::RwLockWriteGuard<'_, bool>>> {
        let mut enabled = self.config.enabled.write()?;
        *enabled = false;
        Ok(())
    }

    /// Check if maintenance mode is enabled
    pub fn is_enabled(&self) -> bool {
        self.config
            .enabled
            .read()
            .map(|enabled| *enabled)
            .unwrap_or(false)
    }

    /// Set maintenance response
    pub fn response(mut self, response: MaintenanceResponse) -> Self {
        self.config.response = response;
        self
    }

    /// Add allowed path (exact match)
    pub fn allow_path(mut self, path: impl Into<String>) -> Self {
        self.config
            .allowed_paths
            .push(PathMatch::Exact(path.into()));
        self
    }

    /// Add allowed path prefix
    pub fn allow_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.config
            .allowed_paths
            .push(PathMatch::Prefix(prefix.into()));
        self
    }

    /// Add allowed path regex pattern
    pub fn allow_regex(mut self, pattern: &str) -> Result<Self, regex::Error> {
        self.config.allowed_paths.push(PathMatch::regex(pattern)?);
        Ok(self)
    }

    /// Add custom path matcher
    pub fn allow_custom(mut self, matcher: fn(&str) -> bool) -> Self {
        self.config.allowed_paths.push(PathMatch::Custom(matcher));
        self
    }

    /// Add allowed HTTP method
    pub fn allow_method(mut self, method: ElifMethod) -> Self {
        self.config.allowed_methods.insert(method);
        self
    }

    /// Add allowed IP address
    pub fn allow_ip(mut self, ip: impl Into<String>) -> Self {
        self.config.allowed_ips.insert(ip.into());
        self
    }

    /// Set bypass header (name and expected value)
    pub fn bypass_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.config.bypass_header = Some((name.into(), value.into()));
        self
    }

    /// Set Retry-After header value in seconds
    pub fn retry_after(mut self, seconds: u64) -> Self {
        self.config.add_retry_after = Some(seconds);
        self
    }

    /// Disable Retry-After header
    pub fn no_retry_after(mut self) -> Self {
        self.config.add_retry_after = None;
        self
    }

    /// Start in enabled state
    pub fn enabled(self) -> Self {
        let _ = self.enable();
        self
    }

    /// Check if request should bypass maintenance mode
    fn should_allow_request(&self, request: &ElifRequest) -> bool {
        // Check if maintenance mode is disabled
        if !self.is_enabled() {
            return true;
        }

        // Method check is removed - we check paths first, then other bypass conditions

        // Check allowed paths
        let path = request.path();
        for path_match in &self.config.allowed_paths {
            if path_match.matches(path) {
                return true;
            }
        }

        // Check bypass header
        if let Some((header_name, expected_value)) = &self.config.bypass_header {
            if let Some(header_value) = request.header(header_name) {
                if let Ok(value_str) = header_value.to_str() {
                    if value_str == expected_value {
                        return true;
                    }
                }
            }
        }

        // Check allowed IPs (simplified - would need real IP extraction in production)
        // For now, we'll check X-Forwarded-For or X-Real-IP headers
        let client_ip = request
            .header("x-forwarded-for")
            .or_else(|| request.header("x-real-ip"))
            .and_then(|h| h.to_str().ok())
            .map(|s| s.split(',').next().unwrap_or(s).trim());

        if let Some(ip) = client_ip {
            if self.config.allowed_ips.contains(ip) {
                return true;
            }
        }

        false
    }

    /// Create maintenance response
    async fn create_maintenance_response(&self) -> ElifResponse {
        let mut response = self.config.response.to_elif_response().await;

        // Add Retry-After header if configured
        if let Some(retry_after) = self.config.add_retry_after {
            response = response
                .header("retry-after", retry_after.to_string())
                .unwrap_or_else(|_| ElifResponse::with_status(ElifStatusCode::SERVICE_UNAVAILABLE));
        }

        response
    }
}

impl Default for MaintenanceModeMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

impl Middleware for MaintenanceModeMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let should_allow = self.should_allow_request(&request);
        let config = MaintenanceModeConfig {
            enabled: Arc::clone(&self.config.enabled),
            response: self.config.response.clone(),
            allowed_paths: self.config.allowed_paths.clone(),
            allowed_methods: self.config.allowed_methods.clone(),
            allowed_ips: self.config.allowed_ips.clone(),
            bypass_header: self.config.bypass_header.clone(),
            add_retry_after: self.config.add_retry_after,
        };

        Box::pin(async move {
            if should_allow {
                // Request is allowed, continue to next middleware/handler
                next.run(request).await
            } else {
                // Maintenance mode is active, return maintenance response
                let middleware = MaintenanceModeMiddleware { config };
                middleware.create_maintenance_response().await
            }
        })
    }

    fn name(&self) -> &'static str {
        "MaintenanceModeMiddleware"
    }
}

/// Builder for creating maintenance mode middleware with shared state
pub struct MaintenanceModeBuilder {
    enabled: Arc<RwLock<bool>>,
}

impl MaintenanceModeBuilder {
    /// Create a new maintenance mode builder
    pub fn new() -> Self {
        Self {
            enabled: Arc::new(RwLock::new(false)),
        }
    }

    /// Enable maintenance mode
    pub fn enable(&self) {
        if let Ok(mut enabled) = self.enabled.write() {
            *enabled = true;
        }
    }

    /// Disable maintenance mode
    pub fn disable(&self) {
        if let Ok(mut enabled) = self.enabled.write() {
            *enabled = false;
        }
    }

    /// Check if enabled
    pub fn is_enabled(&self) -> bool {
        self.enabled.read().map(|enabled| *enabled).unwrap_or(false)
    }

    /// Build middleware with shared state
    pub fn build(&self) -> MaintenanceModeMiddleware {
        let config = MaintenanceModeConfig {
            enabled: Arc::clone(&self.enabled),
            ..Default::default()
        };
        MaintenanceModeMiddleware::with_config(config)
    }

    /// Build middleware with custom configuration but shared enabled state
    pub fn build_with_config(
        &self,
        mut config: MaintenanceModeConfig,
    ) -> MaintenanceModeMiddleware {
        config.enabled = Arc::clone(&self.enabled);
        MaintenanceModeMiddleware::with_config(config)
    }
}

impl Default for MaintenanceModeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::request::ElifRequest;
    use crate::response::headers::ElifHeaderMap;
    use crate::response::ElifResponse;

    #[test]
    fn test_path_matching() {
        let exact = PathMatch::Exact("/health".to_string());
        assert!(exact.matches("/health"));
        assert!(!exact.matches("/health-check"));

        let prefix = PathMatch::Prefix("/api/".to_string());
        assert!(prefix.matches("/api/users"));
        assert!(prefix.matches("/api/"));
        assert!(!prefix.matches("/v1/api/users"));

        let regex = PathMatch::regex(r"^/api/v\d+/.*").unwrap();
        assert!(regex.matches("/api/v1/users"));
        assert!(regex.matches("/api/v2/posts"));
        assert!(!regex.matches("/api/users"));

        let custom = PathMatch::Custom(|path| path.ends_with(".json"));
        assert!(custom.matches("/data.json"));
        assert!(!custom.matches("/data.xml"));
    }

    #[tokio::test]
    async fn test_maintenance_response_types() {
        // Text response
        let text_response = MaintenanceResponse::Text("Under maintenance".to_string());
        let response = text_response.to_elif_response().await;
        assert_eq!(response.status_code(), ElifStatusCode::SERVICE_UNAVAILABLE);

        // JSON response
        let json_response = MaintenanceResponse::Json(serde_json::json!({
            "error": "maintenance"
        }));
        let response = json_response.to_elif_response().await;
        assert_eq!(response.status_code(), ElifStatusCode::SERVICE_UNAVAILABLE);

        // HTML response
        let html_response = MaintenanceResponse::Html("<h1>Maintenance</h1>".to_string());
        let response = html_response.to_elif_response().await;
        assert_eq!(response.status_code(), ElifStatusCode::SERVICE_UNAVAILABLE);

        // Custom response
        let custom_response = MaintenanceResponse::Custom {
            status_code: ElifStatusCode::LOCKED,
            content_type: "text/plain".to_string(),
            body: b"Locked".to_vec(),
        };
        let response = custom_response.to_elif_response().await;
        assert_eq!(response.status_code(), ElifStatusCode::LOCKED);
    }

    #[tokio::test]
    async fn test_maintenance_mode_disabled() {
        let middleware = MaintenanceModeMiddleware::new(); // Disabled by default

        let request = ElifRequest::new(
            ElifMethod::GET,
            "/api/data".parse().unwrap(),
            ElifHeaderMap::new(),
        );

        let next =
            Next::new(|_req| Box::pin(async move { ElifResponse::ok().text("Normal response") }));

        let response = middleware.handle(request, next).await;
        assert_eq!(response.status_code(), ElifStatusCode::OK);
    }

    #[tokio::test]
    async fn test_maintenance_mode_enabled() {
        let middleware = MaintenanceModeMiddleware::new().enabled();

        let request = ElifRequest::new(
            ElifMethod::POST,
            "/api/data".parse().unwrap(),
            ElifHeaderMap::new(),
        );

        let next = Next::new(|_req| {
            Box::pin(async move { ElifResponse::ok().text("Should not reach here") })
        });

        let response = middleware.handle(request, next).await;
        assert_eq!(response.status_code(), ElifStatusCode::SERVICE_UNAVAILABLE);
    }

    #[tokio::test]
    async fn test_maintenance_mode_allowed_paths() {
        let middleware = MaintenanceModeMiddleware::new()
            .enabled()
            .allow_path("/health");

        // Health check should be allowed
        let request = ElifRequest::new(
            ElifMethod::GET,
            "/health".parse().unwrap(),
            ElifHeaderMap::new(),
        );

        let next = Next::new(|_req| Box::pin(async move { ElifResponse::ok().text("Healthy") }));

        let response = middleware.handle(request, next).await;
        assert_eq!(response.status_code(), ElifStatusCode::OK);

        // Other paths should be blocked
        let request = ElifRequest::new(
            ElifMethod::GET,
            "/api/data".parse().unwrap(),
            ElifHeaderMap::new(),
        );

        let next =
            Next::new(|_req| Box::pin(async move { ElifResponse::ok().text("Should be blocked") }));

        let response = middleware.handle(request, next).await;
        assert_eq!(response.status_code(), ElifStatusCode::SERVICE_UNAVAILABLE);
    }

    #[tokio::test]
    async fn test_maintenance_mode_bypass_header() {
        let middleware = MaintenanceModeMiddleware::new()
            .enabled()
            .bypass_header("x-admin-key", "secret123");

        // Request with correct bypass header
        let mut headers = ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("x-admin-key").unwrap(),
            "secret123".parse().unwrap(),
        );
        let request = ElifRequest::new(ElifMethod::GET, "/admin/panel".parse().unwrap(), headers);

        let next =
            Next::new(|_req| Box::pin(async move { ElifResponse::ok().text("Admin panel") }));

        let response = middleware.handle(request, next).await;
        assert_eq!(response.status_code(), ElifStatusCode::OK);

        // Request with wrong bypass header
        let mut headers = ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("x-admin-key").unwrap(),
            "wrong-key".parse().unwrap(),
        );
        let request = ElifRequest::new(ElifMethod::GET, "/admin/panel".parse().unwrap(), headers);

        let next =
            Next::new(|_req| Box::pin(async move { ElifResponse::ok().text("Should be blocked") }));

        let response = middleware.handle(request, next).await;
        assert_eq!(response.status_code(), ElifStatusCode::SERVICE_UNAVAILABLE);
    }

    #[tokio::test]
    async fn test_maintenance_mode_allowed_ips() {
        let middleware = MaintenanceModeMiddleware::new()
            .enabled()
            .allow_ip("192.168.1.100");

        // Request from allowed IP
        let mut headers = ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("x-forwarded-for").unwrap(),
            "192.168.1.100".parse().unwrap(),
        );
        let request = ElifRequest::new(ElifMethod::GET, "/api/data".parse().unwrap(), headers);

        let next = Next::new(|_req| Box::pin(async move { ElifResponse::ok().text("Allowed IP") }));

        let response = middleware.handle(request, next).await;
        assert_eq!(response.status_code(), ElifStatusCode::OK);
    }

    #[tokio::test]
    async fn test_maintenance_mode_builder() {
        let builder = MaintenanceModeBuilder::new();
        let middleware = builder.build();

        assert!(!builder.is_enabled());

        // Enable maintenance mode via builder
        builder.enable();
        assert!(builder.is_enabled());

        let request = ElifRequest::new(
            ElifMethod::GET,
            "/api/data".parse().unwrap(),
            ElifHeaderMap::new(),
        );

        let next =
            Next::new(|_req| Box::pin(async move { ElifResponse::ok().text("Should be blocked") }));

        let response = middleware.handle(request, next).await;
        assert_eq!(response.status_code(), ElifStatusCode::SERVICE_UNAVAILABLE);

        // Disable and test again
        builder.disable();
        assert!(!builder.is_enabled());
    }

    #[test]
    fn test_middleware_builder_pattern() {
        let middleware = MaintenanceModeMiddleware::new()
            .allow_path("/health")
            .allow_prefix("/status")
            .allow_method(ElifMethod::OPTIONS)
            .allow_ip("127.0.0.1")
            .bypass_header("x-bypass", "secret")
            .retry_after(7200)
            .enabled();

        assert!(middleware.is_enabled());
        assert_eq!(middleware.config.allowed_paths.len(), 5); // 3 default + 2 added
        assert!(middleware
            .config
            .allowed_methods
            .contains(&ElifMethod::OPTIONS));
        assert!(middleware.config.allowed_ips.contains("127.0.0.1"));
        assert_eq!(
            middleware.config.bypass_header,
            Some(("x-bypass".to_string(), "secret".to_string()))
        );
        assert_eq!(middleware.config.add_retry_after, Some(7200));
    }

    #[test]
    fn test_regex_performance_improvement() {
        // Test that regex is compiled once, not on every match
        let regex_matcher = PathMatch::regex(r"^/api/v\d+/.*").unwrap();

        // These multiple matches should use the same compiled regex
        // (This is a behavioral test - the main benefit is performance under load)
        assert!(regex_matcher.matches("/api/v1/users"));
        assert!(regex_matcher.matches("/api/v2/posts"));
        assert!(regex_matcher.matches("/api/v3/comments"));
        assert!(!regex_matcher.matches("/api/users"));
        assert!(!regex_matcher.matches("/v1/api/users"));

        // Verify error handling for invalid regex
        let invalid_regex = PathMatch::regex(r"[invalid");
        assert!(invalid_regex.is_err());
    }

    #[test]
    fn test_path_match_clone_and_equality() {
        let exact1 = PathMatch::Exact("/test".to_string());
        let exact2 = PathMatch::Exact("/test".to_string());
        let exact3 = PathMatch::Exact("/other".to_string());

        assert_eq!(exact1, exact2);
        assert_ne!(exact1, exact3);

        let cloned = exact1.clone();
        assert_eq!(exact1, cloned);

        let regex1 = PathMatch::regex(r"^/api/.*").unwrap();
        let regex2 = PathMatch::regex(r"^/api/.*").unwrap();
        let regex3 = PathMatch::regex(r"^/other/.*").unwrap();

        assert_eq!(regex1, regex2); // Same pattern
        assert_ne!(regex1, regex3); // Different pattern

        let cloned_regex = regex1.clone();
        assert_eq!(regex1, cloned_regex);
    }
}