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 livekit_server: Option<String>,
160    pub livekit_key: Option<String>,
161    pub livekit_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 kinesis_region: Option<String>,
174    pub kinesis_stream: Option<String>,
175    pub kinesis_access_key: Option<String>,
176    pub kinesis_secret_key: Option<String>,
177    pub zed_environment: Arc<str>,
178    pub openai_api_key: Option<Arc<str>>,
179    pub google_ai_api_key: Option<Arc<str>>,
180    pub anthropic_api_key: Option<Arc<str>>,
181    pub anthropic_staff_api_key: Option<Arc<str>>,
182    pub llm_closed_beta_model_name: Option<Arc<str>>,
183    pub prediction_api_url: Option<Arc<str>>,
184    pub prediction_api_key: Option<Arc<str>>,
185    pub prediction_model: Option<Arc<str>>,
186    pub zed_client_checksum_seed: Option<String>,
187    pub slack_panics_webhook: Option<String>,
188    pub auto_join_channel_id: Option<ChannelId>,
189    pub stripe_api_key: Option<String>,
190    pub supermaven_admin_api_key: Option<Arc<str>>,
191    pub user_backfiller_github_access_token: Option<Arc<str>>,
192}
193
194impl Config {
195    pub fn is_development(&self) -> bool {
196        self.zed_environment == "development".into()
197    }
198
199    /// Returns the base `zed.dev` URL.
200    pub fn zed_dot_dev_url(&self) -> &str {
201        match self.zed_environment.as_ref() {
202            "development" => "http://localhost:3000",
203            "staging" => "https://staging.zed.dev",
204            _ => "https://zed.dev",
205        }
206    }
207
208    #[cfg(test)]
209    pub fn test() -> Self {
210        Self {
211            http_port: 0,
212            database_url: "".into(),
213            database_max_connections: 0,
214            api_token: "".into(),
215            invite_link_prefix: "".into(),
216            livekit_server: None,
217            livekit_key: None,
218            livekit_secret: None,
219            llm_database_url: None,
220            llm_database_max_connections: None,
221            llm_database_migrations_path: None,
222            llm_api_secret: None,
223            rust_log: None,
224            log_json: None,
225            zed_environment: "test".into(),
226            blob_store_url: None,
227            blob_store_region: None,
228            blob_store_access_key: None,
229            blob_store_secret_key: None,
230            blob_store_bucket: None,
231            openai_api_key: None,
232            google_ai_api_key: None,
233            anthropic_api_key: None,
234            anthropic_staff_api_key: None,
235            llm_closed_beta_model_name: None,
236            prediction_api_url: None,
237            prediction_api_key: None,
238            prediction_model: None,
239            clickhouse_url: None,
240            clickhouse_user: None,
241            clickhouse_password: None,
242            clickhouse_database: None,
243            zed_client_checksum_seed: None,
244            slack_panics_webhook: None,
245            auto_join_channel_id: None,
246            migrations_path: None,
247            seed_path: None,
248            stripe_api_key: None,
249            supermaven_admin_api_key: None,
250            user_backfiller_github_access_token: None,
251            kinesis_region: None,
252            kinesis_access_key: None,
253            kinesis_secret_key: None,
254            kinesis_stream: None,
255        }
256    }
257}
258
259/// The service mode that collab should run in.
260#[derive(Debug, PartialEq, Eq, Clone, Copy, strum::Display)]
261#[strum(serialize_all = "snake_case")]
262pub enum ServiceMode {
263    Api,
264    Collab,
265    Llm,
266    All,
267}
268
269impl ServiceMode {
270    pub fn is_collab(&self) -> bool {
271        matches!(self, Self::Collab | Self::All)
272    }
273
274    pub fn is_api(&self) -> bool {
275        matches!(self, Self::Api | Self::All)
276    }
277
278    pub fn is_llm(&self) -> bool {
279        matches!(self, Self::Llm | Self::All)
280    }
281}
282
283pub struct AppState {
284    pub db: Arc<Database>,
285    pub llm_db: Option<Arc<LlmDatabase>>,
286    pub livekit_client: Option<Arc<dyn livekit_server::api::Client>>,
287    pub blob_store_client: Option<aws_sdk_s3::Client>,
288    pub stripe_client: Option<Arc<stripe::Client>>,
289    pub stripe_billing: Option<Arc<StripeBilling>>,
290    pub rate_limiter: Arc<RateLimiter>,
291    pub executor: Executor,
292    pub clickhouse_client: Option<::clickhouse::Client>,
293    pub kinesis_client: Option<::aws_sdk_kinesis::Client>,
294    pub config: Config,
295}
296
297impl AppState {
298    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
299        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
300        db_options.max_connections(config.database_max_connections);
301        let mut db = Database::new(db_options, Executor::Production).await?;
302        db.initialize_notification_kinds().await?;
303
304        let llm_db = if let Some((llm_database_url, llm_database_max_connections)) = config
305            .llm_database_url
306            .clone()
307            .zip(config.llm_database_max_connections)
308        {
309            let mut llm_db_options = db::ConnectOptions::new(llm_database_url);
310            llm_db_options.max_connections(llm_database_max_connections);
311            let mut llm_db = LlmDatabase::new(llm_db_options, executor.clone()).await?;
312            llm_db.initialize().await?;
313            Some(Arc::new(llm_db))
314        } else {
315            None
316        };
317
318        let livekit_client = if let Some(((server, key), secret)) = config
319            .livekit_server
320            .as_ref()
321            .zip(config.livekit_key.as_ref())
322            .zip(config.livekit_secret.as_ref())
323        {
324            Some(Arc::new(livekit_server::api::LiveKitClient::new(
325                server.clone(),
326                key.clone(),
327                secret.clone(),
328            )) as Arc<dyn livekit_server::api::Client>)
329        } else {
330            None
331        };
332
333        let db = Arc::new(db);
334        let stripe_client = build_stripe_client(&config).map(Arc::new).log_err();
335        let this = Self {
336            db: db.clone(),
337            llm_db,
338            livekit_client,
339            blob_store_client: build_blob_store_client(&config).await.log_err(),
340            stripe_billing: stripe_client
341                .clone()
342                .map(|stripe_client| Arc::new(StripeBilling::new(stripe_client))),
343            stripe_client,
344            rate_limiter: Arc::new(RateLimiter::new(db)),
345            executor,
346            clickhouse_client: config
347                .clickhouse_url
348                .as_ref()
349                .and_then(|_| build_clickhouse_client(&config).log_err()),
350            kinesis_client: if config.kinesis_access_key.is_some() {
351                build_kinesis_client(&config).await.log_err()
352            } else {
353                None
354            },
355            config,
356        };
357        Ok(Arc::new(this))
358    }
359}
360
361fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
362    let api_key = config
363        .stripe_api_key
364        .as_ref()
365        .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
366    Ok(stripe::Client::new(api_key))
367}
368
369async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
370    let keys = aws_sdk_s3::config::Credentials::new(
371        config
372            .blob_store_access_key
373            .clone()
374            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
375        config
376            .blob_store_secret_key
377            .clone()
378            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
379        None,
380        None,
381        "env",
382    );
383
384    let s3_config = aws_config::defaults(BehaviorVersion::latest())
385        .endpoint_url(
386            config
387                .blob_store_url
388                .as_ref()
389                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
390        )
391        .region(Region::new(
392            config
393                .blob_store_region
394                .clone()
395                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
396        ))
397        .credentials_provider(keys)
398        .load()
399        .await;
400
401    Ok(aws_sdk_s3::Client::new(&s3_config))
402}
403
404async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis::Client> {
405    let keys = aws_sdk_s3::config::Credentials::new(
406        config
407            .kinesis_access_key
408            .clone()
409            .ok_or_else(|| anyhow!("missing kinesis_access_key"))?,
410        config
411            .kinesis_secret_key
412            .clone()
413            .ok_or_else(|| anyhow!("missing kinesis_secret_key"))?,
414        None,
415        None,
416        "env",
417    );
418
419    let kinesis_config = aws_config::defaults(BehaviorVersion::latest())
420        .region(Region::new(
421            config
422                .kinesis_region
423                .clone()
424                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
425        ))
426        .credentials_provider(keys)
427        .load()
428        .await;
429
430    Ok(aws_sdk_kinesis::Client::new(&kinesis_config))
431}
432
433fn build_clickhouse_client(config: &Config) -> anyhow::Result<::clickhouse::Client> {
434    Ok(::clickhouse::Client::default()
435        .with_url(
436            config
437                .clickhouse_url
438                .as_ref()
439                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
440        )
441        .with_user(
442            config
443                .clickhouse_user
444                .as_ref()
445                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
446        )
447        .with_password(
448            config
449                .clickhouse_password
450                .as_ref()
451                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
452        )
453        .with_database(
454            config
455                .clickhouse_database
456                .as_ref()
457                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
458        ))
459}