Skip to main content

capy_framework/
app.rs

1use crate::{AppConfig, AppContext, AppError, Result, Routes};
2use capy_db::{MigratorTrait, NoMigrations};
3use std::{collections::BTreeMap, marker::PhantomData, path::PathBuf, sync::Arc, time::Duration};
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    request_timeouts: BTreeMap<String, Option<Duration>>,
13    observer: crate::diagnostics::Observer,
14    migrations: PhantomData<M>,
15}
16
17impl Default for App {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23impl App {
24    /// Begin an application using configuration from the current directory.
25    pub fn new() -> Self {
26        Self {
27            routes: Routes::new(),
28            api_routes: None,
29            frontend: None,
30            config: None,
31            request_timeouts: BTreeMap::new(),
32            observer: None,
33            migrations: PhantomData,
34        }
35    }
36}
37
38impl<M: MigratorTrait> App<M> {
39    /// Install an application-owned, nonblocking response observer for telemetry.
40    pub fn observe_requests(mut self, observer: impl crate::RequestObserver) -> Self {
41        self.observer = Some(Arc::new(observer));
42        self
43    }
44
45    /// Override the response-header deadline for a full matched route template,
46    /// such as `/api/events` or `/api/posts/{id}`. `None` intentionally disables
47    /// it. Response body streaming is never subject to this header deadline.
48    pub fn request_timeout_for(
49        mut self,
50        route: impl Into<String>,
51        timeout: Option<Duration>,
52    ) -> Self {
53        self.request_timeouts.insert(route.into(), timeout);
54        self
55    }
56
57    /// Mount API routes under `/api`, preserving JSON errors within that namespace.
58    /// Declare paths such as `/posts` without repeating the prefix.
59    pub fn api_routes(mut self, routes: Routes) -> Self {
60        self.api_routes = Some(routes);
61        self
62    }
63
64    /// Serve built frontend assets and use index.html for non-API browser routes.
65    /// The path is relative to the application's working directory. Production
66    /// startup requires a readable index.html; development may use Vite instead.
67    pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
68        self.frontend = Some(directory.into());
69        self
70    }
71
72    /// Set the application's routes.
73    pub fn routes(mut self, routes: Routes) -> Self {
74        self.routes = routes;
75        self
76    }
77
78    /// Use explicit typed configuration, useful for tests and embedded apps.
79    pub fn config(mut self, config: AppConfig) -> Self {
80        self.config = Some(config);
81        self
82    }
83
84    /// Register a native SeaORM migrator for the application's CLI commands.
85    /// Serving never applies migrations implicitly.
86    pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
87        App {
88            routes: self.routes,
89            api_routes: self.api_routes,
90            frontend: self.frontend,
91            config: self.config,
92            request_timeouts: self.request_timeouts,
93            observer: self.observer,
94            migrations: PhantomData,
95        }
96    }
97
98    /// Build a service using an existing context, without binding a TCP port.
99    /// The returned Axum router can be tested or served with native tooling.
100    pub fn into_router(self, context: AppContext) -> axum::Router {
101        let http = context.config.http.clone();
102        let policy = crate::http_policy::HttpPolicy {
103            default_timeout: (http.request_timeout_seconds != 0)
104                .then(|| Duration::from_secs(http.request_timeout_seconds)),
105            overrides: self.request_timeouts,
106        };
107        let mut router = self.routes.into_router();
108        if let Some(api) = self.api_routes {
109            router = router.nest("/api", api.into_router());
110        }
111        if let Some(directory) = self.frontend {
112            router =
113                router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
114        }
115        let mut router = router
116            .with_state(context)
117            .layer(axum::extract::DefaultBodyLimit::max(http.max_body_bytes))
118            .layer(axum::middleware::from_fn_with_state(
119                policy,
120                crate::http_policy::deadline,
121            ));
122        if http.compression {
123            router = router.layer(tower_http::compression::CompressionLayer::new());
124        }
125        router
126            .layer(axum::middleware::from_fn_with_state(
127                self.observer,
128                crate::diagnostics::request,
129            ))
130            .layer(
131                tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new([
132                    axum::http::header::AUTHORIZATION,
133                    axum::http::header::COOKIE,
134                ]),
135            )
136            .layer(
137                tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([
138                    axum::http::header::SET_COOKIE,
139                ]),
140            )
141    }
142
143    /// Serve by default, or execute the command forwarded by `capy`.
144    /// Supported arguments: `serve`, `check`, `routes`, `migrate`, `migrate:rollback`,
145    /// and `migrate:status`. Migrations are explicit and rollback reverts one.
146    pub async fn run(self) -> Result<()> {
147        let mut args = std::env::args().skip(1);
148        let command = args.next().unwrap_or_else(|| "serve".into());
149        if args.next().is_some() {
150            return Err(AppError::Configuration(
151                "Unexpected arguments. Use the capy CLI for application commands.".into(),
152            ));
153        }
154        self.run_command(&command).await
155    }
156
157    /// Run a specific application command without reading process arguments.
158    pub async fn run_command(self, command: &str) -> Result<()> {
159        if command == "routes" {
160            for route in self.routes.inventory() {
161                println!("{:<7} {}", route.method, route.path);
162            }
163            if let Some(api) = &self.api_routes {
164                for route in api.inventory() {
165                    println!("{:<7} /api{}", route.method, route.path);
166                }
167            }
168            return Ok(());
169        }
170        if !matches!(
171            command,
172            "serve" | "check" | "migrate" | "migrate:rollback" | "migrate:status"
173        ) {
174            return Err(AppError::Configuration(format!(
175                "Unknown application command: {command}"
176            )));
177        }
178        let config = match &self.config {
179            Some(config) => config.clone(),
180            None => AppConfig::load()?,
181        };
182        config.validate()?;
183        if command == "check" || (command == "serve" && config.app.environment == "production") {
184            if let Some(directory) = &self.frontend {
185                crate::frontend::validate(directory)?;
186            }
187        }
188        if command == "check" {
189            let migrations = M::migrations();
190            let mut names = std::collections::BTreeSet::new();
191            for migration in &migrations {
192                if !names.insert(migration.name()) {
193                    return Err(AppError::Configuration(
194                        "Duplicate registered migration name.".into(),
195                    ));
196                }
197            }
198            println!(
199                "Configuration valid; {} migrations registered. No database connection opened.",
200                migrations.len()
201            );
202            return Ok(());
203        }
204        init_logging(&config);
205        let db = capy_db::connect(&config.database).await?;
206        match command {
207            "migrate" => {
208                M::up(&db, None).await?;
209                println!("Migrations applied.");
210            }
211            "migrate:rollback" => {
212                M::down(&db, Some(1)).await?;
213                println!("Rolled back the latest migration.");
214            }
215            "migrate:status" => {
216                let statuses = capy_db::status::<M>(&db).await?;
217                if statuses.is_empty() {
218                    println!("No migrations registered.");
219                }
220                for status in statuses {
221                    println!(
222                        "{:<8} {}",
223                        if status.applied { "Applied" } else { "Pending" },
224                        status.name
225                    );
226                }
227            }
228            _ => {
229                let listener =
230                    tokio::net::TcpListener::bind((config.host(), config.port())).await?;
231                let address = listener.local_addr()?;
232                if config.app.environment == "production" {
233                    tracing::info!(%address, environment = %config.app.environment, "Capy ready");
234                } else if std::env::var_os("CAPY_DEV").is_some() {
235                    println!(
236                        "āœ“ Database connected\nāœ“ Backend ready\nServer running on http://{address}"
237                    );
238                } else {
239                    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.",
240                        env!("CARGO_PKG_VERSION"), config.app.environment,
241                        if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
242                }
243                let shutdown_timeout = Duration::from_secs(config.server.shutdown_timeout_seconds);
244                let context = AppContext {
245                    config: Arc::new(config),
246                    db,
247                };
248                serve(
249                    listener,
250                    self.into_router(context),
251                    shutdown_timeout,
252                    shutdown_signal(),
253                )
254                .await?;
255            }
256        }
257        Ok(())
258    }
259}
260
261// axum-server owns connection cancellation. Merely dropping axum::serve's
262// graceful future leaves its detached connection tasks running in shared runtimes.
263pub(crate) async fn serve(
264    listener: tokio::net::TcpListener,
265    router: axum::Router,
266    timeout: Duration,
267    signal: impl std::future::Future<Output = ()>,
268) -> Result<()> {
269    let handle = axum_server::Handle::new();
270    let server = axum_server::from_tcp(listener.into_std()?)?
271        .handle(handle.clone())
272        .serve(router.into_make_service());
273    tokio::pin!(server);
274    tokio::select! {
275        result = &mut server => { result?; }
276        () = signal => {
277            tracing::info!("shutdown requested");
278            handle.graceful_shutdown(None);
279            tracing::info!("waiting for active requests");
280            match tokio::time::timeout(timeout, &mut server).await {
281                Ok(result) => result?,
282                Err(_) => {
283                    tracing::warn!("shutdown deadline reached");
284                    handle.shutdown();
285                    server.await?;
286                }
287            }
288        }
289    }
290    tracing::info!("server stopped");
291    Ok(())
292}
293
294fn init_logging(config: &AppConfig) {
295    let filter = EnvFilter::try_from_default_env()
296        .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
297    if config.app.environment != "production"
298        && std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
299    {
300        let _ = tracing_subscriber::fmt()
301            .with_env_filter(filter)
302            .with_ansi(false)
303            .json()
304            .with_writer(crate::dev_logging::writer)
305            .try_init();
306    } else if config.app.environment == "production" {
307        let _ = tracing_subscriber::fmt()
308            .with_env_filter(filter)
309            .json()
310            .try_init();
311    } else {
312        let _ = tracing_subscriber::fmt()
313            .with_env_filter(filter)
314            .compact()
315            .try_init();
316    }
317}
318
319async fn shutdown_signal() {
320    let ctrl_c = async {
321        let _ = tokio::signal::ctrl_c().await;
322    };
323    #[cfg(unix)]
324    let terminate = async {
325        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
326            Ok(mut stream) => {
327                stream.recv().await;
328            }
329            Err(_) => std::future::pending::<()>().await,
330        }
331    };
332    #[cfg(not(unix))]
333    let terminate = std::future::pending::<()>();
334    tokio::select! { () = ctrl_c => {}, () = terminate => {} }
335}