aboutsummaryrefslogtreecommitdiff
path: root/src/config.rs
blob: c02af52cae53a965aaae31c5344eb49b550da581 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use anyhow::Context;
use serde::{
    de::{value, Error, SeqAccess, Visitor},
    Deserialize, Deserializer, Serialize,
};
use std::{collections::HashMap, fmt, fs::read_to_string, net::SocketAddr, path::PathBuf};

#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    pub http: Option<HttpConfig>,
    pub https: Option<HttpsConfig>,
    #[serde(default)]
    pub limits: Limits,
    #[serde(default)]
    pub hosts: HashMap<String, HostConfig>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Limits {
    pub max_incoming_connections: usize,
    pub max_outgoing_connections: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HttpConfig {
    #[serde(deserialize_with = "string_or_seq")]
    pub bind: Vec<SocketAddr>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HttpsConfig {
    pub bind: Vec<SocketAddr>,
    pub tls_cert: PathBuf,
    pub tls_key: PathBuf,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HostConfig {
    Backend { backend: SocketAddr },
    Files { files: FileserverConfig },
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FileserverConfig {
    pub root: PathBuf,
    #[serde(default)]
    pub index: bool,
}

// fall back to expecting a single string and putting that in a 1-length vector
fn string_or_seq<'de, D>(des: D) -> Result<Vec<SocketAddr>, D::Error>
where
    D: Deserializer<'de>,
{
    struct StringOrList;
    impl<'de> Visitor<'de> for StringOrList {
        type Value = Vec<SocketAddr>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("sequence or list")
        }

        fn visit_str<E>(self, val: &str) -> Result<Vec<SocketAddr>, E>
        where
            E: Error,
        {
            let addr = SocketAddr::deserialize(value::StrDeserializer::new(val))?;
            Ok(vec![addr])
        }

        fn visit_seq<A>(self, val: A) -> Result<Vec<SocketAddr>, A::Error>
        where
            A: SeqAccess<'de>,
        {
            Vec::<SocketAddr>::deserialize(value::SeqAccessDeserializer::new(val))
        }
    }

    des.deserialize_any(StringOrList)
}

impl Config {
    pub fn load(path: &str) -> anyhow::Result<Config> {
        let raw = read_to_string(path).context("reading config file")?;
        let config: Config = serde_yaml::from_str(&raw).context("parsing config")?;
        Ok(config)
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_incoming_connections: 1024,
            max_outgoing_connections: 2048,
        }
    }
}