wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Tests for server runtime behaviour.

use std::{
    io,
    net::SocketAddr,
    sync::{
        Arc,
        Mutex,
        atomic::{AtomicUsize, Ordering},
    },
};

use rstest::rstest;
use tokio::{
    net::{TcpListener, TcpStream},
    sync::oneshot,
    task::yield_now,
    time::{Duration, Instant, advance, sleep, timeout},
};
use tokio_util::{sync::CancellationToken, task::TaskTracker};

use super::{
    AcceptLoopOptions,
    BackoffConfig,
    MockAcceptListener,
    PreambleHooks,
    SupervisorLifecycle,
    WireframeServer,
    accept_loop,
    test_support::preparation_factory,
};
use crate::{
    app::WireframeApp,
    server::{
        ServerError,
        test_util::{bind_server, factory, free_listener},
    },
};

#[rstest]
#[tokio::test]
async fn test_run_with_immediate_shutdown(
    factory: impl Fn() -> WireframeApp + Send + Sync + Clone + 'static,
    free_listener: std::io::Result<std::net::TcpListener>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let server = bind_server(factory, free_listener?)?;
    let shutdown_future = async { tokio::time::sleep(Duration::from_millis(10)).await };
    timeout(
        Duration::from_secs(1),
        server.run_with_shutdown(shutdown_future),
    )
    .await
    .map_err(|_| "server did not finish in time")??;
    Ok(())
}

#[rstest]
#[tokio::test]
async fn test_server_graceful_shutdown_with_ctrl_c_simulation(
    factory: impl Fn() -> WireframeApp + Send + Sync + Clone + 'static,
    free_listener: std::io::Result<std::net::TcpListener>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let server = bind_server(factory, free_listener?)?;
    let (tx, rx) = oneshot::channel();
    let handle = tokio::spawn(async move {
        server
            .run_with_shutdown(async {
                drop(rx.await);
            })
            .await
            .expect("server run failed");
    });
    let _shutdown_sent = tx.send(());
    handle.await.expect("server join error");
    Ok(())
}

