Skip to main content

larastvel_core/
bootstrap.rs

1use std::path::PathBuf;
2
3use axum::Router as AxumRouter;
4
5use crate::console::ConsoleKernel;
6use crate::database::DatabaseManager;
7use crate::foundation::Application;
8use crate::logging;
9use crate::models;
10use crate::routing::Registrar;
11
12/// Fluent application builder — the Rust equivalent of Laravel 11+'s
13/// `bootstrap/app.php`.
14///
15/// # Example
16///
17/// ```rust,ignore
18/// use larastvel_core::bootstrap::App;
19/// use std::sync::Arc;
20///
21/// #[tokio::main]
22/// async fn main() {
23///     App::configure(None)
24///         .with_routing(|r| {
25///             routes::web::web(r);
26///         })
27///         .with_providers(|app| {
28///             app.register_provider(Arc::new(
29///                 RouteServiceProvider::new()
30///                     .web(|r| routes::web::web(r)),
31///             ));
32///         })
33///         .with_console_commands(|kernel| {
34///             kernel.add_command(Arc::new(MyCommand));
35///         })
36///         .run()
37///         .await;
38/// }
39/// ```
40#[allow(clippy::type_complexity)]
41pub struct App {
42    base_path: Option<PathBuf>,
43    routing: Option<Box<dyn FnOnce(&Registrar) + Send>>,
44    providers: Option<Box<dyn FnOnce(&Application) + Send>>,
45    console_commands: Option<Box<dyn FnOnce(&ConsoleKernel) + Send>>,
46    layers: Vec<Box<dyn FnOnce(AxumRouter) -> AxumRouter + Send>>,
47}
48
49impl App {
50    /// Create a new application builder with an optional base path.
51    ///
52    /// Pass `None` to use the current directory as the base path.
53    pub fn configure(base_path: Option<PathBuf>) -> Self {
54        Self {
55            base_path,
56            routing: None,
57            providers: None,
58            console_commands: None,
59            layers: Vec::new(),
60        }
61    }
62
63    /// Register web and/or API routes via a closure that receives a [`Registrar`].
64    ///
65    /// Multiple calls accumulate; each closure is called during boot.
66    pub fn with_routing(mut self, f: impl FnOnce(&Registrar) + Send + 'static) -> Self {
67        let prev = self.routing.take();
68        self.routing = Some(if let Some(prev) = prev {
69            Box::new(move |r| {
70                prev(r);
71                f(r);
72            })
73        } else {
74            Box::new(f)
75        });
76        self
77    }
78
79    /// Register service providers via a closure that receives the [`Application`].
80    pub fn with_providers(mut self, f: impl FnOnce(&Application) + Send + 'static) -> Self {
81        let prev = self.providers.take();
82        self.providers = Some(if let Some(prev) = prev {
83            Box::new(move |app| {
84                prev(app);
85                f(app);
86            })
87        } else {
88            Box::new(f)
89        });
90        self
91    }
92
93    /// Register console commands via a closure that receives the [`ConsoleKernel`].
94    ///
95    /// Multiple calls accumulate; each closure is called during boot.
96    pub fn with_console_commands(
97        mut self,
98        f: impl FnOnce(&ConsoleKernel) + Send + 'static,
99    ) -> Self {
100        let prev = self.console_commands.take();
101        self.console_commands = Some(if let Some(prev) = prev {
102            Box::new(move |k| {
103                prev(k);
104                f(k);
105            })
106        } else {
107            Box::new(f)
108        });
109        self
110    }
111
112    /// Add a Tower layer or Axum extension to the final application router.
113    ///
114    /// The closure receives the fully-built `Router` after all routes are
115    /// registered and must return a router. Multiple calls accumulate.
116    ///
117    /// ```rust,ignore
118    /// use larastvel_core::axum::Extension;
119    ///
120    /// App::configure(None)
121    ///     .with_routing(|r| { /* routes */ })
122    ///     .with_layer(|router| router.layer(Extension(my_state)))
123    ///     .run()
124    ///     .await;
125    /// ```
126    pub fn with_layer(mut self, f: impl FnOnce(AxumRouter) -> AxumRouter + Send + 'static) -> Self {
127        self.layers.push(Box::new(f));
128        self
129    }
130
131    /// Build and run the application, consuming the builder.
132    pub async fn run(self) {
133        let app = Application::new(self.base_path.clone());
134        logging::init(&app.config());
135
136        // Connect to database
137        let db = DatabaseManager::new(&app.config());
138        match db.connect().await {
139            Ok(conn) => {
140                tracing::info!("Database connected successfully");
141                let _ = models::set_global_database(conn);
142            }
143            Err(e) => tracing::warn!("Database connection failed: {} (app will still run)", e),
144        }
145
146        let app = app.with_database(db);
147
148        // Register providers
149        if let Some(f) = self.providers {
150            f(&app);
151        }
152
153        // Register console commands
154        if let Some(f) = self.console_commands {
155            let kernel = app.console_kernel();
156            f(&kernel);
157        }
158
159        // Register routes via routing closure
160        if let Some(f) = self.routing {
161            let registrar = app.router();
162            f(&registrar);
163        }
164
165        // Apply user-registered layers/extensions
166        for layer in self.layers {
167            app.with_layer(layer);
168        }
169
170        app.run().await;
171    }
172}
173
174// ============================================================================
175// TESTS
176// ============================================================================
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    #[test]
183    fn test_app_configure_defaults() {
184        let app_builder = App::configure(None);
185        assert!(app_builder.routing.is_none());
186        assert!(app_builder.providers.is_none());
187        assert!(app_builder.console_commands.is_none());
188    }
189
190    #[test]
191    fn test_app_configure_with_base_path() {
192        let app_builder = App::configure(Some("/tmp".into()));
193        assert_eq!(app_builder.base_path, Some(PathBuf::from("/tmp")));
194    }
195
196    #[test]
197    fn test_app_with_routing_stores_closure() {
198        let app_builder = App::configure(None).with_routing(|_r| {});
199        assert!(app_builder.routing.is_some());
200    }
201
202    #[test]
203    fn test_app_with_providers_stores_closure() {
204        let app_builder = App::configure(None).with_providers(|_app| {});
205        assert!(app_builder.providers.is_some());
206    }
207
208    #[test]
209    fn test_app_with_console_commands_stores_closure() {
210        let app_builder = App::configure(None).with_console_commands(|_kernel| {});
211        assert!(app_builder.console_commands.is_some());
212    }
213
214    #[test]
215    fn test_app_with_console_commands_accumulates() {
216        use std::sync::atomic::{AtomicUsize, Ordering};
217        use std::sync::Arc;
218        let counter = Arc::new(AtomicUsize::new(0));
219
220        let app = App::configure(None)
221            .with_console_commands({
222                let c = counter.clone();
223                move |_k| {
224                    c.fetch_add(1, Ordering::SeqCst);
225                }
226            })
227            .with_console_commands(move |_k| {
228                counter.fetch_add(1, Ordering::SeqCst);
229            });
230
231        assert!(app.console_commands.is_some());
232    }
233}