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
//! Parameter extraction engine for elif.rs
//!
//! This module provides enhanced parameter extraction with type conversion,
//! validation, and error handling for route parameters.
//!
//! ## Performance Design
//!
//! The extraction system is designed for optimal performance in request handling:
//!
//! 1. **One-time validation**: Parameters are validated once during `ExtractedParams`
//!    creation, not on every access.
//! 2. **Zero-copy access**: `get_str()` returns `&str` references without allocation.
//! 3. **Efficient type conversion**: Only string parsing overhead, no constraint re-checking.
//!
//! ## Usage Pattern
//!
//! ```rust,ignore
//! // 1. Route matcher extracts raw parameters (once per request)
//! let route_match = matcher.resolve(&method, path)?;
//!
//! // 2. Parameter extractor validates constraints (once per request)  
//! let extractor = extractors.get(&route_match.route_id)?;
//! let params = extractor.extract_from_params(route_match.params)?;
//!
//! // 3. Multiple fast parameter accesses (no validation overhead)
//! let user_id: i64 = params.get("id")?;        // Fast: only string->int parsing
//! let user_name = params.get_str("name")?;     // Fast: zero-copy &str access
//! ```

use super::pattern::{ParamConstraint, RoutePattern};
use std::collections::HashMap;
use std::str::FromStr;
use thiserror::Error;
use uuid::Uuid;

/// Errors that can occur during parameter extraction and conversion
#[derive(Error, Debug)]
pub enum ExtractionError {
    #[error("Missing parameter: {0}")]
    Missing(String),
    #[error("Parameter validation failed for '{param}': {reason}")]
    ValidationFailed { param: String, reason: String },
    #[error("Type conversion failed for parameter '{param}': {error}")]
    ConversionFailed { param: String, error: String },
    #[error("Constraint violation for parameter '{param}': expected {constraint}, got '{value}'")]
    ConstraintViolation {
        param: String,
        constraint: String,
        value: String,
    },
}

/// Extracted and validated route parameters
#[derive(Debug, Clone)]
pub struct ExtractedParams {
    raw_params: HashMap<String, String>,
    pattern: RoutePattern,
}

impl ExtractedParams {
    /// Create new extracted parameters from RouteMatch with validation
    pub fn from_route_match(
        raw_params: HashMap<String, String>,
        pattern: RoutePattern,
    ) -> Result<Self, ExtractionError> {
        let extracted = Self {
            raw_params,
            pattern,
        };

        // Validate all parameters against their constraints upfront
        extracted.validate_all()?;

        Ok(extracted)
    }

    /// Get a parameter as a raw string
    pub fn get_str(&self, name: &str) -> Option<&str> {
        self.raw_params.get(name).map(|s| s.as_str())
    }

    /// Get a parameter converted to a specific type
    ///
    /// Note: Parameters are pre-validated during ExtractedParams creation,
    /// so this method only handles type conversion.
    pub fn get<T>(&self, name: &str) -> Result<T, ExtractionError>
    where
        T: FromStr,
        T::Err: std::fmt::Display,
    {
        let value = self
            .raw_params
            .get(name)
            .ok_or_else(|| ExtractionError::Missing(name.to_string()))?;

        // Convert to target type (constraints already validated during creation)
        value
            .parse::<T>()
            .map_err(|e| ExtractionError::ConversionFailed {
                param: name.to_string(),
                error: e.to_string(),
            })
    }

    /// Get a parameter as an integer
    pub fn get_int(&self, name: &str) -> Result<i64, ExtractionError> {
        self.get::<i64>(name)
    }

    /// Get a parameter as a UUID
    pub fn get_uuid(&self, name: &str) -> Result<Uuid, ExtractionError> {
        self.get::<Uuid>(name)
    }

    /// Get a parameter with a default value if missing
    pub fn get_or<T>(&self, name: &str, default: T) -> Result<T, ExtractionError>
    where
        T: FromStr,
        T::Err: std::fmt::Display,
    {
        match self.get(name) {
            Ok(value) => Ok(value),
            Err(ExtractionError::Missing(_)) => Ok(default),
            Err(e) => Err(e),
        }
    }

