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<axum::http::Error> for Error {
 47    fn from(error: axum::http::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: config
180                .clickhouse_url
181                .as_ref()
182                .and_then(|_| build_clickhouse_client(&config).log_err()),
183            config,
184        };
185        Ok(Arc::new(this))
186    }
187}
188
189async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
190    let keys = aws_sdk_s3::config::Credentials::new(
191        config
192            .blob_store_access_key
193            .clone()
194            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
195        config
196            .blob_store_secret_key
197            .clone()
198            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
199        None,
200        None,
201        "env",
202    );
203
204    let s3_config = aws_config::defaults(BehaviorVersion::latest())
205        .endpoint_url(
206            config
207                .blob_store_url
208                .as_ref()
209                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
210        )
211        .region(Region::new(
212            config
213                .blob_store_region
214                .clone()
215                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
216        ))
217        .credentials_provider(keys)
218        .load()
219        .await;
220
221    Ok(aws_sdk_s3::Client::new(&s3_config))
222}
223
224fn build_clickhouse_client(config: &Config) -> anyhow::Result<clickhouse::Client> {
225    Ok(clickhouse::Client::default()
226        .with_url(
227            config
228                .clickhouse_url
229                .as_ref()
230                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
231        )
232        .with_user(
233            config
234                .clickhouse_user
235                .as_ref()
236                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
237        )
238        .with_password(
239            config
240                .clickhouse_password
241                .as_ref()
242                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
243        )
244        .with_database(
245            config
246                .clickhouse_database
247                .as_ref()
248                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
249        ))
250}