http_srv/server/
config.rs

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#![allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]

use std::{
    env, fs,
    path::{Path, PathBuf},
    process,
    str::FromStr,
    time::Duration,
};

use jsonrs::Json;
use pool::PoolConfig;

use crate::{
    log::{self},
    log_info, log_warn, Result,
};

#[derive(Clone, Debug)]
pub struct ServerConfig {
    pub port: u16,
    pub pool_conf: PoolConfig,
    pub keep_alive_timeout: Duration,
    pub keep_alive_requests: u16,
    pub log_file: Option<String>,
}

#[cfg(not(test))]
fn get_default_conf_file() -> Option<PathBuf> {
    if let Ok(path) = env::var("XDG_CONFIG_HOME") {
        let mut p = PathBuf::new();
        p.push(path);
        p.push("http-srv");
        p.push("config.json");
        Some(p)
    } else if let Ok(path) = env::var("HOME") {
        let mut p = PathBuf::new();
        p.push(path);
        p.push(".config");
        p.push("http-srv");
        p.push("config.json");
        Some(p)
    } else {
        None
    }
}

#[cfg(test)]
fn get_default_conf_file() -> Option<PathBuf> {
    None
}

/// [`crate::HttpServer`] configuration
///
/// # Example
/// ```
/// use http_srv::server::ServerConfig;
/// use pool::PoolConfig;
///
/// let pool_conf = PoolConfig::builder()
///                 .n_workers(120_u16)
///                 .build().unwrap();
/// let conf =
/// ServerConfig::default()
///     .port(8080)
///     .pool_config(pool_conf);
/// ```
impl ServerConfig {
    /// Parse the configuration from the command line args
    pub fn parse<S: AsRef<str>>(args: &[S]) -> Result<Self> {
        let mut conf = Self::default();

        let mut conf_file = get_default_conf_file();

        /* Parse the --config-file before the rest */
        let mut first_pass = args.iter();
        while let Some(arg) = first_pass.next() {
            if arg.as_ref() == "--config-file" {
                if let Some(fname) = first_pass.next() {
                    let filename = PathBuf::from(fname.as_ref());
                    if filename.exists() {
                        conf_file = Some(filename);
                    } else {
                        log_warn!(
                            "Config path: {} doesn't exist",
                            filename.as_os_str().to_str().unwrap_or("[??]")
                        );
                    }
                }
            }
        }

        if let Some(cfile) = conf_file {
            conf.parse_conf_file(&cfile)?;
        }

        let mut args = args.iter();
        while let Some(arg) = args.next() {
            macro_rules! parse_next {
                () => {
                    args.next_parse().ok_or_else(|| {
                        format!("Missing or incorrect argument for \"{}\"", arg.as_ref())
                    })?
                };
                (as $t:ty) => {{
                    let _next: $t = parse_next!();
                    _next
                }};
            }

            let mut pool_conf_builder = PoolConfig::builder();

            match arg.as_ref() {
                "-p" | "--port" => conf.port = parse_next!(),
                "-n" | "-n-workers" => {
                    pool_conf_builder.n_workers(parse_next!(as u16));
                }
                "-d" | "--dir" => {
                    let path: String = parse_next!();
                    env::set_current_dir(Path::new(&path))?;
                }
                "-k" | "--keep-alive" => {
                    let timeout = parse_next!();
                    conf.keep_alive_timeout = Duration::from_secs_f32(timeout);
                }
                "-r" | "--keep-alive-requests" => conf.keep_alive_requests = parse_next!(),
                "-l" | "--log" => conf.log_file = Some(parse_next!()),
                "--log-level" => {
                    let n: u8 = parse_next!();
                    log::set_level(n.try_into()?);
                }
                "--config-file" => {}
                "-h" | "--help" => help(),
                unknown => return Err(format!("Unknow argument: {unknown}").into()),
            }
        }

        log_info!("{conf:#?}");
        Ok(conf)
    }
    fn parse_conf_file(&mut self, conf_file: &Path) -> crate::Result<()> {
        if !conf_file.exists() {
            return Ok(());
        }
        let conf_str = conf_file.as_os_str().to_str().unwrap_or("");
        let f = fs::read_to_string(conf_file).unwrap_or_else(|err| {
            eprintln!("Error reading config file \"{conf_str}\": {err}");
            std::process::exit(1);
        });
        let json = Json::deserialize(&f).unwrap_or_else(|err| {
            eprintln!("Error parsing config file: {err}");
            std::process::exit(1);
        });
        log_info!("Parsing config file: {conf_str}");
        let Json::Object(obj) = json else {
            return Err("Expected json object".into());
        };
        for (k, v) in obj {
            macro_rules! num {
                () => {
                    num!(v)
                };
                ($v:ident) => {
                    $v.number().ok_or_else(|| {
                        format!("Parsing config file ({conf_str}): Expected number for \"{k}\"")
                    })?
                };
                ($v:ident as $t:ty) => {{
                    let _n = num!($v);
                    _n as $t
                }};
            }
            macro_rules! string {
                () => {
                    v.string()
                        .ok_or_else(|| {
                            format!("Parsing config file ({conf_str}): Expected string for \"{k}\"")
                        })?
                        .to_string()
                };
            }
            macro_rules! obj {
                () => {
                    v.object().ok_or_else(|| {
                        format!("Parsing config file ({conf_str}): Expected object for \"{k}\"")
                    })?
                };
            }

            match &*k {
                "port" => self.port = num!() as u16,
                "root_dir" => {
                    let path: String = string!();
                    let path = path.replacen(
                        '~',
                        env::var("HOME").as_ref().map(String::as_str).unwrap_or("~"),
                        1,
                    );
                    env::set_current_dir(Path::new(&path))?;
                }
                "keep_alive_timeout" => self.keep_alive_timeout = Duration::from_secs_f64(num!()),
                "keep_alive_requests" => self.keep_alive_requests = num!() as u16,
                "log_file" => self.log_file = Some(string!()),
                "log_level" => {
                    let n = num!(v as u8);
                    log::set_level(n.try_into()?);
                }
                "pool_config" => {
                    for (k, v) in obj!() {
                        match &**k {
                            "n_workers" => self.pool_conf.n_workers = num!(v as u16),
                            "pending_buffer_size" => {
                                let n = v.number().map(|n| n as u16);
                                self.pool_conf.incoming_buf_size = n;
                            }
                            _ => log_warn!(
                                "Parsing config file ({conf_str}): Unexpected key: \"{k}\""
                            ),
                        }
                    }
                }
                _ => log_warn!("Parsing config file ({conf_str}): Unexpected key: \"{k}\""),
            };
        }
        Ok(())
    }
    #[inline]
    #[must_use]
    pub fn pool_config(mut self, conf: PoolConfig) -> Self {
        self.pool_conf = conf;
        self
    }
    #[inline]
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }
    #[inline]
    #[must_use]
    pub fn keep_alive_timeout(mut self, timeout: Duration) -> Self {
        self.keep_alive_timeout = timeout;
        self
    }
    #[inline]
    #[must_use]
    pub fn keep_alive_requests(mut self, n: u16) -> Self {
        self.keep_alive_requests = n;
        self
    }
}

