lib.rs

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