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
//! Route compilation and optimization for elif.rs
//!
//! This module provides compilation and optimization of route definitions
//! into efficient runtime structures for high-performance route matching.

use super::extraction::ParameterExtractor;
use super::matcher::{RouteDefinition, RouteMatchError, RouteMatcher};
use super::pattern::{RoutePattern, RoutePatternError};
use super::{HttpMethod, RouteInfo};
use std::collections::{HashMap, HashSet};
use thiserror::Error;

/// Errors that can occur during route compilation
#[derive(Error, Debug)]
pub enum CompilationError {
    #[error("Route pattern error: {0}")]
    PatternError(#[from] RoutePatternError),
    #[error("Route matching error: {0}")]
    MatcherError(#[from] RouteMatchError),
    #[error("Duplicate route ID: {0}")]
    DuplicateRouteId(String),
    #[error("Route conflict detected: {0} conflicts with {1}")]
    RouteConflict(String, String),
    #[error("Invalid route configuration: {0}")]
    InvalidConfiguration(String),
    #[error("Compilation failed: {0}")]
    CompilationFailed(String),
}

/// Configuration for route compilation
#[derive(Debug, Clone)]
pub struct CompilerConfig {
    /// Enable conflict detection
    pub detect_conflicts: bool,
    /// Enable route optimization
    pub enable_optimization: bool,
    /// Maximum number of routes before warning
    pub max_routes_warning: usize,
    /// Enable performance analysis
    pub performance_analysis: bool,
}

impl Default for CompilerConfig {
    fn default() -> Self {
        Self {
            detect_conflicts: true,
            enable_optimization: true,
            max_routes_warning: 1000,
            performance_analysis: true,
        }
    }
}

/// Statistics about compiled routes
#[derive(Debug, Clone)]
pub struct CompilationStats {
    pub total_routes: usize,
    pub static_routes: usize,
    pub dynamic_routes: usize,
    pub parameter_routes: usize,
    pub catch_all_routes: usize,
    pub conflicts_detected: usize,
    pub optimizations_applied: usize,
    pub compilation_time_ms: u128,
}

/// A single route definition for compilation
#[derive(Debug, Clone)]
pub struct CompilableRoute {
    pub id: String,
    pub method: HttpMethod,
    pub path: String,
    pub name: Option<String>,
    pub metadata: HashMap<String, String>,
}

impl CompilableRoute {
    pub fn new(id: String, method: HttpMethod, path: String) -> Self {
        Self {
            id,
            method,
            path,
            name: None,
            metadata: HashMap::new(),
        }
    }

    pub fn with_name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }

    pub fn with_metadata(mut self, key: String, value: String) -> Self {
        self.metadata.insert(key, value);
        self
    }
}

/// Result of route compilation
#[derive(Debug)]
pub struct CompilationResult {
    pub matcher: RouteMatcher,
    pub extractors: HashMap<String, ParameterExtractor>,
    pub route_registry: HashMap<String, RouteInfo>,
    pub stats: CompilationStats,
    pub warnings: Vec<String>,
}

/// Route compiler with optimization and validation
#[derive(Debug)]
pub struct RouteCompiler {
    config: CompilerConfig,
    routes: Vec<CompilableRoute>,
    route_ids: HashSet<String>,
}

impl RouteCompiler {
    /// Create a new route compiler
    pub fn new() -> Self {
        Self::with_config(CompilerConfig::default())
    }

    /// Create a new route compiler with custom configuration
    pub fn with_config(config: CompilerConfig) -> Self {
        Self {
            config,
            routes: Vec::new(),
            route_ids: HashSet::new(),
        }
    }

    /// Add a route to be compiled
    pub fn add_route(&mut self, route: CompilableRoute) -> Result<(), CompilationError> {
        // Check for duplicate route IDs
        if self.route_ids.contains(&route.id) {
            return Err(CompilationError::DuplicateRouteId(route.id));
        }

        self.route_ids.insert(route.id.clone());
        self.routes.push(route);
        Ok(())
    }

