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
8pub 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 migrations: PhantomData<M>,
18}
19
20impl Default for App {
21 fn default() -> Self {
22 Self::new()
23 }
24}
25
26impl App {
27 pub fn new() -> Self {
29 Self {
30 routes: Routes::new(),
31 api_routes: None,
32 frontend: None,
33 config: None,
34 request_timeouts: BTreeMap::new(),
35 observer: None,
36 openapi_customizer: None,
37 migrations: PhantomData,
38 }
39 }
40}
41
42impl<M: MigratorTrait> App<M> {
43 pub fn openapi_with(
46 mut self,
47 customize: impl Fn(&mut crate::ApiDocument) + Send + Sync + 'static,
48 ) -> Self {
49 self.openapi_customizer = Some(Arc::new(customize));
50 self
51 }
52
53 pub fn openapi(&self) -> Result<crate::ApiDocument> {
55 let config = self
56 .config
57 .clone()
58 .map(Ok)
59 .unwrap_or_else(AppConfig::load_for_contracts)?;
60 self.api_document(&config)
61 }
62
63 fn api_document(&self, config: &AppConfig) -> Result<crate::ApiDocument> {
64 let mut routes = vec![("", &self.routes)];
65 if let Some(api) = &self.api_routes {
66 routes.push(("/api", api));
67 }
68 let mut document = crate::ApiDocument::from_routes(
69 config.api.title.as_deref().unwrap_or(&config.app.name),
70 &config.api.version,
71 routes,
72 )?;
73 if let Some(customize) = &self.openapi_customizer {
74 customize(&mut document);
75 }
76 Ok(document)
77 }
78
79 pub fn observe_requests(mut self, observer: impl crate::RequestObserver) -> Self {
81 self.observer = Some(Arc::new(observer));
82 self
83 }
84
85 pub fn request_timeout_for(
89 mut self,
90 route: impl Into<String>,
91 timeout: Option<Duration>,
92 ) -> Self {
93 self.request_timeouts.insert(route.into(), timeout);
94 self
95 }
96
97 pub fn api_routes(mut self, routes: Routes) -> Self {
100 self.api_routes = Some(routes);
101 self
102 }
103
104 pub fn frontend(mut self, directory: impl Into<PathBuf>) -> Self {
108 self.frontend = Some(directory.into());
109 self
110 }
111
112 pub fn routes(mut self, routes: Routes) -> Self {
114 self.routes = routes;
115 self
116 }
117
118 pub fn config(mut self, config: AppConfig) -> Self {
120 self.config = Some(config);
121 self
122 }
123
124 pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
127 App {
128 routes: self.routes,
129 api_routes: self.api_routes,
130 frontend: self.frontend,
131 config: self.config,
132 request_timeouts: self.request_timeouts,
133 observer: self.observer,
134 openapi_customizer: self.openapi_customizer,
135 migrations: PhantomData,
136 }
137 }
138
139 pub fn into_router(self, context: AppContext) -> axum::Router {
142 let docs_enabled =
143 context.config.api.docs && context.config.app.environment != "production";
144 let schema = (context.config.api.openapi || docs_enabled).then(|| {
145 self.api_document(&context.config)
146 .map(|doc| doc.as_value().clone())
147 });
148 let http = context.config.http.clone();
149 let policy = crate::http_policy::HttpPolicy {
150 default_timeout: (http.request_timeout_seconds != 0)
151 .then(|| Duration::from_secs(http.request_timeout_seconds)),
152 overrides: self.request_timeouts,
153 };
154 let mut router = self.routes.into_router();
155 if let Some(api) = self.api_routes {
156 router = router.nest("/api", api.into_router());
157 }
158 if let Some(schema) = schema {
159 let schema = Arc::new(schema.map_err(|error| error.to_string()));
162 router = router.route(
163 "/openapi.json",
164 axum::routing::get(move || {
165 let schema = schema.clone();
166 async move {
167 match schema.as_ref() {
168 Ok(document) => Ok(axum::Json(document.clone())),
169 Err(_) => Err(AppError::Configuration(
170 "Invalid API contract. Run capy openapi to inspect the error."
171 .into(),
172 )),
173 }
174 }
175 }),
176 );
177 }
178 if docs_enabled {
179 router = router.route(
180 "/docs/api",
181 axum::routing::get(|| async {
182 axum::response::Html(include_str!("api_docs.html"))
183 }),
184 );
185 }
186 if let Some(directory) = self.frontend {
187 router =
188 router.fallback(move |request| crate::frontend::serve(directory.clone(), request));
189 }
190 let mut router = router
191 .with_state(context)
192 .layer(axum::extract::DefaultBodyLimit::max(http.max_body_bytes))
193 .layer(axum::middleware::from_fn_with_state(
194 policy,
195 crate::http_policy::deadline,
196 ));
197 if http.compression {
198 router = router.layer(tower_http::compression::CompressionLayer::new());
199 }
200 router
201 .layer(axum::middleware::from_fn_with_state(
202 self.observer,
203 crate::diagnostics::request,
204 ))
205 .layer(
206 tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new([
207 axum::http::header::AUTHORIZATION,
208 axum::http::header::COOKIE,
209 ]),
210 )
211 .layer(
212 tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([
213 axum::http::header::SET_COOKIE,
214 ]),
215 )
216 }
217
218 pub async fn run(self) -> Result<()> {
222 let mut args = std::env::args().skip(1);
223 let command = args.next().unwrap_or_else(|| "serve".into());
224 if args.next().is_some() {
225 return Err(AppError::Configuration(
226 "Unexpected arguments. Use the capy CLI for application commands.".into(),
227 ));
228 }
229 self.run_command(&command).await
230 }
231
232 pub async fn run_command(self, command: &str) -> Result<()> {
234 if command == "__capy_contract" {
235 print!("{}", self.openapi()?.to_json()?);
236 return Ok(());
237 }
238 if command == "routes:api" {
239 self.openapi()?;
241 for (prefix, routes) in std::iter::once(("", &self.routes))
242 .chain(self.api_routes.as_ref().map(|r| ("/api", r)))
243 {
244 for route in routes.api_inventory() {
245 println!(
246 "{:<7} {:<28} {:<22} {}",
247 route.method,
248 format!("{prefix}{}", route.path),
249 route.operation_id.unwrap_or_default(),
250 route.response.unwrap_or_default()
251 );
252 }
253 }
254 return Ok(());
255 }
256 if command == "routes" {
257 for route in self.routes.inventory() {
258 println!("{:<7} {}", route.method, route.path);
259 }
260 if let Some(api) = &self.api_routes {
261 for route in api.inventory() {
262 println!("{:<7} /api{}", route.method, route.path);
263 }
264 }
265 return Ok(());
266 }
267 if !matches!(
268 command,
269 "serve" | "check" | "migrate" | "migrate:rollback" | "migrate:status"
270 ) {
271 return Err(AppError::Configuration(format!(
272 "Unknown application command: {command}"
273 )));
274 }
275 let config = match &self.config {
276 Some(config) => config.clone(),
277 None => AppConfig::load()?,
278 };
279 config.validate()?;
280 if matches!(command, "serve" | "check") {
282 self.api_document(&config)?;
283 }
284 if command == "check" || (command == "serve" && config.app.environment == "production") {
285 if let Some(directory) = &self.frontend {
286 crate::frontend::validate(directory)?;
287 }
288 }
289 if command == "check" {
290 let migrations = M::migrations();
291 let mut names = std::collections::BTreeSet::new();
292 for migration in &migrations {
293 if !names.insert(migration.name()) {
294 return Err(AppError::Configuration(
295 "Duplicate registered migration name.".into(),
296 ));
297 }
298 }
299 println!(
300 "Configuration valid; {} migrations registered. No database connection opened.",
301 migrations.len()
302 );
303 return Ok(());
304 }
305 init_logging(&config);
306 let db = capy_db::connect(&config.database).await?;
307 match command {
308 "migrate" => {
309 M::up(&db, None).await?;
310 println!("Migrations applied.");
311 }
312 "migrate:rollback" => {
313 M::down(&db, Some(1)).await?;
314 println!("Rolled back the latest migration.");
315 }
316 "migrate:status" => {
317 let statuses = capy_db::status::<M>(&db).await?;
318 if statuses.is_empty() {
319 println!("No migrations registered.");
320 }
321 for status in statuses {
322 println!(
323 "{:<8} {}",
324 if status.applied { "Applied" } else { "Pending" },
325 status.name
326 );
327 }
328 }
329 _ => {
330 let listener =
331 tokio::net::TcpListener::bind((config.host(), config.port())).await?;
332 let address = listener.local_addr()?;
333 if config.app.environment == "production" {
334 tracing::info!(%address, environment = %config.app.environment, "Capy ready");
335 } else if std::env::var_os("CAPY_DEV").is_some() {
336 println!(
337 "ā Database connected\nā Backend ready\nServer running on http://{address}"
338 );
339 } else {
340 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.",
341 env!("CARGO_PKG_VERSION"), config.app.environment,
342 if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
343 }
344 let shutdown_timeout = Duration::from_secs(config.server.shutdown_timeout_seconds);
345 let context = AppContext {
346 config: Arc::new(config),
347 db,
348 };
349 serve(
350 listener,
351 self.into_router(context),
352 shutdown_timeout,
353 shutdown_signal(),
354 )
355 .await?;
356 }
357 }
358 Ok(())
359 }
360}
361
362pub(crate) async fn serve(
365 listener: tokio::net::TcpListener,
366 router: axum::Router,
367 timeout: Duration,
368 signal: impl std::future::Future<Output = ()>,
369) -> Result<()> {
370 let handle = axum_server::Handle::new();
371 let server = axum_server::from_tcp(listener.into_std()?)?
372 .handle(handle.clone())
373 .serve(router.into_make_service());
374 tokio::pin!(server);
375 tokio::select! {
376 result = &mut server => { result?; }
377 () = signal => {
378 tracing::info!("shutdown requested");
379 handle.graceful_shutdown(None);
380 tracing::info!("waiting for active requests");
381 match tokio::time::timeout(timeout, &mut server).await {
382 Ok(result) => result?,
383 Err(_) => {
384 tracing::warn!("shutdown deadline reached");
385 handle.shutdown();
386 server.await?;
387 }
388 }
389 }
390 }
391 tracing::info!("server stopped");
392 Ok(())
393}
394
395fn init_logging(config: &AppConfig) {
396 let filter = EnvFilter::try_from_default_env()
397 .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
398 if config.app.environment != "production"
399 && std::env::var("CAPY_DEV_LOG").is_ok_and(|value| value == "1")
400 {
401 let _ = tracing_subscriber::fmt()
402 .with_env_filter(filter)
403 .with_ansi(false)
404 .json()
405 .with_writer(crate::dev_logging::writer)
406 .try_init();
407 } else if config.app.environment == "production" {
408 let _ = tracing_subscriber::fmt()
409 .with_env_filter(filter)
410 .json()
411 .try_init();
412 } else {
413 let _ = tracing_subscriber::fmt()
414 .with_env_filter(filter)
415 .compact()
416 .try_init();
417 }
418}
419
420async fn shutdown_signal() {
421 let ctrl_c = async {
422 let _ = tokio::signal::ctrl_c().await;
423 };
424 #[cfg(unix)]
425 let terminate = async {
426 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
427 Ok(mut stream) => {
428 stream.recv().await;
429 }
430 Err(_) => std::future::pending::<()>().await,
431 }
432 };
433 #[cfg(not(unix))]
434 let terminate = std::future::pending::<()>();
435 tokio::select! { () = ctrl_c => {}, () = terminate => {} }
436}