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