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 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};
23pub use cents::*;
24use db::{ChannelId, Database};
25use executor::Executor;
26use llm::db::LlmDatabase;
27use serde::Deserialize;
28use std::{path::PathBuf, sync::Arc};
29use util::ResultExt;
30
31use crate::stripe_billing::StripeBilling;
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 pub stripe_client: Option<Arc<stripe::Client>>,
273 pub stripe_billing: Option<Arc<StripeBilling>>,
274 pub executor: Executor,
275 pub kinesis_client: Option<::aws_sdk_kinesis::Client>,
276 pub config: Config,
277}
278
279impl AppState {
280 pub async fn new(config: Config, executor: Executor) -> Result<Arc<Self>> {
281 let mut db_options = db::ConnectOptions::new(config.database_url.clone());
282 db_options.max_connections(config.database_max_connections);
283 let mut db = Database::new(db_options, Executor::Production).await?;
284 db.initialize_notification_kinds().await?;
285
286 let llm_db = if let Some((llm_database_url, llm_database_max_connections)) = config
287 .llm_database_url
288 .clone()
289 .zip(config.llm_database_max_connections)
290 {
291 let mut llm_db_options = db::ConnectOptions::new(llm_database_url);
292 llm_db_options.max_connections(llm_database_max_connections);
293 let mut llm_db = LlmDatabase::new(llm_db_options, executor.clone()).await?;
294 llm_db.initialize().await?;
295 Some(Arc::new(llm_db))
296 } else {
297 None
298 };
299
300 let livekit_client = if let Some(((server, key), secret)) = config
301 .livekit_server
302 .as_ref()
303 .zip(config.livekit_key.as_ref())
304 .zip(config.livekit_secret.as_ref())
305 {
306 Some(Arc::new(livekit_api::LiveKitClient::new(
307 server.clone(),
308 key.clone(),
309 secret.clone(),
310 )) as Arc<dyn livekit_api::Client>)
311 } else {
312 None
313 };
314
315 let db = Arc::new(db);
316 let stripe_client = build_stripe_client(&config).map(Arc::new).log_err();
317 let this = Self {
318 db: db.clone(),
319 llm_db,
320 livekit_client,
321 blob_store_client: build_blob_store_client(&config).await.log_err(),
322 stripe_billing: stripe_client
323 .clone()
324 .map(|stripe_client| Arc::new(StripeBilling::new(stripe_client))),
325 stripe_client,
326 executor,
327 kinesis_client: if config.kinesis_access_key.is_some() {
328 build_kinesis_client(&config).await.log_err()
329 } else {
330 None
331 },
332 config,
333 };
334 Ok(Arc::new(this))
335 }
336}
337
338fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
339 let api_key = config
340 .stripe_api_key
341 .as_ref()
342 .context("missing stripe_api_key")?;
343 Ok(stripe::Client::new(api_key))
344}
345
346async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
347 let keys = aws_sdk_s3::config::Credentials::new(
348 config
349 .blob_store_access_key
350 .clone()
351 .context("missing blob_store_access_key")?,
352 config
353 .blob_store_secret_key
354 .clone()
355 .context("missing blob_store_secret_key")?,
356 None,
357 None,
358 "env",
359 );
360
361 let s3_config = aws_config::defaults(BehaviorVersion::latest())
362 .endpoint_url(
363 config
364 .blob_store_url
365 .as_ref()
366 .context("missing blob_store_url")?,
367 )
368 .region(Region::new(
369 config
370 .blob_store_region
371 .clone()
372 .context("missing blob_store_region")?,
373 ))
374 .credentials_provider(keys)
375 .load()
376 .await;
377
378 Ok(aws_sdk_s3::Client::new(&s3_config))
379}
380
381async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis::Client> {
382 let keys = aws_sdk_s3::config::Credentials::new(
383 config
384 .kinesis_access_key
385 .clone()
386 .context("missing kinesis_access_key")?,
387 config
388 .kinesis_secret_key
389 .clone()
390 .context("missing kinesis_secret_key")?,
391 None,
392 None,
393 "env",
394 );
395
396 let kinesis_config = aws_config::defaults(BehaviorVersion::latest())
397 .region(Region::new(
398 config
399 .kinesis_region
400 .clone()
401 .context("missing kinesis_region")?,
402 ))
403 .credentials_provider(keys)
404 .load()
405 .await;
406
407 Ok(aws_sdk_kinesis::Client::new(&kinesis_config))
408}