memstead_base/engine/
roster.rs1use std::collections::{BTreeSet, HashSet};
20use std::path::PathBuf;
21use std::sync::Arc;
22
23use serde::{Deserialize, Serialize};
24
25use super::{Engine, EngineError};
26
27#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct RosterFingerprint {
31 len: u64,
32 modified: Option<std::time::SystemTime>,
33 hash: u64,
34}
35
36#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
38pub struct RosterChange {
39 pub added: Vec<String>,
41 pub removed: Vec<String>,
44 pub quarantined: Vec<String>,
48 pub failures: Vec<crate::ops::RefreshFailure>,
52}
53
54impl RosterChange {
55 pub fn is_empty(&self) -> bool {
57 self.added.is_empty()
58 && self.removed.is_empty()
59 && self.quarantined.is_empty()
60 && self.failures.is_empty()
61 }
62}
63
64pub type RosterChangedEvent = RosterChange;
66
67pub type RosterCallback = Arc<dyn Fn(&RosterChangedEvent) + Send + Sync + 'static>;
70
71pub(crate) type RosterSubscribers = std::sync::Mutex<(u64, Vec<(u64, RosterCallback)>)>;
73
74fn hash_bytes(bytes: &[u8]) -> u64 {
75 use std::hash::{Hash, Hasher};
76 let mut h = std::collections::hash_map::DefaultHasher::new();
77 bytes.hash(&mut h);
78 h.finish()
79}
80
81impl Engine {
82 fn roster_path(&self) -> Option<PathBuf> {
85 self.workspace_root.as_ref().map(|root| {
86 root.join(crate::workspace_store::WORKSPACE_STORE_DIR)
87 .join("state")
88 .join("mounts.json")
89 })
90 }
91
92 fn roster_fingerprint_now(&self) -> Result<Option<RosterFingerprint>, std::io::Error> {
97 let Some(path) = self.roster_path() else {
98 return Ok(None);
99 };
100 let meta = match std::fs::metadata(&path) {
101 Ok(m) => m,
102 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
103 Err(e) => return Err(e),
104 };
105 let len = meta.len();
106 let modified = meta.modified().ok();
107 if let Some(cached) = &self.roster_fingerprint
108 && cached.len == len
109 && cached.modified == modified
110 {
111 return Ok(Some(cached.clone()));
112 }
113 let bytes = std::fs::read(&path)?;
114 Ok(Some(RosterFingerprint {
115 len,
116 modified,
117 hash: hash_bytes(&bytes),
118 }))
119 }
120
121 pub(crate) fn capture_roster_fingerprint(&mut self) {
124 self.roster_fingerprint = self.roster_fingerprint_now().ok().flatten();
125 }
126
127 pub fn reconcile_roster(&mut self) -> Result<Option<RosterChange>, EngineError> {
146 let now = self.roster_fingerprint_now().map_err(|e| {
147 EngineError::Backend(crate::backend::BackendError::Other(format!(
148 "roster unreadable: {e}"
149 )))
150 })?;
151 let Some(now) = now else {
152 return Ok(None);
153 };
154 let Some(cached) = self.roster_fingerprint.clone() else {
155 return self.apply_roster(now).map(Some);
157 };
158 if cached.hash == now.hash {
159 self.roster_fingerprint = Some(now);
160 return Ok(None);
161 }
162 self.apply_roster(now).map(Some)
163 }
164
165 pub(crate) fn reconcile_roster_forced(&mut self) -> Result<RosterChange, EngineError> {
170 let now = self.roster_fingerprint_now().map_err(|e| {
171 EngineError::Backend(crate::backend::BackendError::Other(format!(
172 "roster unreadable: {e}"
173 )))
174 })?;
175 match now {
176 Some(now) => self.apply_roster(now),
177 None => Ok(RosterChange::default()),
178 }
179 }
180
181 fn apply_roster(&mut self, now: RosterFingerprint) -> Result<RosterChange, EngineError> {
182 let root = self
183 .workspace_root
184 .clone()
185 .expect("a roster fingerprint implies a workspace root");
186 let workspace = crate::workspace_store::WorkspaceStoreAdapter::load(
187 &crate::workspace_store::FileWorkspaceStore::new(),
188 &root,
189 )
190 .map_err(|e| {
191 EngineError::Backend(crate::backend::BackendError::Other(format!(
192 "roster under {} unreadable: {e}",
193 root.display()
194 )))
195 })?;
196
197 let cross_mem_links = workspace.settings.cross_mem_links.clone();
198 let manifest: BTreeSet<String> = workspace
199 .mounts
200 .iter()
201 .filter(|m| m.capability == crate::workspace::MountCapability::Write)
202 .map(|m| m.mem.clone())
203 .collect();
204 let mounted: BTreeSet<String> = self
205 .mounts
206 .iter()
207 .filter(|m| m.mount.capability == crate::workspace::MountCapability::Write)
208 .map(|m| m.mount.mem.clone())
209 .collect();
210 let quarantined_now: BTreeSet<String> = self
211 .quarantined
212 .iter()
213 .map(|q| q.mount.mem.clone())
214 .collect();
215
216 let mut change = RosterChange::default();
217 let mut all_applied = true;
218
219 let mut schema_report = crate::ops::FullRefreshReport::default();
223 self.refresh_schema_sources(&mut schema_report);
224 change.failures.extend(schema_report.failures);
225
226 for name in mounted.difference(&manifest) {
229 match self.unmount_mem(name) {
230 Ok(()) => change.removed.push(name.clone()),
231 Err(e) => {
232 all_applied = false;
233 change.failures.push(crate::ops::RefreshFailure {
234 item: format!("unmount:{name}"),
235 error: e.to_string(),
236 });
237 }
238 }
239 }
240 let gone_quarantined: Vec<String> =
241 quarantined_now.difference(&manifest).cloned().collect();
242 if !gone_quarantined.is_empty() {
243 self.quarantined
244 .retain(|q| !gone_quarantined.contains(&q.mount.mem));
245 change.removed.extend(gone_quarantined);
246 }
247
248 let mut any_mounted = false;
250 for mount in workspace.mounts {
251 if mount.capability != crate::workspace::MountCapability::Write
252 || mounted.contains(&mount.mem)
253 || quarantined_now.contains(&mount.mem)
254 {
255 continue;
256 }
257 let name = mount.mem.clone();
258 let backend = match (self.backend_factory)(&mount) {
259 Ok(b) => b,
260 Err(e) => {
261 self.quarantine_mount(mount, e.code(), e.to_string());
262 change.quarantined.push(name);
263 continue;
264 }
265 };
266 if let Some(crate::ops::WarningHint::MountUnbacked { reason, .. }) =
270 super::boot::unbacked_mount_warning(&mount, backend.as_ref())
271 && reason != crate::ops::MountUnbackedReason::Empty
272 {
273 let (code, message) = super::boot::missing_storage_reason(&mount);
274 self.quarantine_mount(mount, &code, message);
275 change.quarantined.push(name);
276 continue;
277 }
278 match self.register_writable_mem_batched(
279 mount.clone(),
280 backend,
281 crate::mem::MemOrigin::ExplicitToml,
282 ) {
283 Ok(()) => {
284 any_mounted = true;
285 self.recently_unmounted.remove(&name);
286 change.added.push(name);
287 }
288 Err(e) => {
289 self.quarantine_mount(mount, e.code(), e.to_string());
290 change.quarantined.push(name);
291 }
292 }
293 }
294 if any_mounted {
295 self.finish_batched_registrations();
296 }
297
298 let mut current = self.settings().clone();
303 current.cross_mem_links = cross_mem_links;
304 self.set_settings(current);
305 if all_applied {
306 self.roster_fingerprint = Some(now);
307 }
308 self.invalidate_communities();
309 self.invalidate_search_indexes();
310 self.emit_roster_changed(&change);
311 Ok(change)
312 }
313
314 fn quarantine_mount(&mut self, mount: crate::workspace::Mount, code: &str, message: String) {
315 self.quarantined.push(super::QuarantinedMem {
316 mount,
317 reason_code: code.to_string(),
318 reason_message: message,
319 });
320 }
321
322 pub(crate) fn unmount_mem(&mut self, mem: &str) -> Result<(), EngineError> {
329 #[cfg(test)]
330 if self.inject_unmount_failure.as_deref() == Some(mem) {
331 return Err(EngineError::Backend(crate::backend::BackendError::Other(
332 format!("injected unmount failure for mem `{mem}`"),
333 )));
334 }
335 let removed = self.unregister_writable_mem(mem)?;
336 if removed.is_none() {
337 self.quarantined.retain(|q| q.mount.mem != mem);
339 }
340 self.pending_mem_changed.retain(|n| n.mem != mem);
341 self.labelling_memo = std::cell::OnceCell::new();
342 self.recently_unmounted.insert(mem.to_string());
343 Ok(())
344 }
345
346 pub fn recently_unmounted(&self, mem: &str) -> bool {
349 self.recently_unmounted.contains(mem)
350 }
351
352 pub fn subscribe_roster_changes(&self, callback: RosterCallback) -> u64 {
355 let mut subs = self
356 .roster_subscribers
357 .lock()
358 .expect("roster subscriber registry mutex must not be poisoned");
359 let id = subs.0 + 1;
360 subs.0 = id;
361 subs.1.push((id, callback));
362 id
363 }
364
365 pub fn unsubscribe_roster_changes(&self, id: u64) {
367 let mut subs = self
368 .roster_subscribers
369 .lock()
370 .expect("roster subscriber registry mutex must not be poisoned");
371 subs.1.retain(|(slot, _)| *slot != id);
372 }
373
374 fn emit_roster_changed(&self, change: &RosterChange) {
375 if change.is_empty() {
376 return;
377 }
378 let callbacks: Vec<RosterCallback> = self
379 .roster_subscribers
380 .lock()
381 .expect("roster subscriber registry mutex must not be poisoned")
382 .1
383 .iter()
384 .map(|(_, cb)| cb.clone())
385 .collect();
386 for cb in callbacks {
387 cb(change);
388 }
389 }
390
391 pub fn writable_mem_set(&self) -> HashSet<String> {
394 self.mounts
395 .iter()
396 .filter(|m| m.mount.capability == crate::workspace::MountCapability::Write)
397 .map(|m| m.mount.mem.clone())
398 .collect()
399 }
400}