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 qwen2_7b_api_key: Option<Arc<str>>,
155    pub qwen2_7b_api_url: Option<Arc<str>>,
156    pub zed_client_checksum_seed: Option<String>,
157    pub slack_panics_webhook: Option<String>,
158    pub auto_join_channel_id: Option<ChannelId>,
159    pub stripe_api_key: Option<String>,
160    pub stripe_price_id: Option<Arc<str>>,
161    pub supermaven_admin_api_key: Option<Arc<str>>,
162}
163
164impl Config {
165    pub fn is_development(&self) -> bool {
166        self.zed_environment == "development".into()
167    }
168
169    /// Returns the base `zed.dev` URL.
170    pub fn zed_dot_dev_url(&self) -> &str {
171        match self.zed_environment.as_ref() {
172            "development" => "http://localhost:3000",
173            "staging" => "https://staging.zed.dev",
174            _ => "https://zed.dev",
175        }
176    }
177}
178
179pub struct AppState {
180    pub db: Arc<Database>,
181    pub live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
182    pub blob_store_client: Option<aws_sdk_s3::Client>,
183    pub stripe_client: Option<Arc<stripe::Client>>,
184    pub rate_limiter: Arc<RateLimiter>,
185    pub executor: Executor,
186    pub clickhouse_client: Option<clickhouse::Client>,
187    pub config: Config,
188}
189
190impl AppState {
191    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
192        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
193        db_options.max_connections(config.database_max_connections);
194        let mut db = Database::new(db_options, Executor::Production).await?;
195        db.initialize_notification_kinds().await?;
196
197        let live_kit_client = if let Some(((server, key), secret)) = config
198            .live_kit_server
199            .as_ref()
200            .zip(config.live_kit_key.as_ref())
201            .zip(config.live_kit_secret.as_ref())
202        {
203            Some(Arc::new(live_kit_server::api::LiveKitClient::new(
204                server.clone(),
205                key.clone(),
206                secret.clone(),
207            )) as Arc<dyn live_kit_server::api::Client>)
208        } else {
209            None
210        };
211
212        let db = Arc::new(db);
213        let this = Self {
214            db: db.clone(),
215            live_kit_client,
216            blob_store_client: build_blob_store_client(&config).await.log_err(),
217            stripe_client: build_stripe_client(&config)
218                .await
219                .map(|client| Arc::new(client))
220                .log_err(),
221            rate_limiter: Arc::new(RateLimiter::new(db)),
222            executor,
223            clickhouse_client: config
224                .clickhouse_url
225                .as_ref()
226                .and_then(|_| build_clickhouse_client(&config).log_err()),
227            config,
228        };
229        Ok(Arc::new(this))
230    }
231}
232
233async fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
234    let api_key = config
235        .stripe_api_key
236        .as_ref()
237        .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
238
239    Ok(stripe::Client::new(api_key))
240}
241
242async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
243    let keys = aws_sdk_s3::config::Credentials::new(
244        config
245            .blob_store_access_key
246            .clone()
247            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
248        config
249            .blob_store_secret_key
250            .clone()
251            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
252        None,
253        None,
254        "env",
255    );
256
257    let s3_config = aws_config::defaults(BehaviorVersion::latest())
258        .endpoint_url(
259            config
260                .blob_store_url
261                .as_ref()
262                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
263        )
264        .region(Region::new(
265            config
266                .blob_store_region
267                .clone()
268                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
269        ))
270        .credentials_provider(keys)
271        .load()
272        .await;
273
274    Ok(aws_sdk_s3::Client::new(&s3_config))
275}
276
277fn build_clickhouse_client(config: &Config) -> anyhow::Result<clickhouse::Client> {
278    Ok(clickhouse::Client::default()
279        .with_url(
280            config
281                .clickhouse_url
282                .as_ref()
283                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
284        )
285        .with_user(
286            config
287                .clickhouse_user
288                .as_ref()
289                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
290        )
291        .with_password(
292            config
293                .clickhouse_password
294                .as_ref()
295                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
296        )
297        .with_database(
298            config
299                .clickhouse_database
300                .as_ref()
301                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
302        ))
303}