#![cfg(not(loom))]
#![forbid(unsafe_code)]
#[path = "common/prepared_support.rs"]
mod prepared_support;
#[path = "common/protocol_request.rs"]
mod protocol_request;
#[path = "common/recording_protocol.rs"]
mod recording_protocol;
#[path = "common/recording_protocol_contexts.rs"]
mod recording_protocol_contexts;
#[path = "common/server_harness.rs"]
mod server_harness;
#[path = "common/tagging_codec.rs"]
mod tagging_codec;
use std::sync::Arc;
use bytes::Bytes;
use futures::stream;
use prepared_support::{
assert_context_continuity,
assert_two_frame_event_log,
marked,
only_registered_handle,
wait_for_setup,
};
use protocol_request::request_frame;
use recording_protocol::{HookEvent, MARKER, RecordingProtocolFixture};
use rstest::rstest;
use server_harness::{EVENT_TIMEOUT, read_frame, spawn_server, stop};
use tagging_codec::{TaggingCodec, WRAP_TAG};
use tokio::{io::AsyncWriteExt, net::TcpStream, sync::mpsc, time::timeout};
use wireframe::{
app::{Envelope, Handler, ResponseHandler},
codec::EofError,
response::{FrameStream, Response},
serializer::{BincodeSerializer, Serializer},
session::SessionRegistry,
};
use wireframe_testing::{TestResult, decode_frames, prepare_and_drive_with_frames};
type ResponseApp = wireframe::app::WireframeApp<BincodeSerializer, (), Envelope>;
fn echo_handler() -> Handler<Envelope> { Arc::new(|_env: &Envelope| Box::pin(async {})) }
fn two_frame_stream_handler() -> ResponseHandler<Envelope> {
Arc::new(|_request: &Envelope| {
Box::pin(async {
let frames: FrameStream<Envelope, ()> = Box::pin(stream::iter(vec![
Ok(Envelope::new(2, None, vec![1_u8])),
Ok(Envelope::new(2, None, vec![2_u8])),
]));
Response::Stream(frames)
})
})
}
fn two_frame_multi_packet_handler() -> ResponseHandler<Envelope> {
Arc::new(|_request: &Envelope| {
Box::pin(async {
let (tx, rx) = mpsc::channel(2);
for payload in [vec![1_u8], vec![2_u8]] {
let _sent = tx.send(Envelope::new(2, None, payload)).await;
}
drop(tx);
Response::MultiPacket(rx)
})
})
}
fn single_frame_handler() -> ResponseHandler<Envelope> {
Arc::new(|_request: &Envelope| {
Box::pin(async { Response::Single(Envelope::new(1, None, b"resp".to_vec())) })
})
}
struct ExpectedFrames {
first: Vec<u8>,
second: Vec<u8>,
}
impl ExpectedFrames {
fn new() -> TestResult<Self> {
const REQUEST_CORRELATION: Option<u64> = Some(7);
const RESPONSE_ID: u32 = 2;
Ok(Self {
first: BincodeSerializer.serialize(&Envelope::new(
RESPONSE_ID,
REQUEST_CORRELATION,
vec![1_u8],
))?,
second: BincodeSerializer.serialize(&Envelope::new(
RESPONSE_ID,
REQUEST_CORRELATION,
vec![2_u8],
))?,
})
}
fn hooked_wire_frames(&self, terminator: &[u8]) -> Vec<Vec<u8>> {
[self.first.as_slice(), self.second.as_slice(), terminator]
.into_iter()
.map(marked)
.collect()
}
}
async fn assert_two_frame_source_is_hooked_once(
route_id: u32,
handler: ResponseHandler<Envelope>,
context: &str,
) -> TestResult<()> {
const TERMINATOR_BYTES: &[u8] = b"END";
let fixture =
RecordingProtocolFixture::<Bytes>::new(Some(Bytes::from_static(TERMINATOR_BYTES)));
let app = ResponseApp::new()?
.route_response(route_id, handler)?
.with_protocol(fixture.protocol());
let bytes = prepare_and_drive_with_frames(app, vec![request_frame(route_id)?]).await?;
let expected = ExpectedFrames::new()?;
assert_two_frame_event_log(
&fixture,
[&expected.first, &expected.second],
TERMINATOR_BYTES,
context,
);
assert_eq!(
decode_frames(&bytes)?,
expected.hooked_wire_frames(TERMINATOR_BYTES),
"{context}: each frame and the terminator are hooked exactly once"
);
Ok(())
}
#[rstest]
#[tokio::test]
async fn prepared_response_runs_before_send_once_after_serialization() -> TestResult<()> {
let fixture = RecordingProtocolFixture::<Bytes>::new(None);
let app = ResponseApp::new()?
.route(1, echo_handler())?
.with_codec(TaggingCodec::new(1024))
.with_protocol(fixture.protocol());
let bytes = prepare_and_drive_with_frames(app, vec![request_frame(1)?]).await?;
let frames = decode_frames(&bytes)?;
let [decoded] = frames.as_slice() else {
return Err(format!("expected exactly one response frame, got {}", frames.len()).into());
};
let events = fixture.events();
let [
HookEvent::Setup,
HookEvent::BeforeSend(observed),
HookEvent::CommandEnd,
] = events.as_slice()
else {
return Err(format!(
"expected setup, before_send, then command end on the prepared path, got {events:?}"
)
.into());
};
assert_eq!(
observed.last(),
Some(&WRAP_TAG),
"the hook must run after the codec wrapped the payload: {observed:?}"
);
let mut expected = observed.to_vec();
expected.push(MARKER);
assert_eq!(
decoded, &expected,
"the hook must observe the codec-wrapped frame that the peer decodes"
);
Ok(())
}
#[rstest]
#[tokio::test]
async fn prepared_stream_runs_before_send_once_per_frame_and_terminator() -> TestResult<()> {
assert_two_frame_source_is_hooked_once(2, two_frame_stream_handler(), "streamed response").await
}
#[rstest]
#[tokio::test]
async fn prepared_multi_packet_runs_before_send_once_per_frame_and_terminator() -> TestResult<()> {
assert_two_frame_source_is_hooked_once(
3,
two_frame_multi_packet_handler(),
"multi-packet response",
)
.await
}
#[rstest]
#[tokio::test]
async fn prepared_pushes_run_before_send_once_in_write_order() -> TestResult<()> {
let fixture = RecordingProtocolFixture::<Bytes>::new(None);
let registry = Arc::new(SessionRegistry::<Bytes>::new());
let app = ResponseApp::new()?
.with_protocol(fixture.protocol())
.with_session_registry(Arc::clone(®istry));
let (addr, shutdown) = spawn_server(app).await?;
let mut client = TcpStream::connect(addr).await?;
wait_for_setup(&fixture).await?;
let handle = only_registered_handle(®istry)?;
handle
.push_high_priority(Bytes::from_static(b"high"))
.await
.map_err(|error| format!("high-priority push should be accepted: {error:?}"))?;
let high = timeout(EVENT_TIMEOUT, read_frame(&mut client)).await??;
handle
.push_low_priority(Bytes::from_static(b"low"))
.await
.map_err(|error| format!("low-priority push should be accepted: {error:?}"))?;
let low = timeout(EVENT_TIMEOUT, read_frame(&mut client)).await??;
assert_eq!(
high,
marked(b"high"),
"the high-priority frame carries exactly one hook marker"
);
assert_eq!(
low,
marked(b"low"),
"the low-priority frame carries exactly one hook marker"
);
assert_eq!(
fixture.events(),
vec![
HookEvent::Setup,
HookEvent::BeforeSend(Bytes::from_static(b"high")),
HookEvent::BeforeSend(Bytes::from_static(b"low")),
],
"the prepared push path dispatches setup, then one before_send per frame in write order"
);
assert_context_continuity(&fixture, ®istry);
drop(client);
stop(&shutdown).await
}
#[rstest]
#[tokio::test]
async fn prepared_connection_shares_one_context_across_push_and_response() -> TestResult<()> {
const REQUEST_CORRELATION: Option<u64> = Some(7);
let fixture = RecordingProtocolFixture::<Bytes>::new(None);
let registry = Arc::new(SessionRegistry::<Bytes>::new());
let app = ResponseApp::new()?
.route_response(1, single_frame_handler())?
.with_protocol(fixture.protocol())
.with_session_registry(Arc::clone(®istry));
let (addr, shutdown) = spawn_server(app).await?;
let mut client = TcpStream::connect(addr).await?;
wait_for_setup(&fixture).await?;
let handle = only_registered_handle(®istry)?;
handle
.push_high_priority(Bytes::from_static(b"push"))
.await
.map_err(|error| format!("the push should be accepted: {error:?}"))?;
let pushed = timeout(EVENT_TIMEOUT, read_frame(&mut client)).await??;
client.write_all(&request_frame(1)?).await?;
let response = timeout(EVENT_TIMEOUT, read_frame(&mut client)).await??;
let expected_response =
BincodeSerializer.serialize(&Envelope::new(1, REQUEST_CORRELATION, b"resp".to_vec()))?;
assert_eq!(pushed, marked(b"push"), "the push carries one hook marker");
assert_eq!(
response,
marked(&expected_response),
"the handler response carries one hook marker"
);
assert_eq!(
fixture.events(),
vec![
HookEvent::Setup,
HookEvent::BeforeSend(Bytes::from_static(b"push")),
HookEvent::BeforeSend(Bytes::from(expected_response)),
HookEvent::CommandEnd,
],
"setup, the push, the response and the completion hook share one order"
);
assert_context_continuity(&fixture, ®istry);
drop(client);
stop(&shutdown).await
}
#[rstest]
#[tokio::test]
async fn prepared_connection_runs_setup_then_reports_truncation() -> TestResult<()> {
let fixture = RecordingProtocolFixture::<Bytes>::new(None);
let app = ResponseApp::new()?.with_protocol(fixture.protocol());
let outcome = prepare_and_drive_with_frames(app, vec![vec![0x00]]).await;
assert!(
outcome.is_err(),
"a truncated length header must reach the caller: {outcome:?}"
);
let events = fixture.events();
let expected = vec![
HookEvent::Setup,
HookEvent::Eof {
error: EofError::MidHeader {
bytes_received: 1,
header_size: 4,
},
partial: vec![0x00],
},
];
assert_eq!(
events, expected,
"a prepared connection dispatches setup once and reports the truncation: {events:?}"
);
Ok(())
}