mod api; mod auth; mod db; mod env; mod rpc; use axum::{body::Body, http::StatusCode, response::IntoResponse, Router}; use db::{Db, PostgresDb}; use opentelemetry::{ trace::{get_active_span, Tracer}, KeyValue, }; use serde::Deserialize; use std::{ net::{SocketAddr, TcpListener}, sync::Arc, }; #[derive(Default, Deserialize)] pub struct Config { pub http_port: u16, pub database_url: String, pub api_token: String, pub honeycomb_api_key: Option, pub honeycomb_dataset: Option, } pub struct AppState { db: Arc, api_token: String, } impl AppState { async fn new(config: &Config) -> Result> { let db = PostgresDb::new(&config.database_url, 5).await?; let this = Self { db: Arc::new(db), api_token: config.api_token.clone(), }; Ok(Arc::new(this)) } } #[tokio::main] async fn main() -> Result<()> { if std::env::var("LOG_JSON").is_ok() { json_env_logger::init(); } else { env_logger::init(); } if let Err(error) = env::load_dotenv() { log::error!( "error loading .env.toml (this is expected in production): {}", error ); } let config = envy::from_env::().expect("error loading config"); init_tracing(&config); let state = AppState::new(&config).await?; let tracer = opentelemetry::global::tracer(""); tracer.in_span("testing", |_| { get_active_span(|span| { span.set_attribute(KeyValue::new("foo", "bar")); }); log::info!("testing in span"); }); let listener = TcpListener::bind(&format!("0.0.0.0:{}", config.http_port)) .expect("failed to bind TCP listener"); let app = Router::::new() .merge(api::routes(state.clone())) .merge(rpc::routes(state)); axum::Server::from_tcp(listener)? .serve(app.into_make_service_with_connect_info::()) .await?; Ok(()) } pub type Result = std::result::Result; pub enum Error { Http(StatusCode, String), Internal(anyhow::Error), } impl From for Error where E: Into, { fn from(error: E) -> Self { Self::Internal(error.into()) } } impl IntoResponse for Error { fn into_response(self) -> axum::response::Response { match self { Error::Http(code, message) => (code, message).into_response(), Error::Internal(error) => { (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response() } } } } impl std::fmt::Debug for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::Http(code, message) => (code, message).fmt(f), Error::Internal(error) => error.fmt(f), } } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::Http(code, message) => write!(f, "{code}: {message}"), Error::Internal(error) => error.fmt(f), } } } pub fn init_tracing(config: &Config) -> Option<()> { use opentelemetry_otlp::WithExportConfig; let (honeycomb_api_key, honeycomb_dataset) = config .honeycomb_api_key .clone() .zip(config.honeycomb_dataset.clone())?; let mut metadata = tonic::metadata::MetadataMap::new(); metadata.insert("x-honeycomb-team", honeycomb_api_key.parse().unwrap()); metadata.insert("x-honeycomb-dataset", honeycomb_dataset.parse().unwrap()); opentelemetry_otlp::new_pipeline() .tracing() .with_exporter( opentelemetry_otlp::new_exporter() .tonic() .with_endpoint("api.honeycomb.io:443") .with_metadata(metadata), ) .install_batch(opentelemetry::runtime::Tokio) .expect("failed to initialize tracing"); None }