liminal-server 0.24.1

Standalone server for the liminal messaging bus
Documentation
//! The options every socket the server accepts carries before it is handed
//! onward.

use std::net::{SocketAddr, TcpStream};
use std::time::Duration;

/// How long an accepted connection stays silent before the kernel probes its
/// peer. Probing is the kernel's, sent only on a silent connection: one empty
/// segment per idle connection per half minute, and nothing of ours wakes.
pub const KEEPALIVE_IDLE: Duration = Duration::from_secs(30);
/// The gap between unanswered probes.
pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(10);
/// Unanswered probes before the kernel ends the connection: five ride out a
/// brief network drop, and a peer that is gone is found within 80 seconds
/// (30 + 5 x 10), when the connection's close releases any agent seat it
/// held (`agents::runtime::connection_closed`).
pub const KEEPALIVE_RETRIES: u32 = 5;

/// Prepares a freshly accepted socket before it is handed onward.
///
/// Every socket the server ACCEPTS carries `TCP_NODELAY`, the accept-side twin
/// of the client sockets in liminal-sdk, which have always set it. Nagle holds a
/// frame's trailing partial segment until the peer's delayed ACK arrives, so
/// without this any server-initiated write spanning more than one segment stalls
/// ~40ms — and server push is a core protocol primitive, not an edge case.
///
/// Every accept loop in the server routes its socket through this one function
/// (main wire protocol, sibling WebSocket, health endpoint), so the option is
/// pinned in one place rather than re-derived per listener. The shed paths are
/// deliberately NOT prepared: those sockets are dropped unwritten.
///
/// A failure here degrades latency but does not break the connection, so the
/// socket is still served — the accept loops treat per-connection setup trouble
/// as loggable, never as a reason to drop a peer or kill the loop.
pub fn prepare_accepted_socket(stream: &TcpStream, peer_addr: Option<SocketAddr>) {
    if let Err(error) = stream.set_nodelay(true) {
        tracing::warn!(
            ?peer_addr,
            %error,
            "failed to set TCP_NODELAY on accepted socket"
        );
    }
    let keepalive = socket2::TcpKeepalive::new()
        .with_time(KEEPALIVE_IDLE)
        .with_interval(KEEPALIVE_INTERVAL)
        .with_retries(KEEPALIVE_RETRIES);
    if let Err(error) = socket2::SockRef::from(stream).set_tcp_keepalive(&keepalive) {
        tracing::warn!(
            ?peer_addr,
            %error,
            "failed to set TCP keepalive on accepted socket; a vanished peer holds its seat \
             until the connection is otherwise closed"
        );
    }
}

#[cfg(test)]
#[path = "accepted_socket_tests.rs"]
mod tests;