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
//! Controller auto-registration system for zero-boilerplate controller setup
//!
//! This module implements the Controller Auto-Registration System that automatically
//! discovers controllers from modules and registers their routes with the router.
//!
//! ## Overview
//!
//! The system bridges the gap between compile-time module discovery (which only
//! has controller names as strings) and runtime controller registration (which
//! needs actual instances with metadata).
//!
//! ## Key Components
//!
//! - `ControllerRegistry`: Central registry for discovered controllers
//! - `ControllerMetadata`: Enhanced metadata structure for registration
//! - `RouteRegistrationEngine`: Handles automatic route registration

use std::collections::HashMap;
use std::sync::Arc;
use std::pin::Pin;
use std::future::Future;
use elif_core::modules::CompileTimeModuleMetadata;
use elif_core::container::IocContainer;
use crate::controller::ControllerRoute;
use crate::routing::{ElifRouter, HttpMethod};
use crate::bootstrap::{BootstrapError, RouteConflict, RouteInfo, ConflictType, ConflictResolution, ParamDef};

/// Enhanced controller metadata for auto-registration
#[derive(Debug, Clone)]
pub struct ControllerMetadata {
    /// Controller name (type name)
    pub name: String,
    /// Base path for all routes in this controller
    pub base_path: String,
    /// All routes defined in this controller
    pub routes: Vec<RouteMetadata>,
    /// Middleware applied to all controller routes
    pub middleware: Vec<String>,
    /// Dependencies this controller needs from IoC container
    pub dependencies: Vec<String>,
}

/// Route metadata extracted from controller
#[derive(Debug, Clone)]
pub struct RouteMetadata {
    /// HTTP method (GET, POST, etc.)
    pub method: HttpMethod,
    /// Route path relative to controller base path
    pub path: String,
    /// Name of the handler method
    pub handler_name: String,
    /// Middleware specific to this route
    pub middleware: Vec<String>,
    /// Route parameters with validation info
    pub params: Vec<ParamMetadata>,
}

/// Parameter metadata for route validation
#[derive(Debug, Clone)]
pub struct ParamMetadata {
    /// Parameter name
    pub name: String,
    /// Parameter type (string, int, uuid, etc.)
    pub param_type: String,
    /// Whether parameter is required
    pub required: bool,
    /// Default value if optional
    pub default: Option<String>,
}

/// Central registry for controller auto-registration
#[derive(Debug)]
pub struct ControllerRegistry {
    /// Map of controller name to metadata
    controllers: HashMap<String, ControllerMetadata>,
    /// IoC container for controller resolution
    #[allow(dead_code)]
    container: Arc<IocContainer>,
}

impl ControllerRegistry {
    /// Create a new controller registry
    pub fn new(container: Arc<IocContainer>) -> Self {
        Self {
            controllers: HashMap::new(),
            container,
        }
    }

    /// Build controller registry from discovered modules
    pub fn from_modules(modules: &[CompileTimeModuleMetadata], container: Arc<IocContainer>) -> Result<Self, BootstrapError> {
        let mut registry = Self::new(container);
        
        // Extract all controller names from modules
        let mut controller_names = std::collections::HashSet::new();
        for module in modules {
            for controller_name in &module.controllers {
                controller_names.insert(controller_name.clone());
            }
        }

        // Build metadata for each controller
        for controller_name in controller_names {
            let metadata = registry.build_controller_metadata(&controller_name)?;
            registry.controllers.insert(controller_name.clone(), metadata);
        }

        Ok(registry)
    }

    /// Build metadata for a specific controller using the type registry
    fn build_controller_metadata(&self, controller_name: &str) -> Result<ControllerMetadata, BootstrapError> {
        // Use the global controller type registry to create an instance
        let controller = super::controller_registry::create_controller(controller_name)?;
        
        // Extract real metadata from the controller instance
        let routes = controller.routes()
            .into_iter()
            .map(|route| RouteMetadata::from(route))
            .collect();
        
        let dependencies = controller.dependencies();
        
        Ok(ControllerMetadata {
            name: controller.name().to_string(),
            base_path: controller.base_path().to_string(),
            routes,
            middleware: vec![], // Controller-level middleware can be added later
            dependencies,
        })
    }

