1use anyhow::anyhow;
2use axum::{routing::get, Router};
3use collab::{db, env, AppState, Config, MigrateConfig, Result};
4use db::Database;
5use std::{
6 env::args,
7 net::{SocketAddr, TcpListener},
8 path::Path,
9};
10use tracing_log::LogTracer;
11use tracing_subscriber::{filter::EnvFilter, fmt::format::JsonFields, Layer};
12use util::ResultExt;
13
14const VERSION: &'static str = env!("CARGO_PKG_VERSION");
15
16#[tokio::main]
17async fn main() -> Result<()> {
18 if let Err(error) = env::load_dotenv() {
19 eprintln!(
20 "error loading .env.toml (this is expected in production): {}",
21 error
22 );
23 }
24
25 match args().skip(1).next().as_deref() {
26 Some("version") => {
27 println!("collab v{VERSION}");
28 }
29 Some("migrate") => {
30 let config = envy::from_env::<MigrateConfig>().expect("error loading config");
31 let mut db_options = db::ConnectOptions::new(config.database_url.clone());
32 db_options.max_connections(5);
33 let db = Database::new(db_options).await?;
34
35 let migrations_path = config
36 .migrations_path
37 .as_deref()
38 .unwrap_or_else(|| Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")));
39
40 let migrations = db.migrate(&migrations_path, false).await?;
41 for (migration, duration) in migrations {
42 println!(
43 "Ran {} {} {:?}",
44 migration.version, migration.description, duration
45 );
46 }
47
48 return Ok(());
49 }
50 Some("serve") => {
51 let config = envy::from_env::<Config>().expect("error loading config");
52 init_tracing(&config);
53
54 let state = AppState::new(config).await?;
55 state.db.clear_stale_data().await?;
56
57 let listener = TcpListener::bind(&format!("0.0.0.0:{}", state.config.http_port))
58 .expect("failed to bind TCP listener");
59
60 let rpc_server = collab::rpc::Server::new(state.clone());
61
62 let app = collab::api::routes(rpc_server.clone(), state.clone())
63 .merge(collab::rpc::routes(rpc_server.clone()))
64 .merge(Router::new().route("/", get(handle_root)));
65
66 axum::Server::from_tcp(listener)?
67 .serve(app.into_make_service_with_connect_info::<SocketAddr>())
68 .await?;
69 }
70 _ => {
71 Err(anyhow!("usage: collab <version | migrate | serve>"))?;
72 }
73 }
74 Ok(())
75}
76
77async fn handle_root() -> String {
78 format!("collab v{VERSION}")
79}
80
81pub fn init_tracing(config: &Config) -> Option<()> {
82 use std::str::FromStr;
83 use tracing_subscriber::layer::SubscriberExt;
84 let rust_log = config.rust_log.clone()?;
85
86 LogTracer::init().log_err()?;
87
88 let subscriber = tracing_subscriber::Registry::default()
89 .with(if config.log_json.unwrap_or(false) {
90 Box::new(
91 tracing_subscriber::fmt::layer()
92 .fmt_fields(JsonFields::default())
93 .event_format(
94 tracing_subscriber::fmt::format()
95 .json()
96 .flatten_event(true)
97 .with_span_list(true),
98 ),
99 ) as Box<dyn Layer<_> + Send + Sync>
100 } else {
101 Box::new(
102 tracing_subscriber::fmt::layer()
103 .event_format(tracing_subscriber::fmt::format().pretty()),
104 )
105 })
106 .with(EnvFilter::from_str(rust_log.as_str()).log_err()?);
107
108 tracing::subscriber::set_global_default(subscriber).unwrap();
109
110 None
111}