wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Event observation for the connection actor.
//!
//! Every observation mode — the standalone drive, the prepared connection's
//! response drive, and the drain that follows a peer close — waits on the one
//! biased `tokio::select!` loop defined here. Keeping the loop apart from the
//! response driving that consumes its events leaves the priority ordering in a
//! single place for a refactor to preserve.

use super::{
    ConnectionActor,
    event::{Event, EventWatch},
    output::{AvailableOutput, EventAvailability},
    polling::EventSources,
    state::ActorState,
};
use crate::{app::Packet, correlation::CorrelatableFrame, push::FrameLike};

impl<F, E, P> ConnectionActor<F, E, P>
where
    F: FrameLike + CorrelatableFrame + Packet,
    E: std::fmt::Debug,
    P: FrameLike,
{
    /// Compute which event sources are currently available for polling.
    const fn compute_availability(&self, state: &ActorState) -> EventAvailability {
        EventAvailability {
            high: self.high_rx.is_some(),
            low: self.low_rx.is_some(),
            output: self
                .active_output
                .available_output(state.is_shutting_down()),
        }
    }

    /// Await the next ready event using biased priority ordering.
    ///
    /// Shutdown is observed first, followed by high-priority pushes, then
    /// low-priority pushes, multi-packet channels, and finally the response
    /// stream. This matches the design documentation. The final `else` branch
    /// prevents `tokio::select!` from panicking if all guards are false.
    ///
    /// The `strict_priority_order` and `shutdown_signal_precedence` tests
    /// assert that this ordering is preserved across refactors.
    pub(super) async fn next_event(&mut self, state: &ActorState) -> Event<F, E, P> {
        self.next_event_inner(
            state,
            EventWatch {
                peer: false,
                shutdown: true,
            },
        )
        .await
    }

    /// Whether peer-close observation applies to the current actor state.
    const fn should_watch_peer(watch: EventWatch, state: &ActorState) -> bool {
        watch.peer && state.is_active()
    }

    /// Shared select loop for every observation mode.
    pub(super) async fn next_event_inner(
        &mut self,
        state: &ActorState,
        watch: EventWatch,
    ) -> Event<F, E, P> {
        let avail = self.compute_availability(state);
        let can_poll_multi_packet = avail.output == AvailableOutput::MultiPacket;
        let can_poll_response = avail.output == AvailableOutput::Response;
        let EventSources {
            high,
            low,
            multi_packet,
            response,
            shutdown,
            peer_closed,
        } = self.event_sources();

        tokio::select! {
            biased;

            () = Self::wait_shutdown(shutdown), if watch.shutdown && state.is_active() => {
                Event::Shutdown
            }
            () = Self::wait_peer_closed(peer_closed), if Self::should_watch_peer(watch, state) => {
                Event::PeerClosed
            }
            res = Self::poll_queue(high), if avail.high => Event::High(res),
            res = Self::poll_queue(low), if avail.low => Event::Low(res),
            res = Self::poll_queue(multi_packet), if can_poll_multi_packet => Event::MultiPacket(res),
            res = Self::poll_response(response), if can_poll_response => Event::Response(res),
            else => Event::Idle,
        }
    }
}

#[cfg(all(test, not(loom)))]
mod tests {
    //! Availability as `compute_availability` computes it, in both states.
    //!
    //! This sits beside the private method rather than under
    //! `connection::tests`, because the method is private to this module and
    //! its visibility is deliberately unchanged. The gate cases in
    //! `connection::tests::availability` prove the shutdown rule; these prove
    //! that the loop's own computation reports the queue lanes and the output
    //! source from the actor it was given, rather than a constant.

    use rstest::rstest;
    use tokio_util::sync::CancellationToken;

    use super::super::{
        ConnectionActor,
        output::{AvailableOutput, EventAvailability},
        state::ActorState,
        tests::installed_output::InstalledOutput,
    };
    use crate::{NoProtocolError, push::PushQueues};

    /// Assert the queue flags the gate is expected to compute.
    ///
    /// Taking booleans rather than the actor keeps this helper infallible, so
    /// every fallible setup call stays in a test body where the repository's
    /// `expect_used` allowance applies.
    fn assert_lanes(availability: EventAvailability, high: bool, low: bool) {
        assert_eq!(
            availability.high, high,
            "the high-priority lane flag must match the actor's lane"
        );
        assert_eq!(
            availability.low, low,
            "the low-priority lane flag must match the actor's lane"
        );
    }

    /// An installed source is pollable while active and suppressed on shutdown.
    #[rstest]
    #[case::response(InstalledOutput::Response)]
    #[case::multi_packet(InstalledOutput::MultiPacket)]
    #[test]
    fn compute_availability_reports_and_suppresses_the_installed_output(
        #[case] installed: InstalledOutput,
    ) {
        let (queues, handle) = PushQueues::<u8>::builder()
            .high_capacity(1)
            .low_capacity(1)
            .unlimited()
            .build()
            .expect("push queues should build");
        let mut actor: ConnectionActor<u8, NoProtocolError> =
            ConnectionActor::new(queues, handle, None, CancellationToken::new());
        let mut keep_alive = Vec::new();
        installed
            .install_pending(&mut actor, &mut keep_alive)
            .expect("output should install");
        let mut state = installed.actor_state();

        let active = actor.compute_availability(&state);
        assert_lanes(active, true, true);
        assert!(
            active.output == installed.available(),
            "the installed {installed:?} output must be pollable while active"
        );

        state.start_shutdown();
        let shutting_down = actor.compute_availability(&state);
        assert_lanes(shutting_down, true, true);
        assert!(
            matches!(shutting_down.output, AvailableOutput::None),
            "shutdown must suppress the installed {installed:?} output"
        );
        assert!(
            installed.is_retained(&actor),
            "shutdown must retain the installed {installed:?} output for cleanup"
        );
    }

    /// A closed lane is reported unpollable, so the flags are not a constant.
    #[test]
    fn compute_availability_reports_a_closed_lane() {
        let (queues, handle) = PushQueues::<u8>::builder()
            .high_capacity(1)
            .low_capacity(1)
            .unlimited()
            .build()
            .expect("push queues should build");
        let mut actor: ConnectionActor<u8, NoProtocolError> =
            ConnectionActor::new(queues, handle, None, CancellationToken::new());
        actor.low_rx = None;
        let state = ActorState::new(false, false);

        let availability = actor.compute_availability(&state);
        assert_lanes(availability, true, false);
        assert!(
            matches!(availability.output, AvailableOutput::None),
            "no output source is installed"
        );
    }
}