use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use crate::error::{MnemoError, Result};
#[derive(Clone, Debug, Default)]
pub struct CancelToken(Arc<(Mutex<bool>, Condvar)>);
impl CancelToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
let (flag, wake) = &*self.0;
*flag.lock().unwrap_or_else(|e| e.into_inner()) = true;
wake.notify_all();
}
pub fn is_cancelled(&self) -> bool {
*self.0 .0.lock().unwrap_or_else(|e| e.into_inner())
}
fn sleep(&self, d: Duration) -> bool {
let (flag, wake) = &*self.0;
let guard = flag.lock().unwrap_or_else(|e| e.into_inner());
if *guard {
return true;
}
let (guard, _) = wake
.wait_timeout_while(guard, d, |cancelled| !*cancelled)
.unwrap_or_else(|e| e.into_inner());
*guard
}
}
pub(crate) struct Call {
started: Instant,
deadline: Instant,
cancel: Option<CancelToken>,
sleep: Duration,
pub(crate) sidecar_reopened: bool,
}
const FIRST_SLEEP: Duration = Duration::from_millis(1);
const LONGEST_SLEEP: Duration = Duration::from_millis(50);
const YOUNG_FOR: Duration = Duration::from_millis(15);
const YOUNG_THEN: Duration = Duration::from_millis(2);
#[derive(Clone, Copy, PartialEq, Eq)]
enum Shape {
Doubling,
Young,
}
#[cfg(feature = "dev-hooks")]
fn backoff_shape() -> Shape {
static SHAPE: std::sync::OnceLock<Shape> = std::sync::OnceLock::new();
*SHAPE.get_or_init(|| match std::env::var("MNEMO_DEV_BACKOFF").as_deref() {
Ok("young") => Shape::Young,
_ => Shape::Doubling,
})
}
#[cfg(not(feature = "dev-hooks"))]
fn backoff_shape() -> Shape {
Shape::Doubling
}
const LONGEST_DEADLINE: Duration = Duration::from_secs(100 * 365 * 24 * 3600);
impl Call {
pub(crate) fn new(deadline: Duration, cancel: Option<&CancelToken>) -> Self {
let now = Instant::now();
let deadline = now
.checked_add(deadline.min(LONGEST_DEADLINE))
.or_else(|| now.checked_add(Duration::from_secs(24 * 3600)))
.unwrap_or(now);
Call {
started: now,
deadline,
cancel: cancel.cloned(),
sleep: FIRST_SLEEP,
sidecar_reopened: false,
}
}
pub(crate) fn check(&self) -> Result<()> {
match &self.cancel {
Some(c) if c.is_cancelled() => Err(MnemoError::Cancelled),
_ => Ok(()),
}
}
pub(crate) fn past_deadline(&self) -> bool {
Instant::now() >= self.deadline
}
pub(crate) fn back_off(&mut self) -> Result<bool> {
self.check()?;
let now = Instant::now();
if now >= self.deadline {
return Ok(false);
}
let young = backoff_shape() == Shape::Young && now - self.started < YOUNG_FOR;
let jittered = {
use rand::Rng;
let (lo, hi) = if young {
(1.0, 2.0)
} else {
let ms = self.sleep.as_secs_f64() * 1000.0;
(ms / 2.0, ms)
};
Duration::from_secs_f64(rand::thread_rng().gen_range(lo..=hi) / 1000.0)
};
let d = jittered.min(self.deadline - now);
let cancelled = match &self.cancel {
Some(c) => c.sleep(d),
None => {
std::thread::sleep(d);
false
}
};
if cancelled {
return Err(MnemoError::Cancelled);
}
if young {
self.sleep = YOUNG_THEN;
return Ok(Instant::now() < self.deadline);
}
self.sleep = (self.sleep * 2).min(LONGEST_SLEEP);
Ok(Instant::now() < self.deadline)
}
}