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
//! # Request ID Middleware
//!
//! Provides unique request ID generation and tracking for distributed systems.
//! Supports X-Request-ID header forwarding and custom ID generation strategies.

use crate::middleware::v2::{Middleware, Next, NextFuture};
use crate::request::ElifRequest;
use crate::response::{ElifHeaderName, ElifHeaderValue, ElifResponse};

use std::sync::atomic::{AtomicU64, Ordering};
use uuid::Uuid;

/// Request ID generation strategy
#[derive(Debug)]
pub enum RequestIdStrategy {
    /// Generate UUID v4 (random)
    UuidV4,
    /// Generate UUID v1 (timestamp-based)
    UuidV1,
    /// Use incrementing counter (not suitable for distributed systems)
    Counter(AtomicU64),
    /// Use custom prefix with UUID
    PrefixedUuid(String),
    /// Use custom function to generate request ID
    Custom(fn() -> String),
}

impl Default for RequestIdStrategy {
    fn default() -> Self {
        Self::UuidV4
    }
}

impl Clone for RequestIdStrategy {
    fn clone(&self) -> Self {
        match self {
            Self::UuidV4 => Self::UuidV4,
            Self::UuidV1 => Self::UuidV1,
            Self::Counter(counter) => {
                // Create new counter starting from current value
                Self::Counter(AtomicU64::new(counter.load(Ordering::Relaxed)))
            }
            Self::PrefixedUuid(prefix) => Self::PrefixedUuid(prefix.clone()),
            Self::Custom(func) => Self::Custom(*func),
        }
    }
}

impl RequestIdStrategy {
    /// Generate a new request ID using this strategy
    pub fn generate(&self) -> String {
        match self {
            Self::UuidV4 => Uuid::new_v4().to_string(),
            Self::UuidV1 => {
                // UUID v1 requires MAC address and timestamp
                // For simplicity, we'll use v4 with timestamp prefix
                let timestamp = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_millis();
                format!("{}-{}", timestamp, Uuid::new_v4())
            }
            Self::Counter(counter) => {
                let count = counter.fetch_add(1, Ordering::SeqCst);
                format!("req-{:016x}", count)
            }
            Self::PrefixedUuid(prefix) => {
                format!("{}-{}", prefix, Uuid::new_v4())
            }
            Self::Custom(generator) => generator(),
        }
    }
}

/// Configuration for request ID middleware
#[derive(Debug)]
pub struct RequestIdConfig {
    /// Header name for request ID (default: "x-request-id")
    pub header_name: String,
    /// Request ID generation strategy
    pub strategy: RequestIdStrategy,
    /// Whether to generate new ID if one already exists
    pub override_existing: bool,
    /// Whether to add request ID to response headers
    pub add_to_response: bool,
    /// Whether to log request ID
    pub log_request_id: bool,
}

impl Clone for RequestIdConfig {
    fn clone(&self) -> Self {
        Self {
            header_name: self.header_name.clone(),
            strategy: self.strategy.clone(),
            override_existing: self.override_existing,
            add_to_response: self.add_to_response,
            log_request_id: self.log_request_id,
        }
    }
}

impl Default for RequestIdConfig {
    fn default() -> Self {
        Self {
            header_name: "x-request-id".to_string(),
            strategy: RequestIdStrategy::default(),
            override_existing: false,
            add_to_response: true,
            log_request_id: true,
        }
    }
}

/// Middleware for request ID generation and tracking
#[derive(Debug)]
pub struct RequestIdMiddleware {
    config: RequestIdConfig,
}

impl RequestIdMiddleware {
    /// Create new request ID middleware with default configuration
    pub fn new() -> Self {
        Self {
            config: RequestIdConfig::default(),
        }
    }

    /// Create request ID middleware with custom configuration
    pub fn with_config(config: RequestIdConfig) -> Self {
        Self { config }
    }

    /// Set custom header name for request ID
    pub fn header_name(mut self, name: impl Into<String>) -> Self {
        self.config.header_name = name.into();
        self
    }

