summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 97ed1116d9cf193710cffae7c3a088b0f6f09839 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::{fs::File, path::PathBuf};
use tracing::level_filters::LevelFilter;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

use statsrv::service::Services;

#[cfg(not(debug_assertions))]
const DEFAULT_CONFIG: &str = "/etc/statsrv.toml";
#[cfg(debug_assertions)]
const DEFAULT_CONFIG: &str = "./config.toml";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::registry()
        .with(
            EnvFilter::builder()
                .with_default_directive(LevelFilter::INFO.into())
                .from_env_lossy(),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();

    let config = match Config::parse() {
        Ok(c) => c,
        Err(err) => {
            tracing::debug!("Failed to read config file: `{err}`");
            tracing::debug!("Using default config values");
            Default::default()
        }
    };

    let router = statsrv::router(config.root).with_state(config.services);

    let listener = tokio::net::TcpListener::bind(config.address).await.unwrap();
    tracing::info!("listening on {}", listener.local_addr().unwrap());

    axum::serve(listener, router).await.map_err(Into::into)
}

#[derive(Debug, Clone, serde::Deserialize)]
#[serde(default)]
pub struct Config {
    pub root: PathBuf,
    pub address: String,
    pub services: Services,
}

impl Config {
    fn parse() -> Result<Self, Box<dyn std::error::Error>> {
        let config_path = std::env::args().nth(1).unwrap_or_else(|| {
            tracing::debug!("Falling back to default config location");
            DEFAULT_CONFIG.to_string()
        });

        let config_file = File::open(&config_path)?;
        let config_toml = std::io::read_to_string(config_file)?;
        toml::from_str(&config_toml).map_err(Into::into)
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            root: PathBuf::from("./"),
            address: String::from("127.0.0.1:8080"),
            services: Services::new(Default::default()),
        }
    }
}