use std::{
future,
num::NonZeroUsize,
sync::Arc,
time::{Duration, Instant},
};
use bytes::Bytes;
use rstest::{fixture, rstest};
use super::{super::stream_active::PendingEvent, ConnectionStreams};
use crate::{
app::{
StreamingHandler,
inbound_handler::stream_handles::{ChunkBudget, ChunkOffer, FirstChunk},
},
message_assembler::{
EnvelopeRouting,
FirstFrameHeader,
FirstFrameInput,
MessageAssemblyState,
MessageKey,
},
request::{QueuedBytes, RequestBodyStream, RequestParts, accounted_body_channel},
};
#[rstest]
#[test]
fn the_stall_policy_decides_against_the_instant_it_is_given() {
let short_wait = Duration::from_millis(50);
let start = tokio::time::Instant::now();
let mut streams = ConnectionStreams::new(QueuedBytes::new());
streams.stalled_since = Some(start);
assert!(
!streams.stall_expired_at(short_wait, start),
"a stall that has not started cannot have expired"
);
assert_eq!(
streams.stall_remaining_at(short_wait, start),
short_wait,
"an untouched interval offers the whole bound"
);
assert!(
!streams.stall_expired_at(short_wait, start + short_wait / 2),
"half the bound is not past the bound"
);
assert_eq!(
streams.stall_remaining_at(short_wait, start + short_wait / 2),
short_wait / 2,
"the remaining interval is the part not yet spent"
);
assert!(
streams.stall_expired_at(short_wait, start + short_wait),
"the bound itself has expired"
);
assert_eq!(
streams.stall_remaining_at(short_wait, start + short_wait * 2),
Duration::ZERO,
"a passed bound leaves nothing to spend"
);
}
#[fixture]
fn stalled_handler() -> StreamingHandler {
Arc::new(|_parts: RequestParts, body: RequestBodyStream| {
Box::pin(async move {
let _body = body;
future::pending::<Option<Bytes>>().await
})
})
}
#[fixture]
fn unaffordable_first_chunk() -> FirstChunk {
FirstChunk {
key: None,
assembly: None,
parts: RequestParts::new(1, None, Vec::new()),
chunk: Bytes::from_static(b"abcd"),
is_last: false,
}
}
#[fixture]
fn keyed_first_chunk() -> FirstChunk {
FirstChunk {
key: Some(MessageKey(3)),
assembly: None,
parts: RequestParts::new(1, None, Vec::new()),
chunk: Bytes::from_static(b"abcd"),
is_last: false,
}
}
#[fixture]
fn tight_budget() -> ChunkBudget {
ChunkBudget {
other_retained: 0,
limit: 6,
}
}
#[rstest]
#[tokio::test(start_paused = true)]
async fn an_unaffordable_first_chunk_becomes_a_pending_admission(
unaffordable_first_chunk: FirstChunk,
stalled_handler: StreamingHandler,
) {
let mut streams = ConnectionStreams::new(QueuedBytes::new());
let _held_body = retain_bytes_outside_the_slot(&streams).await;
streams.start(unaffordable_first_chunk, &stalled_handler);
assert!(
streams.is_live(),
"the slot must be registered before its first chunk is admitted"
);
assert!(
streams.has_pending_send(),
"an unaffordable first chunk must wait as a pending admission"
);
}
#[rstest]
#[tokio::test(start_paused = true)]
async fn a_released_account_admits_the_pending_first_chunk(
unaffordable_first_chunk: FirstChunk,
stalled_handler: StreamingHandler,
tight_budget: ChunkBudget,
) {
let mut streams = ConnectionStreams::new(QueuedBytes::new());
let held_body = retain_bytes_outside_the_slot(&streams).await;
streams.start(unaffordable_first_chunk, &stalled_handler);
drop(held_body);
let event = streams
.drive_pending(Duration::from_secs(1), tight_budget)
.await;
assert!(
matches!(event, PendingEvent::Send(Ok(()))),
"the first chunk should be admitted once the account drains"
);
streams.complete_send(Ok(()));
assert!(!streams.has_pending_send(), "the admission is finished");
assert_eq!(
streams.retained_bytes(),
b"abcd".len(),
"the delivered chunk is charged to the connection account"
);
}
#[rstest]
#[tokio::test(start_paused = true)]
async fn a_chunk_refused_by_outside_bytes_is_admitted_once_they_are_released(
unaffordable_first_chunk: FirstChunk,
stalled_handler: StreamingHandler,
) {
let mut streams = ConnectionStreams::new(QueuedBytes::new());
let _held_body = retain_bytes_outside_the_slot(&streams).await;
streams.start(unaffordable_first_chunk, &stalled_handler);
let crowded = ChunkBudget {
other_retained: 4,
limit: 11,
};
let refused = streams.drive_pending(Duration::from_secs(1), crowded).await;
assert!(
matches!(refused, PendingEvent::Idle),
"the chunk must wait while the assembly holds bytes"
);
let freed = ChunkBudget {
other_retained: 0,
limit: 11,
};
let admitted = streams.drive_pending(Duration::from_secs(1), freed).await;
assert!(
matches!(admitted, PendingEvent::Send(Ok(()))),
"the released bytes must let the queued chunk in"
);
}
#[rstest]
#[tokio::test(start_paused = true)]
async fn an_assembly_purge_releases_the_bytes_refusing_a_pending_chunk(
unaffordable_first_chunk: FirstChunk,
stalled_handler: StreamingHandler,
) {
let mut streams = ConnectionStreams::new(QueuedBytes::new());
let _held_body = retain_bytes_outside_the_slot(&streams).await;
streams.start(unaffordable_first_chunk, &stalled_handler);
let start = Instant::now();
let mut assembly = retaining_assembly(start);
let crowded = ChunkBudget {
other_retained: assembly.total_buffered_bytes(),
limit: 11,
};
let refused = streams.drive_pending(Duration::from_secs(1), crowded).await;
assert!(
matches!(refused, PendingEvent::Idle),
"the chunk must wait while the assembly retains its bytes"
);
let purged = assembly.purge_expired_detailed_at(start + Duration::from_secs(31));
assert!(
!purged.buffered().is_empty(),
"the stalled assembly must actually expire"
);
let freed = ChunkBudget {
other_retained: assembly.total_buffered_bytes(),
limit: 11,
};
let admitted = streams.drive_pending(Duration::from_secs(1), freed).await;
assert!(
matches!(admitted, PendingEvent::Send(Ok(()))),
"the purged assembly must release the bytes the chunk was waiting for"
);
}
#[rstest]
#[tokio::test(start_paused = true)]
async fn a_continuation_chunk_is_admitted_only_after_the_first_chunk(
keyed_first_chunk: FirstChunk,
stalled_handler: StreamingHandler,
) {
let mut streams = ConnectionStreams::new(QueuedBytes::new());
let _held_body = retain_bytes_outside_the_slot(&streams).await;
let key = keyed_first_chunk
.key
.expect("the fixture carries a message key");
streams.start(keyed_first_chunk, &stalled_handler);
let continuation = || ChunkOffer {
key,
chunk: Bytes::from_static(b"next"),
is_last: true,
};
assert!(
!streams.push_chunk(continuation()),
"a continuation must not be queued behind an unadmitted chunk"
);
let roomy = ChunkBudget {
other_retained: 0,
limit: usize::MAX,
};
let first = streams.drive_pending(Duration::from_secs(1), roomy).await;
assert!(
matches!(first, PendingEvent::Send(Ok(()))),
"the first chunk must be admitted once the account has room"
);
streams.complete_send(Ok(()));
assert!(
streams.push_chunk(continuation()),
"the continuation is accepted once no admission is in flight"
);
let second = streams.drive_pending(Duration::from_secs(1), roomy).await;
assert!(
matches!(second, PendingEvent::Send(Ok(()))),
"the continuation must reach the handler after the first chunk"
);
streams.complete_send(Ok(()));
assert!(
!streams.has_pending_send(),
"the final chunk closes the body"
);
assert_eq!(
streams.retained_bytes(),
b"held".len() + b"abcd".len() + b"next".len(),
"every delivered chunk is charged to the connection account"
);
}
fn retaining_assembly(start: Instant) -> MessageAssemblyState {
let mut state = MessageAssemblyState::new(
NonZeroUsize::new(1024).expect("the per-message cap is non-zero"),
Duration::from_secs(30),
);
let header = FirstFrameHeader {
message_key: MessageKey(7),
metadata_len: 0,
body_len: 4,
total_body_len: None,
is_last: false,
};
let input = FirstFrameInput::new(&header, EnvelopeRouting::default(), vec![], b"abcd")
.expect("the first frame fits the per-message cap");
state
.accept_first_frame_at(input, start)
.expect("the first frame is admissible");
state
}
async fn retain_bytes_outside_the_slot(streams: &ConnectionStreams) -> RequestBodyStream {
let (sender, body) = accounted_body_channel(1, streams.queued());
sender
.send_chunk(Bytes::from_static(b"held"), 0, usize::MAX)
.await
.expect("the consumer is still open");
body
}