Skip to main content

strands/storage/search/
mod.rs

1//! Pluggable search strategies for storage backends.
2//!
3//! A [`SearchStrategy`] is one way of searching stored content: a keyword scan, a full-text
4//! index, vector similarity. Backends delegate their [`Storage::search`] to a strategy, and
5//! consumers such as memory stores can override it. [`KeywordSearchStrategy`] is the default for
6//! every shipped backend.
7
8use async_trait::async_trait;
9
10use super::Storage;
11use crate::error::Result;
12
13pub(crate) mod keyword;
14
15pub use keyword::KeywordSearchStrategy;
16
17/// A single result from a search (`StorageSearchResult`).
18#[derive(Debug, Clone, PartialEq)]
19#[non_exhaustive]
20pub struct StorageSearchResult {
21    /// Storage key of the matched item.
22    pub key: String,
23    /// Relevance score; higher is more relevant. Distance-based backends invert distances to
24    /// similarities before returning them.
25    pub score: f64,
26    /// The stored bytes, when the backend returns them.
27    pub data: Option<Vec<u8>>,
28}
29
30impl StorageSearchResult {
31    /// A result without data.
32    pub fn new(key: impl Into<String>, score: f64) -> Self {
33        Self {
34            key: key.into(),
35            score,
36            data: None,
37        }
38    }
39
40    /// Sets the stored bytes.
41    #[must_use]
42    pub fn with_data(mut self, data: Vec<u8>) -> Self {
43        self.data = Some(data);
44        self
45    }
46}
47
48/// A pluggable way to search a storage backend (`SearchStrategy`).
49///
50/// Backends configured with a strategy call [`index`](SearchStrategy::index) on every write and
51/// delegate [`Storage::search`] to [`search`](SearchStrategy::search).
52///
53/// ```
54/// use strands::storage::search::{SearchStrategy, StorageSearchResult};
55/// use strands::storage::{InMemoryStorage, InMemoryStorageConfig, Storage};
56/// use std::sync::Arc;
57///
58/// struct PrefixMatch;
59///
60/// #[strands::async_trait]
61/// impl SearchStrategy for PrefixMatch {
62///     async fn search(&self, storage: &dyn Storage, query: &str) -> strands::Result<Vec<StorageSearchResult>> {
63///         let keys = storage.list(query).await?;
64///         Ok(keys.into_iter().map(|key| StorageSearchResult::new(key, 1.0)).collect())
65///     }
66/// }
67///
68/// # #[tokio::main(flavor = "current_thread")]
69/// # async fn main() -> strands::Result<()> {
70/// let config = InMemoryStorageConfig::builder().search_strategy(Arc::new(PrefixMatch)).build();
71/// let storage = InMemoryStorage::with_config(config);
72/// storage.write("notes/a.md", b"x").await?;
73/// assert_eq!(storage.search("notes/").await?[0].key, "notes/a.md");
74/// # Ok(())
75/// # }
76/// ```
77#[async_trait]
78pub trait SearchStrategy: Send + Sync + 'static {
79    /// Indexes one entry for later searches; called on each write. Strategies that search on the
80    /// fly (keyword) or manage their own index keep the default no-op.
81    ///
82    /// `key` is relative to `storage`. Namespaced instances of a backend share its strategy and
83    /// pass keys relative to their own prefix, so two entries can arrive with the same key and
84    /// one entry can arrive under different keys. A strategy that keeps its own index should key
85    /// it by where the entry lives (such as [`LocalFileStorage::base_dir`](super::LocalFileStorage::base_dir)
86    /// plus the key), or use a separate storage per index.
87    ///
88    /// # Errors
89    ///
90    /// An error fails the write that triggered it.
91    async fn index(&self, _storage: &dyn Storage, _key: &str, _data: &[u8]) -> Result<()> {
92        Ok(())
93    }
94
95    /// Whether the strategy reads or writes the host filesystem itself, so it
96    /// cannot work on storage routed through a sandbox. `false` by default.
97    fn requires_host_fs(&self) -> bool {
98        false
99    }
100
101    /// The strategy's name for error messages.
102    fn name(&self) -> &str {
103        "SearchStrategy"
104    }
105
106    /// Searches `storage` for `query`, best match first.
107    ///
108    /// # Errors
109    ///
110    /// Returns an error when the search fails.
111    async fn search(&self, storage: &dyn Storage, query: &str) -> Result<Vec<StorageSearchResult>>;
112}