wabot-feature-socket-controller 0.2.0

Socket.IO controller framework — port of wabot-ts feature/socket-controller, built on socketioxide.
Documentation
//! # wabot-feature-socket-controller
//!
//! Socket.IO controllers. Port of
//! `wabot-ts/src/feature/socket-controller`, built on
//! [`socketioxide`].
//!
//! ```ignore
//! #[injectable]
//! struct RoomController { rooms: Arc<Rooms> }
//!
//! #[socket_controller("/rooms", handshake(ApiKeyHandshake))]
//! impl RoomController {
//!     #[on_socket_event("connection")]
//!     async fn on_connect(&self, socket: SocketRef) -> SocketResult<()> { … }
//!
//!     #[on_socket_event("join")]
//!     async fn join(&self, req: JoinRoom, socket: SocketRef) -> SocketResult<Joined> { … }
//! }
//! ```
//!
//! An event handler takes the validated payload and the socket, and
//! whatever it returns is sent back through the client's
//! acknowledgement callback — so a Socket.IO event reads like a
//! request/response, which is how clients actually use them.
//!
//! ## What a connection is
//!
//! Each connection gets a **child container**, built once at handshake
//! and reused for every event on that socket. That is the analogue of
//! the per-request container in REST: a handshake middleware
//! authenticates and registers what it learned, and every later event
//! on that socket resolves it.
//!
//! ```text
//! handshake → middlewares → child container (+ Auth, + whatever) → events
//! ```
//!
//! ## Refusing a connection
//!
//! A [`HandshakeMiddleware`] that returns `Err` rejects the handshake:
//! the client gets a connect error and no events are ever wired.
//! Rejecting at the handshake rather than per event is the point —
//! otherwise every handler would have to re-check, and the one that
//! forgot would be the hole.

use async_trait::async_trait;
use serde::Serialize;
use socketioxide::extract::{AckSender, SocketRef};
use socketioxide::SocketIo;
use thiserror::Error;
use wabot_core::injection::Container;

/// Test harness. Behind `testing` (on by default) — it is small and
/// depends on nothing extra, so gating it further would only make it
/// awkward to reach from a dev-dependency.
#[cfg(feature = "testing")]
#[cfg(feature = "live-harness")]
pub mod live;
pub mod runtime;
pub mod server;
pub mod testing;

pub use runtime::{register_socket_namespace, HandshakeEntry, SocketEventEntry, SocketEventFn};
pub use server::{run_socket_controllers, socket_layer, SocketServerConfig};
#[cfg(feature = "testing")]
pub use testing::{EmittedEvent, SocketHarness};

/// Re-exported so macro emissions and user code share one copy.
pub use socketioxide;

#[derive(Debug, Error)]
pub enum SocketError {
    /// The payload didn't match what the handler expects. Reported to
    /// the client through its ack callback, like a 400.
    #[error("invalid event payload: {0}")]
    Validation(String),
    /// The handshake was refused — the connection never opens.
    #[error("handshake refused: {0}")]
    Unauthorized(String),
    #[error("{0}")]
    Handler(String),
}

pub type SocketResult<T> = Result<T, SocketError>;

impl SocketError {
    /// What goes back through the ack: `{ "error": { "code", "message" } }`.
    ///
    /// A shape rather than a bare string because a client has to
    /// branch on it, and parsing prose is how that goes wrong.
    pub fn to_payload(&self) -> serde_json::Value {
        let code = match self {
            SocketError::Validation(_) => "INVALID_PAYLOAD",
            SocketError::Unauthorized(_) => "UNAUTHORIZED",
            SocketError::Handler(_) => "HANDLER_ERROR",
        };
        serde_json::json!({ "error": { "code": code, "message": self.to_string() } })
    }
}

/// Runs at handshake, before any event is wired.
///
/// The socket is available, so a middleware can read the handshake
/// auth payload or headers; the container is the connection's own, so
/// what it registers is visible to every handler on that socket.
///
/// Returning `Err` refuses the connection.
#[async_trait]
pub trait HandshakeMiddleware: Send + Sync {
    async fn handle(&self, socket: &SocketRef, container: &Container) -> SocketResult<()>;
}

