ruvel 0.12.0

The laravel alternative framework with rust performance
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
use crate::contracts::support::Responsable;
use crate::http::BoxFuture;
use crate::http::{Method, Middleware, Request, Response, Status};
use crate::routing::pipeline::Pipeline;
use arc_swap::ArcSwap;
use std::borrow::Cow;
use std::collections::HashMap;
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};

use super::into_middleware::{IntoMiddleware, MiddlewareItem};
use super::pending_resource_registrar::PendingResourceRegistration;
use super::pending_route_registrar::PendingRouteRegistrar;
pub use super::route::HandlerFn;
use super::route::{FxHashMap, MethodSlots, ParamBuf, Route, Segment, parse_param_name};
use super::route_registrar::RouteRegistrar;
use crate::http::Controller;

type MiddlewareList = Vec<Arc<dyn Middleware>>;
type MiddlewareGroupMap = HashMap<String, MiddlewareList>;
type MiddlewareAliasMap = HashMap<String, Arc<dyn Middleware>>;

#[derive(Clone)]
pub struct Router {
    static_routes: FxHashMap<Box<str>, MethodSlots>,
    routes: Segment,
    middlewares: Arc<RwLock<MiddlewareList>>,
    middleware_groups: Arc<RwLock<MiddlewareGroupMap>>,
    aliases: Arc<RwLock<MiddlewareAliasMap>>,

    // Cached 404 Fallback and 501 Not Implemented chains with pre-composed global middleware
    fallback_handler: HandlerFn,
    fallback_chain: Arc<ArcSwap<HandlerFn>>,
    not_implemented_handler: HandlerFn,
    not_implemented_chain: Arc<ArcSwap<HandlerFn>>,
    has_global_middlewares: Arc<AtomicBool>,
}

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

impl Router {
    pub fn new() -> Self {
        // Allocate the 404 and 501 handlers ONCE at application boot
        let fallback_handler: HandlerFn = Arc::new(|_req| {
            Box::pin(async {
                Response::with_body(
                    Status::NotFound,
                    "text/plain; charset=utf-8",
                    b"404 Not Found".to_vec(),
                )
            })
        });
        let fallback_chain = Arc::new(ArcSwap::from_pointee(Arc::clone(&fallback_handler)));

        let not_implemented_handler: HandlerFn = Arc::new(|_req| {
            Box::pin(async {
                Response::with_body(
                    Status::NotImplemented,
                    "text/plain; charset=utf-8",
                    b"501 Not Implemented".to_vec(),
                )
            })
        });
        let not_implemented_chain =
            Arc::new(ArcSwap::from_pointee(Arc::clone(&not_implemented_handler)));

        Self {
            static_routes: FxHashMap::default(),
            routes: Segment::new(),
            middlewares: Arc::new(RwLock::new(Vec::new())),
            middleware_groups: Arc::new(RwLock::new(HashMap::new())),
            aliases: Arc::new(RwLock::new(HashMap::new())),
            fallback_handler,
            fallback_chain,
            not_implemented_handler,
            not_implemented_chain,
            has_global_middlewares: Arc::new(AtomicBool::new(false)),
        }
    }

    fn rebuild_fallback_chain(&self, global: &[Arc<dyn Middleware>]) {
        if global.is_empty() {
            self.fallback_chain
                .store(Arc::new(Arc::clone(&self.fallback_handler)));
            self.not_implemented_chain
                .store(Arc::new(Arc::clone(&self.not_implemented_handler)));
            self.has_global_middlewares.store(false, Ordering::Release);
        } else {
            let fallback_chain = Pipeline::new()
                .append(global.iter().cloned())
                .compose(Arc::clone(&self.fallback_handler));
            self.fallback_chain.store(Arc::new(fallback_chain));

            let not_implemented_chain = Pipeline::new()
                .append(global.iter().cloned())
                .compose(Arc::clone(&self.not_implemented_handler));
            self.not_implemented_chain
                .store(Arc::new(not_implemented_chain));

            self.has_global_middlewares.store(true, Ordering::Release);
        }
    }

