use super::filter::{RootedFilter, WatchFilter};
use super::group::run_group;
use crate::bus::SharedEvent;
use crate::fake::{ProcScript, ScriptedRunner};
use crate::supervisor::SupervisorHandle;
use crate::supervisor::spawn_supervisor;
use crate::testing::test_paths;
use crate::watch::source::WatchBatch;
use core::time::Duration;
use shep_core::config::{AppConfig, normalize};
use shep_core::protocol::{BusEvent, ProcessEventKind, ProcessInfo};
use std::path::{Path, PathBuf};
use tokio::sync::broadcast;
use tokio::sync::mpsc;
pub(super) const EVENT_WAIT: Duration = Duration::from_secs(30);
const SETTLE_YIELDS: usize = 16;
pub(super) async fn settle() {
for _ in 0..SETTLE_YIELDS {
tokio::task::yield_now().await;
}
}
pub(super) fn spawn_test_fixture(
scripts: Vec<ProcScript>,
) -> (
SupervisorHandle,
broadcast::Receiver<SharedEvent>,
tempfile::TempDir,
) {
let dir = tempfile::tempdir().unwrap();
let (events, rx) = crate::bus::test_bus(64);
let runner = ScriptedRunner::new(scripts);
let handle = spawn_supervisor(runner, test_paths(&dir), events);
(handle, rx, dir)
}
pub(super) async fn start_app(
handle: &SupervisorHandle,
name: &str,
instances: u32,
) -> Vec<ProcessInfo> {
let mut app = AppConfig::minimal(name, "./srv");
app.instances = instances;
handle.start(vec![normalize(app).unwrap()]).await.unwrap()
}
pub(super) async fn expect_restart(
rx: &mut broadcast::Receiver<SharedEvent>,
name: &str,
deadline: Duration,
) -> ProcessInfo {
loop {
match tokio::time::timeout(deadline, rx.recv())
.await
.map(|received| received.map(|event| event.to_event()))
{
Ok(Ok(BusEvent::Process {
event: ProcessEventKind::Restart,
info,
..
})) if info.name == name => return info,
Ok(Ok(_)) => continue,
Ok(Err(broadcast::error::RecvError::Lagged(_))) => continue,
Ok(Err(err)) => panic!("event stream closed before a restart of {name}: {err}"),
Err(_) => panic!("timed out waiting for a watch-triggered restart of {name}"),
}
}
}
pub(super) async fn assert_no_restart_within(
rx: &mut broadcast::Receiver<SharedEvent>,
name: &str,
window: Duration,
) {
let deadline = tokio::time::Instant::now() + window;
loop {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
match tokio::time::timeout(remaining, rx.recv())
.await
.map(|received| received.map(|event| event.to_event()))
{
Err(_) => return, Ok(Ok(BusEvent::Process {
event: ProcessEventKind::Restart,
info,
..
})) if info.name == name => {
panic!(
"unexpected watch-triggered restart of {name} observed (restarts={})",
info.restarts
);
}
Ok(Ok(_)) => continue,
Ok(Err(broadcast::error::RecvError::Lagged(skipped))) => {
panic!(
"event stream lagged by {skipped} while checking for no restart of \
{name}: a skipped event may have been the restart this forbids"
)
}
Ok(Err(err)) => {
panic!("event channel closed while checking for no restart of {name}: {err}")
}
}
}
}
pub(super) fn matches_everything(root: PathBuf) -> RootedFilter {
RootedFilter {
root,
filter: WatchFilter::new(&[], &[]).unwrap(),
}
}
pub(super) fn spawn_group_matching_everything(
root: &Path,
name: &str,
handle: &SupervisorHandle,
) -> (
mpsc::UnboundedSender<WatchBatch>,
tokio::task::JoinHandle<()>,
) {
let (tx, group_rx) = mpsc::unbounded_channel();
let group = tokio::spawn(run_group(
name.to_string(),
matches_everything(root.to_path_buf()),
group_rx,
handle.clone(),
));
(tx, group)
}
pub(super) fn changed(paths: Vec<PathBuf>) -> WatchBatch {
WatchBatch {
paths,
rescan: false,
}
}
pub(super) fn rescan_marker() -> WatchBatch {
WatchBatch {
paths: Vec::new(),
rescan: true,
}
}
pub(super) const MAX_BATCHES: usize = 8;
pub(super) const SINGLE_FLIGHT_SCRIPTS: usize = MAX_BATCHES + 4;
#[derive(Debug, Clone, Copy)]
pub(super) struct Batch {
pub(super) triggers: bool,
pub(super) gap: Duration,
}
fn gap_strategy() -> impl proptest::strategy::Strategy<Value = Duration> {
use proptest::strategy::Strategy as _; proptest::prop_oneof![
4 => proptest::strategy::Just(Duration::ZERO),
3 => (1u64..2_000u64).prop_map(Duration::from_millis),
1 => (2_000u64..6_000u64).prop_map(Duration::from_millis),
]
}
pub(super) fn batch_strategy() -> impl proptest::strategy::Strategy<Value = Batch> {
use proptest::strategy::Strategy as _; (proptest::bool::ANY, gap_strategy()).prop_map(|(triggers, gap)| Batch { triggers, gap })
}
pub(super) fn expected_restart_instants(batches: &[Batch], restart: Duration) -> Vec<Duration> {
let mut arrivals = Vec::with_capacity(batches.len());
let mut at = Duration::ZERO;
for batch in batches {
at += batch.gap;
arrivals.push((at, batch.triggers));
}
let mut finished = Vec::new();
let mut idle_since = Duration::ZERO;
let mut i = 0;
while i < arrivals.len() {
let woke_at = arrivals[i].0.max(idle_since);
let mut triggers = arrivals[i].1;
i += 1;
while i < arrivals.len() && arrivals[i].0 <= woke_at {
triggers |= arrivals[i].1;
i += 1;
}
idle_since = if triggers {
let done = woke_at + restart;
finished.push(done);
done
} else {
woke_at
};
}
finished
}