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