lib.rs

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