Skip to main content

rust_web_server/traffic/
config.rs

1//! `[traffic]` settings (`RWS_CONFIG_TRAFFIC_*`).
2
3use std::path::PathBuf;
4
5pub const RWS_CONFIG_TRAFFIC_ENABLED: &str = "RWS_CONFIG_TRAFFIC_ENABLED";
6pub const RWS_CONFIG_TRAFFIC_RETENTION_DAYS: &str = "RWS_CONFIG_TRAFFIC_RETENTION_DAYS";
7pub const RWS_CONFIG_TRAFFIC_PERSIST: &str = "RWS_CONFIG_TRAFFIC_PERSIST";
8pub const RWS_CONFIG_TRAFFIC_EXCLUDE: &str = "RWS_CONFIG_TRAFFIC_EXCLUDE";
9
10fn read(key: &str) -> String {
11    std::env::var(key).unwrap_or_default().trim().to_string()
12}
13
14/// `enabled`: `Some(false)` turns counting off even with the admin API on;
15/// `None` when unset.
16pub fn enabled_setting() -> Option<bool> {
17    match read(RWS_CONFIG_TRAFFIC_ENABLED).to_ascii_lowercase().as_str() {
18        "" => None,
19        "false" | "0" | "no" | "off" => Some(false),
20        _ => Some(true),
21    }
22}
23
24/// `retention_days`: 1–90, default 30.
25pub fn retention_days() -> u64 {
26    read(RWS_CONFIG_TRAFFIC_RETENTION_DAYS).parse::<u64>().ok().filter(|d| *d >= 1).map_or(30, |d| d.min(90))
27}
28
29/// `exclude`: exact paths not counted (comma-separated); default the
30/// health, readiness and metrics endpoints.
31pub fn exclude() -> Vec<String> {
32    let value = std::env::var(RWS_CONFIG_TRAFFIC_EXCLUDE);
33    match value {
34        Ok(v) => v.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect(),
35        Err(_) => ["/healthz", "/readyz", "/metrics"].iter().map(|p| p.to_string()).collect(),
36    }
37}
38
39/// `persist`: the file the counts are saved to. Unset: `traffic.json` next
40/// to the certificate (the ACME certificate's directory, else the TLS
41/// certificate's) — the state directory; without either, nothing is
42/// saved. `"off"`: not saved.
43pub fn persist_path() -> Option<PathBuf> {
44    let value = read(RWS_CONFIG_TRAFFIC_PERSIST);
45    if value.eq_ignore_ascii_case("off") {
46        return None;
47    }
48    if !value.is_empty() {
49        return Some(PathBuf::from(value));
50    }
51    [crate::entry_point::Config::RWS_CONFIG_ACME_CERT_PATH, crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE]
52        .iter()
53        .map(|key| read(key))
54        .find(|path| !path.is_empty())
55        .and_then(|cert| PathBuf::from(cert).parent().map(|dir| dir.join("traffic.json")))
56}