Skip to main content

base/interface/
config_source.rs

1//! `ConfigSource` — where the settings layers come from.
2//!
3//! `LoadedSettings::load` merges three tiers, each with a gitignored overlay beside
4//! it, and it read all six with `std::fs::read_to_string`. That made the file
5//! system part of the definition of "configuration": a deployment that keeps
6//! its settings in a config service, a Kubernetes ConfigMap, or a database had
7//! no way in that did not involve writing six files to disk first so the
8//! engine could read them back.
9//!
10//! What moves is only *where the layers come from*. The merge — six layers
11//! low-to-high, generic recursive JSON merge, `paths` stripped from every
12//! layer, the `permissions` rule lists from an overlay held apart — stays exactly where
13//! it was, in `settings::LoadedSettings::load_from`. A source hands over
14//! JSON values in priority order and has no say in what happens to them,
15//! which is what keeps "settings come from somewhere else" from turning into
16//! "settings mean something else".
17//!
18//! # A source reports its own failures and yields nothing
19//!
20//! `LoadedSettings::load` never fails: a layer that is absent is skipped, and one
21//! that will not parse is skipped with a warning rather than taking startup
22//! down with it. That property belongs to the loader and cannot be delegated,
23//! so [`ConfigSource::layers`] returns layers rather than a `Result` — a
24//! source that cannot reach its backing store logs why and returns what it
25//! has. Losing a layer is bad; refusing to start because a remote service is
26//! slow is worse.
27//!
28//! # Synchronous, and a remote source is still a fit
29//!
30//! Configuration is read once, before anything is built, and every caller of
31//! `LoadedSettings::load` today is synchronous. A source that has to go over a
32//! network fetches in [`ConfigSource::layers`] — it is called once per process
33//! and is allowed to be slow — or fetches ahead of time and hands the result
34//! over as [`InMemoryLayers`]. [`Chain`] is for the common shape of the second
35//! case: the files on disk, with what the control plane says layered on top.
36
37use std::sync::Arc;
38
39/// Which tier a layer belongs to, lowest priority first.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Tier {
42    /// Shared by every scene on this machine.
43    Global,
44    /// This product instance.
45    Scene,
46    /// This project.
47    Project,
48    /// `agixd --set`, `EmbedConfig::settings`: above every file, read as the global tier is.
49    Cli,
50    /// A session's own `options.settings`, over the tiers its project and scene merge.
51    Session,
52    /// The deployment's — see `settings::managed`: any settings key, over
53    /// every other layer, a session's own included.
54    Managed,
55}
56
57impl Tier {
58    pub fn name(self) -> &'static str {
59        match self {
60            Self::Global => "global",
61            Self::Scene => "scene",
62            Self::Project => "project",
63            Self::Cli => "cli",
64            Self::Session => "session",
65            Self::Managed => "managed",
66        }
67    }
68}
69
70/// One layer of configuration, already parsed.
71#[derive(Debug, Clone)]
72pub struct ConfigLayer {
73    pub tier: Tier,
74    /// Whether this is the per-machine overlay for its tier rather than the
75    /// shared settings.
76    ///
77    /// The merge treats the two identically but for one rule: the
78    /// `permissions` rule lists in an overlay are marked
79    /// `LoadedRule::machine_local`, apart from the shared
80    /// rules, because a rule nobody else on the team can see is not the same
81    /// kind of statement as one committed alongside the code.
82    pub machine_local: bool,
83    /// Where this layer came from, as something a person can act on — a path,
84    /// a URL, a config-map key. Only ever used in diagnostics.
85    pub origin: String,
86    pub value: serde_json::Value,
87}
88
89/// Where the settings layers come from.
90pub trait ConfigSource: Send + Sync {
91    /// Every layer this source has, lowest priority first.
92    fn layers(&self) -> Vec<ConfigLayer>;
93}
94
95/// Layers the host already has in hand.
96///
97/// This is what a deployment that keeps configuration somewhere other than a
98/// disk actually uses: fetch from the config service, the ConfigMap or the
99/// database, and hand the JSON over. It is also the whole of a test that wants
100/// a settings tree without a temporary directory.
101pub struct InMemoryLayers(pub Vec<ConfigLayer>);
102
103impl InMemoryLayers {
104    pub fn new() -> Self {
105        Self(Vec::new())
106    }
107
108    /// Append a layer above everything added so far.
109    pub fn with(
110        mut self,
111        tier: Tier,
112        machine_local: bool,
113        origin: impl Into<String>,
114        value: serde_json::Value,
115    ) -> Self {
116        self.0.push(ConfigLayer {
117            tier,
118            machine_local,
119            origin: origin.into(),
120            value,
121        });
122        self
123    }
124}
125
126impl Default for InMemoryLayers {
127    fn default() -> Self {
128        Self::new()
129    }
130}
131
132impl ConfigSource for InMemoryLayers {
133    fn layers(&self) -> Vec<ConfigLayer> {
134        self.0.clone()
135    }
136}
137
138/// Several sources end to end, each outranking the one before it.
139///
140/// The shape a remote deployment wants: `Chain(vec![files, from_control_plane])`
141/// keeps whatever is on the machine and lets the fleet-wide answer win.
142pub struct Chain(pub Vec<Arc<dyn ConfigSource>>);
143
144impl ConfigSource for Chain {
145    fn layers(&self) -> Vec<ConfigLayer> {
146        self.0.iter().flat_map(|s| s.layers()).collect()
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn a_chain_puts_later_sources_above_earlier_ones() {
156        let lower = Arc::new(InMemoryLayers::new().with(
157            Tier::Global,
158            false,
159            "lower",
160            serde_json::json!({"a": 1}),
161        ));
162        let upper = Arc::new(InMemoryLayers::new().with(
163            Tier::Project,
164            false,
165            "upper",
166            serde_json::json!({"a": 2}),
167        ));
168        let chain = Chain(vec![lower, upper]);
169
170        let origins: Vec<_> = chain.layers().into_iter().map(|l| l.origin).collect();
171        assert_eq!(origins, vec!["lower", "upper"]);
172    }
173}