1mod api;
2mod auth;
3mod db;
4mod env;
5mod rpc;
6
7#[cfg(test)]
8mod db_tests;
9#[cfg(test)]
10mod integration_tests;
11
12use axum::{body::Body, Router};
13use collab::{Error, Result};
14use db::{Db, PostgresDb};
15use serde::Deserialize;
16use std::{
17 net::{SocketAddr, TcpListener},
18 sync::Arc,
19 time::Duration,
20};
21use tracing_log::LogTracer;
22use tracing_subscriber::{filter::EnvFilter, fmt::format::JsonFields, Layer};
23use util::ResultExt;
24
25#[derive(Default, Deserialize)]
26pub struct Config {
27 pub http_port: u16,
28 pub database_url: String,
29 pub api_token: String,
30 pub invite_link_prefix: String,
31 pub rust_log: Option<String>,
32 pub log_json: Option<bool>,
33}
34
35pub struct AppState {
36 db: Arc<dyn Db>,
37 config: Config,
38}
39
40impl AppState {
41 async fn new(config: Config) -> Result<Arc<Self>> {
42 let db = PostgresDb::new(&config.database_url, 5).await?;
43 let this = Self {
44 db: Arc::new(db),
45 config,
46 };
47 Ok(Arc::new(this))
48 }
49}
50
51#[tokio::main]
52async fn main() -> Result<()> {
53 if let Err(error) = env::load_dotenv() {
54 eprintln!(
55 "error loading .env.toml (this is expected in production): {}",
56 error
57 );
58 }
59
60 let config = envy::from_env::<Config>().expect("error loading config");
61 init_tracing(&config);
62 let state = AppState::new(config).await?;
63
64 let listener = TcpListener::bind(&format!("0.0.0.0:{}", state.config.http_port))
65 .expect("failed to bind TCP listener");
66 let rpc_server = rpc::Server::new(state.clone(), None);
67
68 rpc_server.start_recording_project_activity(Duration::from_secs(5 * 60), rpc::RealExecutor);
69
70 let app = Router::<Body>::new()
71 .merge(api::routes(&rpc_server, state.clone()))
72 .merge(rpc::routes(rpc_server));
73
74 axum::Server::from_tcp(listener)?
75 .serve(app.into_make_service_with_connect_info::<SocketAddr>())
76 .await?;
77
78 Ok(())
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}