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 manifest: BTreeSet<String> = workspace
198 .mounts
199 .iter()
200 .filter(|m| m.capability == crate::workspace::MountCapability::Write)
201 .map(|m| m.mem.clone())
202 .collect();
203 let mounted: BTreeSet<String> = self
204 .mounts
205 .iter()
206 .filter(|m| m.mount.capability == crate::workspace::MountCapability::Write)
207 .map(|m| m.mount.mem.clone())
208 .collect();
209 let quarantined_now: BTreeSet<String> = self
210 .quarantined
211 .iter()
212 .map(|q| q.mount.mem.clone())
213 .collect();
214
215 let mut change = RosterChange::default();
216 let mut all_applied = true;
217
218 let mut schema_report = crate::ops::FullRefreshReport::default();
222 self.refresh_schema_sources(&mut schema_report);
223 change.failures.extend(schema_report.failures);
224
225 for name in mounted.difference(&manifest) {
228 match self.unmount_mem(name) {
229 Ok(()) => change.removed.push(name.clone()),
230 Err(e) => {
231 all_applied = false;
232 change.failures.push(crate::ops::RefreshFailure {
233 item: format!("unmount:{name}"),
234 error: e.to_string(),
235 });
236 }
237 }
238 }
239 let gone_quarantined: Vec<String> =
240 quarantined_now.difference(&manifest).cloned().collect();
241 if !gone_quarantined.is_empty() {
242 self.quarantined
243 .retain(|q| !gone_quarantined.contains(&q.mount.mem));
244 change.removed.extend(gone_quarantined);
245 }
246
247 let mut any_mounted = false;
249 for mount in workspace.mounts {
250 if mount.capability != crate::workspace::MountCapability::Write
251 || mounted.contains(&mount.mem)
252 || quarantined_now.contains(&mount.mem)
253 {
254 continue;
255 }
256 let name = mount.mem.clone();
257 let backend = match (self.backend_factory)(&mount) {
258 Ok(b) => b,
259 Err(e) => {
260 self.quarantine_mount(mount, e.code(), e.to_string());
261 change.quarantined.push(name);
262 continue;
263 }
264 };
265 if let Some(crate::ops::WarningHint::MountUnbacked { reason, .. }) =
269 super::boot::unbacked_mount_warning(&mount, backend.as_ref(), None)
270 && reason != crate::ops::MountUnbackedReason::Empty
271 {
272 let location = match &mount.storage {
273 crate::workspace::MountStorage::GitBranch { branch, .. } => branch.clone(),
274 crate::workspace::MountStorage::Folder { path }
275 | crate::workspace::MountStorage::Archive { path } => {
276 path.display().to_string()
277 }
278 crate::workspace::MountStorage::InMemory => String::new(),
279 };
280 self.quarantine_mount(
281 mount,
282 "MOUNT_UNBACKED",
283 format!(
284 "the mount's storage is gone ({location}); it is configured but cannot \
285 serve, so it is held out of the roster rather than answering reads \
286 with an empty graph"
287 ),
288 );
289 change.quarantined.push(name);
290 continue;
291 }
292 match self.register_writable_mem_batched(
293 mount.clone(),
294 backend,
295 crate::mem::MemOrigin::ExplicitToml,
296 ) {
297 Ok(()) => {
298 any_mounted = true;
299 self.recently_unmounted.remove(&name);
300 change.added.push(name);
301 }
302 Err(e) => {
303 self.quarantine_mount(mount, e.code(), e.to_string());
304 change.quarantined.push(name);
305 }
306 }
307 }
308 if any_mounted {
309 self.finish_batched_registrations();
310 }
311
312 if all_applied {
313 self.roster_fingerprint = Some(now);
314 }
315 self.invalidate_communities();
316 self.invalidate_search_indexes();
317 self.emit_roster_changed(&change);
318 Ok(change)
319 }
320
321 fn quarantine_mount(&mut self, mount: crate::workspace::Mount, code: &str, message: String) {
322 self.quarantined.push(super::QuarantinedMem {
323 mount,
324 reason_code: code.to_string(),
325 reason_message: message,
326 });
327 }
328
329 pub(crate) fn unmount_mem(&mut self, mem: &str) -> Result<(), EngineError> {
336 #[cfg(test)]
337 if self.inject_unmount_failure.as_deref() == Some(mem) {
338 return Err(EngineError::Backend(crate::backend::BackendError::Other(
339 format!("injected unmount failure for mem `{mem}`"),
340 )));
341 }
342 let removed = self.unregister_writable_mem(mem)?;
343 if removed.is_none() {
344 self.quarantined.retain(|q| q.mount.mem != mem);
346 }
347 self.pending_mem_changed.retain(|n| n.mem != mem);
348 self.labelling_memo = std::cell::OnceCell::new();
349 self.recently_unmounted.insert(mem.to_string());
350 Ok(())
351 }
352
353 pub fn recently_unmounted(&self, mem: &str) -> bool {
356 self.recently_unmounted.contains(mem)
357 }
358
359 pub fn subscribe_roster_changes(&self, callback: RosterCallback) -> u64 {
362 let mut subs = self
363 .roster_subscribers
364 .lock()
365 .expect("roster subscriber registry mutex must not be poisoned");
366 let id = subs.0 + 1;
367 subs.0 = id;
368 subs.1.push((id, callback));
369 id
370 }
371
372 pub fn unsubscribe_roster_changes(&self, id: u64) {
374 let mut subs = self
375 .roster_subscribers
376 .lock()
377 .expect("roster subscriber registry mutex must not be poisoned");
378 subs.1.retain(|(slot, _)| *slot != id);
379 }
380
381 fn emit_roster_changed(&self, change: &RosterChange) {
382 if change.is_empty() {
383 return;
384 }
385 let callbacks: Vec<RosterCallback> = self
386 .roster_subscribers
387 .lock()
388 .expect("roster subscriber registry mutex must not be poisoned")
389 .1
390 .iter()
391 .map(|(_, cb)| cb.clone())
392 .collect();
393 for cb in callbacks {
394 cb(change);
395 }
396 }
397
398 pub fn writable_mem_set(&self) -> HashSet<String> {
401 self.mounts
402 .iter()
403 .filter(|m| m.mount.capability == crate::workspace::MountCapability::Write)
404 .map(|m| m.mount.mem.clone())
405 .collect()
406 }
407}