main.rs

  1mod api;
  2mod auth;
  3mod db;
  4mod env;
  5mod rpc;
  6
  7use axum::{body::Body, http::StatusCode, response::IntoResponse, Router};
  8use db::{Db, PostgresDb};
  9
 10use serde::Deserialize;
 11use std::{
 12    net::{SocketAddr, TcpListener},
 13    sync::Arc,
 14};
 15
 16#[derive(Default, Deserialize)]
 17pub struct Config {
 18    pub http_port: u16,
 19    pub database_url: String,
 20    pub api_token: String,
 21}
 22
 23pub struct AppState {
 24    db: Arc<dyn Db>,
 25    api_token: String,
 26}
 27
 28impl AppState {
 29    async fn new(config: &Config) -> Result<Arc<Self>> {
 30        let db = PostgresDb::new(&config.database_url, 5).await?;
 31        let this = Self {
 32            db: Arc::new(db),
 33            api_token: config.api_token.clone(),
 34        };
 35        Ok(Arc::new(this))
 36    }
 37}
 38
 39#[tokio::main]
 40async fn main() -> Result<()> {
 41    if std::env::var("LOG_JSON").is_ok() {
 42        json_env_logger::init();
 43    } else {
 44        env_logger::init();
 45    }
 46
 47    if let Err(error) = env::load_dotenv() {
 48        log::error!(
 49            "error loading .env.toml (this is expected in production): {}",
 50            error
 51        );
 52    }
 53
 54    let config = envy::from_env::<Config>().expect("error loading config");
 55    let state = AppState::new(&config).await?;
 56
 57    let listener = TcpListener::bind(&format!("0.0.0.0:{}", config.http_port))
 58        .expect("failed to bind TCP listener");
 59
 60    let app = Router::<Body>::new()
 61        .merge(api::routes(state.clone()))
 62        .merge(rpc::routes(state));
 63
 64    axum::Server::from_tcp(listener)?
 65        .serve(app.into_make_service_with_connect_info::<SocketAddr>())
 66        .await?;
 67
 68    Ok(())
 69}
 70
 71pub type Result<T, E = Error> = std::result::Result<T, E>;
 72
 73pub enum Error {
 74    Http(StatusCode, String),
 75    Internal(anyhow::Error),
 76}
 77
 78impl<E> From<E> for Error
 79where
 80    E: Into<anyhow::Error>,
 81{
 82    fn from(error: E) -> Self {
 83        Self::Internal(error.into())
 84    }
 85}
 86
 87impl IntoResponse for Error {
 88    fn into_response(self) -> axum::response::Response {
 89        match self {
 90            Error::Http(code, message) => (code, message).into_response(),
 91            Error::Internal(error) => {
 92                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
 93            }
 94        }
 95    }
 96}
 97
 98impl std::fmt::Debug for Error {
 99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        match self {
101            Error::Http(code, message) => (code, message).fmt(f),
102            Error::Internal(error) => error.fmt(f),
103        }
104    }
105}
106
107impl std::fmt::Display for Error {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        match self {
110            Error::Http(code, message) => write!(f, "{code}: {message}"),
111            Error::Internal(error) => error.fmt(f),
112        }
113    }
114}