aft_base/subc_config/
bind_cache.rs1use super::prepared::{unknown, ConfigObservationError, CONFIG_FILE_LIMIT};
2use super::{read_bounded_config, ConfigTier, UserConfigMigration};
3use crate::config_resolve::ParsedConfigDocument;
4use crate::file_identity::{self, FileIdentity};
5use std::collections::HashMap;
6use std::fs::Permissions;
7use std::io::ErrorKind;
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10use std::time::{Duration, SystemTime};
11
12#[derive(PartialEq, Eq)]
13struct FileStamp {
14 modified: SystemTime,
15 size: u64,
16 identity: FileIdentity,
17 permissions: Permissions,
18}
19
20impl FileStamp {
21 fn read(path: &Path, now: SystemTime) -> std::io::Result<Option<Self>> {
22 let (meta, identity) = file_identity::metadata(path)?;
23 if !meta.is_file() || identity == FileIdentity::Unavailable {
24 return Ok(None);
25 }
26 let modified = meta.modified()?;
27 if !now
30 .duration_since(modified)
31 .is_ok_and(|age| age > Duration::from_secs(2))
32 {
33 return Ok(None);
34 }
35 Ok(Some(Self {
36 modified,
37 size: meta.len(),
38 identity,
39 permissions: meta.permissions(),
40 }))
41 }
42}
43
44pub(super) struct ParsedFile {
45 pub(super) tier: ConfigTier,
46 pub(super) document: ParsedConfigDocument,
47}
48
49impl ParsedFile {
50 pub(super) fn new(tier: ConfigTier) -> Arc<Self> {
51 let document = ParsedConfigDocument::new(&tier);
52 Arc::new(Self { tier, document })
53 }
54}
55
56pub(super) struct ObservedFile {
57 pub(super) parsed: Arc<ParsedFile>,
58 stamp: Option<(PathBuf, FileStamp)>,
59}
60
61impl ObservedFile {
62 pub(super) fn approved(tier: ConfigTier) -> Self {
63 Self {
64 parsed: ParsedFile::new(tier),
65 stamp: None,
66 }
67 }
68}
69
70struct CachedFile {
71 stamp: FileStamp,
72 root: Option<PathBuf>,
73 parsed: Arc<ParsedFile>,
74}
75
76#[derive(Default)]
79pub struct BindConfigCache {
80 files: HashMap<PathBuf, CachedFile>,
81 #[cfg(any(test, feature = "test-support"))]
82 file_parses: usize,
83 #[cfg(test)]
84 now: Option<SystemTime>,
85}
86
87impl BindConfigCache {
88 pub fn release_project(&mut self, root: &Path) {
89 self.files
90 .retain(|_, entry| entry.root.as_deref() != Some(root));
91 }
92
93 #[cfg(any(test, feature = "test-support"))]
94 pub fn file_parses(&self) -> usize {
95 self.file_parses
96 }
97
98 fn now(&self) -> SystemTime {
99 #[cfg(test)]
100 if let Some(now) = self.now {
101 return now;
102 }
103 SystemTime::now()
104 }
105
106 pub(super) fn observe(
107 &mut self,
108 path: &Path,
109 root: Option<&Path>,
110 ) -> Result<(Option<ObservedFile>, Option<UserConfigMigration>), ConfigObservationError> {
111 let now = self.now();
112 let stamp = match FileStamp::read(path, now) {
113 Ok(stamp) => stamp,
114 Err(error) if error.kind() == ErrorKind::NotFound => {
115 self.files.remove(path);
116 return Ok((None, None));
117 }
118 Err(_) => None,
121 };
122 if let Some(entry) = self
123 .files
124 .get(path)
125 .filter(|entry| Some(&entry.stamp) == stamp.as_ref() && entry.root.as_deref() == root)
126 {
127 return Ok((
128 Some(ObservedFile {
129 parsed: entry.parsed.clone(),
130 stamp: None,
131 }),
132 None,
133 ));
134 }
135 self.files.remove(path);
136 let tier = if root.is_some() { "project" } else { "user" };
137 let Some(mut doc) = read_file(path)? else {
138 return Ok((None, None));
139 };
140 let migration = if tier == "user" {
141 let migration =
142 crate::config_fix::auto_migrate_user_config_bounded(path, CONFIG_FILE_LIMIT)
143 .map_err(|error| unknown(path, &error))?;
144 let Some(after) = read_file(path)? else {
145 return Ok((None, migration));
146 };
147 doc = after;
148 migration
149 } else {
150 None
151 };
152 let stamp = stamp.filter(|stamp| {
156 migration.is_none() && FileStamp::read(path, now).ok().flatten().as_ref() == Some(stamp)
157 });
158 #[cfg(any(test, feature = "test-support"))]
159 {
160 self.file_parses += 1;
161 }
162 let parsed = ParsedFile::new(ConfigTier {
163 tier: tier.into(),
164 source: path.to_string_lossy().into_owned(),
165 doc,
166 });
167 Ok((
168 Some(ObservedFile {
169 parsed,
170 stamp: stamp.map(|stamp| (path.to_owned(), stamp)),
171 }),
172 migration,
173 ))
174 }
175
176 pub(super) fn remember(&mut self, observation: ObservedFile, root: Option<&Path>) {
179 if let Some((path, stamp)) = observation.stamp {
180 self.files.insert(
181 path,
182 CachedFile {
183 stamp,
184 root: root.map(Path::to_owned),
185 parsed: observation.parsed,
186 },
187 );
188 }
189 }
190}
191
192fn read_file(path: &Path) -> Result<Option<String>, ConfigObservationError> {
193 let file = match crate::config::open_config_file(path) {
195 Ok(file) => file,
196 Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
197 Err(error) => return Err(unknown(path, &error)),
198 };
199 read_bounded_config(file, CONFIG_FILE_LIMIT)
200 .map(Some)
201 .map_err(|error| unknown(path, &error))
202}
203
204#[cfg(test)]
205mod tests;