reinhardt-urls 0.2.2

URL routing and proxy utilities for Reinhardt 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
//! Route Group functionality
//!
//! Provides functionality to group multiple routes and apply middleware to the entire group.

use crate::routers::ServerRouter;
use reinhardt_middleware::Middleware;

/// Route information tuple: (path, name, namespace, methods)
pub type RouteInfo = Vec<(String, Option<String>, Option<String>, Vec<hyper::Method>)>;

/// Route Group
///
/// Groups multiple routes and applies group-level middleware.
///
/// # Examples
///
/// ```
/// use reinhardt_urls::routers::RouteGroup;
/// use reinhardt_urls::routers::ServerRouter;
/// use reinhardt_middleware::LoggingMiddleware;
/// use hyper::Method;
/// # use reinhardt_http::{Request, Response, Result};
///
/// # async fn users_list(_req: Request) -> Result<Response> {
/// #     Ok(Response::ok())
/// # }
/// # async fn users_detail(_req: Request) -> Result<Response> {
/// #     Ok(Response::ok())
/// # }
///
/// let mut group = RouteGroup::new()
///     .with_prefix("/api/v1")
///     .with_middleware(LoggingMiddleware::new());
///
/// let router = group
///     .function("/users", Method::GET, users_list)
///     .function("/users/{id}", Method::GET, users_detail)
///     .build();
///
/// // Verify router configuration
/// assert_eq!(router.prefix(), "/api/v1");
/// ```
pub struct RouteGroup {
	router: ServerRouter,
}

impl RouteGroup {
	/// Create a new route group
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	///
	/// let group = RouteGroup::new();
	/// ```
	pub fn new() -> Self {
		Self {
			router: ServerRouter::new(),
		}
	}

