1use crate::{AppConfig, AppContext, AppError, Result, Routes};
2use capy_db::{MigratorTrait, NoMigrations};
3use std::{marker::PhantomData, sync::Arc};
4use tracing_subscriber::EnvFilter;
5
6pub struct App<M = NoMigrations> {
8 routes: Routes,
9 config: Option<AppConfig>,
10 migrations: PhantomData<M>,
11}
12
13impl Default for App {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl App {
20 pub fn new() -> Self {
22 Self {
23 routes: Routes::new(),
24 config: None,
25 migrations: PhantomData,
26 }
27 }
28}
29
30impl<M: MigratorTrait> App<M> {
31 pub fn routes(mut self, routes: Routes) -> Self {
33 self.routes = routes;
34 self
35 }
36
37 pub fn config(mut self, config: AppConfig) -> Self {
39 self.config = Some(config);
40 self
41 }
42
43 pub fn migrations<N: MigratorTrait>(self, _migrator: N) -> App<N> {
46 App {
47 routes: self.routes,
48 config: self.config,
49 migrations: PhantomData,
50 }
51 }
52
53 pub fn into_router(self, context: AppContext) -> axum::Router {
56 self.routes
57 .into_router()
58 .with_state(context)
59 .layer(axum::middleware::from_fn(crate::diagnostics::request))
60 }
61
62 pub async fn run(self) -> Result<()> {
66 let mut args = std::env::args().skip(1);
67 let command = args.next().unwrap_or_else(|| "serve".into());
68 if args.next().is_some() {
69 return Err(AppError::Configuration(
70 "Unexpected arguments. Use the capy CLI for application commands.".into(),
71 ));
72 }
73 self.run_command(&command).await
74 }
75
76 pub async fn run_command(self, command: &str) -> Result<()> {
78 if command == "routes" {
79 for route in self.routes.inventory() {
80 println!("{:<7} {}", route.method, route.path);
81 }
82 return Ok(());
83 }
84 if !matches!(
85 command,
86 "serve" | "migrate" | "migrate:rollback" | "migrate:status"
87 ) {
88 return Err(AppError::Configuration(format!(
89 "Unknown application command: {command}"
90 )));
91 }
92 let config = match &self.config {
93 Some(config) => config.clone(),
94 None => AppConfig::load()?,
95 };
96 config.validate()?;
97 init_logging(&config);
98 let db = capy_db::connect(&config.database).await?;
99 match command {
100 "migrate" => {
101 M::up(&db, None).await?;
102 println!("Migrations applied.");
103 }
104 "migrate:rollback" => {
105 M::down(&db, Some(1)).await?;
106 println!("Rolled back the latest migration.");
107 }
108 "migrate:status" => {
109 let statuses = capy_db::status::<M>(&db).await?;
110 if statuses.is_empty() {
111 println!("No migrations registered.");
112 }
113 for status in statuses {
114 println!(
115 "{:<8} {}",
116 if status.applied { "Applied" } else { "Pending" },
117 status.name
118 );
119 }
120 }
121 _ => {
122 let listener =
123 tokio::net::TcpListener::bind((config.app.host.as_str(), config.app.port))
124 .await?;
125 let address = listener.local_addr()?;
126 if config.app.environment == "production" {
127 tracing::info!(%address, environment = %config.app.environment, "Capy ready");
128 } else {
129 println!("Capy v{}\n\nApplication\n http://{address}\n\nEnvironment\n {}\n\nDatabase\n {}\n\nReady.",
130 env!("CARGO_PKG_VERSION"), config.app.environment,
131 if config.database.url.starts_with("sqlite:") { "SQLite" } else { "PostgreSQL" });
132 }
133 let context = AppContext {
134 config: Arc::new(config),
135 db,
136 };
137 axum::serve(listener, self.into_router(context))
138 .with_graceful_shutdown(shutdown_signal())
139 .await?;
140 }
141 }
142 Ok(())
143 }
144}
145
146fn init_logging(config: &AppConfig) {
147 let filter = EnvFilter::try_from_default_env()
148 .unwrap_or_else(|_| EnvFilter::new(crate::diagnostics::DEFAULT_FILTER));
149 if config.app.environment == "production" {
150 let _ = tracing_subscriber::fmt()
151 .with_env_filter(filter)
152 .json()
153 .try_init();
154 } else {
155 let _ = tracing_subscriber::fmt()
156 .with_env_filter(filter)
157 .compact()
158 .try_init();
159 }
160}
161
162async fn shutdown_signal() {
163 let ctrl_c = async {
164 let _ = tokio::signal::ctrl_c().await;
165 };
166 #[cfg(unix)]
167 let terminate = async {
168 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
169 Ok(mut stream) => {
170 stream.recv().await;
171 }
172 Err(_) => std::future::pending::<()>().await,
173 }
174 };
175 #[cfg(not(unix))]
176 let terminate = std::future::pending::<()>();
177 tokio::select! { () = ctrl_c => {}, () = terminate => {} }
178}