use std::time::{Duration, Instant};
use ulo_transport::ErrorKind;
use crate::Broker;
use crate::cases::app::{ADD, Add, Fixture, HOLD, Sum, joined, within};
use crate::rt::{sleep, spawn};
const HELD_AFTER_DISRUPT: Duration = Duration::from_secs(3);
pub async fn after_disrupt<B: Broker>() {
let fixture = Fixture::<B>::start().await;
let budget = fixture.broker.budget();
let durable = fixture.capabilities().durable_replies();
let rpc = fixture.rpc().clone();
let held_for = budget.settle + HELD_AFTER_DISRUPT;
let held_ms = u64::try_from(held_for.as_millis()).unwrap_or(u64::MAX);
let held = spawn::<B, _, _>(async move { rpc.request::<_, u64>(HOLD, &held_ms).timeout(Duration::from_secs(60)).await });
sleep::<B>(budget.settle).await;
within::<B, _>(budget.recovery, "`Broker::disrupt`", fixture.broker.disrupt()).await;
let ended = joined(within::<B, _>(held_for + budget.recovery, "the call waiting on the severed connection", held).await, "the held call's task");
match (ended, durable) {
(Err(error), false) if error.kind() == ErrorKind::Unavailable => {}
(other, false) => panic!(
"a call waiting on a severed connection fails `Unavailable` on a link declared without `durable_replies` ({}), got: {other:?}",
fixture.capabilities().why_not_durable_replies().unwrap_or_default()
),
(Ok(answered), true) => {
assert_eq!(answered, held_ms, "the held call's answer");
let outage = fixture.broker.outage().expect(
"the link declares `durable_replies`, so `Broker::outage` reports when the client was out",
);
let reopened = outage.reopened.expect("the client reconnected to receive the answer, so the relay let a connection through");
let published = fixture.server.probe.held_answered().expect("the held call's handler answered");
assert!(
outage.shut <= published && published < reopened,
"the held call's answer is published while the client is out: published {:?} after the cut, the client \
reconnecting {:?} after it",
published.saturating_duration_since(outage.shut),
reopened.saturating_duration_since(outage.shut),
);
}
(other, true) => panic!(
"the link declares `durable_replies`, so a call waiting on a severed connection is answered once the client reconnects, got: {other:?}"
),
}
let deadline = Instant::now() + budget.recovery;
loop {
let outcome = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 4, b: 5 }).timeout(Duration::from_secs(1)).await;
match outcome {
Ok(sum) => {
assert_eq!(sum, Sum { sum: 9 });
break;
}
outcome if Instant::now() >= deadline => panic!("calls did not recover within the budget: {outcome:?}"),
_ => sleep::<B>(Duration::from_millis(200)).await,
}
}
fixture.stop().await;
}