lib.rs

  1pub mod api;
  2pub mod auth;
  3pub mod db;
  4pub mod env;
  5pub mod executor;
  6pub mod rpc;
  7
  8#[cfg(test)]
  9mod tests;
 10
 11use anyhow::anyhow;
 12use aws_config::{BehaviorVersion, Region};
 13use axum::{http::StatusCode, response::IntoResponse};
 14use db::Database;
 15use executor::Executor;
 16use serde::Deserialize;
 17use std::{path::PathBuf, sync::Arc};
 18use util::ResultExt;
 19
 20pub type Result<T, E = Error> = std::result::Result<T, E>;
 21
 22pub enum Error {
 23    Http(StatusCode, String),
 24    Database(sea_orm::error::DbErr),
 25    Internal(anyhow::Error),
 26}
 27
 28impl From<anyhow::Error> for Error {
 29    fn from(error: anyhow::Error) -> Self {
 30        Self::Internal(error)
 31    }
 32}
 33
 34impl From<sea_orm::error::DbErr> for Error {
 35    fn from(error: sea_orm::error::DbErr) -> Self {
 36        Self::Database(error)
 37    }
 38}
 39
 40impl From<axum::Error> for Error {
 41    fn from(error: axum::Error) -> Self {
 42        Self::Internal(error.into())
 43    }
 44}
 45
 46impl From<hyper::Error> for Error {
 47    fn from(error: hyper::Error) -> Self {
 48        Self::Internal(error.into())
 49    }
 50}
 51
 52impl From<serde_json::Error> for Error {
 53    fn from(error: serde_json::Error) -> Self {
 54        Self::Internal(error.into())
 55    }
 56}
 57
 58impl IntoResponse for Error {
 59    fn into_response(self) -> axum::response::Response {
 60        match self {
 61            Error::Http(code, message) => {
 62                log::error!("HTTP error {}: {}", code, &message);
 63                (code, message).into_response()
 64            }
 65            Error::Database(error) => {
 66                log::error!(
 67                    "HTTP error {}: {:?}",
 68                    StatusCode::INTERNAL_SERVER_ERROR,
 69                    &error
 70                );
 71                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
 72            }
 73            Error::Internal(error) => {
 74                log::error!(
 75                    "HTTP error {}: {:?}",
 76                    StatusCode::INTERNAL_SERVER_ERROR,
 77                    &error
 78                );
 79                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
 80            }
 81        }
 82    }
 83}
 84
 85impl std::fmt::Debug for Error {
 86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 87        match self {
 88            Error::Http(code, message) => (code, message).fmt(f),
 89            Error::Database(error) => error.fmt(f),
 90            Error::Internal(error) => error.fmt(f),
 91        }
 92    }
 93}
 94
 95impl std::fmt::Display for Error {
 96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 97        match self {
 98            Error::Http(code, message) => write!(f, "{code}: {message}"),
 99            Error::Database(error) => error.fmt(f),
100            Error::Internal(error) => error.fmt(f),
101        }
102    }
103}
104
105impl std::error::Error for Error {}
106
107#[derive(Deserialize)]
108pub struct Config {
109    pub http_port: u16,
110    pub database_url: String,
111    pub database_max_connections: u32,
112    pub api_token: String,
113    pub clickhouse_url: Option<String>,
114    pub clickhouse_user: Option<String>,
115    pub clickhouse_password: Option<String>,
116    pub clickhouse_database: Option<String>,
117    pub invite_link_prefix: String,
118    pub live_kit_server: Option<String>,
119    pub live_kit_key: Option<String>,
120    pub live_kit_secret: Option<String>,
121    pub rust_log: Option<String>,
122    pub log_json: Option<bool>,
123    pub blob_store_url: Option<String>,
124    pub blob_store_region: Option<String>,
125    pub blob_store_access_key: Option<String>,
126    pub blob_store_secret_key: Option<String>,
127    pub blob_store_bucket: Option<String>,
128    pub zed_environment: Arc<str>,
129    pub zed_client_checksum_seed: Option<String>,
130    pub slack_panics_webhook: Option<String>,
131}
132
133impl Config {
134    pub fn is_development(&self) -> bool {
135        self.zed_environment == "development".into()
136    }
137}
138
139#[derive(Default, Deserialize)]
140pub struct MigrateConfig {
141    pub database_url: String,
142    pub migrations_path: Option<PathBuf>,
143}
144
145pub struct AppState {
146    pub db: Arc<Database>,
147    pub live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
148    pub blob_store_client: Option<aws_sdk_s3::Client>,
149    pub clickhouse_client: Option<clickhouse::Client>,
150    pub config: Config,
151}
152
153impl AppState {
154    pub async fn new(config: Config) -> Result<Arc<Self>> {
155        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
156        db_options.max_connections(config.database_max_connections);
157        let mut db = Database::new(db_options, Executor::Production).await?;
158        db.initialize_notification_kinds().await?;
159
160        let live_kit_client = if let Some(((server, key), secret)) = config
161            .live_kit_server
162            .as_ref()
163            .zip(config.live_kit_key.as_ref())
164            .zip(config.live_kit_secret.as_ref())
165        {
166            Some(Arc::new(live_kit_server::api::LiveKitClient::new(
167                server.clone(),
168                key.clone(),
169                secret.clone(),
170            )) as Arc<dyn live_kit_server::api::Client>)
171        } else {
172            None
173        };
174
175        let this = Self {
176            db: Arc::new(db),
177            live_kit_client,
178            blob_store_client: build_blob_store_client(&config).await.log_err(),
179            clickhouse_client: build_clickhouse_client(&config).log_err(),
180            config,
181        };
182        Ok(Arc::new(this))
183    }
184}
185
186async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
187    let keys = aws_sdk_s3::config::Credentials::new(
188        config
189            .blob_store_access_key
190            .clone()
191            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
192        config
193            .blob_store_secret_key
194            .clone()
195            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
196        None,
197        None,
198        "env",
199    );
200
201    let s3_config = aws_config::defaults(BehaviorVersion::latest())
202        .endpoint_url(
203            config
204                .blob_store_url
205                .as_ref()
206                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
207        )
208        .region(Region::new(
209            config
210                .blob_store_region
211                .clone()
212                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
213        ))
214        .credentials_provider(keys)
215        .load()
216        .await;
217
218    Ok(aws_sdk_s3::Client::new(&s3_config))
219}
220
221fn build_clickhouse_client(config: &Config) -> anyhow::Result<clickhouse::Client> {
222    Ok(clickhouse::Client::default()
223        .with_url(
224            config
225                .clickhouse_url
226                .as_ref()
227                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
228        )
229        .with_user(
230            config
231                .clickhouse_user
232                .as_ref()
233                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
234        )
235        .with_password(
236            config
237                .clickhouse_password
238                .as_ref()
239                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
240        )
241        .with_database(
242            config
243                .clickhouse_database
244                .as_ref()
245                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
246        ))
247}