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