use std::time::{Duration, Instant};
use ulo_transport::ErrorKind;
use futures_util::FutureExt;
use crate::Broker;
use crate::cases::app::{ADD, Add, Fixture, NEVER, Sum, eventually, failed, joined, within};
use crate::rt::{sleep, spawn};
const CALL_TIMEOUT: Duration = Duration::from_secs(60);
const PATIENCE: Duration = Duration::from_secs(5);
const CLOSE_BOUND: Duration = Duration::from_secs(30);
pub async fn client_close<B: Broker>() {
let Fixture { broker, server, client } = Fixture::<B>::start().await;
let budget = broker.budget();
let rpc = client.rpc.clone();
let caller = rpc.clone();
let mut waiting = spawn::<B, _, _>(async move { caller.request::<_, ()>(NEVER, &()).timeout(CALL_TIMEOUT).await });
let probe = server.probe.clone();
assert!(
eventually::<B>(budget.settle + PATIENCE, || probe.unanswered() > 0).await,
"the call did not reach its handler within {:?}",
budget.settle + PATIENCE,
);
let held = broker.client_connections().await;
if let Some(open) = held {
assert!(open > 0, "the environment counts no connection of the client's while its call waits");
}
if let Some(ended) = (&mut waiting).now_or_never() {
panic!("the call ended before its client closed: {ended:?}");
}
let closed = within::<B, _>(CLOSE_BOUND, "the client app's close", client.closed()).await;
if let Err(error) = closed {
panic!("the client app's close reported a failure: {error}");
}
let ended = joined(within::<B, _>(PATIENCE, "the call waiting when its client closed", waiting).await, "the waiting call's task");
failed(ended, ErrorKind::Unavailable);
if held.is_some() {
let deadline = Instant::now() + PATIENCE;
loop {
match broker.client_connections().await {
Some(0) => break,
open if Instant::now() >= deadline => {
panic!("the client's connections were still open {PATIENCE:?} after its app closed: {open:?}")
}
_ => sleep::<B>(Duration::from_millis(50)).await,
}
}
sleep::<B>(budget.settle).await;
let reopened = broker.client_connections().await;
assert_eq!(reopened, Some(0), "the closed client opened a connection with no call made");
}
let deadline = Instant::now() + budget.boot;
loop {
let outcome = rpc.request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).timeout(Duration::from_millis(500)).await;
match outcome {
Ok(sum) => {
assert_eq!(sum, Sum { sum: 5 });
break;
}
outcome if Instant::now() >= deadline => {
panic!("a call after the client's close was not answered within the boot budget: {outcome:?}")
}
_ => sleep::<B>(Duration::from_millis(100)).await,
}
}
if held.is_some() {
let open = broker.client_connections().await;
assert!(open.is_some_and(|open| open > 0), "the call after the close was answered with no connection open: {open:?}");
}
server.stop().await;
}