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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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

Expand Down
7 changes: 4 additions & 3 deletions src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:
///
Expand All @@ -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<C: TypeConfig> {
/// The cached directory, used as given: the cache holds the keys under `{dir}/`.
Expand Down
26 changes: 15 additions & 11 deletions src/event_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -93,20 +94,17 @@ 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.
started.take();

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);
Expand All @@ -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) => {
Expand All @@ -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
Expand Down
3 changes: 3 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
#### `recovery.rs` - 连接恢复测试
验证连接失败后的自动恢复能力。模拟网络中断,验证自动重连和状态恢复。

#### `failed_initial_flush.rs` - 初始数据中断测试
验证初始数据(initial flush)中途断开时,读者读不到其中一部分:首次初始化时得到错误,重连时得到重连前的完整数据。

#### `unsupported_subscribe.rs` - 不支持订阅测试
验证数据源不支持订阅时的优雅降级。返回 `SubscribeError::Unsupported` 错误。

Expand Down
231 changes: 231 additions & 0 deletions tests/failed_initial_flush.rs
Original file line number Diff line number Diff line change
@@ -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<Event<Val>, 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<Mutex<VecDeque<BoxFuture<'static, EventStream<Val>>>>>,
}

impl ScriptedSource {
fn new(streams: Vec<BoxFuture<'static, EventStream<Val>>>) -> Self {
Self {
streams: Arc::new(Mutex::new(streams.into())),
}
}
}

#[async_trait::async_trait]
impl Source<Val> for ScriptedSource {
async fn subscribe(
&self,
_left: &str,
_right: &str,
) -> Result<EventStream<Val>, 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<F>(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<Item>) -> EventStream<Val> {
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<ScriptedConfig>) -> Result<Vec<(String, String)>, 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::<ScriptedConfig>::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::<ScriptedConfig>::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");
}
Loading