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 From<anyhow::Error> for Error {
 80    fn from(error: anyhow::Error) -> Self {
 81        Self::Internal(error)
 82    }
 83}
 84
 85impl From<sqlx::Error> for Error {
 86    fn from(error: sqlx::Error) -> Self {
 87        Self::Internal(error.into())
 88    }
 89}
 90
 91impl From<axum::Error> for Error {
 92    fn from(error: axum::Error) -> Self {
 93        Self::Internal(error.into())
 94    }
 95}
 96
 97impl From<hyper::Error> for Error {
 98    fn from(error: hyper::Error) -> Self {
 99        Self::Internal(error.into())
100    }
101}
102
103impl IntoResponse for Error {
104    fn into_response(self) -> axum::response::Response {
105        match self {
106            Error::Http(code, message) => (code, message).into_response(),
107            Error::Internal(error) => {
108                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
109            }
110        }
111    }
112}
113
114impl std::fmt::Debug for Error {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        match self {
117            Error::Http(code, message) => (code, message).fmt(f),
118            Error::Internal(error) => error.fmt(f),
119        }
120    }
121}
122
123impl std::fmt::Display for Error {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        match self {
126            Error::Http(code, message) => write!(f, "{code}: {message}"),
127            Error::Internal(error) => error.fmt(f),
128        }
129    }
130}
131
132impl std::error::Error for Error {}
133
134pub fn init_tracing(config: &Config) -> Option<()> {
135    use opentelemetry::KeyValue;
136    use opentelemetry_otlp::WithExportConfig;
137    use std::str::FromStr;
138    use tracing_opentelemetry::OpenTelemetryLayer;
139    use tracing_subscriber::layer::SubscriberExt;
140    let rust_log = config.rust_log.clone()?;
141
142    LogTracer::init().log_err()?;
143
144    let open_telemetry_layer = config
145        .honeycomb_api_key
146        .clone()
147        .zip(config.honeycomb_dataset.clone())
148        .map(|(honeycomb_api_key, honeycomb_dataset)| {
149            let mut metadata = tonic::metadata::MetadataMap::new();
150            metadata.insert("x-honeycomb-team", honeycomb_api_key.parse().unwrap());
151            let tracer = opentelemetry_otlp::new_pipeline()
152                .tracing()
153                .with_exporter(
154                    opentelemetry_otlp::new_exporter()
155                        .tonic()
156                        .with_endpoint("https://api.honeycomb.io")
157                        .with_metadata(metadata),
158                )
159                .with_trace_config(opentelemetry::sdk::trace::config().with_resource(
160                    opentelemetry::sdk::Resource::new(vec![KeyValue::new(
161                        "service.name",
162                        honeycomb_dataset,
163                    )]),
164                ))
165                .install_batch(opentelemetry::runtime::Tokio)
166                .expect("failed to initialize tracing");
167
168            OpenTelemetryLayer::new(tracer)
169        });
170
171    let subscriber = tracing_subscriber::Registry::default()
172        .with(open_telemetry_layer)
173        .with(if config.log_json.unwrap_or(false) {
174            Box::new(
175                tracing_subscriber::fmt::layer()
176                    .fmt_fields(JsonFields::default())
177                    .event_format(
178                        tracing_subscriber::fmt::format()
179                            .json()
180                            .flatten_event(true)
181                            .with_span_list(true),
182                    ),
183            ) as Box<dyn Layer<_> + Send + Sync>
184        } else {
185            Box::new(
186                tracing_subscriber::fmt::layer()
187                    .event_format(tracing_subscriber::fmt::format().pretty()),
188            )
189        })
190        .with(EnvFilter::from_str(rust_log.as_str()).log_err()?);
191
192    tracing::subscriber::set_global_default(subscriber).unwrap();
193
194    None
195}