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 stripe_zed_pro_price_id: Option<String>,
186    pub stripe_zed_pro_trial_price_id: Option<String>,
187    pub stripe_zed_free_price_id: Option<String>,
188    pub supermaven_admin_api_key: Option<Arc<str>>,
189    pub user_backfiller_github_access_token: Option<Arc<str>>,
190}
191
192impl Config {
193    pub fn is_development(&self) -> bool {
194        self.zed_environment == "development".into()
195    }
196
197    /// Returns the base `zed.dev` URL.
198    pub fn zed_dot_dev_url(&self) -> &str {
199        match self.zed_environment.as_ref() {
200            "development" => "http://localhost:3000",
201            "staging" => "https://staging.zed.dev",
202            _ => "https://zed.dev",
203        }
204    }
205
206    pub fn zed_pro_price_id(&self) -> anyhow::Result<stripe::PriceId> {
207        Self::parse_stripe_price_id("Zed Pro", self.stripe_zed_pro_price_id.as_deref())
208    }
209
210    pub fn zed_pro_trial_price_id(&self) -> anyhow::Result<stripe::PriceId> {
211        Self::parse_stripe_price_id(
212            "Zed Pro Trial",
213            self.stripe_zed_pro_trial_price_id.as_deref(),
214        )
215    }
216
217    pub fn zed_free_price_id(&self) -> anyhow::Result<stripe::PriceId> {
218        Self::parse_stripe_price_id("Zed Free", self.stripe_zed_pro_price_id.as_deref())
219    }
220
221    fn parse_stripe_price_id(name: &str, value: Option<&str>) -> anyhow::Result<stripe::PriceId> {
222        use std::str::FromStr as _;
223
224        let price_id = value.ok_or_else(|| anyhow!("{name} price ID not set"))?;
225
226        Ok(stripe::PriceId::from_str(price_id)?)
227    }
228
229    #[cfg(test)]
230    pub fn test() -> Self {
231        Self {
232            http_port: 0,
233            database_url: "".into(),
234            database_max_connections: 0,
235            api_token: "".into(),
236            invite_link_prefix: "".into(),
237            livekit_server: None,
238            livekit_key: None,
239            livekit_secret: None,
240            llm_database_url: None,
241            llm_database_max_connections: None,
242            llm_database_migrations_path: None,
243            llm_api_secret: None,
244            rust_log: None,
245            log_json: None,
246            zed_environment: "test".into(),
247            blob_store_url: None,
248            blob_store_region: None,
249            blob_store_access_key: None,
250            blob_store_secret_key: None,
251            blob_store_bucket: None,
252            openai_api_key: None,
253            google_ai_api_key: None,
254            anthropic_api_key: None,
255            anthropic_staff_api_key: None,
256            llm_closed_beta_model_name: None,
257            prediction_api_url: None,
258            prediction_api_key: None,
259            prediction_model: None,
260            zed_client_checksum_seed: None,
261            slack_panics_webhook: None,
262            auto_join_channel_id: None,
263            migrations_path: None,
264            seed_path: None,
265            stripe_api_key: None,
266            stripe_zed_pro_price_id: None,
267            stripe_zed_pro_trial_price_id: None,
268            stripe_zed_free_price_id: None,
269            supermaven_admin_api_key: None,
270            user_backfiller_github_access_token: None,
271            kinesis_region: None,
272            kinesis_access_key: None,
273            kinesis_secret_key: None,
274            kinesis_stream: None,
275        }
276    }
277}
278
279/// The service mode that collab should run in.
280#[derive(Debug, PartialEq, Eq, Clone, Copy, strum::Display)]
281#[strum(serialize_all = "snake_case")]
282pub enum ServiceMode {
283    Api,
284    Collab,
285    All,
286}
287
288impl ServiceMode {
289    pub fn is_collab(&self) -> bool {
290        matches!(self, Self::Collab | Self::All)
291    }
292
293    pub fn is_api(&self) -> bool {
294        matches!(self, Self::Api | Self::All)
295    }
296}
297
298pub struct AppState {
299    pub db: Arc<Database>,
300    pub llm_db: Option<Arc<LlmDatabase>>,
301    pub livekit_client: Option<Arc<dyn livekit_api::Client>>,
302    pub blob_store_client: Option<aws_sdk_s3::Client>,
303    pub stripe_client: Option<Arc<stripe::Client>>,
304    pub stripe_billing: Option<Arc<StripeBilling>>,
305    pub rate_limiter: Arc<RateLimiter>,
306    pub executor: Executor,
307    pub kinesis_client: Option<::aws_sdk_kinesis::Client>,
308    pub config: Config,
309}
310
311impl AppState {
312    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
313        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
314        db_options.max_connections(config.database_max_connections);
315        let mut db = Database::new(db_options, Executor::Production).await?;
316        db.initialize_notification_kinds().await?;
317
318        let llm_db = if let Some((llm_database_url, llm_database_max_connections)) = config
319            .llm_database_url
320            .clone()
321            .zip(config.llm_database_max_connections)
322        {
323            let mut llm_db_options = db::ConnectOptions::new(llm_database_url);
324            llm_db_options.max_connections(llm_database_max_connections);
325            let mut llm_db = LlmDatabase::new(llm_db_options, executor.clone()).await?;
326            llm_db.initialize().await?;
327            Some(Arc::new(llm_db))
328        } else {
329            None
330        };
331
332        let livekit_client = if let Some(((server, key), secret)) = config
333            .livekit_server
334            .as_ref()
335            .zip(config.livekit_key.as_ref())
336            .zip(config.livekit_secret.as_ref())
337        {
338            Some(Arc::new(livekit_api::LiveKitClient::new(
339                server.clone(),
340                key.clone(),
341                secret.clone(),
342            )) as Arc<dyn livekit_api::Client>)
343        } else {
344            None
345        };
346
347        let db = Arc::new(db);
348        let stripe_client = build_stripe_client(&config).map(Arc::new).log_err();
349        let this = Self {
350            db: db.clone(),
351            llm_db,
352            livekit_client,
353            blob_store_client: build_blob_store_client(&config).await.log_err(),
354            stripe_billing: stripe_client
355                .clone()
356                .map(|stripe_client| Arc::new(StripeBilling::new(stripe_client))),
357            stripe_client,
358            rate_limiter: Arc::new(RateLimiter::new(db)),
359            executor,
360            kinesis_client: if config.kinesis_access_key.is_some() {
361                build_kinesis_client(&config).await.log_err()
362            } else {
363                None
364            },
365            config,
366        };
367        Ok(Arc::new(this))
368    }
369}
370
371fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
372    let api_key = config
373        .stripe_api_key
374        .as_ref()
375        .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
376    Ok(stripe::Client::new(api_key))
377}
378
379async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
380    let keys = aws_sdk_s3::config::Credentials::new(
381        config
382            .blob_store_access_key
383            .clone()
384            .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
385        config
386            .blob_store_secret_key
387            .clone()
388            .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
389        None,
390        None,
391        "env",
392    );
393
394    let s3_config = aws_config::defaults(BehaviorVersion::latest())
395        .endpoint_url(
396            config
397                .blob_store_url
398                .as_ref()
399                .ok_or_else(|| anyhow!("missing blob_store_url"))?,
400        )
401        .region(Region::new(
402            config
403                .blob_store_region
404                .clone()
405                .ok_or_else(|| anyhow!("missing blob_store_region"))?,
406        ))
407        .credentials_provider(keys)
408        .load()
409        .await;
410
411    Ok(aws_sdk_s3::Client::new(&s3_config))
412}
413
414async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis::Client> {
415    let keys = aws_sdk_s3::config::Credentials::new(
416        config
417            .kinesis_access_key
418            .clone()
419            .ok_or_else(|| anyhow!("missing kinesis_access_key"))?,
420        config
421            .kinesis_secret_key
422            .clone()
423            .ok_or_else(|| anyhow!("missing kinesis_secret_key"))?,
424        None,
425        None,
426        "env",
427    );
428
429    let kinesis_config = aws_config::defaults(BehaviorVersion::latest())
430        .region(Region::new(
431            config
432                .kinesis_region
433                .clone()
434                .ok_or_else(|| anyhow!("missing kinesis_region"))?,
435        ))
436        .credentials_provider(keys)
437        .load()
438        .await;
439
440    Ok(aws_sdk_kinesis::Client::new(&kinesis_config))
441}