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