Skip to main content

halephant_core/config/
reload.rs

1//! SIGHUP-driven configuration hot reload. Loads a new
2//! [`crate::config::Config`] from disk, classifies each changed field
3//! as hot-reloadable or restart-required, and atomically swaps the
4//! shared [`arc_swap::ArcSwap`] handle on success.
5
6use std::path::Path;
7use std::sync::Arc;
8
9use arc_swap::ArcSwap;
10
11use crate::config::Config;
12
13/// Outcome of a single SIGHUP-triggered reload attempt. Reported via the
14/// `halephant.config.reloads` counter and the structured log event on the
15/// `SIGHUP` branch in `main`.
16#[derive(Debug)]
17pub enum ReloadOutcome {
18    /// New config loaded and swapped in atomically. The caller runs
19    /// `topology.refresh()` and `pools.warm_up()` so any added nodes,
20    /// pools, or `min_connections` floors take effect immediately.
21    Success,
22    /// The new config parsed successfully but changes one or more
23    /// fields that are bound at startup (listen sockets, OTel
24    /// providers, logging subscriber, …). The old config stays in
25    /// place; operators must restart the process to apply the change.
26    RestartRequired(&'static str),
27    /// The file could not be read, could not be parsed, or failed
28    /// validation. The old config stays in place.
29    ParseFailed(anyhow::Error),
30}
31
32/// Attempt to reload the config from disk and swap it into the shared
33/// `ArcSwap`. On success the swap is atomic and immediately visible to
34/// every component holding a handle to `config`; the caller is
35/// responsible for running side effects (topology refresh, warm-up).
36/// On failure the swap is not performed.
37///
38/// This is `async` because it offloads the file read + TOML parse to
39/// `tokio::task::spawn_blocking`: `Config::load` uses
40/// `std::fs::read_to_string` under the hood, and running that on an
41/// async worker would stall the accept loop and every other task on
42/// the same worker for the duration of the disk read — potentially
43/// noticeable on NFS-mounted or encrypted filesystems.
44pub async fn reload_config(config_path: &Path, config: &ArcSwap<Config>) -> ReloadOutcome {
45    // Clone the path into the blocking task because the closure
46    // requires `'static` data; `PathBuf` is a small, cheap clone.
47    let config_path_owned = config_path.to_path_buf();
48    let load_result = tokio::task::spawn_blocking(move || Config::load(&config_path_owned)).await;
49
50    let new_config = match load_result {
51        Ok(Ok(c)) => c,
52        Ok(Err(e)) => return ReloadOutcome::ParseFailed(e.into()),
53        Err(join_err) => {
54            return ReloadOutcome::ParseFailed(anyhow::anyhow!(
55                "config load task failed: {join_err}"
56            ));
57        }
58    };
59
60    // `load_full` snapshots the current config for field comparison.
61    // Holding the snapshot only for the duration of `requires_restart`
62    // keeps the window between the comparison and the subsequent
63    // `store` small; a concurrent reload is impossible because SIGHUP
64    // is serialized through the main select loop.
65    let current = config.load_full();
66    if let Some(field) = requires_restart(&current, &new_config) {
67        return ReloadOutcome::RestartRequired(field);
68    }
69
70    config.store(Arc::new(new_config));
71    ReloadOutcome::Success
72}
73
74/// Compare two configs and return the first field whose change cannot
75/// be applied without a process restart. Returns `None` when every
76/// difference is safe to hot-reload.
77///
78/// Restart-required fields fall into three categories:
79/// - **Bound at startup:** `server.listen`, `admin.listen`. The TCP
80///   sockets are created once during `main` and cannot be rebound
81///   under an already-serving process.
82/// - **Cached into long-lived handles:** `server.pgpass` (loaded into
83///   `Arc<Pgpass>` once), `server.workers` (consumed by the tokio
84///   runtime).
85/// - **Subscriber / exporter configuration:** `otel.endpoint`,
86///   `otel.service_name`, `logging.format`, `logging.level`. These
87///   configure the tracing subscriber and OTel providers that live
88///   for the process lifetime.
89pub fn requires_restart(old: &Config, new: &Config) -> Option<&'static str> {
90    if old.server.listen != new.server.listen {
91        return Some("server.listen");
92    }
93    if old.server.pgpass != new.server.pgpass {
94        return Some("server.pgpass");
95    }
96    if old.server.workers != new.server.workers {
97        return Some("server.workers");
98    }
99    if old.admin.listen != new.admin.listen {
100        return Some("admin.listen");
101    }
102    if old.otel.endpoint != new.otel.endpoint {
103        return Some("otel.endpoint");
104    }
105    if old.otel.service_name != new.otel.service_name {
106        return Some("otel.service_name");
107    }
108    if old.logging.format != new.logging.format {
109        return Some("logging.format");
110    }
111    if old.logging.level != new.logging.level {
112        return Some("logging.level");
113    }
114    None
115}
116
117// ---------------------------------------------------------------------------
118// Tests
119// ---------------------------------------------------------------------------
120
121#[cfg(test)]
122#[allow(clippy::unwrap_used)]
123mod tests {
124    use std::path::{Path, PathBuf};
125
126    use super::*;
127
128    /// Minimal TOML config with a single cluster — used as the baseline
129    /// for field-mutation tests. Every `requires_restart` case builds a
130    /// pair of configs from this template with one field altered.
131    const BASE_TOML: &str = r#"
132        [server]
133        listen = ["0.0.0.0:6432"]
134
135        [logging]
136        level = "info"
137
138        [cluster.main]
139        nodes = ["127.0.0.1:5432"]
140
141        [cluster.main.pool.mydb.user.myuser]
142    "#;
143
144    fn base_config() -> Config {
145        Config::parse(BASE_TOML).unwrap()
146    }
147
148    // ---- requires_restart: identity -------------------------------------
149
150    #[test]
151    fn requires_restart_identical_configs_returns_none() {
152        let a = base_config();
153        let b = base_config();
154        assert_eq!(requires_restart(&a, &b), None);
155    }
156
157    // ---- requires_restart: restart-bound fields -------------------------
158
159    #[test]
160    fn requires_restart_flags_listen_change() {
161        let old = base_config();
162        let new = Config::parse(&BASE_TOML.replace(
163            r#"listen = ["0.0.0.0:6432"]"#,
164            r#"listen = ["0.0.0.0:7000"]"#,
165        ))
166        .unwrap();
167        assert_eq!(requires_restart(&old, &new), Some("server.listen"));
168    }
169
170    #[test]
171    fn requires_restart_flags_pgpass_change() {
172        let old = base_config();
173        let mut new = base_config();
174        new.server.pgpass = Some(PathBuf::from("/tmp/pgpass"));
175        assert_eq!(requires_restart(&old, &new), Some("server.pgpass"));
176    }
177
178    #[test]
179    fn requires_restart_flags_workers_change() {
180        let old = base_config();
181        let mut new = base_config();
182        new.server.workers = 4;
183        assert_eq!(requires_restart(&old, &new), Some("server.workers"));
184    }
185
186    #[test]
187    fn requires_restart_flags_admin_listen_change() {
188        let old = base_config();
189        let mut new = base_config();
190        new.admin.listen = Some("0.0.0.0:6433".into());
191        assert_eq!(requires_restart(&old, &new), Some("admin.listen"));
192    }
193
194    #[test]
195    fn requires_restart_flags_otel_endpoint_change() {
196        let old = base_config();
197        let mut new = base_config();
198        new.otel.endpoint = Some("http://collector:4317".into());
199        assert_eq!(requires_restart(&old, &new), Some("otel.endpoint"));
200    }
201
202    #[test]
203    fn requires_restart_flags_otel_service_name_change() {
204        let old = base_config();
205        let mut new = base_config();
206        new.otel.service_name = "halephant-prod".into();
207        assert_eq!(requires_restart(&old, &new), Some("otel.service_name"));
208    }
209
210    #[test]
211    fn requires_restart_flags_logging_format_change() {
212        let old = base_config();
213        let mut new = base_config();
214        new.logging.format = crate::config::logging::LogFormat::Text;
215        assert_eq!(requires_restart(&old, &new), Some("logging.format"));
216    }
217
218    #[test]
219    fn requires_restart_flags_logging_level_change() {
220        let old = base_config();
221        let mut new = base_config();
222        new.logging.level = "debug".into();
223        assert_eq!(requires_restart(&old, &new), Some("logging.level"));
224    }
225
226    // ---- requires_restart: hot-reloadable fields ------------------------
227
228    #[test]
229    fn requires_restart_allows_cluster_node_addition() {
230        let old = base_config();
231        let new = Config::parse(&BASE_TOML.replace(
232            r#"nodes = ["127.0.0.1:5432"]"#,
233            r#"nodes = ["127.0.0.1:5432", "127.0.0.1:5433"]"#,
234        ))
235        .unwrap();
236        assert_eq!(requires_restart(&old, &new), None);
237    }
238
239    #[test]
240    fn requires_restart_allows_max_connections_change() {
241        let old = base_config();
242        let new = Config::parse(
243            r#"
244            [server]
245            listen = ["0.0.0.0:6432"]
246
247            [logging]
248            level = "info"
249
250            [cluster.main]
251            nodes = ["127.0.0.1:5432"]
252
253            [cluster.main.pool.mydb]
254            max_connections = { primary = 50 }
255
256            [cluster.main.pool.mydb.user.myuser]
257            "#,
258        )
259        .unwrap();
260        assert_eq!(requires_restart(&old, &new), None);
261    }
262
263    #[test]
264    fn requires_restart_allows_checkout_timeout_change() {
265        let old = base_config();
266        let new = Config::parse(
267            r#"
268            [server]
269            listen = ["0.0.0.0:6432"]
270            checkout_timeout = "5s"
271
272            [logging]
273            level = "info"
274
275            [cluster.main]
276            nodes = ["127.0.0.1:5432"]
277
278            [cluster.main.pool.mydb.user.myuser]
279            "#,
280        )
281        .unwrap();
282        assert_eq!(requires_restart(&old, &new), None);
283    }
284
285    #[test]
286    fn requires_restart_allows_shutdown_timeout_change() {
287        let old = base_config();
288        let new = Config::parse(
289            r#"
290            [server]
291            listen = ["0.0.0.0:6432"]
292            shutdown_timeout = "60s"
293
294            [logging]
295            level = "info"
296
297            [cluster.main]
298            nodes = ["127.0.0.1:5432"]
299
300            [cluster.main.pool.mydb.user.myuser]
301            "#,
302        )
303        .unwrap();
304        assert_eq!(requires_restart(&old, &new), None);
305    }
306
307    #[test]
308    fn requires_restart_allows_adding_new_cluster() {
309        let old = base_config();
310        let new = Config::parse(
311            r#"
312            [server]
313            listen = ["0.0.0.0:6432"]
314
315            [logging]
316            level = "info"
317
318            [cluster.main]
319            nodes = ["127.0.0.1:5432"]
320
321            [cluster.main.pool.mydb.user.myuser]
322
323            [cluster.warehouse]
324            nodes = ["127.0.0.1:5433"]
325
326            [cluster.warehouse.pool.analytics.user.analyst]
327            "#,
328        )
329        .unwrap();
330        assert_eq!(requires_restart(&old, &new), None);
331    }
332
333    // ---- reload_config ---------------------------------------------------
334
335    /// Write a TOML config to a temp file and return the path. The
336    /// `tempfile::NamedTempFile` handle must be kept alive by the test
337    /// so the file isn't removed out from under `reload_config`.
338    fn write_temp_config(toml: &str) -> tempfile::NamedTempFile {
339        use std::io::Write;
340        let mut f = tempfile::Builder::new()
341            .prefix("halephant-reload-")
342            .suffix(".toml")
343            .tempfile()
344            .unwrap();
345        f.write_all(toml.as_bytes()).unwrap();
346        f.flush().unwrap();
347        f
348    }
349
350    #[tokio::test]
351    async fn reload_config_success_swaps_arc() {
352        let initial = base_config();
353        let shared = Arc::new(ArcSwap::from_pointee(initial));
354
355        // Write a hot-reloadable new config (raised max_connections).
356        let new_toml = r#"
357            [server]
358            listen = ["0.0.0.0:6432"]
359
360            [logging]
361            level = "info"
362
363            [cluster.main]
364            nodes = ["127.0.0.1:5432"]
365
366            [cluster.main.pool.mydb]
367            max_connections = { primary = 77 }
368
369            [cluster.main.pool.mydb.user.myuser]
370        "#;
371        let file = write_temp_config(new_toml);
372
373        let outcome = reload_config(file.path(), &shared).await;
374        assert!(matches!(outcome, ReloadOutcome::Success), "{outcome:?}");
375
376        // The swap is visible on the next `load`.
377        let after = shared.load_full();
378        let (_, _, pool) = after.find_pool("mydb").expect("pool still exists");
379        assert_eq!(pool.max_connections.primary, 77);
380    }
381
382    #[tokio::test]
383    async fn reload_config_restart_required_does_not_swap() {
384        let initial = base_config();
385        let shared = Arc::new(ArcSwap::from_pointee(initial));
386
387        // Change `server.listen` — classified as restart-required.
388        let new_toml = r#"
389            [server]
390            listen = ["0.0.0.0:7000"]
391
392            [logging]
393            level = "info"
394
395            [cluster.main]
396            nodes = ["127.0.0.1:5432"]
397
398            [cluster.main.pool.mydb.user.myuser]
399        "#;
400        let file = write_temp_config(new_toml);
401
402        let outcome = reload_config(file.path(), &shared).await;
403        assert!(
404            matches!(outcome, ReloadOutcome::RestartRequired("server.listen")),
405            "{outcome:?}"
406        );
407
408        // Old config is still in place — `server.listen` unchanged.
409        let after = shared.load_full();
410        assert_eq!(after.server.listen, vec!["0.0.0.0:6432".to_owned()]);
411    }
412
413    #[tokio::test]
414    async fn reload_config_parse_error_does_not_swap() {
415        let initial = base_config();
416        let shared = Arc::new(ArcSwap::from_pointee(initial));
417
418        // Not valid TOML.
419        let file = write_temp_config("this is [not valid toml\n");
420
421        let outcome = reload_config(file.path(), &shared).await;
422        assert!(
423            matches!(outcome, ReloadOutcome::ParseFailed(_)),
424            "{outcome:?}"
425        );
426
427        // Old config is still in place.
428        let after = shared.load_full();
429        assert!(after.find_pool("mydb").is_some());
430    }
431
432    #[tokio::test]
433    async fn reload_config_validation_error_does_not_swap() {
434        let initial = base_config();
435        let shared = Arc::new(ArcSwap::from_pointee(initial));
436
437        // Parses as TOML but fails `Config::validate()` — `server.listen`
438        // cannot be empty.
439        let new_toml = r#"
440            [server]
441            listen = []
442
443            [cluster.main]
444            nodes = ["127.0.0.1:5432"]
445
446            [cluster.main.pool.mydb.user.myuser]
447        "#;
448        let file = write_temp_config(new_toml);
449
450        let outcome = reload_config(file.path(), &shared).await;
451        assert!(
452            matches!(outcome, ReloadOutcome::ParseFailed(_)),
453            "{outcome:?}"
454        );
455
456        // Old config is still in place.
457        let after = shared.load_full();
458        assert_eq!(after.server.listen, vec!["0.0.0.0:6432".to_owned()]);
459    }
460
461    #[tokio::test]
462    async fn reload_config_missing_file_returns_parse_failed() {
463        let initial = base_config();
464        let shared = Arc::new(ArcSwap::from_pointee(initial));
465
466        let missing = Path::new("/nonexistent/halephant-reload.toml");
467        let outcome = reload_config(missing, &shared).await;
468        assert!(
469            matches!(outcome, ReloadOutcome::ParseFailed(_)),
470            "{outcome:?}"
471        );
472    }
473}