lib.rs

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