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 auto_join_channel_id: Option<ChannelId>,
157 pub supermaven_admin_api_key: Option<Arc<str>>,
158}
159
160impl Config {
161 pub fn is_development(&self) -> bool {
162 self.zed_environment == "development".into()
163 }
164
165 /// Returns the base `zed.dev` URL.
166 pub fn zed_dot_dev_url(&self) -> &str {
167 match self.zed_environment.as_ref() {
168 "development" => "http://localhost:3000",
169 "staging" => "https://staging.zed.dev",
170 _ => "https://zed.dev",
171 }
172 }
173
174 #[cfg(test)]
175 pub fn test() -> Self {
176 Self {
177 http_port: 0,
178 database_url: "".into(),
179 database_max_connections: 0,
180 api_token: "".into(),
181 invite_link_prefix: "".into(),
182 livekit_server: None,
183 livekit_key: None,
184 livekit_secret: None,
185 llm_database_url: None,
186 llm_database_max_connections: None,
187 llm_database_migrations_path: None,
188 llm_api_secret: None,
189 rust_log: None,
190 log_json: None,
191 zed_environment: "test".into(),
192 blob_store_url: None,
193 blob_store_region: None,
194 blob_store_access_key: None,
195 blob_store_secret_key: None,
196 blob_store_bucket: None,
197 openai_api_key: None,
198 google_ai_api_key: None,
199 anthropic_api_key: None,
200 anthropic_staff_api_key: None,
201 llm_closed_beta_model_name: None,
202 prediction_api_url: None,
203 prediction_api_key: None,
204 prediction_model: None,
205 zed_client_checksum_seed: None,
206 auto_join_channel_id: None,
207 migrations_path: None,
208 seed_path: None,
209 supermaven_admin_api_key: None,
210 kinesis_region: None,
211 kinesis_access_key: None,
212 kinesis_secret_key: None,
213 kinesis_stream: None,
214 }
215 }
216}
217
218/// The service mode that collab should run in.
219#[derive(Debug, PartialEq, Eq, Clone, Copy, strum::Display)]
220#[strum(serialize_all = "snake_case")]
221pub enum ServiceMode {
222 Api,
223 Collab,
224 All,
225}
226
227impl ServiceMode {
228 pub const fn is_collab(&self) -> bool {
229 matches!(self, Self::Collab | Self::All)
230 }
231
232 pub const fn is_api(&self) -> bool {
233 matches!(self, Self::Api | Self::All)
234 }
235}
236
237pub struct AppState {
238 pub db: Arc<Database>,
239 pub livekit_client: Option<Arc<dyn livekit_api::Client>>,
240 pub blob_store_client: Option<aws_sdk_s3::Client>,
241 pub executor: Executor,
242 pub kinesis_client: Option<::aws_sdk_kinesis::Client>,
243 pub config: Config,
244}
245
246impl AppState {
247 pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
248 let mut db_options = db::ConnectOptions::new(config.database_url.clone());
249 db_options.max_connections(config.database_max_connections);
250 let mut db = Database::new(db_options).await?;
251 db.initialize_notification_kinds().await?;
252
253 let livekit_client = if let Some(((server, key), secret)) = config
254 .livekit_server
255 .as_ref()
256 .zip(config.livekit_key.as_ref())
257 .zip(config.livekit_secret.as_ref())
258 {
259 Some(Arc::new(livekit_api::LiveKitClient::new(
260 server.clone(),
261 key.clone(),
262 secret.clone(),
263 )) as Arc<dyn livekit_api::Client>)
264 } else {
265 None
266 };
267
268 let db = Arc::new(db);
269 let this = Self {
270 db: db.clone(),
271 livekit_client,
272 blob_store_client: build_blob_store_client(&config).await.log_err(),
273 executor,
274 kinesis_client: if config.kinesis_access_key.is_some() {
275 build_kinesis_client(&config).await.log_err()
276 } else {
277 None
278 },
279 config,
280 };
281 Ok(Arc::new(this))
282 }
283}
284
285async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
286 let keys = aws_sdk_s3::config::Credentials::new(
287 config
288 .blob_store_access_key
289 .clone()
290 .context("missing blob_store_access_key")?,
291 config
292 .blob_store_secret_key
293 .clone()
294 .context("missing blob_store_secret_key")?,
295 None,
296 None,
297 "env",
298 );
299
300 let s3_config = aws_config::defaults(BehaviorVersion::latest())
301 .endpoint_url(
302 config
303 .blob_store_url
304 .as_ref()
305 .context("missing blob_store_url")?,
306 )
307 .region(Region::new(
308 config
309 .blob_store_region
310 .clone()
311 .context("missing blob_store_region")?,
312 ))
313 .credentials_provider(keys)
314 .load()
315 .await;
316
317 Ok(aws_sdk_s3::Client::new(&s3_config))
318}
319
320async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis::Client> {
321 let keys = aws_sdk_s3::config::Credentials::new(
322 config
323 .kinesis_access_key
324 .clone()
325 .context("missing kinesis_access_key")?,
326 config
327 .kinesis_secret_key
328 .clone()
329 .context("missing kinesis_secret_key")?,
330 None,
331 None,
332 "env",
333 );
334
335 let kinesis_config = aws_config::defaults(BehaviorVersion::latest())
336 .region(Region::new(
337 config
338 .kinesis_region
339 .clone()
340 .context("missing kinesis_region")?,
341 ))
342 .credentials_provider(keys)
343 .load()
344 .await;
345
346 Ok(aws_sdk_kinesis::Client::new(&kinesis_config))
347}