From 30175f8a4ac73fbbaf2e2a6710cf17d10ed5f287 Mon Sep 17 00:00:00 2001 From: BohuTANG Date: Sun, 15 Nov 2026 09:27:45 +0800 Subject: [PATCH] feat: add CacheReader for shared non-blocking reads and resync Replace the internal Mutex with an RwLock and add Cache::reader(), a cloneable handle whose try_access_now() never waits: it returns None while the watcher holds the data exclusively (initial fetch, reconnect, applying a change), so callers can fall back to the remote store instead of queueing behind it. CacheReader::request_resync() makes the watcher drop its stream and re-fetch everything; callers use it when they detect that a stream silently stopped delivering, e.g. a half-open connection. Reconnect delays get a random factor in [0.5, 1.5) so that many caches seeing the same failure do not retry in lockstep. Bump version to 0.3.0. --- Cargo.toml | 2 +- src/cache.rs | 80 +++++++++++++++++++++++++++---- src/event_watcher.rs | 79 ++++++++++++++++++++---------- src/lib.rs | 2 + src/testing/source.rs | 18 +++++++ tests/reader_resync.rs | 106 +++++++++++++++++++++++++++++++++++++++++ 6 files changed, 253 insertions(+), 34 deletions(-) create mode 100644 tests/reader_resync.rs diff --git a/Cargo.toml b/Cargo.toml index 7f0db80..072629d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ A distributed cache implementation that: - Handles connection failures with automatic recovery - Ensures data consistency through sequence number tracking """ -version = "0.2.1" +version = "0.3.0" authors = ["Databend Authors "] license = "Apache-2.0" publish = false diff --git a/src/cache.rs b/src/cache.rs index 8514c4a..e452a25 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -19,8 +19,9 @@ 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::Notify; +use tokio::sync::RwLock; +use tokio::sync::RwLockWriteGuard; use crate::cache_data::CacheData; use crate::errors::Unsupported; @@ -43,8 +44,9 @@ use crate::TypeConfig; /// /// 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. +/// 1. **Internal Lock (RwLock)**: Protects concurrent access between user operations and the +/// background cache updater. Readers share it; the updater holds it exclusively and briefly +/// for each change, and for the whole reset-and-refetch during (re)initialization. /// /// 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. @@ -78,7 +80,10 @@ pub struct Cache { #[allow(dead_code)] watcher_cancel_tx: oneshot::Sender<()>, - data: Arc, Unsupported>>>, + data: Arc, Unsupported>>>, + + /// Wakes the background watcher to drop the current stream and re-fetch everything. + resync: Arc, /// A process-wide unique identifier for the cache. Used for debugging purposes. uniq: u64, @@ -128,7 +133,8 @@ where C: TypeConfig let mut cache = Cache { prefix, 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")))), + resync: Arc::new(Notify::new()), uniq, name: name.to_string(), }; @@ -172,8 +178,19 @@ where C: TypeConfig } /// Get the internal cache data. - pub async fn cache_data(&mut self) -> MutexGuard<'_, Result, Unsupported>> { - self.data.lock().await + pub async fn cache_data(&mut self) -> RwLockWriteGuard<'_, Result, Unsupported>> { + self.data.write().await + } + + /// Return a cloneable read-only handle that can be shared by concurrent readers. + /// + /// The handle does not keep the cache alive: once the [`Cache`] is dropped the watcher stops + /// and the handle keeps returning the last state it saw. + pub fn reader(&self) -> CacheReader { + CacheReader { + data: self.data.clone(), + resync: self.resync.clone(), + } } /// Access the cache data in read-only mode. @@ -181,7 +198,7 @@ where C: TypeConfig &mut 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())?; @@ -201,6 +218,7 @@ where C: TypeConfig right, source, data: self.data.clone(), + resync: self.resync.clone(), name: watcher_name.to_string(), }; @@ -228,3 +246,47 @@ where C: TypeConfig (left, right) } } + +/// A cloneable, read-only view of a [`Cache`] for concurrent readers. +/// +/// Reads never wait: while the watcher holds the data exclusively (initial fetch, reconnect, or +/// applying a change) they return `None`, so a caller can fall back to the remote store instead of +/// queueing behind it. +pub struct CacheReader { + data: Arc, Unsupported>>>, + resync: Arc, +} + +impl Clone for CacheReader { + fn clone(&self) -> Self { + CacheReader { + data: self.data.clone(), + resync: self.resync.clone(), + } + } +} + +impl CacheReader +where C: TypeConfig +{ + /// Run `f` on the cache data if it is readable right now. + /// + /// Returns `None` if the watcher currently holds the data exclusively, and `Some(Err(_))` if + /// the cache is not initialized or the remote store does not support subscribing. + 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())) + } + + /// Ask the watcher to drop the current stream, reset the data and re-fetch everything. + /// + /// Used when the caller detects that the cache stopped following the remote store, e.g. a + /// half-open connection that never reports an error. Readers get `None` until the re-fetch + /// completes. + pub fn request_resync(&self) { + self.resync.notify_one(); + } +} diff --git a/src/event_watcher.rs b/src/event_watcher.rs index bd35f36..b9bdc16 100644 --- a/src/event_watcher.rs +++ b/src/event_watcher.rs @@ -15,6 +15,7 @@ use std::future::Future; use std::sync::Arc; use std::time::Duration; +use std::time::SystemTime; use futures::FutureExt; use futures::Stream; @@ -24,7 +25,8 @@ use log::error; use log::info; use log::warn; use tokio::sync::oneshot; -use tokio::sync::Mutex; +use tokio::sync::Notify; +use tokio::sync::RwLock; use crate::cache_data::CacheData; use crate::errors::ConnectionClosed; @@ -46,13 +48,26 @@ 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 users. + pub(crate) data: Arc, Unsupported>>>, + + /// Notified by [`crate::CacheReader::request_resync`] to drop the stream and re-fetch. + pub(crate) resync: Arc, /// Contains descriptive information of this watcher. pub(crate) name: String, } +/// Scale `d` by a pseudo-random factor in `[0.5, 1.5)`, so that many caches reconnecting after +/// the same remote failure do not retry in lockstep. +fn jitter(d: Duration) -> Duration { + let nanos = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map(|t| t.subsec_nanos()) + .unwrap_or_default(); + d * (500 + nanos % 1000) / 1000 +} + impl EventWatcher where C: TypeConfig { @@ -94,7 +109,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 @@ -163,7 +178,8 @@ where C: TypeConfig "{} watcher loop exited with error: {}; reset cache and re-fetch all data to re-establish", self.name, e ); - // continue + // Spread the re-subscribe of all caches that saw the same failure. + sleep = Some((jitter(Duration::from_millis(100)), e.to_string())); } } } @@ -221,7 +237,7 @@ where C: TypeConfig self.name, conn_err, sleep_duration ); - tokio::time::sleep(sleep_duration).await; + tokio::time::sleep(jitter(sleep_duration)).await; sleep_duration = std::cmp::min(sleep_duration * 3 / 2, max_sleep); } } @@ -254,6 +270,11 @@ where C: TypeConfig return Ok(()); } + _ = self.resync.notified().fuse() => { + warn!("{}: resync requested; drop the watch stream and re-fetch", self.name); + return Err(ConnectionClosed::new_str("resync requested").context(&self.name)); + } + watch_result = strm.try_next().fuse() => { watch_result } @@ -274,7 +295,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 +315,8 @@ mod tests { use std::future::Future; use std::sync::Arc; - use tokio::sync::Mutex; + use tokio::sync::Notify; + use tokio::sync::RwLock; use super::*; use crate::testing::source::TestSource; @@ -329,7 +351,8 @@ 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()))), + resync: Arc::new(Notify::new()), name: "test-watcher".to_string(), }; @@ -347,12 +370,13 @@ 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(), source: test_source.clone(), data: cache.clone(), + resync: Arc::new(Notify::new()), name: "test-integration".to_string(), }; @@ -374,7 +398,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 +418,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 +470,8 @@ 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()))), + resync: Arc::new(Notify::new()), name: "test-init-cache".to_string(), }; @@ -488,7 +513,8 @@ 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()))), + resync: Arc::new(Notify::new()), name: "test-init-cache-error".to_string(), }; @@ -523,12 +549,13 @@ 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(), source: TestSource::new(), data: cache.clone(), + resync: Arc::new(Notify::new()), name: "test-watch-kv-changes".to_string(), }; @@ -544,7 +571,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,12 +587,13 @@ 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(), source: TestSource::new(), data: cache.clone(), + resync: Arc::new(Notify::new()), name: "test-watch-kv-changes-cancel".to_string(), }; @@ -581,7 +609,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,12 +639,13 @@ 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(), source: TestSource::new(), data: cache.clone(), + resync: Arc::new(Notify::new()), name: "test-watch-kv-changes-error".to_string(), }; @@ -630,7 +659,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,12 +689,13 @@ 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(), source: TestSource::new(), data: cache.clone(), + resync: Arc::new(Notify::new()), name: "test-watch-kv-changes-unexpected".to_string(), }; @@ -676,7 +706,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,12 +740,13 @@ 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(), source: TestSource::new(), data: cache.clone(), + resync: Arc::new(Notify::new()), name: "test-watch-kv-changes-multi-update".to_string(), }; @@ -725,7 +756,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/src/lib.rs b/src/lib.rs index cd9d08d..303d2a6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -84,6 +84,8 @@ mod event_watcher; mod type_config; pub use cache::Cache; +pub use cache::CacheReader; +pub use cache_data::CacheData; pub use type_config::Source; pub use type_config::TypeConfig; diff --git a/src/testing/source.rs b/src/testing/source.rs index 302c91c..97214e1 100644 --- a/src/testing/source.rs +++ b/src/testing/source.rs @@ -142,6 +142,24 @@ impl TestSource { state.subscriptions.clear(); } + /// Change a key without notifying any subscriber. + /// + /// Simulates a stream that silently stopped delivering events, such as a half-open + /// connection: the source moves on while the cache keeps its old view. + pub async fn set_silently(&self, key: &str, value: Option<&str>) { + let mut state = self.state.lock().await; + state.seq_counter += 1; + let new_seq = state.seq_counter; + match value { + Some(v) => { + state.data.insert(key.to_string(), Val::new(new_seq, v)); + } + None => { + state.data.remove(key); + } + } + } + #[cfg(test)] pub async fn insert_for_test(&self, key: impl ToString, val: Val) { let mut state = self.state.lock().await; diff --git a/tests/reader_resync.rs b/tests/reader_resync.rs new file mode 100644 index 0000000..ae71bf9 --- /dev/null +++ b/tests/reader_resync.rs @@ -0,0 +1,106 @@ +// 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. + +//! `CacheReader`: shared non-blocking reads, and `request_resync` recovering a stalled stream. + +use std::time::Duration; + +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::CacheReader; +use tokio::time::sleep; + +fn read(reader: &CacheReader, key: &str) -> Option> { + reader + .try_access_now(|d| d.data.get(key).cloned()) + .and_then(Result::ok) +} + +async fn wait_for(reader: &CacheReader, key: &str, want: Option) { + for _ in 0..100 { + if read(reader, key) == Some(want.clone()) { + return; + } + sleep(Duration::from_millis(20)).await; + } + panic!( + "{key} did not become {want:?}, last {:?}", + read(reader, key) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn test_concurrent_readers_share_access() { + let source = TestSource::new(); + source.set("/k1", Some("v1")).await; + let cache = Cache::::new(source.clone(), "", "reader-shared").await; + let reader = cache.reader(); + wait_for(&reader, "/k1", Some(Val::new(1, "v1"))).await; + + // Hold one read access while others read: shared access must not make them fall back. + let held = reader.clone(); + let others = reader.clone(); + let got = held + .try_access_now(|_| read(&others, "/k1")) + .expect("readable") + .expect("initialized"); + assert_eq!(got, Some(Some(Val::new(1, "v1")))); + + let tasks: Vec<_> = (0..8) + .map(|_| { + let r = reader.clone(); + tokio::spawn(async move { + let mut hits = 0; + for _ in 0..1000 { + if read(&r, "/k1").is_some() { + hits += 1; + } + } + hits + }) + }) + .collect(); + for t in tasks { + assert_eq!(t.await.unwrap(), 1000); + } + drop(cache); +} + +#[tokio::test] +async fn test_request_resync_recovers_stalled_stream() { + let source = TestSource::new(); + source.set("/k1", Some("v1")).await; + let cache = Cache::::new(source.clone(), "", "reader-resync").await; + let reader = cache.reader(); + wait_for(&reader, "/k1", Some(Val::new(1, "v1"))).await; + + // The source moves on but the stream delivers nothing: the cache stays stale. + source.set_silently("/k1", Some("v2")).await; + source.set_silently("/k2", Some("x")).await; + sleep(Duration::from_millis(200)).await; + assert_eq!(read(&reader, "/k1"), Some(Some(Val::new(1, "v1")))); + assert_eq!(read(&reader, "/k2"), Some(None)); + + // Resync drops the stream and re-fetches the full range. + reader.request_resync(); + wait_for(&reader, "/k1", Some(Val::new(2, "v2"))).await; + wait_for(&reader, "/k2", Some(Val::new(3, "x"))).await; + + // Events flow again on the new stream. + source.set("/k1", None).await; + wait_for(&reader, "/k1", None).await; + drop(cache); +}