scalo 2.12.1

Self-regulating runtime for Rust data-plane services. Backpressure, load shedding and adaptive scaling are on by default.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
// Project:   scalo
// File:      src/config/reloader.rs
// Purpose:   Universal config hot-reload with SIGHUP, periodic, and file polling
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Universal configuration reloader for data-plane components.
//!
//! `ConfigReloader<T>` provides three reload triggers, any combination of
//! which can be enabled simultaneously:
//!
//! 1. **SIGHUP** (Unix only) -- standard daemon reload signal
//! 2. **Periodic timer** -- reload every N seconds
//! 3. **File polling** -- detect config file changes via mtime comparison
//!
//! The reloader calls a user-supplied `reload_fn` to load config and a
//! `validate_fn` to validate before applying. On success it updates the
//! `SharedConfig<T>` which notifies all subscribers.
//!
//! ## Usage
//!
//! ```rust,no_run
//! use std::path::PathBuf;
//! use std::time::Duration;
//! use scalo::config::reloader::{ConfigReloader, ReloaderConfig};
//! use scalo::config::shared::SharedConfig;
//!
//! #[derive(Clone, Debug, Default)]
//! struct AppConfig {
//!     pub workers: usize,
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let config = AppConfig { workers: 4 };
//!     let shared = SharedConfig::new(config);
//!
//!     let reloader_config = ReloaderConfig {
//!         config_path: Some(PathBuf::from("config.yaml")),
//!         poll_interval: Duration::from_secs(5),
//!         periodic_interval: Duration::ZERO,  // disabled
//!         debounce: Duration::from_millis(500),
//!         enable_sighup: true,
//!     };
//!
//!     let reloader = ConfigReloader::new(
//!         reloader_config,
//!         shared.clone(),
//!         || {
//!             // Your config loading logic here
//!             Ok(AppConfig { workers: 8 })
//!         },
//!         |cfg| {
//!             // Your validation logic here
//!             if cfg.workers == 0 {
//!                 return Err("workers must be > 0".into());
//!             }
//!             Ok(())
//!         },
//!     );
//!
//!     let _handle = reloader.start();
//!     // ... run your application ...
//! }
//! ```
//!
//! Replaces the per-component reload implementations in the loader
//! (`ConfigWatcher`, file polling), the receiver (`config_reload_task`,
//! SIGHUP + periodic), and the archiver: set the matching `ReloaderConfig`
//! fields and pass the component's existing load/validate functions.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use tokio::task::JoinHandle;
use tracing::{debug, error, info, warn};

use super::shared::SharedConfig;
use super::watch::{ConfigTrigger, ConfigWatch};

/// Boxed error type for reload/validate callbacks.
type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// Configuration for the reloader.
#[derive(Debug, Clone)]
pub struct ReloaderConfig {
    /// Path to config file to watch for changes (None = no file watching).
    pub config_path: Option<PathBuf>,

    /// File polling interval. Only used when `config_path` is Some.
    /// Default: 5 seconds.
    pub poll_interval: Duration,

    /// Periodic reload interval. Set to `Duration::ZERO` to disable.
    /// Default: disabled.
    pub periodic_interval: Duration,

    /// Minimum time between reloads (debounce).
    /// Default: 500ms.
    pub debounce: Duration,

    /// Enable SIGHUP reload trigger (Unix only, ignored on other platforms).
    /// Default: true.
    pub enable_sighup: bool,
}

impl Default for ReloaderConfig {
    fn default() -> Self {
        Self {
            config_path: None,
            poll_interval: Duration::from_secs(5),
            periodic_interval: Duration::ZERO,
            debounce: Duration::from_millis(500),
            enable_sighup: true,
        }
    }
}

/// Universal configuration reloader.
///
/// Supports three reload triggers (any combination):
/// - **SIGHUP** (Unix) -- `enable_sighup: true`
/// - **Periodic timer** -- `periodic_interval > 0`
/// - **File polling** -- `config_path: Some(path)`
///
/// On each trigger, calls `reload_fn` to load new config, `validate_fn` to
/// validate, then updates the `SharedConfig<T>` if valid.
/// Callback invoked after a successful reload with the new config value.
type PostReloadHook<T> = Arc<dyn Fn(&T) + Send + Sync>;

pub struct ConfigReloader<T: Clone + Send + Sync + 'static> {
    config: ReloaderConfig,
    shared: SharedConfig<T>,
    reload_fn: Arc<dyn Fn() -> Result<T, BoxError> + Send + Sync>,
    validate_fn: Arc<dyn Fn(&T) -> Result<(), BoxError> + Send + Sync>,
    post_reload_hooks: Vec<PostReloadHook<T>>,
}

