From e4badc4e86715d08feb6ce5f0937482b442d3cba Mon Sep 17 00:00:00 2001 From: Zhang Yanpo Date: Wed, 18 Nov 2026 18:03:51 +0800 Subject: [PATCH] feat: cache: read through `&self`, and without waiting # Summary `Cache` reads take `&self`, and the data is behind a tokio `RwLock` instead of a `Mutex`, so concurrent readers share a cache, by reference or `Arc`, without an outer lock. The new `try_access_now`, `try_get_now` and `try_list_dir_now` never wait: they return `None` while the watcher holds the data, as while it initializes or reconnects. # Details The watcher holds the lock exclusively, briefly to apply each change, and for the whole reset-and-refetch of an initialization. The waiting reads, `try_get`, `try_list_dir`, `try_last_seq` and `try_access`, wait for it as before. The non-waiting reads use `RwLock::try_read`, which is not a future: a lock polled once with `now_or_never()` returned `None` whenever the task's tokio coop budget was spent, even with the lock free, and its caller read the remote store for no reason. `Some(Err(_))` still reports a source that cannot be subscribed. Upgrade tip: `cache_data()` takes `&self` and returns a `RwLockReadGuard` instead of a `MutexGuard`. A caller that kept a cache behind a mutex only to read it can drop the mutex. Fixes: #4 --- README.md | 18 ++-- src/cache.rs | 107 ++++++++++++-------- src/event_watcher.rs | 44 ++++----- tests/cache_api.rs | 4 +- tests/concurrent_same_range.rs | 51 ++++------ tests/concurrent_write.rs | 2 +- tests/multi_watcher_concurrent.rs | 34 +++---- tests/read_now.rs | 159 ++++++++++++++++++++++++++++++ tests/unsupported_subscribe.rs | 10 +- 9 files changed, 301 insertions(+), 128 deletions(-) create mode 100644 tests/read_now.rs diff --git a/README.md b/README.md index 7062442..9e95a4a 100644 --- a/README.md +++ b/README.md @@ -52,21 +52,21 @@ let value = cache.try_get("key").await?; // List all entries under a directory let entries = cache.try_list_dir("dir").await?; + +// Read without waiting: `None` while the cache initializes, reconnects or applies a change +if let Some(value) = cache.try_get_now("key") { + let value = value?; +} ``` ## Concurrency Control -The cache employs a two-level concurrency control mechanism: - -1. **Internal Lock (Mutex)**: Protects concurrent access between user operations and the background cache updater. This lock is held briefly during each operation. - -2. **External Lock (Method Design)**: Public methods require `&mut self` even for read-only operations. This prevents concurrent access to the cache instance from multiple call sites. External synchronization should be implemented by the caller if needed. +The data is behind a read-write lock. Readers share it; the background watcher holds it exclusively, briefly to apply each change, and for the whole reset-and-refetch while it initializes or reconnects. -This design intentionally separates concerns: -- The internal lock handles short-term, fine-grained synchronization with the updater -- The external lock requirement (`&mut self`) enables longer-duration access patterns without blocking the background updater unnecessarily +Every read takes `&self`, so a cache is shared by reference or `Arc` without an outer lock: -Note that despite requiring `&mut self`, all operations are logically read-only with respect to the cache's public API. +- `try_get`, `try_list_dir`, `try_last_seq` and `try_access` wait while the watcher holds the data, e.g. until the cache is initialized. +- `try_get_now`, `try_list_dir_now` and `try_access_now` never wait: they return `None` while the watcher holds the data, and the caller reads the remote data store instead. They are not futures, so they answer whether or not the task's tokio coop budget is spent. ## Initialization Process diff --git a/src/cache.rs b/src/cache.rs index 3ffc56d..772a192 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -19,8 +19,8 @@ use std::sync::Arc; use futures::FutureExt; use log::debug; use tokio::sync::oneshot; -use tokio::sync::Mutex; -use tokio::sync::MutexGuard; +use tokio::sync::RwLock; +use tokio::sync::RwLockReadGuard; use crate::cache_data::CacheData; use crate::errors::Unsupported; @@ -35,28 +35,22 @@ use crate::TypeConfig; /// ## Features /// /// - **Automatic Synchronization**: Background watcher task keeps local cache in sync with remote data store -/// - **Concurrency Control**: Two-level concurrency control mechanism for safe access +/// - **Concurrency Control**: Readers share the data; reads take `&self` /// - **Safe Reconnection**: Automatic recovery from connection failures with state consistency /// - **Consistent Initialization**: Ensures cache is fully initialized before use /// /// ## Concurrency Control /// -/// The cache employs a two-level concurrency control mechanism: +/// The data is behind a read-write lock. Readers share it; the background watcher holds it +/// exclusively, briefly to apply each change, and for the whole reset-and-refetch while it +/// initializes or reconnects. /// -/// 1. **Internal Lock (Mutex)**: Protects concurrent access between user operations and the -/// background cache updater. This lock is held briefly during each operation. +/// Every read takes `&self`, so a cache is shared by reference or `Arc` without an outer lock: /// -/// 2. **External Lock (Method Design)**: Public methods require `&mut self` even for read-only -/// operations. This prevents concurrent access to the cache instance from multiple call sites. -/// External synchronization should be implemented by the caller if needed. -/// -/// This design intentionally separates concerns: -/// - The internal lock handles short-term, fine-grained synchronization with the updater -/// - The external lock requirement (`&mut self`) enables longer-duration access patterns -/// without blocking the background updater unnecessarily -/// -/// Note that despite requiring `&mut self`, all operations are logically read-only -/// with respect to the cache's public API. +/// - `try_get`, `try_list_dir`, `try_last_seq` and `try_access` wait while the watcher holds the +/// data, e.g. until the cache is initialized. +/// - `try_get_now`, `try_list_dir_now` and `try_access_now` never wait: they return `None` while +/// the watcher holds the data, and the caller reads the remote data store instead. /// /// ## Error Handling /// @@ -78,7 +72,7 @@ pub struct Cache { #[allow(dead_code)] watcher_cancel_tx: oneshot::Sender<()>, - data: Arc, Unsupported>>>, + data: Arc, Unsupported>>>, /// A process-wide unique identifier for the cache. Used for debugging purposes. uniq: u64, @@ -125,7 +119,7 @@ where C: TypeConfig let mut cache = Cache { dir, watcher_cancel_tx: cancel_tx, - data: Arc::new(Mutex::new(Err(Unsupported::new("Cache not initialized")))), + data: Arc::new(RwLock::new(Err(Unsupported::new("Cache not initialized")))), uniq, name: name.to_string(), }; @@ -136,14 +130,14 @@ where C: TypeConfig } /// Get a SeqV from the cache by key. - pub async fn try_get(&mut self, key: &str) -> Result, Unsupported> { + pub async fn try_get(&self, key: &str) -> Result, Unsupported> { debug!("Cache::access: try_get({})", key); self.try_access(|cache_data| cache_data.data.get(key).cloned()) .await } /// Get the last sequence number of the cache. - pub async fn try_last_seq(&mut self) -> Result { + pub async fn try_last_seq(&self) -> Result { self.try_access(|cache_data| cache_data.last_seq).await } @@ -151,36 +145,23 @@ where C: TypeConfig /// /// `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, - dir: &str, - ) -> Result, Unsupported> { - let left = format!("{}/", dir); - let right = format!("{}0", dir); - + pub async fn try_list_dir(&self, dir: &str) -> Result, Unsupported> { debug!("Cache::access: try_list_dir({})", dir); - - self.try_access(|cache_data| { - cache_data - .data - .range(left..right) - .map(|(k, v)| (k.to_string(), v.clone())) - .collect() - }) - .await + self.try_access(|cache_data| list_dir(cache_data, dir)) + .await } - /// Get the internal cache data. - pub async fn cache_data(&mut self) -> MutexGuard<'_, Result, Unsupported>> { - self.data.lock().await + /// Get the internal cache data, for reading. + pub async fn cache_data(&self) -> RwLockReadGuard<'_, Result, Unsupported>> { + self.data.read().await } /// Access the cache data in read-only mode. pub async fn try_access( - &mut self, + &self, f: impl FnOnce(&CacheData) -> T, ) -> Result { - let guard = self.data.lock().await; + let guard = self.data.read().await; let g = guard.as_ref().map_err(|e| e.clone())?; @@ -188,6 +169,37 @@ where C: TypeConfig Ok(t) } + /// Run `f` on the cache data if the cache can answer now, without waiting. + /// + /// `None` while the background watcher holds the data exclusively: while it initializes or + /// reconnects, or applies a change. `Some(Err(_))` if the remote data store cannot be + /// subscribed. The caller reads the remote data store instead of the cache on `None`. + /// + /// Readers share the data, so concurrent reads do not push each other away. The read is not + /// a future: it answers whether or not the task's tokio coop budget is spent. + pub fn try_access_now( + &self, + f: impl FnOnce(&CacheData) -> T, + ) -> Option> { + let guard = self.data.try_read().ok()?; + Some(guard.as_ref().map(f).map_err(|e| e.clone())) + } + + /// The value of `key` if the cache can answer now, see [`Self::try_access_now`]. + pub fn try_get_now(&self, key: &str) -> Option, Unsupported>> { + self.try_access_now(|cache_data| cache_data.data.get(key).cloned()) + } + + /// The entries under the directory `dir` if the cache can answer now, see + /// [`Self::try_access_now`] and [`Self::try_list_dir`]. + #[allow(clippy::type_complexity)] + pub fn try_list_dir_now( + &self, + dir: &str, + ) -> Option, Unsupported>> { + self.try_access_now(|cache_data| list_dir(cache_data, dir)) + } + /// Spawns a background task to watch to the remote data store key value change events, feed to the cache. /// /// It does not return until a full copy of the cache is received. @@ -227,3 +239,14 @@ where C: TypeConfig (left, right) } } + +/// The entries under the directory `dir`: the keys under `{dir}/`, `dir` used as given. +fn list_dir(cache_data: &CacheData, dir: &str) -> Vec<(String, C::Value)> { + let left = format!("{}/", dir); + let right = format!("{}0", dir); + cache_data + .data + .range(left..right) + .map(|(k, v)| (k.to_string(), v.clone())) + .collect() +} diff --git a/src/event_watcher.rs b/src/event_watcher.rs index bd35f36..b1db9c9 100644 --- a/src/event_watcher.rs +++ b/src/event_watcher.rs @@ -24,7 +24,7 @@ use log::error; use log::info; use log::warn; use tokio::sync::oneshot; -use tokio::sync::Mutex; +use tokio::sync::RwLock; use crate::cache_data::CacheData; use crate::errors::ConnectionClosed; @@ -46,8 +46,8 @@ pub(crate) struct EventWatcher { /// The client to interact with the remote data store. pub(crate) source: C::Source, - /// The shared cache data protected by a mutex. - pub(crate) data: Arc, Unsupported>>>, + /// The shared cache data, written by this watcher and read concurrently by the users. + pub(crate) data: Arc, Unsupported>>>, /// Contains descriptive information of this watcher. pub(crate) name: String, @@ -94,7 +94,7 @@ where C: TypeConfig // 1. Retry until a successful connection is established and cache is initialized. let strm = { // Hold the lock until the cache is fully initialized. - let mut cache_data = self.data.lock().await; + let mut cache_data = self.data.write().await; // The data lock is acquired and will be kept until the cache is fully initialized. // At this point, we notify the caller that initialization has started by consuming @@ -274,7 +274,7 @@ where C: TypeConfig } }; - let mut cache_data = self.data.lock().await; + let mut cache_data = self.data.write().await; // Safe unwrap: before entering this method, the cache data is ensured to be Ok. let d = cache_data.as_mut().unwrap(); @@ -294,7 +294,7 @@ mod tests { use std::future::Future; use std::sync::Arc; - use tokio::sync::Mutex; + use tokio::sync::RwLock; use super::*; use crate::testing::source::TestSource; @@ -329,7 +329,7 @@ mod tests { left: "start".to_string(), right: "end".to_string(), source: test_source, - data: Arc::new(Mutex::new(Ok(CacheData::default()))), + data: Arc::new(RwLock::new(Ok(CacheData::default()))), name: "test-watcher".to_string(), }; @@ -347,7 +347,7 @@ mod tests { .insert_for_test("initial_key", Val::new(1, "initial_value")) .await; - let cache = Arc::new(Mutex::new(Ok(CacheData::default()))); + let cache = Arc::new(RwLock::new(Ok(CacheData::default()))); let watcher = EventWatcher:: { left: "".to_string(), right: "z".to_string(), @@ -374,7 +374,7 @@ mod tests { // 检查初始数据已同步到本地cache { - let cache_data = cache.lock().await; + let cache_data = cache.read().await; let cache_data = cache_data.as_ref().unwrap(); assert_eq!( cache_data.data.get("initial_key").unwrap(), @@ -394,7 +394,7 @@ mod tests { // 检查本地cache内容 { - let cache_data = cache.lock().await; + let cache_data = cache.read().await; let cache_data = cache_data.as_ref().unwrap(); assert_eq!( cache_data.data.get("key1").unwrap(), @@ -446,7 +446,7 @@ mod tests { left: "".to_string(), right: "z".to_string(), source: TestSource::new(), - data: Arc::new(Mutex::new(Ok(CacheData::default()))), + data: Arc::new(RwLock::new(Ok(CacheData::default()))), name: "test-init-cache".to_string(), }; @@ -488,7 +488,7 @@ mod tests { left: "".to_string(), right: "z".to_string(), source: TestSource::new(), - data: Arc::new(Mutex::new(Ok(CacheData::default()))), + data: Arc::new(RwLock::new(Ok(CacheData::default()))), name: "test-init-cache-error".to_string(), }; @@ -523,7 +523,7 @@ mod tests { ]; let stream = stream::iter(events); - let cache = Arc::new(Mutex::new(Ok(CacheData::default()))); + let cache = Arc::new(RwLock::new(Ok(CacheData::default()))); let mut watcher = EventWatcher:: { left: "".to_string(), right: "z".to_string(), @@ -544,7 +544,7 @@ mod tests { assert!(res.is_err()); // 检查cache内容 - let cache_data = cache.lock().await; + let cache_data = cache.read().await; let cache_data = cache_data.as_ref().unwrap(); assert_eq!(cache_data.data.get("k1"), Some(&Val::new(1, "v1"))); assert_eq!(cache_data.data.get("k2"), Some(&Val::new(2, "v2"))); @@ -560,7 +560,7 @@ mod tests { // 构造一个永不结束的流 let stream = stream::pending(); - let cache = Arc::new(Mutex::new(Ok(CacheData::default()))); + let cache = Arc::new(RwLock::new(Ok(CacheData::default()))); let mut watcher = EventWatcher:: { left: "".to_string(), right: "z".to_string(), @@ -581,7 +581,7 @@ mod tests { assert!(res.is_ok()); // 检查cache内容应为空 - let cache_data = cache.lock().await; + let cache_data = cache.read().await; let cache_data = cache_data.as_ref().unwrap(); assert!(cache_data.data.is_empty()); assert_eq!(cache_data.last_seq, 0); @@ -611,7 +611,7 @@ mod tests { ]; let stream = stream::iter(events); - let cache = Arc::new(Mutex::new(Ok(CacheData::default()))); + let cache = Arc::new(RwLock::new(Ok(CacheData::default()))); let mut watcher = EventWatcher:: { left: "".to_string(), right: "z".to_string(), @@ -630,7 +630,7 @@ mod tests { assert!(err.to_string().contains("test error")); // 检查cache内容只包含第一个事件 - let cache_data = cache.lock().await; + let cache_data = cache.read().await; let cache_data = cache_data.as_ref().unwrap(); assert_eq!(cache_data.data.get("k1"), Some(&Val::new(1, "v1"))); assert!(!cache_data.data.contains_key("k2")); @@ -660,7 +660,7 @@ mod tests { ]; let stream = stream::iter(events); - let cache = Arc::new(Mutex::new(Ok(CacheData::default()))); + let cache = Arc::new(RwLock::new(Ok(CacheData::default()))); let mut watcher = EventWatcher:: { left: "".to_string(), right: "z".to_string(), @@ -676,7 +676,7 @@ mod tests { let _ = watcher.watch_kv_changes(stream, cancel).await; // 检查panic前cache内容(只处理第一个Change) - let cache_data = cache.lock().await; + let cache_data = cache.read().await; let cache_data = cache_data.as_ref().unwrap(); assert_eq!(cache_data.data.get("k1"), Some(&Val::new(1, "v1"))); assert!(!cache_data.data.contains_key("k2")); @@ -710,7 +710,7 @@ mod tests { ]; let stream = stream::iter(events); - let cache = Arc::new(Mutex::new(Ok(CacheData::default()))); + let cache = Arc::new(RwLock::new(Ok(CacheData::default()))); let mut watcher = EventWatcher:: { left: "".to_string(), right: "z".to_string(), @@ -725,7 +725,7 @@ mod tests { }; let _ = watcher.watch_kv_changes(stream, cancel).await; - let cache_data = cache.lock().await; + let cache_data = cache.read().await; let cache_data = cache_data.as_ref().unwrap(); // last_seq应为最大值5,内容为最后一次变更 assert_eq!(cache_data.last_seq, 5); diff --git a/tests/cache_api.rs b/tests/cache_api.rs index a9a2617..556fd00 100644 --- a/tests/cache_api.rs +++ b/tests/cache_api.rs @@ -324,7 +324,7 @@ async fn test_cache_dir_is_used_as_given() { entries.into_iter().map(|(k, _)| k).collect() } - let mut cache = Cache::::new(source.clone(), "dirs", "dirs").await; + let 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" @@ -337,7 +337,7 @@ async fn test_cache_dir_is_used_as_given() { ]); // A cache of the empty-named directory holds its keys only. - let mut empty_named = Cache::::new(source.clone(), "dirs/", "dirs-empty").await; + let 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!( diff --git a/tests/concurrent_same_range.rs b/tests/concurrent_same_range.rs index 4007d6f..ef51a72 100644 --- a/tests/concurrent_same_range.rs +++ b/tests/concurrent_same_range.rs @@ -252,49 +252,40 @@ async fn test_concurrent_same_range_watchers() -> Result<(), Box::new(source.clone(), "continuous", "continuous-test").await; + let cache = Cache::::new(source.clone(), "continuous", "continuous-test").await; // 2. Shared state for background writer coordination // These atomic variables allow safe communication between the main test thread diff --git a/tests/multi_watcher_concurrent.rs b/tests/multi_watcher_concurrent.rs index 3388076..1f7247e 100644 --- a/tests/multi_watcher_concurrent.rs +++ b/tests/multi_watcher_concurrent.rs @@ -296,33 +296,27 @@ async fn test_multi_watcher_concurrent() { } }); - let rapid_reads_a = tokio::spawn({ - let mut cache_a = cache_a; - async move { - for _ in 0..10 { - let _ = cache_a.try_get("app/user/user1").await; - let _ = cache_a.try_list_dir("app/user").await; - sleep(Duration::from_millis(8)).await; - } - cache_a + let rapid_reads_a = tokio::spawn(async move { + for _ in 0..10 { + let _ = cache_a.try_get("app/user/user1").await; + let _ = cache_a.try_list_dir("app/user").await; + sleep(Duration::from_millis(8)).await; } + cache_a }); - let rapid_reads_b = tokio::spawn({ - let mut cache_b = cache_b; - async move { - for _ in 0..10 { - let _ = cache_b.try_get("app/config/setting1").await; - let _ = cache_b.try_list_dir("app").await; - sleep(Duration::from_millis(6)).await; - } - cache_b + let rapid_reads_b = tokio::spawn(async move { + for _ in 0..10 { + let _ = cache_b.try_get("app/config/setting1").await; + let _ = cache_b.try_list_dir("app").await; + sleep(Duration::from_millis(6)).await; } + cache_b }); let (_, cache_a, cache_b) = tokio::join!(rapid_writes, rapid_reads_a, rapid_reads_b); - let mut cache_a = cache_a.unwrap(); - let mut cache_b = cache_b.unwrap(); + let cache_a = cache_a.unwrap(); + let cache_b = cache_b.unwrap(); // Wait for final synchronization sleep(Duration::from_millis(200)).await; diff --git a/tests/read_now.rs b/tests/read_now.rs new file mode 100644 index 0000000..63ab3d6 --- /dev/null +++ b/tests/read_now.rs @@ -0,0 +1,159 @@ +// Copyright 2021 Datafuse Labs +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The non-blocking `&self` reads: `try_get_now`, `try_list_dir_now` and `try_access_now`. +//! +//! They answer at once from a ready cache, to any number of concurrent readers sharing it, and +//! return `None` while the cache cannot answer, without waiting for it. + +use std::sync::Arc; +use std::time::Duration; + +use futures::stream; +use futures::FutureExt; +use futures::StreamExt; +use sub_cache::errors::SubscribeError; +use sub_cache::event_stream::EventStream; +use sub_cache::testing::source::TestSource; +use sub_cache::testing::source::Val; +use sub_cache::testing::types::TestConfig; +use sub_cache::Cache; +use sub_cache::Source; +use sub_cache::TypeConfig; +use tokio::time::sleep; + +/// Wait until the cache answers `key` with `data` without waiting. +async fn wait_for_now(cache: &Cache, key: &str, data: &str) { + for _ in 0..100 { + if let Some(Ok(Some(v))) = cache.try_get_now(key) { + if v.data == data { + return; + } + } + sleep(Duration::from_millis(20)).await; + } + panic!("the cache did not answer {key} = {data} without waiting"); +} + +#[tokio::test] +async fn test_read_now_from_a_ready_cache() { + let source = TestSource::new(); + source.set("now/a", Some("a")).await; + source.set("now/d/x", Some("x")).await; + source.set("other/b", Some("b")).await; + + let cache = Arc::new(Cache::::new(source.clone(), "now", "read-now").await); + wait_for_now(&cache, "now/a", "a").await; + + // Readers share the cache without an outer lock. + let readers = (0..8).map(|_| { + let cache = cache.clone(); + tokio::spawn(async move { + let a = cache.try_get_now("now/a").unwrap().unwrap().map(|v| v.data); + let missing = cache.try_get_now("now/missing").unwrap().unwrap(); + let dir = cache.try_list_dir_now("now/d").unwrap().unwrap(); + let dir = dir + .into_iter() + .map(|(k, v)| (k, v.data)) + .collect::>(); + (a, missing, dir) + }) + }); + for reader in readers { + let (a, missing, dir) = reader.await.unwrap(); + assert_eq!(a.as_deref(), Some("a")); + assert_eq!(missing, None); + assert_eq!(dir, vec![("now/d/x".to_string(), "x".to_string())]); + } + + // Changes reach the reads. + source.set("now/a", Some("a2")).await; + wait_for_now(&cache, "now/a", "a2").await; +} + +/// A tokio mutex lock polled once fails when the task's coop budget is spent, though the mutex +/// is free; a read that does not wait still answers. +#[tokio::test] +async fn test_read_now_with_spent_coop_budget() { + let source = TestSource::new(); + source.set("budget/a", Some("a")).await; + let cache = Cache::::new(source.clone(), "budget", "read-now-budget").await; + wait_for_now(&cache, "budget/a", "a").await; + + let free = tokio::sync::Mutex::new(()); + let spent = (0..10_000).any(|_| free.lock().now_or_never().is_none()); + assert!( + spent, + "a free tokio mutex always locked: the coop budget was never spent" + ); + + let a = cache + .try_get_now("budget/a") + .unwrap() + .unwrap() + .map(|v| v.data); + assert_eq!(a.as_deref(), Some("a")); +} + +/// A source whose stream never delivers an event: the cache stays initializing. +#[derive(Debug, Clone)] +struct SilentSource; + +#[async_trait::async_trait] +impl Source for SilentSource { + async fn subscribe( + &self, + _left: &str, + _right: &str, + ) -> Result, SubscribeError> { + Ok(stream::pending().boxed()) + } +} + +#[derive(Debug, Default)] +struct SilentConfig; + +impl TypeConfig for SilentConfig { + type Value = Val; + type Source = SilentSource; + + fn value_seq(value: &Self::Value) -> u64 { + value.seq + } + + fn spawn(future: F, _name: impl ToString) + where + F: std::future::Future + Send + 'static, + F::Output: Send + 'static, + { + tokio::spawn(future); + } +} + +/// While the cache initializes, a read that does not wait answers `None` at once; a read that +/// waits does not answer. +#[tokio::test] +async fn test_read_now_while_initializing() { + let cache = Cache::::new(SilentSource, "silent", "read-now-silent").await; + + assert!(cache.try_get_now("silent/a").is_none()); + assert!(cache.try_list_dir_now("silent").is_none()); + assert!(cache.try_access_now(|data| data.last_seq).is_none()); + + let waiting = tokio::time::timeout(Duration::from_millis(100), cache.try_get("silent/a")); + assert!( + waiting.await.is_err(), + "a read that waits answered an initializing cache" + ); +} diff --git a/tests/unsupported_subscribe.rs b/tests/unsupported_subscribe.rs index 6eb45d0..6b8aef9 100644 --- a/tests/unsupported_subscribe.rs +++ b/tests/unsupported_subscribe.rs @@ -93,7 +93,7 @@ async fn test_unsupported_subscribe() { // 2. Create cache with the unsupported source // The cache creation should complete, but the background watcher should fail - let mut cache = Cache::::new( + let cache = Cache::::new( unsupported_source, "unsupported_test", "unsupported-test", @@ -200,6 +200,12 @@ async fn test_unsupported_subscribe() { ); } + // 7. The reads that do not wait return the error too, not `None`. + let now = cache.try_access_now(|data| data.last_seq); + assert!(matches!(now, Some(Err(_))), "try_access_now: {now:?}"); + let now = cache.try_get_now("unsupported_test/key"); + assert!(matches!(now, Some(Err(_))), "try_get_now: {now:?}"); + println!("Unsupported subscription test completed successfully!"); println!("Cache properly entered degraded state and consistently returns Unsupported errors"); } @@ -216,7 +222,7 @@ async fn test_unsupported_subscribe_different_errors() { for (i, error_message) in test_cases.iter().enumerate() { let unsupported_source = UnsupportedSource::new(error_message); - let mut cache = Cache::::new( + let cache = Cache::::new( unsupported_source, &format!("unsupported_test_{i}"), &format!("unsupported-test-{i}"),