wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Shared support for the client request-hook tests.
//!
//! Holds the echo and capturing servers, the hook harnesses, and the fixtures
//! that [`super::request_hooks`] exercises, keeping that module within the
//! repository's 400-line limit.

use std::{
    future::Future,
    net::SocketAddr,
    panic::AssertUnwindSafe,
    sync::{
        Arc,
        Mutex,
        MutexGuard,
        PoisonError,
        atomic::{AtomicUsize, Ordering},
    },
    time::Duration,
};

use futures::FutureExt as _;
use rstest::fixture;
use wireframe_testing::ServerMode;

use super::helpers::{TestResult, bind_loopback, spawn_frame_server, spawn_serving_task};
use crate::{app::Envelope, client::WireframeClient, test_helpers::ServerTaskGuard};

/// Spawn a server that captures each received frame payload for inspection.
///
/// Every frame is recorded and echoed back so the client can receive it; the
/// accumulated frames come back through the join handle.
pub(super) async fn spawn_capturing_server() -> TestResult<(
    std::net::SocketAddr,
    tokio::task::JoinHandle<std::io::Result<Vec<Vec<u8>>>>,
)> {
    spawn_serving_task(Vec::new(), |captured: &mut Vec<Vec<u8>>, bytes| {
        captured.push(bytes.to_vec());
        Some(bytes.freeze())
    })
    .await
}

/// Locks a hook log, recovering the entries if a previous holder panicked.
///
/// The log only accumulates marker bytes, so no invariant is broken by a
/// poisoning; discarding the recorded markers would lose the very evidence the
/// assertion needs.
pub(super) fn lock_log(log: &Mutex<Vec<u8>>) -> MutexGuard<'_, Vec<u8>> {
    log.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Client type returned by [`connect_client_with_hooks`].
pub(super) type TestClient = WireframeClient<
    crate::serializer::BincodeSerializer,
    crate::rewind_stream::RewindStream<tokio::net::TcpStream>,
>;

/// Helper to build and connect a client with custom hook configuration.
pub(super) async fn connect_client_with_hooks<F>(
    addr: std::net::SocketAddr,
    configure: F,
) -> TestResult<TestClient>
where
    F: FnOnce(crate::client::WireframeClientBuilder) -> crate::client::WireframeClientBuilder,
{
    let builder = WireframeClient::builder();
    Ok(configure(builder).connect(addr).await?)
}

/// Generic test harness for request hook tests.
///
/// Spawns an echo server, connects a client with custom hooks,
/// runs the test body, and handles cleanup automatically.
pub(super) async fn run_hook_test<F, T>(configure_hooks: F, test_body: T) -> TestResult
where
    F: FnOnce(crate::client::WireframeClientBuilder) -> crate::client::WireframeClientBuilder,
    T: for<'a> FnOnce(
        &'a mut TestClient,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = TestResult> + 'a>>,
{
    run_hook_test_with_server(
        configure_hooks,
        test_body,
        spawn_frame_server(ServerMode::Echo),
    )
    .await
}

/// Variant for tests that need the capturing server.
pub(super) async fn run_hook_test_with_capture<F, T>(
    configure_hooks: F,
    test_body: T,
) -> TestResult<Vec<Vec<u8>>>
where
    F: FnOnce(crate::client::WireframeClientBuilder) -> crate::client::WireframeClientBuilder,
    T: for<'a> FnOnce(
        &'a mut TestClient,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = TestResult> + 'a>>,
{
    run_hook_test_with_server(configure_hooks, test_body, spawn_capturing_server()).await
}

