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, strum::Display)]
239#[strum(serialize_all = "snake_case")]
240pub enum ServiceMode {
241    Api,
242    Collab,
243    Llm,
244    All,
245}
246
247impl ServiceMode {
248    pub fn is_collab(&self) -> bool {
249        matches!(self, Self::Collab | Self::All)
250    }
251
252    pub fn is_api(&self) -> bool {
253        matches!(self, Self::Api | Self::All)
254    }
255
256    pub fn is_llm(&self) -> bool {
257        matches!(self, Self::Llm | Self::All)
258    }
259}
260
261pub struct AppState {
262    pub db: Arc<Database>,
263    pub live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
264    pub blob_store_client: Option<aws_sdk_s3::Client>,
265    pub stripe_client: Option<Arc<stripe::Client>>,
266    pub rate_limiter: Arc<RateLimiter>,
267    pub executor: Executor,
268    pub clickhouse_client: Option<clickhouse::Client>,
269    pub config: Config,
270}
271
272impl AppState {
273    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
274        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
275        db_options.max_connections(config.database_max_connections);
276        let mut db = Database::new(db_options, Executor::Production).await?;
277        db.initialize_notification_kinds().await?;
278
279        let live_kit_client = if let Some(((server, key), secret)) = config
280            .live_kit_server
281            .as_ref()
282            .zip(config.live_kit_key.as_ref())
283            .zip(config.live_kit_secret.as_ref())
284        {
285            Some(Arc::new(live_kit_server::api::LiveKitClient::new(
286                server.clone(),
287                key.clone(),
288                secret.clone(),
289            )) as Arc<dyn live_kit_server::api::Client>)
290        } else {
291            None
292        };
293
294        let db = Arc::new(db);
295        let this = Self {
296            db: db.clone(),
297            live_kit_client,
298            blob_store_client: build_blob_store_client(&config).await.log_err(),
299            stripe_client: build_stripe_client(&config)
300                .await
301                .map(|client| Arc::new(client))
302                .log_err(),
303            rate_limiter: Arc::new(RateLimiter::new(db)),
304            executor,
305            clickhouse_client: config
306                .clickhouse_url
307                .as_ref()
308                .and_then(|_| build_clickhouse_client(&config).log_err()),
309            config,
310        };
311        Ok(Arc::new(this))
312    }
313}
314
315async fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
316    let api_key = config
317        .stripe_api_key
318        .as_ref()
319        .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
320
321    Ok(stripe::Client::new(api_key))
322}
323
324async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
325    let keys = aws_sdk_s3::config::Credentials::new(
326        config
327            .blob_store_access_key
328            .clone()
329            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
330        config
331            .blob_store_secret_key
332            .clone()
333            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
334        None,
335        None,
336        "env",
337    );
338
339    let s3_config = aws_config::defaults(BehaviorVersion::latest())
340        .endpoint_url(
341            config
342                .blob_store_url
343                .as_ref()
344                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
345        )
346        .region(Region::new(
347            config
348                .blob_store_region
349                .clone()
350                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
351        ))
352        .credentials_provider(keys)
353        .load()
354        .await;
355
356    Ok(aws_sdk_s3::Client::new(&s3_config))
357}
358
359fn build_clickhouse_client(config: &Config) -> anyhow::Result<clickhouse::Client> {
360    Ok(clickhouse::Client::default()
361        .with_url(
362            config
363                .clickhouse_url
364                .as_ref()
365                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
366        )
367        .with_user(
368            config
369                .clickhouse_user
370                .as_ref()
371                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
372        )
373        .with_password(
374            config
375                .clickhouse_password
376                .as_ref()
377                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
378        )
379        .with_database(
380            config
381                .clickhouse_database
382                .as_ref()
383                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
384        ))
385}