    /// Set global middlewares on the router.
    pub fn set_middlewares(&self, global: Vec<Arc<dyn Middleware>>) {
        let mut guard = self.middlewares.write().unwrap();
        *guard = global;
        self.rebuild_fallback_chain(&guard);
    }

    /// Set route middleware groups on the router.
    pub fn set_middleware_groups(&self, groups: HashMap<String, Vec<Arc<dyn Middleware>>>) {
        *self.middleware_groups.write().unwrap() = groups;
    }

    /// Set route middleware aliases on the router.
    pub fn set_middleware_aliases(&self, aliases: HashMap<String, Arc<dyn Middleware>>) {
        *self.aliases.write().unwrap() = aliases;
    }

    /// Install global middleware, groups, and aliases from application configuration.
    pub fn install_middleware(
        &self,
        global: Vec<Arc<dyn Middleware>>,
        groups: HashMap<String, Vec<Arc<dyn Middleware>>>,
        aliases: HashMap<String, Arc<dyn Middleware>>,
    ) {
        {
            let mut guard = self.middlewares.write().unwrap();
            *guard = global;
            self.rebuild_fallback_chain(&guard);
        }
        *self.middleware_groups.write().unwrap() = groups;
        *self.aliases.write().unwrap() = aliases;
    }

    /// Check whether a middleware group is registered on the router.
    pub fn has_middleware_group(&self, name: &str) -> bool {
        self.middleware_groups.read().unwrap().contains_key(name)
    }

    /// Check whether a middleware alias is registered on the router.
    pub fn has_middleware_alias(&self, name: &str) -> bool {
        self.aliases.read().unwrap().contains_key(name)
    }

    #[allow(dead_code)]
    pub(crate) fn insert_route(&mut self, method: Method, path: &str, route: Route) {
        self.insert_route_arc(&[method], path, Arc::new(route));
    }

    pub(crate) fn insert_route_for_methods(
        &mut self,
        methods: &[Method],
        path: &str,
        route: Route,
    ) {
        if methods.is_empty() {
            return;
        }
        self.insert_route_arc(methods, path, Arc::new(route));
    }

    fn insert_route_arc(&mut self, methods: &[Method], path: &str, route: Arc<Route>) {
        let trimmed = path.trim_matches('/');

        if trimmed.is_empty() {
            let slots = self.static_routes.entry(Box::from("")).or_default();
            for method in methods {
                slots.insert(method.clone(), Arc::clone(&route));
                self.routes
                    .insert_arc(method.clone(), &[], Arc::clone(&route));
            }
            return;
        }

        let segments: Vec<&str> = trimmed.split('/').filter(|s| !s.is_empty()).collect();
        let is_static = segments.iter().all(|s| parse_param_name(s).is_none());

        if is_static {
            let key: Box<str> = if !trimmed.contains("//") {
                Box::from(trimmed)
            } else {
                Box::from(segments.join("/"))
            };
            let slots = self.static_routes.entry(key).or_default();
            for method in methods {
                slots.insert(method.clone(), Arc::clone(&route));
            }
        }

        for method in methods {
            self.routes
                .insert_arc(method.clone(), &segments, Arc::clone(&route));
        }
    }

    /// Pre-compiles and resolves all middlewares (global + route-specific) into a [`Pipeline`] at registration time.
    pub(crate) fn compile_route_middlewares(
        &self,
        local_items: &[MiddlewareItem],
        excluded_aliases: &[String],
    ) -> Pipeline {
        let mut pipeline = Pipeline::new();

        // 1. Append global middlewares from the router
        let global = self.middlewares.read().unwrap();
        if !global.is_empty() {
            pipeline = pipeline.append(global.iter().cloned());
        }

        // 2. Local route-specific middleware (aliases, groups, or direct instances)
        for item in local_items {
            pipeline = self.resolve_middleware_item(pipeline, item, excluded_aliases);
        }

        pipeline
    }

