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