use std::collections::BTreeMap;
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
const CANCEL_POLL: Duration = Duration::from_millis(25);
#[derive(Debug)]
pub(super) struct Ready<T> {
pub page: u32,
pub item: T,
pub surface_bytes: u64,
}
#[derive(Debug)]
struct State<T> {
ready: BTreeMap<u32, (T, u64)>,
head: u64,
backlog: u64,
compilers: usize,
renderers: usize,
closed: bool,
}
#[derive(Debug)]
pub(super) struct Dispatch<T> {
state: Mutex<State<T>>,
changed: Condvar,
capacity: usize,
backlog_limit: u64,
}
impl<T> Dispatch<T> {
pub(super) fn new(
first_page: u64,
capacity: usize,
backlog_limit: u64,
compilers: usize,
renderers: usize,
) -> Self {
Self {
state: Mutex::new(State {
ready: BTreeMap::new(),
head: first_page,
backlog: 0,
compilers,
renderers,
closed: false,
}),
changed: Condvar::new(),
capacity: capacity.max(1),
backlog_limit,
}
}
fn lock(&self) -> MutexGuard<'_, State<T>> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn wait<'a>(&self, guard: MutexGuard<'a, State<T>>, poll: bool) -> MutexGuard<'a, State<T>> {
if poll {
self.changed
.wait_timeout(guard, CANCEL_POLL)
.map(|(guard, _)| guard)
.unwrap_or_else(|poisoned| poisoned.into_inner().0)
} else {
self.changed
.wait(guard)
.unwrap_or_else(PoisonError::into_inner)
}
}
pub(super) fn push(&self, page: u32, item: T, surface_bytes: u64) -> bool {
let mut state = self.lock();
loop {
if state.closed || state.renderers == 0 {
return false;
}
if state.ready.len() < self.capacity || u64::from(page) == state.head {
break;
}
state = self.wait(state, false);
}
state.ready.insert(page, (item, surface_bytes));
drop(state);
self.changed.notify_all();
true
}
pub(super) fn take(&self, cancelled: &dyn Fn() -> bool, poll: bool) -> Option<Ready<T>> {
let mut state = self.lock();
loop {
if state.closed {
return None;
}
if let Some((&page, &(_, surface_bytes))) = state.ready.first_key_value() {
let admissible = surface_bytes == 0
|| u64::from(page) == state.head
|| state.backlog == 0
|| state.backlog.saturating_add(surface_bytes) <= self.backlog_limit
|| cancelled();
if admissible {
let (item, surface_bytes) = state.ready.remove(&page)?;
drop(state);
self.changed.notify_all();
return Some(Ready {
page,
item,
surface_bytes,
});
}
} else if state.compilers == 0 {
return None;
}
state = self.wait(state, poll);
}
}
pub(super) fn finished(&self, surface_bytes: u64) {
let mut state = self.lock();
state.backlog = state.backlog.saturating_add(surface_bytes);
}
pub(super) fn emitted(&self, next_head: u64, surface_bytes: u64) {
let mut state = self.lock();
state.backlog = state.backlog.saturating_sub(surface_bytes);
state.head = state.head.max(next_head);
drop(state);
self.changed.notify_all();
}
#[cfg(test)]
pub(super) fn backlog(&self) -> u64 {
self.lock().backlog
}
fn worker_exited(&self, compiler: bool) {
let mut state = self.lock();
if compiler {
state.compilers = state.compilers.saturating_sub(1);
} else {
state.renderers = state.renderers.saturating_sub(1);
}
drop(state);
self.changed.notify_all();
}
fn close(&self) {
self.lock().closed = true;
self.changed.notify_all();
}
pub(super) fn compiler(&self) -> ExitGuard<'_, T> {
ExitGuard {
dispatch: self,
kind: GuardKind::Compiler,
}
}
pub(super) fn renderer(&self) -> ExitGuard<'_, T> {
ExitGuard {
dispatch: self,
kind: GuardKind::Renderer,
}
}
pub(super) fn collector(&self) -> ExitGuard<'_, T> {
ExitGuard {
dispatch: self,
kind: GuardKind::Collector,
}
}
}
#[derive(Debug, Clone, Copy)]
enum GuardKind {
Compiler,
Renderer,
Collector,
}
#[derive(Debug)]
pub(super) struct ExitGuard<'a, T> {
dispatch: &'a Dispatch<T>,
kind: GuardKind,
}
impl<T> Drop for ExitGuard<'_, T> {
fn drop(&mut self) {
match self.kind {
GuardKind::Compiler => self.dispatch.worker_exited(true),
GuardKind::Renderer => self.dispatch.worker_exited(false),
GuardKind::Collector => self.dispatch.close(),
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
const NEVER: &dyn Fn() -> bool = &|| false;
#[test]
fn head_is_taken_even_when_the_backlog_is_over_the_limit() {
let d = Dispatch::<&str>::new(0, 4, 10, 1, 1);
d.finished(100); assert!(d.push(2, "two", 8));
assert!(d.push(0, "zero", 8));
assert_eq!(d.take(NEVER, false).unwrap().page, 0);
}
#[test]
fn out_of_order_pages_wait_for_backlog_room() {
let d = std::sync::Arc::new(Dispatch::<u32>::new(0, 4, 10, 1, 1));
d.finished(8);
assert!(d.push(3, 3, 8)); let taker = {
let d = d.clone();
std::thread::spawn(move || d.take(NEVER, false).map(|r| r.page))
};
std::thread::sleep(Duration::from_millis(30));
assert!(
!taker.is_finished(),
"page 3 must wait while the backlog is full"
);
d.emitted(1, 8);
assert_eq!(taker.join().unwrap(), Some(3));
assert_eq!(d.backlog(), 0);
}
#[test]
fn an_empty_backlog_admits_a_page_larger_than_the_limit() {
let d = Dispatch::<()>::new(0, 4, 10, 1, 1);
assert!(d.push(5, (), 1_000));
assert_eq!(d.take(NEVER, false).unwrap().page, 5);
}
#[test]
fn pages_without_a_surface_and_cancelled_pipelines_are_never_held() {
let d = Dispatch::<()>::new(0, 4, 10, 1, 1);
d.finished(100);
assert!(d.push(7, (), 0));
assert_eq!(d.take(NEVER, false).unwrap().page, 7);
assert!(d.push(8, (), 50));
assert_eq!(d.take(&|| true, true).unwrap().page, 8);
}
#[test]
fn the_head_is_accepted_into_a_full_ready_set() {
let d = Dispatch::<()>::new(0, 1, u64::MAX, 1, 1);
assert!(d.push(1, (), 1));
assert!(d.push(0, (), 1));
}
#[test]
fn workers_stop_when_their_counterparts_are_gone() {
let d = Dispatch::<()>::new(0, 1, u64::MAX, 1, 1);
drop(d.compiler());
assert!(
d.take(NEVER, false).is_none(),
"no compiler and nothing ready"
);
drop(d.renderer());
assert!(!d.push(3, (), 1), "nobody left to render it");
}
#[test]
fn a_stopped_collector_releases_waiters() {
let d = std::sync::Arc::new(Dispatch::<()>::new(0, 4, 0, 1, 1));
d.finished(1);
assert!(d.push(2, (), 1));
let taker = {
let d = d.clone();
std::thread::spawn(move || d.take(NEVER, false).is_none())
};
std::thread::sleep(Duration::from_millis(20));
drop(d.collector());
assert!(taker.join().unwrap());
}
}