    fn resolve_middleware_item(
        &self,
        mut pipeline: Pipeline,
        item: &MiddlewareItem,
        excluded_aliases: &[String],
    ) -> Pipeline {
        match item {
            MiddlewareItem::Alias(name) => {
                if excluded_aliases.contains(name) {
                    return pipeline;
                }
                let aliases = self.aliases.read().unwrap();
                if let Some(alias) = aliases.get(name) {
                    pipeline = pipeline.pipe(Arc::clone(alias));
                    return pipeline;
                }
                let groups = self.middleware_groups.read().unwrap();
                if let Some(group) = groups.get(name) {
                    pipeline = pipeline.append(group.iter().cloned());
                } else {
                    panic!("Unknown middleware [{name}]");
                }
            }
            MiddlewareItem::Instance(instance) => {
                pipeline = pipeline.pipe(Arc::clone(instance));
            }
        }
        pipeline
    }

    /// Register routes defined within the closure, passing `&mut Router` directly.
    pub fn group(&mut self, configure: impl FnOnce(&mut Self)) {
        configure(self);
    }

    pub fn get<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::get(self, path, handler)
    }

    pub fn post<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::post(self, path, handler)
    }

    pub fn put<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::put(self, path, handler)
    }

    pub fn patch<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::patch(self, path, handler)
    }

    pub fn delete<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::delete(self, path, handler)
    }

    pub fn head<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::head(self, path, handler)
    }

    pub fn options<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::options(self, path, handler)
    }

    pub fn trace<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::trace(self, path, handler)
    }

    pub fn connect<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::connect(self, path, handler)
    }

    pub fn any<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::any(self, path, handler)
    }

    pub fn r#match<F, Fut, R>(
        &mut self,
        methods: &[Method],
        path: &str,
        handler: F,
    ) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        <Self as RouteRegistrar>::r#match(self, methods, path, handler)
    }

    pub fn domain(&mut self, domain: impl Into<String>) -> PendingRouteRegistrar<'_> {
        <Self as RouteRegistrar>::domain(self, domain)
    }

    pub fn prefix(&mut self, prefix: impl Into<String>) -> PendingRouteRegistrar<'_> {
        <Self as RouteRegistrar>::prefix(self, prefix)
    }

    pub fn name(&mut self, name: impl Into<String>) -> PendingRouteRegistrar<'_> {
        <Self as RouteRegistrar>::name(self, name)
    }

    pub fn middleware(&mut self, middleware: impl IntoMiddleware) -> PendingRouteRegistrar<'_> {
        <Self as RouteRegistrar>::middleware(self, middleware)
    }

    pub fn without_middleware(
        &mut self,
        middleware: impl IntoMiddleware,
    ) -> PendingRouteRegistrar<'_> {
        <Self as RouteRegistrar>::without_middleware(self, middleware)
    }

    pub fn resource<C: Controller + 'static>(
        &mut self,
        name: &str,
        controller: C,
    ) -> PendingResourceRegistration<'_> {
        <Self as RouteRegistrar>::resource(self, name, controller)
    }

    pub fn api_resource<C: Controller + 'static>(
        &mut self,
        name: &str,
        controller: C,
    ) -> PendingResourceRegistration<'_> {
        <Self as RouteRegistrar>::api_resource(self, name, controller)
    }

    pub fn dispatch(&self, mut req: Request) -> BoxFuture<'static, Response> {
        let trimmed = req.path.trim_matches('/');

        // Tier 1: O(1) static fast-path. If the path exists in the static map for another method,
        // fall through to the trie so dynamic parameter routes can still match.
        if let Some(slots) = self.static_routes.get(trimmed)
            && let Some(route) = slots.get(&req.method)
        {
            return (route.chain)(req);
        }

        // Tier 2: Segment trie lookup on `&str` slices with a stack-allocated parameter buffer.
        let mut params = ParamBuf::new();
        if let Some(route) = self.routes.lookup(&req.method, trimmed, &mut params) {
            for &(key, value) in params.as_slice() {
                req.params
                    .insert(Cow::Borrowed(key), Cow::Owned(value.to_owned()));
            }
            return (route.chain)(req);
        }

        // Unrecognized HTTP method not matched by any route: 501 Not Implemented (RFC 9110 §9.1).
        if matches!(req.method, Method::Unknown(_)) {
            if !self.has_global_middlewares.load(Ordering::Acquire) {
                return (self.not_implemented_handler)(req);
            }
            let guard = self.not_implemented_chain.load();
            return (***guard)(req);
        }

        // Known method missed, but path exists for other methods: 405 Method Not Allowed + Allow.
        let mut allowed = Vec::new();
        self.routes.collect_allowed_methods(trimmed, &mut allowed);
        if !allowed.is_empty() {
            let allow_header = allowed.join(", ");
            let handler: HandlerFn = Arc::new(move |_req| {
                let allow_header = allow_header.clone();
                Box::pin(async move {
                    Response::with_body(
                        Status::MethodNotAllowed,
                        "text/plain; charset=utf-8",
                        b"405 Method Not Allowed".to_vec(),
                    )
                    .header("Allow", allow_header)
                })
            });
            if !self.has_global_middlewares.load(Ordering::Acquire) {
                return handler(req);
            }
            let global = { self.middlewares.read().unwrap().clone() };
            let chain = Pipeline::new().append(global).compose(handler);
            return chain(req);
        }

        // 404 fallback: avoid ArcSwap load overhead when no global middleware is registered.
        if !self.has_global_middlewares.load(Ordering::Acquire) {
            return (self.fallback_handler)(req);
        }
        let guard = self.fallback_chain.load();
        (***guard)(req)
    }
}

