use std::{future, io, sync::Arc, time::Duration};
use bytes::Bytes;
use futures::StreamExt;
use metrics::{SharedString, Unit};
use metrics_util::{
CompositeKey,
debugging::{DebugValue, DebuggingRecorder},
};
use rstest::fixture;
use crate::{
app::{
StreamingHandler,
inbound_handler::{
stream_active::{BodyIdentity, HandlerFuture},
stream_handles::{ChunkBudget, FirstChunk},
stream_terminal::{HandlerWait, TerminalFailure},
},
},
metrics::{STREAMING_BODY_OUTCOMES, StreamingBodyOutcome},
request::{AccountedBodySender, RequestBodyStream, RequestParts},
};
pub(super) type Sample = (CompositeKey, Option<Unit>, Option<SharedString>, DebugValue);
#[fixture]
pub(super) fn final_chunk() -> FirstChunk {
FirstChunk {
key: None,
assembly: None,
parts: RequestParts::new(7, None, Vec::new()),
chunk: Bytes::from_static(b"last"),
is_last: true,
}
}
#[fixture]
pub(super) fn generous_budget() -> ChunkBudget {
ChunkBudget {
other_retained: 0,
limit: usize::MAX,
}
}
pub(super) fn dropping_handler() -> StreamingHandler {
Arc::new(|_parts: RequestParts, body: RequestBodyStream| {
drop(body);
Box::pin(future::pending())
})
}
pub(super) fn truncated_failure() -> TerminalFailure {
TerminalFailure {
identity: identity(),
error: io::Error::new(io::ErrorKind::UnexpectedEof, "truncated body"),
}
}
pub(super) const fn identity() -> BodyIdentity {
BodyIdentity {
message_id: 7,
correlation_id: None,
}
}
pub(super) fn reading_handler(mut body: RequestBodyStream) -> HandlerFuture {
Box::pin(async move {
let mut received = Vec::new();
while let Some(chunk) = body.next().await {
match chunk {
Ok(bytes) => received.extend_from_slice(&bytes),
Err(_) => return Some(Bytes::from_static(b"failed")),
}
}
Some(Bytes::from(received))
})
}
pub(super) fn reading_route() -> StreamingHandler {
Arc::new(|_parts: RequestParts, body: RequestBodyStream| reading_handler(body))
}
pub(super) struct Counts(Vec<Sample>);
impl Counts {
pub(super) fn count(&self, outcome: StreamingBodyOutcome) -> u64 {
self.0
.iter()
.filter(|sample| counts_outcome(sample, outcome))
.map(|(_, _, _, recorded)| match recorded {
DebugValue::Counter(count) => *count,
_ => 0,
})
.sum()
}
}
pub(super) fn recorded<T>(scenario: impl FnOnce() -> T) -> (T, Counts) {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let value = ::metrics::with_local_recorder(&recorder, scenario);
let counts = Counts(snapshotter.snapshot().into_vec());
(value, counts)
}
pub(super) fn counted<T>(outcome: StreamingBodyOutcome, scenario: impl FnOnce() -> T) -> (T, u64) {
let (value, counts) = recorded(scenario);
(value, counts.count(outcome))
}
pub(super) struct Expectation {
pub(super) reply: HandlerWait,
pub(super) recorded: StreamingBodyOutcome,
pub(super) why: &'static str,
}
pub(super) fn assert_exchange(
settled: io::Result<HandlerWait>,
counts: &Counts,
expected: &Expectation,
) {
let reply = match settled {
Ok(wait) => wait,
Err(error) => panic!("the exchange must run on a paused runtime: {error}"),
};
let why = expected.why;
assert_eq!(reply, expected.reply, "{why}");
for outcome in OUTCOMES {
let count = u64::from(outcome == expected.recorded);
assert_eq!(
counts.count(outcome),
count,
"{} recorded {count} times: {why}",
outcome.as_str()
);
}
}
const OUTCOMES: [StreamingBodyOutcome; 6] = [
StreamingBodyOutcome::Delivered,
StreamingBodyOutcome::Terminal,
StreamingBodyOutcome::Abandoned,
StreamingBodyOutcome::AdmissionTimeout,
StreamingBodyOutcome::DeliveryTimeout,
StreamingBodyOutcome::NoHandler,
];
fn counts_outcome(sample: &Sample, outcome: StreamingBodyOutcome) -> bool {
let (key, ..) = sample;
key.key().name() == STREAMING_BODY_OUTCOMES
&& key
.key()
.labels()
.any(|label| label.key() == "outcome" && label.value() == outcome.as_str())
}
pub(super) fn paused_block_on<F: future::Future>(future: F) -> io::Result<F::Output> {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.start_paused(true)
.build()?;
Ok(runtime.block_on(future))
}
pub(super) const fn wait() -> Duration { Duration::from_millis(50) }
pub(super) async fn queue_one_chunk(sender: &AccountedBodySender) {
let _refused_if_reached = sender
.clone()
.send_chunk(Bytes::from_static(b"chunk"), 0, usize::MAX)
.await;
}