/// Shared harness behind [`run_hook_test`] and [`run_hook_test_with_capture`].
///
/// Takes the server as an unpolled future so each caller chooses its own
/// server without duplicating the connect, run-body, teardown, and join steps.
///
/// The server task is accounted for on every exit path. On success the client
/// is already dropped, so the serve loop ends and the join yields its result,
/// propagating both the `JoinError` and the server's own I/O error. On a
/// returned error or a panicking body the task is aborted and awaited instead:
/// the client may never have connected, leaving the server parked in `accept`,
/// so waiting for a loop that cannot end would hang the test rather than report
/// the original outcome. Cancelling the harness future itself is the remaining
/// path; the guard's abort-on-drop fallback stops the task there without
/// awaiting it.
async fn run_hook_test_with_server<F, T, R, S>(
    configure_hooks: F,
    test_body: T,
    server: S,
) -> TestResult<R>
where
    F: FnOnce(crate::client::WireframeClientBuilder) -> crate::client::WireframeClientBuilder,
    T: for<'a> FnOnce(
        &'a mut TestClient,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = TestResult> + 'a>>,
    S: Future<Output = TestResult<(SocketAddr, tokio::task::JoinHandle<std::io::Result<R>>)>>,
{
    let (addr, server_task) = server.await?;

    let ((), server_result) = ServerTaskGuard::new(server_task)
        .run_and_join(drive_client(addr, configure_hooks, test_body))
        .await?;

    Ok(server_result?)
}

/// Connects a client, runs the body against it, and drops it before returning.
///
/// The drop happens on the failure path too, so the server always observes the
/// close rather than the connection being held open by a leaked client.
async fn drive_client<F, T>(addr: SocketAddr, configure_hooks: F, test_body: T) -> TestResult
where
    F: FnOnce(crate::client::WireframeClientBuilder) -> crate::client::WireframeClientBuilder,
    T: for<'a> FnOnce(
        &'a mut TestClient,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = TestResult> + 'a>>,
{
    let mut client = connect_client_with_hooks(addr, configure_hooks).await?;
    let outcome = test_body(&mut client).await;
    drop(client);
    outcome
}

/// Test fixture for tracking hook invocations with a counter.
pub(super) struct HookCounter {
    counter: Arc<AtomicUsize>,
}

impl HookCounter {
    pub(super) fn new() -> Self {
        Self {
            counter: Arc::new(AtomicUsize::new(0)),
        }
    }

    pub(super) fn before_send_hook(&self) -> impl Fn(&mut Vec<u8>) + Send + Sync + 'static {
        let count = self.counter.clone();
        move |_bytes: &mut Vec<u8>| {
            count.fetch_add(1, Ordering::SeqCst);
        }
    }

    pub(super) fn after_receive_hook(
        &self,
    ) -> impl Fn(&mut bytes::BytesMut) + Send + Sync + 'static {
        let count = self.counter.clone();
        move |_bytes: &mut bytes::BytesMut| {
            count.fetch_add(1, Ordering::SeqCst);
        }
    }

    pub(super) fn assert_count(&self, expected: usize, message: &str) {
        assert_eq!(self.counter.load(Ordering::SeqCst), expected, "{message}");
    }
}

/// Test fixture for tracking hook invocations with a log.
pub(super) struct HookLog {
    log: Arc<Mutex<Vec<u8>>>,
}

impl HookLog {
    pub(super) fn new() -> Self {
        Self {
            log: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub(super) fn before_send_hook(
        &self,
        marker: u8,
    ) -> impl Fn(&mut Vec<u8>) + Send + Sync + 'static {
        let log = self.log.clone();
        move |_bytes: &mut Vec<u8>| {
            lock_log(&log).push(marker);
        }
    }

    pub(super) fn after_receive_hook(
        &self,
        marker: u8,
    ) -> impl Fn(&mut bytes::BytesMut) + Send + Sync + 'static {
        let log = self.log.clone();
        move |_bytes: &mut bytes::BytesMut| {
            lock_log(&log).push(marker);
        }
    }

    pub(super) fn assert_entries(&self, expected: &[u8], message: &str) {
        assert_eq!(lock_log(&self.log).as_slice(), expected, "{message}");
    }
}

/// Fixture: create a fresh [`HookCounter`].
#[rustfmt::skip]
#[fixture]
pub(super) fn hook_counter() -> HookCounter {
    HookCounter::new()
}

/// Fixture: create a fresh [`HookLog`].
#[rustfmt::skip]
#[fixture]
pub(super) fn hook_log() -> HookLog {
    HookLog::new()
}

/// Helper: test body that sends an envelope.
pub(super) async fn send_envelope_test_body(client: &mut TestClient) -> TestResult {
    let envelope = Envelope::new(1, None, vec![1, 2, 3]);
    client.send_envelope(envelope).await?;
    Ok(())
}

