wabot-feature-socket-controller 0.2.0

Socket.IO controller framework — port of wabot-ts feature/socket-controller, built on socketioxide.
Documentation
//! Per-connection wiring — the part every `#[socket_controller]`
//! shares. Port of `runSocketControllers.ts`.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use socketioxide::extract::{AckSender, Data, SocketRef};
use socketioxide::handler::ConnectHandler;
use socketioxide::SocketIo;
use wabot_core::injection::Container;

use crate::{HandshakeMiddleware, SocketError};

/// One `#[on_socket_event]` method, type-erased.
#[derive(Clone)]
pub struct SocketEventEntry {
    /// The event name a client emits.
    pub event: &'static str,
    pub invoke: SocketEventFn,
}

/// Deserialize + validate + dispatch + ack, all inside the closure the
/// macro emits.
/// The socket is `Option` because a test drives the same closure
/// without a live connection — see `AckSink` for the other half of
/// that. A handler that asked for a `SocketRef` and gets `None`
/// reports it rather than pretending.
pub type SocketEventFn = Arc<
    dyn Fn(
            Container,
            Option<SocketRef>,
            serde_json::Value,
            crate::AckSink,
        ) -> Pin<Box<dyn Future<Output = ()> + Send>>
        + Send
        + Sync,
>;

/// A handshake middleware, built from the connection's container so it
/// can depend on request-scoped things.
#[derive(Clone)]
pub struct HandshakeEntry {
    pub name: &'static str,
    #[allow(clippy::type_complexity)]
    pub build: Arc<dyn Fn(&Container) -> Arc<dyn HandshakeMiddleware> + Send + Sync>,
}

/// The event name that means "the socket just connected" rather than
/// something the client emitted. Matches TS.
pub const CONNECTION_EVENT: &str = "connection";

/// Attach one controller's namespace to `io`.
///
/// Called by the macro-emitted `register_socket_handlers`; call it
/// directly to wire a controller built by hand.
pub fn register_socket_namespace(
    io: &SocketIo,
    parent: Container,
    namespace: String,
    handshake: Vec<HandshakeEntry>,
    events: Vec<SocketEventEntry>,
) {
    tracing::info!(namespace = %namespace, events = events.len(), "config socket namespace");

    // The handshake runs as a socketioxide **connect middleware**, not
    // at the top of the connect handler, and that ordering is load
    // bearing: a middleware runs before the client is told the
    // connection succeeded, whereas anything awaited inside the
    // handler leaves a window where the client has already started
    // emitting and no listener is attached yet. Those events are
    // dropped silently — the first version of this did exactly that,
    // and every event test timed out.
    //
    // So: middleware authenticates and can refuse; the handler then
    // wires listeners with no `await` before them.
    let middleware_namespace = namespace.clone();
    let middleware = move |socket: SocketRef| {
        let parent = parent.clone();
        let handshake = handshake.clone();
        let namespace = middleware_namespace.clone();
        async move {
            // One container per connection, reused by every event on
            // this socket — the socket analogue of the per-request
            // container.
            let container = parent.create_child();
            for entry in &handshake {
                let middleware = (entry.build)(&container);
                if let Err(error) = middleware.handle(&socket, &container).await {
                    tracing::warn!(
                        namespace = %namespace,
                        middleware = entry.name,
                        %error,
                        "handshake refused"
                    );
                    // Returning Err refuses the connection: socketioxide
                    // sends `connect_error` and the namespace is never
                    // joined, so no handler can run for a socket that
                    // failed to authenticate.
                    return Err(error);
                }
            }
            socket.extensions.insert(container);
            Ok::<(), SocketError>(())
        }
    };

    // **Synchronous** on purpose. An async connect handler is only
    // polled when the runtime gets to it, which can be after the
    // client — already told the connection succeeded — has emitted its
    // first event; that packet finds no listener and is dropped. This
    // registers every listener inline, before socketioxide processes
    // another packet, and defers only the `connection` handler.
    let handler = move |socket: SocketRef| {
        // The middleware put it there; a socket that reaches the
        // handler has passed the handshake.
        let Some(container) = socket.extensions.get::<Container>() else {
            tracing::error!("socket reached the handler without a connection container");
            socket.disconnect().ok();
            return;
        };

        let mut on_connection: Option<SocketEventEntry> = None;
        for entry in events.clone() {
            if entry.event == CONNECTION_EVENT {
                on_connection = Some(entry);
                continue;
            }

            let container = container.clone();
            let invoke = entry.invoke.clone();
            socket.on(
                entry.event,
                move |socket: SocketRef, Data::<serde_json::Value>(payload), ack: AckSender| {
                    let container = container.clone();
                    let invoke = invoke.clone();
                    async move {
                        (invoke)(
                            container,
                            Some(socket),
                            payload,
                            crate::AckSink::Client(ack),
                        )
                        .await;
                    }
                },
            );
        }

        // Every listener is attached by the time this runs, so a
        // `connection` handler that emits can't beat them into place.
        //
        // No ack: a connection isn't a client emit, so there is no
        // callback to answer. Whatever the handler returns is dropped,
        // which the macro's docs say plainly.
        if let Some(entry) = on_connection {
            let socket = socket.clone();
            tokio::spawn(async move {
                (entry.invoke)(
                    container,
                    Some(socket),
                    serde_json::Value::Null,
                    crate::AckSink::None,
                )
                .await;
            });
        }
    };

    io.ns(namespace, handler.with(middleware));
}

/// Deserialize + validate an event payload, reporting a bad one the
/// way the client can act on.
///
/// Shared by every generated handler so one place decides what
/// "invalid" means.
pub fn parse_payload<T>(payload: serde_json::Value) -> Result<T, SocketError>
where
    T: serde::de::DeserializeOwned + wabot_core::validation::Validate,
{
    let value: T = serde_json::from_value(payload)
        .map_err(|error| SocketError::Validation(error.to_string()))?;
    value
        .validate()
        .map_err(|error| SocketError::Validation(error.to_string()))?;
    Ok(value)
}