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};
  9use serde::Deserialize;
 10use std::{
 11    net::{SocketAddr, TcpListener},
 12    sync::Arc,
 13};
 14use tracing::metadata::LevelFilter;
 15
 16#[derive(Default, Deserialize)]
 17pub struct Config {
 18    pub http_port: u16,
 19    pub database_url: String,
 20    pub api_token: String,
 21    pub honeycomb_api_key: Option<String>,
 22    pub honeycomb_dataset: Option<String>,
 23    pub trace_level: Option<String>,
 24}
 25
 26pub struct AppState {
 27    db: Arc<dyn Db>,
 28    api_token: String,
 29}
 30
 31impl AppState {
 32    async fn new(config: &Config) -> Result<Arc<Self>> {
 33        let db = PostgresDb::new(&config.database_url, 5).await?;
 34        let this = Self {
 35            db: Arc::new(db),
 36            api_token: config.api_token.clone(),
 37        };
 38        Ok(Arc::new(this))
 39    }
 40}
 41
 42#[tokio::main]
 43async fn main() -> Result<()> {
 44    env_logger::init();
 45
 46    if let Err(error) = env::load_dotenv() {
 47        log::error!(
 48            "error loading .env.toml (this is expected in production): {}",
 49            error
 50        );
 51    }
 52
 53    let config = envy::from_env::<Config>().expect("error loading config");
 54    init_tracing(&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}
115
116pub fn init_tracing(config: &Config) -> Option<()> {
117    use opentelemetry::KeyValue;
118    use opentelemetry_otlp::WithExportConfig;
119    use std::str::FromStr;
120    use tracing_opentelemetry::OpenTelemetryLayer;
121    use tracing_subscriber::layer::SubscriberExt;
122
123    let (honeycomb_api_key, honeycomb_dataset) = config
124        .honeycomb_api_key
125        .clone()
126        .zip(config.honeycomb_dataset.clone())?;
127
128    let mut metadata = tonic::metadata::MetadataMap::new();
129    metadata.insert("x-honeycomb-team", honeycomb_api_key.parse().unwrap());
130    let tracer = opentelemetry_otlp::new_pipeline()
131        .tracing()
132        .with_exporter(
133            opentelemetry_otlp::new_exporter()
134                .tonic()
135                .with_endpoint("https://api.honeycomb.io")
136                .with_metadata(metadata),
137        )
138        .with_trace_config(opentelemetry::sdk::trace::config().with_resource(
139            opentelemetry::sdk::Resource::new(vec![KeyValue::new(
140                "service.name",
141                honeycomb_dataset,
142            )]),
143        ))
144        .install_batch(opentelemetry::runtime::Tokio)
145        .expect("failed to initialize tracing");
146
147    let subscriber = tracing_subscriber::Registry::default()
148        .with(OpenTelemetryLayer::new(tracer))
149        .with(tracing_subscriber::fmt::layer())
150        .with(
151            config
152                .trace_level
153                .as_ref()
154                .map_or(LevelFilter::INFO, |level| {
155                    LevelFilter::from_str(level).unwrap()
156                }),
157        );
158
159    tracing::subscriber::set_global_default(subscriber).unwrap();
160
161    None
162}