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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
use crate::core::logger::log_request_summary;
use crate::protocol::form::FormData;
use crate::protocol::request::{HttpMethod, Request};
use crate::protocol::response::Response;
use crate::routing::file_system::FILE_ROUTING_REGISTRY;
use crate::security::cookies::CookieJar;
use crate::security::errors::{GlobalErrorHandler, ShieldError, default_framework_error_handler};
use crate::security::jwt::Claims;
use crate::security::middleware::{
AfterRequestHook, Middleware, MiddlewareResult, MiddlewareState,
};
use crate::security::session::{Session, SessionStore};
use crate::security::telemetry::SystemTelemetry;
use crate::security::xss::{Sanitizer, UntrustedString};
use futures::future::{BoxFuture, FutureExt};
use lazy_static::lazy_static;
use sea_orm::DatabaseConnection;
use std::collections::HashMap;
use std::fs;
use std::future::Future;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::Path;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;
pub type BoxedResponse = BoxFuture<'static, Response>;
pub type Handler = fn(RequestContext) -> BoxedResponse;
/// Short representation for handlers that can fail safely with an explicit framework error
pub type ShieldResult<T> = Result<T, ShieldError>;
pub trait IntoResponse {
fn into_response(self) -> Response;
}
// A standard Response trivially turns into a Response
impl IntoResponse for Response {
fn into_response(self) -> Response {
self
}
}
// Add this blanket implementation to allow pre-boxed trait objects
impl IntoHandler for Box<dyn IntoHandler> {
fn call(&self, ctx: RequestContext) -> BoxedResponse {
// Delegate straight down to the inner trait object inside the box!
self.as_ref().call(ctx)
}
}
// A ShieldResult turns into a Response by catching errors and invoking a fallback
impl IntoResponse for ShieldResult<Response> {
fn into_response(self) -> Response {
match self {
Ok(res) => res,
Err(err) => {
println!(
"[SECURITY AUDIT] Handler caught an explicit framework error: {:?}",
err
);
// Determine status code and message based on the actual error type
let (status, msg_string): (u16, String) = match err {
ShieldError::UnauthorizedAccess => {
(401, "<h1>401 Unauthorized</h1>".to_string())
}
ShieldError::Forbidden => (403, "<h1>403 Forbidden</h1>".to_string()),
ShieldError::NotFound => (404, "<h1>404 Not Found</h1>".to_string()),
ShieldError::BadRequest(err) => {
(400, format!("<h1>400 Bad Request</h1><br/>{}", err))
}
_ => (500, "<h1>500 Internal Security Error</h1>".to_string()),
};
// 2. Pass the final String reference directly into your Sanitizer
Response::new(status, Sanitizer::trust(&msg_string))
}
}
}
}
// Support raw static string slices: &'static str
impl IntoResponse for &'static str {
fn into_response(self) -> Response {
// Automatically wraps the text as an HTML response with a 200 OK status
Response::new(200, Sanitizer::trust(self))
}
}
// Support dynamic heap strings: String
impl IntoResponse for String {
fn into_response(self) -> Response {
Response::new(200, Sanitizer::trust(&self))
}
}
pub trait IntoHandler: Send + Sync + 'static {
fn call(&self, ctx: RequestContext) -> BoxedResponse;
}
impl<F, Fut, R> IntoHandler for F
where
F: Fn(RequestContext) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = R> + Send + 'static,
R: IntoResponse + 'static,
{
fn call(&self, ctx: RequestContext) -> BoxedResponse {
let fut = (self)(ctx);
async move {
let res = fut.await;
res.into_response()
}
.boxed()
}
}
#[derive(Clone, Debug)]
pub struct RequestContext {
pub req: Request,
pub telemetry: SystemTelemetry,
pub params: HashMap<String, UntrustedString>,
pub peer_addr: SocketAddr,
pub headers: HashMap<String, String>,
pub claims: Option<Claims>,
pub query: HashMap<String, UntrustedString>,
pub session: Option<Arc<Mutex<Session>>>,
pub form: FormData,
pub db: Option<Arc<DatabaseConnection>>,
pub raw_body: Vec<u8>,
pub content_type: Option<String>,
pub cookies: Arc<Mutex<CookieJar>>,
pub start_time: std::time::Instant,
pub role_inheritance: Arc<HashMap<String, Vec<String>>>,
}
impl RequestContext {
pub fn new() -> Self {
Self {
req: Request::new(),
telemetry: SystemTelemetry::new(),
params: HashMap::new(),
peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080),
headers: HashMap::new(),
claims: None,
query: HashMap::new(),
session: None,
form: FormData::new(),
db: None,
raw_body: Vec::new(),
content_type: None,
cookies: Arc::new(Mutex::new(CookieJar::new(None, String::new()))),
start_time: std::time::Instant::now(),
role_inheritance: Arc::new(HashMap::new()),
}
}
/// Safely resolves the true client IP address while mitigating IP Spoofing risks
pub fn resolve_client_ip(&self) -> String {
// Look for X-Forwarded-For (injected by downstream edge networks/proxies)
if let Some(forwarded_header) = self.req.headers.get("x-forwarded-for") {
// X-Forwarded-For can look like: "203.0.113.195, 70.41.3.18, 150.172.238.178"
// The very first value on the left is the actual client identity.
if let Some(real_ip) = forwarded_header.split(',').next() {
let trimmed_ip = real_ip.trim();
if !trimmed_ip.is_empty() {
return trimmed_ip.to_string();
}
}
}
// If the header doesn't exist, use the verified physical socket connection IP
// We drop the port number (.ip()) so the token tracks the host computer
self.peer_addr.ip().to_string()
}
pub fn start_session(store: &SessionStore) -> Arc<Mutex<Session>> {
let (ptr, _) = store.get_or_create(None);
ptr
}
/// Returns true if the user's browser sent a session cookie but it was
/// rejected or evicted by the framework because it expired on the server.
pub fn is_session_expired(&self) -> bool {
// If the browser sent a cookie header, but the AuthMiddleware stripped
// it out and left the active context session empty, it means the session expired!
let had_cookie = self
.req
.headers
.get("cookie")
.or_else(|| self.req.headers.get("Cookie"))
.map(|val| val.contains("GSESSION_ID"))
.unwrap_or(false);
had_cookie && self.session.is_none()
}
/// A helper method allowing handlers to cleanly extract JSON data structures
pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, ShieldError> {
let content_type = self.content_type.as_deref().unwrap_or("");
if !content_type.starts_with("application/json") {
return Err(ShieldError::BadRequest(
"Content-Type must be application/json".to_string(),
));
}
serde_json::from_slice(&self.raw_body)
.map_err(|e| ShieldError::BadRequest(format!("Failed to parse JSON body: {}", e)))
}
/// Zero-boilerplate helper to read a standard, unsigned cookie
pub fn get_cookie(&self, name: &str) -> Option<String> {
self.cookies.lock().ok()?.get(name).cloned()
}
/// Handles the Mutex lock internally and yields an immediate Option<String>.
pub fn get_signed_cookie(&self, name: &str) -> Option<String> {
// Lock the internal mutex safely. If it fails, return None.
let jar = self.cookies.lock().ok()?;
// Call the inner CookieJar method
jar.get_signed(name)
}
/// Premium helper to inject or update a cookie directly without manual locking
pub fn set_cookie(&self, cookie: crate::protocol::response::Cookie) {
if let Ok(mut jar) = self.cookies.lock() {
jar.add(cookie);
}
}
/// Premium helper to inject a secure, cryptographically signed cookie
pub fn set_signed_cookie(&self, cookie: crate::protocol::response::Cookie) {
if let Ok(mut jar) = self.cookies.lock() {
jar.add_signed(cookie);
}
}
/// Premium helper to instruct the browser to instantly shred a cookie
pub fn remove_cookie(&self, name: &str) {
if let Ok(mut jar) = self.cookies.lock() {
jar.remove(name);
}
}
/// Write a key-value attribute directly into the active session instance
pub fn set_session_data(&self, key: &str, value: &str) {
if let Some(ref session_arc) = self.session {
if let Ok(mut session) = session_arc.lock() {
session.data.insert(key.to_string(), value.to_string());
}
}
}
/// Read an attribute value out of the active session instance
pub fn get_session_data(&self, key: &str) -> Option<String> {
let session_arc = self.session.as_ref()?;
let session = session_arc.lock().ok()?;
session.data.get(key).cloned()
}
/// Explicitly tag the session as authenticated to a specific User Entity ID
pub fn login_user_id(&self, user_id: &str) {
if let Some(ref session_arc) = self.session {
if let Ok(mut session) = session_arc.lock() {
session.user_id = Some(user_id.to_string());
}
}
}
/// Explicitly check if the current request context belongs to a logged-in user
pub fn is_user_authenticated(&self) -> bool {
self.get_session_data("user_id").is_some()
}
/// Extracts the cached role string natively out of GritShield's hybrid state store.
/// Prioritizes stateful session storage, falling back seamlessly to stateless JWT claims.
pub fn get_user_role(&self) -> Option<String> {
// Check stateful session storage first
if let Some(ref session_arc) = self.session {
if let Ok(session) = session_arc.lock() {
if let Some(role) = session.data.get("role") {
return Some(role.clone());
}
}
}
// Stateless Fallback: Read the role field embedded inside the cryptographically validated JWT
if let Some(ref claims) = self.claims {
return Some(claims.role.clone());
}
None
}
/// Non-blocking check evaluating security roles using hierarchical permissions (Admin, Operator, Auditor) bypassing.
pub fn has_fixed_role(&self, target_role: &str) -> bool {
match self.get_user_role() {
Some(role) => {
// If an exact match is found, allow entry immediately
if role == target_role {
return true;
}
// Hierarchical authorization structure bypass rules
match (role.as_str(), target_role) {
("Admin", _) => true, // Admins bypass all lower operational barriers
("Operator", "Admin") => false,
("Operator", _) => true, // Operators access standard and low tier pathways
("Auditor", "Auditor") => true,
_ => false,
}
}
None => false,
}
}
/// Dynamic recursive tree climber to check if a user role inherits the target role
fn check_inheritance(&self, current_role: &str, target_role: &str) -> bool {
if current_role == target_role {
return true;
}
// Search the map stored natively inside the request context
if let Some(children) = self.role_inheritance.get(current_role) {
for child in children {
if child == target_role || self.check_inheritance(child, target_role) {
return true;
}
}
}
false
}
/// Evaluates BOTH Dynamic Graph Trees AND Fixed System matrices
/// Prioritizes runtime user-defined inheritance graphs first, falling back to core system rules.
pub fn has_role(&self, target_role: &str) -> bool {
// Evaluate against user-defined dynamic runtime configurations first
if let Some(user_role) = self.get_user_role() {
if self.check_inheritance(&user_role, target_role) {
return true;
}
}
// FALLBACK — Check hardcoded framework override rules if dynamic checks yield false
if self.has_fixed_role(target_role) {
return true;
}
false
}
/// Checks if the user has the required role, and if not, returns a Forbidden error
pub fn require_role(&self, target_role: &str) -> ShieldResult<()> {
if self.has_role(target_role) {
Ok(())
} else {
println!(
"\x1b[33m[SECURITY EXCEPTION] Inline unified RBAC guard tripped: Missing role '{}'\x1b[0m",
target_role
);
Err(ShieldError::Forbidden)
}
}
/// Generates or retrieves an existing CSRF token for the active session context.
/// If a session exists but lacks a token, it initializes one on-the-fly dynamically.
pub fn get_csrf_token(&self) -> String {
if let Some(ref session_arc) = self.session {
let mut session = session_arc.lock().unwrap();
// If it exists, return it immediately
if let Some(token) = session.data.get("csrf_token") {
return token.clone();
}
// If the session exists but lacks a token, mint it right now!
let fresh_token = uuid::Uuid::new_v4().to_string();
session
.data
.insert("csrf_token".to_string(), fresh_token.clone());
println!(
"[CSRF KERNEL] Lazy-initialized token on first context read: {}",
fresh_token
);
return fresh_token;
}
// Fallback catch if no session is mounted at all
String::new()
}
/// Safely extracts and decodes a query parameter value by key.
/// Converts hex escape sequences (like %20) back into clean UTF-8 text.
pub fn get_query_param_decoded(&self, key: &str) -> Option<String> {
// Assuming your request object has a query map or parses raw params
// Adjust `self.req.query.get(key)` to match how your Request parser tracks URL params
let raw_val = self.query.get(key)?;
let mut decoded = String::new();
let mut chars = raw_val.as_str().chars();
while let Some(ch) = chars.next() {
if ch == '%' {
// Read the next two characters representing hex digits
let mut hex = String::new();
if let Some(h1) = chars.next() {
hex.push(h1);
}
if let Some(h2) = chars.next() {
hex.push(h2);
}
if let Ok(byte) = u8::from_str_radix(&hex, 16) {
decoded.push(byte as char);
}
} else if ch == '+' {
decoded.push(' '); // Form encoding variant fallback
} else {
decoded.push(ch);
}
}
Some(decoded)
}
}
// The struct that will be globally collected from any file
pub struct AutoRoute {
pub path: &'static str,
pub method: HttpMethod,
pub handler: Handler,
pub required_role: Option<&'static str>,
}
// Tell the compiler to create a tracking registry for AutoRoute elements
inventory::collect!(AutoRoute);
pub struct Node {
pub children: HashMap<String, Node>,
pub is_end: bool,
pub methods: HashMap<HttpMethod, Box<dyn IntoHandler>>,
pub parameter_name: Option<String>,
}
impl Node {
pub fn new() -> Self {
Node {
children: HashMap::new(),
is_end: false,
methods: HashMap::new(),
parameter_name: None,
}
}
}
pub enum RoutingResult<'a> {
Found(&'a dyn IntoHandler, HashMap<String, UntrustedString>),
MethodNotAllowed,
NotFound,
}
pub type AsyncPageFuture = Pin<Box<dyn Future<Output = Response> + Send>>;
pub type PageHandlerFn = fn(RequestContext) -> AsyncPageFuture;
lazy_static! {
pub static ref GLOBAL_FALLBACK: Mutex<Option<PageHandlerFn>> = Mutex::new(None);
}
/// A registration hook your macro or files can call during static initialization
pub fn register_global_fallback(handler: PageHandlerFn) {
if let Ok(mut guard) = GLOBAL_FALLBACK.lock() {
*guard = Some(handler);
}
}
pub struct Router {
root: Node,
pub middlewares: Vec<Box<dyn Middleware>>, // A list of dynamic trait objects
pub db: Option<Arc<DatabaseConnection>>, // An optional database connection
pub after_hooks: Vec<Box<dyn AfterRequestHook>>,
pub use_logger: bool,
pub global_error_handler: GlobalErrorHandler,
pub telemetry: SystemTelemetry,
pub fallback_handler: Option<PageHandlerFn>,
pub role_registry: HashMap<String, &'static str>, // Local thread-safe registry tracking roles mapped to explicit route URL strings
pub role_inheritance: HashMap<String, Vec<String>>,
}
impl Router {
pub fn new() -> Self {
let fallback = if let Ok(guard) = GLOBAL_FALLBACK.lock() {
guard.clone()
} else {
None
};
let mut router = Router {
root: Node::new(),
middlewares: Vec::new(),
db: None,
use_logger: false,
after_hooks: Vec::new(),
global_error_handler: GlobalErrorHandler {
handler: Some(default_framework_error_handler),
},
telemetry: SystemTelemetry::new(),
fallback_handler: fallback,
role_registry: HashMap::new(),
role_inheritance: HashMap::new(),
};
for route in inventory::iter::<AutoRoute> {
println!(
"[AUTO-ROUTING] Registering {} {:?}",
route.path, route.method
);
// Capture role properties globally at framework startup
if let Some(role) = route.required_role {
println!(
"\x1b[33m[RBAC SHIELD] Detected role requirement for path: {} | Required role: {}\x1b[0m",
route.path, role
);
router.role_registry.insert(route.path.to_string(), role);
}
// Route standard mapping execution
router.add_route(route.method, route.path, route.handler);
}
router
}
pub fn mount_db(mut self, db: Arc<DatabaseConnection>) -> Self {
self.db = Some(db);
self
}
/// Premium builder to switch on detailed diagnostic server logs
pub fn mount_logger(mut self) -> Self {
self.use_logger = true;
self
}
pub fn mount(&mut self, route_info: (&str, HttpMethod, Handler)) {
self.add_route(route_info.1, route_info.0, route_info.2);
}
/// Register a global pipeline middleware by moving ownership
pub fn add_middleware(mut self, middleware: impl Middleware + 'static) -> Self {
self.middlewares.push(Box::new(middleware));
self // Return ownership back out to the chain
}
pub fn run_after_hooks(&self, ctx: RequestContext, status: u16, duration: Duration) {
for hook in &self.after_hooks {
hook.call(&ctx, status, duration);
}
}
/// Allows developers to attach a custom layout handler for unmatched 404 routes
pub fn set_fallback(mut self, handler: PageHandlerFn) -> Self {
self.fallback_handler = Some(handler);
self
}
/// Builder method to dynamically define role hierarchies at startup
pub fn add_role_inheritance(mut self, parent: &str, children: Vec<&str>) -> Self {
let child_strings = children.into_iter().map(|s| s.to_string()).collect();
self.role_inheritance
.insert(parent.to_string(), child_strings);
self
}
pub fn run_middlewares(&self, ctx: &mut RequestContext) -> MiddlewareResult {
// Initialize an empty accumulator state packer
let mut accumulated_state = MiddlewareState {
session: None,
claims: None,
session_was_stale: false,
};
for middleware in &self.middlewares {
match middleware.execute(ctx) {
MiddlewareResult::Next(maybe_state) => {
if let Some(state) = maybe_state {
// Merge fields dynamically without overwriting existing ones with None
if state.session.is_some() {
accumulated_state.session = state.session;
}
if state.claims.is_some() {
accumulated_state.claims = state.claims;
}
}
continue;
}
MiddlewareResult::Error(res) => return MiddlewareResult::Error(res),
}
}
// Return the perfectly merged collection of sessions and claims
MiddlewareResult::Next(Some(accumulated_state))
}
pub fn add_route<H>(&mut self, method: HttpMethod, path: &str, handler: H)
where
H: IntoHandler,
{
let mut current = &mut self.root;
for segment in path.split('/').filter(|s| !s.is_empty()) {
current = current
.children
.entry(segment.to_string())
.or_insert(Node::new());
}
current.is_end = true;
current.methods.insert(method, Box::new(handler));
}
pub fn match_route<'a>(&'a self, method: &HttpMethod, path: &str) -> RoutingResult<'a> {
let mut current = &self.root;
let mut params = HashMap::new();
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
for (i, segment) in segments.iter().enumerate() {
if let Some(next_node) = current.children.get(*segment) {
current = next_node;
} else {
// Find any child key that signals a dynamic parameter
let param_match = current
.children
.iter()
.find(|(key, _)| key.starts_with(':'));
if let Some((key, param_node)) = param_match {
// Check if either the map key OR the internal name contains the '*' wildcard flag
let is_wildcard = key.contains('*')
|| param_node
.parameter_name
.as_ref()
.map_or(false, |name| name.contains('*'));
if is_wildcard {
// Grab everything remaining, join it with slashes, and clean the parameter key
let remainder = segments[i..].join("/");
let clean_key = key.trim_start_matches(':').to_string(); // drops ':' to leave '*path'
params.insert(clean_key, UntrustedString::new(remainder));
current = param_node;
break; // 🚀 Break instantly! The wildcard has devoured the rest of the URL path
} else {
// Try the node's explicit property first; if None, fall back to the child map key string!
let clean_key = if let Some(ref name) = param_node.parameter_name {
name.trim_start_matches(':').to_string()
} else {
key.trim_start_matches(':').to_string()
};
// Insert the dynamic slug value safely into our parameters dictionary
params.insert(clean_key, UntrustedString::new(segment.to_string()));
// Advance the tracker node downward to continue evaluating subsequent segments
current = param_node;
}
} else {
return RoutingResult::NotFound;
}
}
}
match current.methods.get(method) {
Some(handler) => RoutingResult::Found(&**handler, params),
None => {
if !current.methods.is_empty() {
RoutingResult::MethodNotAllowed
} else {
RoutingResult::NotFound
}
}
}
}
/// Seamlessly crawls a filesystem folder, computes URL paths,
/// and mounts handlers dynamically.
pub fn mount_file_routes<P: AsRef<Path>>(
mut self,
folder_path: P,
) -> Result<Self, Box<dyn std::error::Error>> {
let base_path = folder_path.as_ref().to_path_buf();
self.crawl_directory(&base_path, &base_path)?;
Ok(self)
}
fn crawl_directory(&mut self, current_dir: &Path, base_dir: &Path) -> std::io::Result<()> {
if current_dir.is_dir() {
for entry in fs::read_dir(current_dir)? {
let entry = entry?;
let path = entry.path();
if path.file_name().map_or(false, |name| name == "404.rs") {
// Skip it! We attach it explicitly as an engine fallback instead
continue;
}
if path.is_dir() {
// Recursively crawl nested folders (e.g., pages/api)
self.crawl_directory(&path, &base_dir)?;
} else if path.is_file() && path.extension().map_or(false, |ext| ext == "rs") {
self.process_page_file(&path, base_dir);
}
}
}
Ok(())
}
fn process_page_file(&mut self, file_path: &Path, base_dir: &Path) {
// 1. Convert filesystem paths to absolute lookup keys
// Example: "src/pages/api/users.rs"
let file_key = file_path.to_string_lossy().replace("\\", "/");
// 2. Compute the dynamic URL Route path
let relative = file_path.strip_prefix(base_dir).unwrap().with_extension("");
let relative_str = relative.to_string_lossy().replace("\\", "/");
let mut url_route = if relative_str == "index" {
"/".to_string()
} else if relative_str.ends_with("/index") {
format!("/{}", relative_str.trim_end_matches("/index"))
} else {
format!("/{}", relative_str)
};
// Converts "docs/[..path]" -> "docs/:*path"
if url_route.contains('[') && url_route.contains(']') {
url_route = url_route
.replace("[..", ":*") // Handles the Next.js catch-all style
.replace("[", ":*") // Fallback for standard dynamic brackets
.replace("]", "");
}
// Converts folder/foo/_path_ to folder/foo/:*path (Alternative layout)
if url_route.contains('_') {
url_route = url_route.replace("_", ":*");
}
// Extract the handler out of our pre-compiled global registry map safely
if let Ok(registry) = FILE_ROUTING_REGISTRY.lock() {
if let Some(registered) = registry.get(&file_key) {
println!(
"[GRITSHIELD FS-ROUTER] Mapping File System Asset: {} ➡️ Route: [{:?}] {}",
file_key, registered.method, url_route
);
let handler_instance = (registered.handler_factory)();
self.add_route(registered.method, &url_route, handler_instance);
} else {
eprintln!(
"[WARN] Discovered file '{}', but no `register_page!` statement was found inside it.",
file_key
);
}
}
}
/// Builder to mount custom post-execution lifecycle hooks
pub fn add_after_hook(mut self, hook: Box<dyn AfterRequestHook>) -> Self {
self.after_hooks.push(hook);
self
}
/// A framework-level diagnostic utility that prints highly optimized operational logs.
pub fn log_lifecycle(&self, ctx: &RequestContext, status: u16, duration: std::time::Duration) {
let session_id_log = ctx.session.as_ref().map(|s| s.lock().unwrap().id.clone());
let jwt_sub_log = ctx.claims.as_ref().map(|c| c.sub.clone());
log_request_summary(&ctx.req, status, duration, session_id_log, jwt_sub_log);
}
}