main.rs

  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                        .merge(collab::api::events::router())
 65                        .layer(Extension(state.clone())),
 66                );
 67
 68            axum::Server::from_tcp(listener)?
 69                .serve(app.into_make_service_with_connect_info::<SocketAddr>())
 70                .with_graceful_shutdown(async move {
 71                    let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())
 72                        .expect("failed to listen for interrupt signal");
 73                    let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())
 74                        .expect("failed to listen for interrupt signal");
 75                    let sigterm = sigterm.recv();
 76                    let sigint = sigint.recv();
 77                    futures::pin_mut!(sigterm, sigint);
 78                    futures::future::select(sigterm, sigint).await;
 79                    tracing::info!("Received interrupt signal");
 80                    rpc_server.teardown();
 81                })
 82                .await?;
 83        }
 84        _ => {
 85            Err(anyhow!("usage: collab <version | migrate | serve>"))?;
 86        }
 87    }
 88    Ok(())
 89}
 90
 91async fn run_migrations() -> Result<()> {
 92    let config = envy::from_env::<MigrateConfig>().expect("error loading config");
 93    let db_options = db::ConnectOptions::new(config.database_url.clone());
 94    let db = Database::new(db_options, Executor::Production).await?;
 95
 96    let migrations_path = config
 97        .migrations_path
 98        .as_deref()
 99        .unwrap_or_else(|| Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")));
100
101    let migrations = db.migrate(&migrations_path, false).await?;
102    for (migration, duration) in migrations {
103        log::info!(
104            "Migrated {} {} {:?}",
105            migration.version,
106            migration.description,
107            duration
108        );
109    }
110
111    return Ok(());
112}
113
114async fn handle_root() -> String {
115    format!("collab v{} ({})", VERSION, REVISION.unwrap_or("unknown"))
116}
117
118async fn handle_liveness_probe(Extension(state): Extension<Arc<AppState>>) -> Result<String> {
119    state.db.get_all_users(0, 1).await?;
120    Ok("ok".to_string())
121}
122
123pub fn init_tracing(config: &Config) -> Option<()> {
124    use std::str::FromStr;
125    use tracing_subscriber::layer::SubscriberExt;
126    let rust_log = config.rust_log.clone()?;
127
128    LogTracer::init().log_err()?;
129
130    let subscriber = tracing_subscriber::Registry::default()
131        .with(if config.log_json.unwrap_or(false) {
132            Box::new(
133                tracing_subscriber::fmt::layer()
134                    .fmt_fields(JsonFields::default())
135                    .event_format(
136                        tracing_subscriber::fmt::format()
137                            .json()
138                            .flatten_event(true)
139                            .with_span_list(true),
140                    ),
141            ) as Box<dyn Layer<_> + Send + Sync>
142        } else {
143            Box::new(
144                tracing_subscriber::fmt::layer()
145                    .event_format(tracing_subscriber::fmt::format().pretty()),
146            )
147        })
148        .with(EnvFilter::from_str(rust_log.as_str()).log_err()?);
149
150    tracing::subscriber::set_global_default(subscriber).unwrap();
151
152    None
153}