wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Inbound connection handling and route preparation utilities.
//!
//! Everything between an accepted socket and a dispatched envelope lives here.
//! A prepared route calls [`process_connection`] with a
//! [`ConnectionProcessingContext`], which carries the immutable application
//! inputs for one connection: the middleware chains and streaming handlers,
//! serializer, codec, assembly and fragmentation settings, protocol hooks, read
//! timeout, the server stop token, the push queue template, the
//! [`SessionRegistry`], and the peer address. That function owns setup and
//! teardown around the framed work, which it hands to `core`.
//!
//! [`process_connection`] and its inputs are split across the submodules by
//! responsibility:
//!
//! - `core` prepares framing and the response actor for one connection, then hands the transport to
//!   the streaming dispatch loop.
//! - `actor` builds the response actor: `build_connection_actor` allocates the connection's
//!   identifier and publishes its push handle in one step, and installs the guard that deregisters
//!   that entry when the connection ends.
//! - `frames` holds the buffered inbound frame and the read deadline, and runs the timeout's expiry
//!   command.
//! - `push_service` races queued pushes against the reader, writes the batch the actor hands over,
//!   and drains the lanes once the peer closes.
//! - `push_write` bounds each push write by the stop token and, when the peer can no longer be
//!   observed, by the idle grace.
//! - `dispatch` decodes one frame's payload into an envelope.
//! - `framing` and `peer_watch` prepare the transport halves and observe the peer while a response
//!   is written.
//! - `tests` covers envelope decoding, decode-failure diagnostics, and the unprepared compatibility
//!   path.
//!
//! Streaming request-body delivery is split across the `stream_*` modules.
//! [`stream_dispatch`] owns the connection loop and its state machine,
//! [`stream_frame`] routes one decoded frame into the live slot or the parking
//! queue, and [`stream_slot`], [`stream_active`], and [`stream_parked`] hold the
//! slot, the live exchange, and the messages parked behind it.
//! [`stream_actions`] carries the per-step maintenance actions,
//! [`stream_observed`] the peer-observed replies, and
//! [`stream_admission_watch`] the wait for chunk admission, while
//! [`stream_terminal`] ends a body whose handler is still running.
//! [`stream_handles`] and [`stream_types`] hold the shared handles and value
//! types, and [`stream_diagnostics`] emits the structured events.
//!
//! Route preparation lives here too. The server spawner forwards the accepted
//! socket's peer address through `PreparedApp::handle_connection_with_shutdown`,
//! so the TCP path reaches [`process_connection`] with the peer the preamble
//! hooks were given. The `WireframeApp` compatibility path calls
//! [`process_connection`] directly from `handle_unprepared_connection_result`,
//! which is handed a stream rather than an accepted socket, so it passes `None`
//! and its diagnostics name no peer. Either way the connection's push handle is
//! registered before the first frame is read and removed again when the loop
//! ends.

mod actor;
mod compat;
mod recovery;
// The connection-local runtime drives the same frame loop from outside this
// module, so the processing entry point is crate-visible.
pub(crate) mod core;

pub(crate) mod dispatch;

mod frames;

mod framing;

mod peer_watch;

mod push_service;

mod push_write;

mod stream_actions;

mod stream_active;

mod stream_admission_watch;

mod stream_close;

mod stream_diagnostics;

mod stream_dispatch;

mod stream_frame;

mod stream_handles;

mod stream_observed;

mod stream_parked;

mod stream_pushes;

mod stream_reads;

mod stream_slot;

mod stream_terminal;

#[cfg(test)]
#[cfg(feature = "metrics")]
#[path = "stream_outcome_support.rs"]
mod stream_outcome_support;

mod stream_types;
use std::{collections::HashMap, net::SocketAddr, sync::Arc};

#[cfg(feature = "test-support")]
pub use dispatch::benchmark_decode_envelope;
use log::warn;
use tokio::io::{self, AsyncRead, AsyncWrite};
use tokio_util::sync::CancellationToken;

