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