rust_web_server/config_reload/mod.rs
1//! Hot configuration reload.
2//!
3//! Re-reads `rws.config.toml` without restarting the server. Non-binding
4//! settings — those that would require a new TCP socket (IP, port,
5//! thread count) or a new TLS acceptor (cert/key paths) — are logged as
6//! ignored. All other settings take effect on the next incoming request.
7//!
8//! # Triggering a reload
9//!
10//! * **Unix signal**: send `SIGHUP` to the server process.
11//! ```bash
12//! kill -HUP $(pidof rws)
13//! ```
14//! * **HTTP endpoint**: `POST /admin/config/reload` (no body required).
15//!
16//! # What is hot-reloadable
17//!
18//! | Setting | Env var |
19//! |---------|---------|
20//! | CORS — all fields | `RWS_CONFIG_CORS_*` |
21//! | Rate-limit thresholds | `RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS`, `RWS_CONFIG_RATE_LIMIT_WINDOW_SECS` |
22//! | Log format | `RWS_CONFIG_LOG_FORMAT` |
23//! | Request allocation size | `RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES` |
24//!
25//! # What is NOT hot-reloadable (requires restart)
26//!
27//! | Setting | Why |
28//! |---------|-----|
29//! | IP / Port | Bound socket cannot be moved |
30//! | Thread count | Thread pool is fixed at startup |
31//! | TLS cert / key | TLS acceptor is built once at startup |
32
33#[cfg(test)]
34mod tests;
35
36use std::sync::{OnceLock, RwLock};
37use std::sync::atomic::AtomicBool;
38#[cfg(all(unix, feature = "http1"))]
39use std::sync::atomic::Ordering;
40
41use crate::entry_point::Config;
42use crate::entry_point::config_file::override_environment_variables_from_config;
43use crate::rate_limit;
44
45/// Global flag set by the SIGHUP signal handler.
46///
47/// The accept loop checks this between connections and calls [`reload`] when
48/// it is `true`, then resets it to `false`.
49pub static RELOAD_REQUESTED: AtomicBool = AtomicBool::new(false);
50
51/// Snapshot of all hot-reloadable configuration values at a point in time.
52///
53/// Obtain the current snapshot with [`current()`]. The snapshot is updated
54/// atomically every time [`reload()`] completes — no partial reads are possible.
55#[derive(Debug, Clone)]
56pub struct ConfigSnapshot {
57 /// `RWS_CONFIG_CORS_ALLOW_ALL`
58 pub cors_allow_all: bool,
59 /// `RWS_CONFIG_CORS_ALLOW_ORIGINS`
60 pub cors_allow_origins: String,
61 /// `RWS_CONFIG_CORS_ALLOW_CREDENTIALS`
62 pub cors_allow_credentials: String,
63 /// `RWS_CONFIG_CORS_ALLOW_METHODS`
64 pub cors_allow_methods: String,
65 /// `RWS_CONFIG_CORS_ALLOW_HEADERS`
66 pub cors_allow_headers: String,
67 /// `RWS_CONFIG_CORS_EXPOSE_HEADERS`
68 pub cors_expose_headers: String,
69 /// `RWS_CONFIG_CORS_MAX_AGE`
70 pub cors_max_age: String,
71 /// `RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS`
72 pub rate_limit_max_requests: u32,
73 /// `RWS_CONFIG_RATE_LIMIT_WINDOW_SECS`
74 pub rate_limit_window_secs: u64,
75 /// `RWS_CONFIG_LOG_FORMAT`
76 pub log_format: String,
77 /// `RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES`
78 pub request_allocation_size: i64,
79}
80
81impl ConfigSnapshot {
82 fn from_env() -> Self {
83 let read = |key: &str| std::env::var(key).unwrap_or_default();
84 Self {
85 cors_allow_all: read(Config::RWS_CONFIG_CORS_ALLOW_ALL)
86 .eq_ignore_ascii_case("true"),
87 cors_allow_origins: read(Config::RWS_CONFIG_CORS_ALLOW_ORIGINS),
88 cors_allow_credentials: read(Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS),
89 cors_allow_methods: read(Config::RWS_CONFIG_CORS_ALLOW_METHODS),
90 cors_allow_headers: read(Config::RWS_CONFIG_CORS_ALLOW_HEADERS),
91 cors_expose_headers: read(Config::RWS_CONFIG_CORS_EXPOSE_HEADERS),
92 cors_max_age: read(Config::RWS_CONFIG_CORS_MAX_AGE),
93 rate_limit_max_requests: std::env::var("RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS")
94 .ok()
95 .and_then(|v| v.parse().ok())
96 .unwrap_or(1000),
97 rate_limit_window_secs: std::env::var("RWS_CONFIG_RATE_LIMIT_WINDOW_SECS")
98 .ok()
99 .and_then(|v| v.parse().ok())
100 .unwrap_or(60),
101 log_format: read(Config::RWS_CONFIG_LOG_FORMAT),
102 request_allocation_size: std::env::var(
103 Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES,
104 )
105 .ok()
106 .and_then(|v| v.parse().ok())
107 .unwrap_or(*Config::RWS_DEFAULT_REQUEST_ALLOCATION_SIZE_IN_BYTES),
108 }
109 }
110}
111
112static SNAPSHOT: OnceLock<RwLock<ConfigSnapshot>> = OnceLock::new();
113
114fn global() -> &'static RwLock<ConfigSnapshot> {
115 SNAPSHOT.get_or_init(|| RwLock::new(ConfigSnapshot::from_env()))
116}
117
118/// Returns a clone of the current hot-reloadable configuration snapshot.
119///
120/// This takes a brief read lock and clones a handful of strings — safe to call
121/// on every request if needed.
122pub fn current() -> ConfigSnapshot {
123 global().read().unwrap().clone()
124}
125
126/// Re-read `rws.config.toml` and apply all hot-reloadable changes in-place.
127///
128/// Called automatically when [`RELOAD_REQUESTED`] is set (SIGHUP on Unix) or
129/// from the `POST /admin/config/reload` handler.
130///
131/// Settings that cannot be changed without a restart (IP, port, thread count,
132/// TLS cert/key) are silently ignored — they are re-parsed from the file but
133/// have no effect until the next process start.
134pub fn reload() {
135 // Re-parse rws.config.toml → updates process env vars for CORS, log format, etc.
136 // Only one thread ever calls this (the signal handler or admin endpoint),
137 // while workers only read env vars, so the single-writer / many-readers
138 // pattern is safe in practice on all supported platforms.
139 override_environment_variables_from_config(None);
140
141 let snapshot = ConfigSnapshot::from_env();
142
143 // Apply rate-limit changes to the live global limiter immediately.
144 rate_limit::global().set_limits(
145 snapshot.rate_limit_max_requests,
146 snapshot.rate_limit_window_secs,
147 );
148
149 // Publish the new snapshot atomically.
150 *global().write().unwrap() = snapshot.clone();
151
152 println!(
153 "Config reloaded — cors_allow_all={} rate_limit={}/{} log_format={}",
154 snapshot.cors_allow_all,
155 snapshot.rate_limit_max_requests,
156 snapshot.rate_limit_window_secs,
157 snapshot.log_format,
158 );
159}
160
161/// Install a `SIGHUP` signal handler that sets [`RELOAD_REQUESTED`].
162///
163/// Call this once at server startup (before the accept loop). Safe to call
164/// on non-Unix platforms — it compiles to a no-op.
165///
166/// The handler itself does the minimum allowed in a signal context: it stores
167/// `true` into an `AtomicBool`. The actual [`reload()`] call happens on the
168/// main thread between connection accepts.
169pub fn install_sighup_handler() {
170 #[cfg(all(unix, feature = "http1"))]
171 // SAFETY: The handler only writes to a process-global AtomicBool which is
172 // async-signal-safe. No allocation, no locks, no I/O.
173 unsafe {
174 libc::signal(libc::SIGHUP, sighup_handler as *const () as libc::sighandler_t);
175 }
176}
177
178#[cfg(all(unix, feature = "http1"))]
179extern "C" fn sighup_handler(_: libc::c_int) {
180 RELOAD_REQUESTED.store(true, Ordering::SeqCst);
181}