1use anyhow::anyhow;
2use axum::{routing::get, Extension, Router};
3use collab::{
4 api::fetch_extensions_from_blob_store_periodically, db, env, executor::Executor, AppState,
5 Config, MigrateConfig, Result,
6};
7use db::Database;
8use std::{
9 env::args,
10 net::{SocketAddr, TcpListener},
11 path::Path,
12 sync::Arc,
13};
14use tokio::signal::unix::SignalKind;
15use tracing_log::LogTracer;
16use tracing_subscriber::{filter::EnvFilter, fmt::format::JsonFields, Layer};
17use util::ResultExt;
18
19const VERSION: &'static str = env!("CARGO_PKG_VERSION");
20const REVISION: Option<&'static str> = option_env!("GITHUB_SHA");
21
22#[tokio::main]
23async fn main() -> Result<()> {
24 if let Err(error) = env::load_dotenv() {
25 eprintln!(
26 "error loading .env.toml (this is expected in production): {}",
27 error
28 );
29 }
30
31 match args().skip(1).next().as_deref() {
32 Some("version") => {
33 println!("collab v{} ({})", VERSION, REVISION.unwrap_or("unknown"));
34 }
35 Some("migrate") => {
36 run_migrations().await?;
37 }
38 Some("serve") => {
39 let config = envy::from_env::<Config>().expect("error loading config");
40 init_tracing(&config);
41
42 run_migrations().await?;
43
44 let state = AppState::new(config).await?;
45
46 let listener = TcpListener::bind(&format!("0.0.0.0:{}", state.config.http_port))
47 .expect("failed to bind TCP listener");
48
49 let epoch = state
50 .db
51 .create_server(&state.config.zed_environment)
52 .await?;
53 let rpc_server = collab::rpc::Server::new(epoch, state.clone(), Executor::Production);
54 rpc_server.start().await?;
55
56 fetch_extensions_from_blob_store_periodically(state.clone(), Executor::Production);
57
58 let app = collab::api::routes(rpc_server.clone(), state.clone())
59 .merge(collab::rpc::routes(rpc_server.clone()))
60 .merge(
61 Router::new()
62 .route("/", get(handle_root))
63 .route("/healthz", get(handle_liveness_probe))
64 .layer(Extension(state.clone())),
65 );
66
67 axum::Server::from_tcp(listener)?
68 .serve(app.into_make_service_with_connect_info::<SocketAddr>())
69 .with_graceful_shutdown(async move {
70 let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())
71 .expect("failed to listen for interrupt signal");
72 let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())
73 .expect("failed to listen for interrupt signal");
74 let sigterm = sigterm.recv();
75 let sigint = sigint.recv();
76 futures::pin_mut!(sigterm, sigint);
77 futures::future::select(sigterm, sigint).await;
78 tracing::info!("Received interrupt signal");
79 rpc_server.teardown();
80 })
81 .await?;
82 }
83 _ => {
84 Err(anyhow!("usage: collab <version | migrate | serve>"))?;
85 }
86 }
87 Ok(())
88}
89
90async fn run_migrations() -> Result<()> {
91 let config = envy::from_env::<MigrateConfig>().expect("error loading config");
92 let db_options = db::ConnectOptions::new(config.database_url.clone());
93 let db = Database::new(db_options, Executor::Production).await?;
94
95 let migrations_path = config
96 .migrations_path
97 .as_deref()
98 .unwrap_or_else(|| Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")));
99
100 let migrations = db.migrate(&migrations_path, false).await?;
101 for (migration, duration) in migrations {
102 log::info!(
103 "Migrated {} {} {:?}",
104 migration.version,
105 migration.description,
106 duration
107 );
108 }
109
110 return Ok(());
111}
112
113async fn handle_root() -> String {
114 format!("collab v{} ({})", VERSION, REVISION.unwrap_or("unknown"))
115}
116
117async fn handle_liveness_probe(Extension(state): Extension<Arc<AppState>>) -> Result<String> {
118 state.db.get_all_users(0, 1).await?;
119 Ok("ok".to_string())
120}
121
122pub fn init_tracing(config: &Config) -> Option<()> {
123 use std::str::FromStr;
124 use tracing_subscriber::layer::SubscriberExt;
125 let rust_log = config.rust_log.clone()?;
126
127 LogTracer::init().log_err()?;
128
129 let subscriber = tracing_subscriber::Registry::default()
130 .with(if config.log_json.unwrap_or(false) {
131 Box::new(
132 tracing_subscriber::fmt::layer()
133 .fmt_fields(JsonFields::default())
134 .event_format(
135 tracing_subscriber::fmt::format()
136 .json()
137 .flatten_event(true)
138 .with_span_list(true),
139 ),
140 ) as Box<dyn Layer<_> + Send + Sync>
141 } else {
142 Box::new(
143 tracing_subscriber::fmt::layer()
144 .event_format(tracing_subscriber::fmt::format().pretty()),
145 )
146 })
147 .with(EnvFilter::from_str(rust_log.as_str()).log_err()?);
148
149 tracing::subscriber::set_global_default(subscriber).unwrap();
150
151 None
152}