    /// Get a parameter as an Option (None if missing)
    pub fn get_optional<T>(&self, name: &str) -> Result<Option<T>, ExtractionError>
    where
        T: FromStr,
        T::Err: std::fmt::Display,
    {
        match self.get(name) {
            Ok(value) => Ok(Some(value)),
            Err(ExtractionError::Missing(_)) => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// Get all parameter names
    pub fn param_names(&self) -> Vec<&String> {
        self.raw_params.keys().collect()
    }

    /// Get all raw parameter values
    pub fn raw_params(&self) -> &HashMap<String, String> {
        &self.raw_params
    }

    /// Validate all parameters against their constraints
    pub fn validate_all(&self) -> Result<(), ExtractionError> {
        for (param_name, param_value) in &self.raw_params {
            // Find the corresponding segment in the pattern
            for segment in &self.pattern.segments {
                match segment {
                    super::pattern::PathSegment::Parameter { name, constraint }
                        if name == param_name =>
                    {
                        if !constraint.validate(param_value) {
                            return Err(ExtractionError::ConstraintViolation {
                                param: param_name.clone(),
                                constraint: format!("{:?}", constraint),
                                value: param_value.clone(),
                            });
                        }
                        break;
                    }
                    super::pattern::PathSegment::CatchAll { name } if name == param_name => {
                        // Catch-all parameters don't have constraints to validate
                        break;
                    }
                    _ => continue,
                }
            }
        }
        Ok(())
    }
}

/// Parameter extractor for route patterns
#[derive(Debug)]
pub struct ParameterExtractor {
    pattern: RoutePattern,
}

impl ParameterExtractor {
    /// Create a new parameter extractor for a route pattern
    pub fn new(pattern: RoutePattern) -> Self {
        Self { pattern }
    }

    /// Extract and validate parameters from raw parameters (efficient - no re-matching)
    pub fn extract_from_params(
        &self,
        raw_params: HashMap<String, String>,
    ) -> Result<ExtractedParams, ExtractionError> {
        ExtractedParams::from_route_match(raw_params, self.pattern.clone())
    }

    /// Extract parameters from a path that matches this pattern (legacy method - less efficient)
    ///
    /// Note: This method performs pattern matching and parameter extraction.
    /// For better performance, use extract_from_params() when raw parameters are already available.
    pub fn extract(&self, path: &str) -> Result<ExtractedParams, ExtractionError> {
        // First verify the path matches the pattern
        if !self.pattern.matches(path) {
            return Err(ExtractionError::ValidationFailed {
                param: "path".to_string(),
                reason: "Path does not match route pattern".to_string(),
            });
        }

        // Extract raw parameters
        let raw_params = self.pattern.extract_params(path);

        // Use the efficient method
        self.extract_from_params(raw_params)
    }

    /// Get the route pattern
    pub fn pattern(&self) -> &RoutePattern {
        &self.pattern
    }

    /// Get expected parameter names
    pub fn param_names(&self) -> &[String] {
        &self.pattern.param_names
    }
}

/// Builder for creating typed parameter extractors with validation
#[derive(Debug)]
pub struct TypedExtractorBuilder {
    pattern: RoutePattern,
    custom_constraints: HashMap<String, ParamConstraint>,
}

impl TypedExtractorBuilder {
    /// Create a new builder for the given route pattern
    pub fn new(pattern: RoutePattern) -> Self {
        Self {
            pattern,
            custom_constraints: HashMap::new(),
        }
    }

    /// Add a custom constraint for a parameter
    pub fn constraint(mut self, param_name: &str, constraint: ParamConstraint) -> Self {
        self.custom_constraints
            .insert(param_name.to_string(), constraint);
        self
    }

    /// Add an integer constraint
    pub fn int_param(self, param_name: &str) -> Self {
        self.constraint(param_name, ParamConstraint::Int)
    }

    /// Add a UUID constraint
    pub fn uuid_param(self, param_name: &str) -> Self {
        self.constraint(param_name, ParamConstraint::Uuid)
    }

    /// Add an alphabetic constraint
    pub fn alpha_param(self, param_name: &str) -> Self {
        self.constraint(param_name, ParamConstraint::Alpha)
    }

    /// Add a slug constraint
    pub fn slug_param(self, param_name: &str) -> Self {
        self.constraint(param_name, ParamConstraint::Slug)
    }

    /// Build the parameter extractor
    pub fn build(mut self) -> ParameterExtractor {
        // Apply custom constraints to the pattern
        for segment in &mut self.pattern.segments {
            if let super::pattern::PathSegment::Parameter { name, constraint } = segment {
                if let Some(custom_constraint) = self.custom_constraints.remove(name) {
                    *constraint = custom_constraint;
                }
            }
        }

        ParameterExtractor::new(self.pattern)
    }
}

/// Convenience macros for parameter extraction
#[macro_export]
macro_rules! extract_params {
    ($extracted:expr, $($name:ident: $type:ty),+ $(,)?) => {
        {
            $(
                let $name: $type = $extracted.get(stringify!($name))?;
            )+
        }
    };
}

#[macro_export]
macro_rules! extract_optional_params {
    ($extracted:expr, $($name:ident: $type:ty),+ $(,)?) => {
        {
            $(
                let $name: Option<$type> = $extracted.get_optional(stringify!($name))?;
            )+
        }
    };
}

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

    #[test]
    fn test_basic_parameter_extraction() {
        let pattern = RoutePattern::parse("/users/{id}/posts/{slug}").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        let extracted = extractor.extract("/users/123/posts/hello-world").unwrap();

        assert_eq!(extracted.get_str("id"), Some("123"));
        assert_eq!(extracted.get_str("slug"), Some("hello-world"));
    }

    #[test]
    fn test_efficient_parameter_extraction() {
        // Test the new efficient extraction method that avoids re-matching
        let pattern = RoutePattern::parse("/users/{id:int}/posts/{slug}").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        // Simulate what RouteMatcher would provide
        let mut raw_params = HashMap::new();
        raw_params.insert("id".to_string(), "456".to_string());
        raw_params.insert("slug".to_string(), "test-post".to_string());

        // Use the efficient method (no path matching/extraction)
        let extracted = extractor.extract_from_params(raw_params).unwrap();

        assert_eq!(extracted.get_str("id"), Some("456"));
        assert_eq!(extracted.get_str("slug"), Some("test-post"));
        assert_eq!(extracted.get_int("id").unwrap(), 456);
    }

    #[test]
    fn test_typed_parameter_extraction() {
        let pattern = RoutePattern::parse("/users/{id:int}/posts/{slug}").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        let extracted = extractor.extract("/users/123/posts/hello-world").unwrap();

        // Should extract as integer
        assert_eq!(extracted.get_int("id").unwrap(), 123);

        // Should extract as string
        assert_eq!(extracted.get::<String>("slug").unwrap(), "hello-world");
    }

    #[test]
    fn test_uuid_parameter_extraction() {
        let pattern = RoutePattern::parse("/users/{id:uuid}").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
        let extracted = extractor.extract(&format!("/users/{}", uuid_str)).unwrap();

        let uuid = extracted.get_uuid("id").unwrap();
        assert_eq!(uuid.to_string(), uuid_str);
    }

    #[test]
    fn test_constraint_violations() {
        let pattern = RoutePattern::parse("/users/{id:int}").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        // Should fail with non-integer value
        let result = extractor.extract("/users/abc");
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ExtractionError::ValidationFailed { .. }
        ));
    }

    #[test]
    fn test_optional_parameters() {
        let pattern = RoutePattern::parse("/users/{id}").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        let extracted = extractor.extract("/users/123").unwrap();

        // Existing parameter
        let id: Option<i64> = extracted.get_optional("id").unwrap();
        assert_eq!(id, Some(123));

        // Missing parameter
        let missing: Option<String> = extracted.get_optional("missing").unwrap();
        assert_eq!(missing, None);
    }

    #[test]
    fn test_parameter_with_defaults() {
        let pattern = RoutePattern::parse("/users/{id}").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        let extracted = extractor.extract("/users/123").unwrap();

        // Existing parameter
        let id = extracted.get_or("id", 0i64).unwrap();
        assert_eq!(id, 123);

        // Missing parameter with default
        let page = extracted.get_or("page", 1i64).unwrap();
        assert_eq!(page, 1);
    }

    #[test]
    fn test_catch_all_parameter() {
        let pattern = RoutePattern::parse("/files/*path").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        let extracted = extractor.extract("/files/docs/images/logo.png").unwrap();

        let path: String = extracted.get("path").unwrap();
        assert_eq!(path, "docs/images/logo.png");
    }

    #[test]
    fn test_typed_extractor_builder() {
        let pattern = RoutePattern::parse("/api/{version}/users/{id}").unwrap();
        let extractor = TypedExtractorBuilder::new(pattern)
            .slug_param("version")
            .int_param("id")
            .build();

        let extracted = extractor.extract("/api/v1/users/123").unwrap();

        assert_eq!(extracted.get::<String>("version").unwrap(), "v1");
        assert_eq!(extracted.get_int("id").unwrap(), 123);
    }

    #[test]
    fn test_custom_regex_constraint() {
        use regex::Regex;

        let pattern = RoutePattern::parse("/posts/{slug}").unwrap();
        let regex = Regex::new(r"^[a-z0-9-]+$").unwrap();

        let extractor = TypedExtractorBuilder::new(pattern)
            .constraint("slug", ParamConstraint::Custom(regex))
            .build();

        // Should match valid slug
        let result = extractor.extract("/posts/hello-world-123");
        assert!(result.is_ok());

        // Should fail with invalid characters
        let result = extractor.extract("/posts/Hello_World!");
        assert!(result.is_err());
    }

    #[test]
    fn test_all_constraints() {
        // Test all built-in constraint types
        assert!(ParamConstraint::Int.validate("123"));
        assert!(!ParamConstraint::Int.validate("abc"));

        assert!(ParamConstraint::Alpha.validate("hello"));
        assert!(!ParamConstraint::Alpha.validate("hello123"));

        assert!(ParamConstraint::Slug.validate("hello-world_123"));
        assert!(!ParamConstraint::Slug.validate("hello world!"));

        let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
        assert!(ParamConstraint::Uuid.validate(uuid_str));
        assert!(!ParamConstraint::Uuid.validate("not-a-uuid"));

        assert!(ParamConstraint::None.validate("anything"));
        assert!(!ParamConstraint::None.validate("")); // Empty not allowed
    }

    #[test]
    fn test_error_types() {
        let pattern = RoutePattern::parse("/users/{id:int}").unwrap();
        let extractor = ParameterExtractor::new(pattern);

        let extracted = extractor.extract("/users/123").unwrap();

        // Missing parameter error
        let result: Result<i64, _> = extracted.get("missing");
        assert!(matches!(result.unwrap_err(), ExtractionError::Missing(_)));

        // Type conversion error (try to get string as different type)
        // First we need an actual string parameter
        let pattern2 = RoutePattern::parse("/users/{name}").unwrap();
        let extractor2 = ParameterExtractor::new(pattern2);
        let extracted2 = extractor2.extract("/users/john").unwrap();

        let result: Result<i64, _> = extracted2.get("name");
        assert!(matches!(
            result.unwrap_err(),
            ExtractionError::ConversionFailed { .. }
        ));
    }

    #[test]
    fn test_parameter_access_performance() {
        // Test that parameter access is fast (no redundant validation)
        let pattern = RoutePattern::parse("/users/{id:int}/posts/{slug:alpha}").unwrap();

        let mut raw_params = HashMap::new();
        raw_params.insert("id".to_string(), "123".to_string());
        raw_params.insert("slug".to_string(), "helloworld".to_string());

        let extracted = ExtractedParams::from_route_match(raw_params, pattern).unwrap();

        let start = std::time::Instant::now();

        // Perform many parameter accesses
        for _ in 0..10000 {
            let id: i64 = extracted.get("id").unwrap();
            let slug: String = extracted.get("slug").unwrap();
            assert_eq!(id, 123);
            assert_eq!(slug, "helloworld");
        }

        let elapsed = start.elapsed();

        // Should be very fast since no constraint validation is done on each access
        assert!(
            elapsed.as_millis() < 50,
            "Parameter access took too long: {}ms",
            elapsed.as_millis()
        );

        println!(
            "20,000 parameter accesses completed in {}μs",
            elapsed.as_micros()
        );
    }

    #[test]
    fn test_integration_with_route_matcher() {
        // Test the complete flow: RouteMatcher -> ParameterExtractor (efficient)
        use super::super::{compiler::RouteCompilerBuilder, HttpMethod};

        // Build a compiled routing system
        let compilation_result = RouteCompilerBuilder::new()
            .get("users_show".to_string(), "/users/{id:int}".to_string())
            .get(
                "posts_show".to_string(),
                "/posts/{slug:alpha}/comments/{id:uuid}".to_string(),
            )
            .build()
            .unwrap();

        // Simulate a request resolution
        let route_match = compilation_result
            .matcher
            .resolve(&HttpMethod::GET, "/users/123")
            .unwrap();

        assert_eq!(route_match.route_id, "users_show");
        assert_eq!(route_match.params.get("id"), Some(&"123".to_string()));

        // Use the efficient extraction method (no re-matching!)
        let extractor = compilation_result.extractors.get("users_show").unwrap();
        let extracted = extractor.extract_from_params(route_match.params).unwrap();

        // Type-safe parameter access
        let user_id: i64 = extracted.get("id").unwrap();
        assert_eq!(user_id, 123);

        // Test complex route with multiple constraints
        // Use "helloworld" (no hyphens) to match the alpha constraint
        let route_match = compilation_result
            .matcher
            .resolve(
                &HttpMethod::GET,
                "/posts/helloworld/comments/550e8400-e29b-41d4-a716-446655440000",
            )
            .unwrap();

        assert_eq!(route_match.route_id, "posts_show");

        let extractor = compilation_result.extractors.get("posts_show").unwrap();
        let extracted = extractor.extract_from_params(route_match.params).unwrap();

        let slug: String = extracted.get("slug").unwrap();
        let comment_id = extracted.get_uuid("id").unwrap();

        assert_eq!(slug, "helloworld");
        assert_eq!(
            comment_id.to_string(),
            "550e8400-e29b-41d4-a716-446655440000"
        );
    }
}