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 user_backfiller;
 14
 15#[cfg(test)]
 16mod tests;
 17
 18use anyhow::anyhow;
 19use aws_config::{BehaviorVersion, Region};
 20use axum::{
 21    http::{HeaderMap, StatusCode},
 22    response::IntoResponse,
 23};
 24pub use cents::*;
 25use db::{ChannelId, Database};
 26use executor::Executor;
 27pub use rate_limiter::*;
 28use serde::Deserialize;
 29use std::{path::PathBuf, sync::Arc};
 30use util::ResultExt;
 31
 32pub type Result<T, E = Error> = std::result::Result<T, E>;
 33
 34pub enum Error {
 35    Http(StatusCode, String, HeaderMap),
 36    Database(sea_orm::error::DbErr),
 37    Internal(anyhow::Error),
 38    Stripe(stripe::StripeError),
 39}
 40
 41impl From<anyhow::Error> for Error {
 42    fn from(error: anyhow::Error) -> Self {
 43        Self::Internal(error)
 44    }
 45}
 46
 47impl From<sea_orm::error::DbErr> for Error {
 48    fn from(error: sea_orm::error::DbErr) -> Self {
 49        Self::Database(error)
 50    }
 51}
 52
 53impl From<stripe::StripeError> for Error {
 54    fn from(error: stripe::StripeError) -> Self {
 55        Self::Stripe(error)
 56    }
 57}
 58
 59impl From<axum::Error> for Error {
 60    fn from(error: axum::Error) -> Self {
 61        Self::Internal(error.into())
 62    }
 63}
 64
 65impl From<axum::http::Error> for Error {
 66    fn from(error: axum::http::Error) -> Self {
 67        Self::Internal(error.into())
 68    }
 69}
 70
 71impl From<serde_json::Error> for Error {
 72    fn from(error: serde_json::Error) -> Self {
 73        Self::Internal(error.into())
 74    }
 75}
 76
 77impl Error {
 78    fn http(code: StatusCode, message: String) -> Self {
 79        Self::Http(code, message, HeaderMap::default())
 80    }
 81}
 82
 83impl IntoResponse for Error {
 84    fn into_response(self) -> axum::response::Response {
 85        match self {
 86            Error::Http(code, message, headers) => {
 87                log::error!("HTTP error {}: {}", code, &message);
 88                (code, headers, message).into_response()
 89            }
 90            Error::Database(error) => {
 91                log::error!(
 92                    "HTTP error {}: {:?}",
 93                    StatusCode::INTERNAL_SERVER_ERROR,
 94                    &error
 95                );
 96                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
 97            }
 98            Error::Internal(error) => {
 99                log::error!(
100                    "HTTP error {}: {:?}",
101                    StatusCode::INTERNAL_SERVER_ERROR,
102                    &error
103                );
104                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
105            }
106            Error::Stripe(error) => {
107                log::error!(
108                    "HTTP error {}: {:?}",
109                    StatusCode::INTERNAL_SERVER_ERROR,
110                    &error
111                );
112                (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
113            }
114        }
115    }
116}
117
118impl std::fmt::Debug for Error {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        match self {
121            Error::Http(code, message, _headers) => (code, message).fmt(f),
122            Error::Database(error) => error.fmt(f),
123            Error::Internal(error) => error.fmt(f),
124            Error::Stripe(error) => error.fmt(f),
125        }
126    }
127}
128
129impl std::fmt::Display for Error {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        match self {
132            Error::Http(code, message, _) => write!(f, "{code}: {message}"),
133            Error::Database(error) => error.fmt(f),
134            Error::Internal(error) => error.fmt(f),
135            Error::Stripe(error) => error.fmt(f),
136        }
137    }
138}
139
140impl std::error::Error for Error {}
141
142#[derive(Clone, Deserialize)]
143pub struct Config {
144    pub http_port: u16,
145    pub database_url: String,
146    pub migrations_path: Option<PathBuf>,
147    pub seed_path: Option<PathBuf>,
148    pub database_max_connections: u32,
149    pub api_token: String,
150    pub clickhouse_url: Option<String>,
151    pub clickhouse_user: Option<String>,
152    pub clickhouse_password: Option<String>,
153    pub clickhouse_database: Option<String>,
154    pub invite_link_prefix: String,
155    pub live_kit_server: Option<String>,
156    pub live_kit_key: Option<String>,
157    pub live_kit_secret: Option<String>,
158    pub llm_database_url: Option<String>,
159    pub llm_database_max_connections: Option<u32>,
160    pub llm_database_migrations_path: Option<PathBuf>,
161    pub llm_api_secret: Option<String>,
162    pub rust_log: Option<String>,
163    pub log_json: Option<bool>,
164    pub blob_store_url: Option<String>,
165    pub blob_store_region: Option<String>,
166    pub blob_store_access_key: Option<String>,
167    pub blob_store_secret_key: Option<String>,
168    pub blob_store_bucket: Option<String>,
169    pub zed_environment: Arc<str>,
170    pub openai_api_key: Option<Arc<str>>,
171    pub google_ai_api_key: Option<Arc<str>>,
172    pub anthropic_api_key: Option<Arc<str>>,
173    pub anthropic_staff_api_key: Option<Arc<str>>,
174    pub llm_closed_beta_model_name: Option<Arc<str>>,
175    pub zed_client_checksum_seed: Option<String>,
176    pub slack_panics_webhook: Option<String>,
177    pub auto_join_channel_id: Option<ChannelId>,
178    pub stripe_api_key: Option<String>,
179    pub stripe_llm_access_price_id: Option<Arc<str>>,
180    pub stripe_llm_usage_price_id: Option<Arc<str>>,
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_llm_usage_price_id.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            stripe_llm_access_price_id: None,
242            stripe_llm_usage_price_id: 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 live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
276    pub blob_store_client: Option<aws_sdk_s3::Client>,
277    pub stripe_client: Option<Arc<stripe::Client>>,
278    pub rate_limiter: Arc<RateLimiter>,
279    pub executor: Executor,
280    pub clickhouse_client: Option<::clickhouse::Client>,
281    pub config: Config,
282}
283
284impl AppState {
285    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
286        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
287        db_options.max_connections(config.database_max_connections);
288        let mut db = Database::new(db_options, Executor::Production).await?;
289        db.initialize_notification_kinds().await?;
290
291        let live_kit_client = if let Some(((server, key), secret)) = config
292            .live_kit_server
293            .as_ref()
294            .zip(config.live_kit_key.as_ref())
295            .zip(config.live_kit_secret.as_ref())
296        {
297            Some(Arc::new(live_kit_server::api::LiveKitClient::new(
298                server.clone(),
299                key.clone(),
300                secret.clone(),
301            )) as Arc<dyn live_kit_server::api::Client>)
302        } else {
303            None
304        };
305
306        let db = Arc::new(db);
307        let this = Self {
308            db: db.clone(),
309            live_kit_client,
310            blob_store_client: build_blob_store_client(&config).await.log_err(),
311            stripe_client: build_stripe_client(&config).await.map(Arc::new).log_err(),
312            rate_limiter: Arc::new(RateLimiter::new(db)),
313            executor,
314            clickhouse_client: config
315                .clickhouse_url
316                .as_ref()
317                .and_then(|_| build_clickhouse_client(&config).log_err()),
318            config,
319        };
320        Ok(Arc::new(this))
321    }
322}
323
324async fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
325    let api_key = config
326        .stripe_api_key
327        .as_ref()
328        .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
329
330    Ok(stripe::Client::new(api_key))
331}
332
333async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
334    let keys = aws_sdk_s3::config::Credentials::new(
335        config
336            .blob_store_access_key
337            .clone()
338            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
339        config
340            .blob_store_secret_key
341            .clone()
342            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
343        None,
344        None,
345        "env",
346    );
347
348    let s3_config = aws_config::defaults(BehaviorVersion::latest())
349        .endpoint_url(
350            config
351                .blob_store_url
352                .as_ref()
353                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
354        )
355        .region(Region::new(
356            config
357                .blob_store_region
358                .clone()
359                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
360        ))
361        .credentials_provider(keys)
362        .load()
363        .await;
364
365    Ok(aws_sdk_s3::Client::new(&s3_config))
366}
367
368fn build_clickhouse_client(config: &Config) -> anyhow::Result<::clickhouse::Client> {
369    Ok(::clickhouse::Client::default()
370        .with_url(
371            config
372                .clickhouse_url
373                .as_ref()
374                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
375        )
376        .with_user(
377            config
378                .clickhouse_user
379                .as_ref()
380                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
381        )
382        .with_password(
383            config
384                .clickhouse_password
385                .as_ref()
386                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
387        )
388        .with_database(
389            config
390                .clickhouse_database
391                .as_ref()
392                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
393        ))
394}