1use anyhow::anyhow;
2use axum::headers::HeaderMapExt;
3use axum::{
4 extract::MatchedPath,
5 http::{Request, Response},
6 routing::get,
7 Extension, Router,
8};
9use collab::api::billing::sync_llm_usage_with_stripe_periodically;
10use collab::api::CloudflareIpCountryHeader;
11use collab::llm::{db::LlmDatabase, log_usage_periodically};
12use collab::migrations::run_database_migrations;
13use collab::user_backfiller::spawn_user_backfiller;
14use collab::{api::billing::poll_stripe_events_periodically, llm::LlmState, ServiceMode};
15use collab::{
16 api::fetch_extensions_from_blob_store_periodically, db, env, executor::Executor,
17 rpc::ResultExt, AppState, Config, RateLimiter, Result,
18};
19use db::Database;
20use std::{
21 env::args,
22 net::{SocketAddr, TcpListener},
23 path::Path,
24 sync::Arc,
25 time::Duration,
26};
27#[cfg(unix)]
28use tokio::signal::unix::SignalKind;
29use tower_http::trace::TraceLayer;
30use tracing_subscriber::{
31 filter::EnvFilter, fmt::format::JsonFields, util::SubscriberInitExt, Layer,
32};
33use util::{maybe, ResultExt as _};
34
35const VERSION: &str = env!("CARGO_PKG_VERSION");
36const REVISION: Option<&'static str> = option_env!("GITHUB_SHA");
37
38#[tokio::main]
39async fn main() -> Result<()> {
40 if let Err(error) = env::load_dotenv() {
41 eprintln!(
42 "error loading .env.toml (this is expected in production): {}",
43 error
44 );
45 }
46
47 let mut args = args().skip(1);
48 match args.next().as_deref() {
49 Some("version") => {
50 println!("collab v{} ({})", VERSION, REVISION.unwrap_or("unknown"));
51 }
52 Some("migrate") => {
53 let config = envy::from_env::<Config>().expect("error loading config");
54 setup_app_database(&config).await?;
55 }
56 Some("seed") => {
57 let config = envy::from_env::<Config>().expect("error loading config");
58 let db_options = db::ConnectOptions::new(config.database_url.clone());
59
60 let mut db = Database::new(db_options, Executor::Production).await?;
61 db.initialize_notification_kinds().await?;
62
63 collab::seed::seed(&config, &db, false).await?;
64
65 if let Some(llm_database_url) = config.llm_database_url.clone() {
66 let db_options = db::ConnectOptions::new(llm_database_url);
67 let mut db = LlmDatabase::new(db_options.clone(), Executor::Production).await?;
68 db.initialize().await?;
69 collab::llm::db::seed_database(&config, &mut db, true).await?;
70 }
71 }
72 Some("serve") => {
73 let mode = match args.next().as_deref() {
74 Some("collab") => ServiceMode::Collab,
75 Some("api") => ServiceMode::Api,
76 Some("llm") => ServiceMode::Llm,
77 Some("all") => ServiceMode::All,
78 _ => {
79 return Err(anyhow!(
80 "usage: collab <version | migrate | seed | serve <api|collab|llm|all>>"
81 ))?;
82 }
83 };
84
85 let config = envy::from_env::<Config>().expect("error loading config");
86 init_tracing(&config);
87 let mut app = Router::new()
88 .route("/", get(handle_root))
89 .route("/healthz", get(handle_liveness_probe))
90 .layer(Extension(mode));
91
92 let listener = TcpListener::bind(format!("0.0.0.0:{}", config.http_port))
93 .expect("failed to bind TCP listener");
94
95 let mut on_shutdown = None;
96
97 if mode.is_llm() {
98 setup_llm_database(&config).await?;
99
100 let state = LlmState::new(config.clone(), Executor::Production).await?;
101
102 log_usage_periodically(state.clone());
103
104 app = app
105 .merge(collab::llm::routes())
106 .layer(Extension(state.clone()));
107 }
108
109 if mode.is_collab() || mode.is_api() {
110 setup_app_database(&config).await?;
111
112 let state = AppState::new(config, Executor::Production).await?;
113
114 if let Some(stripe_billing) = state.stripe_billing.clone() {
115 let executor = state.executor.clone();
116 executor.spawn_detached(async move {
117 stripe_billing.initialize().await.trace_err();
118 });
119 }
120
121 if mode.is_collab() {
122 state.db.purge_old_embeddings().await.trace_err();
123 RateLimiter::save_periodically(
124 state.rate_limiter.clone(),
125 state.executor.clone(),
126 );
127
128 let epoch = state
129 .db
130 .create_server(&state.config.zed_environment)
131 .await?;
132 let rpc_server = collab::rpc::Server::new(epoch, state.clone());
133 rpc_server.start().await?;
134
135 poll_stripe_events_periodically(state.clone(), rpc_server.clone());
136
137 app = app
138 .merge(collab::api::routes(rpc_server.clone()))
139 .merge(collab::rpc::routes(rpc_server.clone()));
140
141 on_shutdown = Some(Box::new(move || rpc_server.teardown()));
142 }
143
144 if mode.is_api() {
145 fetch_extensions_from_blob_store_periodically(state.clone());
146 spawn_user_backfiller(state.clone());
147
148 let llm_db = maybe!(async {
149 let database_url = state
150 .config
151 .llm_database_url
152 .as_ref()
153 .ok_or_else(|| anyhow!("missing LLM_DATABASE_URL"))?;
154 let max_connections = state
155 .config
156 .llm_database_max_connections
157 .ok_or_else(|| anyhow!("missing LLM_DATABASE_MAX_CONNECTIONS"))?;
158
159 let mut db_options = db::ConnectOptions::new(database_url);
160 db_options.max_connections(max_connections);
161 LlmDatabase::new(db_options, state.executor.clone()).await
162 })
163 .await
164 .trace_err();
165
166 if let Some(mut llm_db) = llm_db {
167 llm_db.initialize().await?;
168 sync_llm_usage_with_stripe_periodically(state.clone());
169 }
170
171 app = app
172 .merge(collab::api::events::router())
173 .merge(collab::api::extensions::router())
174 }
175
176 app = app.layer(Extension(state.clone()));
177 }
178
179 app = app.layer(
180 TraceLayer::new_for_http()
181 .make_span_with(|request: &Request<_>| {
182 let matched_path = request
183 .extensions()
184 .get::<MatchedPath>()
185 .map(MatchedPath::as_str);
186
187 let geoip_country_code = request
188 .headers()
189 .typed_get::<CloudflareIpCountryHeader>()
190 .map(|header| header.to_string());
191
192 tracing::info_span!(
193 "http_request",
194 method = ?request.method(),
195 matched_path,
196 geoip_country_code,
197 user_id = tracing::field::Empty,
198 login = tracing::field::Empty,
199 authn.jti = tracing::field::Empty,
200 is_staff = tracing::field::Empty
201 )
202 })
203 .on_response(
204 |response: &Response<_>, latency: Duration, _: &tracing::Span| {
205 let duration_ms = latency.as_micros() as f64 / 1000.;
206 tracing::info!(
207 duration_ms,
208 status = response.status().as_u16(),
209 "finished processing request"
210 );
211 },
212 ),
213 );
214
215 #[cfg(unix)]
216 let signal = async move {
217 let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())
218 .expect("failed to listen for interrupt signal");
219 let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())
220 .expect("failed to listen for interrupt signal");
221 let sigterm = sigterm.recv();
222 let sigint = sigint.recv();
223 futures::pin_mut!(sigterm, sigint);
224 futures::future::select(sigterm, sigint).await;
225 };
226
227 #[cfg(windows)]
228 let signal = async move {
229 // todo(windows):
230 // `ctrl_close` does not work well, because tokio's signal handler always returns soon,
231 // but system terminates the application soon after returning CTRL+CLOSE handler.
232 // So we should implement blocking handler to treat CTRL+CLOSE signal.
233 let mut ctrl_break = tokio::signal::windows::ctrl_break()
234 .expect("failed to listen for interrupt signal");
235 let mut ctrl_c = tokio::signal::windows::ctrl_c()
236 .expect("failed to listen for interrupt signal");
237 let ctrl_break = ctrl_break.recv();
238 let ctrl_c = ctrl_c.recv();
239 futures::pin_mut!(ctrl_break, ctrl_c);
240 futures::future::select(ctrl_break, ctrl_c).await;
241 };
242
243 axum::Server::from_tcp(listener)
244 .map_err(|e| anyhow!(e))?
245 .serve(app.into_make_service_with_connect_info::<SocketAddr>())
246 .with_graceful_shutdown(async move {
247 signal.await;
248 tracing::info!("Received interrupt signal");
249
250 if let Some(on_shutdown) = on_shutdown {
251 on_shutdown();
252 }
253 })
254 .await
255 .map_err(|e| anyhow!(e))?;
256 }
257 _ => {
258 Err(anyhow!(
259 "usage: collab <version | migrate | seed | serve <api|collab|llm|all>>"
260 ))?;
261 }
262 }
263 Ok(())
264}
265
266async fn setup_app_database(config: &Config) -> Result<()> {
267 let db_options = db::ConnectOptions::new(config.database_url.clone());
268 let mut db = Database::new(db_options, Executor::Production).await?;
269
270 let migrations_path = config.migrations_path.as_deref().unwrap_or_else(|| {
271 #[cfg(feature = "sqlite")]
272 let default_migrations = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations.sqlite");
273 #[cfg(not(feature = "sqlite"))]
274 let default_migrations = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations");
275
276 Path::new(default_migrations)
277 });
278
279 let migrations = run_database_migrations(db.options(), migrations_path).await?;
280 for (migration, duration) in migrations {
281 log::info!(
282 "Migrated {} {} {:?}",
283 migration.version,
284 migration.description,
285 duration
286 );
287 }
288
289 db.initialize_notification_kinds().await?;
290
291 if config.seed_path.is_some() {
292 collab::seed::seed(config, &db, false).await?;
293 }
294
295 Ok(())
296}
297
298async fn setup_llm_database(config: &Config) -> Result<()> {
299 let database_url = config
300 .llm_database_url
301 .as_ref()
302 .ok_or_else(|| anyhow!("missing LLM_DATABASE_URL"))?;
303
304 let db_options = db::ConnectOptions::new(database_url.clone());
305 let db = LlmDatabase::new(db_options, Executor::Production).await?;
306
307 let migrations_path = config
308 .llm_database_migrations_path
309 .as_deref()
310 .unwrap_or_else(|| {
311 #[cfg(feature = "sqlite")]
312 let default_migrations = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations_llm.sqlite");
313 #[cfg(not(feature = "sqlite"))]
314 let default_migrations = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations_llm");
315
316 Path::new(default_migrations)
317 });
318
319 let migrations = run_database_migrations(db.options(), migrations_path).await?;
320 for (migration, duration) in migrations {
321 log::info!(
322 "Migrated {} {} {:?}",
323 migration.version,
324 migration.description,
325 duration
326 );
327 }
328
329 Ok(())
330}
331
332async fn handle_root(Extension(mode): Extension<ServiceMode>) -> String {
333 format!("zed:{mode} v{VERSION} ({})", REVISION.unwrap_or("unknown"))
334}
335
336async fn handle_liveness_probe(
337 app_state: Option<Extension<Arc<AppState>>>,
338 llm_state: Option<Extension<Arc<LlmState>>>,
339) -> Result<String> {
340 if let Some(state) = app_state {
341 state.db.get_all_users(0, 1).await?;
342 }
343
344 if let Some(llm_state) = llm_state {
345 llm_state.db.list_providers().await?;
346 }
347
348 Ok("ok".to_string())
349}
350
351pub fn init_tracing(config: &Config) -> Option<()> {
352 use std::str::FromStr;
353 use tracing_subscriber::layer::SubscriberExt;
354
355 let filter = EnvFilter::from_str(config.rust_log.as_deref()?).log_err()?;
356
357 tracing_subscriber::registry()
358 .with(if config.log_json.unwrap_or(false) {
359 Box::new(
360 tracing_subscriber::fmt::layer()
361 .fmt_fields(JsonFields::default())
362 .event_format(
363 tracing_subscriber::fmt::format()
364 .json()
365 .flatten_event(true)
366 .with_span_list(false),
367 )
368 .with_filter(filter),
369 ) as Box<dyn Layer<_> + Send + Sync>
370 } else {
371 Box::new(
372 tracing_subscriber::fmt::layer()
373 .event_format(tracing_subscriber::fmt::format().pretty())
374 .with_filter(filter),
375 )
376 })
377 .init();
378
379 None
380}