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
6type OpenApiCustomizer = Arc<dyn Fn(&mut crate::ApiDocument) + Send + Sync>;
7
8/// Application builder: configuration, database, tracing, migrations, and HTTP.
9pub struct App<M = NoMigrations> {
10    routes: Routes,
11    api_routes: Option<Routes>,
12    frontend: Option<PathBuf>,
13    config: Option<AppConfig>,
14    request_timeouts: BTreeMap<String, Option<Duration>>,
15    observer: crate::diagnostics::Observer,
16    openapi_customizer: Option<OpenApiCustomizer>,
17    #[cfg(feature = "auth")]
18    auth_delivery: Option<Arc<dyn capy_auth::ResetDelivery>>,
19    migrations: PhantomData<M>,
20}
21
22impl Default for App {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl App {
29    /// Begin an application using configuration from the current directory.
30    pub fn new() -> Self {
31        Self {
32            routes: Routes::new(),
33            api_routes: None,
34            frontend: None,
35            config: None,
36            request_timeouts: BTreeMap::new(),
37            observer: None,
38            openapi_customizer: None,
39            #[cfg(feature = "auth")]
40            auth_delivery: None,
41            migrations: PhantomData,
42        }
43    }
44}
45
46impl<M: MigratorTrait> App<M> {
47    /// Install conventional `/api/auth` routes and synchronizer CSRF protection.
48    /// The application owns password-reset delivery. Migrate identity tables first.
49    #[cfg(feature = "auth")]
50    pub fn auth(mut self, delivery: impl capy_auth::ResetDelivery) -> Self {
51        self.auth_delivery = Some(Arc::new(delivery));
52        self
53    }
54
55    /// Customize standard OpenAPI metadata, servers or security schemes.
56    /// The same function runs during offline export and endpoint generation.
57    pub fn openapi_with(
58        mut self,
59        customize: impl Fn(&mut crate::ApiDocument) + Send + Sync + 'static,
60    ) -> Self {
61        self.openapi_customizer = Some(Arc::new(customize));
62        self
63    }
64
65    /// Generate this application's explicit contract without opening a database connection.
66    pub fn openapi(&self) -> Result<crate::ApiDocument> {
67        let config = self
68            .config
69            .clone()
70            .map(Ok)
71            .unwrap_or_else(AppConfig::load_for_contracts)?;
72        self.api_document(&config)
73    }
74
75    fn api_document(&self, config: &AppConfig) -> Result<crate::ApiDocument> {
76        let mut routes = vec![("", &self.routes)];
77        if let Some(api) = &self.api_routes {
78            routes.push(("/api", api));
79        }
80        #[cfg(feature = "auth")]
81        let auth_routes = capy_auth::routes();
82        #[cfg(feature = "auth")]
83        if let Some(delivery) = &self.auth_delivery {
84            let production = config.app.environment == "production";
85            config.auth.validate(production)?;
86            if production && delivery.development_only() {
87                return Err(AppError::Configuration("Install an application-owned password reset delivery adapter before enabling auth in production.".into()));
88            }
89            routes.push(("/api/auth", &auth_routes));
90        }
91        let mut document = crate::ApiDocument::from_routes(
92            config.api.title.as_deref().unwrap_or(&config.app.name),
93            &config.api.version,
94            routes,
95        )?;
96        #[cfg(feature = "auth")]
97        if self.auth_delivery.is_some() {
98            document.as_value_mut()["components"]["securitySchemes"]["session"] = crate::serde_json::json!({
99                "type": "apiKey", "in": "cookie",
100                "name": config.auth.cookie_name(config.app.environment == "production")
101            });
102            if let Some(paths) = document.as_value_mut()["paths"].as_object_mut() {
103                for (path, methods) in paths {
104                    if let Some(methods) = methods.as_object_mut() {
105                        for (method, operation) in methods {
106                            let mutation =
107                                matches!(method.as_str(), "post" | "put" | "patch" | "delete");
108                            let bootstrap = path == "/api/auth/csrf" && method == "get";
109                            if mutation || bootstrap {
110                                if operation.get("parameters").is_none() {
111                                    operation["parameters"] = crate::serde_json::json!([]);
112                                }
113                                operation["parameters"].as_array_mut().expect("generated parameter array").push(crate::serde_json::json!({
114                                    "name": if bootstrap { "X-Capy-CSRF" } else { "X-CSRF-Token" },
115                                    "in": "header", "required": true,
116                                    "description": if bootstrap { "Send 1 to bootstrap a same-origin CSRF session." } else { "Synchronizer token from GET /api/auth/csrf; never a session secret." },
117                                    "schema": {"type": "string"}
118                                }));
119                                operation["responses"]["403"] = crate::serde_json::json!({"description": "CSRF or policy rejection", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ApiErrorResponse"}}}});
120                            }
121                        }
122                    }
123                }
124            }
125        }
126        if let Some(customize) = &self.openapi_customizer {
127            customize(&mut document);
128        }
129        Ok(document)
130    }
131
132    /// Install an application-owned, nonblocking response observer for telemetry.
133    pub fn observe_requests(mut self, observer: impl crate::RequestObserver) -> Self {
134        self.observer = Some(Arc::new(observer));
135        self
136    }
137
138    /// Override the response-header deadline for a full matched route template,
139    /// such as `/api/events` or `/api/posts/{id}`. `None` intentionally disables
140    /// it. Response body streaming is never subject to this header deadline.
141    pub fn request_timeout_for(
142        mut self,
143        route: impl Into<String>,
144        timeout: Option<Duration>,
145    ) -> Self {
146        self.request_timeouts.insert(route.into(), timeout);
147        self
148    }
149
150    /// Mount API routes under `/api`, preserving JSON errors within that namespace.
151    /// Declare paths such as `/posts` without repeating the prefix.
152    pub fn api_routes(mut self, routes: Routes) -> Self {
153        self.api_routes = Some(routes);
154        self
155    }
156
157    /// Serve built frontend assets and use index.html for non-API browser routes.
158    /// The path is relative to the application's working directory. Production
159    /// startup requires a readable index.html; development may use Vite instead.
160    pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
161        self.frontend = Some(directory.into());
162        self
163    }
164
165    /// Set the application's routes.
166    pub fn routes(mut self, routes: Routes) -> Self {
167        self.routes = routes;
168        self
169    }
170
171    /// Use explicit typed configuration, useful for tests and embedded apps.
172    pub fn config(mut self, config: AppConfig) -> Self {
173        self.config = Some(config);
174        self
175    }
176
177    /// Register a native SeaORM migrator for the application's CLI commands.
178    /// Serving never applies migrations implicitly.
179    pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
180        App {
181            routes: self.routes,
182            api_routes: self.api_routes,
183            frontend: self.frontend,
184            config: self.config,
185            request_timeouts: self.request_timeouts,
186            observer: self.observer,
187            openapi_customizer: self.openapi_customizer,
188            #[cfg(feature = "auth")]
189            auth_delivery: self.auth_delivery,
190            migrations: PhantomData,
191        }
192    }
193
194    /// Build a service using an existing context, without binding a TCP port.
195    /// The returned Axum router can be tested or served with native tooling.
196    pub fn into_router(self, context: AppContext) -> axum::Router {
197        let docs_enabled =
198            context.config.api.docs && context.config.app.environment != "production";
199        let schema = (context.config.api.openapi || docs_enabled).then(|| {
200            self.api_document(&context.config)
201                .map(|doc| doc.as_value().clone())
202        });
203        let http = context.config.http.clone();
204        let policy = crate::http_policy::HttpPolicy {
205            default_timeout: (http.request_timeout_seconds != 0)
206                .then(|| Duration::from_secs(http.request_timeout_seconds)),
207            overrides: self.request_timeouts,
208        };
209        let mut router = self.routes.into_router();
210        if let Some(api) = self.api_routes {
211            router = router.nest("/api", api.into_router());
212        }
213        #[cfg(feature = "auth")]
214        let auth = self
215            .auth_delivery
216            .map(|delivery| capy_auth::AuthService::new(context.clone(), delivery));
217        #[cfg(feature = "auth")]
218        if auth.is_some() {
219            router = router.nest("/api/auth", capy_auth::routes().into_router());
220        }
221        if let Some(schema) = schema {
222            // run_command reports generation errors before binding; native into_router
223            // callers receive the same sanitized HTTP envelope if their metadata is invalid.
224            let schema = Arc::new(schema.map_err(|error| error.to_string()));
225            router = router.route(
226                "/openapi.json",
227                axum::routing::get(move || {
228                    let schema = schema.clone();
229                    async move {
230                        match schema.as_ref() {
231                            Ok(document) => Ok(axum::Json(document.clone())),
232                            Err(_) => Err(AppError::Configuration(
233                                "Invalid API contract. Run capy openapi to inspect the error."
234                                    .into(),
235                            )),
236                        }
237                    }
238                }),
239            );
240        }
241        if docs_enabled {
242            router = router.route(
243                "/docs/api",
244                axum::routing::get(|| async {
245                    axum::response::Html(include_str!("api_docs.html"))
246                }),
247            );
248        }
249        if let Some(directory) = self.frontend {
250            router =
251                router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
252        }
253        let mut router = router.with_state(context);
254        #[cfg(feature = "auth")]
255        if let Some(service) = auth {
256            router = match service {
257                Ok(service) => service.protect(router),
258                Err(_) => axum::Router::new().fallback(|| async {
259                    AppError::Configuration("Invalid auth configuration. Run capy check.".into())
260                }),
261            };
262        }
263        // Auth extraction and CSRF database work remain inside the existing deadline.
264        router = router
265            .layer(axum::extract::DefaultBodyLimit::max(http.max_body_bytes))
266            .layer(axum::middleware::from_fn_with_state(
267                policy,
268                crate::http_policy::deadline,
269            ));
270        if http.compression {
271            router = router.layer(tower_http::compression::CompressionLayer::new());
272        }
273        router
274            .layer(axum::middleware::from_fn_with_state(
275                self.observer,
276                crate::diagnostics::request,
277            ))
278            .layer(
279                tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new([
280                    axum::http::header::AUTHORIZATION,
281                    axum::http::header::COOKIE,
282                    axum::http::HeaderName::from_static("x-csrf-token"),
283                ]),
284            )
285            .layer(
286                tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([
287                    axum::http::header::SET_COOKIE,
288                ]),
289            )
290    }
291
292    /// Serve by default, or execute the command forwarded by `capy`.
293    /// Supported arguments: `serve`, `check`, `routes`, `migrate`, `migrate:rollback`,
294    /// and `migrate:status`. Migrations are explicit and rollback reverts one.
295    pub async fn run(self) -> Result<()> {
296        let mut args = std::env::args().skip(1);
297        let command = args.next().unwrap_or_else(|| "serve".into());
298        if args.next().is_some() {
299            return Err(AppError::Configuration(
300                "Unexpected arguments. Use the capy CLI for application commands.".into(),
301            ));
302        }
303        self.run_command(&command).await
304    }
305
306    /// Run a specific application command without reading process arguments.
307    pub async fn run_command(self, command: &str) -> Result<()> {
308        if command == "__capy_contract" {
309            print!("{}", self.openapi()?.to_json()?);
310            return Ok(());
311        }
312        if command == "routes:api" {
313            // Also validate incomplete/duplicate metadata before showing the inventory.
314            self.openapi()?;
315            for (prefix, routes) in std::iter::once(("", &self.routes))
316                .chain(self.api_routes.as_ref().map(|r| ("/api", r)))
317            {
318                for route in routes.api_inventory() {
319                    println!(
320                        "{:<7} {:<28} {:<22} {}",
321                        route.method,
322                        format!("{prefix}{}", route.path),
323                        route.operation_id.unwrap_or_default(),
324                        route.response.unwrap_or_default()
325                    );
326                }
327            }
328            #[cfg(feature = "auth")]
329            if self.auth_delivery.is_some() {
330                for route in capy_auth::routes().api_inventory() {
331                    println!(
332                        "{:<7} {:<28} {:<22} {}",
333                        route.method,
334                        format!("/api/auth{}", route.path),
335                        route.operation_id.unwrap_or_default(),
336                        route.response.unwrap_or_default()
337                    );
338                }
339            }
340            return Ok(());
341        }
342        if command == "routes" {
343            for route in self.routes.inventory() {
344                println!("{:<7} {}", route.method, route.path);
345            }
346            if let Some(api) = &self.api_routes {
347                for route in api.inventory() {
348                    println!("{:<7} /api{}", route.method, route.path);
349                }
350            }
351            #[cfg(feature = "auth")]
352            if self.auth_delivery.is_some() {
353                for route in capy_auth::routes().inventory() {
354                    println!("{:<7} /api/auth{}", route.method, route.path);
355                }
356            }
357            return Ok(());
358        }
359        if !matches!(
360            command,
361            "serve" | "check" | "migrate" | "migrate:rollback" | "migrate:status" | "auth:prune"
362        ) {
363            return Err(AppError::Configuration(format!(
364                "Unknown application command: {command}"
365            )));
366        }
367        let config = match &self.config {
368            Some(config) => config.clone(),
369            None => AppConfig::load()?,
370        };
371        config.validate()?;
372        // Validate declared contracts before starting HTTP or approving configuration.
373        if matches!(command, "serve" | "check") {
374            self.api_document(&config)?;
375        }
376        if command == "check" || (command == "serve" && config.app.environment == "production") {
377            if let Some(directory) = &self.frontend {
378                crate::frontend::validate(directory)?;
379            }
380        }
381        if command == "check" {
382            let migrations = M::migrations();
383            let mut names = std::collections::BTreeSet::new();
384            for migration in &migrations {
385                if !names.insert(migration.name()) {
386                    return Err(AppError::Configuration(
387                        "Duplicate registered migration name.".into(),
388                    ));
389                }
390            }
391            println!(
392                "Configuration valid; {} migrations registered. No database connection opened.",
393                migrations.len()
394            );
395            return Ok(());
396        }
397        if command == "auth:prune" {
398            #[cfg(feature = "auth")]
399            if self.auth_delivery.is_some() {
400                let db = capy_db::connect(&config.database).await?;
401                println!(
402                    "Pruned {} expired auth records.",
403                    capy_auth::prune(&db).await?
404                );
405                return Ok(());
406            }
407            return Err(AppError::Configuration(
408                "Install auth with capy make:auth before pruning.".into(),
409            ));
410        }
411        init_logging(&config);
412        let db = capy_db::connect(&config.database).await?;
413        match command {
414            "migrate" => {
415                M::up(&db, None).await?;
416                println!("Migrations applied.");
417            }
418            "migrate:rollback" => {
419                M::down(&db, Some(1)).await?;
420                println!("Rolled back the latest migration.");
421            }
422            "migrate:status" => {
423                let statuses = capy_db::status::<M>(&db).await?;
424                if statuses.is_empty() {
425                    println!("No migrations registered.");
426                }
427                for status in statuses {
428                    println!(
429                        "{:<8} {}",
430                        if status.applied { "Applied" } else { "Pending" },
431                        status.name
432                    );
433                }
434            }
435            _ => {
436                let listener =
437                    tokio::net::TcpListener::bind((config.host(), config.port())).await?;
438                let address = listener.local_addr()?;
439                if config.app.environment == "production" {
440                    tracing::info!(%address, environment = %config.app.environment, "Capy ready");
441                } else if std::env::var_os("CAPY_DEV").is_some() {
442                    println!(
443                        "āœ“ Database connected\nāœ“ Backend ready\nServer running on http://{address}"
444                    );
445                } else {
446                    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.",
447                        env!("CARGO_PKG_VERSION"), config.app.environment,
448                        if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
449                }
450                let shutdown_timeout = Duration::from_secs(config.server.shutdown_timeout_seconds);
451                let context = AppContext {
452                    config: Arc::new(config),
453                    db,
454                };
455                serve(
456                    listener,
457                    self.into_router(context),
458                    shutdown_timeout,
459                    shutdown_signal(),
460                )
461                .await?;
462            }
463        }
464        Ok(())
465    }
466}
467
468// axum-server owns connection cancellation. Merely dropping axum::serve's
469// graceful future leaves its detached connection tasks running in shared runtimes.
470pub(crate) async fn serve(
471    listener: tokio::net::TcpListener,
472    router: axum::Router,
473    timeout: Duration,
474    signal: impl std::future::Future<Output = ()>,
475) -> Result<()> {
476    let handle = axum_server::Handle::new();
477    let server = axum_server::from_tcp(listener.into_std()?)?
478        .handle(handle.clone())
479        .serve(router.into_make_service_with_connect_info::<std::net::SocketAddr>());
480    tokio::pin!(server);
481    tokio::select! {
482        result = &mut server => { result?; }
483        () = signal => {
484            tracing::info!("shutdown requested");
485            handle.graceful_shutdown(None);
486            tracing::info!("waiting for active requests");
487            match tokio::time::timeout(timeout, &mut server).await {
488                Ok(result) => result?,
489                Err(_) => {
490                    tracing::warn!("shutdown deadline reached");
491                    handle.shutdown();
492                    server.await?;
493                }
494            }
495        }
496    }
497    tracing::info!("server stopped");
498    Ok(())
499}
500
501fn init_logging(config: &AppConfig) {
502    let filter = EnvFilter::try_from_default_env()
503        .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
504    if config.app.environment != "production"
505        && std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
506    {
507        let _ = tracing_subscriber::fmt()
508            .with_env_filter(filter)
509            .with_ansi(false)
510            .json()
511            .with_writer(crate::dev_logging::writer)
512            .try_init();
513    } else if config.app.environment == "production" {
514        let _ = tracing_subscriber::fmt()
515            .with_env_filter(filter)
516            .json()
517            .try_init();
518    } else {
519        let _ = tracing_subscriber::fmt()
520            .with_env_filter(filter)
521            .compact()
522            .try_init();
523    }
524}
525
526async fn shutdown_signal() {
527    let ctrl_c = async {
528        let _ = tokio::signal::ctrl_c().await;
529    };
530    #[cfg(unix)]
531    let terminate = async {
532        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
533            Ok(mut stream) => {
534                stream.recv().await;
535            }
536            Err(_) => std::future::pending::<()>().await,
537        }
538    };
539    #[cfg(not(unix))]
540    let terminate = std::future::pending::<()>();
541    tokio::select! { () = ctrl_c => {}, () = terminate => {} }
542}