1pub mod api;
2pub mod auth;
3pub mod db;
4pub mod env;
5pub mod executor;
6pub mod rpc;
7
8#[cfg(test)]
9mod tests;
10
11use anyhow::anyhow;
12use aws_config::{BehaviorVersion, Region};
13use axum::{http::StatusCode, response::IntoResponse};
14use db::{ChannelId, Database};
15use executor::Executor;
16use serde::Deserialize;
17use std::{path::PathBuf, sync::Arc};
18use util::ResultExt;
19
20pub type Result<T, E = Error> = std::result::Result<T, E>;
21
22pub enum Error {
23 Http(StatusCode, String),
24 Database(sea_orm::error::DbErr),
25 Internal(anyhow::Error),
26}
27
28impl From<anyhow::Error> for Error {
29 fn from(error: anyhow::Error) -> Self {
30 Self::Internal(error)
31 }
32}
33
34impl From<sea_orm::error::DbErr> for Error {
35 fn from(error: sea_orm::error::DbErr) -> Self {
36 Self::Database(error)
37 }
38}
39
40impl From<axum::Error> for Error {
41 fn from(error: axum::Error) -> Self {
42 Self::Internal(error.into())
43 }
44}
45
46impl From<axum::http::Error> for Error {
47 fn from(error: axum::http::Error) -> Self {
48 Self::Internal(error.into())
49 }
50}
51
52impl From<serde_json::Error> for Error {
53 fn from(error: serde_json::Error) -> Self {
54 Self::Internal(error.into())
55 }
56}
57
58impl IntoResponse for Error {
59 fn into_response(self) -> axum::response::Response {
60 match self {
61 Error::Http(code, message) => {
62 log::error!("HTTP error {}: {}", code, &message);
63 (code, message).into_response()
64 }
65 Error::Database(error) => {
66 log::error!(
67 "HTTP error {}: {:?}",
68 StatusCode::INTERNAL_SERVER_ERROR,
69 &error
70 );
71 (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
72 }
73 Error::Internal(error) => {
74 log::error!(
75 "HTTP error {}: {:?}",
76 StatusCode::INTERNAL_SERVER_ERROR,
77 &error
78 );
79 (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", &error)).into_response()
80 }
81 }
82 }
83}
84
85impl std::fmt::Debug for Error {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 match self {
88 Error::Http(code, message) => (code, message).fmt(f),
89 Error::Database(error) => error.fmt(f),
90 Error::Internal(error) => error.fmt(f),
91 }
92 }
93}
94
95impl std::fmt::Display for Error {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 match self {
98 Error::Http(code, message) => write!(f, "{code}: {message}"),
99 Error::Database(error) => error.fmt(f),
100 Error::Internal(error) => error.fmt(f),
101 }
102 }
103}
104
105impl std::error::Error for Error {}
106
107#[derive(Deserialize)]
108pub struct Config {
109 pub http_port: u16,
110 pub database_url: String,
111 pub database_max_connections: u32,
112 pub api_token: String,
113 pub clickhouse_url: Option<String>,
114 pub clickhouse_user: Option<String>,
115 pub clickhouse_password: Option<String>,
116 pub clickhouse_database: Option<String>,
117 pub invite_link_prefix: String,
118 pub live_kit_server: Option<String>,
119 pub live_kit_key: Option<String>,
120 pub live_kit_secret: Option<String>,
121 pub rust_log: Option<String>,
122 pub log_json: Option<bool>,
123 pub blob_store_url: Option<String>,
124 pub blob_store_region: Option<String>,
125 pub blob_store_access_key: Option<String>,
126 pub blob_store_secret_key: Option<String>,
127 pub blob_store_bucket: Option<String>,
128 pub zed_environment: Arc<str>,
129 pub zed_client_checksum_seed: Option<String>,
130 pub slack_panics_webhook: Option<String>,
131 pub auto_join_channel_id: Option<ChannelId>,
132}
133
134impl Config {
135 pub fn is_development(&self) -> bool {
136 self.zed_environment == "development".into()
137 }
138}
139
140#[derive(Default, Deserialize)]
141pub struct MigrateConfig {
142 pub database_url: String,
143 pub migrations_path: Option<PathBuf>,
144}
145
146pub struct AppState {
147 pub db: Arc<Database>,
148 pub live_kit_client: Option<Arc<dyn live_kit_server::api::Client>>,
149 pub blob_store_client: Option<aws_sdk_s3::Client>,
150 pub clickhouse_client: Option<clickhouse::Client>,
151 pub config: Config,
152}
153
154impl AppState {
155 pub async fn new(config: Config) -> Result<Arc<Self>> {
156 let mut db_options = db::ConnectOptions::new(config.database_url.clone());
157 db_options.max_connections(config.database_max_connections);
158 let mut db = Database::new(db_options, Executor::Production).await?;
159 db.initialize_notification_kinds().await?;
160
161 let live_kit_client = if let Some(((server, key), secret)) = config
162 .live_kit_server
163 .as_ref()
164 .zip(config.live_kit_key.as_ref())
165 .zip(config.live_kit_secret.as_ref())
166 {
167 Some(Arc::new(live_kit_server::api::LiveKitClient::new(
168 server.clone(),
169 key.clone(),
170 secret.clone(),
171 )) as Arc<dyn live_kit_server::api::Client>)
172 } else {
173 None
174 };
175
176 let this = Self {
177 db: Arc::new(db),
178 live_kit_client,
179 blob_store_client: build_blob_store_client(&config).await.log_err(),
180 clickhouse_client: config
181 .clickhouse_url
182 .as_ref()
183 .and_then(|_| build_clickhouse_client(&config).log_err()),
184 config,
185 };
186 Ok(Arc::new(this))
187 }
188}
189
190async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::Client> {
191 let keys = aws_sdk_s3::config::Credentials::new(
192 config
193 .blob_store_access_key
194 .clone()
195 .ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
196 config
197 .blob_store_secret_key
198 .clone()
199 .ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
200 None,
201 None,
202 "env",
203 );
204
205 let s3_config = aws_config::defaults(BehaviorVersion::latest())
206 .endpoint_url(
207 config
208 .blob_store_url
209 .as_ref()
210 .ok_or_else(|| anyhow!("missing blob_store_url"))?,
211 )
212 .region(Region::new(
213 config
214 .blob_store_region
215 .clone()
216 .ok_or_else(|| anyhow!("missing blob_store_region"))?,
217 ))
218 .credentials_provider(keys)
219 .load()
220 .await;
221
222 Ok(aws_sdk_s3::Client::new(&s3_config))
223}
224
225fn build_clickhouse_client(config: &Config) -> anyhow::Result<clickhouse::Client> {
226 Ok(clickhouse::Client::default()
227 .with_url(
228 config
229 .clickhouse_url
230 .as_ref()
231 .ok_or_else(|| anyhow!("missing clickhouse_url"))?,
232 )
233 .with_user(
234 config
235 .clickhouse_user
236 .as_ref()
237 .ok_or_else(|| anyhow!("missing clickhouse_user"))?,
238 )
239 .with_password(
240 config
241 .clickhouse_password
242 .as_ref()
243 .ok_or_else(|| anyhow!("missing clickhouse_password"))?,
244 )
245 .with_database(
246 config
247 .clickhouse_database
248 .as_ref()
249 .ok_or_else(|| anyhow!("missing clickhouse_database"))?,
250 ))
251}