Skip to main content

strands/storage/
in_memory_storage.rs

1//! In-memory storage.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
6
7use async_trait::async_trait;
8
9use super::search::{KeywordSearchStrategy, SearchStrategy, StorageSearchResult};
10use super::{Storage, normalize_key, normalize_prefix, sort_keys};
11use crate::error::Result;
12
13type Entries = HashMap<String, Vec<u8>>;
14
15/// Options for [`InMemoryStorage`] (`InMemoryStorageConfig`).
16#[derive(Clone, Default, bon::Builder)]
17pub struct InMemoryStorageConfig {
18    /// Search strategy. When set, writes are indexed and [`InMemoryStorage::search`] delegates to
19    /// it instead of the default keyword scan.
20    pub search_strategy: Option<Arc<dyn SearchStrategy>>,
21}
22
23impl fmt::Debug for InMemoryStorageConfig {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        f.debug_struct("InMemoryStorageConfig")
26            .field("search_strategy", &self.search_strategy.is_some())
27            .finish()
28    }
29}
30
31/// [`Storage`] backed by a map in memory (`InMemoryStorage`).
32///
33/// For tests and for environments without disk access. Content does not survive the process
34/// ([`Storage::is_ephemeral`] is `true`); use [`LocalFileStorage`](super::LocalFileStorage) to
35/// persist. The store is unbounded, with no eviction. Keys follow the shipped backends' rules:
36/// slash runs collapse, leading and trailing slashes are stripped and `..` segments are rejected.
37///
38/// ```
39/// use strands::storage::{InMemoryStorage, Storage};
40///
41/// # #[tokio::main(flavor = "current_thread")]
42/// # async fn main() -> strands::Result<()> {
43/// let storage = InMemoryStorage::new();
44/// let agent = storage.namespace("memory/agent")?;
45/// agent.write("notes.md", b"dark mode").await?;
46/// assert_eq!(storage.list("").await?, ["memory/agent/notes.md"]);
47/// assert_eq!(agent.search("dark").await?[0].key, "notes.md");
48/// # Ok(())
49/// # }
50/// ```
51pub struct InMemoryStorage {
52    /// Shared with every instance [`namespace`](Self::namespace) returns; each sees only the keys
53    /// under its own prefix.
54    entries: Arc<RwLock<Entries>>,
55    prefix: String,
56    namespaced: bool,
57    search_strategy: Option<Arc<dyn SearchStrategy>>,
58}
59
60impl InMemoryStorage {
61    /// An empty store using the default keyword search.
62    pub fn new() -> Self {
63        Self::with_config(InMemoryStorageConfig::default())
64    }
65
66    /// An empty store with options.
67    pub fn with_config(config: InMemoryStorageConfig) -> Self {
68        Self {
69            entries: Arc::default(),
70            prefix: String::new(),
71            namespaced: false,
72            search_strategy: config.search_strategy,
73        }
74    }
75
76    /// A store scoped to `prefix` that shares this store's entries and search strategy.
77    ///
78    /// Unlike a [`NamespacedStorage`](super::NamespacedStorage) view, the scoped store's search
79    /// sees only the entries under the prefix and scores their keys without it, so a query does
80    /// not match every entry because it contains a word of the prefix. The shared strategy
81    /// receives the scoped store and keys relative to the prefix.
82    ///
83    /// # Errors
84    ///
85    /// Returns a [`StorageError`](crate::StorageError) when the prefix contains a backslash or a
86    /// `..` segment.
87    pub fn namespace(&self, prefix: &str) -> Result<Self> {
88        let normalized = normalize_prefix(prefix)?;
89        let normalized = normalized.strip_suffix('/').unwrap_or(&normalized);
90        let prefix = if normalized.is_empty() {
91            self.prefix.clone()
92        } else {
93            format!("{}{normalized}/", self.prefix)
94        };
95        Ok(Self {
96            entries: Arc::clone(&self.entries),
97            prefix,
98            namespaced: true,
99            search_strategy: self.search_strategy.clone(),
100        })
101    }
102
103    /// Searches the entries this store sees, with its strategy or the default keyword scan.
104    ///
105    /// # Errors
106    ///
107    /// Returns the strategy's error.
108    pub async fn search(&self, query: &str) -> Result<Vec<StorageSearchResult>> {
109        match &self.search_strategy {
110            Some(strategy) => strategy.search(self, query).await,
111            None => KeywordSearchStrategy.search(self, query).await,
112        }
113    }
114
115    /// Removes every entry this store sees: those under its namespace, or all of them when it is
116    /// not namespaced.
117    pub fn clear(&self) {
118        let mut entries = self.write_entries();
119        if self.prefix.is_empty() {
120            entries.clear();
121            return;
122        }
123        entries.retain(|key, _| !key.starts_with(&self.prefix));
124    }
125
126    fn read_entries(&self) -> RwLockReadGuard<'_, Entries> {
127        self.entries.read().unwrap_or_else(PoisonError::into_inner)
128    }
129
130    fn write_entries(&self) -> RwLockWriteGuard<'_, Entries> {
131        self.entries.write().unwrap_or_else(PoisonError::into_inner)
132    }
133}
134
135impl Default for InMemoryStorage {
136    fn default() -> Self {
137        Self::new()
138    }
139}
140
141impl fmt::Debug for InMemoryStorage {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.debug_struct("InMemoryStorage")
144            .field("prefix", &self.prefix)
145            .field("search_strategy", &self.search_strategy.is_some())
146            .finish_non_exhaustive()
147    }
148}
149
150#[async_trait]
151impl Storage for InMemoryStorage {
152    async fn write(&self, key: &str, data: &[u8]) -> Result<()> {
153        let normalized = normalize_key(key)?;
154        self.write_entries()
155            .insert(format!("{}{normalized}", self.prefix), data.to_vec());
156        if let Some(strategy) = &self.search_strategy {
157            strategy.index(self, &normalized, data).await?;
158        }
159        Ok(())
160    }
161
162    async fn read(&self, key: &str) -> Result<Option<Vec<u8>>> {
163        let full_key = format!("{}{}", self.prefix, normalize_key(key)?);
164        Ok(self.read_entries().get(&full_key).cloned())
165    }
166
167    async fn delete(&self, key: &str) -> Result<()> {
168        let full_key = format!("{}{}", self.prefix, normalize_key(key)?);
169        self.write_entries().remove(&full_key);
170        Ok(())
171    }
172
173    async fn list(&self, prefix: &str) -> Result<Vec<String>> {
174        let full_prefix = format!("{}{}", self.prefix, normalize_prefix(prefix)?);
175        let mut keys: Vec<String> = self
176            .read_entries()
177            .keys()
178            .filter(|key| key.starts_with(&full_prefix))
179            .map(|key| key[self.prefix.len()..].to_owned())
180            .collect();
181        sort_keys(&mut keys);
182        Ok(keys)
183    }
184
185    fn namespace(&self, prefix: &str) -> Option<Result<Arc<dyn Storage>>> {
186        Some(Self::namespace(self, prefix).map(|scoped| Arc::new(scoped) as Arc<dyn Storage>))
187    }
188
189    async fn search(&self, query: &str) -> Option<Result<Vec<StorageSearchResult>>> {
190        Some(Self::search(self, query).await)
191    }
192
193    fn storage_type(&self) -> &str {
194        "InMemoryStorage"
195    }
196
197    fn is_ephemeral(&self) -> bool {
198        true
199    }
200
201    fn is_namespaced(&self) -> bool {
202        self.namespaced
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use std::sync::Mutex;
209
210    use super::*;
211
212    fn text(bytes: Option<Vec<u8>>) -> String {
213        String::from_utf8(bytes.unwrap()).unwrap()
214    }
215
216    #[tokio::test]
217    async fn stores_data_under_the_given_key() {
218        let storage = InMemoryStorage::new();
219        storage.write("test/key", b"hello").await.unwrap();
220        assert_eq!(storage.read("test/key").await.unwrap(), Some(b"hello".to_vec()));
221    }
222
223    #[tokio::test]
224    async fn overwrites_existing_data() {
225        let storage = InMemoryStorage::new();
226        storage.write("key", b"first").await.unwrap();
227        storage.write("key", b"second").await.unwrap();
228        assert_eq!(text(storage.read("key").await.unwrap()), "second");
229    }
230
231    #[tokio::test]
232    async fn copies_bytes_on_write_to_prevent_aliasing() {
233        let storage = InMemoryStorage::new();
234        let mut data = vec![1, 2, 3];
235        storage.write("key", &data).await.unwrap();
236        data[0] = 99;
237        assert_eq!(storage.read("key").await.unwrap().unwrap()[0], 1);
238    }
239
240    #[tokio::test]
241    async fn returns_null_for_missing_keys() {
242        let storage = InMemoryStorage::new();
243        assert_eq!(storage.read("nonexistent").await.unwrap(), None);
244    }
245
246    #[tokio::test]
247    async fn copies_bytes_on_read_to_prevent_aliasing() {
248        let storage = InMemoryStorage::new();
249        storage.write("key", &[1, 2, 3]).await.unwrap();
250        let mut first = storage.read("key").await.unwrap().unwrap();
251        first[0] = 99;
252        assert_eq!(storage.read("key").await.unwrap().unwrap()[0], 1);
253    }
254
255    #[tokio::test]
256    async fn removes_an_existing_key() {
257        let storage = InMemoryStorage::new();
258        storage.write("key", &[1]).await.unwrap();
259        storage.delete("key").await.unwrap();
260        assert_eq!(storage.read("key").await.unwrap(), None);
261    }
262
263    #[tokio::test]
264    async fn is_a_no_op_for_missing_keys() {
265        let storage = InMemoryStorage::new();
266        storage.delete("nonexistent").await.unwrap();
267    }
268
269    #[tokio::test]
270    async fn returns_keys_matching_a_prefix() {
271        let storage = InMemoryStorage::new();
272        storage.write("sessions/a/data", &[1]).await.unwrap();
273        storage.write("sessions/b/data", &[2]).await.unwrap();
274        storage.write("memory/notes", &[3]).await.unwrap();
275        assert_eq!(
276            storage.list("sessions/").await.unwrap(),
277            ["sessions/a/data", "sessions/b/data"]
278        );
279    }
280
281    #[tokio::test]
282    async fn returns_all_keys_when_prefix_is_empty() {
283        let storage = InMemoryStorage::new();
284        storage.write("a", &[1]).await.unwrap();
285        storage.write("b", &[2]).await.unwrap();
286        assert_eq!(storage.list("").await.unwrap(), ["a", "b"]);
287    }
288
289    #[tokio::test]
290    async fn returns_keys_sorted_lexicographically() {
291        let storage = InMemoryStorage::new();
292        for key in ["c", "a", "b"] {
293            storage.write(key, &[1]).await.unwrap();
294        }
295        assert_eq!(storage.list("").await.unwrap(), ["a", "b", "c"]);
296    }
297
298    #[tokio::test]
299    async fn returns_empty_array_when_no_keys_match() {
300        let storage = InMemoryStorage::new();
301        storage.write("other/key", &[1]).await.unwrap();
302        assert!(storage.list("sessions/").await.unwrap().is_empty());
303    }
304
305    #[tokio::test]
306    async fn removes_all_entries() {
307        let storage = InMemoryStorage::new();
308        storage.write("a", &[1]).await.unwrap();
309        storage.write("b", &[2]).await.unwrap();
310        storage.clear();
311        assert!(storage.list("").await.unwrap().is_empty());
312    }
313
314    #[tokio::test]
315    async fn normalizes_slashes_so_equivalent_keys_resolve_to_the_same_entry() {
316        let storage = InMemoryStorage::new();
317        storage.write("/a//b/", &[1]).await.unwrap();
318        assert_eq!(storage.read("a/b").await.unwrap(), Some(vec![1]));
319    }
320
321    #[tokio::test]
322    async fn rejects_empty_keys() {
323        let storage = InMemoryStorage::new();
324        let error = storage.write("", &[1]).await.unwrap_err();
325        assert_eq!(error.name(), "StorageError");
326    }
327
328    #[tokio::test]
329    async fn rejects_keys_with_dot_dot_segments() {
330        let storage = InMemoryStorage::new();
331        let error = storage.write("a/../b", &[1]).await.unwrap_err();
332        assert_eq!(error.name(), "StorageError");
333    }
334
335    #[tokio::test]
336    async fn rejects_prefixes_with_dot_dot_segments() {
337        let storage = InMemoryStorage::new();
338        let error = storage.list("../").await.unwrap_err();
339        assert_eq!(error.name(), "StorageError");
340    }
341
342    /// An `index` call: the key, the bytes and the keys the storage it was given lists.
343    type IndexCall = (String, Vec<u8>, Vec<String>);
344
345    /// Records `index` and `search` calls with the relative keys and the storage's view of itself.
346    #[derive(Default)]
347    struct Recording {
348        indexed: Mutex<Vec<IndexCall>>,
349        searched: Mutex<Vec<(String, Vec<String>)>>,
350    }
351
352    #[async_trait]
353    impl SearchStrategy for Recording {
354        async fn index(&self, storage: &dyn Storage, key: &str, data: &[u8]) -> Result<()> {
355            let visible = storage.list("").await?;
356            self.indexed
357                .lock()
358                .unwrap()
359                .push((key.to_owned(), data.to_vec(), visible));
360            Ok(())
361        }
362
363        async fn search(&self, storage: &dyn Storage, query: &str) -> Result<Vec<StorageSearchResult>> {
364            let visible = storage.list("").await?;
365            self.searched.lock().unwrap().push((query.to_owned(), visible));
366            Ok(vec![StorageSearchResult::new("hit", 1.0)])
367        }
368    }
369
370    fn with_strategy(strategy: &Arc<Recording>) -> InMemoryStorage {
371        let config = InMemoryStorageConfig::builder()
372            .search_strategy(Arc::clone(strategy) as Arc<dyn SearchStrategy>)
373            .build();
374        InMemoryStorage::with_config(config)
375    }
376
377    #[tokio::test]
378    async fn indexes_writes_and_delegates_search_to_a_search_strategy_from_config() {
379        let strategy = Arc::new(Recording::default());
380        let configured = with_strategy(&strategy);
381        configured.write("a", &[1]).await.unwrap();
382        assert_eq!(
383            *strategy.indexed.lock().unwrap(),
384            [("a".to_owned(), vec![1], vec!["a".to_owned()])]
385        );
386        assert_eq!(
387            configured.search("query").await.unwrap(),
388            [StorageSearchResult::new("hit", 1.0)]
389        );
390        assert_eq!(strategy.searched.lock().unwrap().len(), 1);
391    }
392
393    #[tokio::test]
394    async fn uses_the_default_keyword_scan_with_an_empty_config() {
395        let configured = InMemoryStorage::with_config(InMemoryStorageConfig::default());
396        configured.write("notes", b"dark mode").await.unwrap();
397        let results = configured.search("dark").await.unwrap();
398        assert_eq!(results.iter().map(|r| r.key.as_str()).collect::<Vec<_>>(), ["notes"]);
399    }
400
401    #[tokio::test]
402    async fn returns_a_scoped_in_memory_storage_that_shares_entries_with_the_parent() {
403        let storage = InMemoryStorage::new();
404        let scoped = storage.namespace("memory/agent").unwrap();
405        scoped.write("notes.md", b"hello").await.unwrap();
406        assert!(Storage::is_namespaced(&scoped));
407        assert_eq!(scoped.storage_type(), "InMemoryStorage");
408        assert_eq!(storage.list("").await.unwrap(), ["memory/agent/notes.md"]);
409        assert_eq!(scoped.list("").await.unwrap(), ["notes.md"]);
410        assert_eq!(text(scoped.read("notes.md").await.unwrap()), "hello");
411        scoped.delete("notes.md").await.unwrap();
412        assert!(storage.list("").await.unwrap().is_empty());
413    }
414
415    #[tokio::test]
416    async fn composes_nested_namespaces() {
417        let storage = InMemoryStorage::new();
418        let nested = storage.namespace("a").unwrap().namespace("b/").unwrap();
419        nested.write("k", b"v").await.unwrap();
420        assert_eq!(storage.list("").await.unwrap(), ["a/b/k"]);
421    }
422
423    #[tokio::test]
424    async fn searches_only_entries_under_the_prefix_and_scores_keys_without_it() {
425        let storage = InMemoryStorage::new();
426        storage
427            .write("other/memory-agent-notes.md", b"unrelated")
428            .await
429            .unwrap();
430        let scoped = storage.namespace("memory/agent").unwrap();
431        scoped.write("deploy.md", b"blue green deploys").await.unwrap();
432        scoped.write("theme.md", b"dark mode").await.unwrap();
433        let results = scoped.search("memory agent deploy").await.unwrap();
434        assert_eq!(
435            results.iter().map(|r| r.key.as_str()).collect::<Vec<_>>(),
436            ["deploy.md"]
437        );
438    }
439
440    #[tokio::test]
441    async fn passes_the_scoped_instance_and_relative_keys_to_the_search_strategy() {
442        let strategy = Arc::new(Recording::default());
443        let parent = with_strategy(&strategy);
444        parent.write("outside.md", b"x").await.unwrap();
445        let scoped = parent.namespace("memory/agent").unwrap();
446        scoped.write("deploy.md", b"x").await.unwrap();
447        scoped.search("query").await.unwrap();
448        let indexed = strategy.indexed.lock().unwrap();
449        assert_eq!(
450            indexed[1],
451            ("deploy.md".to_owned(), b"x".to_vec(), vec!["deploy.md".to_owned()])
452        );
453        assert_eq!(
454            *strategy.searched.lock().unwrap(),
455            [("query".to_owned(), vec!["deploy.md".to_owned()])]
456        );
457    }
458
459    #[tokio::test]
460    async fn clears_only_entries_under_the_prefix() {
461        let storage = InMemoryStorage::new();
462        storage.write("keep.md", b"x").await.unwrap();
463        let scoped = storage.namespace("memory").unwrap();
464        scoped.write("drop.md", b"y").await.unwrap();
465        scoped.clear();
466        assert_eq!(storage.list("").await.unwrap(), ["keep.md"]);
467    }
468
469    #[tokio::test]
470    async fn exposes_namespacing_and_search_through_dyn_storage() {
471        let storage: Arc<dyn Storage> = Arc::new(InMemoryStorage::new());
472        assert!(storage.is_ephemeral());
473        assert!(!storage.is_namespaced());
474        let scoped = storage.namespace("memory").unwrap().unwrap();
475        scoped.write("theme.md", b"dark mode").await.unwrap();
476        let results = scoped.search("dark").await.unwrap().unwrap();
477        assert_eq!(results[0].key, "theme.md");
478        assert_eq!(storage.list("").await.unwrap(), ["memory/theme.md"]);
479    }
480
481    #[test]
482    fn an_empty_namespace_keeps_the_prefix() {
483        let storage = InMemoryStorage::new();
484        let scoped = storage.namespace("a").unwrap().namespace("").unwrap();
485        assert_eq!(scoped.prefix, "a/");
486        assert!(storage.namespace("../x").is_err());
487    }
488}