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