lib.rs

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