use std::time::Duration;
use crate::CancelToken;
pub const DEFAULT_STATEMENT_TIMEOUT_SECS: u64 = 30;
pub fn format_limit(limit_ms: u64) -> String {
if limit_ms.is_multiple_of(1000) {
format!("{}s", limit_ms / 1000)
} else {
format!("{limit_ms}ms")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limit {
pub budget: Duration,
pub requested: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TimeoutPolicy {
pub default: Option<Duration>,
pub ceiling: Option<Duration>,
}
impl TimeoutPolicy {
pub fn from_secs(default_secs: u64, ceiling_secs: u64) -> Self {
let secs = |n: u64| (n != 0).then(|| Duration::from_secs(n));
Self {
default: secs(default_secs),
ceiling: secs(ceiling_secs),
}
}
pub const SERVED: Self = Self {
default: Some(Duration::from_secs(DEFAULT_STATEMENT_TIMEOUT_SECS)),
ceiling: None,
};
pub fn resolve(&self, request: Option<Duration>) -> Option<Limit> {
let (wanted, requested) = match request {
Some(d) if d.is_zero() => (None, true),
Some(d) => (Some(d), true),
None => (self.default, false),
};
match (wanted, self.ceiling) {
(Some(w), Some(c)) if c < w => Some(Limit {
budget: c,
requested: false,
}),
(Some(w), _) => Some(Limit {
budget: w,
requested,
}),
(None, Some(c)) => Some(Limit {
budget: c,
requested: false,
}),
(None, None) => None,
}
}
}
#[must_use = "dropping the guard disarms the deadline; hold it for the statement"]
#[derive(Debug)]
pub struct Armed {
#[cfg(not(target_arch = "wasm32"))]
key: Option<imp::Key>,
}
impl Drop for Armed {
fn drop(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(key) = self.key.take() {
imp::disarm(key);
}
}
}
pub fn arm(token: &CancelToken, limit: Option<Duration>) -> Armed {
#[cfg(not(target_arch = "wasm32"))]
{
Armed {
key: limit.and_then(|d| imp::arm(token.clone(), d)),
}
}
#[cfg(target_arch = "wasm32")]
{
let _ = (token, limit);
Armed {}
}
}
#[cfg(not(target_arch = "wasm32"))]
mod imp {
use std::collections::BTreeMap;
use std::sync::{Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
use crate::CancelToken;
pub(super) type Key = (Instant, u64);
#[derive(Default)]
struct State {
next_id: u64,
entries: BTreeMap<Key, CancelToken>,
}
struct Timer {
state: Mutex<State>,
wake: Condvar,
}
fn timer() -> &'static Timer {
static TIMER: OnceLock<&'static Timer> = OnceLock::new();
TIMER.get_or_init(|| {
let timer: &'static Timer = Box::leak(Box::new(Timer {
state: Mutex::new(State::default()),
wake: Condvar::new(),
}));
std::thread::Builder::new()
.name("relate-deadline".into())
.spawn(move || run(timer))
.expect("the statement deadline timer thread must start");
timer
})
}
fn lock(timer: &Timer) -> std::sync::MutexGuard<'_, State> {
timer
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(super) fn arm(token: CancelToken, limit: Duration) -> Option<Key> {
let timer = timer();
let due = Instant::now().checked_add(limit)?;
let mut state = lock(timer);
state.next_id += 1;
let key = (due, state.next_id);
let earliest = state.entries.keys().next().is_none_or(|first| key < *first);
state.entries.insert(key, token);
drop(state);
if earliest {
timer.wake.notify_one();
}
Some(key)
}
pub(super) fn disarm(key: Key) {
lock(timer()).entries.remove(&key);
}
fn run(timer: &'static Timer) {
let mut state = lock(timer);
loop {
let now = Instant::now();
match state.entries.keys().next().copied() {
None => {
state = timer
.wake
.wait(state)
.unwrap_or_else(std::sync::PoisonError::into_inner);
}
Some(key) if key.0 <= now => {
if let Some(token) = state.entries.remove(&key) {
token.cancel_timed_out();
}
}
Some(key) => {
state = timer
.wake
.wait_timeout(state, key.0 - now)
.unwrap_or_else(std::sync::PoisonError::into_inner)
.0;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const SECS: fn(u64) -> Duration = Duration::from_secs;
#[test]
fn a_request_overrides_the_default_in_both_directions() {
let policy = TimeoutPolicy {
default: Some(SECS(30)),
ceiling: None,
};
let shorter = policy.resolve(Some(SECS(5))).unwrap();
assert_eq!((shorter.budget, shorter.requested), (SECS(5), true));
let longer = policy.resolve(Some(SECS(600))).unwrap();
assert_eq!((longer.budget, longer.requested), (SECS(600), true));
let none = policy.resolve(None).unwrap();
assert_eq!((none.budget, none.requested), (SECS(30), false));
assert_eq!(policy.resolve(Some(SECS(0))), None, "0 asks for no bound");
}
#[test]
fn the_ceiling_bounds_every_value_including_no_bound() {
let policy = TimeoutPolicy {
default: Some(SECS(30)),
ceiling: Some(SECS(60)),
};
assert_eq!(policy.resolve(Some(SECS(600))).unwrap().budget, SECS(60));
assert_eq!(policy.resolve(Some(SECS(0))).unwrap().budget, SECS(60));
assert_eq!(policy.resolve(Some(SECS(10))).unwrap().budget, SECS(10));
let off = TimeoutPolicy::default();
assert_eq!(off.resolve(None), None);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn an_armed_deadline_cancels_with_the_timeout_cause() {
let token = CancelToken::new();
let _armed = arm(&token, Some(Duration::from_millis(20)));
let start = std::time::Instant::now();
while !token.is_cancelled() {
assert!(start.elapsed() < SECS(10), "the deadline never fired");
std::thread::sleep(Duration::from_millis(5));
}
assert!(token.timed_out());
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_disarmed_deadline_never_cancels() {
let token = CancelToken::new();
drop(arm(&token, Some(Duration::from_millis(30))));
std::thread::sleep(Duration::from_millis(120));
assert!(!token.is_cancelled());
}
#[test]
fn limits_format_as_seconds_when_exact() {
assert_eq!(format_limit(30_000), "30s");
assert_eq!(format_limit(1_500), "1500ms");
}
}