use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ostrya_rt as rt;
pub(crate) struct Stall {
window: Duration,
state: Mutex<State>,
}
struct State {
next_id: u64,
bodies: HashMap<u64, Entry>,
}
struct Entry {
at: Instant,
reading: bool,
}
impl Stall {
pub(crate) fn new(window: Duration) -> Arc<Stall> {
Arc::new(Stall {
window,
state: Mutex::new(State {
next_id: 0,
bodies: HashMap::new(),
}),
})
}
pub(crate) fn track(self: &Arc<Stall>) -> Tracker {
let mut state = self.state.lock().expect("stall mutex");
let id = state.next_id;
state.next_id += 1;
state.bodies.insert(
id,
Entry {
at: Instant::now(),
reading: false,
},
);
Tracker {
stall: self.clone(),
id,
}
}
pub(crate) async fn expired(&self) {
loop {
let wait = {
let state = self.state.lock().expect("stall mutex");
let oldest = state
.bodies
.values()
.filter(|entry| !entry.reading)
.map(|entry| entry.at)
.min();
match oldest {
Some(oldest) => match self.window.checked_sub(oldest.elapsed()) {
Some(left) if !left.is_zero() => left,
_ => return,
},
None => self.window,
}
};
rt::Timer::after(wait).await;
}
}
}
pub(crate) struct Tracker {
stall: Arc<Stall>,
id: u64,
}
impl Tracker {
pub(crate) fn progress(&self) {
let mut state = self.stall.state.lock().expect("stall mutex");
if let Some(entry) = state.bodies.get_mut(&self.id) {
entry.at = Instant::now();
entry.reading = false;
}
}
pub(crate) fn reading(&self) {
let mut state = self.stall.state.lock().expect("stall mutex");
if let Some(entry) = state.bodies.get_mut(&self.id) {
entry.reading = true;
}
}
}
impl Drop for Tracker {
fn drop(&mut self) {
self.stall
.state
.lock()
.expect("stall mutex")
.bodies
.remove(&self.id);
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures_lite::future;
use ostrya_rt::block_on;
#[test]
fn a_body_with_no_frame_for_the_window_expires() {
block_on(async {
let window = Duration::from_millis(200);
let stall = Stall::new(window);
let idle = future::or(
async {
stall.expired().await;
false
},
async {
rt::Timer::after(window * 2).await;
true
},
);
assert!(idle.await, "no live body, so no expiry");
let tracker = stall.track();
let started = Instant::now();
let fed = future::or(
async {
stall.expired().await;
false
},
async {
for _ in 0..6 {
rt::Timer::after(window / 4).await;
tracker.progress();
}
true
},
);
assert!(fed.await, "a body that gives frames does not expire");
tracker.reading();
let reading = future::or(
async {
stall.expired().await;
false
},
async {
rt::Timer::after(window * 2).await;
true
},
);
assert!(
reading.await,
"a body that waits for its reader does not expire"
);
tracker.progress();
stall.expired().await;
assert!(started.elapsed() >= window * 3 + window * 6 / 4);
drop(tracker);
assert!(stall.state.lock().unwrap().bodies.is_empty());
});
}
}