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