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_usage_price_id: Option<Arc<str>>,
180    pub supermaven_admin_api_key: Option<Arc<str>>,
181    pub user_backfiller_github_access_token: Option<Arc<str>>,
182}
183
184impl Config {
185    pub fn is_development(&self) -> bool {
186        self.zed_environment == "development".into()
187    }
188
189    /// Returns the base `zed.dev` URL.
190    pub fn zed_dot_dev_url(&self) -> &str {
191        match self.zed_environment.as_ref() {
192            "development" => "http://localhost:3000",
193            "staging" => "https://staging.zed.dev",
194            _ => "https://zed.dev",
195        }
196    }
197
198    pub fn is_llm_billing_enabled(&self) -> bool {
199        self.stripe_llm_usage_price_id.is_some()
200    }
201
202    #[cfg(test)]
203    pub fn test() -> Self {
204        Self {
205            http_port: 0,
206            database_url: "".into(),
207            database_max_connections: 0,
208            api_token: "".into(),
209            invite_link_prefix: "".into(),
210            live_kit_server: None,
211            live_kit_key: None,
212            live_kit_secret: None,
213            llm_database_url: None,
214            llm_database_max_connections: None,
215            llm_database_migrations_path: None,
216            llm_api_secret: None,
217            rust_log: None,
218            log_json: None,
219            zed_environment: "test".into(),
220            blob_store_url: None,
221            blob_store_region: None,
222            blob_store_access_key: None,
223            blob_store_secret_key: None,
224            blob_store_bucket: None,
225            openai_api_key: None,
226            google_ai_api_key: None,
227            anthropic_api_key: None,
228            anthropic_staff_api_key: None,
229            llm_closed_beta_model_name: None,
230            clickhouse_url: None,
231            clickhouse_user: None,
232            clickhouse_password: None,
233            clickhouse_database: None,
234            zed_client_checksum_seed: None,
235            slack_panics_webhook: None,
236            auto_join_channel_id: None,
237            migrations_path: None,
238            seed_path: None,
239            stripe_api_key: None,
240            stripe_llm_usage_price_id: 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 live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
274    pub blob_store_client: Option<aws_sdk_s3::Client>,
275    pub stripe_client: Option<Arc<stripe::Client>>,
276    pub rate_limiter: Arc<RateLimiter>,
277    pub executor: Executor,
278    pub clickhouse_client: Option<::clickhouse::Client>,
279    pub config: Config,
280}
281
282impl AppState {
283    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
284        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
285        db_options.max_connections(config.database_max_connections);
286        let mut db = Database::new(db_options, Executor::Production).await?;
287        db.initialize_notification_kinds().await?;
288
289        let live_kit_client = if let Some(((server, key), secret)) = config
290            .live_kit_server
291            .as_ref()
292            .zip(config.live_kit_key.as_ref())
293            .zip(config.live_kit_secret.as_ref())
294        {
295            Some(Arc::new(live_kit_server::api::LiveKitClient::new(
296                server.clone(),
297                key.clone(),
298                secret.clone(),
299            )) as Arc<dyn live_kit_server::api::Client>)
300        } else {
301            None
302        };
303
304        let db = Arc::new(db);
305        let this = Self {
306            db: db.clone(),
307            live_kit_client,
308            blob_store_client: build_blob_store_client(&config).await.log_err(),
309            stripe_client: build_stripe_client(&config).await.map(Arc::new).log_err(),
310            rate_limiter: Arc::new(RateLimiter::new(db)),
311            executor,
312            clickhouse_client: config
313                .clickhouse_url
314                .as_ref()
315                .and_then(|_| build_clickhouse_client(&config).log_err()),
316            config,
317        };
318        Ok(Arc::new(this))
319    }
320}
321
322async fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
323    let api_key = config
324        .stripe_api_key
325        .as_ref()
326        .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
327
328    Ok(stripe::Client::new(api_key))
329}
330
331async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
332    let keys = aws_sdk_s3::config::Credentials::new(
333        config
334            .blob_store_access_key
335            .clone()
336            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
337        config
338            .blob_store_secret_key
339            .clone()
340            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
341        None,
342        None,
343        "env",
344    );
345
346    let s3_config = aws_config::defaults(BehaviorVersion::latest())
347        .endpoint_url(
348            config
349                .blob_store_url
350                .as_ref()
351                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
352        )
353        .region(Region::new(
354            config
355                .blob_store_region
356                .clone()
357                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
358        ))
359        .credentials_provider(keys)
360        .load()
361        .await;
362
363    Ok(aws_sdk_s3::Client::new(&s3_config))
364}
365
366fn build_clickhouse_client(config: &Config) -> anyhow::Result<::clickhouse::Client> {
367    Ok(::clickhouse::Client::default()
368        .with_url(
369            config
370                .clickhouse_url
371                .as_ref()
372                .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
373        )
374        .with_user(
375            config
376                .clickhouse_user
377                .as_ref()
378                .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
379        )
380        .with_password(
381            config
382                .clickhouse_password
383                .as_ref()
384                .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
385        )
386        .with_database(
387            config
388                .clickhouse_database
389                .as_ref()
390                .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
391        ))
392}