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