diff --git a/README.md b/README.md index 9e95a4a..2d7c24d 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ if let Some(value) = cache.try_get_now("key") { ## Concurrency Control -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. +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 re-fetch while it initializes or reconnects. Every read takes `&self`, so a cache is shared by reference or `Arc` without an outer lock: @@ -87,6 +87,7 @@ The cache implements robust error handling: - Connection failures are automatically retried in the background - Background watcher task automatically recovers from errors +- The cached data is replaced only by a complete initial flush: a flush that fails part way is never served - Users are shielded from transient errors through the abstraction - The cache ensures data consistency by tracking sequence numbers diff --git a/src/cache.rs b/src/cache.rs index 772a192..d3be094 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -42,8 +42,8 @@ use crate::TypeConfig; /// ## Concurrency Control /// /// 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. +/// exclusively, briefly to apply each change, and for the whole re-fetch while it initializes +/// or reconnects. /// /// Every read takes `&self`, so a cache is shared by reference or `Arc` without an outer lock: /// @@ -55,9 +55,10 @@ use crate::TypeConfig; /// ## Error Handling /// /// - Background watcher task automatically recovers from errors by: -/// - Resetting the cache state /// - Re-establishing the watch stream /// - Re-fetching all data to ensure consistency +/// - Replacing the cache data only with a complete initial flush: a flush that fails part +/// way is never served /// - Users are shielded from transient errors through the abstraction pub struct Cache { /// The cached directory, used as given: the cache holds the keys under `{dir}/`. diff --git a/src/event_watcher.rs b/src/event_watcher.rs index b1db9c9..cf5070f 100644 --- a/src/event_watcher.rs +++ b/src/event_watcher.rs @@ -70,7 +70,8 @@ where C: TypeConfig /// # Error Handling /// /// - Connection failures are automatically retried with exponential backoff - /// - On error, the cache is reset and re-fetched to ensure consistency + /// - On error, all data is re-fetched; the cache data is replaced only by a complete initial + /// flush, so a flush that fails part way is never served /// - The watcher continues running until explicitly canceled pub(crate) async fn main( mut self, @@ -93,10 +94,10 @@ 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. + // Hold the lock for the whole attempt, so that readers wait for its data. let mut cache_data = self.data.write().await; - // The data lock is acquired and will be kept until the cache is fully initialized. + // The data lock is acquired and will be kept until this attempt ends. // At this point, we notify the caller that initialization has started by consuming // the `started` sender. This signals to the receiving end that it's now safe to // acquire the data lock, as we're about to populate the cache with initial data. @@ -104,9 +105,6 @@ where C: TypeConfig let strm_res = self.retry_new_stream().await; - // Everytime when establishing a cache, the old data must be cleared and receive a new one. - *cache_data = Ok(Default::default()); - let mut strm = match strm_res { Ok(strm) => { info!("{}: cache watch stream established", self.name); @@ -130,14 +128,20 @@ where C: TypeConfig }; let init_res = { - // Safe unwrap: before entering this method, the cache data is ensured to be Ok. - let d = cache_data.as_mut().unwrap(); - self.initialize_cache(d, &mut strm).await + // Fetch the initial flush aside, and replace the cache data only with a + // complete one. A flush that fails part way is dropped: the lock is released + // before the retry, and the readers then get the data from before this + // attempt, a complete copy or an error, never a part of the flush. + let mut fresh = CacheData::default(); + self.initialize_cache(&mut fresh, &mut strm) + .await + .map(|_| fresh) }; match init_res { - Ok(_) => { + Ok(fresh) => { info!("{}: cache initialized successfully", self.name); + *cache_data = Ok(fresh); strm } Err(conn_err) => { @@ -160,7 +164,7 @@ where C: TypeConfig } Err(e) => { error!( - "{} watcher loop exited with error: {}; reset cache and re-fetch all data to re-establish", + "{} watcher loop exited with error: {}; re-fetch all data to re-establish", self.name, e ); // continue diff --git a/tests/README.md b/tests/README.md index b11a2f5..d774fd8 100644 --- a/tests/README.md +++ b/tests/README.md @@ -31,6 +31,9 @@ #### `recovery.rs` - 连接恢复测试 验证连接失败后的自动恢复能力。模拟网络中断,验证自动重连和状态恢复。 +#### `failed_initial_flush.rs` - 初始数据中断测试 +验证初始数据(initial flush)中途断开时,读者读不到其中一部分:首次初始化时得到错误,重连时得到重连前的完整数据。 + #### `unsupported_subscribe.rs` - 不支持订阅测试 验证数据源不支持订阅时的优雅降级。返回 `SubscribeError::Unsupported` 错误。 diff --git a/tests/failed_initial_flush.rs b/tests/failed_initial_flush.rs new file mode 100644 index 0000000..ccbff68 --- /dev/null +++ b/tests/failed_initial_flush.rs @@ -0,0 +1,231 @@ +// 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. + +//! A failed initial flush is never served as a ready cache. +//! +//! A reader that queues while the watcher fetches an initial flush runs when the flush fails part +//! way, before the retry. It gets the data from before the flush, a complete copy or an error, +//! never the part of the flush that arrived. + +use std::collections::VecDeque; +use std::pin::pin; +use std::sync::Arc; +use std::sync::Mutex; + +use futures::future::BoxFuture; +use futures::poll; +use futures::stream; +use futures::FutureExt; +use futures::StreamExt; +use sub_cache::errors::ConnectionClosed; +use sub_cache::errors::SubscribeError; +use sub_cache::errors::Unsupported; +use sub_cache::event_stream::Change; +use sub_cache::event_stream::Event; +use sub_cache::event_stream::EventStream; +use sub_cache::testing::source::Val; +use sub_cache::Cache; +use sub_cache::Source; +use sub_cache::TypeConfig; +use tokio::sync::oneshot; + +type Item = Result, ConnectionClosed>; + +/// A source that serves the n-th subscription with the stream of the n-th future in `streams`; +/// a subscription beyond them never returns. +#[derive(Clone)] +struct ScriptedSource { + streams: Arc>>>>, +} + +impl ScriptedSource { + fn new(streams: Vec>>) -> Self { + Self { + streams: Arc::new(Mutex::new(streams.into())), + } + } +} + +#[async_trait::async_trait] +impl Source for ScriptedSource { + async fn subscribe( + &self, + _left: &str, + _right: &str, + ) -> Result, SubscribeError> { + let next = self.streams.lock().unwrap().pop_front(); + match next { + Some(stream) => Ok(stream.await), + None => std::future::pending().await, + } + } +} + +#[derive(Debug, Default)] +struct ScriptedConfig; + +impl TypeConfig for ScriptedConfig { + type Value = Val; + type Source = ScriptedSource; + + 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); + } +} + +/// An event of an initial flush: `key` is `data` at `seq`. +fn init(key: &str, seq: u64, data: &str) -> Item { + Ok(Event::Initialization(Change::new( + key, + None, + Some(Val::new(seq, data)), + ))) +} + +fn complete() -> Item { + Ok(Event::InitializationComplete) +} + +fn broken() -> Item { + Err(ConnectionClosed::new_str( + "connection reset during the initial flush", + )) +} + +/// A connection that sends `items`, then stays open. +fn connection(items: Vec) -> EventStream { + stream::iter(items).chain(stream::pending()).boxed() +} + +fn kv(pairs: &[(&str, &str)]) -> Vec<(String, String)> { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() +} + +/// All entries of `cache` as `(key, data)`; waits while the watcher holds the data. +async fn entries(cache: &Cache) -> Result, Unsupported> { + cache + .try_access(|cache_data| { + let data = &cache_data.data; + data.iter() + .map(|(k, v)| (k.clone(), v.data.clone())) + .collect() + }) + .await +} + +/// The first initial flush breaks part way: a reader queued on it gets an error, and a later +/// reader gets the complete flush of the retry. +#[tokio::test] +async fn test_failed_first_initial_flush_is_not_served() { + let (gate_tx, gate_rx) = oneshot::channel::<()>(); + + let source = ScriptedSource::new(vec![ + async move { + gate_rx.await.ok(); + connection(vec![init("dir/k1", 1, "a"), broken()]) + } + .boxed(), + async move { + connection(vec![ + init("dir/k1", 1, "a"), + init("dir/k2", 2, "b"), + complete(), + ]) + } + .boxed(), + ]); + + // `new()` returns when the watcher holds the data to fetch the first flush, which waits for + // `gate`. + let cache = Cache::::new(source, "dir", "first-flush").await; + + let mut read = pin!(entries(&cache)); + assert!( + poll!(read.as_mut()).is_pending(), + "the read must queue on the data" + ); + + // The flush breaks after `k1`; the queued read runs before the retry. + gate_tx.send(()).unwrap(); + let got = read.await; + assert!( + got.is_err(), + "a reader got a part of the initial flush: {got:?}" + ); + + let got = entries(&cache).await.unwrap(); + assert_eq!(got, kv(&[("dir/k1", "a"), ("dir/k2", "b")])); +} + +/// The initial flush of a reconnect breaks part way: a reader queued on it gets the copy from +/// before the reconnect, which is complete. +#[tokio::test] +async fn test_failed_reconnect_initial_flush_is_not_served() { + let (break_tx, break_rx) = oneshot::channel::<()>(); + let (subscribed_tx, subscribed_rx) = oneshot::channel::<()>(); + let (gate_tx, gate_rx) = oneshot::channel::<()>(); + + let source = ScriptedSource::new(vec![ + async move { + let flush = stream::iter(vec![ + init("dir/k1", 1, "a"), + init("dir/k2", 2, "b"), + complete(), + ]); + let breaks = stream::once(async move { + break_rx.await.ok(); + broken() + }); + flush.chain(breaks).boxed() + } + .boxed(), + async move { + // The watcher holds the data while it subscribes. + subscribed_tx.send(()).ok(); + gate_rx.await.ok(); + connection(vec![init("dir/k1", 3, "a2"), broken()]) + } + .boxed(), + ]); + + let cache = Cache::::new(source, "dir", "reconnect-flush").await; + let before = kv(&[("dir/k1", "a"), ("dir/k2", "b")]); + assert_eq!(entries(&cache).await.unwrap(), before); + + // The connection breaks, and the watcher subscribes again. + break_tx.send(()).unwrap(); + subscribed_rx.await.unwrap(); + + let mut read = pin!(entries(&cache)); + assert!( + poll!(read.as_mut()).is_pending(), + "the read must queue on the data" + ); + + // The flush of the reconnect breaks after `k1`; the queued read runs before the retry. + gate_tx.send(()).unwrap(); + let got = read.await.unwrap(); + assert_eq!(got, before, "a reader got a part of the initial flush"); +}