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_log::LogTracer;
 15use tracing_subscriber::{filter::EnvFilter, fmt::format::JsonFields, Layer};
 16use util::ResultExt;
 17
 18#[derive(Default, Deserialize)]
 19pub struct Config {
 20    pub http_port: u16,
 21    pub database_url: String,
 22    pub api_token: String,
 23    pub honeycomb_api_key: Option<String>,
 24    pub honeycomb_dataset: Option<String>,
 25    pub rust_log: Option<String>,
 26    pub log_json: Option<bool>,
 27}
 28
 29pub struct AppState {
 30    db: Arc<dyn Db>,
 31    api_token: String,
 32}
 33
 34impl AppState {
 35    async fn new(config: &Config) -> Result<Arc<Self>> {
 36        let db = PostgresDb::new(&config.database_url, 5).await?;
 37        let this = Self {
 38            db: Arc::new(db),
 39            api_token: config.api_token.clone(),
 40        };
 41        Ok(Arc::new(this))
 42    }
 43}
 44
 45#[tokio::main]
 46async fn main() -> Result<()> {
 47    if let Err(error) = env::load_dotenv() {
 48        eprintln!(
 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    init_tracing(&config);
 56    let state = AppState::new(&config).await?;
 57
 58    let listener = TcpListener::bind(&format!("0.0.0.0:{}", config.http_port))
 59        .expect("failed to bind TCP listener");
 60
 61    let app = Router::<Body>::new()
 62        .merge(api::routes(state.clone()))
 63        .merge(rpc::routes(state));
 64
 65    axum::Server::from_tcp(listener)?
 66        .serve(app.into_make_service_with_connect_info::<SocketAddr>())
 67        .await?;
 68
 69    Ok(())
 70}
 71
 72pub type Result<T, E = Error> = std::result::Result<T, E>;
 73
 74pub enum Error {
 75    Http(StatusCode, String),
 76    Internal(anyhow::Error),
 77}
 78
 79impl<E> From<E> for Error
 80where
 81    E: Into<anyhow::Error>,
 82{
 83    fn from(error: E) -> Self {
 84        Self::Internal(error.into())
 85    }
 86}
 87
 88impl IntoResponse for Error {
 89    fn into_response(self) -> axum::response::Response {
 90        match self {
 91            Error::Http(code, message) => (code, message).into_response(),
 92            Error::Internal(error) => {
 93                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
 94            }
 95        }
 96    }
 97}
 98
 99impl std::fmt::Debug for Error {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        match self {
102            Error::Http(code, message) => (code, message).fmt(f),
103            Error::Internal(error) => error.fmt(f),
104        }
105    }
106}
107
108impl std::fmt::Display for Error {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        match self {
111            Error::Http(code, message) => write!(f, "{code}: {message}"),
112            Error::Internal(error) => error.fmt(f),
113        }
114    }
115}
116
117pub fn init_tracing(config: &Config) -> Option<()> {
118    use opentelemetry::KeyValue;
119    use opentelemetry_otlp::WithExportConfig;
120    use std::str::FromStr;
121    use tracing_opentelemetry::OpenTelemetryLayer;
122    use tracing_subscriber::layer::SubscriberExt;
123    let rust_log = config.rust_log.clone()?;
124
125    LogTracer::init().log_err()?;
126
127    let open_telemetry_layer = config
128        .honeycomb_api_key
129        .clone()
130        .zip(config.honeycomb_dataset.clone())
131        .map(|(honeycomb_api_key, honeycomb_dataset)| {
132            let mut metadata = tonic::metadata::MetadataMap::new();
133            metadata.insert("x-honeycomb-team", honeycomb_api_key.parse().unwrap());
134            let tracer = opentelemetry_otlp::new_pipeline()
135                .tracing()
136                .with_exporter(
137                    opentelemetry_otlp::new_exporter()
138                        .tonic()
139                        .with_endpoint("https://api.honeycomb.io")
140                        .with_metadata(metadata),
141                )
142                .with_trace_config(opentelemetry::sdk::trace::config().with_resource(
143                    opentelemetry::sdk::Resource::new(vec![KeyValue::new(
144                        "service.name",
145                        honeycomb_dataset,
146                    )]),
147                ))
148                .install_batch(opentelemetry::runtime::Tokio)
149                .expect("failed to initialize tracing");
150
151            OpenTelemetryLayer::new(tracer)
152        });
153
154    let subscriber = tracing_subscriber::Registry::default()
155        .with(open_telemetry_layer)
156        .with(if config.log_json.unwrap_or(false) {
157            Box::new(
158                tracing_subscriber::fmt::layer()
159                    .fmt_fields(JsonFields::default())
160                    .event_format(
161                        tracing_subscriber::fmt::format()
162                            .json()
163                            .flatten_event(true)
164                            .with_span_list(true),
165                    ),
166            ) as Box<dyn Layer<_> + Send + Sync>
167        } else {
168            Box::new(
169                tracing_subscriber::fmt::layer()
170                    .event_format(tracing_subscriber::fmt::format().pretty()),
171            )
172        })
173        .with(EnvFilter::from_str(rust_log.as_str()).log_err()?);
174
175    tracing::subscriber::set_global_default(subscriber).unwrap();
176
177    None
178}