#[rstest]
#[tokio::test]
async fn test_graceful_shutdown_releases_listener(
    factory: impl Fn() -> WireframeApp + Send + Sync + Clone + 'static,
    free_listener: std::io::Result<std::net::TcpListener>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let listener = free_listener?;
    let addr = listener.local_addr()?;
    let server = bind_server(factory, listener)?;
    let (ready_tx, ready_rx) = oneshot::channel();
    let (shutdown_tx, shutdown_rx) = oneshot::channel();
    let handle = tokio::spawn(async move {
        server
            .ready_signal(ready_tx)
            .run_with_shutdown(async {
                drop(shutdown_rx.await);
            })
            .await
    });

    timeout(Duration::from_secs(1), ready_rx)
        .await
        .expect("server did not reach readiness")
        .expect("server dropped readiness sender");
    shutdown_tx
        .send(())
        .expect("server shutdown receiver was dropped");
    assert!(handle.await?.is_ok(), "graceful shutdown failed");

    let release_result = timeout(Duration::from_secs(1), async {
        loop {
            match TcpStream::connect(addr).await {
                Ok(stream) => drop(stream),
                Err(error) if error.kind() == io::ErrorKind::ConnectionRefused => return Ok(()),
                Err(error) => return Err(error),
            }
            sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("server listener remained bound after graceful shutdown");
    release_result?;
    Ok(())
}

#[rstest]
#[tokio::test]
async fn test_multiple_worker_creation(
    free_listener: std::io::Result<std::net::TcpListener>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let call_count = Arc::new(AtomicUsize::new(0));
    let clone = call_count.clone();
    let factory = move || -> WireframeApp {
        clone.fetch_add(1, Ordering::SeqCst);
        WireframeApp::default()
    };
    let server = WireframeServer::new(factory)
        .workers(3)
        .bind_existing_listener(free_listener?)
        .expect("Failed to bind");
    let shutdown_future = async { tokio::time::sleep(Duration::from_millis(10)).await };
    timeout(
        Duration::from_secs(1),
        server.run_with_shutdown(shutdown_future),
    )
    .await
    .map_err(|_| "server did not finish in time")??;
    assert_eq!(
        call_count.load(Ordering::SeqCst),
        1,
        "call_count.load(Ordering::SeqCst) should equal 1"
    );
    Ok(())
}

/// Startup factory failures prevent readiness and worker installation.
#[rstest]
#[tokio::test]
async fn factory_failure_returns_before_readiness(
    free_listener: std::io::Result<std::net::TcpListener>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let factory = || -> Result<WireframeApp, io::Error> {
        Err(io::Error::other("application construction failed"))
    };
    let server = WireframeServer::new(factory)
        .workers(3)
        .bind_existing_listener(free_listener?)?;
    let (ready_tx, ready_rx) = oneshot::channel();

    let result = server
        .ready_signal(ready_tx)
        .run_with_shutdown(std::future::pending())
        .await;

    assert!(
        matches!(result, Err(ServerError::FactoryBuild(error)) if error.to_string() == "application construction failed"),
        "assertion failed: matches!(result, Err(ServerError::FactoryBuild(error)) if \
         error.to_string() == \"application construction failed\")"
    );
    assert!(
        ready_rx.await.is_err(),
        "assertion failed: ready_rx.await.is_err()"
    );
    Ok(())
}

#[rstest]
#[tokio::test]
async fn readiness_waits_for_application_preparation(
    free_listener: std::io::Result<std::net::TcpListener>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let (entered, barrier, factory) = preparation_factory();
    let server = WireframeServer::new(factory).bind_existing_listener(free_listener?)?;
    let (ready_tx, mut ready_rx) = oneshot::channel();
    let (shutdown_tx, shutdown_rx) = oneshot::channel();
    let server_task = tokio::spawn(async move {
        server
            .ready_signal(ready_tx)
            .run_with_shutdown(async {
                drop(shutdown_rx.await);
            })
            .await
    });

    timeout(Duration::from_secs(1), entered.notified())
        .await
        .expect("application preparation did not start");
    assert!(
        timeout(Duration::from_millis(20), &mut ready_rx)
            .await
            .is_err(),
        "assertion failed: timeout(Duration::from_millis(20), &mut ready_rx) .await .is_err()"
    );

    barrier.wait().await;
    timeout(Duration::from_secs(1), &mut ready_rx)
        .await
        .expect("server did not signal readiness after preparation")
        .expect("server dropped readiness sender after preparation");
    shutdown_tx
        .send(())
        .expect("server shutdown receiver was dropped");
    server_task.await??;
    Ok(())
}

#[rstest]
#[tokio::test]
async fn test_accept_loop_shutdown_signal(
    factory: impl Fn() -> WireframeApp + Send + Sync + Clone + 'static,
) {
    let token = CancellationToken::new();
    let tracker = TaskTracker::new();
    let listener = Arc::new(
        TcpListener::bind("127.0.0.1:0")
            .await
            .expect("failed to bind test listener"),
    );
    let app = Arc::new(factory().prepare().await.expect("prepare app"));

    tracker.spawn(accept_loop(
        listener,
        AcceptLoopOptions::<()> {
            app,
            preamble: PreambleHooks::default(),
            shutdown: token.clone(),
            tracker: tracker.clone(),
            backoff: BackoffConfig::default(),
            lifecycle: SupervisorLifecycle::new(),
        },
    ));

    token.cancel();
    tracker.close();

    let result = timeout(Duration::from_millis(100), tracker.wait()).await;
    assert!(result.is_ok(), "assertion failed: result.is_ok()");
}

/// Creates a mock listener that fails with exponential backoff tracking.
fn setup_backoff_mock_listener(
    calls: &Arc<Mutex<Vec<Instant>>>,
    num_calls: usize,
) -> MockAcceptListener {
    let mut listener = MockAcceptListener::new();
    let shared_call_log = Arc::clone(calls);
    listener
        .expect_accept()
        .returning(move || {
            let call_log = Arc::clone(&shared_call_log);
            Box::pin(async move {
                call_log
                    .lock()
                    .map_err(|_| io::Error::other("mock call log mutex poisoned"))?
                    .push(Instant::now());
                Err(io::Error::other("mock error"))
            })
        })
        .times(num_calls);
    listener
        .expect_local_addr()
        .returning(|| Ok(SocketAddr::from(([127, 0, 0, 1], 0))))
        .times(num_calls);
    listener
}

/// Validates that recorded call intervals match expected backoff delays.
fn assert_backoff_intervals(
    calls: &[Instant],
    expected: &[Duration],
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let intervals: Vec<_> = calls
        .windows(2)
        .map(|window| {
            let a = window
                .first()
                .ok_or_else(|| "window has first element".to_owned())?;
            let b = window
                .get(1)
                .ok_or_else(|| "window has second element".to_owned())?;
            b.checked_duration_since(*a)
                .ok_or_else(|| "instants should be monotonically increasing".to_owned())
        })
        .collect::<Result<_, _>>()?;

    if intervals.len() != expected.len() {
        return Err(format!(
            "interval count mismatch: got {}, expected {}",
            intervals.len(),
            expected.len()
        )
        .into());
    }

    for (interval, expected_delay) in intervals.into_iter().zip(expected.iter()) {
        if interval != *expected_delay {
            return Err(format!(
                "interval mismatch: got {interval:?}, expected {expected_delay:?}"
            )
            .into());
        }
    }

    Ok(())
}

#[rstest]
#[tokio::test(start_paused = true)]
async fn test_accept_loop_exponential_backoff_async(
    factory: impl Fn() -> WireframeApp + Send + Sync + Clone + 'static,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let calls = Arc::new(Mutex::new(Vec::new()));
    let listener = Arc::new(setup_backoff_mock_listener(&calls, 4));
    let token = CancellationToken::new();
    let tracker = TaskTracker::new();
    let backoff = BackoffConfig {
        initial_delay: Duration::from_millis(5),
        max_delay: Duration::from_millis(20),
    };
    let app = Arc::new(factory().prepare().await.expect("prepare app"));

    tracker.spawn(accept_loop(
        listener,
        AcceptLoopOptions::<()> {
            app,
            preamble: PreambleHooks::default(),
            shutdown: token.clone(),
            tracker: tracker.clone(),
            backoff,
            lifecycle: SupervisorLifecycle::new(),
        },
    ));

    yield_now().await;

    let first_call = {
        let recorded_calls = calls.lock().expect("lock");
        assert_eq!(recorded_calls.len(), 1, "calls.len() should equal 1");
        recorded_calls
            .first()
            .copied()
            .expect("call record missing")
    };

    for ms in [5, 10, 20] {
        advance(Duration::from_millis(ms)).await;
        yield_now().await;
    }

    token.cancel();
    advance(Duration::from_millis(20)).await;
    yield_now().await;
    tracker.close();
    tracker.wait().await;

    let recorded_calls = calls.lock().expect("lock");
    assert_eq!(recorded_calls.len(), 4, "calls.len() should equal 4");
    let first = recorded_calls
        .first()
        .copied()
        .expect("at least one call logged");
    assert_eq!(first, first_call, "first should equal first_call");
    let expected = [
        Duration::from_millis(5),
        Duration::from_millis(10),
        Duration::from_millis(20),
    ];
    assert_backoff_intervals(&recorded_calls, &expected)?;
    Ok(())
}