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::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 seed_path: Option<PathBuf>,
119    pub database_max_connections: u32,
120    pub api_token: String,
121    pub livekit_server: Option<String>,
122    pub livekit_key: Option<String>,
123    pub livekit_secret: Option<String>,
124    pub rust_log: Option<String>,
125    pub log_json: Option<bool>,
126    pub blob_store_url: Option<String>,
127    pub blob_store_region: Option<String>,
128    pub blob_store_access_key: Option<String>,
129    pub blob_store_secret_key: Option<String>,
130    pub blob_store_bucket: Option<String>,
131    pub kinesis_region: Option<String>,
132    pub kinesis_stream: Option<String>,
133    pub kinesis_access_key: Option<String>,
134    pub kinesis_secret_key: Option<String>,
135    pub zed_environment: Arc<str>,
136    pub zed_client_checksum_seed: Option<String>,
137}
138
139impl Config {
140    pub fn is_development(&self) -> bool {
141        self.zed_environment == "development".into()
142    }
143
144    /// Returns the base `zed.dev` URL.
145    pub fn zed_dot_dev_url(&self) -> &str {
146        match self.zed_environment.as_ref() {
147            "development" => "http://localhost:3000",
148            "staging" => "https://staging.zed.dev",
149            _ => "https://zed.dev",
150        }
151    }
152
153    #[cfg(feature = "test-support")]
154    pub fn test() -> Self {
155        Self {
156            http_port: 0,
157            database_url: "".into(),
158            database_max_connections: 0,
159            api_token: "".into(),
160            livekit_server: None,
161            livekit_key: None,
162            livekit_secret: None,
163            rust_log: None,
164            log_json: None,
165            zed_environment: "test".into(),
166            blob_store_url: None,
167            blob_store_region: None,
168            blob_store_access_key: None,
169            blob_store_secret_key: None,
170            blob_store_bucket: None,
171            zed_client_checksum_seed: None,
172            seed_path: None,
173            kinesis_region: None,
174            kinesis_access_key: None,
175            kinesis_secret_key: None,
176            kinesis_stream: None,
177        }
178    }
179}
180
181/// The service mode that collab should run in.
182#[derive(Debug, PartialEq, Eq, Clone, Copy, strum::Display)]
183#[strum(serialize_all = "snake_case")]
184pub enum ServiceMode {
185    Api,
186    Collab,
187    All,
188}
189
190impl ServiceMode {
191    pub fn is_collab(&self) -> bool {
192        matches!(self, Self::Collab | Self::All)
193    }
194
195    pub fn is_api(&self) -> bool {
196        matches!(self, Self::Api | Self::All)
197    }
198}
199
200pub struct AppState {
201    pub db: Arc<Database>,
202    pub livekit_client: Option<Arc<dyn livekit_api::Client>>,
203    pub blob_store_client: Option<aws_sdk_s3::Client>,
204    pub executor: Executor,
205    pub kinesis_client: Option<::aws_sdk_kinesis::Client>,
206    pub config: Config,
207}
208
209impl AppState {
210    pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
211        let mut db_options = db::ConnectOptions::new(config.database_url.clone());
212        db_options.max_connections(config.database_max_connections);
213        let mut db = Database::new(db_options).await?;
214        db.initialize_notification_kinds().await?;
215
216        let livekit_client = if let Some(((server, key), secret)) = config
217            .livekit_server
218            .as_ref()
219            .zip(config.livekit_key.as_ref())
220            .zip(config.livekit_secret.as_ref())
221        {
222            Some(Arc::new(livekit_api::LiveKitClient::new(
223                server.clone(),
224                key.clone(),
225                secret.clone(),
226            )) as Arc<dyn livekit_api::Client>)
227        } else {
228            None
229        };
230
231        let db = Arc::new(db);
232        let this = Self {
233            db: db.clone(),
234            livekit_client,
235            blob_store_client: build_blob_store_client(&config).await.log_err(),
236            executor,
237            kinesis_client: if config.kinesis_access_key.is_some() {
238                build_kinesis_client(&config).await.log_err()
239            } else {
240                None
241            },
242            config,
243        };
244        Ok(Arc::new(this))
245    }
246}
247
248async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
249    let keys = aws_sdk_s3::config::Credentials::new(
250        config
251            .blob_store_access_key
252            .clone()
253            .context("missing blob_store_access_key")?,
254        config
255            .blob_store_secret_key
256            .clone()
257            .context("missing blob_store_secret_key")?,
258        None,
259        None,
260        "env",
261    );
262
263    let s3_config = aws_config::defaults(BehaviorVersion::latest())
264        .endpoint_url(
265            config
266                .blob_store_url
267                .as_ref()
268                .context("missing blob_store_url")?,
269        )
270        .region(Region::new(
271            config
272                .blob_store_region
273                .clone()
274                .context("missing blob_store_region")?,
275        ))
276        .credentials_provider(keys)
277        .load()
278        .await;
279
280    Ok(aws_sdk_s3::Client::new(&s3_config))
281}
282
283async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis::Client> {
284    let keys = aws_sdk_s3::config::Credentials::new(
285        config
286            .kinesis_access_key
287            .clone()
288            .context("missing kinesis_access_key")?,
289        config
290            .kinesis_secret_key
291            .clone()
292            .context("missing kinesis_secret_key")?,
293        None,
294        None,
295        "env",
296    );
297
298    let kinesis_config = aws_config::defaults(BehaviorVersion::latest())
299        .region(Region::new(
300            config
301                .kinesis_region
302                .clone()
303                .context("missing kinesis_region")?,
304        ))
305        .credentials_provider(keys)
306        .load()
307        .await;
308
309    Ok(aws_sdk_kinesis::Client::new(&kinesis_config))
310}