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;
  9pub mod rpc;
 10pub mod seed;
 11pub mod stripe_billing;
 12pub mod stripe_client;
 13pub mod user_backfiller;
 14
 15#[cfg(test)]
 16mod tests;
 17
 18use anyhow::Context as _;
 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;
 28use serde::Deserialize;
 29use std::{path::PathBuf, sync::Arc};
 30use util::ResultExt;
 31
 32use crate::stripe_billing::StripeBilling;
 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 invite_link_prefix: String,
153    pub livekit_server: Option<String>,
154    pub livekit_key: Option<String>,
155    pub livekit_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 kinesis_region: Option<String>,
168    pub kinesis_stream: Option<String>,
169    pub kinesis_access_key: Option<String>,
170    pub kinesis_secret_key: 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 prediction_api_url: Option<Arc<str>>,
178    pub prediction_api_key: Option<Arc<str>>,
179    pub prediction_model: Option<Arc<str>>,
180    pub zed_client_checksum_seed: Option<String>,
181    pub slack_panics_webhook: Option<String>,
182    pub auto_join_channel_id: Option<ChannelId>,
183    pub stripe_api_key: Option<String>,
184    pub supermaven_admin_api_key: Option<Arc<str>>,
185    pub user_backfiller_github_access_token: Option<Arc<str>>,
186}
187
188impl Config {
189    pub fn is_development(&self) -> bool {
190        self.zed_environment == "development".into()
191    }
192
193    /// Returns the base `zed.dev` URL.
194    pub fn zed_dot_dev_url(&self) -> &str {
195        match self.zed_environment.as_ref() {
196            "development" => "http://localhost:3000",
197            "staging" => "https://staging.zed.dev",
198            _ => "https://zed.dev",
199        }
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            livekit_server: None,
211            livekit_key: None,
212            livekit_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            prediction_api_url: None,
231            prediction_api_key: None,
232            prediction_model: None,
233            zed_client_checksum_seed: None,
234            slack_panics_webhook: None,
235            auto_join_channel_id: None,
236            migrations_path: None,
237            seed_path: None,
238            stripe_api_key: None,
239            supermaven_admin_api_key: None,
240            user_backfiller_github_access_token: None,
241            kinesis_region: None,
242            kinesis_access_key: None,
243            kinesis_secret_key: None,
244            kinesis_stream: 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    All,
256}
257
258impl ServiceMode {
259    pub fn is_collab(&self) -> bool {
260        matches!(self, Self::Collab | Self::All)
261    }
262
263    pub fn is_api(&self) -> bool {
264        matches!(self, Self::Api | Self::All)
265    }
266}
267
268pub struct AppState {
269    pub db: Arc<Database>,
270    pub llm_db: Option<Arc<LlmDatabase>>,
271    pub livekit_client: Option<Arc<dyn livekit_api::Client>>,
272    pub blob_store_client: Option<aws_sdk_s3::Client>,
273    pub stripe_client: Option<Arc<stripe::Client>>,
274    pub stripe_billing: Option<Arc<StripeBilling>>,
275    pub executor: Executor,
276    pub kinesis_client: Option<::aws_sdk_kinesis::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 llm_db = if let Some((llm_database_url, llm_database_max_connections)) = config
288            .llm_database_url
289            .clone()
290            .zip(config.llm_database_max_connections)
291        {
292            let mut llm_db_options = db::ConnectOptions::new(llm_database_url);
293            llm_db_options.max_connections(llm_database_max_connections);
294            let mut llm_db = LlmDatabase::new(llm_db_options, executor.clone()).await?;
295            llm_db.initialize().await?;
296            Some(Arc::new(llm_db))
297        } else {
298            None
299        };
300
301        let livekit_client = if let Some(((server, key), secret)) = config
302            .livekit_server
303            .as_ref()
304            .zip(config.livekit_key.as_ref())
305            .zip(config.livekit_secret.as_ref())
306        {
307            Some(Arc::new(livekit_api::LiveKitClient::new(
308                server.clone(),
309                key.clone(),
310                secret.clone(),
311            )) as Arc<dyn livekit_api::Client>)
312        } else {
313            None
314        };
315
316        let db = Arc::new(db);
317        let stripe_client = build_stripe_client(&config).map(Arc::new).log_err();
318        let this = Self {
319            db: db.clone(),
320            llm_db,
321            livekit_client,
322            blob_store_client: build_blob_store_client(&config).await.log_err(),
323            stripe_billing: stripe_client
324                .clone()
325                .map(|stripe_client| Arc::new(StripeBilling::new(stripe_client))),
326            stripe_client,
327            executor,
328            kinesis_client: if config.kinesis_access_key.is_some() {
329                build_kinesis_client(&config).await.log_err()
330            } else {
331                None
332            },
333            config,
334        };
335        Ok(Arc::new(this))
336    }
337}
338
339fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
340    let api_key = config
341        .stripe_api_key
342        .as_ref()
343        .context("missing stripe_api_key")?;
344    Ok(stripe::Client::new(api_key))
345}
346
347async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
348    let keys = aws_sdk_s3::config::Credentials::new(
349        config
350            .blob_store_access_key
351            .clone()
352            .context("missing blob_store_access_key")?,
353        config
354            .blob_store_secret_key
355            .clone()
356            .context("missing blob_store_secret_key")?,
357        None,
358        None,
359        "env",
360    );
361
362    let s3_config = aws_config::defaults(BehaviorVersion::latest())
363        .endpoint_url(
364            config
365                .blob_store_url
366                .as_ref()
367                .context("missing blob_store_url")?,
368        )
369        .region(Region::new(
370            config
371                .blob_store_region
372                .clone()
373                .context("missing blob_store_region")?,
374        ))
375        .credentials_provider(keys)
376        .load()
377        .await;
378
379    Ok(aws_sdk_s3::Client::new(&s3_config))
380}
381
382async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis::Client> {
383    let keys = aws_sdk_s3::config::Credentials::new(
384        config
385            .kinesis_access_key
386            .clone()
387            .context("missing kinesis_access_key")?,
388        config
389            .kinesis_secret_key
390            .clone()
391            .context("missing kinesis_secret_key")?,
392        None,
393        None,
394        "env",
395    );
396
397    let kinesis_config = aws_config::defaults(BehaviorVersion::latest())
398        .region(Region::new(
399            config
400                .kinesis_region
401                .clone()
402                .context("missing kinesis_region")?,
403        ))
404        .credentials_provider(keys)
405        .load()
406        .await;
407
408    Ok(aws_sdk_kinesis::Client::new(&kinesis_config))
409}