use std::collections::HashSet;
use std::time::{Duration, Instant};
use futures_util::StreamExt;
use futures_util::stream::BoxStream;
use ulo::{App, Module, ModuleDef, ModuleIdentity, Shape, Signal};
use ulo::app::Connected;
use ulo_rpc::link::ClientProbe;
use ulo_rpc::{CallHeaders, Codec, Delivery, Frame, Link, Outbound, Pattern, ReplyTo};
use crate::rt::{sleep, timeout};
use crate::{Broker, Budget, Harness, report};
const ORDERED: &str = "conformance.ordered";
const ROUNDS: u64 = 200;
const OPENS: u64 = 20;
const PATIENCE: Duration = Duration::from_secs(5);
fn short_hold(budget: Budget) -> Duration {
budget.settle / 2
}
fn call_deadline(budget: Budget) -> Duration {
budget.settle + budget.settle / 5
}
const PROBE_POLL: Duration = Duration::from_millis(10);
struct Empty;
impl Module for Empty {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_type::<Self>()
}
fn register(&self, m: &mut ModuleDef<'_>) {
let _ = m;
}
}
struct Linked<B: Broker> {
broker: B,
app: App<Connected>,
server: B::Link,
inbound: BoxStream<'static, Delivery>,
client: B::Link,
outbound: Outbound,
}
impl<B: Broker> Linked<B> {
async fn streamed() -> Self {
let broker = B::start().await;
let shapes = broker.link().capabilities().shapes;
assert!(
shapes.contains(&Shape::ClientStreaming) || shapes.contains(&Shape::Bidi),
"the link carries no streamed request, so no `open` can be sent: declare the scenario not applicable, \
naming the streamed scenarios that assert the startup refusal"
);
Linked::on(broker).await
}
async fn on(broker: B) -> Self {
let app = App::builder(Empty)
.runtime(<B::Harness as Harness>::runtime())
.wire()
.unwrap_or_else(|error| crate::startup_failed!("the ordering scenario's app did not wire: {}", report(&error)))
.connect()
.await
.unwrap_or_else(|error| crate::startup_failed!("the ordering scenario's app did not connect: {}", report(&error)));
let mut server = broker.link();
server.prepare(&app.handle()).await.unwrap_or_else(|error| crate::startup_failed!("the server's link did not prepare: {error}"));
let inbound = server
.listen(&[Pattern::from(ORDERED).into()])
.await
.unwrap_or_else(|error| crate::startup_failed!("the server's link did not listen: {error}"));
let client = broker.client_link(&server.bound());
let handle = app.handle();
let runtime = handle.runtime().unwrap_or_else(|| crate::startup_failed!("the ordering scenario's app has no runtime"));
let outbound = client.connect(runtime).await.unwrap_or_else(|error| crate::startup_failed!("the client's link did not connect: {error}"));
Linked { broker, app, server, inbound, client, outbound }
}
async fn read_pairs(&mut self, rounds: u64, opens: &str) {
let (mut opened, mut cancels) = (0u64, 0u64);
let mut held = HashSet::new();
while opened + cancels < 2 * rounds {
let Some(delivered) = timeout::<B, _>(PATIENCE, self.inbound.next()).await else {
panic!(
"{opened} {opens} and {cancels} cancels of {rounds} each reached the server within {PATIENCE:?} of the last; the \
server holds {held:?}"
);
};
let delivery = delivered.expect("the server's inbound stream ended");
match delivery.frame {
Frame::Req { id, .. } | Frame::Open { id, .. } => {
held.insert(id);
opened += 1;
}
Frame::Cancel { id } => {
assert!(held.remove(&id), "the server received a cancel for a call it does not hold: {id}");
cancels += 1;
}
other => panic!("the server received a frame other than {opens} or a cancel: {other:?}"),
}
}
assert!(held.is_empty(), "calls with no cancel after them: {held:?}");
}
async fn stop(self) {
let _ = self.client.close().await;
let _ = self.server.close().await;
let _ = self.app.close(Signal::new("conformance")).await;
}
}
pub async fn cancel_follows_its_request<B: Broker>() {
let broker = B::start().await;
if let Some(reason) = broker.link().capabilities().why_not_ordered_control() {
crate::skipped("cancel_follows_its_request", "ordered_control", reason);
return;
}
let mut linked = Linked::on(broker).await;
let pattern = Pattern::from(ORDERED);
let codec = if linked.server.capabilities().binary { Codec::Cbor } else { Codec::Json };
let null = codec.encode(&()).expect("a unit encodes");
for id in 1..=ROUNDS {
let request = Frame::Req { id, pattern: ORDERED.to_owned(), headers: CallHeaders::new(), data: null.clone() };
let request = (linked.outbound.send)(pattern.clone(), request, Some(ReplyTo { id }));
let cancel = (linked.outbound.send)(pattern.clone(), Frame::Cancel { id }, None);
let (requested, cancelled) = futures_util::join!(request, cancel);
requested.unwrap_or_else(|error| panic!("request {id} was not sent: {error}"));
cancelled.unwrap_or_else(|error| panic!("the cancel of request {id} was not sent: {error}"));
}
linked.read_pairs(ROUNDS, "requests").await;
linked.stop().await;
}
pub async fn cancel_before_opened<B: Broker>() {
let mut linked = Linked::<B>::streamed().await;
let pattern = Pattern::from(ORDERED);
for id in 1..=OPENS {
let open = Frame::Open { id, pattern: ORDERED.to_owned(), headers: CallHeaders::new() };
let open = (linked.outbound.send)(pattern.clone(), open, Some(ReplyTo { id }));
let cancel = (linked.outbound.send)(pattern.clone(), Frame::Cancel { id }, None);
let (opened, cancelled) = futures_util::join!(open, cancel);
opened.unwrap_or_else(|error| panic!("the open of call {id} was not sent: {error}"));
cancelled.unwrap_or_else(|error| panic!("the cancel of call {id} was not sent: {error}"));
}
linked.read_pairs(OPENS, "opens").await;
linked.stop().await;
}
fn probe<B: Broker>(linked: &Linked<B>) -> &ClientProbe {
B::probe(&linked.client).unwrap_or_else(|| {
panic!(
"the environment reads no client probe, so the link holds no `cancel` for an `opened`: declare the held-cancel \
scenarios not applicable with the reason"
)
})
}
async fn probe_until<B: Broker>(probe: &ClientProbe, what: &str, done: impl Fn(&ClientProbe) -> bool) {
let waited = timeout::<B, _>(PATIENCE, async {
while !done(probe) {
sleep::<B>(PROBE_POLL).await;
}
})
.await;
assert!(waited.is_some(), "{what} did not happen within {PATIENCE:?}");
}
impl<B: Broker> Linked<B> {
async fn cancel_with_opened_withheld(&mut self, id: u64, headers: CallHeaders) {
probe(self).withhold();
let pattern = Pattern::from(ORDERED);
let open = Frame::Open { id, pattern: ORDERED.to_owned(), headers };
(self.outbound.send)(pattern.clone(), open, Some(ReplyTo { id }))
.await
.unwrap_or_else(|error| panic!("the open of call {id} was not sent: {error}"));
let delivered = timeout::<B, _>(PATIENCE, self.inbound.next()).await.expect("the open did not reach the server");
let frame = delivered.expect("the server's inbound stream ended").frame;
assert!(matches!(frame, Frame::Open { .. }), "the server received {frame:?} where the open was due");
let probe = probe(self);
probe_until::<B>(probe, "the server's `opened` reaching the client", |probe| probe.withheld() == 1).await;
(self.outbound.send)(pattern, Frame::Cancel { id }, None)
.await
.unwrap_or_else(|error| panic!("the cancel of call {id} was not sent: {error}"));
assert_eq!(probe.calls(), Some(1), "the client's table once the call was cancelled before its `opened`");
}
}
pub async fn late_opened<B: Broker>() {
let mut linked = Linked::<B>::streamed().await;
let late = short_hold(linked.broker.budget());
linked.cancel_with_opened_withheld(1, CallHeaders::new()).await;
sleep::<B>(late).await;
probe(&linked).release();
let delivered = timeout::<B, _>(PATIENCE, linked.inbound.next()).await.unwrap_or_else(|| {
panic!("the held cancel did not reach the server within {PATIENCE:?} of the late `opened`")
});
let frame = delivered.expect("the server's inbound stream ended").frame;
assert!(matches!(frame, Frame::Cancel { .. }), "the server received {frame:?} where the held cancel was due");
assert_eq!(probe(&linked).calls(), Some(0), "the client's table once the held cancel went out");
linked.stop().await;
}
pub async fn hold_runs_out<B: Broker>() {
let mut linked = Linked::<B>::streamed().await;
let hold = short_hold(linked.broker.budget());
probe(&linked).set_hold(hold);
let cancelled = Instant::now();
linked.cancel_with_opened_withheld(1, CallHeaders::new()).await;
probe_until::<B>(probe(&linked), "the held cancel's entry dropped", |probe| probe.calls() == Some(0)).await;
assert!(cancelled.elapsed() >= hold, "the held cancel was dropped before its hold ran out");
linked.stop().await;
}
pub async fn held_until_deadline<B: Broker>() {
let mut linked = Linked::<B>::streamed().await;
let deadline = call_deadline(linked.broker.budget());
probe(&linked).set_hold(Duration::from_secs(30));
let mut headers = CallHeaders::new();
headers.insert("deadline-ms", deadline.as_millis().to_string());
let opened = Instant::now();
linked.cancel_with_opened_withheld(1, headers).await;
probe_until::<B>(probe(&linked), "the held cancel's entry dropped at its call's deadline", |probe| probe.calls() == Some(0)).await;
assert!(opened.elapsed() >= deadline, "the held cancel was dropped {:?} after its `open`, before the call's {deadline:?} deadline", opened.elapsed());
linked.stop().await;
}