1pub mod api;
2pub mod auth;
3mod cents;
4pub mod db;
5pub mod env;
6pub mod executor;
7pub mod llm;
8pub mod migrations;
9pub mod rpc;
10pub mod seed;
11pub mod stripe_billing;
12pub mod stripe_client;
13pub mod user_backfiller;
14
15#[cfg(test)]
16mod tests;
17
18use anyhow::Context as _;
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;
28use serde::Deserialize;
29use std::{path::PathBuf, sync::Arc};
30use util::ResultExt;
31
32use crate::stripe_billing::StripeBilling;
33use crate::stripe_client::{RealStripeClient, StripeClient};
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 /// This is a real instance of the Stripe client; we're working to replace references to this with the
275 /// [`StripeClient`] trait.
276 pub real_stripe_client: Option<Arc<stripe::Client>>,
277 pub stripe_client: Option<Arc<dyn StripeClient>>,
278 pub stripe_billing: Option<Arc<StripeBilling>>,
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
328 .clone()
329 .map(|stripe_client| Arc::new(StripeBilling::new(stripe_client))),
330 real_stripe_client: stripe_client.clone(),
331 stripe_client: stripe_client
332 .map(|stripe_client| Arc::new(RealStripeClient::new(stripe_client)) as _),
333 executor,
334 kinesis_client: if config.kinesis_access_key.is_some() {
335 build_kinesis_client(&config).await.log_err()
336 } else {
337 None
338 },
339 config,
340 };
341 Ok(Arc::new(this))
342 }
343}
344
345fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
346 let api_key = config
347 .stripe_api_key
348 .as_ref()
349 .context("missing stripe_api_key")?;
350 Ok(stripe::Client::new(api_key))
351}
352
353async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
354 let keys = aws_sdk_s3::config::Credentials::new(
355 config
356 .blob_store_access_key
357 .clone()
358 .context("missing blob_store_access_key")?,
359 config
360 .blob_store_secret_key
361 .clone()
362 .context("missing blob_store_secret_key")?,
363 None,
364 None,
365 "env",
366 );
367
368 let s3_config = aws_config::defaults(BehaviorVersion::latest())
369 .endpoint_url(
370 config
371 .blob_store_url
372 .as_ref()
373 .context("missing blob_store_url")?,
374 )
375 .region(Region::new(
376 config
377 .blob_store_region
378 .clone()
379 .context("missing blob_store_region")?,
380 ))
381 .credentials_provider(keys)
382 .load()
383 .await;
384
385 Ok(aws_sdk_s3::Client::new(&s3_config))
386}
387
388async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis::Client> {
389 let keys = aws_sdk_s3::config::Credentials::new(
390 config
391 .kinesis_access_key
392 .clone()
393 .context("missing kinesis_access_key")?,
394 config
395 .kinesis_secret_key
396 .clone()
397 .context("missing kinesis_secret_key")?,
398 None,
399 None,
400 "env",
401 );
402
403 let kinesis_config = aws_config::defaults(BehaviorVersion::latest())
404 .region(Region::new(
405 config
406 .kinesis_region
407 .clone()
408 .context("missing kinesis_region")?,
409 ))
410 .credentials_provider(keys)
411 .load()
412 .await;
413
414 Ok(aws_sdk_kinesis::Client::new(&kinesis_config))
415}