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