main.rs

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