use std::{future::Future, io, time::Duration};
use bytes::Bytes;
use futures::{SinkExt, StreamExt};
use tokio::{io::DuplexStream, sync::Notify, task::JoinHandle, time::timeout};
use tokio_util::{
codec::{Framed, LengthDelimitedCodec},
sync::CancellationToken,
};
use wireframe_testing::{TestError, TestResult};
use super::super::{ConnectionProcessingContext, process_connection};
use crate::{
app::{Envelope, PreparedApp, WireframeApp},
serializer::{BincodeSerializer, Serializer},
test_helpers::first_frame_payload,
};
pub(super) type App = WireframeApp<BincodeSerializer, (), Envelope>;
type Prepared = PreparedApp<BincodeSerializer, (), Envelope>;
pub(super) type Client = Framed<DuplexStream, LengthDelimitedCodec>;
const DUPLEX_CAPACITY: usize = 1024;
pub(super) const STEP_WAIT: Duration = Duration::from_secs(5);
pub(super) const GRACE_SLACK: Duration = Duration::from_millis(1);
const REQUEST_CORRELATION: u64 = 5;
pub(super) fn ensure(condition: bool, message: impl Into<String>) -> TestResult {
if condition {
Ok(())
} else {
Err(TestError::Msg(message.into()))
}
}
pub(super) struct Scenario {
pub(super) client: Client,
pub(super) connection: JoinHandle<io::Result<()>>,
}
pub(super) async fn spawn_connection(app: App) -> TestResult<Scenario> {
spawn_connection_buffering(app, DUPLEX_CAPACITY).await
}
pub(super) async fn spawn_connection_buffering(app: App, capacity: usize) -> TestResult<Scenario> {
let prepared: Prepared = app
.prepare()
.await
.map_err(|error| format!("prepare the application: {error}"))?;
let (client, server) = tokio::io::duplex(capacity);
let shutdown = CancellationToken::new();
let connection = tokio::spawn({
let observed = shutdown.clone();
async move { process_connection(server, context(&prepared, &observed)).await }
});
Ok(Scenario {
client: Framed::new(client, LengthDelimitedCodec::new()),
connection,
})
}
fn context<'a, C, F>(
prepared: &'a PreparedApp<BincodeSerializer, C, Envelope, F>,
shutdown: &'a CancellationToken,
) -> ConnectionProcessingContext<'a, BincodeSerializer, C, Envelope, F>
where
C: Send + 'static,
F: crate::codec::FrameCodec,
{
ConnectionProcessingContext {
routes: &prepared.routes,
streaming_routes: &prepared.streaming_routes,
serializer: prepared.serializer.as_ref(),
codec: &prepared.codec,
on_connect: prepared.on_connect.as_deref(),
on_disconnect: prepared.on_disconnect.as_deref(),
message_assembler: prepared.message_assembler.as_deref(),
fragmentation: prepared.fragmentation,
protocol_hooks: prepared.protocol_hooks(),
memory_budgets: prepared.memory_budgets,
read_timeout_ms: prepared.read_timeout_ms,
shutdown,
push_queues: prepared.push_queues(),
session_registry: std::sync::Arc::clone(&prepared.session_registry),
peer_addr: None,
recovery_hook: prepared.recovery_hook.as_deref(),
recovery_config: prepared.recovery_config.clone(),
}
}
pub(super) async fn send_request(client: &mut Client, route: u32, payload: &[u8]) -> TestResult {
let envelope = Envelope::new(route, Some(REQUEST_CORRELATION), payload.to_vec());
let encoded = BincodeSerializer.serialize(&envelope)?;
client.send(Bytes::from(encoded)).await?;
Ok(())
}
pub(super) async fn send_complete(
client: &mut Client,
route: u32,
key: u64,
body: &[u8],
) -> TestResult {
send_request(
client,
route,
&first_frame_payload(key.into(), body, true, None)?,
)
.await
}
pub(super) async fn read_reply(client: &mut Client, step: &str) -> TestResult<Vec<u8>> {
read_reply_within(STEP_WAIT, client, step).await
}
pub(super) async fn read_reply_within(
wait: Duration,
client: &mut Client,
step: &str,
) -> TestResult<Vec<u8>> {
let frame = bounded_for(wait, step, client.next())
.await?
.ok_or_else(|| format!("the connection closed before {step} arrived"))??;
let (envelope, _): (Envelope, usize) = BincodeSerializer.deserialize(&frame)?;
Ok(envelope.payload_bytes().to_vec())
}
pub(super) async fn open_body(
client: &mut Client,
route: u32,
key: u64,
started: &Notify,
) -> TestResult {
send_request(
client,
route,
&first_frame_payload(key.into(), b"start", false, None)?,
)
.await?;
bounded("the live handler starting", started.notified()).await
}
pub(super) async fn bounded<T>(step: &str, future: impl Future<Output = T>) -> TestResult<T> {
bounded_for(STEP_WAIT, step, future).await
}
pub(super) async fn bounded_for<T>(
wait: Duration,
step: &str,
future: impl Future<Output = T>,
) -> TestResult<T> {
timeout(wait, future)
.await
.map_err(|_| format!("{step} did not complete within {wait:?}").into())
}