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