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}
131
132impl Config {
133    pub fn is_development(&self) -> bool {
134        self.zed_environment == "development".into()
135    }
136}
137
138#[derive(Default, Deserialize)]
139pub struct MigrateConfig {
140    pub database_url: String,
141    pub migrations_path: Option<PathBuf>,
142}
143
144pub struct AppState {
145    pub db: Arc<Database>,
146    pub live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
147    pub blob_store_client: Option<aws_sdk_s3::Client>,
148    pub clickhouse_client: Option<clickhouse::Client>,
149    pub config: Config,
150}
151
152impl AppState {
153    pub async fn new(config: Config) -> Result<Arc<Self>> {
154        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
155        db_options.max_connections(config.database_max_connections);
156        let mut db = Database::new(db_options, Executor::Production).await?;
157        db.initialize_notification_kinds().await?;
158
159        let live_kit_client = if let Some(((server, key), secret)) = config
160            .live_kit_server
161            .as_ref()
162            .zip(config.live_kit_key.as_ref())
163            .zip(config.live_kit_secret.as_ref())
164        {
165            Some(Arc::new(live_kit_server::api::LiveKitClient::new(
166                server.clone(),
167                key.clone(),
168                secret.clone(),
169            )) as Arc<dyn live_kit_server::api::Client>)
170        } else {
171            None
172        };
173
174        let this = Self {
175            db: Arc::new(db),
176            live_kit_client,
177            blob_store_client: build_blob_store_client(&config).await.log_err(),
178            clickhouse_client: build_clickhouse_client(&config).log_err(),
179            config,
180        };
181        Ok(Arc::new(this))
182    }
183}
184
185async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
186    let keys = aws_sdk_s3::config::Credentials::new(
187        config
188            .blob_store_access_key
189            .clone()
190            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
191        config
192            .blob_store_secret_key
193            .clone()
194            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
195        None,
196        None,
197        "env",
198    );
199
200    let s3_config = aws_config::defaults(BehaviorVersion::latest())
201        .endpoint_url(
202            config
203                .blob_store_url
204                .as_ref()
205                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
206        )
207        .region(Region::new(
208            config
209                .blob_store_region
210                .clone()
211                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
212        ))
213        .credentials_provider(keys)
214        .load()
215        .await;
216
217    Ok(aws_sdk_s3::Client::new(&s3_config))
218}
219
220fn build_clickhouse_client(config: &Config) -> anyhow::Result<clickhouse::Client> {
221    Ok(clickhouse::Client::default()
222        .with_url(
223            config
224                .clickhouse_url
225                .as_ref()
226                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
227        )
228        .with_user(
229            config
230                .clickhouse_user
231                .as_ref()
232                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
233        )
234        .with_password(
235            config
236                .clickhouse_password
237                .as_ref()
238                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
239        )
240        .with_database(
241            config
242                .clickhouse_database
243                .as_ref()
244                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
245        ))
246}