/// The connection's container, from inside an event handler.
///
/// Stored in the socket's extensions at handshake. `None` only if the
/// socket was set up outside this framework.
pub fn connection_container(socket: &SocketRef) -> Option<Container> {
    socket.extensions.get::<Container>()
}

/// Where a handler's answer goes.
///
/// A real connection sends it to the client; a test captures it. Both
/// go through the same [`ack_result`], so what a harness observes is
/// what a client would have received — the dispatch has one
/// implementation, not two.
pub enum AckSink {
    /// The client's callback.
    Client(AckSender),
    /// Captured in memory, for a test.
    Captured(std::sync::Arc<parking_lot::Mutex<Option<serde_json::Value>>>),
    /// Nothing to answer: a `connection` handler, or a client that
    /// emitted without a callback. Socket.IO acks are optional, so
    /// this is not an error.
    None,
}

impl AckSink {
    /// A sink that records what was sent, and the handle to read it.
    pub fn capture() -> (
        Self,
        std::sync::Arc<parking_lot::Mutex<Option<serde_json::Value>>>,
    ) {
        let slot = std::sync::Arc::new(parking_lot::Mutex::new(None));
        (Self::Captured(slot.clone()), slot)
    }

    pub fn send(self, value: &serde_json::Value) {
        match self {
            AckSink::Client(ack) => {
                if let Err(error) = ack.send(value) {
                    tracing::debug!(%error, "could not send the ack");
                }
            }
            AckSink::Captured(slot) => *slot.lock() = Some(value.clone()),
            AckSink::None => {}
        }
    }
}

/// Send `value` back through the ack.
pub fn ack_with(ack: AckSink, value: &serde_json::Value) {
    ack.send(value);
}

/// Helper the macro emits around a handler's return value.
#[doc(hidden)]
pub fn ack_result<T: Serialize>(ack: AckSink, result: SocketResult<T>) {
    match result {
        Ok(value) => match serde_json::to_value(&value) {
            Ok(value) => ack.send(&value),
            Err(error) => ack.send(
                &SocketError::Handler(format!("could not serialize the response: {error}"))
                    .to_payload(),
            ),
        },
        Err(error) => {
            tracing::warn!(%error, "socket event failed");
            ack.send(&error.to_payload());
        }
    }
}

/// Everything a `#[socket_controller]` needs to attach itself.
pub struct SocketControllerRegistration {
    pub namespace: String,
    pub handshake: Vec<HandshakeEntry>,
    pub events: Vec<SocketEventEntry>,
}

impl SocketControllerRegistration {
    /// Attach this controller to `io`.
    pub fn attach(self, io: &SocketIo, container: Container) {
        register_socket_namespace(io, container, self.namespace, self.handshake, self.events);
    }

    /// Event names in registration order.
    pub fn event_names(&self) -> Vec<&'static str> {
        self.events.iter().map(|entry| entry.event).collect()
    }

    /// Handshake middleware names in the order they run.
    pub fn handshake_names(&self) -> Vec<&'static str> {
        self.handshake.iter().map(|entry| entry.name).collect()
    }
}

#[doc(hidden)]
pub mod __reexport {
    pub use async_trait::async_trait;
    pub use serde_json;
    pub use socketioxide::extract::{AckSender, Data, SocketRef};
    pub use std::sync::Arc;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_error_payload_is_a_shape_a_client_can_branch_on() {
        let payload = SocketError::Validation("text is required".into()).to_payload();
        assert_eq!(payload["error"]["code"], "INVALID_PAYLOAD");
        assert!(payload["error"]["message"]
            .as_str()
            .unwrap()
            .contains("text is required"));

        assert_eq!(
            SocketError::Unauthorized("no key".into()).to_payload()["error"]["code"],
            "UNAUTHORIZED"
        );
        assert_eq!(
            SocketError::Handler("boom".into()).to_payload()["error"]["code"],
            "HANDLER_ERROR"
        );
    }
}