use super::{
    Route,
    builder::{WireframeApp, push::with_codec_frame_limit},
    connection_runtime::{ConnectionRuntime, InboundConfig},
    envelope::{Envelope, Packet},
    lifecycle::{ConnectionSetup, ConnectionTeardown},
    memory_budgets::MemoryBudgets,
    middleware_types::{Middleware, StreamingHandler},
};
use crate::{
    codec::{FrameCodec, RecoveryConfig, RecoveryPolicyHook},
    frame::FrameMetadata,
    hooks::ProtocolHooks,
    message::{DecodeWith, EncodeWith},
    message_assembler::MessageAssembler,
    middleware::HandlerService,
    push::PushQueuesBuilder,
    serializer::Serializer,
    session::SessionRegistry,
};

/// Maximum consecutive deserialization failures before closing a connection.
pub(super) const MAX_DESER_FAILURES: u32 = 10;

/// Immutable inputs required to drive one connection through prepared routes.
pub(crate) struct ConnectionProcessingContext<'a, S, C, E, F>
where
    S: Serializer + Send + Sync,
    C: Send + 'static,
    E: Packet,
    F: FrameCodec,
{
    /// Immutable middleware chains used to dispatch decoded envelopes.
    pub(crate) routes: &'a HashMap<u32, HandlerService<E>>,
    /// Streaming handlers keyed by message identifier.
    pub(crate) streaming_routes: &'a HashMap<u32, StreamingHandler>,
    /// Serializer shared by all frames on the connection.
    pub(crate) serializer: &'a S,
    /// Codec configuration shared by all frames on the connection.
    pub(crate) codec: &'a F,
    /// Optional hook that creates per-connection state.
    pub(crate) on_connect: Option<&'a ConnectionSetup<C>>,
    /// Optional hook that releases per-connection state after processing.
    pub(crate) on_disconnect: Option<&'a ConnectionTeardown<C>>,
    /// Optional assembly strategy for multi-frame protocol messages.
    pub(crate) message_assembler: Option<&'a dyn MessageAssembler>,
    /// Fragmentation settings used to initialize the frame pipeline.
    pub(crate) fragmentation: Option<crate::fragment::FragmentationConfig>,
    /// Protocol hooks built for this connection from the installed protocol.
    pub(crate) protocol_hooks: ProtocolHooks<F::Frame, ()>,
    /// Optional byte budgets enforced while processing the connection.
    pub(crate) memory_budgets: Option<MemoryBudgets>,
    /// Maximum interval to wait for the next inbound frame.
    pub(crate) read_timeout_ms: u64,
    /// Server shutdown signal; cancelling it stops this connection.
    pub(crate) shutdown: &'a CancellationToken,
    /// Template cloned to build each connection's push queues.
    pub(crate) push_queues: PushQueuesBuilder<F::Frame>,
    /// Registry that each connection registers its push handle with.
    pub(crate) session_registry: Arc<SessionRegistry<F::Frame>>,
    /// Peer address of the accepted socket, when the server reported one.
    pub(crate) peer_addr: Option<SocketAddr>,
    /// Optional hook consulted when a decoder fails on this connection.
    pub(crate) recovery_hook: Option<&'a dyn RecoveryPolicyHook>,
    /// Global recovery settings copied for this connection.
    pub(crate) recovery_config: RecoveryConfig,
}

