1use anyhow::anyhow;
2use axum::headers::HeaderMapExt;
3use axum::{
4 Extension, Router,
5 extract::MatchedPath,
6 http::{Request, Response},
7 routing::get,
8};
9
10use collab::ServiceMode;
11use collab::api::CloudflareIpCountryHeader;
12use collab::{
13 AppState, Config, Result, api::fetch_extensions_from_blob_store_periodically, db, env,
14 executor::Executor,
15};
16use db::Database;
17use std::{
18 env::args,
19 net::{SocketAddr, TcpListener},
20 sync::Arc,
21 time::Duration,
22};
23#[cfg(unix)]
24use tokio::signal::unix::SignalKind;
25use tower_http::trace::TraceLayer;
26use tracing_subscriber::{
27 Layer, filter::EnvFilter, fmt::format::JsonFields, util::SubscriberInitExt,
28};
29use util::ResultExt as _;
30
31const VERSION: &str = env!("CARGO_PKG_VERSION");
32const REVISION: Option<&'static str> = option_env!("GITHUB_SHA");
33
34#[expect(clippy::result_large_err)]
35#[tokio::main]
36async fn main() -> Result<()> {
37 if let Err(error) = env::load_dotenv() {
38 eprintln!(
39 "error loading .env.toml (this is expected in production): {}",
40 error
41 );
42 }
43
44 let mut args = args().skip(1);
45 match args.next().as_deref() {
46 Some("version") => {
47 println!("collab v{} ({})", VERSION, REVISION.unwrap_or("unknown"));
48 }
49 Some("seed") => {
50 let config = envy::from_env::<Config>().expect("error loading config");
51 let db_options = db::ConnectOptions::new(config.database_url.clone());
52
53 let mut db = Database::new(db_options).await?;
54 db.initialize_notification_kinds().await?;
55
56 collab::seed::seed(&config, &db, false).await?;
57 }
58 Some("serve") => {
59 let mode = match args.next().as_deref() {
60 Some("collab") => ServiceMode::Collab,
61 Some("api") => ServiceMode::Api,
62 Some("all") => ServiceMode::All,
63 _ => {
64 return Err(anyhow!(
65 "usage: collab <version | seed | serve <api|collab|all>>"
66 ))?;
67 }
68 };
69
70 let config = envy::from_env::<Config>().expect("error loading config");
71 init_tracing(&config);
72 init_panic_hook();
73
74 let mut app = Router::new()
75 .route("/", get(handle_root))
76 .route("/healthz", get(handle_liveness_probe))
77 .layer(Extension(mode));
78
79 let listener = TcpListener::bind(format!("0.0.0.0:{}", config.http_port))
80 .expect("failed to bind TCP listener");
81
82 let mut on_shutdown = None;
83
84 if mode.is_collab() || mode.is_api() {
85 setup_app_database(&config).await?;
86
87 let state = AppState::new(config, Executor::Production).await?;
88
89 if mode.is_collab() {
90 let epoch = state
91 .db
92 .create_server(&state.config.zed_environment)
93 .await?;
94 let rpc_server = collab::rpc::Server::new(epoch, state.clone());
95 rpc_server.start().await?;
96
97 app = app.merge(collab::rpc::routes(rpc_server.clone()));
98
99 on_shutdown = Some(Box::new(move || rpc_server.teardown()));
100 }
101
102 if mode.is_api() {
103 fetch_extensions_from_blob_store_periodically(state.clone());
104
105 app = app
106 .merge(collab::api::events::router())
107 .merge(collab::api::extensions::router())
108 }
109
110 app = app.layer(Extension(state.clone()));
111 }
112
113 app = app.layer(
114 TraceLayer::new_for_http()
115 .make_span_with(|request: &Request<_>| {
116 let matched_path = request
117 .extensions()
118 .get::<MatchedPath>()
119 .map(MatchedPath::as_str);
120
121 let geoip_country_code = request
122 .headers()
123 .typed_get::<CloudflareIpCountryHeader>()
124 .map(|header| header.to_string());
125
126 tracing::info_span!(
127 "http_request",
128 method = ?request.method(),
129 matched_path,
130 geoip_country_code,
131 user_id = tracing::field::Empty,
132 login = tracing::field::Empty,
133 authn.jti = tracing::field::Empty,
134 is_staff = tracing::field::Empty
135 )
136 })
137 .on_response(
138 |response: &Response<_>, latency: Duration, _: &tracing::Span| {
139 let duration_ms = latency.as_micros() as f64 / 1000.;
140 tracing::info!(
141 duration_ms,
142 status = response.status().as_u16(),
143 "finished processing request"
144 );
145 },
146 ),
147 );
148
149 #[cfg(unix)]
150 let signal = async move {
151 let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())
152 .expect("failed to listen for interrupt signal");
153 let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())
154 .expect("failed to listen for interrupt signal");
155 let sigterm = sigterm.recv();
156 let sigint = sigint.recv();
157 futures::pin_mut!(sigterm, sigint);
158 futures::future::select(sigterm, sigint).await;
159 };
160
161 #[cfg(windows)]
162 let signal = async move {
163 // todo(windows):
164 // `ctrl_close` does not work well, because tokio's signal handler always returns soon,
165 // but system terminates the application soon after returning CTRL+CLOSE handler.
166 // So we should implement blocking handler to treat CTRL+CLOSE signal.
167 let mut ctrl_break = tokio::signal::windows::ctrl_break()
168 .expect("failed to listen for interrupt signal");
169 let mut ctrl_c = tokio::signal::windows::ctrl_c()
170 .expect("failed to listen for interrupt signal");
171 let ctrl_break = ctrl_break.recv();
172 let ctrl_c = ctrl_c.recv();
173 futures::pin_mut!(ctrl_break, ctrl_c);
174 futures::future::select(ctrl_break, ctrl_c).await;
175 };
176
177 axum::Server::from_tcp(listener)
178 .map_err(|e| anyhow!(e))?
179 .serve(app.into_make_service_with_connect_info::<SocketAddr>())
180 .with_graceful_shutdown(async move {
181 signal.await;
182 tracing::info!("Received interrupt signal");
183
184 if let Some(on_shutdown) = on_shutdown {
185 on_shutdown();
186 }
187 })
188 .await
189 .map_err(|e| anyhow!(e))?;
190 }
191 _ => {
192 Err(anyhow!(
193 "usage: collab <version | migrate | seed | serve <api|collab|llm|all>>"
194 ))?;
195 }
196 }
197 Ok(())
198}
199
200async fn setup_app_database(config: &Config) -> Result<()> {
201 let db_options = db::ConnectOptions::new(config.database_url.clone());
202 let mut db = Database::new(db_options).await?;
203
204 db.initialize_notification_kinds().await?;
205
206 if config.seed_path.is_some() {
207 collab::seed::seed(config, &db, false).await?;
208 }
209
210 Ok(())
211}
212
213async fn handle_root(Extension(mode): Extension<ServiceMode>) -> String {
214 format!("zed:{mode} v{VERSION} ({})", REVISION.unwrap_or("unknown"))
215}
216
217async fn handle_liveness_probe(app_state: Option<Extension<Arc<AppState>>>) -> Result<String> {
218 if let Some(state) = app_state {
219 state.db.get_all_users(0, 1).await?;
220 }
221
222 Ok("ok".to_string())
223}
224
225pub fn init_tracing(config: &Config) -> Option<()> {
226 use std::str::FromStr;
227 use tracing_subscriber::layer::SubscriberExt;
228
229 let filter = EnvFilter::from_str(config.rust_log.as_deref()?).log_err()?;
230
231 tracing_subscriber::registry()
232 .with(if config.log_json.unwrap_or(false) {
233 Box::new(
234 tracing_subscriber::fmt::layer()
235 .fmt_fields(JsonFields::default())
236 .event_format(
237 tracing_subscriber::fmt::format()
238 .json()
239 .flatten_event(true)
240 .with_span_list(false),
241 )
242 .with_filter(filter),
243 ) as Box<dyn Layer<_> + Send + Sync>
244 } else {
245 Box::new(
246 tracing_subscriber::fmt::layer()
247 .event_format(tracing_subscriber::fmt::format().pretty())
248 .with_filter(filter),
249 )
250 })
251 .init();
252
253 None
254}
255
256fn init_panic_hook() {
257 std::panic::set_hook(Box::new(move |panic_info| {
258 let panic_message = match panic_info.payload().downcast_ref::<&'static str>() {
259 Some(message) => *message,
260 None => match panic_info.payload().downcast_ref::<String>() {
261 Some(message) => message.as_str(),
262 None => "Box<Any>",
263 },
264 };
265 let backtrace = std::backtrace::Backtrace::force_capture();
266 let location = panic_info
267 .location()
268 .map(|loc| format!("{}:{}", loc.file(), loc.line()));
269 tracing::error!(panic = true, ?location, %panic_message, %backtrace, "Server Panic");
270 }));
271}