1use std::sync::{Arc, OnceLock};
4
5use arc_swap::ArcSwap;
6
7type Hook<T> = Arc<dyn Fn(&Arc<T>, &Arc<T>) + Send + Sync>;
9
10struct Registered<T> {
14 token: u64,
15 hook: Hook<T>,
16}
17
18impl<T> Clone for Registered<T> {
19 fn clone(&self) -> Self {
20 Self {
21 token: self.token,
22 hook: Arc::clone(&self.hook),
23 }
24 }
25}
26
27pub struct ConfigCell<T> {
51 inner: OnceLock<ArcSwap<T>>,
52
53 hooks: OnceLock<ArcSwap<Vec<Registered<T>>>>,
56
57 next_token: std::sync::atomic::AtomicU64,
60
61 #[cfg(feature = "async")]
64 notify: crate::asynchronous::Notify,
65}
66
67impl<T> ConfigCell<T> {
68 #[must_use]
70 #[cfg(not(loom))]
71 pub const fn new() -> Self {
72 Self {
73 inner: OnceLock::new(),
74 hooks: OnceLock::new(),
75 next_token: std::sync::atomic::AtomicU64::new(0),
76 #[cfg(feature = "async")]
77 notify: crate::asynchronous::Notify::new(),
78 }
79 }
80
81 #[must_use]
83 #[cfg(loom)]
84 pub fn new() -> Self {
85 Self {
86 inner: OnceLock::new(),
87 hooks: OnceLock::new(),
88 next_token: std::sync::atomic::AtomicU64::new(0),
89 #[cfg(feature = "async")]
90 notify: crate::asynchronous::Notify::new(),
91 }
92 }
93
94 pub fn store(&self, value: T) {
100 let value = Arc::new(value);
101
102 let slot = self.inner.get_or_init(|| ArcSwap::new(Arc::clone(&value)));
106 let previous = slot.swap(Arc::clone(&value));
107
108 #[cfg(feature = "async")]
118 self.notify.bump();
119
120 if !Arc::ptr_eq(&previous, &value) {
121 self.dispatch(&previous, &value);
122 }
123 }
124
125 pub fn on_reload(&self, hook: impl Fn(&Arc<T>, &Arc<T>) + Send + Sync + 'static) {
142 let _ = self.register(Arc::new(hook));
143 }
144
145 #[must_use = "dropping the guard unregisters the hook; bind it for as long \
151 as the hook should fire, or use `on_reload` for a permanent one"]
152 pub fn on_reload_scoped(
153 &'static self,
154 hook: impl Fn(&Arc<T>, &Arc<T>) + Send + Sync + 'static,
155 ) -> HookGuard<T> {
156 HookGuard {
157 cell: self,
158 token: self.register(Arc::new(hook)),
159 }
160 }
161
162 fn register(&self, hook: Hook<T>) -> u64 {
163 let token = self
164 .next_token
165 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
166
167 self.hooks
168 .get_or_init(|| ArcSwap::from_pointee(Vec::new()))
169 .rcu(|current| {
170 let mut next = Vec::with_capacity(current.len() + 1);
171
172 next.extend(current.iter().cloned());
173 next.push(Registered {
174 token,
175 hook: Arc::clone(&hook),
176 });
177
178 next
179 });
180
181 token
182 }
183
184 fn unregister(&self, token: u64) {
185 let Some(hooks) = self.hooks.get() else {
186 return;
187 };
188
189 hooks.rcu(|current| {
190 current
191 .iter()
192 .filter(|registered| registered.token != token)
193 .cloned()
194 .collect::<Vec<_>>()
195 });
196 }
197
198 fn dispatch(&self, previous: &Arc<T>, current: &Arc<T>) {
199 let Some(hooks) = self.hooks.get() else {
200 return;
201 };
202
203 for registered in hooks.load().iter() {
206 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
212 (registered.hook)(previous, current);
213 }));
214
215 if outcome.is_err() {
216 crate::log::warning!(
217 "a reload hook panicked; it stays registered and the \
218 remaining hooks still run"
219 );
220 }
221 }
222 }
223
224 pub fn load(&self) -> Option<Arc<T>> {
226 self.inner.get().map(ArcSwap::load_full)
227 }
228
229 pub fn get_or_panic(&self, type_name: &str) -> Arc<T> {
238 self.load().unwrap_or_else(|| {
239 panic!(
240 "{type_name} has no snapshot installed; configure and install \
241 one first: `{type_name}::builder(\"..\")...init()?`"
242 )
243 })
244 }
245
246 #[cfg(feature = "async")]
254 #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
255 pub fn changes(&'static self) -> crate::Changes<T>
256 where
257 T: Send + Sync,
258 {
259 crate::Changes::new(self)
260 }
261
262 #[cfg(feature = "async")]
263 pub(crate) fn notify(&self) -> &crate::asynchronous::Notify {
264 &self.notify
265 }
266}
267
268pub struct HookGuard<T: 'static> {
271 cell: &'static ConfigCell<T>,
272 token: u64,
273}
274
275impl<T> Drop for HookGuard<T> {
276 fn drop(&mut self) {
277 self.cell.unregister(self.token);
278 }
279}
280
281impl<T> std::fmt::Debug for HookGuard<T> {
282 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
283 f.debug_struct("HookGuard")
284 .field("token", &self.token)
285 .finish_non_exhaustive()
286 }
287}
288
289impl<T> Default for ConfigCell<T> {
290 fn default() -> Self {
291 Self::new()
292 }
293}
294
295impl<T: std::fmt::Debug> std::fmt::Debug for ConfigCell<T> {
296 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297 match self.load() {
298 Some(value) => f.debug_tuple("ConfigCell").field(&value).finish(),
299 None => f.write_str("ConfigCell(uninitialized)"),
300 }
301 }
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307 use std::sync::Mutex;
308 use std::thread;
309
310 #[test]
311 fn a_fresh_cell_is_empty() {
312 let cell = ConfigCell::<u16>::new();
313
314 assert!(cell.load().is_none());
315 }
316
317 #[test]
318 fn a_reader_keeps_the_generation_it_took() {
319 let cell = ConfigCell::new();
320 cell.store(String::from("first"));
321
322 let held = cell.load().unwrap();
323 cell.store(String::from("second"));
324
325 assert_eq!(*held, "first");
326 assert_eq!(*cell.load().unwrap(), "second");
327 }
328
329 #[test]
330 fn concurrent_first_writes_do_not_lose_the_cell() {
331 let cell: &'static ConfigCell<usize> = Box::leak(Box::new(ConfigCell::new()));
332
333 let writers: Vec<_> = (0..8)
334 .map(|value| thread::spawn(move || cell.store(value)))
335 .collect();
336
337 for writer in writers {
338 writer.join().unwrap();
339 }
340
341 let final_value = *cell.load().expect("some writer must have won");
342 assert!(final_value < 8);
343 }
344
345 #[test]
346 fn the_first_store_is_an_initialization_not_a_reload() {
347 let seen = Arc::new(Mutex::new(Vec::new()));
348 let cell = ConfigCell::new();
349
350 let recorder = Arc::clone(&seen);
351 cell.on_reload(move |previous, current| {
352 recorder.lock().unwrap().push((**previous, **current));
353 });
354
355 cell.store(1u16);
356 assert!(
357 seen.lock().unwrap().is_empty(),
358 "there is nothing to compare the first snapshot against"
359 );
360
361 cell.store(2u16);
362 cell.store(3u16);
363
364 assert_eq!(*seen.lock().unwrap(), [(1, 2), (2, 3)]);
365 }
366
367 #[test]
368 fn every_registered_callback_runs() {
369 let count = Arc::new(Mutex::new(0usize));
370 let cell = ConfigCell::new();
371
372 for _ in 0..3 {
373 let counter = Arc::clone(&count);
374 cell.on_reload(move |_, _| *counter.lock().unwrap() += 1);
375 }
376
377 cell.store(1u16);
378 cell.store(2u16);
379
380 assert_eq!(*count.lock().unwrap(), 3);
381 }
382
383 #[test]
384 fn a_panicking_hook_silences_neither_the_rest_nor_the_next_reload() {
385 let count = Arc::new(Mutex::new(0usize));
386 let cell = ConfigCell::new();
387
388 cell.on_reload(|_, _| panic!("a bug in somebody's hook"));
389 {
390 let counter = Arc::clone(&count);
391 cell.on_reload(move |_, _| *counter.lock().unwrap() += 1);
392 }
393
394 cell.store(1u16);
395 cell.store(2u16);
396 cell.store(3u16);
397
398 assert_eq!(
399 *count.lock().unwrap(),
400 2,
401 "the hook after the panicking one must run on every reload"
402 );
403 }
404
405 #[test]
406 fn dropping_the_guard_unregisters_the_hook() {
407 let count = Arc::new(Mutex::new(0usize));
408 let cell: &'static ConfigCell<u16> = Box::leak(Box::new(ConfigCell::new()));
409
410 cell.store(1);
411
412 let guard = {
413 let counter = Arc::clone(&count);
414 cell.on_reload_scoped(move |_, _| *counter.lock().unwrap() += 1)
415 };
416
417 cell.store(2);
418 assert_eq!(*count.lock().unwrap(), 1);
419
420 drop(guard);
421 cell.store(3);
422 assert_eq!(
423 *count.lock().unwrap(),
424 1,
425 "an unregistered hook must not fire"
426 );
427 }
428
429 #[test]
430 #[should_panic(expected = "`DbConfig::builder(")]
431 fn get_or_panic_points_at_the_builder() {
432 ConfigCell::<u16>::new().get_or_panic("DbConfig");
433 }
434}