hyperi-rustlib 2.6.0

Opinionated Rust framework for high-throughput data pipelines at PB scale. Auto-wiring config, logging, metrics, tracing, health, and graceful shutdown — built from many years of production infrastructure experience.
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
// Project:   hyperi-rustlib
// File:      src/config/shared.rs
// Purpose:   Thread-safe shared configuration with hot-reload support
// Language:  Rust
//
// License:   FSL-1.1-ALv2
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Generic thread-safe shared configuration with version tracking.
//!
//! `SharedConfig<T>` wraps any config struct in an `Arc<RwLock<T>>` with a
//! monotonic version counter and a tokio watch channel for subscriber
//! notifications. This is the universal building block for hot-reload across
//! all DFE components (loader, receiver, archiver).
//!
//! ## Usage
//!
//! ```rust
//! use hyperi_rustlib::config::shared::SharedConfig;
//!
//! #[derive(Clone, Debug, Default)]
//! struct AppConfig {
//!     pub buffer_size: usize,
//!     pub log_level: String,
//! }
//!
//! // Create shared config
//! let shared = SharedConfig::new(AppConfig {
//!     buffer_size: 1024,
//!     log_level: "info".into(),
//! });
//!
//! // Read config (zero-copy via read guard)
//! {
//!     let cfg = shared.read();
//!     assert_eq!(cfg.buffer_size, 1024);
//! }
//!
//! // Subscribe to changes
//! let mut rx = shared.subscribe();
//!
//! // Update config (notifies all subscribers)
//! let mut new_cfg = shared.get();
//! new_cfg.buffer_size = 2048;
//! shared.update(new_cfg);
//!
//! assert_eq!(shared.version(), 1);
//! assert_eq!(*rx.borrow(), 1);
//! ```
//!
//! ## Migration from Component-Specific Implementations
//!
//! All DFE components previously had their own `SharedConfig` hard-coded to
//! their specific `Config` struct. This generic version is a drop-in
//! replacement:
//!
//! ```text
//! // Before (component-specific):
//! use crate::config::SharedConfig;           // hard-coded to crate::Config
//!
//! // After (generic from rustlib):
//! use hyperi_rustlib::config::SharedConfig;   // SharedConfig<Config>
//! let shared = SharedConfig::new(config);     // type inferred from argument
//! ```
//!
//! ### API Compatibility
//!
//! | Component Method | rustlib Equivalent | Notes |
//! |------------------|--------------------|-------|
//! | `read()` | `read()` | Returns `RwLockReadGuard` |
//! | `get()` | `get()` | Clones current config |
//! | `with(f)` | `with(f)` | Closure-based read |
//! | `update(cfg)` | `update(cfg)` | Write + version bump + notify |
//! | `version()` | `version()` | Atomic version counter |
//! | `subscribe()` | `subscribe()` | `watch::Receiver<u64>` |
//! | `clone_inner()` | Removed | Use `Clone` on `SharedConfig` instead |

use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use parking_lot::RwLock;
use tokio::sync::watch;
use tracing::debug;

/// Thread-safe shared configuration with version tracking and change
/// notification.
///
/// Designed for hot-reload: components subscribe to config changes via the
/// watch channel and react accordingly. The version counter provides a cheap
/// way to detect whether config has changed since last check.
///
/// `T` must be `Clone` (for `get()`), `Send + Sync` (for cross-thread access),
/// and `'static` (for use in async tasks).
pub struct SharedConfig<T> {
    inner: Arc<RwLock<T>>,
    version: Arc<AtomicU64>,
    watch_tx: Arc<watch::Sender<u64>>,
    watch_rx: watch::Receiver<u64>,
}

impl<T: Clone + Send + Sync + 'static> SharedConfig<T> {
    /// Create a new shared config from an initial value.
    ///
    /// Version starts at 0. First `update()` bumps to 1.
    #[must_use]
    pub fn new(config: T) -> Self {
        let (watch_tx, watch_rx) = watch::channel(0);

        Self {
            inner: Arc::new(RwLock::new(config)),
            version: Arc::new(AtomicU64::new(0)),
            watch_tx: Arc::new(watch_tx),
            watch_rx,
        }
    }

    /// Read the current configuration (zero-copy).
    ///
    /// Returns a read guard that holds the lock. Multiple readers can hold
    /// the lock simultaneously. Prefer this over `get()` when you don't need
    /// to hold the config across await points.
    #[inline]
    pub fn read(&self) -> parking_lot::RwLockReadGuard<'_, T> {
        self.inner.read()
    }

    /// Get a clone of the current configuration.
    ///
    /// Use when you need to hold the config across await points or pass it
    /// to other functions. For read-only access in synchronous code, prefer
    /// `read()` or `with()`.
    #[must_use]
    pub fn get(&self) -> T {
        self.inner.read().clone()
    }

    /// Access configuration via a closure (avoids cloning).
    ///
    /// The closure receives a reference to the current config while holding
    /// the read lock. Useful for extracting a few fields without cloning the
    /// entire struct.
    pub fn with<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&T) -> R,
    {
        let guard = self.inner.read();
        f(&guard)
    }

    /// Get the current config version.
    ///
    /// Version is 0 after creation, incremented by 1 on each `update()`.
    /// Monotonically increasing — never decreases.
    #[inline]
    #[must_use]
    pub fn version(&self) -> u64 {
        self.version.load(Ordering::Acquire)
    }

    /// Update the configuration atomically.
    ///
    /// This will:
    /// 1. Acquire write lock and replace the config
    /// 2. Increment the version counter
    /// 3. Notify all subscribers via the watch channel
    pub fn update(&self, new_config: T) {
        {
            let mut guard = self.inner.write();
            *guard = new_config;
        }

        let new_version = self.version.fetch_add(1, Ordering::AcqRel) + 1;

        // Notify subscribers (ignore error if no receivers)
        let _ = self.watch_tx.send(new_version);

        debug!(version = new_version, "Configuration updated");
    }

    /// Subscribe to configuration changes.
    ///
    /// Returns a `watch::Receiver<u64>` that yields the new version number
    /// on each config update. Use `rx.changed().await` to wait for the next
    /// change.
    ///
    /// ```ignore
    /// let mut rx = shared.subscribe();
    /// loop {
    ///     rx.changed().await.unwrap();
    ///     let version = *rx.borrow();
    ///     let config = shared.get();
    ///     // React to config change...
    /// }
    /// ```
    #[must_use]
    pub fn subscribe(&self) -> watch::Receiver<u64> {
        self.watch_rx.clone()
    }
}

