Skip to main content

aft_base/
write_intent.rs

1//! Synchronous write intent around every AFT filesystem mutation.
2//!
3//! An intent is deliberately not cleared when a command fails: formatting,
4//! partial writes and rollback can all change bytes before the error returns.
5//! Only whoever indexes the paths may resolve it, by reading their bytes again.
6
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Mutex, OnceLock, Weak};
9
10/// Notifications bracket an AFT mutation: Before precedes any filesystem write;
11/// After runs when the guard drops, after formatting or rollback even on error.
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum WritePhase {
14    Before,
15    After,
16}
17
18/// Directory operations invalidate descendants, not just one indexed path.
19#[derive(Clone, Debug, Eq, PartialEq)]
20pub enum WriteIntent {
21    Paths(Vec<PathBuf>),
22    Directory(PathBuf),
23}
24
25/// The runtime uses this to invalidate trigram, semantic and callgraph data
26/// under its shared revision/snapshot lock. Listeners filter paths to their
27/// owning root. Callbacks must not write files, which would recurse into intent.
28pub trait WriteIntentListener: Send + Sync {
29    fn record_change(&self, change: &WriteIntent, phase: WritePhase);
30}
31
32fn listeners() -> &'static Mutex<Vec<Weak<dyn WriteIntentListener>>> {
33    static LISTENERS: OnceLock<Mutex<Vec<Weak<dyn WriteIntentListener>>>> = OnceLock::new();
34    LISTENERS.get_or_init(|| Mutex::new(Vec::new()))
35}
36
37/// Register a weak listener reference, so dropping the driver stops callbacks.
38pub fn register_listener(listener: &Arc<dyn WriteIntentListener>) {
39    let mut registered = listeners().lock().unwrap_or_else(|e| e.into_inner());
40    registered.retain(|listener| listener.strong_count() != 0);
41    registered.push(Arc::downgrade(listener));
42}
43
44fn notify(
45    registered: &[Weak<dyn WriteIntentListener>],
46    changes: &[WriteIntent],
47    phase: WritePhase,
48) {
49    for listener in registered {
50        if let Some(listener) = listener.upgrade() {
51            for change in changes {
52                listener.record_change(change, phase);
53            }
54        }
55    }
56}
57
58#[cfg(any(test, feature = "test-support"))]
59thread_local! {
60    pub static CLASSIFICATION_STATS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
61}
62
63fn is_directory(path: &Path) -> bool {
64    #[cfg(any(test, feature = "test-support"))]
65    CLASSIFICATION_STATS.with(|count| count.set(count.get() + 1));
66    path.is_dir()
67}
68
69/// Called before the first possible filesystem mutation, not after success.
70/// Directory intents invalidate the whole watcher epoch: their descendants
71/// (including newly created names) cannot safely be enumerated from an index.
72pub fn record_paths<'a>(paths: impl IntoIterator<Item = &'a Path>) -> IntentGuard {
73    let listener_snapshot = {
74        let mut registered = listeners().lock().unwrap_or_else(|e| e.into_inner());
75        registered.retain(|listener| listener.strong_count() != 0);
76        registered.clone()
77    };
78    if listener_snapshot.is_empty() {
79        return IntentGuard {
80            listeners: Vec::new(),
81            changes: Vec::new(),
82        };
83    }
84    let paths = paths
85        .into_iter()
86        .map(|path| (path, is_directory(path)))
87        .collect::<Vec<_>>();
88    let mut changes = paths
89        .iter()
90        .filter(|(_, is_dir)| *is_dir)
91        .map(|(path, _)| WriteIntent::Directory(path.to_path_buf()))
92        .collect::<Vec<_>>();
93    let files = paths
94        .iter()
95        .filter(|(_, is_dir)| !*is_dir)
96        .map(|(path, _)| path.to_path_buf())
97        .collect::<Vec<_>>();
98    if !files.is_empty() {
99        changes.push(WriteIntent::Paths(files));
100    }
101    notify(&listener_snapshot, &changes, WritePhase::Before);
102    IntentGuard {
103        listeners: listener_snapshot,
104        changes,
105    }
106}
107
108/// Keeps concurrent reconciliation from resolving pending intent or marking
109/// the watcher healthy while a filesystem mutation is still running.
110#[must_use]
111pub struct IntentGuard {
112    listeners: Vec<Weak<dyn WriteIntentListener>>,
113    changes: Vec<WriteIntent>,
114}
115
116impl Drop for IntentGuard {
117    fn drop(&mut self) {
118        notify(&self.listeners, &self.changes, WritePhase::After);
119    }
120}
121
122#[cfg(any(test, feature = "test-support"))]
123#[cfg_attr(not(test), allow(dead_code, unused_imports))]
124pub mod tests {
125    use super::*;
126
127    pub type Events = Arc<Mutex<Vec<(WriteIntent, WritePhase, Vec<u8>)>>>;
128    pub struct Listener {
129        pub root: PathBuf,
130        pub events: Events,
131    }
132    impl WriteIntentListener for Listener {
133        fn record_change(&self, change: &WriteIntent, phase: WritePhase) {
134            let paths = match change {
135                WriteIntent::Paths(paths) => paths.clone(),
136                WriteIntent::Directory(path) => vec![path.clone()],
137            };
138            if paths.iter().any(|path| path.starts_with(&self.root)) {
139                let bytes = paths
140                    .first()
141                    .and_then(|path| std::fs::read(path).ok())
142                    .unwrap_or_default();
143                self.events
144                    .lock()
145                    .unwrap()
146                    .push((change.clone(), phase, bytes));
147            }
148        }
149    }
150
151    #[test]
152    fn intent_paths_are_classified_once() {
153        let root = tempfile::tempdir().unwrap();
154        let path = root.path().join("new.rs");
155        let listener: Arc<dyn WriteIntentListener> = Arc::new(Listener {
156            root: root.path().to_path_buf(),
157            events: Arc::new(Mutex::new(Vec::new())),
158        });
159        register_listener(&listener);
160        CLASSIFICATION_STATS.with(|count| count.set(0));
161        let guard = record_paths([path.as_path()]);
162        assert_eq!(CLASSIFICATION_STATS.with(|count| count.get()), 1);
163        drop(guard);
164    }
165}