Skip to main content

aft_base/
config_sources.rs

1//! Recorded configuration tiers and the paths that supplied them.
2
3use std::path::{Path, PathBuf};
4use std::sync::OnceLock;
5
6use crate::config::Config;
7use crate::config_resolve::ConfigTier;
8
9/// What one tier's text was when it was last applied, and where it lives.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct TierSource {
12    /// `user` or `project`.
13    pub tier: &'static str,
14    /// The config file for this tier, when known.
15    pub path: Option<PathBuf>,
16    /// The text applied last, or `None` when the tier was absent.
17    pub text: Option<String>,
18    /// Whether `text` was read from `path`. A tier relayed on the wire by an
19    /// older plugin whose file does not exist is kept as it is.
20    pub from_file: bool,
21}
22
23/// What the last configure applied for a root, so a reload can tell whether
24/// the files changed and which changed keys are still waiting for a connect.
25#[derive(Debug, Clone)]
26pub struct ConfigSources {
27    pub prepared_bind_snapshot_id: Option<u64>,
28    pub approved_user: Option<crate::subc_config::ApprovedUser>,
29    pub user: TierSource,
30    pub project: TierSource,
31    /// The resolver output of the last configure, before configure's own
32    /// adjustments. Deferred keys are reported relative to it.
33    pub connected: Config,
34    /// Whether this root's context watches the user file itself. False in the
35    /// daemon, where one process-level watch serves every root.
36    pub owns_user_watch: bool,
37}
38
39impl ConfigSources {
40    /// Record what configure resolved from. `tiers` is what configure passed to
41    /// the resolver: a tier whose `source` names the tier's file was read from
42    /// that file (the daemon's bind reads the files and relays them this way).
43    pub fn from_configure(
44        user_config_path: Option<PathBuf>,
45        project_root: &Path,
46        tiers: &[ConfigTier],
47        connected: &Config,
48    ) -> Self {
49        let project_path =
50            crate::subc_config::project_config_read_path(project_root, connected.harness.as_ref());
51        Self::from_observed_paths(user_config_path, project_path, tiers, connected)
52    }
53
54    /// Record the source paths selected by a trusted local observation without
55    /// probing them again. Reload must watch the same files that supplied tiers.
56    pub(crate) fn from_observed_paths(
57        user_config_path: Option<PathBuf>,
58        project_path: PathBuf,
59        tiers: &[ConfigTier],
60        connected: &Config,
61    ) -> Self {
62        let owns_user_watch = user_config_path.is_some() && process_user_config_path().is_none();
63        let user_path = user_config_path.or_else(process_user_config_path);
64        let source_for = |tier: &'static str, path: Option<PathBuf>| {
65            let used = tiers.iter().find(|candidate| candidate.tier == tier);
66            let from_file = match (used, path.as_ref()) {
67                (Some(used), Some(path)) => Path::new(&used.source) == path.as_path(),
68                (None, _) => true,
69                (Some(_), None) => false,
70            };
71            TierSource {
72                tier,
73                path,
74                text: used.map(|used| used.doc.clone()),
75                from_file,
76            }
77        };
78        Self {
79            prepared_bind_snapshot_id: None,
80            approved_user: None,
81            user: source_for("user", user_path),
82            project: source_for("project", Some(project_path)),
83            connected: connected.clone(),
84            owns_user_watch,
85        }
86    }
87}
88
89static PROCESS_USER_CONFIG_PATH: OnceLock<PathBuf> = OnceLock::new();
90
91/// The daemon watches the user config file once for the whole process and
92/// records its path here, so root contexts do not each start a watch.
93pub fn set_process_user_config_path(path: PathBuf) {
94    let _ = PROCESS_USER_CONFIG_PATH.set(path);
95}
96
97fn process_user_config_path() -> Option<PathBuf> {
98    PROCESS_USER_CONFIG_PATH.get().cloned()
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn observed_sources_keep_exact_paths_and_distinguish_relayed_text() {
107        let user = PathBuf::from("user.jsonc");
108        let project = PathBuf::from("project.jsonc");
109        let config = Config::default();
110        let tiers = vec![
111            ConfigTier {
112                tier: "user".into(),
113                source: "user.jsonc".into(),
114                doc: "{}".into(),
115            },
116            ConfigTier {
117                tier: "project".into(),
118                source: "wire".into(),
119                doc: "{ }".into(),
120            },
121        ];
122        let sources = ConfigSources::from_observed_paths(
123            Some(user.clone()),
124            project.clone(),
125            &tiers,
126            &config,
127        );
128        assert_eq!(sources.user.path, Some(user));
129        assert_eq!(sources.project.path, Some(project));
130        assert_eq!(sources.user.text.as_deref(), Some("{}"));
131        assert_eq!(sources.project.text.as_deref(), Some("{ }"));
132        assert!(sources.user.from_file);
133        assert!(!sources.project.from_file);
134        assert_eq!(sources.prepared_bind_snapshot_id, None);
135    }
136
137    #[test]
138    fn absent_tiers_record_absent_text_as_file_backed() {
139        let sources = ConfigSources::from_observed_paths(
140            Some(PathBuf::from("user.jsonc")),
141            PathBuf::from("project.jsonc"),
142            &[],
143            &Config::default(),
144        );
145        assert_eq!(sources.user.text, None);
146        assert_eq!(sources.project.text, None);
147        assert!(sources.user.from_file);
148        assert!(sources.project.from_file);
149    }
150}