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