/// Drive a connection using immutable application inputs and prepared routes.
///
/// One [`ConnectionRuntime`] owns the per-connection state for the whole
/// call. When a teardown hook is registered and setup produced state, teardown
/// runs exactly once after processing stops: whether stream processing
/// completed cleanly, returned an error such as a malformed frame or a failed
/// send, observed shutdown, or panicked inside a handler. A handler panic is
/// finalized and then re-raised so the connection-task supervisor still counts
/// and logs it.
///
/// Setup completes before any framing state is built, and the framed transport
/// is released before teardown is awaited.
pub(crate) async fn process_connection<S, C, E, F, W>(
    stream: W,
    context: ConnectionProcessingContext<'_, S, C, E, F>,
) -> io::Result<()>
where
    S: Serializer + FrameMetadata<Frame = Envelope> + Send + Sync + 'static,
    C: Send + 'static,
    E: Packet,
    F: FrameCodec,
    W: AsyncRead + AsyncWrite + Send + Unpin + 'static,
    Envelope: DecodeWith<S> + EncodeWith<S>,
{
    let ConnectionProcessingContext {
        routes,
        streaming_routes,
        serializer,
        codec,
        on_connect,
        on_disconnect,
        message_assembler,
        fragmentation,
        protocol_hooks,
        memory_budgets,
        recovery_hook,
        recovery_config,
        read_timeout_ms,
        shutdown,
        push_queues,
        session_registry,
        peer_addr,
    } = context;

    let mut runtime = ConnectionRuntime::new(
        stream,
        InboundConfig {
            routes,
            streaming_routes,
            serializer,
            codec,
            message_assembler,
            fragmentation,
            protocol_hooks,
            memory_budgets,
            read_timeout_ms,
            shutdown,
            push_queues,
            session_registry,
            peer_addr,
            recovery_hook,
            recovery_config,
        },
    );

    // Setup runs before any frame is read. A setup panic or a dropped setup
    // future leaves the finalizer `NotSetUp`, so teardown is never invoked
    // without state. `ConnectionRuntime::new` only stages the transport: the
    // codec clone and frame-buffer reservation happen inside `run`, after this
    // await, so a pending setup cannot retain connection memory.
    if let Some(setup) = on_connect {
        runtime.arm_setup(setup().await);
    }

    // Keep the processing result instead of propagating it with `?`. An early
    // return here would skip finalization and leak per-connection resources on
    // decode, protocol, or transport errors.
    let processing_result = runtime.run(on_disconnect).await;

    if let Err(error) = processing_result {
        warn!(
            "connection terminated with error: correlation_id={:?}, error={error:?}",
            None::<u64>
        );
        return Err(error);
    }

    Ok(())
}

/// Construct each route's middleware chain from borrowed builder inputs.
///
/// Middleware is folded in reverse registration order, preserving the first
/// registered middleware as the outermost service layer. This is the
/// compatibility path, which still owns an unprepared builder and therefore
/// clones each route's handler `Arc`.
pub(crate) async fn build_route_chains<E>(
    handlers: &HashMap<u32, Route<E>>,
    middleware: &[Box<dyn Middleware<E>>],
) -> HashMap<u32, HandlerService<E>>
where
    E: Packet,
{
    let owned = handlers
        .iter()
        .map(|(&id, route)| (id, route.clone()))
        .collect();
    build_route_chains_owned(owned, middleware).await
}

/// Construct each route's middleware chain by consuming the builder's routes.
///
/// Preparation owns the builder, so each handler's `Arc` moves into its service
/// instead of being cloned. The middleware list is borrowed for the whole fold,
/// so it stays alive through every transform.
pub(crate) async fn build_route_chains_owned<E>(
    handlers: HashMap<u32, Route<E>>,
    middleware: &[Box<dyn Middleware<E>>],
) -> HashMap<u32, HandlerService<E>>
where
    E: Packet,
{
    let mut routes = HashMap::with_capacity(handlers.len());
    for (id, route) in handlers {
        let service = HandlerService::from_owned_route(id, route);
        routes.insert(id, fold_middleware(service, middleware).await);
    }
    routes
}

/// Apply every middleware layer to one route service.
///
/// Folded in reverse registration order so the first registered middleware is
/// the outermost layer. Shared by both preparation entry points so the ordering
/// cannot drift between the compatibility path and the prepared path.
async fn fold_middleware<E>(
    mut service: HandlerService<E>,
    middleware: &[Box<dyn Middleware<E>>],
) -> HandlerService<E>
where
    E: Packet,
{
    for mw in middleware.iter().rev() {
        service = mw.transform(service).await;
    }
    service
}

#[cfg(test)]
mod tests;