use crate::{AppConfig, AppContext, AppError, Result, Routes};
use capy_db::{MigratorTrait, NoMigrations};
use std::{collections::BTreeMap, marker::PhantomData, path::PathBuf, sync::Arc, time::Duration};
use tracing_subscriber::EnvFilter;
type OpenApiCustomizer = Arc<dyn Fn(&mut crate::ApiDocument) + Send + Sync>;
pub struct App<M = NoMigrations> {
events: capy_core::Events,
routes: Routes,
api_routes: Option<Routes>,
frontend: Option<PathBuf>,
config: Option<AppConfig>,
request_timeouts: BTreeMap<String, Option<Duration>>,
observer: crate::diagnostics::Observer,
openapi_customizer: Option<OpenApiCustomizer>,
#[cfg(feature = "auth")]
auth_delivery: Option<Arc<dyn capy_auth::ResetDelivery>>,
#[cfg(feature = "jobs")]
jobs: Option<capy_jobs::Jobs>,
#[cfg(feature = "mail")]
mail_enabled: bool,
#[cfg(feature = "mail")]
mailer: Option<capy_mail::Mailer>,
migrations: PhantomData<M>,
}
impl Default for App {
fn default() -> Self {
Self::new()
}
}
impl App {
pub fn new() -> Self {
Self {
events: capy_core::Events::new(),
routes: Routes::new(),
api_routes: None,
frontend: None,
config: None,
request_timeouts: BTreeMap::new(),
observer: None,
openapi_customizer: None,
#[cfg(feature = "auth")]
auth_delivery: None,
#[cfg(feature = "jobs")]
jobs: None,
#[cfg(feature = "mail")]
mail_enabled: false,
#[cfg(feature = "mail")]
mailer: None,
migrations: PhantomData,
}
}
}
impl<M: MigratorTrait> App<M> {
pub fn on<E: capy_core::Event>(
mut self,
listener: impl for<'a> Fn(&'a E, capy_core::EventContext<'a>) -> capy_core::EventFuture<'a>
+ Send
+ Sync
+ 'static,
) -> Self {
self.events = self.events.on::<E>(listener);
self
}
#[cfg(feature = "mail")]
pub fn mail(mut self) -> Self {
self.mail_enabled = true;
self
}
#[cfg(feature = "mail")]
pub fn with_mail(mut self, mailer: capy_mail::Mailer) -> Self {
self.mail_enabled = true;
self.mailer = Some(mailer);
self
}
#[cfg(feature = "mail")]
fn validate_mail(&self, config: &AppConfig) -> Result<()> {
if self.mail_enabled {
if let Some(mailer) = &self.mailer {
mailer.validate_environment(config.app.environment == "production")?;
} else {
capy_mail::Mailer::validate(config)?;
}
#[cfg(feature = "jobs")]
capy_mail::validate_jobs(self.jobs.clone().unwrap_or_default())?;
}
Ok(())
}
#[cfg(feature = "mail")]
fn configured_mailer(&self, config: &AppConfig) -> Result<Option<capy_mail::Mailer>> {
self.validate_mail(config)?;
if !self.mail_enabled {
return Ok(None);
}
self.mailer
.clone()
.map(Ok)
.unwrap_or_else(|| capy_mail::Mailer::from_config(config))
.map(Some)
}
#[cfg(feature = "auth")]
pub fn auth(mut self, delivery: impl capy_auth::ResetDelivery) -> Self {
self.auth_delivery = Some(Arc::new(delivery));
self
}
#[cfg(feature = "jobs")]
pub fn jobs(mut self, jobs: capy_jobs::Jobs) -> Self {
self.jobs = Some(jobs);
self
}
pub fn openapi_with(
mut self,
customize: impl Fn(&mut crate::ApiDocument) + Send + Sync + 'static,
) -> Self {
self.openapi_customizer = Some(Arc::new(customize));
self
}
pub fn openapi(&self) -> Result<crate::ApiDocument> {
let config = self
.config
.clone()
.map(Ok)
.unwrap_or_else(AppConfig::load_for_contracts)?;
self.api_document(&config)
}
fn api_document(&self, config: &AppConfig) -> Result<crate::ApiDocument> {
#[cfg(feature = "mail")]
self.validate_mail(config)?;
#[cfg(feature = "jobs")]
if let Some(jobs) = &self.jobs {
jobs.validate()?;
}
let mut routes = vec![("", &self.routes)];
if let Some(api) = &self.api_routes {
routes.push(("/api", api));
}
#[cfg(feature = "auth")]
let auth_routes = capy_auth::routes();
#[cfg(feature = "auth")]
if let Some(delivery) = &self.auth_delivery {
let production = config.app.environment == "production";
config.auth.validate(production)?;
config.http.client_ip.validate()?;
if production && delivery.development_only() {
return Err(AppError::Configuration("Install an application-owned password reset delivery adapter before enabling auth in production.".into()));
}
routes.push(("/api/auth", &auth_routes));
}
let mut document = crate::ApiDocument::from_routes(
config.api.title.as_deref().unwrap_or(&config.app.name),
&config.api.version,
routes,
)?;
#[cfg(feature = "auth")]
if self.auth_delivery.is_some() {
document.as_value_mut()["components"]["securitySchemes"]["session"] = crate::serde_json::json!({
"type": "apiKey", "in": "cookie",
"name": config.auth.cookie_name(config.app.environment == "production")
});
if let Some(paths) = document.as_value_mut()["paths"].as_object_mut() {
for (path, methods) in paths {
if let Some(methods) = methods.as_object_mut() {
for (method, operation) in methods {
let mutation =
matches!(method.as_str(), "post" | "put" | "patch" | "delete");
let bootstrap = path == "/api/auth/csrf" && method == "get";
if mutation || bootstrap {
if operation.get("parameters").is_none() {
operation["parameters"] = crate::serde_json::json!([]);
}
operation["parameters"].as_array_mut().expect("generated parameter array").push(crate::serde_json::json!({
"name": if bootstrap { "X-Capy-CSRF" } else { "X-CSRF-Token" },
"in": "header", "required": true,
"description": if bootstrap { "Send 1 to bootstrap a same-origin CSRF session." } else { "Synchronizer token from GET /api/auth/csrf; never a session secret." },
"schema": {"type": "string"}
}));
operation["responses"]["403"] = crate::serde_json::json!({"description": "CSRF or policy rejection", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ApiErrorResponse"}}}});
}
}
}
}
}
}
if let Some(customize) = &self.openapi_customizer {
customize(&mut document);
}
Ok(document)
}
pub fn observe_requests(mut self, observer: impl crate::RequestObserver) -> Self {
self.observer = Some(Arc::new(observer));
self
}
pub fn request_timeout_for(
mut self,
route: impl Into<String>,
timeout: Option<Duration>,
) -> Self {
self.request_timeouts.insert(route.into(), timeout);
self
}
pub fn api_routes(mut self, routes: Routes) -> Self {
self.api_routes = Some(routes);
self
}
pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
self.frontend = Some(directory.into());
self
}
pub fn routes(mut self, routes: Routes) -> Self {
self.routes = routes;
self
}
pub fn config(mut self, config: AppConfig) -> Self {
self.config = Some(config);
self
}
pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
App {
events: self.events,
routes: self.routes,
api_routes: self.api_routes,
frontend: self.frontend,
config: self.config,
request_timeouts: self.request_timeouts,
observer: self.observer,
openapi_customizer: self.openapi_customizer,
#[cfg(feature = "auth")]
auth_delivery: self.auth_delivery,
#[cfg(feature = "jobs")]
jobs: self.jobs,
#[cfg(feature = "mail")]
mail_enabled: self.mail_enabled,
#[cfg(feature = "mail")]
mailer: self.mailer,
migrations: PhantomData,
}
}
pub fn into_router(self, context: AppContext) -> axum::Router {
#[cfg(feature = "mail")]
let mailer = self.configured_mailer(&context.config);
let docs_enabled =
context.config.api.docs && context.config.app.environment != "production";
let schema = (context.config.api.openapi || docs_enabled).then(|| {
self.api_document(&context.config)
.map(|doc| doc.as_value().clone())
});
let http = context.config.http.clone();
let policy = crate::http_policy::HttpPolicy {
default_timeout: (http.request_timeout_seconds != 0)
.then(|| Duration::from_secs(http.request_timeout_seconds)),
overrides: self.request_timeouts,
};
let mut router = self.routes.into_router();
if let Some(api) = self.api_routes {
router = router.nest("/api", api.into_router());
}
#[cfg(feature = "auth")]
let auth = self.auth_delivery.map(|delivery| {
capy_auth::AuthService::new(context.clone(), delivery)
.map(|service| service.with_events(self.events.clone()))
});
#[cfg(feature = "auth")]
if auth.is_some() {
router = router.nest("/api/auth", capy_auth::routes().into_router());
}
if let Some(schema) = schema {
let schema = Arc::new(schema.map_err(|error| error.to_string()));
router = router.route(
"/openapi.json",
axum::routing::get(move || {
let schema = schema.clone();
async move {
match schema.as_ref() {
Ok(document) => Ok(axum::Json(document.clone())),
Err(_) => Err(AppError::Configuration(
"Invalid API contract. Run capy openapi to inspect the error."
.into(),
)),
}
}
}),
);
}
if docs_enabled {
router = router.route(
"/docs/api",
axum::routing::get(|| async {
axum::response::Html(include_str!("api_docs.html"))
}),
);
}
if let Some(directory) = self.frontend {
router =
router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
}
let mut router = router
.with_state(context)
.layer(axum::Extension(self.events));
#[cfg(feature = "mail")]
match mailer {
Ok(Some(mailer)) => router = router.layer(axum::Extension(mailer)),
Ok(None) => {}
Err(_) => {
router = axum::Router::new().fallback(|| async {
AppError::Configuration("Invalid mail configuration. Run capy check.".into())
})
}
}
#[cfg(feature = "auth")]
if let Some(service) = auth {
router = match service {
Ok(service) => service.protect(router),
Err(_) => axum::Router::new().fallback(|| async {
AppError::Configuration("Invalid auth configuration. Run capy check.".into())
}),
};
}
router = router
.layer(axum::extract::DefaultBodyLimit::max(http.max_body_bytes))
.layer(axum::middleware::from_fn_with_state(
policy,
crate::http_policy::deadline,
));
if http.compression {
router = router.layer(tower_http::compression::CompressionLayer::new());
}
router
.layer(axum::middleware::from_fn_with_state(
self.observer,
crate::diagnostics::request,
))
.layer(
tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new([
axum::http::header::AUTHORIZATION,
axum::http::header::COOKIE,
axum::http::HeaderName::from_static("x-csrf-token"),
]),
)
.layer(
tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([
axum::http::header::SET_COOKIE,
]),
)
}
pub async fn run(self) -> Result<()> {
let mut args = std::env::args().skip(1);
let command = args.next().unwrap_or_else(|| "serve".into());
#[cfg(feature = "jobs")]
if command.starts_with("queue:") {
return self
.run_queue_command(&command, &args.collect::<Vec<_>>())
.await;
}
#[cfg(feature = "mail")]
if matches!(command.as_str(), "mail:list" | "mail:show" | "mail:clear") {
let config = self
.config
.clone()
.map(Ok)
.unwrap_or_else(AppConfig::load_for_contracts)?;
return crate::mail_commands::run(&config, &command, &args.collect::<Vec<_>>());
}
if args.next().is_some() {
return Err(AppError::Configuration(
"Unexpected arguments. Use the capy CLI for application commands.".into(),
));
}
self.run_command(&command).await
}
#[cfg(feature = "jobs")]
async fn run_queue_command(self, command: &str, args: &[String]) -> Result<()> {
let config = self
.config
.clone()
.map(Ok)
.unwrap_or_else(AppConfig::load)?;
#[cfg(feature = "mail")]
let mailer = self.configured_mailer(&config)?;
let jobs = self.jobs;
#[cfg(feature = "mail")]
let jobs = if let Some(mailer) = mailer {
Some(capy_mail::register_jobs(jobs.unwrap_or_default(), mailer))
} else {
jobs
};
let jobs = jobs.ok_or_else(|| {
AppError::Configuration(
"Register jobs with App::jobs (capy make:job installs the conventional registry)."
.into(),
)
})?;
crate::job_commands::run(command, args, config, jobs).await
}
pub async fn run_command(self, command: &str) -> Result<()> {
#[cfg(feature = "jobs")]
if command.starts_with("queue:") {
return self.run_queue_command(command, &[]).await;
}
#[cfg(feature = "mail")]
if command == "mail:check" {
let config = self
.config
.clone()
.map(Ok)
.unwrap_or_else(AppConfig::load_for_contracts)?;
if !self.mail_enabled {
return Err(AppError::Configuration(
"Enable mail with App::mail.".into(),
));
}
self.validate_mail(&config)?;
println!("Mail: configuration and compiled templates valid. No DNS, authentication or delivery attempted.");
return Ok(());
}
if command == "__capy_contract" {
print!("{}", self.openapi()?.to_json()?);
return Ok(());
}
if command == "routes:api" {
self.openapi()?;
for (prefix, routes) in std::iter::once(("", &self.routes))
.chain(self.api_routes.as_ref().map(|r| ("/api", r)))
{
for route in routes.api_inventory() {
println!(
"{:<7} {:<28} {:<22} {}",
route.method,
format!("{prefix}{}", route.path),
route.operation_id.unwrap_or_default(),
route.response.unwrap_or_default()
);
}
}
#[cfg(feature = "auth")]
if self.auth_delivery.is_some() {
for route in capy_auth::routes().api_inventory() {
println!(
"{:<7} {:<28} {:<22} {}",
route.method,
format!("/api/auth{}", route.path),
route.operation_id.unwrap_or_default(),
route.response.unwrap_or_default()
);
}
}
return Ok(());
}
if command == "routes" {
for route in self.routes.inventory() {
println!("{:<7} {}", route.method, route.path);
}
if let Some(api) = &self.api_routes {
for route in api.inventory() {
println!("{:<7} /api{}", route.method, route.path);
}
}
#[cfg(feature = "auth")]
if self.auth_delivery.is_some() {
for route in capy_auth::routes().inventory() {
println!("{:<7} /api/auth{}", route.method, route.path);
}
}
return Ok(());
}
if !matches!(
command,
"serve" | "check" | "migrate" | "migrate:rollback" | "migrate:status" | "auth:prune"
) {
return Err(AppError::Configuration(format!(
"Unknown application command: {command}"
)));
}
let config = match &self.config {
Some(config) => config.clone(),
None => AppConfig::load()?,
};
config.validate()?;
if matches!(command, "serve" | "check") {
self.api_document(&config)?;
}
if command == "check" || (command == "serve" && config.app.environment == "production") {
if let Some(directory) = &self.frontend {
crate::frontend::validate(directory)?;
}
}
if command == "check" {
#[cfg(feature = "jobs")]
{
let jobs_enabled = self.jobs.is_some();
#[cfg(feature = "mail")]
let jobs_enabled = jobs_enabled || self.mail_enabled;
if jobs_enabled {
config.jobs.validate_database(&config.database)?;
}
}
let migrations = M::migrations();
let mut names = std::collections::BTreeSet::new();
for migration in &migrations {
if !names.insert(migration.name()) {
return Err(AppError::Configuration(
"Duplicate registered migration name.".into(),
));
}
}
println!(
"Configuration valid; {} migrations registered. No database connection opened.",
migrations.len()
);
return Ok(());
}
if command == "auth:prune" {
#[cfg(feature = "auth")]
if self.auth_delivery.is_some() {
let db = capy_db::connect(&config.database).await?;
println!(
"Pruned {} expired auth records.",
capy_auth::prune(&db).await?
);
return Ok(());
}
return Err(AppError::Configuration(
"Install auth with capy make:auth before pruning.".into(),
));
}
init_logging(&config);
let db = capy_db::connect(&config.database).await?;
match command {
"migrate" => {
M::up(&db, None).await?;
println!("Migrations applied.");
}
"migrate:rollback" => {
M::down(&db, Some(1)).await?;
println!("Rolled back the latest migration.");
}
"migrate:status" => {
let statuses = capy_db::status::<M>(&db).await?;
if statuses.is_empty() {
println!("No migrations registered.");
}
for status in statuses {
println!(
"{:<8} {}",
if status.applied { "Applied" } else { "Pending" },
status.name
);
}
}
_ => {
let listener =
tokio::net::TcpListener::bind((config.host(), config.port())).await?;
let address = listener.local_addr()?;
if config.app.environment == "production" {
tracing::info!(%address, environment = %config.app.environment, "Capy ready");
} else if std::env::var_os("CAPY_DEV").is_some() {
println!(
"✓ Database connected\n✓ Backend ready\nServer running on http://{address}"
);
} else {
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.",
env!("CARGO_PKG_VERSION"), config.app.environment,
if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
}
let shutdown_timeout = Duration::from_secs(config.server.shutdown_timeout_seconds);
let context = AppContext {
config: Arc::new(config),
db,
};
serve(
listener,
self.into_router(context),
shutdown_timeout,
shutdown_signal(),
)
.await?;
}
}
Ok(())
}
}
pub(crate) async fn serve(
listener: tokio::net::TcpListener,
router: axum::Router,
timeout: Duration,
signal: impl std::future::Future<Output = ()>,
) -> Result<()> {
let handle = axum_server::Handle::new();
let server = axum_server::from_tcp(listener.into_std()?)?
.handle(handle.clone())
.serve(router.into_make_service_with_connect_info::<std::net::SocketAddr>());
tokio::pin!(server);
tokio::select! {
result = &mut server => { result?; }
() = signal => {
tracing::info!("shutdown requested");
handle.graceful_shutdown(None);
tracing::info!("waiting for active requests");
match tokio::time::timeout(timeout, &mut server).await {
Ok(result) => result?,
Err(_) => {
tracing::warn!("shutdown deadline reached");
handle.shutdown();
server.await?;
}
}
}
}
tracing::info!("server stopped");
Ok(())
}
pub(crate) fn init_logging(config: &AppConfig) {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
if config.app.environment != "production"
&& std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
{
let _ = tracing_subscriber::fmt()
.with_env_filter(filter)
.with_ansi(false)
.json()
.with_writer(crate::dev_logging::writer)
.try_init();
} else if config.app.environment == "production" {
let _ = tracing_subscriber::fmt()
.with_env_filter(filter)
.json()
.try_init();
} else {
let _ = tracing_subscriber::fmt()
.with_env_filter(filter)
.compact()
.try_init();
}
}
pub(crate) async fn shutdown_signal() {
let ctrl_c = async {
let _ = tokio::signal::ctrl_c().await;
};
#[cfg(unix)]
let terminate = async {
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut stream) => {
stream.recv().await;
}
Err(_) => std::future::pending::<()>().await,
}
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! { () = ctrl_c => {}, () = terminate => {} }
}