    /// Add multiple routes
    pub fn add_routes(&mut self, routes: Vec<CompilableRoute>) -> Result<(), CompilationError> {
        for route in routes {
            self.add_route(route)?;
        }
        Ok(())
    }

    /// Compile all routes into optimized structures
    pub fn compile(self) -> Result<CompilationResult, CompilationError> {
        let start_time = std::time::Instant::now();
        let mut warnings = Vec::new();
        let mut optimizations_applied = 0;

        // Capture total route count before moving
        let total_route_count = self.routes.len();

        // Check route count warning
        if total_route_count > self.config.max_routes_warning {
            warnings.push(format!(
                "Large number of routes detected: {}. Consider route grouping or optimization.",
                total_route_count
            ));
        }

        // Parse and validate all route patterns
        let mut parsed_routes = Vec::new();
        let mut static_count = 0;
        let mut dynamic_count = 0;
        let mut parameter_count = 0;
        let mut catch_all_count = 0;

        for route in self.routes {
            let pattern = RoutePattern::parse(&route.path)?;

            // Collect statistics
            if pattern.is_static() {
                static_count += 1;
            } else {
                dynamic_count += 1;
                if pattern.has_catch_all {
                    catch_all_count += 1;
                } else if !pattern.param_names.is_empty() {
                    parameter_count += 1;
                }
            }

            parsed_routes.push((route, pattern));
        }

        // Create route matcher
        let mut matcher = RouteMatcher::new();
        let mut extractors = HashMap::new();
        let mut route_registry = HashMap::new();
        let mut conflicts_detected = 0;

        // Apply optimizations if enabled
        if self.config.enable_optimization {
            parsed_routes = Self::optimize_routes(parsed_routes);
            optimizations_applied += 1;
        }

        // Add routes to matcher and create extractors
        for (route, pattern) in parsed_routes {
            // Extract data we need to move/clone before consuming route
            let route_id = route.id;
            let route_method = route.method;
            let route_path = route.path;
            let route_name = route.name;
            let route_group = route.metadata.get("group").cloned();
            let is_pattern_static = pattern.is_static();
            let pattern_param_names = pattern.param_names.clone();

            // Create route definition
            let route_def = RouteDefinition {
                id: route_id.clone(),
                method: route_method.clone(),
                path: route_path.clone(),
            };

            // Try to add route, handle conflicts
            match matcher.add_route(route_def) {
                Ok(()) => {
                    // Create parameter extractor for dynamic routes
                    if !is_pattern_static {
                        let extractor = ParameterExtractor::new(pattern);
                        extractors.insert(route_id.clone(), extractor);
                    }

                    // Create route info for registry
                    let route_info = RouteInfo {
                        name: route_name,
                        path: route_path,
                        method: route_method,
                        params: pattern_param_names,
                        group: route_group,
                    };
                    route_registry.insert(route_id, route_info);
                }
                Err(RouteMatchError::RouteConflict(source, target)) => {
                    if self.config.detect_conflicts {
                        return Err(CompilationError::RouteConflict(source, target));
                    } else {
                        conflicts_detected += 1;
                        warnings.push(format!(
                            "Route conflict detected: {} conflicts with {}",
                            source, target
                        ));
                    }
                }
                Err(e) => return Err(CompilationError::MatcherError(e)),
            }
        }

        let compilation_time = start_time.elapsed().as_millis();

        // Performance analysis
        if self.config.performance_analysis && compilation_time > 100 {
            warnings.push(format!(
                "Route compilation took {}ms. Consider optimizing route patterns or reducing route count.",
                compilation_time
            ));
        }

        let stats = CompilationStats {
            total_routes: total_route_count,
            static_routes: static_count,
            dynamic_routes: dynamic_count,
            parameter_routes: parameter_count,
            catch_all_routes: catch_all_count,
            conflicts_detected,
            optimizations_applied,
            compilation_time_ms: compilation_time,
        };

        Ok(CompilationResult {
            matcher,
            extractors,
            route_registry,
            stats,
            warnings,
        })
    }