    /// Set request ID generation strategy
    pub fn strategy(mut self, strategy: RequestIdStrategy) -> Self {
        self.config.strategy = strategy;
        self
    }

    /// Use UUID v4 strategy (default)
    pub fn uuid_v4(mut self) -> Self {
        self.config.strategy = RequestIdStrategy::UuidV4;
        self
    }

    /// Use UUID v1 strategy (timestamp-based)
    pub fn uuid_v1(mut self) -> Self {
        self.config.strategy = RequestIdStrategy::UuidV1;
        self
    }

    /// Use counter strategy (not recommended for distributed systems)
    pub fn counter(mut self) -> Self {
        self.config.strategy = RequestIdStrategy::Counter(AtomicU64::new(0));
        self
    }

    /// Use prefixed UUID strategy
    pub fn prefixed(mut self, prefix: impl Into<String>) -> Self {
        self.config.strategy = RequestIdStrategy::PrefixedUuid(prefix.into());
        self
    }

    /// Use custom ID generation function
    pub fn custom_generator(mut self, generator: fn() -> String) -> Self {
        self.config.strategy = RequestIdStrategy::Custom(generator);
        self
    }

    /// Override existing request ID if present
    pub fn override_existing(mut self) -> Self {
        self.config.override_existing = true;
        self
    }

    /// Don't add request ID to response headers
    pub fn no_response_header(mut self) -> Self {
        self.config.add_to_response = false;
        self
    }

    /// Disable request ID logging
    pub fn no_logging(mut self) -> Self {
        self.config.log_request_id = false;
        self
    }

    /// Extract or generate request ID from request
    fn get_or_generate_request_id(&self, request: &ElifRequest) -> String {
        // Check if request already has a request ID
        if !self.config.override_existing {
            if let Some(existing_id) = request.header(&self.config.header_name) {
                if let Ok(id_str) = existing_id.to_str() {
                    if !id_str.trim().is_empty() {
                        return id_str.to_string();
                    }
                }
            }
        }

        // Generate new request ID
        self.config.strategy.generate()
    }

    /// Add request ID to request headers
    fn add_request_id_to_request(&self, mut request: ElifRequest, request_id: &str) -> ElifRequest {
        let header_name = match ElifHeaderName::from_str(&self.config.header_name) {
            Ok(name) => name,
            Err(_) => return request, // Invalid header name, skip
        };

        let header_value = match ElifHeaderValue::from_str(request_id) {
            Ok(value) => value,
            Err(_) => return request, // Invalid header value, skip
        };

        request.headers.insert(header_name, header_value);
        request
    }

    /// Add request ID to response headers
    fn add_request_id_to_response(&self, response: ElifResponse, request_id: &str) -> ElifResponse {
        if !self.config.add_to_response {
            return response;
        }

        let header_name = match self.config.header_name.as_str() {
            "x-request-id" => "x-request-id",
            "request-id" => "request-id",
            "x-trace-id" => "x-trace-id",
            _ => &self.config.header_name,
        };

        response
            .header(header_name, request_id)
            .unwrap_or_else(|_| {
                // If we can't add the header for some reason, return a new response with error
                ElifResponse::internal_server_error().json_value(serde_json::json!({
                    "error": {
                        "code": "internal_error",
                        "message": "Failed to add request ID to response"
                    }
                }))
            })
    }

    /// Log request ID if enabled
    fn log_request_id(&self, request_id: &str, method: &axum::http::Method, path: &str) {
        if self.config.log_request_id {
            tracing::info!(
                request_id = request_id,
                method = %method,
                path = path,
                "Request started"
            );
        }
    }
}

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

impl Middleware for RequestIdMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        // Generate or extract request ID
        let request_id = self.get_or_generate_request_id(&request);
        let method = request.method.clone();
        let path = request.path().to_string();

        // Log request ID
        self.log_request_id(&request_id, method.to_axum(), &path);

        // Add request ID to request headers
        let updated_request = self.add_request_id_to_request(request, &request_id);

        let config = self.config.clone();
        let request_id_clone = request_id.clone();

        Box::pin(async move {
            // Execute next middleware/handler
            let response = next.run(updated_request).await;

            // Add request ID to response headers
            let middleware = RequestIdMiddleware { config };
            middleware.add_request_id_to_response(response, &request_id_clone)
        })
    }

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

