rustapi_core/
auto_route.rs

1//! Auto-route registration using linkme distributed slices
2//!
3//! This module enables zero-config route registration. Routes decorated with
4//! `#[rustapi::get]`, `#[rustapi::post]`, etc. are automatically collected at link-time.
5//!
6//! # How It Works
7//!
8//! When you use `#[rustapi::get("/path")]` or similar macros, they generate a
9//! static registration that adds the route factory function to a distributed slice.
10//! At runtime, `RustApi::auto()` collects all these routes and registers them.
11//!
12//! # Example
13//!
14//! ```rust,ignore
15//! use rustapi_rs::prelude::*;
16//!
17//! #[rustapi::get("/users")]
18//! async fn list_users() -> Json<Vec<User>> {
19//!     Json(vec![])
20//! }
21//!
22//! #[rustapi::post("/users")]
23//! async fn create_user(Json(body): Json<CreateUser>) -> Created<User> {
24//!     // ...
25//! }
26//!
27//! #[rustapi::main]
28//! async fn main() -> Result<()> {
29//!     // Routes are auto-registered, no need for manual .mount() calls!
30//!     RustApi::auto()
31//!         .run("0.0.0.0:8080")
32//!         .await
33//! }
34//! ```
35
36use crate::handler::Route;
37use linkme::distributed_slice;
38
39/// Distributed slice containing all auto-registered route factory functions.
40///
41/// Each element is a function that returns a [`Route`] when called.
42/// The macro `#[rustapi::get]`, `#[rustapi::post]`, etc. automatically
43/// add entries to this slice at compile/link time.
44#[distributed_slice]
45pub static AUTO_ROUTES: [fn() -> Route];
46
47/// Collect all auto-registered routes.
48///
49/// This function iterates over the distributed slice and calls each
50/// route factory function to produce the actual [`Route`] instances.
51///
52/// # Returns
53///
54/// A vector containing all routes that were registered using the
55/// `#[rustapi::get]`, `#[rustapi::post]`, etc. macros.
56///
57/// # Example
58///
59/// ```rust,ignore
60/// let routes = collect_auto_routes();
61/// println!("Found {} auto-registered routes", routes.len());
62/// ```
63pub fn collect_auto_routes() -> Vec<Route> {
64    AUTO_ROUTES.iter().map(|f| f()).collect()
65}
66
67/// Get the count of auto-registered routes without collecting them.
68///
69/// Useful for debugging and logging.
70pub fn auto_route_count() -> usize {
71    AUTO_ROUTES.len()
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn test_auto_routes_slice_exists() {
80        // The slice should exist, even if empty initially
81        let _count = auto_route_count();
82    }
83
84    #[test]
85    fn test_collect_auto_routes() {
86        // Should not panic, returns empty vec if no routes registered
87        let routes = collect_auto_routes();
88        // In tests, we may or may not have routes depending on what's linked
89        let _ = routes;
90    }
91}