wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Shutdown suppression for installed output sources.
//!
//! The observation loop must stop polling a streaming response or a
//! multi-packet channel once shutdown begins. `ConnectionActor` expresses that
//! rule in one place: [`ActiveOutput::available_output`] returns
//! [`AvailableOutput::None`] whenever the actor state reports shutdown, even
//! though the source itself stays installed for the cleanup path.
//!
//! The gate alone would not prove the wiring: `compute_availability` feeds
//! `next_event_inner`, the biased `tokio::select!` that decides which source is
//! polled. A lost shutdown transition there leaves the multi-packet and
//! response arms armed, which is the hang issue #622 reports. These tests
//! therefore assert the gate in both polarities, and separately drive the real
//! observation loop with a source that is ready to poll, so a wrongly armed arm
//! returns its own event instead of the shutdown one.

use rstest::{fixture, rstest};
use tokio::time::{Duration, timeout};
use tokio_util::sync::CancellationToken;

use super::{
    super::{
        ConnectionActor,
        event::{Event, EventWatch},
        output::AvailableOutput,
    },
    installed_output::InstalledOutput,
};
use crate::{
    NoProtocolError,
    push::{PushConfigError, PushQueues},
};

/// Upper bound on one observation-loop wait.
///
/// Shutdown is the only source that may wake the shutdown cases, so a healthy
/// loop returns at once. The bound exists so a regression fails the test rather
/// than hanging the test binary, as the original mutant did.
const OBSERVATION_TIMEOUT: Duration = Duration::from_secs(5);

/// Build an actor with open, empty push lanes and no active output.
///
/// The gate cases keep the lanes, because the gate reports them independently
/// of shutdown and must keep doing so. The observation case closes them, since
/// a ready lane would outrank the output arm it is testing. Building the actor
/// through the public constructor keeps the setup identical to the production
/// path that computes availability.
#[fixture]
fn availability_actor() -> Result<ConnectionActor<u8, NoProtocolError>, PushConfigError> {
    let (queues, handle) = PushQueues::<u8>::builder()
        .high_capacity(1)
        .low_capacity(1)
        .unlimited()
        .build()?;
    Ok(ConnectionActor::new(
        queues,
        handle,
        None,
        CancellationToken::new(),
    ))
}

/// Observe shutdown while ignoring the peer, as the standalone drive does.
const fn active_watch() -> EventWatch {
    EventWatch {
        peer: false,
        shutdown: true,
    }
}

/// Close both push lanes so the observation case isolates the output arm.
///
/// Push lanes outrank output in the biased select, and the fixture's push
/// handle keeps them open, so leaving them in place would let the high lane's
/// `recv` return `None` first and mask the output arm under test.
fn drop_queues(actor: &mut ConnectionActor<u8, NoProtocolError>) {
    actor.high_rx = None;
    actor.low_rx = None;
}

/// Shutdown suppresses the installed output while retaining it for cleanup.
#[rstest]
#[case::response(InstalledOutput::Response)]
#[case::multi_packet(InstalledOutput::MultiPacket)]
fn shutdown_suppresses_the_installed_output(
    #[case] installed: InstalledOutput,
    availability_actor: Result<ConnectionActor<u8, NoProtocolError>, PushConfigError>,
) {
    let mut actor = availability_actor.expect("actor should build");
    let mut keep_alive = Vec::new();
    installed
        .install_pending(&mut actor, &mut keep_alive)
        .expect("output should install");
    let mut state = installed.actor_state();

    assert!(
        actor.high_rx.is_some(),
        "the high-priority lane must stay open before shutdown"
    );
    assert!(
        actor.low_rx.is_some(),
        "the low-priority lane must stay open before shutdown"
    );
    assert!(
        actor
            .active_output
            .available_output(state.is_shutting_down())
            == installed.available(),
        "the installed output must be pollable before shutdown"
    );

    state.start_shutdown();

    assert!(
        installed.is_retained(&actor),
        "shutdown must not clear the installed output"
    );
    assert!(
        matches!(
            actor
                .active_output
                .available_output(state.is_shutting_down()),
            AvailableOutput::None
        ),
        "{}",
        installed.suppression_message()
    );
    assert!(
        actor.high_rx.is_some(),
        "the high-priority lane must stay open after shutdown"
    );
    assert!(
        actor.low_rx.is_some(),
        "the low-priority lane must stay open after shutdown"
    );
}

/// A source ready before the loop runs must not satisfy the observation wait.
///
/// This covers the wiring the gate cases cannot. The shutdown arm is guarded by
/// the actor being active, so once shutdown is in force and the push lanes are
/// closed the loop has nothing left to wait on and returns [`Event::Idle`]. A
/// lost `state.is_shutting_down()` would keep the output arm armed and return
/// the ready item instead, which is the hang class issue #622 reports.
#[rstest]
#[case::response(InstalledOutput::Response)]
#[case::multi_packet(InstalledOutput::MultiPacket)]
#[tokio::test]
async fn shutdown_stops_the_loop_observing_a_ready_output(
    #[case] installed: InstalledOutput,
    availability_actor: Result<ConnectionActor<u8, NoProtocolError>, PushConfigError>,
) {
    let mut actor = availability_actor.expect("actor should build");
    let shutdown = actor.shutdown_token();
    installed
        .install_ready(&mut actor)
        .expect("ready output should install");
    drop_queues(&mut actor);

    let mut state = installed.actor_state();
    state.start_shutdown();
    shutdown.cancel();
    assert!(
        installed.is_retained(&actor),
        "shutdown must not clear the installed output before the loop runs"
    );

    let event = timeout(
        OBSERVATION_TIMEOUT,
        actor.next_event_inner(&state, active_watch()),
    )
    .await
    .expect("a suppressed output must not make the loop wait on it");

    assert!(
        matches!(event, Event::Idle),
        "shutdown must leave the loop idle with the ready {installed:?} output; got {event:?}"
    );
}