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