use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use rt::WatchReceiver;
use crate::RaftTypeConfig;
use crate::async_runtime::Select3;
use crate::errors::ReplicationClosed;
use crate::network::Backoff;
use crate::replication::EXHAUSTED_BACKOFF_DELAY;
use crate::type_config::TypeConfigExt;
use crate::type_config::alias::WatchReceiverOf;
#[derive(Clone)]
pub(crate) struct BackoffConsumer<C>
where C: RaftTypeConfig
{
pub(crate) inner: Arc<Mutex<Option<Backoff>>>,
pub(crate) reset_rx: WatchReceiverOf<C, ()>,
pub(crate) cancel_rx: WatchReceiverOf<C, ()>,
}
impl<C> BackoffConsumer<C>
where C: RaftTypeConfig
{
pub(crate) fn next_delay(&self) -> Option<Duration> {
let mut guard = self.inner.lock().unwrap();
let backoff = guard.as_mut()?;
Some(backoff.next().unwrap_or(EXHAUSTED_BACKOFF_DELAY))
}
pub(crate) async fn backoff_if_enabled(&mut self) -> Result<bool, ReplicationClosed> {
let Some(sleep_duration) = self.next_delay() else {
return Ok(false);
};
let sleep = C::sleep(sleep_duration);
let cancel = self.cancel_rx.changed();
let reset = self.reset_rx.changed();
tracing::debug!("backoff timeout: {:?}", sleep_duration);
let selected = C::select3(cancel, reset, sleep).await;
match selected {
Select3::Third(_) => {
tracing::debug!("backoff timeout");
}
Select3::First(cancel_res) => {
tracing::info!(
"Replication Stream is canceled, res: {:?}, when:(backoff_if_enabled:wait-for-changed)",
cancel_res
);
return Err(ReplicationClosed::new("canceled during backoff"));
}
Select3::Second(reset_res) => {
tracing::info!(
"Backoff is reset, res: {:?}, when:(backoff_if_enabled:wait-for-changed)",
reset_res
);
self.inner.lock().unwrap().take();
}
}
Ok(true)
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use futures_util::FutureExt;
use rt::WatchSender;
use crate::engine::testing::UTConfig;
use crate::network::Backoff;
use crate::replication::backoff_state::BackoffState;
use crate::type_config::TypeConfigExt;
fn constant_200ms_backoff() -> Backoff {
Backoff::new(std::iter::repeat(Duration::from_millis(200)))
}
#[test]
fn samples_delay_only_when_enabled() {
let (_reset_tx, reset_rx) = UTConfig::<()>::watch_channel(());
let (_cancel_tx, cancel_rx) = UTConfig::<()>::watch_channel(());
let mut state = BackoffState::new();
let consumer = state.consumer::<UTConfig>(reset_rx, cancel_rx);
assert_eq!(consumer.next_delay(), None, "disabled: no delay");
state.on_error(100);
state.reconcile(constant_200ms_backoff);
assert_eq!(
consumer.next_delay(),
Some(Duration::from_millis(200)),
"enabled: yields configured delay"
);
state.on_success();
assert_eq!(consumer.next_delay(), None, "after success: no delay");
}
#[test]
fn reset_interrupts_active_backoff() {
UTConfig::<()>::run(async {
let (reset_tx, reset_rx) = UTConfig::<()>::watch_channel(());
let (_cancel_tx, cancel_rx) = UTConfig::<()>::watch_channel(());
let mut state = BackoffState::new();
let mut consumer = state.consumer::<UTConfig>(reset_rx, cancel_rx);
state.on_error(100);
state.reconcile(constant_200ms_backoff);
let wait = consumer.backoff_if_enabled();
let mut wait = Box::pin(wait);
let pending = wait.as_mut().now_or_never();
assert!(pending.is_none(), "backoff should wait before reset");
reset_tx.send(()).unwrap();
let result = UTConfig::<()>::timeout(Duration::from_millis(100), wait).await;
assert!(result.expect("reset should interrupt the 200ms wait").unwrap());
let next_delay = consumer.next_delay();
assert_eq!(next_delay, None);
});
}
}