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 for i in 0.. {
35 if var(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_DOMAIN")).is_none() {
36 break;
37 }
38 for suffix in ["CERT_FILE", "KEY_FILE"] {
39 paths.extend(var(&format!("RWS_CONFIG_VIRTUAL_HOST_{i}_{suffix}")).map(PathBuf::from));
40 }
41 }
42 paths.sort();
43 paths.dedup();
44 paths
45}
46
47type Snapshot = Vec<(PathBuf, Option<(u64, SystemTime)>)>;
49
50fn snapshot(paths: Vec<PathBuf>) -> Snapshot {
51 paths
52 .into_iter()
53 .map(|path| {
54 let state = std::fs::metadata(&path).ok().and_then(|md| Some((md.len(), md.modified().ok()?)));
55 (path, state)
56 })
57 .collect()
58}
59
60pub struct Watcher<F: FnMut() -> Vec<PathBuf>> {
62 paths: F,
63 applied: Snapshot,
64 pending: Option<Snapshot>,
65}
66
67impl<F: FnMut() -> Vec<PathBuf>> Watcher<F> {
68 pub fn new(mut paths: F) -> Self {
71 let applied = snapshot(paths());
72 Watcher { paths, applied, pending: None }
73 }
74
75 pub fn poll(&mut self) -> bool {
78 let now = snapshot((self.paths)());
79 if now == self.applied {
80 self.pending = None;
81 return false;
82 }
83 if self.pending.as_ref() == Some(&now) {
84 self.applied = now;
85 self.pending = None;
86 return true;
87 }
88 self.pending = Some(now);
89 false
90 }
91}
92
93pub fn start() {
96 if !enabled() {
97 return;
98 }
99 let spawned = std::thread::Builder::new().name("rws-config-watch".to_string()).spawn(|| {
100 let mut watcher = Watcher::new(watched_paths);
101 loop {
102 std::thread::sleep(POLL_INTERVAL);
103 if watcher.poll() {
104 println!("config watch: a watched file changed; reloading");
105 crate::config_reload::request_reload();
106 }
107 }
108 });
109 if let Err(e) = spawned {
110 eprintln!("config watch: could not start: {e}");
111 }
112}
113
114#[cfg(test)]
115mod tests;