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