	/// Set prefix
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	///
	/// let group = RouteGroup::new()
	///     .with_prefix("/api/v1");
	/// ```
	pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
		self.router = self.router.with_prefix(prefix);
		self
	}

	/// Set namespace
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	///
	/// let group = RouteGroup::new()
	///     .with_namespace("v1");
	/// ```
	pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
		self.router = self.router.with_namespace(namespace);
		self
	}

	/// Add middleware to apply to the entire group
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	/// use reinhardt_middleware::LoggingMiddleware;
	///
	/// let group = RouteGroup::new()
	///     .with_middleware(LoggingMiddleware::new());
	///
	/// // Middleware is applied to the router
	/// let router = group.build();
	/// assert!(router.prefix().is_empty() || !router.prefix().is_empty());
	/// ```
	pub fn with_middleware<M: Middleware + 'static>(mut self, middleware: M) -> Self {
		self.router = self.router.with_middleware(middleware);
		self
	}

	/// Add a function-based route
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	/// use hyper::Method;
	/// # use reinhardt_http::{Request, Response, Result};
	///
	/// # async fn health(_req: Request) -> Result<Response> {
	/// #     Ok(Response::ok())
	/// # }
	/// let group = RouteGroup::new()
	///     .function("/health", Method::GET, health);
	///
	/// // Router is built successfully
	/// let router = group.build();
	/// assert!(!router.get_all_routes().is_empty());
	/// ```
	pub fn function<F, Fut>(mut self, path: &str, method: hyper::Method, func: F) -> Self
	where
		F: Fn(reinhardt_http::Request) -> Fut + Send + Sync + 'static,
		Fut: std::future::Future<
				Output = reinhardt_core::exception::Result<reinhardt_http::Response>,
			> + Send
			+ 'static,
	{
		self.router = self.router.function(path, method, func);
		self
	}

	/// Add a route with a Handler trait implementation and HTTP method
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_urls::routers::RouteGroup;
	/// 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 group = RouteGroup::new()
	///     .handler_with_method("/articles", Method::GET, ArticleHandler);
	/// ```
	pub fn handler_with_method<H: reinhardt_http::Handler + 'static>(
		mut self,
		path: &str,
		method: hyper::Method,
		handler: H,
	) -> Self {
		self.router = self.router.handler_with_method(path, method, handler);
		self
	}

	/// Add a named function-based route
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	/// use hyper::Method;
	/// # use reinhardt_http::{Request, Response, Result};
	///
	/// # async fn health(_req: Request) -> Result<Response> {
	/// #     Ok(Response::ok())
	/// # }
	/// let group = RouteGroup::new()
	///     .function_named("/health", Method::GET, "health", health);
	///
	/// // Router is built successfully with named route
	/// let router = group.build();
	/// let routes = router.get_all_routes();
	/// assert!(!routes.is_empty());
	/// assert!(routes.len() >= 1);
	/// ```
	#[deprecated(
		since = "0.2.0",
		note = "Use `#[get(\"/path\", name = \"name\")]` + `.endpoint()` instead"
	)]
	pub fn function_named<F, Fut>(
		mut self,
		path: &str,
		method: hyper::Method,
		name: &str,
		func: F,
	) -> Self
	where
		F: Fn(reinhardt_http::Request) -> Fut + Send + Sync + 'static,
		Fut: std::future::Future<
				Output = reinhardt_core::exception::Result<reinhardt_http::Response>,
			> + Send
			+ 'static,
	{
		#[allow(deprecated)]
		{
			self.router = self.router.function_named(path, method, name, func);
		}
		self
	}

	/// Add a named route with a Handler trait implementation and HTTP method
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_urls::routers::RouteGroup;
	/// 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 group = RouteGroup::new()
	///     .handler_with_method_named("/articles", Method::GET, "list_articles", ArticleHandler);
	/// ```
	#[deprecated(
		since = "0.2.0",
		note = "Use `#[get(\"/path\", name = \"name\")]` + `.endpoint()` instead"
	)]
	pub fn handler_with_method_named<H: reinhardt_http::Handler + 'static>(
		mut self,
		path: &str,
		method: hyper::Method,
		name: &str,
		handler: H,
	) -> Self {
		#[allow(deprecated)]
		{
			self.router = self
				.router
				.handler_with_method_named(path, method, name, handler);
		}
		self
	}

	/// Add a ViewSet
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_urls::routers::RouteGroup;
	/// # 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 group = RouteGroup::new()
	///     .viewset("/users", UserViewSet);
	/// ```
	#[cfg(feature = "viewsets")]
	pub fn viewset<V: reinhardt_views::viewsets::ViewSet + 'static>(
		mut self,
		prefix: &str,
		viewset: V,
	) -> Self {
		self.router = self.router.viewset(prefix, 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: copies every action submitted under
	/// `type_name::<M>()` (via the impl-form `#[viewset]` macro's runtime
	/// registration) into the runtime-keyed `register_action(type_name::<V>(), ...)`
	/// slot so `ViewSet::get_extra_actions` finds them at dispatch time.
	///
	/// 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)
	}

	/// Add a class-based view
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_urls::routers::RouteGroup;
	/// # 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 group = RouteGroup::new()
	///     .view("/articles", ArticleListView);
	///
	/// // RouteGroup created successfully
	/// ```
	pub fn view<V>(mut self, path: &str, view: V) -> Self
	where
		V: reinhardt_http::Handler + 'static,
	{
		self.router = self.router.view(path, view);
		self
	}

	/// Add a named class-based view
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_urls::routers::RouteGroup;
	/// # 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 group = RouteGroup::new()
	///     .view_named("/articles", "list", ArticleListView);
	///
	/// // RouteGroup created successfully
	/// ```
	#[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: reinhardt_http::Handler + 'static,
	{
		#[allow(deprecated)]
		{
			self.router = self.router.view_named(path, name, view);
		}
		self
	}

	/// Add a child group (nested group)
	///
	/// # Examples
	///
	/// ```rust
	/// use reinhardt_urls::routers::RouteGroup;
	///
	/// let auth_group = RouteGroup::new()
	///     .with_prefix("/auth/");
	///
	/// let group = RouteGroup::new()
	///     .with_prefix("/api/")
	///     .nest(auth_group);
	///
	/// // RouteGroup with nested group created successfully
	/// ```
	pub fn nest(mut self, child: RouteGroup) -> Self {
		let child_prefix = child.router.prefix().to_string();
		self.router = self.router.mount(&child_prefix, child.router);
		self
	}

	/// Get the prefix of this route group
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	///
	/// let group = RouteGroup::new()
	///     .with_prefix("/api/v1");
	///
	/// assert_eq!(group.prefix(), "/api/v1");
	/// ```
	pub fn prefix(&self) -> &str {
		self.router.prefix()
	}

	/// Get the namespace of this route group
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	///
	/// let group = RouteGroup::new()
	///     .with_namespace("v1");
	///
	/// assert_eq!(group.namespace(), Some("v1"));
	/// ```
	pub fn namespace(&self) -> Option<&str> {
		self.router.namespace()
	}

	/// Get the number of child routers in this group
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	///
	/// let auth_group = RouteGroup::new()
	///     .with_prefix("/auth/");
	///
	/// let group = RouteGroup::new()
	///     .with_prefix("/api/")
	///     .nest(auth_group);
	///
	/// assert_eq!(group.children_count(), 1);
	/// ```
	pub fn children_count(&self) -> usize {
		self.router.children_count()
	}

	/// Get all routes registered in this group
	///
	/// Returns a vector of tuples containing (path, name, namespace, methods).
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	/// use hyper::Method;
	/// # use reinhardt_http::{Request, Response, Result};
	///
	/// # async fn health(_req: Request) -> Result<Response> {
	/// #     Ok(Response::ok())
	/// # }
	/// let group = RouteGroup::new()
	///     .with_prefix("/api")
	///     .function("/health", Method::GET, health);
	///
	/// let routes = group.get_all_routes();
	/// assert!(!routes.is_empty());
	/// ```
	pub fn get_all_routes(&self) -> RouteInfo {
		self.router.get_all_routes()
	}

	/// Build ServerRouter
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_urls::routers::RouteGroup;
	///
	/// let group = RouteGroup::new();
	/// let router = group.build();
	/// ```
	pub fn build(self) -> ServerRouter {
		self.router
	}
}

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