impl<T: Clone + Send + Sync + 'static> ConfigReloader<T> {
    /// Create a new config reloader.
    ///
    /// - `config`: Reload trigger configuration
    /// - `shared`: Shared config to update on successful reload
    /// - `reload_fn`: Called to load a fresh config (re-reads file + env)
    /// - `validate_fn`: Called to validate before applying (return Err to reject)
    pub fn new(
        config: ReloaderConfig,
        shared: SharedConfig<T>,
        reload_fn: impl Fn() -> Result<T, BoxError> + Send + Sync + 'static,
        validate_fn: impl Fn(&T) -> Result<(), BoxError> + Send + Sync + 'static,
    ) -> Self {
        Self {
            config,
            shared,
            reload_fn: Arc::new(reload_fn),
            validate_fn: Arc::new(validate_fn),
            post_reload_hooks: Vec::new(),
        }
    }

    /// Add a hook that runs after each successful reload.
    ///
    /// Use this to connect to the config registry:
    ///
    /// ```rust,no_run
    /// # use scalo::config::reloader::ConfigReloader;
    /// # use scalo::config::registry;
    /// // reloader.with_registry_update("my_app");
    /// ```
    #[must_use]
    pub fn with_post_reload_hook(mut self, hook: impl Fn(&T) + Send + Sync + 'static) -> Self {
        self.post_reload_hooks.push(Arc::new(hook));
        self
    }

    /// Connect to the config registry: after each successful reload,
    /// call `registry::update()` so listeners are notified and the
    /// registry reflects the new effective config.
    ///
    /// Requires `T: Serialize + Default`.
    #[must_use]
    pub fn with_registry_update(self, key: &str) -> Self
    where
        T: serde::Serialize + Default,
    {
        let key = key.to_string();
        self.with_post_reload_hook(move |config| {
            super::registry::update::<T>(&key, config);
        })
    }

    /// Start the reload loop in a background task.
    ///
    /// Returns a `JoinHandle` that can be used to abort the reloader.
    /// The task runs until cancelled or the process exits.
    pub fn start(self) -> JoinHandle<()> {
        let has_file = self.config.config_path.is_some();
        let has_periodic = self.config.periodic_interval > Duration::ZERO;
        let has_sighup = self.config.enable_sighup;

        info!(
            file_watch = has_file,
            periodic = has_periodic,
            sighup = has_sighup,
            "Config reloader started"
        );

        tokio::spawn(async move {
            self.run_loop().await;
        })
    }

    /// Main reload loop -- waits for any trigger, then attempts reload.
    async fn run_loop(self) {
        #[cfg(feature = "shutdown")]
        let shutdown_token = crate::shutdown::token();

        let mut watch =
            ConfigWatch::new(self.config.config_path.clone(), self.config.poll_interval)
                .with_periodic(self.config.periodic_interval)
                .with_sighup(self.config.enable_sighup);
        watch.prime().await;

        let mut last_reload = Instant::now();

        loop {
            // Check for global shutdown before waiting for next trigger
            #[cfg(feature = "shutdown")]
            if shutdown_token.is_cancelled() {
                info!("Config reloader stopping (shutdown)");
                return;
            }

            let trigger_result = {
                #[cfg(feature = "shutdown")]
                {
                    tokio::select! {
                        trigger = watch.next_trigger() => Some(trigger),
                        () = shutdown_token.cancelled() => None,
                    }
                }
                #[cfg(not(feature = "shutdown"))]
                {
                    Some(watch.next_trigger().await)
                }
            };

            let Some(trigger) = trigger_result else {
                info!("Config reloader stopping (shutdown)");
                return;
            };

            // Debounce check
            if last_reload.elapsed() < self.config.debounce {
                debug!("Debouncing config reload");
                continue;
            }

            match trigger {
                ConfigTrigger::FileChanged => {
                    info!(
                        path = ?self.config.config_path,
                        "Config file changed, reloading"
                    );
                }
                ConfigTrigger::Periodic => {
                    info!("Periodic config reload triggered");
                }
                ConfigTrigger::Sighup => {
                    info!("SIGHUP received, reloading configuration");
                }
            }

            self.do_reload();
            last_reload = Instant::now();
        }
    }

    /// Attempt to reload config: load -> validate -> update shared.
    fn do_reload(&self) {
        match (self.reload_fn)() {
            Ok(new_config) => {
                if let Err(e) = (self.validate_fn)(&new_config) {
                    error!(error = %e, "Config reload validation failed, keeping current config");
                    #[cfg(feature = "metrics")]
                    metrics::counter!("config_reloads_total", "result" => "error").increment(1);
                    return;
                }

                let old_version = self.shared.version();
                self.shared.update(new_config.clone());
                let new_version = self.shared.version();

                // Run post-reload hooks (registry update, etc.)
                for hook in &self.post_reload_hooks {
                    hook(&new_config);
                }

                #[cfg(feature = "metrics")]
                metrics::counter!("config_reloads_total", "result" => "success").increment(1);

                info!(
                    old_version = old_version,
                    new_version = new_version,
                    "Configuration reloaded successfully"
                );
            }
            Err(e) => {
                warn!(error = %e, "Config reload failed, keeping current config");
                #[cfg(feature = "metrics")]
                metrics::counter!("config_reloads_total", "result" => "error").increment(1);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Write;
    use std::sync::atomic::{AtomicBool, Ordering};
    use tempfile::TempDir;

    #[derive(Clone, Debug, Default, PartialEq)]
    struct TestConfig {
        pub value: String,
    }

    #[test]
    fn test_reloader_config_defaults() {
        let config = ReloaderConfig::default();
        assert!(config.config_path.is_none());
        assert_eq!(config.poll_interval, Duration::from_secs(5));
        assert_eq!(config.periodic_interval, Duration::ZERO);
        assert_eq!(config.debounce, Duration::from_millis(500));
        assert!(config.enable_sighup);
    }

    #[tokio::test]
    async fn test_periodic_reload() {
        let shared = SharedConfig::new(TestConfig {
            value: "initial".into(),
        });
        let mut rx = shared.subscribe();

        let call_count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let call_count_clone = call_count.clone();

        let reloader = ConfigReloader::new(
            ReloaderConfig {
                periodic_interval: Duration::from_millis(50),
                debounce: Duration::from_millis(10),
                enable_sighup: false,
                ..Default::default()
            },
            shared.clone(),
            move || {
                call_count_clone.fetch_add(1, Ordering::Relaxed);
                Ok(TestConfig {
                    value: "reloaded".into(),
                })
            },
            |_| Ok(()),
        );

        let handle = reloader.start();

        // Wait for at least one reload
        let result = tokio::time::timeout(Duration::from_secs(2), rx.changed()).await;
        assert!(result.is_ok(), "Should receive reload notification");

        assert_eq!(shared.read().value, "reloaded");
        assert!(shared.version() >= 1);
        assert!(call_count.load(Ordering::Relaxed) >= 1);

        handle.abort();
    }

    #[tokio::test]
    async fn test_file_change_triggers_reload() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.yaml");
        fs::write(&config_path, "initial content").unwrap();

        let shared = SharedConfig::new(TestConfig {
            value: "initial".into(),
        });
        let mut rx = shared.subscribe();

        let path_for_reload = config_path.clone();
        let reloader = ConfigReloader::new(
            ReloaderConfig {
                config_path: Some(config_path.clone()),
                poll_interval: Duration::from_millis(50),
                debounce: Duration::from_millis(10),
                enable_sighup: false,
                ..Default::default()
            },
            shared.clone(),
            move || {
                let content = fs::read_to_string(&path_for_reload).unwrap_or_default();
                Ok(TestConfig { value: content })
            },
            |_| Ok(()),
        );

        let handle = reloader.start();

        // Let the watcher start and record initial mtime
        tokio::time::sleep(Duration::from_millis(150)).await;

        // Modify the file
        {
            let mut file = fs::OpenOptions::new()
                .write(true)
                .truncate(true)
                .open(&config_path)
                .unwrap();
            file.write_all(b"updated content").unwrap();
            file.sync_all().unwrap();
        }

        // Wait for the reload
        let result = tokio::time::timeout(Duration::from_secs(2), rx.changed()).await;
        if result.is_ok() {
            assert_eq!(shared.read().value, "updated content");
        }

        handle.abort();
    }

    #[tokio::test]
    async fn test_validation_failure_preserves_config() {
        let shared = SharedConfig::new(TestConfig {
            value: "good".into(),
        });

        let should_fail = Arc::new(AtomicBool::new(true));
        let should_fail_clone = should_fail.clone();

        let reloader = ConfigReloader::new(
            ReloaderConfig {
                periodic_interval: Duration::from_millis(50),
                debounce: Duration::from_millis(10),
                enable_sighup: false,
                ..Default::default()
            },
            shared.clone(),
            || {
                Ok(TestConfig {
                    value: "bad".into(),
                })
            },
            move |_cfg| {
                if should_fail_clone.load(Ordering::Relaxed) {
                    Err("validation failed".into())
                } else {
                    Ok(())
                }
            },
        );

        let handle = reloader.start();

        // Let a few reload attempts happen (all should fail validation)
        tokio::time::sleep(Duration::from_millis(200)).await;

        // Config should still be the original
        assert_eq!(shared.read().value, "good");
        assert_eq!(shared.version(), 0);

        handle.abort();
    }

    #[tokio::test]
    async fn test_reload_fn_error_preserves_config() {
        let shared = SharedConfig::new(TestConfig {
            value: "good".into(),
        });

        let reloader = ConfigReloader::new(
            ReloaderConfig {
                periodic_interval: Duration::from_millis(50),
                debounce: Duration::from_millis(10),
                enable_sighup: false,
                ..Default::default()
            },
            shared.clone(),
            || Err("load failed".into()),
            |_| Ok(()),
        );

        let handle = reloader.start();

        // Let a few reload attempts happen
        tokio::time::sleep(Duration::from_millis(200)).await;

        // Config should still be the original
        assert_eq!(shared.read().value, "good");
        assert_eq!(shared.version(), 0);

        handle.abort();
    }
}