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 anthropic_staff_api_key: Option<Arc<str>>,
170    pub qwen2_7b_api_key: Option<Arc<str>>,
171    pub qwen2_7b_api_url: Option<Arc<str>>,
172    pub zed_client_checksum_seed: Option<String>,
173    pub slack_panics_webhook: Option<String>,
174    pub auto_join_channel_id: Option<ChannelId>,
175    pub stripe_api_key: Option<String>,
176    pub stripe_price_id: Option<Arc<str>>,
177    pub supermaven_admin_api_key: Option<Arc<str>>,
178}
179
180impl Config {
181    pub fn is_development(&self) -> bool {
182        self.zed_environment == "development".into()
183    }
184
185    /// Returns the base `zed.dev` URL.
186    pub fn zed_dot_dev_url(&self) -> &str {
187        match self.zed_environment.as_ref() {
188            "development" => "http://localhost:3000",
189            "staging" => "https://staging.zed.dev",
190            _ => "https://zed.dev",
191        }
192    }
193
194    #[cfg(test)]
195    pub fn test() -> Self {
196        Self {
197            http_port: 0,
198            database_url: "".into(),
199            database_max_connections: 0,
200            api_token: "".into(),
201            invite_link_prefix: "".into(),
202            live_kit_server: None,
203            live_kit_key: None,
204            live_kit_secret: None,
205            llm_database_url: None,
206            llm_database_max_connections: None,
207            llm_database_migrations_path: None,
208            llm_api_secret: None,
209            rust_log: None,
210            log_json: None,
211            zed_environment: "test".into(),
212            blob_store_url: None,
213            blob_store_region: None,
214            blob_store_access_key: None,
215            blob_store_secret_key: None,
216            blob_store_bucket: None,
217            openai_api_key: None,
218            google_ai_api_key: None,
219            anthropic_api_key: None,
220            anthropic_staff_api_key: None,
221            clickhouse_url: None,
222            clickhouse_user: None,
223            clickhouse_password: None,
224            clickhouse_database: None,
225            zed_client_checksum_seed: None,
226            slack_panics_webhook: None,
227            auto_join_channel_id: None,
228            migrations_path: None,
229            seed_path: None,
230            stripe_api_key: None,
231            stripe_price_id: None,
232            supermaven_admin_api_key: None,
233            qwen2_7b_api_key: None,
234            qwen2_7b_api_url: None,
235        }
236    }
237}
238
239/// The service mode that collab should run in.
240#[derive(Debug, PartialEq, Eq, Clone, Copy, strum::Display)]
241#[strum(serialize_all = "snake_case")]
242pub enum ServiceMode {
243    Api,
244    Collab,
245    Llm,
246    All,
247}
248
249impl ServiceMode {
250    pub fn is_collab(&self) -> bool {
251        matches!(self, Self::Collab | Self::All)
252    }
253
254    pub fn is_api(&self) -> bool {
255        matches!(self, Self::Api | Self::All)
256    }
257
258    pub fn is_llm(&self) -> bool {
259        matches!(self, Self::Llm | Self::All)
260    }
261}
262
263pub struct AppState {
264    pub db: Arc<Database>,
265    pub live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
266    pub blob_store_client: Option<aws_sdk_s3::Client>,
267    pub stripe_client: Option<Arc<stripe::Client>>,
268    pub rate_limiter: Arc<RateLimiter>,
269    pub executor: Executor,
270    pub clickhouse_client: Option<clickhouse::Client>,
271    pub config: Config,
272}
273
274impl AppState {
275    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
276        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
277        db_options.max_connections(config.database_max_connections);
278        let mut db = Database::new(db_options, Executor::Production).await?;
279        db.initialize_notification_kinds().await?;
280
281        let live_kit_client = if let Some(((server, key), secret)) = config
282            .live_kit_server
283            .as_ref()
284            .zip(config.live_kit_key.as_ref())
285            .zip(config.live_kit_secret.as_ref())
286        {
287            Some(Arc::new(live_kit_server::api::LiveKitClient::new(
288                server.clone(),
289                key.clone(),
290                secret.clone(),
291            )) as Arc<dyn live_kit_server::api::Client>)
292        } else {
293            None
294        };
295
296        let db = Arc::new(db);
297        let this = Self {
298            db: db.clone(),
299            live_kit_client,
300            blob_store_client: build_blob_store_client(&config).await.log_err(),
301            stripe_client: build_stripe_client(&config)
302                .await
303                .map(|client| Arc::new(client))
304                .log_err(),
305            rate_limiter: Arc::new(RateLimiter::new(db)),
306            executor,
307            clickhouse_client: config
308                .clickhouse_url
309                .as_ref()
310                .and_then(|_| build_clickhouse_client(&config).log_err()),
311            config,
312        };
313        Ok(Arc::new(this))
314    }
315}
316
317async fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
318    let api_key = config
319        .stripe_api_key
320        .as_ref()
321        .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
322
323    Ok(stripe::Client::new(api_key))
324}
325
326async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
327    let keys = aws_sdk_s3::config::Credentials::new(
328        config
329            .blob_store_access_key
330            .clone()
331            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
332        config
333            .blob_store_secret_key
334            .clone()
335            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
336        None,
337        None,
338        "env",
339    );
340
341    let s3_config = aws_config::defaults(BehaviorVersion::latest())
342        .endpoint_url(
343            config
344                .blob_store_url
345                .as_ref()
346                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
347        )
348        .region(Region::new(
349            config
350                .blob_store_region
351                .clone()
352                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
353        ))
354        .credentials_provider(keys)
355        .load()
356        .await;
357
358    Ok(aws_sdk_s3::Client::new(&s3_config))
359}
360
361fn build_clickhouse_client(config: &Config) -> anyhow::Result<clickhouse::Client> {
362    Ok(clickhouse::Client::default()
363        .with_url(
364            config
365                .clickhouse_url
366                .as_ref()
367                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
368        )
369        .with_user(
370            config
371                .clickhouse_user
372                .as_ref()
373                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
374        )
375        .with_password(
376            config
377                .clickhouse_password
378                .as_ref()
379                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
380        )
381        .with_database(
382            config
383                .clickhouse_database
384                .as_ref()
385                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
386        ))
387}