    /// Register all discovered controllers with the router
    pub fn register_all_routes(&self, mut router: ElifRouter) -> Result<ElifRouter, BootstrapError> {
        for (controller_name, metadata) in &self.controllers {
            router = self.register_controller_routes(router, controller_name, metadata)?;
        }
        Ok(router)
    }

    /// Register routes for a specific controller
    fn register_controller_routes(
        &self, 
        mut router: ElifRouter, 
        controller_name: &str, 
        metadata: &ControllerMetadata
    ) -> Result<ElifRouter, BootstrapError> {
        tracing::info!(
            "Bootstrap: Registering controller '{}' with {} routes at base path '{}'",
            controller_name, 
            metadata.routes.len(),
            metadata.base_path
        );
        
        // Create controller instance once and share it across all its routes
        let controller = super::controller_registry::create_controller(controller_name)?;
        let controller_arc = std::sync::Arc::new(controller);

        // Register each route with the HTTP router
        for route in &metadata.routes {
            let full_path = self.combine_paths(&metadata.base_path, &route.path);
            
            tracing::debug!(
                "Registering route: {} {} -> {}::{}",
                route.method,
                full_path,
                controller_name,
                route.handler_name
            );
            
            // Create a handler that captures the shared controller instance
            let controller_clone = std::sync::Arc::clone(&controller_arc);
            let method_name = route.handler_name.clone();
            let handler = move |request: crate::request::ElifRequest| {
                let controller_for_request = std::sync::Arc::clone(&controller_clone);
                let method_for_request = method_name.clone();
                Box::pin(async move {
                    controller_for_request.handle_request_dyn(method_for_request, request).await
                }) as Pin<Box<dyn Future<Output = crate::errors::HttpResult<crate::response::ElifResponse>> + Send>>
            };
            
            // Register route based on HTTP method
            router = match route.method {
                HttpMethod::GET => router.get(&full_path, handler),
                HttpMethod::POST => router.post(&full_path, handler),
                HttpMethod::PUT => router.put(&full_path, handler),
                HttpMethod::DELETE => router.delete(&full_path, handler),
                HttpMethod::PATCH => router.patch(&full_path, handler),
                HttpMethod::HEAD => {
                    tracing::warn!("HEAD method not yet supported for route: {}", full_path);
                    continue;
                },
                HttpMethod::OPTIONS => {
                    tracing::warn!("OPTIONS method not yet supported for route: {}", full_path);
                    continue;
                },
                HttpMethod::TRACE => {
                    tracing::warn!("TRACE method not yet supported for route: {}", full_path);
                    continue;
                },
            };
        }
        
        tracing::info!(
            "Bootstrap: Successfully registered controller '{}' with {} HTTP routes",
            controller_name,
            metadata.routes.len()
        );
        
        Ok(router)
    }

    /// Validate all routes for conflicts
    pub fn validate_routes(&self) -> Result<(), Vec<RouteConflict>> {
        let mut conflicts = Vec::new();
        let mut route_map: HashMap<String, Vec<(String, &RouteMetadata)>> = HashMap::new();

        // Group routes by path pattern
        for (controller_name, metadata) in &self.controllers {
            for route in &metadata.routes {
                let full_path = format!("{}{}", metadata.base_path, route.path);
                let key = format!("{} {}", route.method, full_path);
                
                route_map.entry(key).or_default().push((controller_name.clone(), route));
            }
        }

        // Check for conflicts
        for (_route_key, controllers) in route_map {
            if controllers.len() > 1 {
                // Create RouteInfo for the first two conflicting controllers
                let (first_controller, first_route) = &controllers[0];
                let (second_controller, second_route) = &controllers[1];
                
                let route1 = RouteInfo {
                    method: first_route.method.clone(),
                    path: format!("{}{}", 
                        self.get_controller_base_path(first_controller).unwrap_or_default(),
                        first_route.path
                    ),
                    controller: first_controller.clone(),
                    handler: first_route.handler_name.clone(),
                    middleware: first_route.middleware.clone(),
                    parameters: first_route.params.iter().map(|p| ParamDef {
                        name: p.name.clone(),
                        param_type: p.param_type.clone(),
                        required: p.required,
                        constraints: vec![], // Convert from our ParamMetadata to ParamDef
                    }).collect(),
                };
                
                let route2 = RouteInfo {
                    method: second_route.method.clone(),
                    path: format!("{}{}", 
                        self.get_controller_base_path(second_controller).unwrap_or_default(),
                        second_route.path
                    ),
                    controller: second_controller.clone(),
                    handler: second_route.handler_name.clone(),
                    middleware: second_route.middleware.clone(),
                    parameters: second_route.params.iter().map(|p| ParamDef {
                        name: p.name.clone(),
                        param_type: p.param_type.clone(),
                        required: p.required,
                        constraints: vec![],
                    }).collect(),
                };
                
                conflicts.push(RouteConflict {
                    route1,
                    route2,
                    conflict_type: ConflictType::Exact,
                    resolution_suggestions: vec![
                        ConflictResolution::DifferentControllerPaths {
                            suggestion: format!("Consider using different base paths for {} and {}", 
                                first_controller, second_controller)
                        }
                    ],
                });
            }
        }

        if conflicts.is_empty() {
            Ok(())
        } else {
            Err(conflicts)
        }
    }

