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 stripe_zed_pro_price_id: Option<String>,
186 pub supermaven_admin_api_key: Option<Arc<str>>,
187 pub user_backfiller_github_access_token: Option<Arc<str>>,
188}
189
190impl Config {
191 pub fn is_development(&self) -> bool {
192 self.zed_environment == "development".into()
193 }
194
195 /// Returns the base `zed.dev` URL.
196 pub fn zed_dot_dev_url(&self) -> &str {
197 match self.zed_environment.as_ref() {
198 "development" => "http://localhost:3000",
199 "staging" => "https://staging.zed.dev",
200 _ => "https://zed.dev",
201 }
202 }
203
204 #[cfg(test)]
205 pub fn test() -> Self {
206 Self {
207 http_port: 0,
208 database_url: "".into(),
209 database_max_connections: 0,
210 api_token: "".into(),
211 invite_link_prefix: "".into(),
212 livekit_server: None,
213 livekit_key: None,
214 livekit_secret: None,
215 llm_database_url: None,
216 llm_database_max_connections: None,
217 llm_database_migrations_path: None,
218 llm_api_secret: None,
219 rust_log: None,
220 log_json: None,
221 zed_environment: "test".into(),
222 blob_store_url: None,
223 blob_store_region: None,
224 blob_store_access_key: None,
225 blob_store_secret_key: None,
226 blob_store_bucket: None,
227 openai_api_key: None,
228 google_ai_api_key: None,
229 anthropic_api_key: None,
230 anthropic_staff_api_key: None,
231 llm_closed_beta_model_name: None,
232 prediction_api_url: None,
233 prediction_api_key: None,
234 prediction_model: None,
235 zed_client_checksum_seed: None,
236 slack_panics_webhook: None,
237 auto_join_channel_id: None,
238 migrations_path: None,
239 seed_path: None,
240 stripe_api_key: None,
241 stripe_zed_pro_price_id: None,
242 supermaven_admin_api_key: None,
243 user_backfiller_github_access_token: None,
244 kinesis_region: None,
245 kinesis_access_key: None,
246 kinesis_secret_key: None,
247 kinesis_stream: None,
248 }
249 }
250}
251
252/// The service mode that collab should run in.
253#[derive(Debug, PartialEq, Eq, Clone, Copy, strum::Display)]
254#[strum(serialize_all = "snake_case")]
255pub enum ServiceMode {
256 Api,
257 Collab,
258 All,
259}
260
261impl ServiceMode {
262 pub fn is_collab(&self) -> bool {
263 matches!(self, Self::Collab | Self::All)
264 }
265
266 pub fn is_api(&self) -> bool {
267 matches!(self, Self::Api | Self::All)
268 }
269}
270
271pub struct AppState {
272 pub db: Arc<Database>,
273 pub llm_db: Option<Arc<LlmDatabase>>,
274 pub livekit_client: Option<Arc<dyn livekit_api::Client>>,
275 pub blob_store_client: Option<aws_sdk_s3::Client>,
276 pub stripe_client: Option<Arc<stripe::Client>>,
277 pub stripe_billing: Option<Arc<StripeBilling>>,
278 pub rate_limiter: Arc<RateLimiter>,
279 pub executor: Executor,
280 pub kinesis_client: Option<::aws_sdk_kinesis::Client>,
281 pub config: Config,
282}
283
284impl AppState {
285 pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
286 let mut db_options = db::ConnectOptions::new(config.database_url.clone());
287 db_options.max_connections(config.database_max_connections);
288 let mut db = Database::new(db_options, Executor::Production).await?;
289 db.initialize_notification_kinds().await?;
290
291 let llm_db = if let Some((llm_database_url, llm_database_max_connections)) = config
292 .llm_database_url
293 .clone()
294 .zip(config.llm_database_max_connections)
295 {
296 let mut llm_db_options = db::ConnectOptions::new(llm_database_url);
297 llm_db_options.max_connections(llm_database_max_connections);
298 let mut llm_db = LlmDatabase::new(llm_db_options, executor.clone()).await?;
299 llm_db.initialize().await?;
300 Some(Arc::new(llm_db))
301 } else {
302 None
303 };
304
305 let livekit_client = if let Some(((server, key), secret)) = config
306 .livekit_server
307 .as_ref()
308 .zip(config.livekit_key.as_ref())
309 .zip(config.livekit_secret.as_ref())
310 {
311 Some(Arc::new(livekit_api::LiveKitClient::new(
312 server.clone(),
313 key.clone(),
314 secret.clone(),
315 )) as Arc<dyn livekit_api::Client>)
316 } else {
317 None
318 };
319
320 let db = Arc::new(db);
321 let stripe_client = build_stripe_client(&config).map(Arc::new).log_err();
322 let this = Self {
323 db: db.clone(),
324 llm_db,
325 livekit_client,
326 blob_store_client: build_blob_store_client(&config).await.log_err(),
327 stripe_billing: stripe_client.clone().map(|stripe_client| {
328 Arc::new(StripeBilling::new(
329 stripe_client,
330 config.stripe_zed_pro_price_id.clone(),
331 ))
332 }),
333 stripe_client,
334 rate_limiter: Arc::new(RateLimiter::new(db)),
335 executor,
336 kinesis_client: if config.kinesis_access_key.is_some() {
337 build_kinesis_client(&config).await.log_err()
338 } else {
339 None
340 },
341 config,
342 };
343 Ok(Arc::new(this))
344 }
345}
346
347fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
348 let api_key = config
349 .stripe_api_key
350 .as_ref()
351 .ok_or_else(|| anyhow!("missing stripe_api_key"))?;
352 Ok(stripe::Client::new(api_key))
353}
354
355async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
356 let keys = aws_sdk_s3::config::Credentials::new(
357 config
358 .blob_store_access_key
359 .clone()
360 .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
361 config
362 .blob_store_secret_key
363 .clone()
364 .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
365 None,
366 None,
367 "env",
368 );
369
370 let s3_config = aws_config::defaults(BehaviorVersion::latest())
371 .endpoint_url(
372 config
373 .blob_store_url
374 .as_ref()
375 .ok_or_else(|| anyhow!("missing blob_store_url"))?,
376 )
377 .region(Region::new(
378 config
379 .blob_store_region
380 .clone()
381 .ok_or_else(|| anyhow!("missing blob_store_region"))?,
382 ))
383 .credentials_provider(keys)
384 .load()
385 .await;
386
387 Ok(aws_sdk_s3::Client::new(&s3_config))
388}
389
390async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis::Client> {
391 let keys = aws_sdk_s3::config::Credentials::new(
392 config
393 .kinesis_access_key
394 .clone()
395 .ok_or_else(|| anyhow!("missing kinesis_access_key"))?,
396 config
397 .kinesis_secret_key
398 .clone()
399 .ok_or_else(|| anyhow!("missing kinesis_secret_key"))?,
400 None,
401 None,
402 "env",
403 );
404
405 let kinesis_config = aws_config::defaults(BehaviorVersion::latest())
406 .region(Region::new(
407 config
408 .kinesis_region
409 .clone()
410 .ok_or_else(|| anyhow!("missing kinesis_region"))?,
411 ))
412 .credentials_provider(keys)
413 .load()
414 .await;
415
416 Ok(aws_sdk_kinesis::Client::new(&kinesis_config))
417}