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    let rpc = Peer::new();
 55    run_server(
 56        state.clone(),
 57        rpc,
 58        TcpListener::bind(&format!("0.0.0.0:{}", config.http_port))
 59            .expect("failed to bind TCP listener"),
 60    )
 61    .await?;
 62    Ok(())
 63}
 64
 65pub async fn run_server(
 66    state: Arc<AppState>,
 67    peer: Arc<Peer>,
 68    listener: TcpListener,
 69) -> Result<()> {
 70    // TODO: Compression on API routes?
 71    // TODO: Authenticate API routes.
 72
 73    let app = Router::<Body>::new().merge(api::routes(state.clone()));
 74
 75    // TODO: Add rpc routes
 76
 77    axum::Server::from_tcp(listener)?
 78        .serve(app.into_make_service())
 79        .await?;
 80
 81    Ok(())
 82}
 83
 84pub type Result<T> = std::result::Result<T, Error>;
 85
 86pub enum Error {
 87    Http(StatusCode, String),
 88    Internal(anyhow::Error),
 89}
 90
 91impl<E> From<E> for Error
 92where
 93    E: Into<anyhow::Error>,
 94{
 95    fn from(error: E) -> Self {
 96        Self::Internal(error.into())
 97    }
 98}
 99
100impl IntoResponse for Error {
101    fn into_response(self) -> axum::response::Response {
102        match self {
103            Error::Http(code, message) => (code, message).into_response(),
104            Error::Internal(error) => {
105                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
106            }
107        }
108    }
109}
110
111impl std::fmt::Debug for Error {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        match self {
114            Error::Http(code, message) => (code, message).fmt(f),
115            Error::Internal(error) => error.fmt(f),
116        }
117    }
118}
119
120impl std::fmt::Display for Error {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        match self {
123            Error::Http(code, message) => write!(f, "{code}: {message}"),
124            Error::Internal(error) => error.fmt(f),
125        }
126    }
127}