lib.rs

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