Skip to main content

capy_framework/
app.rs

1use crate::{AppConfig, AppContext, AppError, Result, Routes};
2use capy_db::{MigratorTrait, NoMigrations};
3use std::{marker::PhantomData, path::PathBuf, sync::Arc};
4use tracing_subscriber::EnvFilter;
5
6/// Application builder: configuration, database, tracing, migrations, and HTTP.
7pub struct App<M = NoMigrations> {
8    routes: Routes,
9    api_routes: Option<Routes>,
10    frontend: Option<PathBuf>,
11    config: Option<AppConfig>,
12    migrations: PhantomData<M>,
13}
14
15impl Default for App {
16    fn default() -> Self {
17        Self::new()
18    }
19}
20
21impl App {
22    /// Begin an application using configuration from the current directory.
23    pub fn new() -> Self {
24        Self {
25            routes: Routes::new(),
26            api_routes: None,
27            frontend: None,
28            config: None,
29            migrations: PhantomData,
30        }
31    }
32}
33
34impl<M: MigratorTrait> App<M> {
35    /// Mount API routes under `/api`, preserving JSON errors within that namespace.
36    /// Declare paths such as `/posts` without repeating the prefix.
37    pub fn api_routes(mut self, routes: Routes) -> Self {
38        self.api_routes = Some(routes);
39        self
40    }
41
42    /// Serve built frontend assets and use index.html for non-API browser routes.
43    /// The path is relative to the application's working directory. Production
44    /// startup requires a readable index.html; development may use Vite instead.
45    pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
46        self.frontend = Some(directory.into());
47        self
48    }
49
50    /// Set the application's routes.
51    pub fn routes(mut self, routes: Routes) -> Self {
52        self.routes = routes;
53        self
54    }
55
56    /// Use explicit typed configuration, useful for tests and embedded apps.
57    pub fn config(mut self, config: AppConfig) -> Self {
58        self.config = Some(config);
59        self
60    }
61
62    /// Register a native SeaORM migrator for the application's CLI commands.
63    /// Serving never applies migrations implicitly.
64    pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
65        App {
66            routes: self.routes,
67            api_routes: self.api_routes,
68            frontend: self.frontend,
69            config: self.config,
70            migrations: PhantomData,
71        }
72    }
73
74    /// Build a service using an existing context, without binding a TCP port.
75    /// The returned Axum router can be tested or served with native tooling.
76    pub fn into_router(self, context: AppContext) -> axum::Router {
77        let mut router = self.routes.into_router();
78        if let Some(api) = self.api_routes {
79            router = router.nest("/api", api.into_router());
80        }
81        if let Some(directory) = self.frontend {
82            router =
83                router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
84        }
85        router
86            .with_state(context)
87            .layer(axum::middleware::from_fn(crate::diagnostics::request))
88    }
89
90    /// Serve by default, or execute the command forwarded by `capy`.
91    /// Supported arguments: `serve`, `routes`, `migrate`, `migrate:rollback`,
92    /// and `migrate:status`. Migrations are explicit and rollback reverts one.
93    pub async fn run(self) -> Result<()> {
94        let mut args = std::env::args().skip(1);
95        let command = args.next().unwrap_or_else(|| "serve".into());
96        if args.next().is_some() {
97            return Err(AppError::Configuration(
98                "Unexpected arguments. Use the capy CLI for application commands.".into(),
99            ));
100        }
101        self.run_command(&command).await
102    }
103
104    /// Run a specific application command without reading process arguments.
105    pub async fn run_command(self, command: &str) -> Result<()> {
106        if command == "routes" {
107            for route in self.routes.inventory() {
108                println!("{:<7} {}", route.method, route.path);
109            }
110            if let Some(api) = &self.api_routes {
111                for route in api.inventory() {
112                    println!("{:<7} /api{}", route.method, route.path);
113                }
114            }
115            return Ok(());
116        }
117        if !matches!(
118            command,
119            "serve" | "migrate" | "migrate:rollback" | "migrate:status"
120        ) {
121            return Err(AppError::Configuration(format!(
122                "Unknown application command: {command}"
123            )));
124        }
125        let config = match &self.config {
126            Some(config) => config.clone(),
127            None => AppConfig::load()?,
128        };
129        config.validate()?;
130        if command == "serve" && config.app.environment == "production" {
131            if let Some(directory) = &self.frontend {
132                crate::frontend::validate(directory)?;
133            }
134        }
135        init_logging(&config);
136        let db = capy_db::connect(&config.database).await?;
137        match command {
138            "migrate" => {
139                M::up(&db, None).await?;
140                println!("Migrations applied.");
141            }
142            "migrate:rollback" => {
143                M::down(&db, Some(1)).await?;
144                println!("Rolled back the latest migration.");
145            }
146            "migrate:status" => {
147                let statuses = capy_db::status::<M>(&db).await?;
148                if statuses.is_empty() {
149                    println!("No migrations registered.");
150                }
151                for status in statuses {
152                    println!(
153                        "{:<8} {}",
154                        if status.applied { "Applied" } else { "Pending" },
155                        status.name
156                    );
157                }
158            }
159            _ => {
160                let listener =
161                    tokio::net::TcpListener::bind((config.app.host.as_str(), config.app.port))
162                        .await?;
163                let address = listener.local_addr()?;
164                if config.app.environment == "production" {
165                    tracing::info!(%address, environment = %config.app.environment, "Capy ready");
166                } else if std::env::var_os("CAPY_DEV").is_some() {
167                    println!("āœ“ Database connected\nāœ“ Backend ready");
168                } else {
169                    println!("Capy v{}\n\nA calmer way to build web apps in Rust.\n\nApplication\n  http://{address}\n\nEnvironment\n  {}\n\nDatabase\n  {}\n\nReady.",
170                        env!("CARGO_PKG_VERSION"), config.app.environment,
171                        if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
172                }
173                let context = AppContext {
174                    config: Arc::new(config),
175                    db,
176                };
177                axum::serve(listener, self.into_router(context))
178                    .with_graceful_shutdown(shutdown_signal())
179                    .await?;
180            }
181        }
182        Ok(())
183    }
184}
185
186fn init_logging(config: &AppConfig) {
187    let filter = EnvFilter::try_from_default_env()
188        .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
189    if config.app.environment == "production" {
190        let _ = tracing_subscriber::fmt()
191            .with_env_filter(filter)
192            .json()
193            .try_init();
194    } else {
195        let _ = tracing_subscriber::fmt()
196            .with_env_filter(filter)
197            .compact()
198            .try_init();
199    }
200}
201
202async fn shutdown_signal() {
203    let ctrl_c = async {
204        let _ = tokio::signal::ctrl_c().await;
205    };
206    #[cfg(unix)]
207    let terminate = async {
208        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
209            Ok(mut stream) => {
210                stream.recv().await;
211            }
212            Err(_) => std::future::pending::<()>().await,
213        }
214    };
215    #[cfg(not(unix))]
216    let terminate = std::future::pending::<()>();
217    tokio::select! { () = ctrl_c => {}, () = terminate => {} }
218}