wabot-feature-socket-controller 0.1.0

Socket.IO controller framework — port of wabot-ts feature/socket-controller, built on socketioxide.
Documentation
//! Drive socket events in a test, without a connection.
//!
//! ## What it runs, and what it can't
//!
//! It runs the **same dispatch closure** a live connection runs: the
//! payload is deserialized and validated the same way, the controller
//! is resolved from the same container, and the answer goes through
//! the same [`ack_result`](crate::ack_result) — captured instead of
//! sent. Nothing here reimplements the runtime, so what a test
//! observes is what a client would have received.
//!
//! What it cannot do is *be* a connection. There is no
//! `SocketRef`, so:
//!
//! * a handler that takes a `SocketRef` reports that it needs a live
//!   socket rather than running — [`EmittedEvent::needs_socket`] says
//!   so plainly;
//! * a handshake middleware is *built* but not run, since running one
//!   means handing it a socket.
//!
//! For those, and for anything protocol-level, use a real client. The
//! socket-rooms verification script did exactly that, and
//! is what demonstrated the wire behaviour this harness stands on.
//!
//! ```ignore
//! let harness = SocketHarness::new(RoomController::socket_registration(&container), container);
//!
//! let ack = harness.emit("join", json!({ "room": "general" })).await;
//! assert_eq!(ack.value()["room"], "general");
//!
//! let bad = harness.emit("join", json!({ "room": "" })).await;
//! assert_eq!(bad.error_code(), Some("INVALID_PAYLOAD"));
//! ```

use wabot_core::injection::Container;

use crate::{AckSink, SocketControllerRegistration, SocketEventEntry};

/// Runs a controller's events against a container, with no server.
pub struct SocketHarness {
    registration: SocketControllerRegistration,
    container: Container,
}

impl SocketHarness {
    pub fn new(registration: SocketControllerRegistration, container: Container) -> Self {
        Self {
            registration,
            container,
        }
    }

    pub fn namespace(&self) -> &str {
        &self.registration.namespace
    }

    /// Event names, in registration order.
    pub fn event_names(&self) -> Vec<&'static str> {
        self.registration.event_names()
    }

    /// Handshake middleware names, in the order they would run.
    pub fn handshake_names(&self) -> Vec<&'static str> {
        self.registration.handshake_names()
    }

    /// The container a connection's events resolve from.
    ///
    /// A real connection gets a *child* of it, populated by the
    /// handshake; register there what a middleware would have, and a
    /// handler sees the same thing it would in production.
    pub fn container(&self) -> &Container {
        &self.container
    }

    fn entry(&self, event: &str) -> &SocketEventEntry {
        self.registration
            .events
            .iter()
            .find(|entry| entry.event == event)
            .unwrap_or_else(|| {
                panic!(
                    "no handler for the '{event}' event. This controller handles: {:?}",
                    self.registration.event_names()
                )
            })
    }

    /// Emit an event and capture what the client would have received.
    ///
    /// # Panics
    ///
    /// If no handler is registered for `event` — a test emitting an
    /// event nothing handles is asserting nothing, and in production
    /// that packet is silently dropped, which is worse to discover
    /// later.
    pub async fn emit(&self, event: &str, payload: serde_json::Value) -> EmittedEvent {
        let entry = self.entry(event);
        let (sink, captured) = AckSink::capture();
        (entry.invoke)(self.container.clone(), None, payload, sink).await;
        let ack = captured.lock().clone();
        EmittedEvent {
            event: event.to_string(),
            ack,
        }
    }
}

/// What an emitted event produced.
pub struct EmittedEvent {
    pub event: String,
    /// What went back through the ack, if anything. `None` means the
    /// handler answered nothing — a `connection`-style handler.
    pub ack: Option<serde_json::Value>,
}

impl EmittedEvent {
    /// The acked value.
    ///
    /// # Panics
    ///
    /// If nothing was acked, naming the event — the usual cause is a
    /// handler that needs a live socket.
    pub fn value(&self) -> serde_json::Value {
        self.ack.clone().unwrap_or_else(|| {
            panic!(
                "the '{}' event answered nothing. A handler that takes a SocketRef cannot be \
                 driven without a connection — check needs_socket().",
                self.event
            )
        })
    }

    /// The `error.code` when the handler (or validation) refused.
    pub fn error_code(&self) -> Option<&str> {
        self.ack.as_ref()?.get("error")?.get("code")?.as_str()
    }

    pub fn error_message(&self) -> Option<&str> {
        self.ack.as_ref()?.get("error")?.get("message")?.as_str()
    }

    pub fn is_error(&self) -> bool {
        self.error_code().is_some()
    }

    /// True when the handler declined because it wants a real socket.
    pub fn needs_socket(&self) -> bool {
        self.error_message()
            .is_some_and(|message| message.contains("needs a live socket"))
    }

    /// The acked value as `T`.
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> T {
        serde_json::from_value(self.value()).unwrap_or_else(|error| {
            panic!(
                "the '{}' event answered {:?}, which is not a {} ({error})",
                self.event,
                self.ack,
                std::any::type_name::<T>()
            )
        })
    }
}