/// Helper: test body that sends an envelope and receives a response.
pub(super) async fn send_and_receive_test_body(client: &mut TestClient) -> TestResult {
    let envelope = Envelope::new(1, None, vec![1, 2, 3]);
    client.send_envelope(envelope).await?;
    let _response: Envelope = client.receive_envelope().await?;
    Ok(())
}

/// The harness must surface a server task's own I/O error, not report success.
#[tokio::test]
async fn server_task_io_error_reaches_the_caller() {
    let server = async {
        let (listener, addr) = bind_loopback().await?;
        let handle: tokio::task::JoinHandle<std::io::Result<()>> = tokio::spawn(async move {
            let _accepted = listener.accept().await?;
            Err(std::io::Error::other("server failed"))
        });
        Ok::<_, Box<dyn std::error::Error + Send + Sync>>((addr, handle))
    };

    let error = run_hook_test_with_server(
        |builder| builder,
        |_client| Box::pin(async { Ok(()) }),
        server,
    )
    .await
    .expect_err("a server-side I/O failure must reach the caller");

    assert!(
        error.to_string().contains("server failed"),
        "expected the server's own error, got: {error}"
    );
}

/// A panicking server task must surface as a join failure rather than success.
///
/// The panic is deliberate, so the runtime prints its message during this test.
#[tokio::test]
async fn server_task_panic_reaches_the_caller() {
    let server = async {
        let (listener, addr) = bind_loopback().await?;
        let handle: tokio::task::JoinHandle<std::io::Result<()>> = tokio::spawn(async move {
            let _accepted = listener.accept().await?;
            panic!("server panicked")
        });
        Ok::<_, Box<dyn std::error::Error + Send + Sync>>((addr, handle))
    };

    let result = run_hook_test_with_server(
        |builder| builder,
        |_client| Box::pin(async { Ok(()) }),
        server,
    )
    .await;

    assert!(
        result.is_err(),
        "a panicking server task must fail the harness through its JoinError"
    );
}

/// The harness must return the body's own connection error unchanged, and must
/// not wait for a server that is parked where no client can reach it.
///
/// The listener is dropped before the client connects, so the connection is
/// refused. The spawned task never accepts, so a natural join would block
/// forever; the timeout turns that into a clear failure instead of a hung test.
#[tokio::test]
async fn body_error_is_returned_without_waiting_for_the_server() {
    let server = async {
        let (listener, addr) = bind_loopback().await?;
        drop(listener);
        let handle: tokio::task::JoinHandle<std::io::Result<()>> =
            tokio::spawn(async { std::future::pending().await });
        Ok::<_, Box<dyn std::error::Error + Send + Sync>>((addr, handle))
    };

    let outcome = tokio::time::timeout(
        Duration::from_secs(10),
        run_hook_test_with_server(
            |builder| builder,
            |_client| Box::pin(async { Ok(()) }),
            server,
        ),
    )
    .await
    .expect("the harness must not wait for a server that cannot finish");

    let error = outcome.expect_err("a failed connection must be reported");
    assert!(
        error.downcast_ref::<crate::client::ClientError>().is_some(),
        "expected the body's own connection error, got: {error}"
    );
}

/// A panicking body must resume its original payload once the server is reaped.
#[tokio::test]
async fn body_panic_is_resumed_after_the_server_is_reaped() {
    let server = async {
        let (listener, addr) = bind_loopback().await?;
        let handle: tokio::task::JoinHandle<std::io::Result<()>> = tokio::spawn(async move {
            let _accepted = listener.accept().await?;
            std::future::pending().await
        });
        Ok::<_, Box<dyn std::error::Error + Send + Sync>>((addr, handle))
    };

    let harness = run_hook_test_with_server(
        |builder| builder,
        |_client| Box::pin(async { panic!("body panicked") }),
        server,
    );

    let outcome = AssertUnwindSafe(harness).catch_unwind().await;
    let payload = outcome.expect_err("the body panic must be resumed");
    let message = payload.downcast_ref::<&str>().copied();
    assert_eq!(
        message,
        Some("body panicked"),
        "the original panic payload must be resumed"
    );
}