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