Skip to main content

strands/storage/
mod.rs

1//! Unified byte storage.
2//!
3//! [`Storage`] persists raw bytes under string keys. Every SDK subsystem that needs persistence
4//! (sessions, memory, context offloading) consumes it. The SDK ships [`InMemoryStorage`] and
5//! [`LocalFileStorage`]; [`namespace`] scopes any backend under a key prefix (through its own
6//! namespacing or a [`NamespacedStorage`]), and [`search`] holds the pluggable search strategies.
7//!
8//! ```
9//! use strands::storage::{InMemoryStorage, Storage};
10//!
11//! # #[tokio::main(flavor = "current_thread")]
12//! # async fn main() -> strands::Result<()> {
13//! let storage = InMemoryStorage::new();
14//! storage.write("memory/notes.json", b"[]").await?;
15//! assert_eq!(storage.read("memory/notes.json").await?, Some(b"[]".to_vec()));
16//! assert_eq!(storage.list("memory/").await?, ["memory/notes.json"]);
17//! # Ok(())
18//! # }
19//! ```
20
21use std::any::type_name;
22use std::sync::Arc;
23
24use async_trait::async_trait;
25
26use crate::error::{Result, StorageError};
27
28mod in_memory_storage;
29mod local_file_storage;
30mod namespaced_storage;
31pub mod search;
32
33pub use in_memory_storage::{InMemoryStorage, InMemoryStorageConfig, InMemoryStorageConfigBuilder};
34pub use local_file_storage::{LocalFileStorage, LocalFileStorageConfig, LocalFileStorageConfigBuilder};
35pub use namespaced_storage::NamespacedStorage;
36pub use search::StorageSearchResult;
37
38/// A backend for storing and retrieving raw bytes under string keys (`Storage`).
39///
40/// Keys are opaque strings and implementations round-trip the bytes they are given unchanged.
41/// The shipped backends read `/` as a logical separator: they collapse slash runs, strip leading
42/// and trailing slashes and reject empty keys, backslashes and `..` segments. Custom backends may
43/// use their own key scheme.
44///
45/// Two methods are optional capabilities: [`namespace`](Storage::namespace) and
46/// [`search`](Storage::search) return `None` when the backend does not implement them, and
47/// callers then fall back to a [`NamespacedStorage`] view or a client-side
48/// [`KeywordSearchStrategy`](search::KeywordSearchStrategy) scan.
49///
50/// ```
51/// use std::collections::BTreeMap;
52/// use std::sync::Mutex;
53///
54/// use strands::storage::Storage;
55///
56/// #[derive(Default)]
57/// struct MapStorage(Mutex<BTreeMap<String, Vec<u8>>>);
58///
59/// #[strands::async_trait]
60/// impl Storage for MapStorage {
61///     async fn write(&self, key: &str, data: &[u8]) -> strands::Result<()> {
62///         self.0.lock().unwrap().insert(key.to_owned(), data.to_vec());
63///         Ok(())
64///     }
65///
66///     async fn read(&self, key: &str) -> strands::Result<Option<Vec<u8>>> {
67///         Ok(self.0.lock().unwrap().get(key).cloned())
68///     }
69///
70///     async fn delete(&self, key: &str) -> strands::Result<()> {
71///         self.0.lock().unwrap().remove(key);
72///         Ok(())
73///     }
74///
75///     async fn list(&self, prefix: &str) -> strands::Result<Vec<String>> {
76///         let map = self.0.lock().unwrap();
77///         Ok(map.keys().filter(|key| key.starts_with(prefix)).cloned().collect())
78///     }
79/// }
80///
81/// assert_eq!(MapStorage::default().storage_type(), "MapStorage");
82/// ```
83#[async_trait]
84pub trait Storage: Send + Sync + 'static {
85    /// Stores `data` under `key`, overwriting any existing value.
86    ///
87    /// # Errors
88    ///
89    /// Returns a [`StorageError`] when the key is invalid or the write fails.
90    async fn write(&self, key: &str, data: &[u8]) -> Result<()>;
91
92    /// The bytes stored under `key`, or `None` when no value exists.
93    ///
94    /// # Errors
95    ///
96    /// Returns a [`StorageError`] when the key is invalid or the read fails for a reason other
97    /// than a missing key.
98    async fn read(&self, key: &str) -> Result<Option<Vec<u8>>>;
99
100    /// Deletes the value stored under `key`. A no-op when the key does not exist.
101    ///
102    /// # Errors
103    ///
104    /// Returns a [`StorageError`] when the key is invalid or the delete fails.
105    async fn delete(&self, key: &str) -> Result<()>;
106
107    /// The full keys that start with `prefix`, sorted ascending. An empty prefix lists every key.
108    ///
109    /// # Errors
110    ///
111    /// Returns a [`StorageError`] when the prefix is invalid or the listing fails.
112    async fn list(&self, prefix: &str) -> Result<Vec<String>>;
113
114    /// A view of this storage with every key prefixed by `prefix` (optional `namespace`).
115    ///
116    /// `None` means the backend has no namespacing of its own; wrap it in a [`NamespacedStorage`]
117    /// instead. The shipped backends return an instance of their own type.
118    fn namespace(&self, _prefix: &str) -> Option<Result<Arc<dyn Storage>>> {
119        None
120    }
121
122    /// Searches stored content for `query`, best match first (optional `search`).
123    ///
124    /// `None` means the backend does not search; callers fall back to a client-side scan such as
125    /// [`KeywordSearchStrategy`](search::KeywordSearchStrategy). How a query is interpreted
126    /// (keyword scan, full-text index, vector similarity) is up to the backend.
127    async fn search(&self, _query: &str) -> Option<Result<Vec<StorageSearchResult>>> {
128        None
129    }
130
131    /// The backend's type name, recorded as the archive `storageType`.
132    ///
133    /// Defaults to the implementing type's name without its module path or generics. That name
134    /// comes from [`std::any::type_name`], whose output Rust does not guarantee across compiler
135    /// versions, so a custom backend whose archive may be restored by another build or SDK should
136    /// override it with a fixed name.
137    fn storage_type(&self) -> &str {
138        short_type_name(type_name::<Self>())
139    }
140
141    /// Whether stored data is lost when the process exits.
142    fn is_ephemeral(&self) -> bool {
143        false
144    }
145
146    /// Whether this is already a namespaced view, so constructs that scope storage under a default
147    /// prefix use it as it is.
148    fn is_namespaced(&self) -> bool {
149        false
150    }
151}
152
153/// What the builders' `storage(..)` setters take: a storage by value, an `Arc` of one, or an
154/// `Arc<dyn Storage>` (kept as is, so the agent's [`storage`](crate::Agent::storage) is the same
155/// instance).
156pub trait IntoStorage {
157    /// The storage, shared.
158    fn into_storage(self) -> Arc<dyn Storage>;
159}
160
161impl<S: Storage> IntoStorage for S {
162    fn into_storage(self) -> Arc<dyn Storage> {
163        Arc::new(self)
164    }
165}
166
167impl<S: Storage> IntoStorage for Arc<S> {
168    fn into_storage(self) -> Arc<dyn Storage> {
169        self
170    }
171}
172
173impl IntoStorage for Arc<dyn Storage> {
174    fn into_storage(self) -> Arc<dyn Storage> {
175        self
176    }
177}
178
179/// `strands::storage::InMemoryStorage` -> `InMemoryStorage`; `a::Wrapper<b::Inner>` -> `Wrapper`.
180fn short_type_name(full: &str) -> &str {
181    let path = full.split('<').next().unwrap_or(full);
182    path.rsplit("::").next().unwrap_or(path)
183}
184
185/// Validates and normalizes a key for the path-based backends: collapses slash
186/// runs and strips leading and trailing slashes; rejects backslashes, empty keys and `..` segments.
187pub(crate) fn normalize_key(key: &str) -> Result<String> {
188    if key.contains('\\') {
189        return Err(StorageError::new(format!("Invalid storage key '{key}': backslashes are not allowed")).into());
190    }
191    let segments: Vec<&str> = key.split('/').filter(|segment| !segment.is_empty()).collect();
192    if segments.is_empty() {
193        return Err(StorageError::new("Storage key must not be empty").into());
194    }
195    if segments.contains(&"..") {
196        return Err(StorageError::new(format!(
197            "Invalid storage key '{key}': '..' path segments are not allowed"
198        ))
199        .into());
200    }
201    Ok(segments.join("/"))
202}
203
204/// Normalizes a list prefix: collapses slash runs and strips leading slashes,
205/// keeping one trailing slash. Unlike a key, an empty prefix is valid and matches everything.
206pub(crate) fn normalize_prefix(prefix: &str) -> Result<String> {
207    if prefix.contains('\\') {
208        return Err(StorageError::new(format!(
209            "Invalid storage prefix '{prefix}': backslashes are not allowed"
210        ))
211        .into());
212    }
213    let segments: Vec<&str> = prefix.split('/').filter(|segment| !segment.is_empty()).collect();
214    if segments.contains(&"..") {
215        return Err(StorageError::new(format!(
216            "Invalid storage prefix '{prefix}': '..' path segments are not allowed"
217        ))
218        .into());
219    }
220    let joined = segments.join("/");
221    if prefix.ends_with('/') && !joined.is_empty() {
222        return Ok(format!("{joined}/"));
223    }
224    Ok(joined)
225}
226
227/// Sorts keys by UTF-16 code units, the listing order shared across the Strands SDKs.
228pub(crate) fn sort_keys(keys: &mut [String]) {
229    keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
230}
231
232/// A view of `storage` with every key under `prefix` (`namespace`): the backend's own
233/// [`Storage::namespace`] when it has one, a [`NamespacedStorage`] otherwise. This is the form to
234/// use on an `Arc<dyn Storage>`, where the trait method returns `None` for backends without
235/// namespacing.
236///
237/// ```
238/// use std::sync::Arc;
239/// use strands::storage::{self, InMemoryStorage, Storage};
240///
241/// # #[tokio::main(flavor = "current_thread")]
242/// # async fn main() -> strands::Result<()> {
243/// let root: Arc<dyn Storage> = Arc::new(InMemoryStorage::new());
244/// let sessions = storage::namespace(root.clone(), "sessions")?;
245/// sessions.write("abc.json", b"{}").await?;
246/// assert_eq!(root.list("").await?, ["sessions/abc.json"]);
247/// # Ok(())
248/// # }
249/// ```
250///
251/// # Errors
252///
253/// Returns a [`StorageError`] when the prefix is invalid for the backend.
254pub fn namespace(storage: Arc<dyn Storage>, prefix: &str) -> Result<Arc<dyn Storage>> {
255    if let Some(scoped) = storage.namespace(prefix) {
256        return scoped;
257    }
258    Ok(Arc::new(NamespacedStorage::new(storage, prefix)?))
259}
260
261/// Scopes `storage` under `prefix` unless it is already namespaced.
262pub(crate) fn resolve_namespace(storage: Arc<dyn Storage>, prefix: &str) -> Result<Arc<dyn Storage>> {
263    if storage.is_namespaced() {
264        return Ok(storage);
265    }
266    namespace(storage, prefix)
267}
268
269/// Key normalization, `resolve_namespace` and the trait defaults.
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn normalizes_keys_with_the_ts_rules_and_error_texts() {
276        assert_eq!(normalize_key("/a//b/").unwrap(), "a/b");
277        assert_eq!(normalize_key("./a").unwrap(), "./a");
278        assert_eq!(
279            normalize_key("").unwrap_err().to_string(),
280            "Storage key must not be empty"
281        );
282        assert_eq!(
283            normalize_key("//").unwrap_err().to_string(),
284            "Storage key must not be empty"
285        );
286        assert_eq!(
287            normalize_key("a/../b").unwrap_err().to_string(),
288            "Invalid storage key 'a/../b': '..' path segments are not allowed"
289        );
290        assert_eq!(
291            normalize_key("foo\\bar").unwrap_err().to_string(),
292            "Invalid storage key 'foo\\bar': backslashes are not allowed"
293        );
294    }
295
296    #[test]
297    fn normalizes_prefixes_keeping_one_trailing_slash() {
298        assert_eq!(normalize_prefix("").unwrap(), "");
299        assert_eq!(normalize_prefix("/").unwrap(), "");
300        assert_eq!(normalize_prefix("a/").unwrap(), "a/");
301        assert_eq!(normalize_prefix("a//").unwrap(), "a/");
302        assert_eq!(normalize_prefix("/a//b").unwrap(), "a/b");
303        assert_eq!(
304            normalize_prefix("../").unwrap_err().to_string(),
305            "Invalid storage prefix '../': '..' path segments are not allowed"
306        );
307        assert_eq!(
308            normalize_prefix("a\\").unwrap_err().to_string(),
309            "Invalid storage prefix 'a\\': backslashes are not allowed"
310        );
311    }
312
313    #[test]
314    fn key_errors_are_storage_errors() {
315        assert_eq!(normalize_key("").unwrap_err().name(), "StorageError");
316        assert_eq!(normalize_prefix("..").unwrap_err().name(), "StorageError");
317    }
318
319    #[test]
320    fn sorts_keys_by_utf16_code_units_like_js() {
321        let mut keys = vec![
322            "\u{1F600}".to_owned(),
323            "\u{FF5E}".to_owned(),
324            "b".to_owned(),
325            "a".to_owned(),
326        ];
327        sort_keys(&mut keys);
328        assert_eq!(keys, ["a", "b", "\u{1F600}", "\u{FF5E}"]);
329    }
330
331    #[test]
332    fn short_type_name_drops_the_module_path_and_generics() {
333        assert_eq!(short_type_name("strands::storage::InMemoryStorage"), "InMemoryStorage");
334        assert_eq!(short_type_name("a::Wrapper<b::Inner>"), "Wrapper");
335        assert_eq!(short_type_name("Plain"), "Plain");
336    }
337
338    #[tokio::test]
339    async fn resolve_namespace_keeps_namespaced_storage_and_prefers_the_backends_own() {
340        let root: Arc<dyn Storage> = Arc::new(InMemoryStorage::new());
341        let scoped = resolve_namespace(Arc::clone(&root), "memory").unwrap();
342        assert!(scoped.is_namespaced());
343        assert_eq!(scoped.storage_type(), "InMemoryStorage");
344        assert!(Arc::ptr_eq(
345            &resolve_namespace(Arc::clone(&scoped), "other").unwrap(),
346            &scoped
347        ));
348        scoped.write("k", b"v").await.unwrap();
349        assert_eq!(root.list("").await.unwrap(), ["memory/k"]);
350    }
351
352    #[tokio::test]
353    async fn resolve_namespace_wraps_a_backend_without_namespacing() {
354        let root: Arc<dyn Storage> = Arc::new(Bare(InMemoryStorage::new()));
355        assert!(root.namespace("x").is_none());
356        let scoped = resolve_namespace(Arc::clone(&root), "x").unwrap();
357        assert!(scoped.is_namespaced());
358        scoped.write("k", b"v").await.unwrap();
359        assert_eq!(root.list("").await.unwrap(), ["x/k"]);
360        assert!(root.search("v").await.is_none());
361    }
362
363    #[tokio::test]
364    async fn namespace_scopes_a_dyn_storage_with_or_without_its_own_namespacing() {
365        let root: Arc<dyn Storage> = Arc::new(InMemoryStorage::new());
366        let scoped = namespace(Arc::clone(&root), "a").unwrap();
367        let nested = namespace(Arc::clone(&scoped), "b").unwrap();
368        nested.write("k", b"v").await.unwrap();
369        assert_eq!(root.list("").await.unwrap(), ["a/b/k"]);
370        assert_eq!(scoped.storage_type(), "InMemoryStorage");
371
372        let bare: Arc<dyn Storage> = Arc::new(Bare(InMemoryStorage::new()));
373        let scoped = namespace(Arc::clone(&bare), "x").unwrap();
374        scoped.write("k", b"v").await.unwrap();
375        assert_eq!(bare.list("").await.unwrap(), ["x/k"]);
376        assert_eq!(
377            namespace(bare, "../up").err().map(|error| error.to_string()),
378            Some("Invalid storage prefix '../up': '..' path segments are not allowed".to_owned())
379        );
380    }
381
382    #[test]
383    fn trait_defaults_report_a_durable_unscoped_backend_named_after_its_type() {
384        let bare = Bare(InMemoryStorage::new());
385        assert_eq!(bare.storage_type(), "Bare");
386        assert!(!bare.is_ephemeral());
387        assert!(!bare.is_namespaced());
388    }
389
390    /// A backend that implements only the four required methods.
391    struct Bare(InMemoryStorage);
392
393    #[async_trait]
394    impl Storage for Bare {
395        async fn write(&self, key: &str, data: &[u8]) -> Result<()> {
396            Storage::write(&self.0, key, data).await
397        }
398
399        async fn read(&self, key: &str) -> Result<Option<Vec<u8>>> {
400            Storage::read(&self.0, key).await
401        }
402
403        async fn delete(&self, key: &str) -> Result<()> {
404            Storage::delete(&self.0, key).await
405        }
406
407        async fn list(&self, prefix: &str) -> Result<Vec<String>> {
408            Storage::list(&self.0, prefix).await
409        }
410    }
411}