use std::error::Error as _;
use std::future::{Future, IntoFuture};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use std::time::{Duration, Instant};
use futures_util::StreamExt;
use ulo::{AppHandle, Bound, BoundAddr, BoxError, CancelReason, ExecOptions, ExecutionRef, Runtime, Timer};
use ulo_rpc::{CallHeaders, Capabilities, Frame, Link, Outbound, Subscription, RpcClient, RpcError, RpcStream, ZeroTimeout};
use ulo_rpc::link::Inbound;
use ulo_transport::{Count, ErrorKind};
use crate::{Broker, Budget};
use crate::cases::app::{
ADD, Add, COUNT, DEADLINE, DEADLINE_STREAM, DEADLINE_SUM, EVENT, Fixture, Mounts, PAUSE, STALL, SUM, Sum, TICKS, addresses,
client_over, client_timed, eventually, failed, refused_at_startup, streams, within,
};
pub async fn deadline_ms<B: Broker>() {
let fixture = Fixture::<B>::start().await;
let link = Stamped { link: fixture.broker.client_link(&addresses(&[&fixture.server])), value: "300" };
let client = client_over::<B, _>(link).await;
let started = Instant::now();
let outcome = client.rpc.request::<_, ()>(STALL, &()).timeout(Duration::from_secs(10)).await;
failed(outcome, ErrorKind::Timeout);
assert!(started.elapsed() < Duration::from_secs(5), "the call was answered after {:?}, at the client's timeout rather than the server's", started.elapsed());
let probe = fixture.server.probe.clone();
let settle = fixture.broker.budget().settle;
assert!(eventually::<B>(settle, || probe.stalled().is_some()).await, "the stalled handler was not ended");
assert_eq!(probe.stalled(), Some(Some(CancelReason::Deadline)));
client.close().await;
fixture.stop().await;
}
pub async fn client_timeout<B: Broker>() {
let fixture = Fixture::<B>::start().await;
let started = Instant::now();
let outcome = fixture.rpc().request::<_, ()>(STALL, &()).timeout(Duration::from_millis(300)).await;
failed(outcome, ErrorKind::Timeout);
assert!(started.elapsed() < Duration::from_secs(3), "the client's timeout took {:?}", started.elapsed());
fixture.stop().await;
}
pub async fn timeout_is_the_server_s_deadline<B: Broker>() {
let fixture = Fixture::<B>::start().await;
let link = MutedCancel(fixture.broker.client_link(&addresses(&[&fixture.server])));
let client = client_over::<B, _>(link).await;
let started = Instant::now();
let outcome = client.rpc.request::<_, ()>(STALL, &()).timeout(Duration::from_millis(300)).await;
failed(outcome, ErrorKind::Timeout);
let probe = fixture.server.probe.clone();
let settle = fixture.broker.budget().settle;
assert!(
eventually::<B>(Duration::from_millis(300) + settle, || probe.stalled().is_some()).await,
"the stalled handler was still running {:?} after a call with a 300 ms timeout began",
started.elapsed()
);
assert_eq!(probe.stalled(), Some(Some(CancelReason::Deadline)), "what ended the stalled handler");
client.close().await;
fixture.stop().await;
}
fn idle_of(budget: Budget) -> Duration {
budget.settle
}
fn silence_of(budget: Budget) -> Duration {
idle_of(budget) * 4
}
pub async fn stream_idle_timeout_is_per_frame<B: Broker>() {
let fixture = Fixture::<B>::start().await;
if !streams(&fixture.capabilities()) {
refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
return fixture.stop().await;
}
let idle = idle_of(fixture.broker.budget());
let mut ticks = fixture.rpc().stream::<_, u64>(TICKS, &()).idle_timeout(Bound::After(idle)).await.expect("the stream opens");
let opened = Instant::now();
while opened.elapsed() < idle * 3 {
let tick = within::<B, _>(Duration::from_secs(10), "a tick", ticks.next()).await.expect("the stream yields");
if let Err(error) = tick {
panic!("the stream failed {:?} after it opened, its idle timeout {idle:?}: {error:?}", opened.elapsed());
}
}
drop(ticks);
fixture.stop().await;
}
pub async fn idle_timeout_ends_a_silent_stream<B: Broker>() {
let fixture = Fixture::<B>::start().await;
if !streams(&fixture.capabilities()) {
refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
return fixture.stop().await;
}
let idle = idle_of(fixture.broker.budget());
let silence_for = silence_of(fixture.broker.budget());
let silence = silence_for.as_millis() as u64;
let mut replies = fixture.rpc().stream::<_, u64>(PAUSE, &silence).idle_timeout(Bound::After(idle)).await.expect("the stream opens");
let first = within::<B, _>(Duration::from_secs(10), "the first item", replies.next()).await.expect("the stream yields");
assert_eq!(first.expect("the first item arrives"), 0);
let silent = Instant::now();
let ended = within::<B, _>(Duration::from_secs(10), "the idle timeout", replies.next()).await.expect("the stream yields its end");
let waited = silent.elapsed();
failed(ended, ErrorKind::Timeout);
assert!(waited >= idle - Duration::from_millis(50), "the stream ended {waited:?} into the silence, before its idle timeout");
assert!(waited < silence_for, "the stream ended {waited:?} into the silence, not at its {idle:?} idle timeout");
assert!(replies.next().await.is_none(), "the stream yielded after its idle timeout");
fixture.stop().await;
}
pub async fn stream_deadline_is_the_server_s<B: Broker>() {
let fixture = Fixture::<B>::start().await;
if !streams(&fixture.capabilities()) {
refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
return fixture.stop().await;
}
let settle = fixture.broker.budget().settle;
let deadline = settle + settle / 5;
let link = MutedCancel(fixture.broker.client_link(&addresses(&[&fixture.server])));
let client = client_over::<B, _>(link).await;
let started = Instant::now();
let mut ticks = client.rpc.stream::<_, u64>(TICKS, &()).deadline(deadline).await.expect("the stream opens");
let mut arrived = 0;
let ended = loop {
match within::<B, _>(Duration::from_secs(10), "the stream's deadline", ticks.next()).await {
Some(Ok(_)) => arrived += 1,
Some(Err(error)) => break error,
None => panic!("the stream ended cleanly {:?} after it opened, its deadline {deadline:?}", started.elapsed()),
}
};
assert_eq!(ended.kind(), ErrorKind::Timeout, "what ended the stream: {ended:?}");
assert!(arrived > 0, "no tick arrived before the stream's deadline");
drop(ticks);
let probe = fixture.server.probe.clone();
assert!(
eventually::<B>(deadline + settle, || probe.stopped()).await,
"the ticking stream was still running {:?} after a stream with a {deadline:?} deadline opened",
started.elapsed()
);
assert_eq!(probe.cancelled(), Some(Some(CancelReason::Deadline)), "what ended the ticking stream");
client.close().await;
fixture.stop().await;
}
pub async fn stream_with_neither_bound_runs_on<B: Broker>() {
let fixture = Fixture::<B>::start().await;
if !streams(&fixture.capabilities()) {
refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
return fixture.stop().await;
}
let budget = fixture.broker.budget();
let client = fixture.rpc().clone().timeout(Bound::After(idle_of(budget) / 2)).expect("a nonzero timeout");
let started = Instant::now();
let silence_for = silence_of(budget);
let silence = silence_for.as_millis() as u64;
let replies = client.stream::<_, u64>(PAUSE, &silence).await.expect("the stream opens");
let items: Vec<_> = within::<B, _>(silence_for + Duration::from_secs(10), "the paused stream", replies.collect()).await;
let items: Vec<u64> = items
.into_iter()
.map(|item| item.unwrap_or_else(|error| panic!("the stream failed {:?} after it opened: {error:?}", started.elapsed())))
.collect();
assert_eq!(items, vec![0, 1], "the paused stream's items");
assert!(started.elapsed() >= silence_for, "the stream ended {:?} after it opened, before its silence", started.elapsed());
fixture.stop().await;
}
fn idle_client<B: Broker>(fixture: &Fixture<B>, idle: Duration) -> RpcClient {
fixture.rpc().clone().idle_timeout(Bound::After(idle)).expect("a nonzero idle timeout")
}
async fn paused<B: Broker>(client: &RpcClient, silence: Duration, idle: Bound) -> RpcStream<u64> {
let millis = silence.as_millis() as u64;
let opened = client.stream::<_, u64>(PAUSE, &millis).idle_timeout(idle);
within::<B, _>(Duration::from_secs(10), "the stream's opening", opened.into_future()).await.expect("the stream opens")
}
async fn runs_through_the_silence<B: Broker>(replies: RpcStream<u64>, silence: Duration, what: &str) {
let started = Instant::now();
let items: Vec<_> = within::<B, _>(silence + Duration::from_secs(10), "the paused stream", replies.collect()).await;
let items: Vec<u64> = items
.into_iter()
.map(|item| item.unwrap_or_else(|error| panic!("{what}: the stream failed {:?} after it opened: {error:?}", started.elapsed())))
.collect();
assert_eq!(items, vec![0, 1], "{what}: the paused stream's items");
assert!(started.elapsed() >= silence, "{what}: the stream ended {:?} after it opened, before its silence", started.elapsed());
}
async fn ends_at<B: Broker>(mut replies: RpcStream<u64>, idle: Duration, silence: Duration, what: &str) {
let first = within::<B, _>(Duration::from_secs(10), "the first item", replies.next()).await.expect("the stream yields");
assert_eq!(first.expect("the first item arrives"), 0, "{what}: the first item");
let silent = Instant::now();
let ended = within::<B, _>(silence + Duration::from_secs(10), "the idle timeout", replies.next()).await.expect("the stream yields its end");
let waited = silent.elapsed();
failed(ended, ErrorKind::Timeout);
assert!(waited >= idle - Duration::from_millis(50), "{what}: the stream ended {waited:?} into the silence, before its {idle:?} idle timeout");
assert!(waited < silence, "{what}: the stream ended {waited:?} into the silence, not at its {idle:?} idle timeout");
}
pub async fn unbounded_idle_timeout_outlasts_the_client_s<B: Broker>() {
let fixture = Fixture::<B>::start().await;
if !streams(&fixture.capabilities()) {
refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
return fixture.stop().await;
}
let budget = fixture.broker.budget();
let client = idle_client(&fixture, idle_of(budget));
let replies = paused::<B>(&client, silence_of(budget), Bound::Unbounded).await;
runs_through_the_silence::<B>(replies, silence_of(budget), "a stream at `Bound::Unbounded`").await;
fixture.stop().await;
}
pub async fn default_idle_timeout_is_the_client_s<B: Broker>() {
let fixture = Fixture::<B>::start().await;
if !streams(&fixture.capabilities()) {
refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
return fixture.stop().await;
}
let budget = fixture.broker.budget();
let client = idle_client(&fixture, idle_of(budget));
let replies = paused::<B>(&client, silence_of(budget), Bound::Default).await;
ends_at::<B>(replies, idle_of(budget), silence_of(budget), "a stream at `Bound::Default`").await;
fixture.stop().await;
}
pub async fn shorter_idle_timeout_replaces_the_client_s<B: Broker>() {
let fixture = Fixture::<B>::start().await;
if !streams(&fixture.capabilities()) {
refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
return fixture.stop().await;
}
let budget = fixture.broker.budget();
let client = idle_client(&fixture, silence_of(budget) * 2);
let replies = paused::<B>(&client, silence_of(budget), Bound::After(idle_of(budget))).await;
ends_at::<B>(replies, idle_of(budget), silence_of(budget), "a stream given a shorter idle timeout").await;
fixture.stop().await;
}
pub async fn zero_idle_timeout_is_refused_before_any_frame<B: Broker>() {
let fixture = Fixture::<B>::start().await;
let counts = Arc::new(Counts::default());
let link = Counted { link: fixture.broker.client_link(&addresses(&[&fixture.server])), counts: Arc::clone(&counts) };
let client = client_over::<B, _>(link).await;
let refused = within::<B, _>(
Duration::from_secs(10),
"the refusal",
client.rpc.stream::<_, u64>(PAUSE, &0u64).idle_timeout(Bound::After(Duration::ZERO)).into_future(),
)
.await;
let refused = failed(refused.map(drop), ErrorKind::BadRequest);
assert_eq!(refused.reason(), Some("zero_timeout"), "the refusal's reason: {refused:?}");
assert!(
refused.source().is_some_and(|source| source.downcast_ref::<ZeroTimeout>().is_some()),
"the refusal's source is not a `ZeroTimeout`: {refused:?}"
);
assert_eq!(
(counts.connects.load(Ordering::SeqCst), counts.frames.load(Ordering::SeqCst)),
(0, 0),
"the client's connects and frames sent before the refusal"
);
let sum = client.rpc.request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).timeout(Duration::from_secs(10)).await;
assert_eq!(sum.expect("a unary call after the refusal is answered"), Sum { sum: 5 });
assert!(
counts.connects.load(Ordering::SeqCst) > 0 && counts.frames.load(Ordering::SeqCst) > 0,
"the counts did not move for a call that reached the server"
);
client.close().await;
fixture.stop().await;
}
pub async fn longest_idle_timeout_does_not_panic<B: Broker>() {
let fixture = Fixture::<B>::start().await;
if !streams(&fixture.capabilities()) {
refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
return fixture.stop().await;
}
let budget = fixture.broker.budget();
let client = idle_client(&fixture, idle_of(budget));
let replies = paused::<B>(&client, silence_of(budget), Bound::After(Duration::MAX)).await;
runs_through_the_silence::<B>(replies, silence_of(budget), "a stream at `Bound::After(Duration::MAX)`").await;
fixture.stop().await;
}
pub(crate) const MARK: &str = "x-conformance-mark";
const ZERO_CALLS: usize = 8;
fn zero_refused<T: std::fmt::Debug>(refused: Result<T, RpcError>, what: &str) {
let refused = failed(refused, ErrorKind::BadRequest);
assert_eq!(refused.reason(), Some("zero_timeout"), "{what}: the refusal's reason: {refused:?}");
assert!(
refused.source().is_some_and(|source| source.downcast_ref::<ZeroTimeout>().is_some()),
"{what}: the refusal's source is not a `ZeroTimeout`: {refused:?}"
);
}
pub async fn zero_call_timeout_is_refused_before_the_server_sees_it<B: Broker>() {
let tap = Tap::default();
let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
for _ in 0..ZERO_CALLS {
let call = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "zero").timeout(Duration::ZERO);
zero_refused(within::<B, _>(Duration::from_secs(10), "the refusal", call.into_future()).await, "`Call::timeout(Duration::ZERO)`");
}
let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
assert_eq!(sum.expect("a call with a ten-second timeout is answered"), Sum { sum: 5 });
assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received");
fixture.stop().await;
}
pub async fn zero_stream_deadline_is_refused_before_the_server_sees_it<B: Broker>() {
let tap = Tap::default();
let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
for _ in 0..ZERO_CALLS {
let call = fixture.rpc().stream::<_, u32>(COUNT, &2u32).header(MARK, "zero").deadline(Duration::ZERO);
let refused = within::<B, _>(Duration::from_secs(10), "the refusal", call.into_future()).await;
zero_refused(refused.map(drop), "`StreamCall::deadline(Duration::ZERO)`");
}
let call = fixture.rpc().stream::<_, u32>(COUNT, &2u32).header(MARK, "after").deadline(Duration::from_secs(10));
let opened = within::<B, _>(Duration::from_secs(10), "the stream's opening", call.into_future()).await;
if streams(&fixture.capabilities()) {
let replies = opened.expect("the stream opens");
let items: Vec<_> = within::<B, _>(Duration::from_secs(10), "the stream", replies.collect()).await;
let items: Vec<u32> = items.into_iter().map(|item| item.expect("the stream yields")).collect();
assert_eq!(items, vec![1, 2], "the stream given a ten-second deadline");
} else {
match opened.err() {
Some(error) if error.reason() == Some("shape_unsupported") => {}
other => panic!("a stream on a link carrying none was not refused `shape_unsupported`: {other:?}"),
}
let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
assert_eq!(sum.expect("a request after the refused stream is answered"), Sum { sum: 5 });
}
assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received");
fixture.stop().await;
}
pub async fn passed_deadline_is_refused_before_the_server_sees_it<B: Broker>() {
let tap = Tap::default();
let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
let passed = crate::rt::runtime::<B>().now();
let mut outcomes =
fixture.client.execute(ExecOptions::new().deadline(passed), async |exec| past_deadline::<B>(&fixture, &exec.handle()).await).await;
let opened = fixture.client.open(ExecOptions::new().deadline(passed));
outcomes.extend(past_deadline::<B>(&fixture, &opened.handle()).await);
assert!(!opened.is_cancelled(), "the opened execution was cancelled, so its deadline alone did not refuse the calls");
drop(opened);
let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
assert_eq!(sum.expect("a call outside the execution is answered"), Sum { sum: 5 });
crate::rt::sleep::<B>(fixture.broker.budget().settle).await;
assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received; the calls' outcomes: {outcomes:?}");
assert_eq!(fixture.server.probe.events(), 0, "an event sent past its execution's deadline reached its handler");
for (what, outcome) in outcomes {
match outcome {
Err(error) if error.kind() == ErrorKind::Timeout => {}
other => panic!("{what} made inside an execution whose deadline has passed: expected `Timeout`, got: {other:?}"),
}
}
fixture.stop().await;
}
async fn past_deadline<B: Broker>(fixture: &Fixture<B>, exec: &ExecutionRef) -> Vec<(&'static str, Result<(), RpcError>)> {
let mut outcomes = Vec::new();
for _ in 0..ZERO_CALLS {
let call = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "passed").within(exec);
outcomes.push(("a request", within::<B, _>(Duration::from_secs(10), "the request", call.into_future()).await.map(drop)));
let stream = fixture.rpc().stream::<_, u32>(COUNT, &2u32).header(MARK, "passed").within(exec);
outcomes.push(("a stream", within::<B, _>(Duration::from_secs(10), "the stream", stream.into_future()).await.map(drop)));
let event = fixture.rpc().emit(EVENT, &1u32).header(MARK, "passed").within(exec);
outcomes.push(("an event", within::<B, _>(Duration::from_secs(10), "the event", event.into_future()).await));
}
outcomes
}
pub async fn cancelled_execution_s_call_is_refused_before_the_server_sees_it<B: Broker>() {
let tap = Tap::default();
let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
let outcomes = fixture
.client
.execute(ExecOptions::new(), async |exec| {
exec.cancel();
let exec = exec.handle();
let mut outcomes = Vec::new();
for _ in 0..ZERO_CALLS {
let call = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "cancelled").within(&exec);
outcomes.push(("a request", within::<B, _>(Duration::from_secs(10), "the request", call.into_future()).await.map(drop)));
let stream = fixture.rpc().stream::<_, u32>(COUNT, &2u32).header(MARK, "cancelled").within(&exec);
outcomes.push(("a stream", within::<B, _>(Duration::from_secs(10), "the stream", stream.into_future()).await.map(drop)));
}
outcomes
})
.await;
let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
assert_eq!(sum.expect("a call outside the execution is answered"), Sum { sum: 5 });
assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received; the calls' outcomes: {outcomes:?}");
for (what, outcome) in outcomes {
match outcome {
Err(error) if error.kind() == ErrorKind::Unavailable => {}
other => panic!("{what} made inside a cancelled execution: expected `Unavailable`, got: {other:?}"),
}
}
fixture.stop().await;
}
const DEADLINE_UNIT: Duration = Duration::from_millis(1);
pub async fn measured_once_connected<B: Broker>() {
let fixture = Fixture::<B>::start().await;
let budget = fixture.broker.budget();
let held = budget.settle / 2;
let link = SlowConnect::new(fixture.broker.client_link(&addresses(&[&fixture.server])), Hold::Waits(held));
let handoffs = link.handoffs.clone();
let client = client_over::<B, _>(link).await;
let left = held + budget.boot;
let deadline = crate::rt::runtime::<B>().now() + left;
let opened = client.open(ExecOptions::new().deadline(deadline));
let exec = opened.handle();
let streaming = streams(&fixture.capabilities());
let request = async {
let call = client.rpc.request::<_, ()>(DEADLINE, &()).header(MARK, "request").timeout(left * 2).within(&exec);
("request", call.await)
};
let stream = async {
let call = client.rpc.stream::<_, u32>(DEADLINE_STREAM, &()).header(MARK, "stream").within(&exec);
let outcome = match call.await {
Ok(replies) => replies.collect::<Vec<_>>().await.into_iter().collect::<Result<Vec<u32>, _>>().map(|items| assert_eq!(items, vec![1])),
Err(error) => Err(error),
};
("stream", outcome)
};
let streamed = async {
let items = futures_util::stream::iter([1i64, 2]);
let call = client.rpc.send_stream::<_, i64>(DEADLINE_SUM, items).header(MARK, "streamed").timeout(left * 2).within(&exec);
("streamed", call.await.map(|sum| assert_eq!(sum, 3)))
};
let calls = async {
if streaming {
let (request, stream, streamed) = futures_util::join!(request, stream, streamed);
vec![request, stream, streamed]
} else {
vec![request.await]
}
};
let outcomes = within::<B, _>(left + budget.settle, "the calls", calls).await;
drop(exec);
drop(opened);
for (mark, outcome) in &outcomes {
if let Err(error) = outcome {
panic!("the {mark} made on a new connection failed: {error:?}");
}
}
let seen = fixture.server.probe.seen();
let handed = handoffs.all();
let mut report = Vec::new();
let mut late = false;
for (mark, _) in &outcomes {
let taken = seen.iter().find(|seen| seen.mark.as_deref() == Some(*mark)).unwrap_or_else(|| panic!("the server took no {mark}: {seen:?}"));
let server = taken.deadline.unwrap_or_else(|| panic!("the server gave the {mark} no deadline: {taken:?}"));
let millis: u64 = taken.header.as_deref().and_then(|value| value.parse().ok()).unwrap_or_else(|| panic!("the {mark} carried no readable `deadline-ms`: {taken:?}"));
let read = server - Duration::from_millis(millis);
let sent = handed.iter().find(|(handed, _)| handed == mark).map(|(_, at)| *at).unwrap_or_else(|| panic!("the link was handed no {mark}: {handed:?}"));
let transit = read.saturating_duration_since(sent);
late |= server > deadline + transit + DEADLINE_UNIT;
report.push(format!(
"the {mark}: `deadline-ms: {millis}`, the server's deadline {:+.3} ms from the caller's, its frame {:.3} ms in transit",
signed_millis(server, deadline),
transit.as_secs_f64() * 1e3
));
}
assert!(!late, "a server's deadline was later than its caller's by more than the frame's transit and one unit, its connect held {held:?}:\n{}", report.join("\n"));
client.close().await;
fixture.stop().await;
}
pub async fn connect_past_the_deadline_is_refused_before_the_server_sees_it<B: Broker>() {
let tap = Tap::default();
let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
let budget = fixture.broker.budget();
let left = budget.settle / 5;
let held = left * 2;
let streaming = streams(&fixture.capabilities());
let mut outcomes = Vec::new();
for hold in [Hold::Waits(held), Hold::BlocksConnected(held)] {
for shape in ["a request", "a stream", "a streamed request", "an event"] {
if !streaming && matches!(shape, "a stream" | "a streamed request") {
continue;
}
let link = SlowConnect::new(fixture.broker.client_link(&addresses(&[&fixture.server])), hold);
let client = client_over::<B, _>(link).await;
let opened = client.open(ExecOptions::new().deadline(crate::rt::runtime::<B>().now() + left));
let exec = opened.handle();
let call = async {
match shape {
"a request" => client.rpc.request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "slow").within(&exec).await.map(drop),
"a stream" => client.rpc.stream::<_, u32>(COUNT, &2u32).header(MARK, "slow").within(&exec).await.map(drop),
"a streamed request" => {
let items = futures_util::stream::iter([1i64, 2]);
client.rpc.send_stream::<_, i64>(SUM, items).header(MARK, "slow").within(&exec).await.map(drop)
}
_ => client.rpc.emit(EVENT, &1u32).header(MARK, "slow").within(&exec).await,
}
};
let outcome = within::<B, _>(held + budget.boot, "the call", call).await;
outcomes.push((hold, shape, outcome));
drop(exec);
drop(opened);
client.close().await;
}
}
let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
assert_eq!(sum.expect("a call on a connection already made is answered"), Sum { sum: 5 });
crate::rt::sleep::<B>(budget.settle).await;
assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received; the calls' outcomes: {outcomes:?}");
assert_eq!(fixture.server.probe.events(), 0, "an event whose connect outlasted its deadline reached its handler: {outcomes:?}");
for (hold, shape, outcome) in outcomes {
match outcome {
Err(error) if error.kind() == ErrorKind::Timeout => {}
other => panic!("{shape} whose connect {hold:?} past its deadline: expected `Timeout`, got: {other:?}"),
}
}
fixture.stop().await;
}
const BLOCKED_CALLS: usize = 16;
const UNANSWERED: &str = "10000";
pub async fn blocked_connect_s_timer_ends_with_its_bound<B: Broker>() {
let fixture = Fixture::<B>::start().await;
let budget = fixture.broker.budget();
let timeout = budget.settle * 2 / 5;
let blocked = timeout / 2;
let mut calls = Vec::new();
for _ in 0..BLOCKED_CALLS {
let clock = ArmedClock::new(crate::rt::runtime::<B>());
let stamped = Stamped { link: fixture.broker.client_link(&addresses(&[&fixture.server])), value: UNANSWERED };
let link = SlowConnect::new(stamped, Hold::Blocks(blocked));
let connects = link.connects.clone();
let client = client_timed::<B, _>(link, clock.clone()).await;
clock.take();
let started = Instants::now(&*clock.clock);
let call = client.rpc.request::<_, ()>(STALL, &()).timeout(timeout).into_future();
let outcome = within::<B, _>(timeout + blocked + budget.boot, "the call", call).await;
let answered = Instants::now(&*clock.clock);
calls.push(Blocked { started, answered, connects: connects.all(), sleeps: clock.take(), outcome });
client.close().await;
}
if !calls.iter().all(|call| call.armed_within(timeout)) {
let report: Vec<String> = calls.iter().map(Blocked::report).collect();
panic!(
"a call given {timeout:?} over a connect blocking {blocked:?} failed other than `Timeout`, or, its connect returning \
inside its bound, no sleep it asked for ended inside [the call's start + {timeout:?}, the connect's start + \
{timeout:?}] on the runtime's clock before it answered; every call:\n{}",
report.join("\n")
);
}
fixture.stop().await;
}
#[derive(Clone)]
struct ArmedClock {
clock: Arc<dyn Runtime>,
sleeps: Arc<Mutex<Vec<Armed>>>,
}
#[derive(Clone, Debug)]
struct Armed {
asked: Instant,
ends: Option<Instant>,
ended: Arc<OnceLock<Instant>>,
}
impl ArmedClock {
fn new(clock: Arc<dyn Runtime>) -> ArmedClock {
ArmedClock { clock, sleeps: Arc::default() }
}
fn take(&self) -> Vec<Armed> {
std::mem::take(&mut *self.sleeps.lock().unwrap_or_else(PoisonError::into_inner))
}
}
impl Timer for ArmedClock {
fn sleep(&self, d: Duration) -> ulo::BoxFuture<'static, ()> {
let slept = self.try_sleep(d);
Box::pin(async move {
let _ = slept.await;
})
}
fn now(&self) -> Instant {
self.clock.now()
}
fn try_sleep(&self, d: Duration) -> ulo::BoxFuture<'static, Result<(), ulo::Refused>> {
let asked = self.clock.now();
let (clock, sleeps) = (Arc::clone(&self.clock), Arc::clone(&self.sleeps));
Box::pin(async move {
let ends = clock.now().checked_add(d);
let ended = Arc::new(OnceLock::new());
sleeps.lock().unwrap_or_else(PoisonError::into_inner).push(Armed { asked, ends, ended: Arc::clone(&ended) });
let slept = clock.try_sleep(d).await;
if slept.is_ok() {
let _ = ended.set(clock.now());
}
slept
})
}
}
struct Blocked {
started: Instants,
answered: Instants,
connects: Vec<(Instants, Instants)>,
sleeps: Vec<Armed>,
outcome: Result<(), RpcError>,
}
impl Blocked {
fn armed_within(&self, timeout: Duration) -> bool {
matches!(&self.outcome, Err(error) if error.kind() == ErrorKind::Timeout) && self.timer_armed_in_time(timeout)
}
fn timer_armed_in_time(&self, timeout: Duration) -> bool {
let earliest = self.started.timer + timeout;
let latest = self.connects.first().map(|(connect, _)| connect.timer + timeout);
let ended_it = |sleep: &Armed| {
sleep.asked >= self.started.timer
&& sleep.ends.is_some_and(|ends| ends >= earliest && latest.is_none_or(|latest| ends <= latest))
&& sleep.ended.get().is_some_and(|ended| *ended <= self.answered.timer)
};
let connected_past_the_bound = self.connects.first().is_some_and(|(_, returned)| returned.timer >= earliest);
connected_past_the_bound || self.sleeps.iter().any(ended_it)
}
fn report(&self) -> String {
let since = |at: Instants| format!("{:+.1} ms by std, {:+.1} ms by the runtime", signed_millis(at.std, self.started.std), signed_millis(at.timer, self.started.timer));
let on_runtime = |at: Instant| format!("{:+.3} ms", signed_millis(at, self.started.timer));
let connects: Vec<String> = self
.connects
.iter()
.map(|(began, returned)| format!("a connect began {} and returned {}", since(*began), since(*returned)))
.collect();
let sleeps: Vec<String> = self
.sleeps
.iter()
.map(|sleep| {
let ended = sleep.ended.get().map_or_else(|| "not ended".to_owned(), |ended| format!("ended {}", on_runtime(*ended)));
match sleep.ends {
Some(ends) => format!("a sleep asked {} ending {}, {ended}", on_runtime(sleep.asked), on_runtime(ends)),
None => format!("a sleep asked {} ending past the clock's range, {ended}", on_runtime(sleep.asked)),
}
})
.collect();
format!(
"answered {}; {}; {}; the runtime's clock read {:+.3} ms from std as the call was made; {:?}",
since(self.answered),
if connects.is_empty() { "no connect".to_owned() } else { connects.join(", ") },
if sleeps.is_empty() { "no sleep".to_owned() } else { sleeps.join(", ") },
signed_millis(self.started.timer, self.started.std),
self.outcome
)
}
}
#[derive(Clone, Copy, Debug)]
struct Instants {
std: Instant,
timer: Instant,
}
impl Instants {
fn now(timer: &dyn Timer) -> Instants {
Instants { std: Instant::now(), timer: timer.now() }
}
}
#[derive(Clone, Default)]
struct Connects(Arc<Mutex<Vec<(Instants, Instants)>>>);
impl Connects {
fn all(&self) -> Vec<(Instants, Instants)> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
}
fn signed_millis(a: Instant, b: Instant) -> f64 {
match a.checked_duration_since(b) {
Some(later) => later.as_secs_f64() * 1e3,
None => -(b.duration_since(a).as_secs_f64() * 1e3),
}
}
#[derive(Clone, Copy, Debug)]
enum Hold {
Waits(Duration),
Blocks(Duration),
BlocksConnected(Duration),
}
#[derive(Clone, Default)]
struct Handoffs(Arc<Mutex<Vec<(String, Instant)>>>);
impl Handoffs {
fn all(&self) -> Vec<(String, Instant)> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
}
struct SlowConnect<L> {
link: L,
hold: Hold,
handoffs: Handoffs,
connects: Connects,
}
impl<L> SlowConnect<L> {
fn new(link: L, hold: Hold) -> Self {
SlowConnect { link, hold, handoffs: Handoffs::default(), connects: Connects::default() }
}
}
impl<L: Link> Link for SlowConnect<L> {
const NAME: &'static str = L::NAME;
fn capabilities(&self) -> Capabilities {
self.link.capabilities()
}
fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
self.link.prepare(app)
}
fn usable(&self) -> Result<(), BoxError> {
self.link.usable()
}
fn max_inflight(&mut self, calls: Count) {
self.link.max_inflight(calls);
}
fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
self.link.subscribable(subscriptions)
}
fn listen(&self, patterns: &[Subscription]) -> impl Future<Output = Result<Inbound, BoxError>> + Send {
self.link.listen(patterns)
}
async fn connect(&self, runtime: &Arc<dyn Runtime>) -> Result<Outbound, BoxError> {
let began = Instants::now(&**runtime);
match self.hold {
Hold::Waits(held) => runtime.sleep(held).await,
Hold::Blocks(held) => std::thread::sleep(held),
Hold::BlocksConnected(_) => {}
}
let connected = self.link.connect(runtime).await;
if let (Ok(_), Hold::BlocksConnected(held)) = (&connected, self.hold) {
std::thread::sleep(held);
}
self.connects.0.lock().unwrap_or_else(PoisonError::into_inner).push((began, Instants::now(&**runtime)));
let Outbound { send, replies } = connected?;
let (handoffs, clock) = (self.handoffs.clone(), Arc::clone(runtime));
Ok(Outbound {
send: Box::new(move |pattern, frame, reply_to| {
let headers = match &frame {
Frame::Req { headers, .. } | Frame::Open { headers, .. } | Frame::Evt { headers, .. } => headers.get(MARK),
_ => None,
};
if let Some(mark) = headers {
handoffs.0.lock().unwrap_or_else(PoisonError::into_inner).push((mark.to_owned(), clock.now()));
}
send(pattern, frame, reply_to)
}),
replies,
})
}
fn drain(&self) -> impl Future<Output = ()> + Send {
self.link.drain()
}
fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
self.link.close()
}
fn bound(&self) -> Vec<BoundAddr> {
self.link.bound()
}
}
#[derive(Clone, Default)]
pub(crate) struct Tap(Arc<Mutex<Vec<Stamp>>>);
pub(crate) type Stamp = (String, Option<String>);
impl Tap {
pub(crate) fn marks(&self) -> Vec<String> {
self.stamps().into_iter().map(|(mark, _)| mark).collect()
}
pub(crate) fn stamps(&self) -> Vec<Stamp> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
}
pub(crate) struct Tapped<L> {
pub(crate) link: L,
pub(crate) tap: Tap,
}
impl<L: Link> Link for Tapped<L> {
const NAME: &'static str = L::NAME;
fn capabilities(&self) -> Capabilities {
self.link.capabilities()
}
fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
self.link.prepare(app)
}
fn usable(&self) -> Result<(), BoxError> {
self.link.usable()
}
fn max_inflight(&mut self, calls: Count) {
self.link.max_inflight(calls);
}
fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
self.link.subscribable(subscriptions)
}
async fn listen(&self, patterns: &[Subscription]) -> Result<Inbound, BoxError> {
let inbound = self.link.listen(patterns).await?;
let tap = self.tap.clone();
Ok(Box::pin(inbound.inspect(move |delivery| {
let headers = match &delivery.frame {
Frame::Req { headers, .. } | Frame::Open { headers, .. } | Frame::Evt { headers, .. } => headers,
_ => return,
};
if let Some(mark) = headers.get(MARK) {
let deadline = headers.get("deadline-ms").map(str::to_owned);
tap.0.lock().unwrap_or_else(PoisonError::into_inner).push((mark.to_owned(), deadline));
}
})))
}
fn connect(&self, runtime: &Arc<dyn Runtime>) -> impl Future<Output = Result<Outbound, BoxError>> + Send {
self.link.connect(runtime)
}
fn drain(&self) -> impl Future<Output = ()> + Send {
self.link.drain()
}
fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
self.link.close()
}
fn bound(&self) -> Vec<BoundAddr> {
self.link.bound()
}
}
#[derive(Default)]
struct Counts {
connects: AtomicUsize,
frames: AtomicUsize,
}
struct Counted<L> {
link: L,
counts: Arc<Counts>,
}
impl<L: Link> Link for Counted<L> {
const NAME: &'static str = L::NAME;
fn capabilities(&self) -> Capabilities {
self.link.capabilities()
}
fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
self.link.prepare(app)
}
fn usable(&self) -> Result<(), BoxError> {
self.link.usable()
}
fn max_inflight(&mut self, calls: Count) {
self.link.max_inflight(calls);
}
fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
self.link.subscribable(subscriptions)
}
fn listen(&self, patterns: &[Subscription]) -> impl Future<Output = Result<Inbound, BoxError>> + Send {
self.link.listen(patterns)
}
async fn connect(&self, runtime: &Arc<dyn Runtime>) -> Result<Outbound, BoxError> {
self.counts.connects.fetch_add(1, Ordering::SeqCst);
let Outbound { send, replies } = self.link.connect(runtime).await?;
let counts = Arc::clone(&self.counts);
Ok(Outbound {
send: Box::new(move |pattern, frame, reply_to| {
counts.frames.fetch_add(1, Ordering::SeqCst);
send(pattern, frame, reply_to)
}),
replies,
})
}
fn drain(&self) -> impl Future<Output = ()> + Send {
self.link.drain()
}
fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
self.link.close()
}
fn bound(&self) -> Vec<BoundAddr> {
self.link.bound()
}
}
struct MutedCancel<L>(L);
impl<L: Link> Link for MutedCancel<L> {
const NAME: &'static str = L::NAME;
fn capabilities(&self) -> Capabilities {
self.0.capabilities()
}
fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
self.0.prepare(app)
}
fn usable(&self) -> Result<(), BoxError> {
self.0.usable()
}
fn max_inflight(&mut self, calls: Count) {
self.0.max_inflight(calls);
}
fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
self.0.subscribable(subscriptions)
}
fn listen(&self, patterns: &[Subscription]) -> impl Future<Output = Result<Inbound, BoxError>> + Send {
self.0.listen(patterns)
}
async fn connect(&self, runtime: &Arc<dyn Runtime>) -> Result<Outbound, BoxError> {
let Outbound { send, replies } = self.0.connect(runtime).await?;
Ok(Outbound {
send: Box::new(move |pattern, frame, reply_to| match frame {
Frame::Cancel { .. } => Box::pin(async { Ok(()) }),
frame => send(pattern, frame, reply_to),
}),
replies,
})
}
fn drain(&self) -> impl Future<Output = ()> + Send {
self.0.drain()
}
fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
self.0.close()
}
fn bound(&self) -> Vec<BoundAddr> {
self.0.bound()
}
}
pub struct Stamped<L> {
pub link: L,
pub value: &'static str,
}
impl<L: Link> Link for Stamped<L> {
const NAME: &'static str = L::NAME;
fn capabilities(&self) -> Capabilities {
self.link.capabilities()
}
fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
self.link.prepare(app)
}
fn usable(&self) -> Result<(), BoxError> {
self.link.usable()
}
fn max_inflight(&mut self, calls: Count) {
self.link.max_inflight(calls);
}
fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
self.link.subscribable(subscriptions)
}
fn listen(&self, patterns: &[Subscription]) -> impl Future<Output = Result<Inbound, BoxError>> + Send {
self.link.listen(patterns)
}
async fn connect(&self, runtime: &Arc<dyn Runtime>) -> Result<Outbound, BoxError> {
let Outbound { send, replies } = self.link.connect(runtime).await?;
let value = self.value;
Ok(Outbound {
send: Box::new(move |on, frame, reply_to| {
let frame = match frame {
Frame::Req { id, pattern, headers, data } => Frame::Req { id, pattern, headers: stamped(&headers, value), data },
Frame::Open { id, pattern, headers } => Frame::Open { id, pattern, headers: stamped(&headers, value) },
Frame::Evt { pattern, headers, data } => Frame::Evt { pattern, headers: stamped(&headers, value), data },
other => other,
};
send(on, frame, reply_to)
}),
replies,
})
}
fn drain(&self) -> impl Future<Output = ()> + Send {
self.link.drain()
}
fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
self.link.close()
}
fn bound(&self) -> Vec<BoundAddr> {
self.link.bound()
}
}
fn stamped(headers: &CallHeaders, value: &str) -> CallHeaders {
let mut out = CallHeaders::new();
for (name, kept) in headers.iter().filter(|(name, _)| *name != "deadline-ms") {
out.insert(name, kept);
}
out.insert("deadline-ms", value);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn at(base: Instant, millis: u64) -> Instants {
let moment = base + Duration::from_millis(millis);
Instants { std: moment, timer: moment }
}
fn sleep(base: Instant, asked: u64, ends: u64, ended: u64) -> Armed {
Armed {
asked: base + Duration::from_millis(asked),
ends: Some(base + Duration::from_millis(ends)),
ended: Arc::new(OnceLock::from(base + Duration::from_millis(ended))),
}
}
fn call(base: Instant, connects: Vec<(Instants, Instants)>, sleeps: Vec<Armed>) -> Blocked {
Blocked { started: at(base, 0), answered: at(base, 201), connects, sleeps, outcome: Ok(()) }
}
#[test]
fn a_call_taking_a_connection_another_call_opened_is_held_to_its_own_timer() {
let base = Instant::now();
let timeout = Duration::from_millis(200);
assert!(call(base, vec![], vec![sleep(base, 0, 200, 200)]).timer_armed_in_time(timeout));
assert!(call(base, vec![], vec![sleep(base, 1, 201, 201)]).timer_armed_in_time(timeout), "no connect, no upper end");
assert!(!call(base, vec![], vec![sleep(base, 0, 100, 100)]).timer_armed_in_time(timeout), "armed for too little");
assert!(!call(base, vec![], vec![sleep(base, 0, 200, 250)]).timer_armed_in_time(timeout), "ended after the answer");
assert!(!call(base, vec![], vec![]).timer_armed_in_time(timeout), "no sleep at all");
}
#[test]
fn a_call_with_a_connect_holds_the_sleep_to_the_connects_start() {
let base = Instant::now();
let timeout = Duration::from_millis(200);
let connect = vec![(at(base, 0), at(base, 100))];
assert!(call(base, connect.clone(), vec![sleep(base, 0, 200, 200)]).timer_armed_in_time(timeout));
assert!(!call(base, connect, vec![sleep(base, 100, 300, 200)]).timer_armed_in_time(timeout), "armed after the block");
}
}