#[cfg(test)]
use std::collections::VecDeque;
#[cfg(test)]
use std::sync::mpsc::{self, Receiver, Sender};
#[cfg(test)]
use std::sync::{Arc, Mutex, PoisonError};
#[cfg(test)]
use std::thread::{JoinHandle, ThreadId};
#[cfg(test)]
use super::Environment;
#[cfg(test)]
use super::registry::{Hook, HookFn};
#[cfg(test)]
use unityrs_testkit::guard;
#[cfg(test)]
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Event {
Stopped,
Done,
}
#[cfg(test)]
struct Armed {
thread: ThreadId,
stops: VecDeque<(Hook, usize)>,
seen: usize,
events: Sender<Event>,
go: Arc<Mutex<Receiver<()>>>,
}
#[cfg(test)]
struct Leaving(Arc<Mutex<Vec<Armed>>>);
#[cfg(test)]
impl Drop for Leaving {
fn drop(&mut self) {
let me = std::thread::current().id();
lock(&self.0).retain(|a| a.thread != me);
}
}
#[cfg(test)]
#[derive(Clone, Default)]
pub(crate) struct Gate {
armed: Arc<Mutex<Vec<Armed>>>,
}
#[cfg(test)]
pub(crate) struct Run<T> {
events: Receiver<Event>,
go: Sender<()>,
join: Option<JoinHandle<T>>,
done: std::cell::Cell<bool>,
}
#[cfg(test)]
impl Gate {
pub(crate) fn install(env: &Environment) -> Self {
let gate = Self::default();
let g = gate.clone();
let f = HookFn(Arc::new(move |h| g.reach(h)));
*lock(&env.inner.registry.hook) = Some(f.clone());
*lock(&env.inner.cache.hook) = Some(f);
gate
}
pub(crate) fn run<T: Send + 'static>(
&self,
at: Option<(Hook, usize)>,
f: impl FnOnce() -> T + Send + 'static,
) -> Run<T> {
self.run_stops(at.into_iter().collect(), f)
}
pub(crate) fn run_stops<T: Send + 'static>(
&self,
stops: Vec<(Hook, usize)>,
f: impl FnOnce() -> T + Send + 'static,
) -> Run<T> {
let (events_tx, events) = mpsc::channel();
let (go, go_rx) = mpsc::channel();
let armed = self.armed.clone();
let (ready_tx, ready) = mpsc::channel::<()>();
let join = std::thread::spawn(move || {
if !stops.is_empty() {
lock(&armed).push(Armed {
thread: std::thread::current().id(),
stops: stops.into(),
seen: 0,
events: events_tx.clone(),
go: Arc::new(Mutex::new(go_rx)),
});
}
let _ = ready_tx.send(());
let leaving = Leaving(armed);
let out = f();
drop(leaving);
let _ = events_tx.send(Event::Done);
out
});
guard::wait(&ready, "the armed thread to start");
Run {
events,
go,
join: Some(join),
done: std::cell::Cell::new(false),
}
}
fn reach(&self, h: Hook) {
let me = std::thread::current().id();
let stop = {
let mut armed = lock(&self.armed);
let Some(i) = armed
.iter()
.position(|a| a.thread == me && a.stops.front().is_some_and(|(at, _)| *at == h))
else {
return;
};
let a = &mut armed[i];
a.seen += 1;
if a.stops.front().is_some_and(|(_, nth)| a.seen == *nth) {
a.stops.pop_front();
a.seen = 0;
let channels = (a.events.clone(), a.go.clone());
if a.stops.is_empty() {
armed.swap_remove(i);
}
Some(channels)
} else {
None
}
};
if let Some((events, go)) = stop {
let _ = events.send(Event::Stopped);
guard::hold(&lock(&go), "the test to let the stopped thread go");
}
}
}
#[cfg(test)]
impl<T> Run<T> {
pub(crate) fn next(&self) -> Event {
let e = guard::recv(&self.events, "the armed thread to stop or return");
if e == Event::Done {
self.done.set(true);
}
e
}
#[track_caller]
pub(crate) fn stopped(&self) {
assert_eq!(self.next(), Event::Stopped, "it returned before its point");
}
pub(crate) fn release(&self) {
let _ = self.go.send(());
}
pub(crate) fn finish(mut self) -> T {
while !self.done.get() {
self.release();
self.next();
}
match self.join.take().map(JoinHandle::join) {
Some(Ok(v)) => v,
Some(Err(e)) => std::panic::resume_unwind(e),
None => unreachable!("joined once"),
}
}
}
#[cfg(test)]
#[test]
fn an_armed_thread_that_panics_closes_its_channel() {
let gate = Gate::default();
let mut run = gate.run(Some((Hook::Published, 1)), || {
panic!("the armed thread's own failure")
});
let joined = run.join.take().map(JoinHandle::join);
assert!(matches!(joined, Some(Err(_))), "the thread did not panic");
assert!(
lock(&gate.armed).is_empty(),
"the gate still holds a sender of the thread's channel"
);
let waited = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run.next()));
let failure = waited.expect_err("a closed channel fails the wait");
assert!(
failure
.downcast_ref::<String>()
.is_some_and(|m| m.contains("panicked without answering")),
"the wait failed some other way"
);
}