diff --git a/README.md b/README.md index 8df66e3..7062442 100644 --- a/README.md +++ b/README.md @@ -14,12 +14,14 @@ A distributed cache implementation providing reliable resource management and da ### Cache Structure ```text -/foo -/.. -/.. +/foo +/.. +/.. ``` -- ``: User-defined string to identify a cache instance +- ``: The cached directory, used as given: the cache holds the keys under `/`, and + `foo/` is the empty-named directory inside `foo`, whose keys are `foo//...`. It also + identifies a cache instance ### Main Types @@ -48,8 +50,8 @@ cache.try_access(|c: &CacheData| { // Get a specific value let value = cache.try_get("key").await?; -// List all entries under a prefix -let entries = cache.try_list_dir("prefix").await?; +// List all entries under a directory +let entries = cache.try_list_dir("dir").await?; ``` ## Concurrency Control @@ -70,7 +72,7 @@ Note that despite requiring `&mut self`, all operations are logically read-only When a `Cache` is created, it goes through the following steps: -1. Creates a new instance with specified prefix and context +1. Creates a new instance of the specified directory and name 2. Spawns a background task to watch for key-value changes 3. Establishes a watch stream to the remote data store 4. Fetches and processes initial data diff --git a/src/cache.rs b/src/cache.rs index 8514c4a..3ffc56d 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -66,10 +66,10 @@ use crate::TypeConfig; /// - Re-fetching all data to ensure consistency /// - Users are shielded from transient errors through the abstraction pub struct Cache { - /// The dir path to store the cache ids, without trailing slash. + /// The cached directory, used as given: the cache holds the keys under `{dir}/`. /// - /// Such as `foo`, not `foo/` - prefix: String, + /// `foo` is the directory `foo`, and `foo/` the empty-named directory inside it. + dir: String, /// The sender to cancel the background watcher task. /// @@ -91,11 +91,7 @@ impl fmt::Display for Cache where C: TypeConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "Cache({})({}/)[uniq={}]", - self.name, self.prefix, self.uniq - ) + write!(f, "Cache({})({}/)[uniq={}]", self.name, self.dir, self.uniq) } } @@ -111,14 +107,15 @@ where C: TypeConfig /// # Parameters /// /// * `source` - The client to interact with the remote data store. - /// * `prefix` - The prefix of the cache name and also the directory name to store in remote data store. - /// * `ctx` - The context info of the cache, used for debugging purposes. + /// * `dir` - The directory to cache, used as given: the cache holds the keys under `{dir}/`. + /// `foo` is the directory `foo`, and `foo/` the empty-named directory inside it, whose keys + /// are `foo//...`. A trailing `/` is never stripped. + /// * `name` - The name of the cache, used for debugging purposes. /// /// This method spawns a background task to watch to the remote data store key value change events. /// The task will be notified to quit when this instance is dropped. - pub async fn new(source: C::Source, prefix: impl ToString, name: impl ToString) -> Self { - let prefix = prefix.to_string(); - let prefix = prefix.trim_end_matches('/').to_string(); + pub async fn new(source: C::Source, dir: impl ToString, name: impl ToString) -> Self { + let dir = dir.to_string(); let (cancel_tx, cancel_rx) = oneshot::channel::<()>(); @@ -126,7 +123,7 @@ where C: TypeConfig let uniq = UNIQ.fetch_add(1, atomic::Ordering::SeqCst); let mut cache = Cache { - prefix, + dir, watcher_cancel_tx: cancel_tx, data: Arc::new(Mutex::new(Err(Unsupported::new("Cache not initialized")))), uniq, @@ -150,16 +147,18 @@ where C: TypeConfig self.try_access(|cache_data| cache_data.last_seq).await } - /// List all entries in the cache directory. + /// List the entries under the directory `dir`, the keys under `{dir}/`. + /// + /// `dir` is used as given, as in [`Cache::new`]: `foo/` lists the keys `foo//...` of the + /// empty-named directory inside `foo`. pub async fn try_list_dir( &mut self, - prefix: &str, + dir: &str, ) -> Result, Unsupported> { - let prefix = prefix.trim_end_matches('/'); - let left = format!("{}/", prefix); - let right = format!("{}0", prefix); + let left = format!("{}/", dir); + let right = format!("{}0", dir); - debug!("Cache::access: try_list_dir({})", prefix); + debug!("Cache::access: try_list_dir({})", dir); self.try_access(|cache_data| { cache_data @@ -220,10 +219,10 @@ where C: TypeConfig /// The left-close right-open range for the cached keys. /// /// Since `'0'` is the next char of `'/'`. - /// `[prefix + "/", prefix + "0")` is the range of the cache ids. + /// `[dir + "/", dir + "0")` is the range of the cache ids. fn key_range(&self) -> (String, String) { - let left = self.prefix.clone() + "/"; - let right = self.prefix.clone() + "0"; + let left = self.dir.clone() + "/"; + let right = self.dir.clone() + "0"; (left, right) } diff --git a/src/lib.rs b/src/lib.rs index cd9d08d..6199c8a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,17 +27,19 @@ //! # Cache Key Structure //! //! ```text -//! /foo -//! /.. -//! /.. +//! /foo +//! /.. +//! /.. //! ``` //! -//! - `` is a user-defined string to identify a cache instance. +//! - `` is the cached directory, used as given: the cache holds the keys under `/`. +//! `foo/` is the empty-named directory inside `foo`, whose keys are `foo//...`. The directory +//! also identifies a cache instance. //! //! # Initialization Process //! //! When a [`Cache`] is created, it: -//! 1. Creates a new instance with the specified prefix +//! 1. Creates a new instance of the specified directory //! 2. Spawns a background task to watch for changes //! 3. Establishes a watch stream with initial flush //! 4. Fetches and processes initial data @@ -65,14 +67,14 @@ //! | | cancel | | //! | | | | //! | | In memory BTree | | -//! | +-+ /foo <--+ | | -//! | | /... <--+-+ | -//! | | /... <--+ | | +//! | +-+ /foo <--+ | | +//! | | /... <--+-+ | +//! | | /... <--+ | | //! | | | | //! | + last_seq: u64 <----' Remote Data Store | -//! | /foo --+ | -//! | .-> /... --+--' -//! | | /... --' +//! | /foo --+ | +//! | .-> /... --+--' +//! | | /... --' //! | | //! | ... -------------' //! | Update by other threads diff --git a/tests/cache_api.rs b/tests/cache_api.rs index ac0ea44..a9a2617 100644 --- a/tests/cache_api.rs +++ b/tests/cache_api.rs @@ -310,3 +310,38 @@ async fn test_cache_api_error_handling() { println!("Cache API error handling test completed successfully!"); } + +/// A directory is used as given, and never loses a trailing `/`: `dirs/` is the empty-named +/// directory inside `dirs`, whose keys are `dirs//...`. +#[tokio::test] +async fn test_cache_dir_is_used_as_given() { + let source = TestSource::new(); + source.set("dirs/a", Some("a")).await; + source.set("dirs//b", Some("b")).await; + source.set("dirs///c", Some("c")).await; + + fn keys(entries: Vec<(String, sub_cache::testing::source::Val)>) -> Vec { + entries.into_iter().map(|(k, _)| k).collect() + } + + let mut cache = Cache::::new(source.clone(), "dirs", "dirs").await; + sleep(Duration::from_millis(100)).await; + assert_eq!(keys(cache.try_list_dir("dirs").await.unwrap()), vec![ + "dirs///c", "dirs//b", "dirs/a" + ]); + assert_eq!(keys(cache.try_list_dir("dirs/").await.unwrap()), vec![ + "dirs///c", "dirs//b" + ]); + assert_eq!(keys(cache.try_list_dir("dirs//").await.unwrap()), vec![ + "dirs///c" + ]); + + // A cache of the empty-named directory holds its keys only. + let mut empty_named = Cache::::new(source.clone(), "dirs/", "dirs-empty").await; + sleep(Duration::from_millis(100)).await; + assert_eq!(empty_named.try_get("dirs/a").await.unwrap(), None); + assert_eq!( + keys(empty_named.try_list_dir("dirs/").await.unwrap()), + vec!["dirs///c", "dirs//b"] + ); +}