Skip to main content

contextgraph_core/
mem.rs

1//! In-memory fakes of `CommitStore` and `RefStore`, for fast unit/property
2//! tests and as a reference implementation of the storage contract.
3
4use crate::commit::{Commit, CommitId};
5use crate::error::{GraphError, Result};
6use crate::store::{CommitStore, RefStore};
7use async_trait::async_trait;
8use std::collections::{HashMap, HashSet};
9use std::sync::RwLock;
10
11#[derive(Default)]
12pub struct InMemoryCommitStore {
13    commits: RwLock<HashMap<CommitId, Commit>>,
14    children: RwLock<HashMap<CommitId, HashSet<CommitId>>>,
15}
16
17impl InMemoryCommitStore {
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    fn lock_err(_: impl std::fmt::Debug) -> GraphError {
23        GraphError::Storage("in-memory commit store lock poisoned".into())
24    }
25}
26
27#[async_trait]
28impl CommitStore for InMemoryCommitStore {
29    async fn put(&self, commit: Commit) -> Result<CommitId> {
30        let mut commits = self.commits.write().map_err(Self::lock_err)?;
31
32        if commits.contains_key(&commit.id) {
33            return Ok(commit.id);
34        }
35
36        for parent in &commit.parent_ids {
37            if !commits.contains_key(parent) {
38                return Err(GraphError::ParentNotFound(*parent));
39            }
40        }
41
42        let id = commit.id;
43        let parent_ids = commit.parent_ids.clone();
44        commits.insert(id, commit);
45        drop(commits);
46
47        let mut children = self.children.write().map_err(Self::lock_err)?;
48        for parent in parent_ids {
49            children.entry(parent).or_default().insert(id);
50        }
51        children.entry(id).or_default();
52
53        Ok(id)
54    }
55
56    async fn get(&self, id: &CommitId) -> Result<Option<Commit>> {
57        let commits = self.commits.read().map_err(Self::lock_err)?;
58        Ok(commits.get(id).cloned())
59    }
60
61    async fn contains(&self, id: &CommitId) -> Result<bool> {
62        let commits = self.commits.read().map_err(Self::lock_err)?;
63        Ok(commits.contains_key(id))
64    }
65
66    async fn children(&self, id: &CommitId) -> Result<Vec<CommitId>> {
67        let children = self.children.read().map_err(Self::lock_err)?;
68        Ok(children
69            .get(id)
70            .map(|s| s.iter().copied().collect())
71            .unwrap_or_default())
72    }
73
74    async fn len(&self) -> Result<usize> {
75        let commits = self.commits.read().map_err(Self::lock_err)?;
76        Ok(commits.len())
77    }
78
79    async fn all_ids(&self) -> Result<Vec<CommitId>> {
80        let commits = self.commits.read().map_err(Self::lock_err)?;
81        Ok(commits.keys().copied().collect())
82    }
83
84    async fn remove_many(&self, ids: &[CommitId]) -> Result<()> {
85        let mut commits = self.commits.write().map_err(Self::lock_err)?;
86        let mut children = self.children.write().map_err(Self::lock_err)?;
87        for id in ids {
88            if let Some(commit) = commits.remove(id) {
89                for parent in &commit.parent_ids {
90                    if let Some(set) = children.get_mut(parent) {
91                        set.remove(id);
92                    }
93                }
94            }
95            children.remove(id);
96        }
97        Ok(())
98    }
99}
100
101#[derive(Default)]
102pub struct InMemoryRefStore {
103    branches: RwLock<HashMap<String, CommitId>>,
104}
105
106impl InMemoryRefStore {
107    pub fn new() -> Self {
108        Self::default()
109    }
110
111    fn lock_err(_: impl std::fmt::Debug) -> GraphError {
112        GraphError::Storage("in-memory ref store lock poisoned".into())
113    }
114}
115
116#[async_trait]
117impl RefStore for InMemoryRefStore {
118    async fn get_branch(&self, name: &str) -> Result<Option<CommitId>> {
119        let branches = self.branches.read().map_err(Self::lock_err)?;
120        Ok(branches.get(name).copied())
121    }
122
123    async fn set_branch(&self, name: &str, commit_id: CommitId) -> Result<()> {
124        let mut branches = self.branches.write().map_err(Self::lock_err)?;
125        branches.insert(name.to_string(), commit_id);
126        Ok(())
127    }
128
129    async fn delete_branch(&self, name: &str) -> Result<()> {
130        let mut branches = self.branches.write().map_err(Self::lock_err)?;
131        if branches.remove(name).is_none() {
132            return Err(GraphError::BranchNotFound(name.to_string()));
133        }
134        Ok(())
135    }
136
137    async fn list_branches(&self) -> Result<Vec<(String, CommitId)>> {
138        let branches = self.branches.read().map_err(Self::lock_err)?;
139        Ok(branches.iter().map(|(k, v)| (k.clone(), *v)).collect())
140    }
141}
142
143/// Combines `InMemoryCommitStore` + `InMemoryRefStore` behind a single type
144/// that implements both traits, so it can back `ContextGraph<S>` directly
145/// (the same shape production code gets from `SqliteStore`).
146#[derive(Default)]
147pub struct InMemoryGraphStore {
148    commits: InMemoryCommitStore,
149    refs: InMemoryRefStore,
150}
151
152impl InMemoryGraphStore {
153    pub fn new() -> Self {
154        Self::default()
155    }
156}
157
158#[async_trait]
159impl CommitStore for InMemoryGraphStore {
160    async fn put(&self, commit: Commit) -> Result<CommitId> {
161        self.commits.put(commit).await
162    }
163
164    async fn get(&self, id: &CommitId) -> Result<Option<Commit>> {
165        self.commits.get(id).await
166    }
167
168    async fn contains(&self, id: &CommitId) -> Result<bool> {
169        self.commits.contains(id).await
170    }
171
172    async fn children(&self, id: &CommitId) -> Result<Vec<CommitId>> {
173        self.commits.children(id).await
174    }
175
176    async fn len(&self) -> Result<usize> {
177        self.commits.len().await
178    }
179
180    async fn all_ids(&self) -> Result<Vec<CommitId>> {
181        self.commits.all_ids().await
182    }
183
184    async fn remove_many(&self, ids: &[CommitId]) -> Result<()> {
185        self.commits.remove_many(ids).await
186    }
187}
188
189#[async_trait]
190impl RefStore for InMemoryGraphStore {
191    async fn get_branch(&self, name: &str) -> Result<Option<CommitId>> {
192        self.refs.get_branch(name).await
193    }
194
195    async fn set_branch(&self, name: &str, commit_id: CommitId) -> Result<()> {
196        self.refs.set_branch(name, commit_id).await
197    }
198
199    async fn delete_branch(&self, name: &str) -> Result<()> {
200        self.refs.delete_branch(name).await
201    }
202
203    async fn list_branches(&self) -> Result<Vec<(String, CommitId)>> {
204        self.refs.list_branches().await
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use crate::commit::{Author, Delta, Metadata};
212    use chrono::Utc;
213
214    fn root() -> Commit {
215        Commit::new(
216            vec![],
217            Author::System,
218            Delta::Message {
219                content: "root".into(),
220            },
221            Metadata::new(Utc::now()),
222        )
223    }
224
225    #[tokio::test]
226    async fn putting_a_commit_with_nonexistent_parent_fails() {
227        let store = InMemoryCommitStore::new();
228        let orphan = Commit::new(
229            vec![CommitId::from_bytes([9; 32])],
230            Author::User,
231            Delta::Message {
232                content: "x".into(),
233            },
234            Metadata::new(Utc::now()),
235        );
236        let err = store.put(orphan).await.unwrap_err();
237        assert!(matches!(err, GraphError::ParentNotFound(_)));
238    }
239
240    #[tokio::test]
241    async fn putting_root_commit_succeeds_and_is_retrievable() {
242        let store = InMemoryCommitStore::new();
243        let r = root();
244        let id = store.put(r.clone()).await.unwrap();
245        assert_eq!(id, r.id);
246        let fetched = store.get(&id).await.unwrap().unwrap();
247        assert_eq!(fetched, r);
248    }
249
250    #[tokio::test]
251    async fn putting_identical_commit_twice_does_not_duplicate_storage() {
252        let store = InMemoryCommitStore::new();
253        let r = root();
254        store.put(r.clone()).await.unwrap();
255        store.put(r.clone()).await.unwrap();
256        assert_eq!(store.len().await.unwrap(), 1);
257    }
258
259    #[tokio::test]
260    async fn child_commit_is_indexed_under_its_parent() {
261        let store = InMemoryCommitStore::new();
262        let r = root();
263        store.put(r.clone()).await.unwrap();
264        let child = Commit::new(
265            vec![r.id],
266            Author::User,
267            Delta::Message {
268                content: "hi".into(),
269            },
270            Metadata::new(Utc::now()),
271        );
272        store.put(child.clone()).await.unwrap();
273        let kids = store.children(&r.id).await.unwrap();
274        assert_eq!(kids, vec![child.id]);
275    }
276
277    #[tokio::test]
278    async fn getting_nonexistent_commit_returns_none_not_error() {
279        let store = InMemoryCommitStore::new();
280        let result = store.get(&CommitId::from_bytes([1; 32])).await.unwrap();
281        assert!(result.is_none());
282    }
283
284    #[tokio::test]
285    async fn branching_at_a_commit_then_reading_it_back_round_trips() {
286        let refs = InMemoryRefStore::new();
287        let id = CommitId::from_bytes([1; 32]);
288        refs.set_branch("main", id).await.unwrap();
289        assert_eq!(refs.get_branch("main").await.unwrap(), Some(id));
290    }
291
292    #[tokio::test]
293    async fn deleting_a_nonexistent_branch_fails() {
294        let refs = InMemoryRefStore::new();
295        let err = refs.delete_branch("nope").await.unwrap_err();
296        assert!(matches!(err, GraphError::BranchNotFound(_)));
297    }
298
299    #[tokio::test]
300    async fn moving_a_branch_pointer_overwrites_the_previous_target() {
301        let refs = InMemoryRefStore::new();
302        let a = CommitId::from_bytes([1; 32]);
303        let b = CommitId::from_bytes([2; 32]);
304        refs.set_branch("main", a).await.unwrap();
305        refs.set_branch("main", b).await.unwrap();
306        assert_eq!(refs.get_branch("main").await.unwrap(), Some(b));
307    }
308
309    #[tokio::test]
310    async fn removing_commits_cleans_up_child_index() {
311        let store = InMemoryCommitStore::new();
312        let r = root();
313        store.put(r.clone()).await.unwrap();
314        let child = Commit::new(
315            vec![r.id],
316            Author::User,
317            Delta::Message {
318                content: "hi".into(),
319            },
320            Metadata::new(Utc::now()),
321        );
322        store.put(child.clone()).await.unwrap();
323        store.remove_many(&[child.id]).await.unwrap();
324        assert_eq!(store.children(&r.id).await.unwrap(), Vec::<CommitId>::new());
325        assert_eq!(store.len().await.unwrap(), 1);
326    }
327}