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
6pub 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 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 pub fn api_routes(mut self, routes: Routes) -> Self {
38 self.api_routes = Some(routes);
39 self
40 }
41
42 pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
46 self.frontend = Some(directory.into());
47 self
48 }
49
50 pub fn routes(mut self, routes: Routes) -> Self {
52 self.routes = routes;
53 self
54 }
55
56 pub fn config(mut self, config: AppConfig) -> Self {
58 self.config = Some(config);
59 self
60 }
61
62 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 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 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 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!(
168 "ā Database connected\nā Backend ready\nServer running on http://{address}"
169 );
170 } else {
171 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.",
172 env!("CARGO_PKG_VERSION"), config.app.environment,
173 if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
174 }
175 let context = AppContext {
176 config: Arc::new(config),
177 db,
178 };
179 axum::serve(listener, self.into_router(context))
180 .with_graceful_shutdown(shutdown_signal())
181 .await?;
182 }
183 }
184 Ok(())
185 }
186}
187
188fn init_logging(config: &AppConfig) {
189 let filter = EnvFilter::try_from_default_env()
190 .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
191 if config.app.environment != "production"
192 && std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
193 {
194 let _ = tracing_subscriber::fmt()
195 .with_env_filter(filter)
196 .with_ansi(false)
197 .json()
198 .with_writer(crate::dev_logging::writer)
199 .try_init();
200 } else if config.app.environment == "production" {
201 let _ = tracing_subscriber::fmt()
202 .with_env_filter(filter)
203 .json()
204 .try_init();
205 } else {
206 let _ = tracing_subscriber::fmt()
207 .with_env_filter(filter)
208 .compact()
209 .try_init();
210 }
211}
212
213async fn shutdown_signal() {
214 let ctrl_c = async {
215 let _ = tokio::signal::ctrl_c().await;
216 };
217 #[cfg(unix)]
218 let terminate = async {
219 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
220 Ok(mut stream) => {
221 stream.recv().await;
222 }
223 Err(_) => std::future::pending::<()>().await,
224 }
225 };
226 #[cfg(not(unix))]
227 let terminate = std::future::pending::<()>();
228 tokio::select! { () = ctrl_c => {}, () = terminate => {} }
229}