lib.rs

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