Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ A distributed cache implementation providing reliable resource management and da
### Cache Structure

```text
<prefix>/foo
<prefix>/..
<prefix>/..
<dir>/foo
<dir>/..
<dir>/..
```

- `<prefix>`: User-defined string to identify a cache instance
- `<dir>`: The cached directory, used as given: the cache holds the keys under `<dir>/`, and
`foo/` is the empty-named directory inside `foo`, whose keys are `foo//...`. It also
identifies a cache instance

### Main Types

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
45 changes: 22 additions & 23 deletions src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<C: TypeConfig> {
/// 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.
///
Expand All @@ -91,11 +91,7 @@ impl<C> fmt::Display for Cache<C>
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)
}
}

Expand All @@ -111,22 +107,23 @@ 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::<()>();

static UNIQ: atomic::AtomicU64 = atomic::AtomicU64::new(0);
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,
Expand All @@ -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<Vec<(String, C::Value)>, 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
Expand Down Expand Up @@ -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)
}
Expand Down
24 changes: 13 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,19 @@
//! # Cache Key Structure
//!
//! ```text
//! <prefix>/foo
//! <prefix>/..
//! <prefix>/..
//! <dir>/foo
//! <dir>/..
//! <dir>/..
//! ```
//!
//! - `<prefix>` is a user-defined string to identify a cache instance.
//! - `<dir>` is the cached directory, used as given: the cache holds the keys under `<dir>/`.
//! `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
Expand Down Expand Up @@ -65,14 +67,14 @@
//! | | cancel | |
//! | | | |
//! | | In memory BTree | |
//! | +-+ <prefix>/foo <--+ | |
//! | | <prefix>/... <--+-+ |
//! | | <prefix>/... <--+ | |
//! | +-+ <dir>/foo <--+ | |
//! | | <dir>/... <--+-+ |
//! | | <dir>/... <--+ | |
//! | | | |
//! | + last_seq: u64 <----' Remote Data Store |
//! | <prefix>/foo --+ |
//! | .-> <prefix>/... --+--'
//! | | <prefix>/... --'
//! | <dir>/foo --+ |
//! | .-> <dir>/... --+--'
//! | | <dir>/... --'
//! | |
//! | ... -------------'
//! | Update by other threads
Expand Down
35 changes: 35 additions & 0 deletions tests/cache_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
entries.into_iter().map(|(k, _)| k).collect()
}

let mut cache = Cache::<TestConfig>::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::<TestConfig>::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"]
);
}
Loading