fn help() -> ! {
    println!(
        "\
USAGE: http-srv [-p <port>] [-n <n-workers>] [-d <working-dir>]
PARAMETERS:
    -p, --port <port>    TCP Port to listen for requests
    -n, --n-workers <n>  Number of concurrent workers
    -d, --dir <working-dir>  Root directory of the server
    -k, --keep-alive <sec>   Keep alive seconds
    -r, --keep-alive-requests <num>  Keep alive max requests
    -l, --log <file>   Set log file
    --log-level <n>    Set log level
    -h, --help  Display this help message
    --conf <file> Use the given config file instead of the default one
EXAMPLES:
  http-srv -p 8080 -d /var/html
  http-srv -d ~/desktop -n 1024 --keep-alive 120
  http-srv --log /var/log/http-srv.log"
    );
    process::exit(0);
}

trait ParseIterator {
    fn next_parse<T: FromStr>(&mut self) -> Option<T>;
}

impl<I, R: AsRef<str>> ParseIterator for I
where
    I: Iterator<Item = R>,
{
    fn next_parse<T: FromStr>(&mut self) -> Option<T> {
        self.next()?.as_ref().parse().ok()
    }
}

impl Default for ServerConfig {
    /// Default configuration
    ///
    /// - Port: 80
    /// - NÂș Workers: 1024
    /// - Keep Alive Timeout: 0s (Disabled)
    /// - Keep Alove Requests: 10000
    #[inline]
    fn default() -> Self {
        Self {
            port: 80,
            pool_conf: PoolConfig::default(),
            keep_alive_timeout: Duration::from_secs(0),
            keep_alive_requests: 10000,
            log_file: None,
        }
    }
}

#[cfg(test)]
mod test {
    #![allow(clippy::unwrap_used)]

    use super::ServerConfig;

    #[test]
    fn valid_args() {
        let conf = vec!["-p".to_string(), "80".to_string()];
        ServerConfig::parse(&conf).unwrap();
    }

    macro_rules! expect_err {
        ($conf:expr , $msg:literal) => {
            match ServerConfig::parse(&$conf) {
                Ok(c) => panic!("Didn't panic: {c:#?}"),
                Err(msg) => assert_eq!(msg.get_message(), $msg),
            }
        };
    }

    #[test]
    fn unknown() {
        let conf = vec!["?"];
        expect_err!(conf, "Unknow argument: ?");
    }

    #[test]
    fn missing() {
        let conf = vec!["-n"];
        expect_err!(conf, "Missing or incorrect argument for \"-n\"");
    }

    #[test]
    fn parse_error() {
        let conf = vec!["-p", "abc"];
        expect_err!(conf, "Missing or incorrect argument for \"-p\"");
    }
}