wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Accept-loop utilities for server runtime.

use std::{fmt, io, net::SocketAddr, sync::Arc};

use async_trait::async_trait;
use log::warn;
use tokio::{
    net::{TcpListener, TcpStream},
    select,
    time::{Duration, sleep},
};
use tokio_util::{sync::CancellationToken, task::TaskTracker};

use super::{SupervisorLifecycle, backoff::BackoffConfig};
use crate::{
    app::{Envelope, Packet, PreparedApp},
    codec::{FrameCodec, LengthDelimitedFrameCodec},
    connection::ActiveConnection,
    frame::FrameMetadata,
    message::{DecodeWith, EncodeWith},
    metrics::inc_server_accept_loop_exit,
    preamble::Preamble,
    serializer::{BincodeSerializer, Serializer},
    server::{
        PreambleFailure,
        PreambleHandler,
        connection_spawner::{ConnectionTask, spawn_connection_task},
    },
};

/// Abstraction for sources of incoming connections consumed by the accept loop.
///
/// Implementations must be cancellation-safe: dropping a pending `accept()`
/// future must not leak resources.
#[async_trait]
#[cfg_attr(test, mockall::automock)]
pub(in crate::server) trait AcceptListener: Send + Sync {
    /// Await one incoming stream and its peer address.
    async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)>;
    /// Return the listener address for diagnostics after an accept failure.
    fn local_addr(&self) -> io::Result<SocketAddr>;
}

#[async_trait]
impl AcceptListener for TcpListener {
    async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { Self::accept(self).await }

    fn local_addr(&self) -> io::Result<SocketAddr> { Self::local_addr(self) }
}

/// Inputs shared by one accept-loop worker.
pub(in crate::server) struct AcceptLoopOptions<
    T,
    Ser = BincodeSerializer,
    Ctx = (),
    E = Envelope,
    Codec = LengthDelimitedFrameCodec,
> where
    Ser: Serializer + Send + Sync,
    Ctx: Send + 'static,
    E: Packet,
    Codec: FrameCodec,
{
    /// Prepared root shared by each connection accepted by this worker.
    pub app: Arc<PreparedApp<Ser, Ctx, E, Codec>>,
    /// Preamble callbacks and timeout applied to each accepted stream.
    pub preamble: PreambleHooks<T>,
    /// Shared cancellation signal for every worker loop.
    pub shutdown: CancellationToken,
    /// Tracker retaining spawned connection tasks for graceful shutdown.
    pub tracker: TaskTracker,
    /// Normalized retry policy for transient accept failures.
    pub backoff: BackoffConfig,
    /// Shared lifecycle state used to classify worker termination.
    pub lifecycle: SupervisorLifecycle,
}

/// Borrowed worker inputs used for one `select!` iteration.
struct AcceptHandles<'a, T, Ser, Ctx, E, Codec>
where
    Ser: Serializer + Send + Sync,
    Ctx: Send + 'static,
    E: Packet,
    Codec: FrameCodec,
{
    /// Immutable application root cloned into every connection task.
    app: &'a Arc<PreparedApp<Ser, Ctx, E, Codec>>,
    /// Borrowed handshake callbacks; ownership remains with the accept loop.
    preamble: &'a PreambleHooks<T>,
    /// Borrowed cancellation token observed by `select!`.
    shutdown: &'a CancellationToken,
    /// Borrowed task tracker used when spawning connection work.
    tracker: &'a TaskTracker,
    /// Borrowed immutable retry policy.
    backoff: &'a BackoffConfig,
}

#[derive(Default)]
/// Preamble callbacks copied into each connection task.
pub(in crate::server) struct PreambleHooks<T> {
    /// Callback invoked after a valid preamble has been read.
    pub on_success: Option<PreambleHandler<T>>,
    /// Callback invoked when the preamble is invalid or times out.
    pub on_failure: Option<PreambleFailure>,
    /// Optional upper bound for the handshake read.
    pub timeout: Option<Duration>,
}

impl<T> Clone for PreambleHooks<T> {
    fn clone(&self) -> Self {
        Self {
            on_success: self.on_success.clone(),
            on_failure: self.on_failure.clone(),
            timeout: self.timeout,
        }
    }
}

impl<T> fmt::Debug for PreambleHooks<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PreambleHooks")
            .field(
                "on_success",
                &self.on_success.as_ref().map(|_| "Some(<handler>)"),
            )
            .field(
                "on_failure",
                &self.on_failure.as_ref().map(|_| "Some(<failure>)"),
            )
            .field("timeout", &self.timeout)
            .finish()
    }
}

