Skip to main content

arbor_graph/
store.rs

1use crate::builder::GraphBuilder;
2use crate::graph::ArborGraph;
3use arbor_core::CodeNode;
4use sled::{Batch, Db};
5use std::path::Path;
6use std::time::{Duration, Instant};
7use thiserror::Error;
8
9/// Current cache format version. The cache stores parser output, so a change
10/// to what the parsers extract must invalidate it too, not only a release:
11/// bump `extract-N` whenever extracted nodes or references change shape.
12/// (Revision 2: Rust calls are normalized to `module::fn` / `Type::fn` /
13/// `self.m` / `.m`, and calls inside macros are recorded. Revision 4: TS/JS
14/// test and hook callbacks become `it: <title>` nodes that own their calls.)
15///
16/// The CLI also stamps saved graphs with it, so a graph built by a different
17/// extractor is rebuilt rather than reused after an upgrade.
18pub const CACHE_VERSION: &str = concat!("arbor-", env!("CARGO_PKG_VERSION"), "+extract-4");
19
20#[derive(Error, Debug)]
21pub enum StoreError {
22    #[error("Database error: {0}")]
23    Sled(#[from] sled::Error),
24    #[error("Serialization error: {0}")]
25    Bincode(#[from] bincode::Error),
26    #[error("Corrupted data: {0}")]
27    Corrupted(String),
28    #[error("Cache version mismatch: expected {expected}, found {found}")]
29    VersionMismatch { expected: String, found: String },
30}
31
32pub struct GraphStore {
33    db: Db,
34}
35
36impl GraphStore {
37    /// Opens or creates a graph store at the specified path.
38    /// Returns an error if the cache version doesn't match.
39    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, StoreError> {
40        let db = open_db(path.as_ref())?;
41        match stored_version(&db)? {
42            Some(found) if found != CACHE_VERSION => Err(StoreError::VersionMismatch {
43                expected: CACHE_VERSION.to_string(),
44                found,
45            }),
46            Some(_) => Ok(Self { db }),
47            None => {
48                set_version(&db)?;
49                Ok(Self { db })
50            }
51        }
52    }
53
54    /// Opens a store, clearing it if version mismatches.
55    ///
56    /// Everything goes through one handle. Dropping a sled handle releases
57    /// the directory lock only when its flusher thread exits, so re-opening
58    /// straight after `open` reported a mismatch could fail with "could not
59    /// acquire lock", on the first run after an upgrade.
60    pub fn open_or_reset<P: AsRef<Path>>(path: P) -> Result<Self, StoreError> {
61        let db = open_db(path.as_ref())?;
62        match stored_version(&db)? {
63            Some(found) if found == CACHE_VERSION => {}
64            Some(_) => {
65                db.clear()?;
66                set_version(&db)?;
67                db.flush()?;
68            }
69            None => set_version(&db)?,
70        }
71        Ok(Self { db })
72    }
73
74    /// Gets the stored mtime for a file.
75    pub fn get_mtime(&self, file_path: &str) -> Result<Option<u64>, StoreError> {
76        let key = format!("m:{}", file_path);
77        match self.db.get(&key)? {
78            Some(bytes) => {
79                let mtime: u64 = bincode::deserialize(&bytes)?;
80                Ok(Some(mtime))
81            }
82            None => Ok(None),
83        }
84    }
85
86    /// Gets the stored nodes for a file.
87    pub fn get_file_nodes(&self, file_path: &str) -> Result<Option<Vec<CodeNode>>, StoreError> {
88        let file_key = format!("f:{}", file_path);
89        match self.db.get(&file_key)? {
90            Some(index_bytes) => {
91                let node_ids: Vec<String> = bincode::deserialize(&index_bytes)?;
92                let mut nodes = Vec::with_capacity(node_ids.len());
93                for id in node_ids {
94                    let node_key = format!("n:{}", id);
95                    if let Some(node_bytes) = self.db.get(&node_key)? {
96                        let node: CodeNode = bincode::deserialize(&node_bytes)?;
97                        nodes.push(node);
98                    }
99                }
100                Ok(Some(nodes))
101            }
102            None => Ok(None),
103        }
104    }
105
106    /// Updates the nodes and mtime for a specific file.
107    ///
108    /// This operation is atomic: it removes old nodes associated with the file
109    /// and inserts the new ones.
110    pub fn update_file(
111        &self,
112        file_path: &str,
113        nodes: &[CodeNode],
114        mtime: u64,
115    ) -> Result<(), StoreError> {
116        let file_key = format!("f:{}", file_path);
117        let mtime_key = format!("m:{}", file_path);
118        let mut batch = Batch::default();
119
120        // 1. Get old nodes for this file
121        if let Some(old_bytes) = self.db.get(&file_key)? {
122            let old_ids: Vec<String> = bincode::deserialize(&old_bytes)?;
123            for id in old_ids {
124                batch.remove(format!("n:{}", id).as_bytes());
125            }
126        }
127
128        // 2. Insert new nodes
129        let mut new_ids = Vec::with_capacity(nodes.len());
130        for node in nodes {
131            let node_key = format!("n:{}", node.id);
132            let bytes = bincode::serialize(node)?;
133            batch.insert(node_key.as_bytes(), bytes);
134            new_ids.push(node.id.clone());
135        }
136
137        // 3. Update file index
138        let index_bytes = bincode::serialize(&new_ids)?;
139        batch.insert(file_key.as_bytes(), index_bytes);
140
141        // 4. Update mtime
142        let mtime_bytes = bincode::serialize(&mtime)?;
143        batch.insert(mtime_key.as_bytes(), mtime_bytes);
144
145        // 5. Commit batch
146        self.db.apply_batch(batch)?;
147        self.db.flush()?;
148        Ok(())
149    }
150
151    /// Removes a file from the cache (for deleted files).
152    pub fn remove_file(&self, file_path: &str) -> Result<(), StoreError> {
153        let file_key = format!("f:{}", file_path);
154        let mtime_key = format!("m:{}", file_path);
155        let mut batch = Batch::default();
156
157        // Remove nodes
158        if let Some(old_bytes) = self.db.get(&file_key)? {
159            let old_ids: Vec<String> = bincode::deserialize(&old_bytes)?;
160            for id in old_ids {
161                batch.remove(format!("n:{}", id).as_bytes());
162            }
163        }
164
165        batch.remove(file_key.as_bytes());
166        batch.remove(mtime_key.as_bytes());
167
168        self.db.apply_batch(batch)?;
169        self.db.flush()?;
170        Ok(())
171    }
172
173    /// Lists all cached file paths.
174    pub fn list_cached_files(&self) -> Result<Vec<String>, StoreError> {
175        let mut files = Vec::new();
176        let prefix = b"f:";
177        for item in self.db.scan_prefix(prefix) {
178            let (key, _) = item?;
179            let key_str = String::from_utf8_lossy(&key);
180            if let Some(file_path) = key_str.strip_prefix("f:") {
181                files.push(file_path.to_string());
182            }
183        }
184        Ok(files)
185    }
186
187    /// Loads the entire graph from the store.
188    ///
189    /// This iterates over all stored nodes and reconstructs the ArborGraph
190    /// using the GraphBuilder (which re-links edges).
191    pub fn load_graph(&self) -> Result<ArborGraph, StoreError> {
192        let mut builder = GraphBuilder::new();
193        let mut nodes = Vec::new();
194
195        // Iterate over all keys starting with "n:"
196        let prefix = b"n:";
197        for item in self.db.scan_prefix(prefix) {
198            let (_key, value) = item?;
199            let node: CodeNode = bincode::deserialize(&value)?;
200            nodes.push(node);
201        }
202
203        if nodes.is_empty() {
204            // Return empty graph
205            return Ok(ArborGraph::new());
206        }
207
208        // Reconstruct graph; centrality pre-computed on-demand via ranking.rs for large (500k+) repos (sled keeps RAM low per roadmap)
209        builder.add_nodes(nodes);
210        // resolve_edges() is called by build()
211        let graph = builder.build();
212
213        Ok(graph)
214    }
215
216    /// Clears the stored graph.
217    pub fn clear(&self) -> Result<(), StoreError> {
218        self.db.clear()?;
219        // Re-set version after clear
220        let version_bytes = bincode::serialize(&CACHE_VERSION.to_string())?;
221        self.db.insert("meta:version", version_bytes)?;
222        self.db.flush()?;
223        Ok(())
224    }
225}
226
227/// Open the sled database, waiting up to a second while a handle this
228/// process just dropped still holds the directory lock (sled releases it
229/// when that handle's flusher thread exits). A store held open by another
230/// process still fails, after the wait.
231fn open_db(path: &Path) -> Result<Db, StoreError> {
232    let deadline = Instant::now() + Duration::from_secs(1);
233    loop {
234        match sled::open(path) {
235            Err(sled::Error::Io(error))
236                if error.to_string().contains("could not acquire lock")
237                    && Instant::now() < deadline =>
238            {
239                std::thread::sleep(Duration::from_millis(20));
240            }
241            result => return Ok(result?),
242        }
243    }
244}
245
246fn stored_version(db: &Db) -> Result<Option<String>, StoreError> {
247    match db.get("meta:version")? {
248        Some(bytes) => Ok(Some(bincode::deserialize(&bytes)?)),
249        None => Ok(None),
250    }
251}
252
253fn set_version(db: &Db) -> Result<(), StoreError> {
254    db.insert(
255        "meta:version",
256        bincode::serialize(&CACHE_VERSION.to_string())?,
257    )?;
258    Ok(())
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use arbor_core::NodeKind;
265    use tempfile::tempdir;
266
267    /// test_cache_version failed on CI when the second open found the lock
268    /// still held by the handle just dropped (#250). Repeat the sequence so a
269    /// missing wait shows up here rather than once in a while in CI.
270    #[test]
271    fn a_store_can_be_reopened_right_after_it_is_dropped() {
272        let dir = tempdir().unwrap();
273        for _ in 0..200 {
274            drop(GraphStore::open(dir.path()).unwrap());
275        }
276    }
277
278    #[test]
279    fn an_outdated_cache_is_cleared_without_reopening() {
280        let dir = tempdir().unwrap();
281        {
282            let db = sled::open(dir.path()).unwrap();
283            db.insert("meta:version", bincode::serialize("arbor-0.0.0").unwrap())
284                .unwrap();
285            db.insert("m:stale.rs", bincode::serialize(&1u64).unwrap())
286                .unwrap();
287            db.flush().unwrap();
288        }
289        // No pause after the drop above: a second sled::open inside
290        // open_or_reset could still find the directory locked.
291        let store = GraphStore::open_or_reset(dir.path()).unwrap();
292        assert_eq!(
293            stored_version(&store.db).unwrap().as_deref(),
294            Some(CACHE_VERSION)
295        );
296        assert_eq!(store.get_mtime("stale.rs").unwrap(), None);
297    }
298
299    #[test]
300    fn test_incremental_updates() {
301        let dir = tempdir().unwrap();
302        let store = GraphStore::open(dir.path()).unwrap();
303
304        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "test.rs");
305        let node2 = CodeNode::new("bar", "bar", NodeKind::Function, "test.rs");
306
307        // Initial update with mtime
308        store
309            .update_file("test.rs", &[node1.clone(), node2.clone()], 1000)
310            .unwrap();
311
312        // Verify load
313        let graph = store.load_graph().unwrap();
314        assert_eq!(graph.node_count(), 2);
315
316        // Verify mtime was stored
317        assert_eq!(store.get_mtime("test.rs").unwrap(), Some(1000));
318
319        // Update with one node removed
320        store
321            .update_file("test.rs", std::slice::from_ref(&node1), 2000)
322            .unwrap();
323        let graph2 = store.load_graph().unwrap();
324        assert_eq!(graph2.node_count(), 1);
325        assert!(!graph2.find_by_name("foo").is_empty());
326        assert!(graph2.find_by_name("bar").is_empty());
327
328        // Verify mtime was updated
329        assert_eq!(store.get_mtime("test.rs").unwrap(), Some(2000));
330    }
331
332    #[test]
333    fn test_cache_version() {
334        let dir = tempdir().unwrap();
335
336        // First open sets version
337        let store = GraphStore::open(dir.path()).unwrap();
338        drop(store);
339
340        // Second open should succeed with same version
341        let store2 = GraphStore::open(dir.path()).unwrap();
342        drop(store2);
343    }
344
345    #[test]
346    fn test_remove_file() {
347        let dir = tempdir().unwrap();
348        let store = GraphStore::open(dir.path()).unwrap();
349
350        let node = CodeNode::new("foo", "foo", NodeKind::Function, "test.rs");
351        store.update_file("test.rs", &[node], 1000).unwrap();
352
353        // Verify file exists
354        assert!(store.get_mtime("test.rs").unwrap().is_some());
355        assert!(store.get_file_nodes("test.rs").unwrap().is_some());
356
357        // Remove file
358        store.remove_file("test.rs").unwrap();
359
360        // Verify file is gone
361        assert!(store.get_mtime("test.rs").unwrap().is_none());
362        assert!(store.get_file_nodes("test.rs").unwrap().is_none());
363    }
364
365    #[test]
366    fn test_list_cached_files() {
367        let dir = tempdir().unwrap();
368        let store = GraphStore::open(dir.path()).unwrap();
369
370        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "a.rs");
371        let node2 = CodeNode::new("bar", "bar", NodeKind::Function, "b.rs");
372
373        store.update_file("a.rs", &[node1], 1000).unwrap();
374        store.update_file("b.rs", &[node2], 2000).unwrap();
375
376        let files = store.list_cached_files().unwrap();
377        assert_eq!(files.len(), 2);
378        assert!(files.contains(&"a.rs".to_string()));
379        assert!(files.contains(&"b.rs".to_string()));
380    }
381}