agentmux_srv_core/registry/
def_slug_index.rs1use std::collections::{HashMap, HashSet};
25use std::path::Path;
26use std::sync::{Arc, Mutex};
27use std::time::{Duration, SystemTime};
28
29use serde_json::Value;
30
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct SlugEntry {
36 pub slug: String,
37 pub former: Vec<String>,
38 pub display: Vec<String>,
39}
40
41const RACY_WINDOW: Duration = Duration::from_secs(3);
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46struct Stamp {
47 modified: Option<SystemTime>,
48 len: u64,
49}
50
51impl Stamp {
52 fn of(meta: &std::fs::Metadata) -> Stamp {
53 Stamp { modified: meta.modified().ok(), len: meta.len() }
54 }
55}
56
57struct Cached {
58 stamp: Stamp,
59 racy: bool,
61 slugs: Result<SlugEntry, String>,
63 valid: bool,
65}
66
67#[derive(Default)]
68struct State {
69 by_id: HashMap<String, Cached>,
70 unstatted: Vec<String>,
72 snapshot: Option<Arc<HashMap<String, SlugEntry>>>,
74 #[cfg(any(test, feature = "test-support"))]
75 parses: usize,
76}
77
78#[derive(Default)]
81pub(super) struct SlugIndex(Mutex<State>);
82
83impl SlugIndex {
84 pub fn invalidate(&self, id: &str) {
86 let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
87 s.by_id.remove(id);
88 s.snapshot = None;
89 }
90
91 pub fn all(&self, root: &Path) -> std::io::Result<Arc<HashMap<String, SlugEntry>>> {
93 let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
94 s.scan(root)?;
95 Ok(s.snapshot())
96 }
97
98 pub fn all_strict(&self, root: &Path) -> Result<HashMap<String, SlugEntry>, String> {
101 let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
102 s.scan(root).map_err(|e| format!("{} can't be listed: {e}", root.display()))?;
103 if let Some(file) = s.unstatted.first() {
104 return Err(format!("{file} can't be read"));
105 }
106 s.by_id
107 .iter()
108 .map(|(id, c)| match &c.slugs {
109 Ok(entry) => Ok((id.clone(), entry.clone())),
110 Err(why) => Err(format!("{id}.json: {why}")),
111 })
112 .collect()
113 }
114
115 pub fn one(&self, root: &Path, id: &str) -> std::io::Result<Option<SlugEntry>> {
117 let path = root.join(format!("{id}.json"));
118 let meta = match std::fs::metadata(&path) {
119 Ok(m) if m.is_file() => m,
120 Ok(_) => return Ok(None),
121 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
122 self.invalidate(id);
123 return Ok(None);
124 }
125 Err(e) => return Err(e),
126 };
127 let mut s = self.0.lock().unwrap_or_else(|e| e.into_inner());
128 s.refresh(id, &path, Stamp::of(&meta));
129 Ok(s.by_id.get(id).filter(|c| c.valid).and_then(|c| c.slugs.clone().ok()))
130 }
131
132 #[cfg(test)]
133 pub fn parses(&self) -> usize {
134 self.0.lock().unwrap().parses
135 }
136}
137
138impl State {
139 fn scan(&mut self, root: &Path) -> std::io::Result<()> {
142 let mut seen = HashSet::new();
143 self.unstatted.clear();
144 for dirent in std::fs::read_dir(root)? {
145 let path = dirent?.path();
146 if path.extension().and_then(|e| e.to_str()) != Some("json") || super::atomic::is_temp_file(&path) {
147 continue;
148 }
149 let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_string) else {
150 continue;
151 };
152 let meta = match std::fs::metadata(&path) {
154 Ok(meta) => meta,
155 Err(e) => {
156 self.unstatted.push(format!("{} ({e})", path.display()));
157 continue;
158 }
159 };
160 if !meta.is_file() {
161 continue;
162 }
163 self.refresh(&id, &path, Stamp::of(&meta));
164 seen.insert(id);
165 }
166 let before = self.by_id.len();
167 self.by_id.retain(|id, _| seen.contains(id));
168 if self.by_id.len() != before {
169 self.snapshot = None;
170 }
171 Ok(())
172 }
173
174 fn refresh(&mut self, id: &str, path: &Path, stamp: Stamp) {
175 if matches!(self.by_id.get(id), Some(c) if c.stamp == stamp && !c.racy) {
176 return;
177 }
178 let parsed_at = SystemTime::now();
179 let (slugs, valid) = match std::fs::read(path) {
180 Ok(bytes) => {
181 let valid = match super::def_store::parse_and_validate(&bytes, id) {
182 Ok(_) => true,
183 Err(e) => {
184 tracing::warn!(file = %path.display(), error = %e, "def registry: skipping invalid record");
185 false
186 }
187 };
188 (slug_fields(id, &bytes), valid)
189 }
190 Err(e) => (Err(format!("can't be read: {e}")), false),
191 };
192 #[cfg(any(test, feature = "test-support"))]
193 {
194 self.parses += 1;
195 }
196 let racy = stamp.modified.is_none_or(|m| parsed_at.duration_since(m).map_or(true, |age| age < RACY_WINDOW));
197 let changed = self.by_id.get(id).is_none_or(|c| c.slugs != slugs || c.valid != valid);
198 self.by_id.insert(id.to_string(), Cached { stamp, racy, slugs, valid });
199 if changed {
200 self.snapshot = None;
201 }
202 }
203
204 fn snapshot(&mut self) -> Arc<HashMap<String, SlugEntry>> {
205 self.snapshot
206 .get_or_insert_with(|| {
207 Arc::new(
208 self.by_id
209 .iter()
210 .filter(|(_, c)| c.valid)
211 .filter_map(|(id, c)| c.slugs.clone().ok().map(|e| (id.clone(), e)))
212 .collect(),
213 )
214 })
215 .clone()
216 }
217}
218
219pub(super) fn slug_fields(id: &str, bytes: &[u8]) -> Result<SlugEntry, String> {
228 let json: Value = serde_json::from_slice(bytes).map_err(|e| format!("not JSON ({e})"))?;
229 let data = json.get("data").and_then(Value::as_object).ok_or("no `data` object")?;
230 if data.get("id").and_then(Value::as_str) != Some(id) {
231 return Err("its `data.id` doesn't name this file".to_string());
232 }
233 let slug = match data.get("slug") {
234 None | Some(Value::Null) => String::new(),
235 Some(Value::String(s)) => s.clone(),
236 Some(_) => return Err("`data.slug` isn't a string".to_string()),
237 };
238 let former = match data.get("former_slugs") {
239 None | Some(Value::Null) => Vec::new(),
240 Some(Value::Array(entries)) => entries
241 .iter()
242 .map(|f| f.get("slug").and_then(Value::as_str).map(str::to_string))
243 .collect::<Option<Vec<_>>>()
244 .ok_or("a `data.former_slugs` entry has no string `slug`")?,
245 Some(_) => return Err("`data.former_slugs` isn't a list".to_string()),
246 };
247 let display = ["name", "branch_label"]
248 .iter()
249 .filter_map(|k| data.get(*k).and_then(Value::as_str))
250 .filter(|s| !s.trim().is_empty())
251 .map(str::to_string)
252 .collect();
253 Ok(SlugEntry { slug, former, display })
254}