/// Extension trait to easily get request ID from ElifRequest
pub trait RequestIdExt {
    /// Get the request ID from the request headers
    fn request_id(&self) -> Option<String>;

    /// Get the request ID with fallback header names
    fn request_id_with_fallbacks(&self) -> Option<String>;
}

impl RequestIdExt for ElifRequest {
    fn request_id(&self) -> Option<String> {
        self.header("x-request-id")
            .and_then(|h| h.to_str().ok())
            .map(|s| s.to_string())
    }

    fn request_id_with_fallbacks(&self) -> Option<String> {
        // Try common request ID header names
        let header_names = [
            "x-request-id",
            "request-id",
            "x-trace-id",
            "x-correlation-id",
            "x-session-id",
        ];

        for header_name in &header_names {
            if let Some(value) = self.header(header_name) {
                if let Ok(id_str) = value.to_str() {
                    if !id_str.trim().is_empty() {
                        return Some(id_str.to_string());
                    }
                }
            }
        }

        None
    }
}

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

    #[test]
    fn test_request_id_strategies() {
        // UUID v4
        let uuid_strategy = RequestIdStrategy::UuidV4;
        let id1 = uuid_strategy.generate();
        let id2 = uuid_strategy.generate();
        assert_ne!(id1, id2);
        assert_eq!(id1.len(), 36); // Standard UUID length

        // Counter
        let counter_strategy = RequestIdStrategy::Counter(AtomicU64::new(0));
        let id1 = counter_strategy.generate();
        let id2 = counter_strategy.generate();
        assert_ne!(id1, id2);
        assert!(id1.starts_with("req-"));
        assert!(id2.starts_with("req-"));

        // Prefixed UUID
        let prefixed_strategy = RequestIdStrategy::PrefixedUuid("api".to_string());
        let id = prefixed_strategy.generate();
        assert!(id.starts_with("api-"));
        assert_eq!(id.len(), 40); // "api-" + 36-char UUID

        // Custom
        let custom_strategy = RequestIdStrategy::Custom(|| "custom-123".to_string());
        let id = custom_strategy.generate();
        assert_eq!(id, "custom-123");
    }

    #[test]
    fn test_request_id_config() {
        let config = RequestIdConfig::default();
        assert_eq!(config.header_name, "x-request-id");
        assert!(!config.override_existing);
        assert!(config.add_to_response);
        assert!(config.log_request_id);
    }

    #[tokio::test]
    async fn test_request_id_middleware_basic() {
        let middleware = RequestIdMiddleware::new();

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

        let next = Next::new(|req| {
            Box::pin(async move {
                // Verify request has request ID
                assert!(req.request_id().is_some());
                ElifResponse::ok().text("Success")
            })
        });

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

        // Check response has request ID header
        let axum_response = response.into_axum_response();
        let (parts, _) = axum_response.into_parts();
        assert!(parts.headers.contains_key("x-request-id"));
    }

    #[tokio::test]
    async fn test_request_id_middleware_existing_id() {
        let middleware = RequestIdMiddleware::new();

        let mut headers = crate::response::headers::ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("x-request-id").unwrap(),
            "existing-123".parse().unwrap(),
        );
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/api/test".parse().unwrap(),
            headers,
        );

        let next = Next::new(|req| {
            Box::pin(async move {
                // Should preserve existing request ID
                assert_eq!(req.request_id(), Some("existing-123".to_string()));
                ElifResponse::ok().text("Success")
            })
        });

        let response = middleware.handle(request, next).await;

        // Response should have the same request ID
        let axum_response = response.into_axum_response();
        let (parts, _) = axum_response.into_parts();
        assert_eq!(parts.headers.get("x-request-id").unwrap(), "existing-123");
    }

    #[tokio::test]
    async fn test_request_id_middleware_override() {
        let middleware = RequestIdMiddleware::new().override_existing();

        let mut headers = ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("x-request-id").unwrap(),
            "existing-123".parse().unwrap(),
        );
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/api/test".parse().unwrap(),
            headers,
        );

        let next = Next::new(|req| {
            Box::pin(async move {
                // Should have new request ID, not the existing one
                let request_id = req.request_id().unwrap();
                assert_ne!(request_id, "existing-123");
                ElifResponse::ok().text("Success")
            })
        });

        let response = middleware.handle(request, next).await;

        // Response should have new request ID
        let axum_response = response.into_axum_response();
        let (parts, _) = axum_response.into_parts();
        let response_id = parts.headers.get("x-request-id").unwrap().to_str().unwrap();
        assert_ne!(response_id, "existing-123");
    }

    #[tokio::test]
    async fn test_request_id_custom_header() {
        let middleware = RequestIdMiddleware::new().header_name("x-trace-id");

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

        let next = Next::new(|req| {
            Box::pin(async move {
                // Check custom header name
                assert!(req.header("x-trace-id").is_some());
                ElifResponse::ok().text("Success")
            })
        });

        let response = middleware.handle(request, next).await;

        let axum_response = response.into_axum_response();
        let (parts, _) = axum_response.into_parts();
        assert!(parts.headers.contains_key("x-trace-id"));
    }

    #[tokio::test]
    async fn test_request_id_prefixed() {
        let middleware = RequestIdMiddleware::new().prefixed("api");

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

        let next = Next::new(|req| {
            Box::pin(async move {
                let request_id = req.request_id().unwrap();
                assert!(request_id.starts_with("api-"));
                ElifResponse::ok().text("Success")
            })
        });

        let response = middleware.handle(request, next).await;

        let axum_response = response.into_axum_response();
        let (parts, _) = axum_response.into_parts();
        let response_id = parts.headers.get("x-request-id").unwrap().to_str().unwrap();
        assert!(response_id.starts_with("api-"));
    }

    #[tokio::test]
    async fn test_request_id_counter() {
        let middleware = RequestIdMiddleware::new().counter();

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

        let next = Next::new(|req| {
            Box::pin(async move {
                let request_id = req.request_id().unwrap();
                assert!(request_id.starts_with("req-"));
                ElifResponse::ok().text("Success")
            })
        });

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

    #[tokio::test]
    async fn test_request_id_no_response_header() {
        let middleware = RequestIdMiddleware::new().no_response_header();

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

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

        let response = middleware.handle(request, next).await;

        let axum_response = response.into_axum_response();
        let (parts, _) = axum_response.into_parts();
        assert!(!parts.headers.contains_key("x-request-id"));
    }

    #[test]
    fn test_request_id_extension_trait() {
        let mut headers = ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("x-request-id").unwrap(),
            "test-123".parse().unwrap(),
        );
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/test".parse().unwrap(),
            headers,
        );

        assert_eq!(request.request_id(), Some("test-123".to_string()));

        // Test with fallbacks
        let mut headers = ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("x-trace-id").unwrap(),
            "trace-456".parse().unwrap(),
        );
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/test".parse().unwrap(),
            headers,
        );

        assert_eq!(
            request.request_id_with_fallbacks(),
            Some("trace-456".to_string())
        );
    }

    #[tokio::test]
    async fn test_builder_pattern() {
        let middleware = RequestIdMiddleware::new()
            .header_name("x-custom-id")
            .prefixed("test")
            .override_existing()
            .no_response_header()
            .no_logging();

        assert_eq!(middleware.config.header_name, "x-custom-id");
        assert!(middleware.config.override_existing);
        assert!(!middleware.config.add_to_response);
        assert!(!middleware.config.log_request_id);
        assert!(matches!(
            middleware.config.strategy,
            RequestIdStrategy::PrefixedUuid(_)
        ));
    }
}