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