#[cfg(test)]
mod tests {
	use super::*;
	use hyper::Method;
	use reinhardt_http::{Request, Response, Result};
	use reinhardt_middleware::LoggingMiddleware;

	async fn test_handler(_req: Request) -> Result<Response> {
		Ok(Response::ok())
	}

	#[test]
	fn test_route_group_new() {
		let group = RouteGroup::new();
		let router = group.build();
		assert_eq!(router.prefix(), "");
	}

	#[test]
	fn test_route_group_with_prefix() {
		let group = RouteGroup::new().with_prefix("/api/v1");
		let router = group.build();
		assert_eq!(router.prefix(), "/api/v1");
	}

	#[test]
	fn test_route_group_with_namespace() {
		let group = RouteGroup::new().with_namespace("v1");
		let router = group.build();
		assert_eq!(router.namespace(), Some("v1"));
	}

	#[test]
	fn test_route_group_with_middleware() {
		let group = RouteGroup::new().with_middleware(LoggingMiddleware::new());
		let _router = group.build();
		// Middleware is correctly added, verified in integration tests
	}

	#[test]
	fn test_route_group_function() {
		let group = RouteGroup::new().function("/health", Method::GET, test_handler);
		let _router = group.build();
		// Routes are correctly added, verified in integration tests
	}

	#[test]
	fn test_route_group_nested() {
		let auth_group =
			RouteGroup::new()
				.with_prefix("/auth/")
				.function("/login", Method::POST, test_handler);

		let group = RouteGroup::new().with_prefix("/api/").nest(auth_group);

		let router = group.build();
		assert_eq!(router.children_count(), 1);
	}

	#[test]
	fn test_route_group_multiple_middleware() {
		let group = RouteGroup::new()
			.with_middleware(LoggingMiddleware::new())
			.with_middleware(LoggingMiddleware::new())
			.function("/test", Method::GET, test_handler);

		let _router = group.build();
		// Verify that multiple middleware are correctly added in integration tests
	}
}

#[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` on `RouteGroup`.
	#[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 group_a = RouteGroup::new().viewset(
			"/users",
			DummyViewSet {
				basename: "users".to_string(),
			},
		);
		let group_b = RouteGroup::new().viewset_with_actions(
			"/users",
			DummyViewSet {
				basename: "users".to_string(),
			},
			PhantomData::<DummyImpl>,
		);
		let mut router_a = group_a.build();
		let mut router_b = group_b.build();

		// 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);
	}
}