rust_web_server/config_watch/
mod.rs1use std::path::PathBuf;
13use std::time::{Duration, SystemTime};
14
15pub const RWS_CONFIG_WATCH: &str = "RWS_CONFIG_WATCH";
17
18pub const POLL_INTERVAL: Duration = Duration::from_secs(1);
20
21pub fn enabled() -> bool {
23 std::env::var(RWS_CONFIG_WATCH).is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "true" | "1" | "yes" | "on"))
24}
25
26pub fn watched_paths() -> Vec<PathBuf> {
29 let var = |key: &str| std::env::var(key).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
30 let mut paths = vec![PathBuf::from(var("RWS_CONFIG_FILE").unwrap_or_else(|| "rws.config.toml".to_string()))];
31 for key in [crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE, crate::entry_point::Config::RWS_CONFIG_TLS_KEY_FILE] {
32 paths.extend(var(key).map(PathBuf::from));
33 }
34 if let Some(files) = var("RWS_CONFIG_TLS_CLIENT_CRL_FILE") {
36 paths.extend(files.split(',').map(str::trim).filter(|p| !p.is_empty()).map(PathBuf::from));
37 }
38 for i in 0.. {
39 if var(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_DOMAIN")).is_none() {
40 break;
41 }
42 for suffix in ["CERT_FILE", "KEY_FILE"] {
43 paths.extend(var(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_{suffix}")).map(PathBuf::from));
44 }
45 }
46 paths.sort();
47 paths.dedup();
48 paths
49}
50
51type Snapshot = Vec<(PathBuf, Option<(u64, SystemTime)>)>;
53
54fn snapshot(paths: Vec<PathBuf>) -> Snapshot {
55 paths
56 .into_iter()
57 .map(|path| {
58 let state = std::fs::metadata(&path).ok().and_then(|md| Some((md.len(), md.modified().ok()?)));
59 (path, state)
60 })
61 .collect()
62}
63
64pub struct Watcher<F: FnMut() -> Vec<PathBuf>> {
66 paths: F,
67 applied: Snapshot,
68 pending: Option<Snapshot>,
69}
70
71impl<F: FnMut() -> Vec<PathBuf>> Watcher<F> {
72 pub fn new(mut paths: F) -> Self {
75 let applied = snapshot(paths());
76 Watcher { paths, applied, pending: None }
77 }
78
79 pub fn poll(&mut self) -> bool {
82 let now = snapshot((self.paths)());
83 if now == self.applied {
84 self.pending = None;
85 return false;
86 }
87 if self.pending.as_ref() == Some(&now) {
88 self.applied = now;
89 self.pending = None;
90 return true;
91 }
92 self.pending = Some(now);
93 false
94 }
95}
96
97pub fn start() {
100 if !enabled() {
101 return;
102 }
103 let spawned = std::thread::Builder::new().name("rws-config-watch".to_string()).spawn(|| {
104 let mut watcher = Watcher::new(watched_paths);
105 loop {
106 std::thread::sleep(POLL_INTERVAL);
107 if watcher.poll() {
108 println!("config watch: a watched file changed; reloading");
109 crate::config_reload::request_reload();
110 }
111 }
112 });
113 if let Err(e) = spawned {
114 eprintln!("config watch: could not start: {e}");
115 }
116}
117
118#[cfg(test)]
119mod tests;