mod auth; mod user; use std::time::Duration; use axum::{ extract::{MatchedPath, Request}, response::Response, Router, }; use humantime::format_duration; use tokio::net::TcpListener; use tower_http::trace::TraceLayer; use tracing::{error, info, info_span, warn, Span}; use uuid::Uuid; use crate::{ db::DbPool, models::{AppError, Environment}, services::CachePool, }; #[derive(Clone)] pub struct AppState { db_pool: DbPool, cache_pool: CachePool, env: Environment, } impl AppState { pub fn new(db_pool: DbPool, cache_pool: CachePool, env: Environment) -> Self { Self { db_pool, cache_pool, env, } } pub fn db_pool(&self) -> &DbPool { &self.db_pool } pub fn cache_pool(&self) -> &CachePool { &self.cache_pool } pub fn env(&self) -> &Environment { &self.env } } pub async fn start_app( db_pool: DbPool, cache_pool: CachePool, env: Environment, ) -> Result<(), AppError> { let address = env.hostname(); let port = env.port(); info!("Listening on {address}:{port}..."); let listener = TcpListener::bind(format!("{address}:{port}")) .await .unwrap(); let logging_layer = TraceLayer::new_for_http() .make_span_with(|request: &Request| { let path = request .extensions() .get::() .map(MatchedPath::as_str).unwrap_or(request.uri().path()); info_span!("api_request", request_id = %Uuid::now_v7(), method = %request.method(), %path, status = tracing::field::Empty) }) .on_response(|response: &Response, duration: Duration, span: &Span| { let status = response.status(); span.record("status", status.to_string()); match status { w if w.is_redirection() => warn!(duration = ?format_duration(duration).to_string()), e if e.is_client_error() || e.is_server_error() => error!(duration = ?format_duration(duration).to_string()), _ => info!(duration = ?format_duration(duration).to_string()) } }); let state = AppState::new(db_pool, cache_pool, env); let app = Router::new() .merge(user::requests(state.clone())) .merge(auth::requests(state.clone())) .layer(logging_layer); info!("API started successfully."); axum::serve(listener, app) .await .map_err(AppError::app_startup)?; Ok(()) }