/// Accepts incoming connections and spawns handler tasks.
///
/// The loop accepts connections from `listener`, clones the shared prepared
/// application root for each one, and spawns a task to handle
/// the connection. Failures to accept a connection trigger an exponential
/// back-off governed by `backoff_config`. The loop terminates when `shutdown`
/// is cancelled, and all spawned tasks are tracked by `tracker` for graceful
/// shutdown.
///
/// # Parameters
///
/// - `listener`: Source of incoming TCP connections.
/// - `app`: Immutable [`PreparedApp`] shared by every connection.
/// - `preamble`: Preamble handlers and timeout configuration.
/// - `shutdown`: Signal used to stop the accept loop.
/// - `tracker`: Task tracker used for graceful shutdown.
/// - `backoff_config`: Controls exponential back-off behaviour.
///
/// # Type Parameters
///
/// - `T`: Preamble type for connection handshaking.
/// - `L`: Listener type implementing [`AcceptListener`].
///
/// # Examples
///
/// ```plaintext
/// use std::sync::Arc;
///
/// use tokio_util::{sync::CancellationToken, task::TaskTracker};
/// use wireframe::{
///     app::WireframeApp,
///     // server::runtime::{AcceptListener, BackoffConfig, PreambleHooks, accept_loop},
/// };
///
/// async fn run<L: AcceptListener + Send + Sync + 'static>(listener: Arc<L>) {
///     let tracker = TaskTracker::new();
///     let token = CancellationToken::new();
///     let app = Arc::new(WireframeApp::default().prepare().await?);
///     accept_loop(
///         listener,
///         AcceptLoopOptions::<()> {
///             app,
///             preamble: PreambleHooks::default(),
///             shutdown: token,
///             tracker,
///             backoff: BackoffConfig::default(),
///         },
///     )
///     .await;
/// }
/// ```
pub(in crate::server) async fn accept_loop<T, L, Ser, Ctx, E, Codec>(
    listener: Arc<L>,
    options: AcceptLoopOptions<T, Ser, Ctx, E, Codec>,
) where
    T: Preamble,
    L: AcceptListener + Send + Sync + 'static,
    Ser: Serializer + FrameMetadata<Frame = Envelope> + Send + Sync + 'static,
    Ctx: Send + 'static,
    E: Packet + 'static,
    Codec: FrameCodec,
    Envelope: DecodeWith<Ser> + EncodeWith<Ser>,
{
    let AcceptLoopOptions {
        app,
        preamble,
        shutdown,
        tracker,
        backoff: backoff_config,
        lifecycle,
    } = options;
    let backoff = normalized_backoff(backoff_config);
    let mut delay = backoff.initial_delay;
    let handles = AcceptHandles {
        app: &app,
        preamble: &preamble,
        shutdown: &shutdown,
        tracker: &tracker,
        backoff: &backoff,
    };
    while let Some(next_delay) = accept_iteration(&listener, &handles, delay).await {
        delay = next_delay;
    }
    record_accept_loop_exit(&shutdown, &lifecycle);
}

/// Normalize retry delays and assert the backoff safety invariants.
fn normalized_backoff(config: BackoffConfig) -> BackoffConfig {
    let normalized = config.normalized();
    debug_assert!(
        normalized.initial_delay <= normalized.max_delay,
        "BackoffConfig invariant violated: initial_delay > max_delay"
    );
    debug_assert!(
        normalized.initial_delay >= Duration::from_millis(1),
        "BackoffConfig invariant violated: initial_delay < 1ms"
    );
    normalized
}

/// Record cancellation only when the worker actually exited because of it.
fn record_accept_loop_exit(shutdown: &CancellationToken, lifecycle: &SupervisorLifecycle) {
    if shutdown.is_cancelled() {
        let reason = lifecycle.cancellation_reason();
        inc_server_accept_loop_exit(reason);
        tracing::info!(
            event = "server_accept_loop_exited",
            reason = reason.label(),
            "server_accept_loop_exited",
        );
    }
}

/// Select between shutdown and one accept attempt, returning the next delay.
async fn accept_iteration<T, L, Ser, Ctx, E, Codec>(
    listener: &Arc<L>,
    handles: &AcceptHandles<'_, T, Ser, Ctx, E, Codec>,
    delay: Duration,
) -> Option<Duration>
where
    T: Preamble,
    L: AcceptListener + Send + Sync + 'static,
    Ser: Serializer + FrameMetadata<Frame = Envelope> + Send + Sync + 'static,
    Ctx: Send + 'static,
    E: Packet + 'static,
    Codec: FrameCodec,
    Envelope: DecodeWith<Ser> + EncodeWith<Ser>,
{
    select! {
        biased;

        () = handles.shutdown.cancelled() => None,
        res = listener.accept() => Some(match res {
            Ok((stream, _)) => {
                // Register the connection immediately after a successful
                // accept, before the task exists. The guard is moved into the
                // spawned future and released when that future ends.
                let task = ConnectionTask {
                    stream,
                    app: Arc::clone(handles.app),
                    hooks: handles.preamble.clone(),
                    connection: ActiveConnection::new(),
                    shutdown: handles.shutdown.clone(),
                };
                spawn_connection_task(task, handles.tracker);
                handles.backoff.initial_delay
            }
            Err(e) => {
                let local_addr = listener.local_addr().ok();
                warn!("accept error: error={e:?}, local_addr={local_addr:?}");
                sleep(delay).await;
                (delay * 2).min(handles.backoff.max_delay)
            }
        }),
    }
}