Skip to main content

dynamic_config/
group.rs

1//! Reloading several configuration types as one step.
2//!
3//! Two structs over one file reload independently: for a moment after an edit,
4//! `ServerConfig` is new while `DbConfig` is still old. Usually nobody notices.
5//! Sometimes it matters — a TLS certificate path and the port it is served on,
6//! a queue name and the credentials for it — and then a half-applied
7//! configuration is worse than a late one.
8//!
9//! A group fixes that by splitting a reload in two. **Prepare** does everything
10//! that can fail: read, merge, deserialize, validate. **Commit** does the part
11//! that cannot: swap an `Arc`. Every member prepares before any member commits,
12//! so a failure anywhere leaves every member on its previous snapshot.
13//!
14//! ```text
15//! prepare A ─┐
16//! prepare B ─┼─ all succeeded? ─ yes ─→ commit A, commit B
17//! prepare C ─┘                   no  ─→ nothing moves
18//! ```
19//!
20//! The commits are not one atomic operation — nothing in `std` makes three
21//! `Arc` swaps simultaneous — but they happen with no fallible work between
22//! them, which is the part that actually goes wrong.
23
24use crate::error::Error;
25
26/// The second half of a reload: the part that cannot fail.
27pub type Commit = Box<dyn FnOnce() + Send>;
28
29/// A configuration type that a [`ReloadGroup`] can drive.
30///
31/// Implemented by `#[dynamic_config]`. Implementing it by hand is possible but
32/// rarely what you want — the contract is that `prepare` does *all* the
33/// fallible work, and nothing checks that for you.
34pub trait Reloadable: 'static {
35    /// Loads and validates, returning the swap to perform.
36    ///
37    /// # Errors
38    ///
39    /// Whatever a load of this type would report.
40    fn prepare() -> Result<Commit, Error>;
41
42    /// The type's name, for diagnostics.
43    fn name() -> &'static str;
44}
45
46/// Several configuration types that reload together or not at all.
47///
48/// ```no_run
49/// # use dynamic_config::ReloadGroup;
50/// # struct ServerConfig; struct DbConfig;
51/// # impl dynamic_config::Reloadable for ServerConfig {
52/// #     fn prepare() -> Result<dynamic_config::Commit, dynamic_config::Error> { unimplemented!() }
53/// #     fn name() -> &'static str { "ServerConfig" }
54/// # }
55/// # impl dynamic_config::Reloadable for DbConfig {
56/// #     fn prepare() -> Result<dynamic_config::Commit, dynamic_config::Error> { unimplemented!() }
57/// #     fn name() -> &'static str { "DbConfig" }
58/// # }
59/// let group = ReloadGroup::new()
60///     .with::<ServerConfig>()
61///     .with::<DbConfig>();
62///
63/// group.reload()?;
64/// # Ok::<(), dynamic_config::Error>(())
65/// ```
66#[derive(Default)]
67pub struct ReloadGroup {
68    members: Vec<Member>,
69}
70
71struct Member {
72    name: &'static str,
73    prepare: fn() -> Result<Commit, Error>,
74}
75
76impl ReloadGroup {
77    /// An empty group.
78    #[must_use]
79    pub const fn new() -> Self {
80        Self {
81            members: Vec::new(),
82        }
83    }
84
85    /// Adds a configuration type.
86    ///
87    /// Order matters only for which failure is reported first; the outcome is
88    /// all-or-nothing either way.
89    #[must_use]
90    pub fn with<T: Reloadable>(mut self) -> Self {
91        self.members.push(Member {
92            name: T::name(),
93            prepare: T::prepare,
94        });
95
96        self
97    }
98
99    /// The types in this group, in the order they were added.
100    pub fn members(&self) -> impl Iterator<Item = &'static str> + '_ {
101        self.members.iter().map(|member| member.name)
102    }
103
104    /// Whether the group would do anything.
105    #[must_use]
106    pub fn is_empty(&self) -> bool {
107        self.members.is_empty()
108    }
109
110    /// Loads every member, then installs every member.
111    ///
112    /// # Errors
113    ///
114    /// The first failure, with the offending type's name prepended. Nothing has
115    /// been installed when this returns an error — not even the members that
116    /// loaded cleanly.
117    pub fn reload(&self) -> Result<(), Error> {
118        let mut commits = Vec::with_capacity(self.members.len());
119
120        for member in &self.members {
121            // Any failure here drops the commits collected so far, and dropping
122            // a commit is what *not* applying it means.
123            let commit = (member.prepare)().map_err(|error| error.prepend_key(member.name))?;
124
125            commits.push(commit);
126        }
127
128        for commit in commits {
129            commit();
130        }
131
132        Ok(())
133    }
134}
135
136impl std::fmt::Debug for ReloadGroup {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        f.debug_list().entries(self.members()).finish()
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use std::sync::atomic::{AtomicUsize, Ordering};
146
147    /// A counter per test rather than one shared by all of them: these run in
148    /// parallel, and a `static` they all reset is a race that passes until it
149    /// does not.
150    macro_rules! members {
151        ($counter:ident, $good:ident, $bad:ident) => {
152            static $counter: AtomicUsize = AtomicUsize::new(0);
153
154            struct $good;
155            // Not every test needs the failing half; the macro declares both so
156            // each test's types stay independent.
157            #[allow(dead_code)]
158            struct $bad;
159
160            impl Reloadable for $good {
161                fn prepare() -> Result<Commit, Error> {
162                    Ok(Box::new(|| {
163                        $counter.fetch_add(1, Ordering::SeqCst);
164                    }))
165                }
166
167                fn name() -> &'static str {
168                    stringify!($good)
169                }
170            }
171
172            impl Reloadable for $bad {
173                fn prepare() -> Result<Commit, Error> {
174                    Err(Error::new(crate::ErrorKind::Missing, "nothing supplies it"))
175                }
176
177                fn name() -> &'static str {
178                    stringify!($bad)
179                }
180            }
181        };
182    }
183
184    members!(ALL_COMMITTED, AllGood, AllBad);
185    members!(NONE_COMMITTED, NoneGood, NoneBad);
186    members!(ORDER_COMMITTED, OrderGood, OrderBad);
187
188    #[test]
189    fn every_member_commits_when_every_member_prepares() {
190        ReloadGroup::new()
191            .with::<AllGood>()
192            .with::<AllGood>()
193            .reload()
194            .expect("both prepare cleanly");
195
196        assert_eq!(ALL_COMMITTED.load(Ordering::SeqCst), 2);
197    }
198
199    #[test]
200    fn one_failure_stops_every_commit_including_the_ones_that_would_have_worked() {
201        let error = ReloadGroup::new()
202            .with::<NoneGood>()
203            .with::<NoneBad>()
204            .with::<NoneGood>()
205            .reload()
206            .expect_err("the middle member fails");
207
208        assert_eq!(
209            NONE_COMMITTED.load(Ordering::SeqCst),
210            0,
211            "the member that prepared before the failure must not have committed"
212        );
213        assert!(error.path().starts_with("NoneBad"), "{error}");
214    }
215
216    #[test]
217    fn an_empty_group_is_a_no_op() {
218        let group = ReloadGroup::new();
219
220        assert!(group.is_empty());
221        assert!(group.reload().is_ok());
222    }
223
224    #[test]
225    fn a_group_reports_its_members_in_order() {
226        let group = ReloadGroup::new().with::<OrderGood>().with::<OrderBad>();
227
228        assert_eq!(
229            group.members().collect::<Vec<_>>(),
230            ["OrderGood", "OrderBad"]
231        );
232    }
233}