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
//! Route-registration methods for [`ServerRouter`].
//!
//! Covers function routes, handler routes, named routes, ViewSets,
//! endpoint-trait registration, class-based views, and per-route
//! middleware attachment.
use super::ServerRouter;
use super::handlers::FunctionHandler;
use super::types::{FunctionRoute, ViewRoute};
use crate::routers::Route;
use hyper::Method;
use reinhardt_core::endpoint::EndpointInfo;
use reinhardt_http::{Handler, Request, Response, Result};
use reinhardt_middleware::Middleware;
#[cfg(feature = "viewsets")]
use reinhardt_views::viewsets::ViewSet;
use std::sync::Arc;
impl ServerRouter {
/// Register a function-based route (FastAPI-style)
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// use hyper::Method;
/// # use reinhardt_http::{Request, Response, Result};
///
/// async fn health_check(_req: Request) -> Result<Response> {
/// Ok(Response::ok())
/// }
///
/// let router = ServerRouter::new()
/// .function("/health", Method::GET, health_check);
/// ```
pub fn function<F, Fut>(mut self, path: &str, method: Method, func: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<Response>> + Send + 'static,
{
let handler = Arc::new(FunctionHandler { func });
self.functions.push(FunctionRoute {
path: path.to_string(),
method,
handler,
name: None,
middleware: Vec::new(),
});
self
}
/// Register a route with a Handler trait implementation and HTTP method
///
/// This method accepts a type that implements the `Handler` trait,
/// allowing for stateful handlers and a more object-oriented approach.
/// Unlike `handler()`, this method requires specifying an HTTP method.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// use hyper::Method;
/// use reinhardt_http::{Request, Response, Result};
/// use reinhardt_http::Handler;
/// use async_trait::async_trait;
///
/// #[derive(Clone)]
/// struct ArticleHandler;
///
/// #[async_trait]
/// impl Handler for ArticleHandler {
/// async fn handle(&self, _request: Request) -> Result<Response> {
/// Ok(Response::ok())
/// }
/// }
///
/// let router = ServerRouter::new()
/// .handler_with_method("/articles", Method::GET, ArticleHandler);
/// ```
pub fn handler_with_method<H: Handler + 'static>(
mut self,
path: &str,
method: Method,
handler: H,
) -> Self {
self.functions.push(FunctionRoute {
path: path.to_string(),
method,
handler: Arc::new(handler),
name: None,
middleware: Vec::new(),
});
self
}
/// Register a route (alias for `function`)
///
/// This method is an alias for `function` and provides the same functionality.
/// Use it when you prefer the `route` naming convention.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// use hyper::Method;
/// # use reinhardt_http::{Request, Response, Result};
///
/// async fn health_check(_req: Request) -> Result<Response> {
/// Ok(Response::ok())
/// }
///
/// let router = ServerRouter::new()
/// .route("/health", Method::GET, health_check);
/// ```
#[inline]
pub fn route<F, Fut>(self, path: &str, method: Method, func: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<Response>> + Send + 'static,
{
self.function(path, method, func)
}
/// Register a named function-based route (FastAPI-style with URL reversal)
///
/// # Examples
///
/// ```rust
/// use reinhardt_urls::routers::ServerRouter;
/// use hyper::Method;
/// # use reinhardt_http::{Request, Response, Result};
///
/// # async fn health_check(_req: Request) -> Result<Response> {
/// # Ok(Response::ok())
/// # }
/// let mut router = ServerRouter::new()
/// .with_namespace("api")
/// .function_named("/health", Method::GET, "health", health_check);
///
/// router.register_all_routes();
/// let url = router.reverse("api:health", &[]).unwrap();
/// assert_eq!(url, "/health");
/// ```
#[deprecated(
since = "0.2.0",
note = "Use `#[get(\"/path\", name = \"name\")]` + `.endpoint()` instead"
)]
pub fn function_named<F, Fut>(mut self, path: &str, method: Method, name: &str, func: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<Response>> + Send + 'static,
{
let handler = Arc::new(FunctionHandler { func });
self.functions.push(FunctionRoute {
path: path.to_string(),
method,
handler,
name: Some(name.to_string()),
middleware: Vec::new(),
});
self
}
/// Register a named route with a Handler trait implementation and HTTP method
///
/// This method accepts a type that implements the `Handler` trait,
/// allowing for stateful handlers with URL reversal support.
///
/// # Examples
///
/// ```rust
/// use reinhardt_urls::routers::ServerRouter;
/// use hyper::Method;
/// use reinhardt_http::{Request, Response, Result};
/// use reinhardt_http::Handler;
/// use async_trait::async_trait;
///
/// #[derive(Clone)]
/// struct ArticleHandler;
///
/// #[async_trait]
/// impl Handler for ArticleHandler {
/// async fn handle(&self, _request: Request) -> Result<Response> {
/// Ok(Response::ok())
/// }
/// }
///
/// let mut router = ServerRouter::new()
/// .with_namespace("api")
/// .handler_with_method_named("/articles", Method::GET, "list_articles", ArticleHandler);
///
/// router.register_all_routes();
/// let url = router.reverse("api:list_articles", &[]).unwrap();
/// assert_eq!(url, "/articles");
/// ```
#[deprecated(
since = "0.2.0",
note = "Use `#[get(\"/path\", name = \"name\")]` + `.endpoint()` instead"
)]
pub fn handler_with_method_named<H: Handler + 'static>(
mut self,
path: &str,
method: Method,
name: &str,
handler: H,
) -> Self {
self.functions.push(FunctionRoute {
path: path.to_string(),
method,
handler: Arc::new(handler),
name: Some(name.to_string()),
middleware: Vec::new(),
});
self
}
/// Register a named route (alias for `function_named`)
///
/// This method is an alias for `function_named` and provides the same functionality.
/// Use it when you prefer the `route` naming convention.
///
/// # Examples
///
/// ```rust
/// use reinhardt_urls::routers::ServerRouter;
/// use hyper::Method;
/// # use reinhardt_http::{Request, Response, Result};
///
/// # async fn health_check(_req: Request) -> Result<Response> {
/// # Ok(Response::ok())
/// # }
/// let mut router = ServerRouter::new()
/// .with_namespace("api")
/// .route_named("/health", Method::GET, "health", health_check);
///
/// router.register_all_routes();
/// let url = router.reverse("api:health", &[]).unwrap();
/// assert_eq!(url, "/health");
/// ```
#[deprecated(
since = "0.2.0",
note = "Use `#[get(\"/path\", name = \"name\")]` + `.endpoint()` instead"
)]
#[inline]
pub fn route_named<F, Fut>(self, path: &str, method: Method, name: &str, func: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<Response>> + Send + 'static,
{
#[allow(deprecated)]
self.function_named(path, method, name, func)
}
/// Register a ViewSet (DRF-style)
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// # use reinhardt_views::viewsets::ViewSet;
/// # use async_trait::async_trait;
/// # struct UserViewSet;
/// # #[async_trait]
/// # impl ViewSet for UserViewSet {
/// # fn get_basename(&self) -> &str { "users" }
/// # async fn dispatch(&self, _req: reinhardt_http::Request, _action: reinhardt_views::viewsets::Action)
/// # -> reinhardt_core::exception::Result<reinhardt_http::Response> {
/// # Ok(reinhardt_http::Response::ok())
/// # }
/// # }
///
/// let router = ServerRouter::new()
/// .viewset("/users", UserViewSet);
/// ```
#[cfg(feature = "viewsets")]
pub fn viewset<V: ViewSet + 'static>(mut self, prefix: &str, viewset: V) -> Self {
self.viewsets.insert(prefix.to_string(), Arc::new(viewset));
self
}
/// Same as [`Self::viewset`] at runtime, but carries a `PhantomData<M>`
/// marker that the route resolver machinery recovers at expansion time
/// to discover `#[action]`-decorated methods on the impl block `M`.
///
/// `M` is purely a name-bearing token. Users write
/// `PhantomData::<MyViewSetImpl>` as the third argument. The bound is
/// `M: 'static` so the marker's `std::any::type_name` is reachable for
/// the marker→runtime bridge below.
///
/// Phase 5.1 of Issue #4507: in addition to delegating to [`Self::viewset`],
/// this method calls [`reinhardt_views::viewsets::bridge_marker_actions_to_viewset`]
/// to copy every action submitted under `type_name::<M>()` into the
/// runtime-keyed `register_action(type_name::<V>(), ...)` slot, so the
/// dispatcher's [`ViewSet::get_extra_actions`] lookup finds them under
/// the concrete ViewSet's type name (not the marker's).
///
/// The marker-keyed submissions themselves are produced by a
/// `#[ctor::ctor]` startup function emitted by `#[viewset(basename =
/// "...")] impl M { #[action(...)] fn ... }` (the `ctor` path is the
/// production registration mechanism today; the helper additionally
/// drains an `inventory` collection for forward-compatibility once
/// `const_type_name` stabilizes and `inventory::submit!` becomes usable
/// for marker-keyed registrations). Because `#[ctor]` runs at process
/// startup on non-wasm targets, the marker bridge is a no-op on wasm
/// (gated by `#[cfg(not(target_family = "wasm"))]` at the emitter site).
///
/// Refs Issue #4507.
#[cfg(feature = "viewsets")]
pub fn viewset_with_actions<V, M>(
self,
prefix: &str,
viewset: V,
_marker: std::marker::PhantomData<M>,
) -> Self
where
V: reinhardt_views::viewsets::ViewSet + 'static,
M: 'static,
{
reinhardt_views::viewsets::bridge_marker_actions_to_viewset(
std::any::type_name::<M>(),
std::any::type_name::<V>(),
);
self.viewset(prefix, viewset)
}
/// Register an endpoint using EndpointInfo trait
///
/// This method accepts a factory function that returns a View type implementing
/// both `EndpointInfo` and `Handler` traits. The path, HTTP method, and name
/// are automatically extracted from the `EndpointInfo` implementation.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// # use reinhardt_core::endpoint::EndpointInfo;
/// # use reinhardt_http::{Handler, Request, Response};
/// # use hyper::Method;
/// # struct ListUsers;
/// # impl EndpointInfo for ListUsers {
/// # fn path() -> &'static str { "/users" }
/// # fn method() -> Method { Method::GET }
/// # fn name() -> &'static str { "list_users" }
/// # }
/// # #[async_trait::async_trait]
/// # impl Handler for ListUsers {
/// # async fn handle(&self, _req: Request) -> Result<Response, reinhardt_http::Error> {
/// # Ok(Response::ok())
/// # }
/// # }
/// # fn list_users() -> ListUsers { ListUsers }
///
/// // Pass the function directly (no () needed)
/// let router = ServerRouter::new()
/// .endpoint(list_users);
/// ```
pub fn endpoint<F, E>(mut self, f: F) -> Self
where
F: FnOnce() -> E,
E: EndpointInfo + Handler + 'static,
{
let view = f();
let path = E::path().to_string();
let method = E::method();
let name = E::name().to_string();
self.functions.push(FunctionRoute {
path,
method,
handler: Arc::new(view),
name: Some(name),
middleware: Vec::new(),
});
self
}
/// Register a class-based view (Django-style)
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// # use reinhardt_http::{Handler, {Request, Response, Result}};
/// # use async_trait::async_trait;
/// # struct ArticleListView;
/// # #[async_trait]
/// # impl Handler for ArticleListView {
/// # async fn handle(&self, _req: Request) -> Result<Response> {
/// # Ok(Response::ok())
/// # }
/// # }
///
/// let view = ArticleListView;
/// let router = ServerRouter::new()
/// .view("/articles", view);
/// ```
pub fn view<V>(mut self, path: &str, view: V) -> Self
where
V: Handler + 'static,
{
self.views.push(ViewRoute {
path: path.to_string(),
handler: Arc::new(view),
name: None,
middleware: Vec::new(),
});
self
}
/// Register a named class-based view (Django-style with URL reversal)
///
/// # Examples
///
/// ```rust
/// use reinhardt_urls::routers::ServerRouter;
/// # use reinhardt_http::{Handler, {Request, Response, Result}};
/// # use async_trait::async_trait;
/// # struct ArticleListView;
/// # #[async_trait]
/// # impl Handler for ArticleListView {
/// # async fn handle(&self, _req: Request) -> Result<Response> {
/// # Ok(Response::ok())
/// # }
/// # }
///
/// let view = ArticleListView;
/// let mut router = ServerRouter::new()
/// .with_namespace("articles")
/// .view_named("/articles", "list", view);
///
/// router.register_all_routes();
/// let url = router.reverse("articles:list", &[]).unwrap();
/// assert_eq!(url, "/articles");
/// ```
#[deprecated(
since = "0.2.0",
note = "Use `#[get(\"/path\", name = \"name\")]` + `.endpoint()` instead"
)]
pub fn view_named<V>(mut self, path: &str, name: &str, view: V) -> Self
where
V: Handler + 'static,
{
self.views.push(ViewRoute {
path: path.to_string(),
handler: Arc::new(view),
name: Some(name.to_string()),
middleware: Vec::new(),
});
self
}
/// Register a handler directly (recommended method)
///
/// This method allows you to pass a handler directly without wrapping it in `Arc`.
/// The `Arc` wrapping is handled internally for you.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// # use reinhardt_http::{Handler, {Request, Response, Result}};
/// # use async_trait::async_trait;
/// # struct CustomHandler;
/// # #[async_trait]
/// # impl Handler for CustomHandler {
/// # async fn handle(&self, _req: Request) -> Result<Response> {
/// # Ok(Response::ok())
/// # }
/// # }
///
/// // No Arc::new() needed!
/// let router = ServerRouter::new()
/// .handler("/custom", CustomHandler);
/// ```
pub fn handler<H>(mut self, path: &str, handler: H) -> Self
where
H: Handler + 'static,
{
let route = Route::from_handler(path, handler);
self.routes.push(route);
self
}
/// Register a handler that is already wrapped in Arc (low-level API)
///
/// This is provided for cases where you already have an `Arc<dyn Handler>`.
/// In most cases, you should use `handler()` instead.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// # use reinhardt_http::{Handler, {Request, Response, Result}};
/// # use async_trait::async_trait;
/// # use std::sync::Arc;
/// # struct CustomHandler;
/// # #[async_trait]
/// # impl Handler for CustomHandler {
/// # async fn handle(&self, _req: Request) -> Result<Response> {
/// # Ok(Response::ok())
/// # }
/// # }
///
/// let handler = Arc::new(CustomHandler);
/// let router = ServerRouter::new()
/// .handler_arc("/custom", handler);
/// ```
pub fn handler_arc(mut self, path: &str, handler: Arc<dyn Handler>) -> Self {
let route = Route::new(path, handler);
self.routes.push(route);
self
}
/// Add middleware to the last registered function route
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_urls::routers::ServerRouter;
/// use reinhardt_middleware::LoggingMiddleware;
/// use hyper::Method;
/// # use reinhardt_http::{Request, Response, Result};
///
/// # async fn health(_req: Request) -> Result<Response> {
/// # Ok(Response::ok())
/// # }
/// let router = ServerRouter::new()
/// .function("/health", Method::GET, health)
/// .with_route_middleware(LoggingMiddleware::new());
/// ```
pub fn with_route_middleware<M: Middleware + 'static>(mut self, middleware: M) -> Self {
let middleware = Arc::new(middleware);
if let Some(route) = self.functions.last_mut() {
route.middleware.push(middleware.clone());
} else if let Some(route) = self.views.last_mut() {
route.middleware.push(middleware.clone());
} else if let Some(route) = self.routes.last_mut() {
route.middleware.push(middleware);
}
self
}
}
#[cfg(all(test, feature = "viewsets"))]
mod viewset_with_actions_tests {
use super::*;
use async_trait::async_trait;
use reinhardt_http::{Request, Response, Result};
use reinhardt_views::viewsets::{Action, ViewSet};
use rstest::rstest;
use std::marker::PhantomData;
/// Minimal `ViewSet` fixture for parity tests between `viewset` and
/// `viewset_with_actions`. The dispatch body is irrelevant — these tests
/// only inspect what routes get registered.
#[derive(Debug, Clone)]
struct DummyViewSet {
basename: String,
}
#[async_trait]
impl ViewSet for DummyViewSet {
fn get_basename(&self) -> &str {
&self.basename
}
async fn dispatch(&self, _request: Request, _action: Action) -> Result<Response> {
Ok(Response::ok())
}
}
/// Marker type the route resolver machinery recovers at expansion
/// time. It carries no runtime state.
struct DummyImpl;
#[rstest]
fn viewset_with_actions_is_equivalent_to_viewset() {
// Arrange
let mut router_a = ServerRouter::new().viewset(
"/users",
DummyViewSet {
basename: "users".to_string(),
},
);
let mut router_b = ServerRouter::new().viewset_with_actions(
"/users",
DummyViewSet {
basename: "users".to_string(),
},
PhantomData::<DummyImpl>,
);
// Act
let _ = router_a.register_all_routes();
let _ = router_b.register_all_routes();
let routes_a = router_a.get_all_routes();
let routes_b = router_b.get_all_routes();
// Assert
assert_eq!(routes_a, routes_b);
}
}