    /// Optimize route ordering for better performance
    fn optimize_routes(
        mut routes: Vec<(CompilableRoute, RoutePattern)>,
    ) -> Vec<(CompilableRoute, RoutePattern)> {
        // Sort routes by specificity (more specific routes first)
        // This improves matching performance for common cases
        routes.sort_by(|(_, pattern_a), (_, pattern_b)| {
            // Primary sort: static routes first
            let static_a = pattern_a.is_static();
            let static_b = pattern_b.is_static();

            match (static_a, static_b) {
                (true, false) => std::cmp::Ordering::Less, // Static before dynamic
                (false, true) => std::cmp::Ordering::Greater, // Dynamic after static
                _ => {
                    // Secondary sort: by priority (lower = more specific)
                    pattern_a.priority().cmp(&pattern_b.priority())
                }
            }
        });

        routes
    }
}

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

/// Builder for creating route compilers with fluent API
#[derive(Debug)]
pub struct RouteCompilerBuilder {
    config: CompilerConfig,
    routes: Vec<CompilableRoute>,
}

impl RouteCompilerBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self {
            config: CompilerConfig::default(),
            routes: Vec::new(),
        }
    }

    /// Set compiler configuration
    pub fn config(mut self, config: CompilerConfig) -> Self {
        self.config = config;
        self
    }

    /// Enable or disable conflict detection
    pub fn detect_conflicts(mut self, enabled: bool) -> Self {
        self.config.detect_conflicts = enabled;
        self
    }

    /// Enable or disable route optimization
    pub fn optimize(mut self, enabled: bool) -> Self {
        self.config.enable_optimization = enabled;
        self
    }

    /// Set maximum routes warning threshold
    pub fn max_routes_warning(mut self, max: usize) -> Self {
        self.config.max_routes_warning = max;
        self
    }

    /// Add a route
    pub fn route(mut self, route: CompilableRoute) -> Self {
        self.routes.push(route);
        self
    }

    /// Add a GET route
    pub fn get(mut self, id: String, path: String) -> Self {
        self.routes
            .push(CompilableRoute::new(id, HttpMethod::GET, path));
        self
    }

    /// Add a POST route
    pub fn post(mut self, id: String, path: String) -> Self {
        self.routes
            .push(CompilableRoute::new(id, HttpMethod::POST, path));
        self
    }

    /// Add a PUT route
    pub fn put(mut self, id: String, path: String) -> Self {
        self.routes
            .push(CompilableRoute::new(id, HttpMethod::PUT, path));
        self
    }

    /// Add a DELETE route
    pub fn delete(mut self, id: String, path: String) -> Self {
        self.routes
            .push(CompilableRoute::new(id, HttpMethod::DELETE, path));
        self
    }

    /// Add a PATCH route
    pub fn patch(mut self, id: String, path: String) -> Self {
        self.routes
            .push(CompilableRoute::new(id, HttpMethod::PATCH, path));
        self
    }

    /// Build and compile the routes
    pub fn build(self) -> Result<CompilationResult, CompilationError> {
        let mut compiler = RouteCompiler::with_config(self.config);

        for route in self.routes {
            compiler.add_route(route)?;
        }

        compiler.compile()
    }
}

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

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

    #[test]
    fn test_basic_compilation() {
        let result = RouteCompilerBuilder::new()
            .get("home".to_string(), "/".to_string())
            .get("users_index".to_string(), "/users".to_string())
            .get("users_show".to_string(), "/users/{id}".to_string())
            .build()
            .unwrap();

        assert_eq!(result.stats.total_routes, 3);
        assert_eq!(result.stats.static_routes, 2);
        assert_eq!(result.stats.dynamic_routes, 1);
        assert_eq!(result.stats.parameter_routes, 1);
    }

    #[test]
    fn test_route_optimization() {
        let result = RouteCompilerBuilder::new()
            .optimize(true)
            .get("catch_all".to_string(), "/files/*path".to_string())
            .get("specific".to_string(), "/files/config.json".to_string())
            .get("param".to_string(), "/files/{name}".to_string())
            .build()
            .unwrap();

        assert_eq!(result.stats.optimizations_applied, 1);

        // Test that matching works correctly with optimized order
        let matcher = result.matcher;

        // Static route should match first
        let route_match = matcher
            .resolve(&HttpMethod::GET, "/files/config.json")
            .unwrap();
        assert_eq!(route_match.route_id, "specific");

        // Parameter route should match next
        let route_match = matcher
            .resolve(&HttpMethod::GET, "/files/readme.txt")
            .unwrap();
        assert_eq!(route_match.route_id, "param");

        // Catch-all should match complex paths
        let route_match = matcher
            .resolve(&HttpMethod::GET, "/files/docs/api.md")
            .unwrap();
        assert_eq!(route_match.route_id, "catch_all");
    }

    #[test]
    fn test_constraint_based_priority_ordering() {
        // Test that routes are properly ordered by constraint specificity
        let result = RouteCompilerBuilder::new()
            .optimize(true)
            // Add routes in reverse priority order to test sorting
            .get("catch_all".to_string(), "/users/*path".to_string())
            .get("unconstrained".to_string(), "/users/{name}".to_string())
            .get("alpha_slug".to_string(), "/users/{slug:alpha}".to_string())
            .get("custom_regex".to_string(), "/users/{id:[0-9]+}".to_string())
            .get("int_id".to_string(), "/users/{id:int}".to_string())
            .get("uuid_id".to_string(), "/users/{id:uuid}".to_string())
            .get("static_me".to_string(), "/users/me".to_string())
            .build()
            .unwrap();

        let matcher = result.matcher;

        // Test that most specific routes match first

        // Static route (highest priority)
        let route_match = matcher.resolve(&HttpMethod::GET, "/users/me").unwrap();
        assert_eq!(route_match.route_id, "static_me");

        // UUID constraint (specific)
        let route_match = matcher
            .resolve(
                &HttpMethod::GET,
                "/users/550e8400-e29b-41d4-a716-446655440000",
            )
            .unwrap();
        assert_eq!(route_match.route_id, "uuid_id");

        // Integer constraint (specific)
        let route_match = matcher.resolve(&HttpMethod::GET, "/users/123").unwrap();
        assert_eq!(route_match.route_id, "int_id");

        // Custom regex constraint (medium-high priority)
        let route_match = matcher.resolve(&HttpMethod::GET, "/users/456").unwrap();
        // Note: This should match int_id since it has higher priority than custom regex
        assert_eq!(route_match.route_id, "int_id");

        // Alpha constraint (general)
        let route_match = matcher
            .resolve(&HttpMethod::GET, "/users/johnsmith")
            .unwrap();
        assert_eq!(route_match.route_id, "alpha_slug");

        // Unconstrained parameter (contains characters that don't match any specific constraint)
        let route_match = matcher
            .resolve(&HttpMethod::GET, "/users/user_with_underscores")
            .unwrap();
        assert_eq!(route_match.route_id, "unconstrained");

        // Catch-all (lowest priority)
        let route_match = matcher
            .resolve(&HttpMethod::GET, "/users/path/to/resource")
            .unwrap();
        assert_eq!(route_match.route_id, "catch_all");
    }

    #[test]
    fn test_conflict_detection() {
        let result = RouteCompilerBuilder::new()
            .detect_conflicts(true)
            .get("route1".to_string(), "/users".to_string())
            .get("route2".to_string(), "/users".to_string())
            .build();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            CompilationError::RouteConflict(_, _)
        ));
    }

    #[test]
    fn test_conflict_warnings() {
        let result = RouteCompilerBuilder::new()
            .detect_conflicts(false) // Disable conflict errors, enable warnings
            .get("route1".to_string(), "/users".to_string())
            .get("route2".to_string(), "/users".to_string())
            .build()
            .unwrap();

        assert!(!result.warnings.is_empty());
        assert!(result.warnings[0].contains("conflict"));
        assert_eq!(result.stats.conflicts_detected, 1);
    }

    #[test]
    fn test_parameter_extractors() {
        let result = RouteCompilerBuilder::new()
            .get("users_show".to_string(), "/users/{id:int}".to_string())
            .get(
                "posts_show".to_string(),
                "/posts/{slug}/comments/{id:uuid}".to_string(),
            )
            .build()
            .unwrap();

        // Should create extractors for dynamic routes
        assert!(result.extractors.contains_key("users_show"));
        assert!(result.extractors.contains_key("posts_show"));
        assert_eq!(result.extractors.len(), 2);

        // Test extractor functionality
        let users_extractor = result.extractors.get("users_show").unwrap();
        let extracted = users_extractor.extract("/users/123").unwrap();
        assert_eq!(extracted.get_int("id").unwrap(), 123);
    }

    #[test]
    fn test_route_registry() {
        let result = RouteCompilerBuilder::new()
            .route(
                CompilableRoute::new(
                    "users_show".to_string(),
                    HttpMethod::GET,
                    "/users/{id}".to_string(),
                )
                .with_name("users.show".to_string())
                .with_metadata("group".to_string(), "users".to_string()),
            )
            .build()
            .unwrap();

        let route_info = result.route_registry.get("users_show").unwrap();
        assert_eq!(route_info.name, Some("users.show".to_string()));
        assert_eq!(route_info.group, Some("users".to_string()));
        assert_eq!(route_info.params, vec!["id"]);
    }

    #[test]
    fn test_compilation_stats() {
        let result = RouteCompilerBuilder::new()
            .get("static1".to_string(), "/".to_string())
            .get("static2".to_string(), "/about".to_string())
            .get("param1".to_string(), "/users/{id}".to_string())
            .get("param2".to_string(), "/posts/{slug}".to_string())
            .get("catch_all".to_string(), "/files/*path".to_string())
            .build()
            .unwrap();

        let stats = result.stats;
        assert_eq!(stats.total_routes, 5);
        assert_eq!(stats.static_routes, 2);
        assert_eq!(stats.dynamic_routes, 3);
        assert_eq!(stats.parameter_routes, 2);
        assert_eq!(stats.catch_all_routes, 1);
    }

    #[test]
    fn test_duplicate_route_id() {
        let mut compiler = RouteCompiler::new();

        let route1 = CompilableRoute::new(
            "duplicate".to_string(),
            HttpMethod::GET,
            "/path1".to_string(),
        );
        let route2 = CompilableRoute::new(
            "duplicate".to_string(),
            HttpMethod::POST,
            "/path2".to_string(),
        );

        compiler.add_route(route1).unwrap();
        let result = compiler.add_route(route2);

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            CompilationError::DuplicateRouteId(_)
        ));
    }

    #[test]
    fn test_performance_warnings() {
        // Create many routes to trigger performance warning
        let mut builder = RouteCompilerBuilder::new().max_routes_warning(5);

        for i in 0..10 {
            builder = builder.get(format!("route_{}", i), format!("/route_{}", i));
        }

        let result = builder.build().unwrap();
        assert!(!result.warnings.is_empty());
        assert!(result
            .warnings
            .iter()
            .any(|w| w.contains("Large number of routes")));
    }

    #[test]
    fn test_move_semantics_performance() {
        // Test that compilation uses move semantics efficiently
        let start = std::time::Instant::now();

        let mut builder = RouteCompilerBuilder::new().optimize(true);

        // Create routes with complex metadata to test move optimization
        for i in 0..100 {
            let mut route = CompilableRoute::new(
                format!("route_{}", i),
                HttpMethod::GET,
                format!("/api/v1/resources/{}/items", i),
            );

            // Add metadata to make cloning more expensive
            route = route.with_metadata("group".to_string(), format!("group_{}", i));
            route = route.with_metadata(
                "description".to_string(),
                format!("Route for resource {}", i),
            );
            route = route.with_metadata("version".to_string(), "v1".to_string());

            builder = builder.route(route);
        }

        let result = builder.build().unwrap();
        let compilation_time = start.elapsed();

        // Verify compilation succeeded
        assert_eq!(result.stats.total_routes, 100);
        assert!(result.stats.optimizations_applied > 0);

        // Should compile reasonably fast with move semantics
        assert!(
            compilation_time.as_millis() < 100,
            "Compilation took too long: {}ms",
            compilation_time.as_millis()
        );

        println!(
            "100 complex routes compiled in {}ms using move semantics",
            compilation_time.as_millis()
        );
    }
}