impl RouteRegistrar for Router {
    fn get<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).get(path, handler)
    }

    fn post<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).post(path, handler)
    }

    fn put<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).put(path, handler)
    }

    fn patch<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).patch(path, handler)
    }

    fn delete<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).delete(path, handler)
    }

    fn head<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).head(path, handler)
    }

    fn options<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).options(path, handler)
    }

    fn trace<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).trace(path, handler)
    }

    fn connect<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).connect(path, handler)
    }

    fn any<F, Fut, R>(&mut self, path: &str, handler: F) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).any(path, handler)
    }

    fn r#match<F, Fut, R>(
        &mut self,
        methods: &[Method],
        path: &str,
        handler: F,
    ) -> PendingRouteRegistrar<'_>
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = R> + Send + 'static,
        R: Responsable,
    {
        PendingRouteRegistrar::new(self).r#match(methods, path, handler)
    }

    fn domain(&mut self, domain: impl Into<String>) -> PendingRouteRegistrar<'_> {
        PendingRouteRegistrar::new(self).domain(domain)
    }

    fn prefix(&mut self, prefix: impl Into<String>) -> PendingRouteRegistrar<'_> {
        PendingRouteRegistrar::new(self).prefix(prefix)
    }

    fn name(&mut self, name: impl Into<String>) -> PendingRouteRegistrar<'_> {
        PendingRouteRegistrar::new(self).name(name)
    }

    fn middleware(&mut self, middleware: impl IntoMiddleware) -> PendingRouteRegistrar<'_> {
        PendingRouteRegistrar::new(self).middleware(middleware)
    }

    fn without_middleware(&mut self, middleware: impl IntoMiddleware) -> PendingRouteRegistrar<'_> {
        PendingRouteRegistrar::new(self).without_middleware(middleware)
    }

    fn resource<C: Controller + 'static>(
        &mut self,
        name: &str,
        controller: C,
    ) -> PendingResourceRegistration<'_> {
        PendingResourceRegistration::new(
            self,
            name,
            controller,
            None,
            None,
            None,
            Vec::new(),
            Vec::new(),
            HashMap::new(),
        )
    }
}