    /// Get metadata for a specific controller
    pub fn get_controller_metadata(&self, name: &str) -> Option<&ControllerMetadata> {
        self.controllers.get(name)
    }

    /// Get all registered controller names
    pub fn get_controller_names(&self) -> Vec<String> {
        self.controllers.keys().cloned().collect()
    }

    /// Get total number of routes across all controllers
    pub fn total_routes(&self) -> usize {
        self.controllers.values()
            .map(|metadata| metadata.routes.len())
            .sum()
    }

    /// Get base path for a controller
    fn get_controller_base_path(&self, controller_name: &str) -> Option<String> {
        self.controllers.get(controller_name)
            .map(|metadata| metadata.base_path.clone())
    }

    /// Combine base path and route path
    fn combine_paths(&self, base: &str, route: &str) -> String {
        let base = base.trim_end_matches('/');
        let route = route.trim_start_matches('/');

        let path = if route.is_empty() {
            base.to_string()
        } else if base.is_empty() {
            format!("/{}", route)
        } else {
            format!("{}/{}", base, route)
        };

        // Ensure path is never empty to prevent Axum panics
        if path.is_empty() {
            "/".to_string()
        } else {
            path
        }
    }

}

/// Convert from existing ControllerRoute to our RouteMetadata
impl From<ControllerRoute> for RouteMetadata {
    fn from(route: ControllerRoute) -> Self {
        Self {
            method: route.method,
            path: route.path,
            handler_name: route.handler_name,
            middleware: route.middleware,
            params: route.params.into_iter().map(|p| ParamMetadata {
                name: p.name,
                param_type: format!("{:?}", p.param_type), // Convert enum to string
                required: p.required,
                default: p.default,
            }).collect(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_controller_registry_creation() {
        let container = Arc::new(IocContainer::new());
        let registry = ControllerRegistry::new(container);
        
        assert_eq!(registry.get_controller_names().len(), 0);
        assert_eq!(registry.total_routes(), 0);
    }

    #[test]
    fn test_route_conflict_detection() {
        let container = Arc::new(IocContainer::new());
        let registry = ControllerRegistry::new(container);
        
        // Empty registry should have no conflicts
        assert!(registry.validate_routes().is_ok());
    }

    #[test]
    fn test_controller_metadata_conversion() {
        use crate::controller::{ControllerRoute, RouteParam};
        use crate::routing::params::ParamType;
        
        let controller_route = ControllerRoute {
            method: HttpMethod::GET,
            path: "/test".to_string(),
            handler_name: "test_handler".to_string(),
            middleware: vec!["auth".to_string()],
            params: vec![RouteParam {
                name: "id".to_string(),
                param_type: ParamType::Integer,
                required: true,
                default: None,
            }],
        };

        let route_metadata: RouteMetadata = controller_route.into();
        
        assert_eq!(route_metadata.method, HttpMethod::GET);
        assert_eq!(route_metadata.path, "/test");
        assert_eq!(route_metadata.handler_name, "test_handler");
        assert_eq!(route_metadata.middleware.len(), 1);
        assert_eq!(route_metadata.params.len(), 1);
        assert_eq!(route_metadata.params[0].name, "id");
        assert_eq!(route_metadata.params[0].required, true);
    }
}