use std::time::Duration;
use super::*;
use crate::client::Client;
use crate::testing::Handovers;
use shep_core::protocol::HelloAck;
use shep_core::protocol::PROTOCOL_VERSION;
pub(super) const BOUND: Duration = Duration::from_secs(5);
pub(super) const NEGATIVE_WINDOW: Duration = Duration::from_millis(400);
pub(super) async fn wait_until(bound: Duration, mut condition: impl FnMut() -> bool) -> bool {
tokio::time::timeout(bound, async {
while !condition() {
tokio::task::yield_now().await;
}
})
.await
.is_ok()
}
pub(super) fn ack_from(pid: u32) -> HelloAck {
HelloAck {
daemon_version: format!("0.0.{pid}"),
protocol: PROTOCOL_VERSION,
pid,
min_supported: None,
}
}
pub(super) async fn await_reconnect(
client: &ReconnectingClient,
shepherds: &Handovers,
accepts: u32,
) {
let seen = wait_until(BOUND, || {
shepherds.accepted() >= accepts && client.link() == LinkState::Connected
})
.await;
assert!(
seen,
"no reconnect within {BOUND:?}: {} accepts, link {:?}",
shepherds.accepted(),
client.link()
);
}
pub(super) async fn subscribe_then_lose_it(client: &ReconnectingClient, shepherds: &Handovers) {
let mut events = client
.subscribe(vec!["process.*".to_owned()])
.await
.expect("the first subscription must be answered");
shepherds.cut().await;
let ended = tokio::time::timeout(BOUND, async { while events.next().await.is_some() {} }).await;
assert!(ended.is_ok(), "the stream must end within {BOUND:?}");
}
pub(super) async fn await_refusal(client: &ReconnectingClient) -> LinkState {
let mut refusal = None;
let refused = wait_until(BOUND, || {
let link = client.link();
let is_refusal = matches!(link, LinkState::Refused { .. });
if is_refusal {
refusal = Some(link);
}
is_refusal
})
.await;
assert!(refused, "the link never reached a refusal within {BOUND:?}");
refusal.expect("a held condition recorded the refusal it saw")
}
pub(super) async fn reconnect_ok(client: &mut Client) -> Reconnected {
tokio::time::timeout(BOUND, client.reconnect())
.await
.expect("the reconnect must not hang")
.expect("the successor accepted this handshake")
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn wait_until_reports_a_condition_that_never_holds() {
let (held, ()) = tokio::join!(
wait_until(NEGATIVE_WINDOW, || false),
tokio::time::advance(NEGATIVE_WINDOW * 2)
);
assert!(!held, "a condition that never holds must report false");
}
}