summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 99af338b4d2808a49346b64e35ac36d27f15e04f (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
70
71
72
73
74
75
76
77
78
79
use std::{collections::HashMap, fs::File, path::PathBuf, sync::Arc};
use tower_http::services::ServeDir;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

use statsrv::service::Service;

#[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 state = config
        .services
        .into_iter()
        .map(|(name, service)| (name, service.into()))
        .collect();

    let router = statsrv::router()
        .with_state(Arc::new(state))
        .nest_service("/", ServeDir::new(config.root))
        .layer(tower_http::trace::TraceLayer::new_for_http());

    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: HashMap<String, Service>,
}

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: Default::default(),
        }
    }
}