lib.rs

  1pub mod api;
  2pub mod auth;
  3pub mod db;
  4pub mod env;
  5pub mod executor;
  6pub mod llm;
  7pub mod migrations;
  8mod rate_limiter;
  9pub mod rpc;
 10pub mod seed;
 11
 12#[cfg(test)]
 13mod tests;
 14
 15use anyhow::anyhow;
 16use aws_config::{BehaviorVersion, Region};
 17use axum::{
 18    http::{HeaderMap, StatusCode},
 19    response::IntoResponse,
 20};
 21use db::{ChannelId, Database};
 22use executor::Executor;
 23pub use rate_limiter::*;
 24use serde::Deserialize;
 25use std::{path::PathBuf, sync::Arc};
 26use util::ResultExt;
 27
 28pub type Result<T, E = Error> = std::result::Result<T, E>;
 29
 30pub enum Error {
 31    Http(StatusCode, String, HeaderMap),
 32    Database(sea_orm::error::DbErr),
 33    Internal(anyhow::Error),
 34    Stripe(stripe::StripeError),
 35}
 36
 37impl From<anyhow::Error> for Error {
 38    fn from(error: anyhow::Error) -> Self {
 39        Self::Internal(error)
 40    }
 41}
 42
 43impl From<sea_orm::error::DbErr> for Error {
 44    fn from(error: sea_orm::error::DbErr) -> Self {
 45        Self::Database(error)
 46    }
 47}
 48
 49impl From<stripe::StripeError> for Error {
 50    fn from(error: stripe::StripeError) -> Self {
 51        Self::Stripe(error)
 52    }
 53}
 54
 55impl From<axum::Error> for Error {
 56    fn from(error: axum::Error) -> Self {
 57        Self::Internal(error.into())
 58    }
 59}
 60
 61impl From<axum::http::Error> for Error {
 62    fn from(error: axum::http::Error) -> Self {
 63        Self::Internal(error.into())
 64    }
 65}
 66
 67impl From<serde_json::Error> for Error {
 68    fn from(error: serde_json::Error) -> Self {
 69        Self::Internal(error.into())
 70    }
 71}
 72
 73impl Error {
 74    fn http(code: StatusCode, message: String) -> Self {
 75        Self::Http(code, message, HeaderMap::default())
 76    }
 77}
 78
 79impl IntoResponse for Error {
 80    fn into_response(self) -> axum::response::Response {
 81        match self {
 82            Error::Http(code, message, headers) => {
 83                log::error!("HTTP error {}: {}", code, &message);
 84                (code, headers, message).into_response()
 85            }
 86            Error::Database(error) => {
 87                log::error!(
 88                    "HTTP error {}: {:?}",
 89                    StatusCode::INTERNAL_SERVER_ERROR,
 90                    &error
 91                );
 92                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
 93            }
 94            Error::Internal(error) => {
 95                log::error!(
 96                    "HTTP error {}: {:?}",
 97                    StatusCode::INTERNAL_SERVER_ERROR,
 98                    &error
 99                );
100                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
101            }
102            Error::Stripe(error) => {
103                log::error!(
104                    "HTTP error {}: {:?}",
105                    StatusCode::INTERNAL_SERVER_ERROR,
106                    &error
107                );
108                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
109            }
110        }
111    }
112}
113
114impl std::fmt::Debug for Error {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        match self {
117            Error::Http(code, message, _headers) => (code, message).fmt(f),
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::fmt::Display for Error {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        match self {
128            Error::Http(code, message, _) => write!(f, "{code}: {message}"),
129            Error::Database(error) => error.fmt(f),
130            Error::Internal(error) => error.fmt(f),
131            Error::Stripe(error) => error.fmt(f),
132        }
133    }
134}
135
136impl std::error::Error for Error {}
137
138#[derive(Clone, Deserialize)]
139pub struct Config {
140    pub http_port: u16,
141    pub database_url: String,
142    pub migrations_path: Option<PathBuf>,
143    pub seed_path: Option<PathBuf>,
144    pub database_max_connections: u32,
145    pub api_token: String,
146    pub clickhouse_url: Option<String>,
147    pub clickhouse_user: Option<String>,
148    pub clickhouse_password: Option<String>,
149    pub clickhouse_database: Option<String>,
150    pub invite_link_prefix: String,
151    pub live_kit_server: Option<String>,
152    pub live_kit_key: Option<String>,
153    pub live_kit_secret: Option<String>,
154    pub llm_database_url: Option<String>,
155    pub llm_database_max_connections: Option<u32>,
156    pub llm_database_migrations_path: Option<PathBuf>,
157    pub llm_api_secret: Option<String>,
158    pub rust_log: Option<String>,
159    pub log_json: Option<bool>,
160    pub blob_store_url: Option<String>,
161    pub blob_store_region: Option<String>,
162    pub blob_store_access_key: Option<String>,
163    pub blob_store_secret_key: Option<String>,
164    pub blob_store_bucket: Option<String>,
165    pub zed_environment: Arc<str>,
166    pub openai_api_key: Option<Arc<str>>,
167    pub google_ai_api_key: Option<Arc<str>>,
168    pub anthropic_api_key: Option<Arc<str>>,
169    pub qwen2_7b_api_key: Option<Arc<str>>,
170    pub qwen2_7b_api_url: Option<Arc<str>>,
171    pub zed_client_checksum_seed: Option<String>,
172    pub slack_panics_webhook: Option<String>,
173    pub auto_join_channel_id: Option<ChannelId>,
174    pub stripe_api_key: Option<String>,
175    pub stripe_price_id: Option<Arc<str>>,
176    pub supermaven_admin_api_key: Option<Arc<str>>,
177}
178
179impl Config {
180    pub fn is_development(&self) -> bool {
181        self.zed_environment == "development".into()
182    }
183
184    /// Returns the base `zed.dev` URL.
185    pub fn zed_dot_dev_url(&self) -> &str {
186        match self.zed_environment.as_ref() {
187            "development" => "http://localhost:3000",
188            "staging" => "https://staging.zed.dev",
189            _ => "https://zed.dev",
190        }
191    }
192
193    #[cfg(test)]
194    pub fn test() -> Self {
195        Self {
196            http_port: 0,
197            database_url: "".into(),
198            database_max_connections: 0,
199            api_token: "".into(),
200            invite_link_prefix: "".into(),
201            live_kit_server: None,
202            live_kit_key: None,
203            live_kit_secret: None,
204            llm_database_url: None,
205            llm_database_max_connections: None,
206            llm_database_migrations_path: None,
207            llm_api_secret: None,
208            rust_log: None,
209            log_json: None,
210            zed_environment: "test".into(),
211            blob_store_url: None,
212            blob_store_region: None,
213            blob_store_access_key: None,
214            blob_store_secret_key: None,
215            blob_store_bucket: None,
216            openai_api_key: None,
217            google_ai_api_key: None,
218            anthropic_api_key: None,
219            clickhouse_url: None,
220            clickhouse_user: None,
221            clickhouse_password: None,
222            clickhouse_database: None,
223            zed_client_checksum_seed: None,
224            slack_panics_webhook: None,
225            auto_join_channel_id: None,
226            migrations_path: None,
227            seed_path: None,
228            stripe_api_key: None,
229            stripe_price_id: None,
230            supermaven_admin_api_key: None,
231            qwen2_7b_api_key: None,
232            qwen2_7b_api_url: None,
233        }
234    }
235}
236
237/// The service mode that collab should run in.
238#[derive(Debug, PartialEq, Eq, Clone, Copy)]
239pub enum ServiceMode {
240    Api,
241    Collab,
242    Llm,
243    All,
244}
245
246impl ServiceMode {
247    pub fn is_collab(&self) -> bool {
248        matches!(self, Self::Collab | Self::All)
249    }
250
251    pub fn is_api(&self) -> bool {
252        matches!(self, Self::Api | Self::All)
253    }
254
255    pub fn is_llm(&self) -> bool {
256        matches!(self, Self::Llm | Self::All)
257    }
258}
259
260pub struct AppState {
261    pub db: Arc<Database>,
262    pub live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
263    pub blob_store_client: Option<aws_sdk_s3::Client>,
264    pub stripe_client: Option<Arc<stripe::Client>>,
265    pub rate_limiter: Arc<RateLimiter>,
266    pub executor: Executor,
267    pub clickhouse_client: Option<clickhouse::Client>,
268    pub config: Config,
269}
270
271impl AppState {
272    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
273        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
274        db_options.max_connections(config.database_max_connections);
275        let mut db = Database::new(db_options, Executor::Production).await?;
276        db.initialize_notification_kinds().await?;
277
278        let live_kit_client = if let Some(((server, key), secret)) = config
279            .live_kit_server
280            .as_ref()
281            .zip(config.live_kit_key.as_ref())
282            .zip(config.live_kit_secret.as_ref())
283        {
284            Some(Arc::new(live_kit_server::api::LiveKitClient::new(
285                server.clone(),
286                key.clone(),
287                secret.clone(),
288            )) as Arc<dyn live_kit_server::api::Client>)
289        } else {
290            None
291        };
292
293        let db = Arc::new(db);
294        let this = Self {
295            db: db.clone(),
296            live_kit_client,
297            blob_store_client: build_blob_store_client(&config).await.log_err(),
298            stripe_client: build_stripe_client(&config)
299                .await
300                .map(|client| Arc::new(client))
301                .log_err(),
302            rate_limiter: Arc::new(RateLimiter::new(db)),
303            executor,
304            clickhouse_client: config
305                .clickhouse_url
306                .as_ref()
307                .and_then(|_| build_clickhouse_client(&config).log_err()),
308            config,
309        };
310        Ok(Arc::new(this))
311    }
312}
313
314async fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
315    let api_key = config
316        .stripe_api_key
317        .as_ref()
318        .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
319
320    Ok(stripe::Client::new(api_key))
321}
322
323async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
324    let keys = aws_sdk_s3::config::Credentials::new(
325        config
326            .blob_store_access_key
327            .clone()
328            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
329        config
330            .blob_store_secret_key
331            .clone()
332            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
333        None,
334        None,
335        "env",
336    );
337
338    let s3_config = aws_config::defaults(BehaviorVersion::latest())
339        .endpoint_url(
340            config
341                .blob_store_url
342                .as_ref()
343                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
344        )
345        .region(Region::new(
346            config
347                .blob_store_region
348                .clone()
349                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
350        ))
351        .credentials_provider(keys)
352        .load()
353        .await;
354
355    Ok(aws_sdk_s3::Client::new(&s3_config))
356}
357
358fn build_clickhouse_client(config: &Config) -> anyhow::Result<clickhouse::Client> {
359    Ok(clickhouse::Client::default()
360        .with_url(
361            config
362                .clickhouse_url
363                .as_ref()
364                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
365        )
366        .with_user(
367            config
368                .clickhouse_user
369                .as_ref()
370                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
371        )
372        .with_password(
373            config
374                .clickhouse_password
375                .as_ref()
376                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
377        )
378        .with_database(
379            config
380                .clickhouse_database
381                .as_ref()
382                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
383        ))
384}