impl<T: Clone + Send + Sync + 'static> Clone for SharedConfig<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            version: self.version.clone(),
            watch_tx: self.watch_tx.clone(),
            watch_rx: self.watch_rx.clone(),
        }
    }
}

impl<T: Clone + Send + Sync + Default + 'static> Default for SharedConfig<T> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T: Clone + Send + Sync + 'static> std::fmt::Debug for SharedConfig<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SharedConfig")
            .field("version", &self.version())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

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

    #[test]
    fn test_new_starts_at_version_zero() {
        let shared = SharedConfig::new(TestConfig::default());
        assert_eq!(shared.version(), 0);
    }

    #[test]
    fn test_read_returns_initial_value() {
        let cfg = TestConfig {
            name: "test".into(),
            value: 42,
        };
        let shared = SharedConfig::new(cfg.clone());

        let guard = shared.read();
        assert_eq!(guard.name, "test");
        assert_eq!(guard.value, 42);
    }

    #[test]
    fn test_get_clones_current_config() {
        let cfg = TestConfig {
            name: "original".into(),
            value: 1,
        };
        let shared = SharedConfig::new(cfg);

        let got = shared.get();
        assert_eq!(got.name, "original");
    }

    #[test]
    fn test_with_closure_access() {
        let cfg = TestConfig {
            name: "closure".into(),
            value: 99,
        };
        let shared = SharedConfig::new(cfg);

        let val = shared.with(|c| c.value);
        assert_eq!(val, 99);
    }

    #[test]
    fn test_update_increments_version() {
        let shared = SharedConfig::new(TestConfig::default());

        assert_eq!(shared.version(), 0);

        shared.update(TestConfig {
            name: "v1".into(),
            value: 1,
        });
        assert_eq!(shared.version(), 1);

        shared.update(TestConfig {
            name: "v2".into(),
            value: 2,
        });
        assert_eq!(shared.version(), 2);
    }

    #[test]
    fn test_update_changes_visible() {
        let shared = SharedConfig::new(TestConfig::default());

        shared.update(TestConfig {
            name: "updated".into(),
            value: 100,
        });

        assert_eq!(shared.read().name, "updated");
        assert_eq!(shared.read().value, 100);
    }

    #[tokio::test]
    async fn test_subscribe_receives_notification() {
        let shared = SharedConfig::new(TestConfig::default());
        let mut rx = shared.subscribe();

        assert_eq!(*rx.borrow(), 0);

        shared.update(TestConfig {
            name: "notify".into(),
            value: 1,
        });

        rx.changed().await.expect("should receive change");
        assert_eq!(*rx.borrow(), 1);
    }

    #[tokio::test]
    async fn test_multiple_subscribers_all_notified() {
        let shared = SharedConfig::new(TestConfig::default());

        let mut rx1 = shared.subscribe();
        let mut rx2 = shared.subscribe();
        let mut rx3 = shared.subscribe();

        shared.update(TestConfig {
            name: "multi".into(),
            value: 1,
        });

        rx1.changed().await.expect("subscriber 1");
        rx2.changed().await.expect("subscriber 2");
        rx3.changed().await.expect("subscriber 3");

        assert_eq!(*rx1.borrow(), 1);
        assert_eq!(*rx2.borrow(), 1);
        assert_eq!(*rx3.borrow(), 1);
    }

    #[test]
    fn test_clone_shares_state() {
        let shared = SharedConfig::new(TestConfig::default());
        let cloned = shared.clone();

        shared.update(TestConfig {
            name: "from-original".into(),
            value: 1,
        });

        // Clone sees the update
        assert_eq!(cloned.read().name, "from-original");
        assert_eq!(cloned.version(), 1);

        // Update from clone is visible on original
        cloned.update(TestConfig {
            name: "from-clone".into(),
            value: 2,
        });

        assert_eq!(shared.read().name, "from-clone");
        assert_eq!(shared.version(), 2);
    }

    #[test]
    fn test_default() {
        let shared: SharedConfig<TestConfig> = SharedConfig::default();
        assert_eq!(shared.version(), 0);
        assert_eq!(shared.read().name, "");
    }

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

        let shared_clone = shared.clone();

        // Spawn a reader
        let reader = tokio::spawn(async move {
            let mut values = Vec::new();
            for _ in 0..100 {
                let name = shared_clone.with(|c| c.name.clone());
                values.push(name);
                tokio::task::yield_now().await;
            }
            values
        });

        // Concurrently update
        for i in 0..50 {
            shared.update(TestConfig {
                name: if i % 2 == 0 {
                    "even".into()
                } else {
                    "odd".into()
                },
                value: i,
            });
            tokio::task::yield_now().await;
        }

        // Reader should never panic, all values should be valid
        let values = reader.await.expect("reader task should not panic");
        for v in &values {
            assert!(
                v == "initial" || v == "even" || v == "odd",
                "unexpected value: {v}"
            );
        }
    }
}