Skip to main content

wabot_feature_socket_controller/
lib.rs

1//! # wabot-feature-socket-controller
2//!
3//! Socket.IO controllers. Port of
4//! `wabot-ts/src/feature/socket-controller`, built on
5//! [`socketioxide`].
6//!
7//! ```ignore
8//! #[injectable]
9//! struct RoomController { rooms: Arc<Rooms> }
10//!
11//! #[socket_controller("/rooms", handshake(ApiKeyHandshake))]
12//! impl RoomController {
13//!     #[on_socket_event("connection")]
14//!     async fn on_connect(&self, socket: SocketRef) -> SocketResult<()> { … }
15//!
16//!     #[on_socket_event("join")]
17//!     async fn join(&self, req: JoinRoom, socket: SocketRef) -> SocketResult<Joined> { … }
18//! }
19//! ```
20//!
21//! An event handler takes the validated payload and the socket, and
22//! whatever it returns is sent back through the client's
23//! acknowledgement callback — so a Socket.IO event reads like a
24//! request/response, which is how clients actually use them.
25//!
26//! ## What a connection is
27//!
28//! Each connection gets a **child container**, built once at handshake
29//! and reused for every event on that socket. That is the analogue of
30//! the per-request container in REST: a handshake middleware
31//! authenticates and registers what it learned, and every later event
32//! on that socket resolves it.
33//!
34//! ```text
35//! handshake → middlewares → child container (+ Auth, + whatever) → events
36//! ```
37//!
38//! ## Refusing a connection
39//!
40//! A [`HandshakeMiddleware`] that returns `Err` rejects the handshake:
41//! the client gets a connect error and no events are ever wired.
42//! Rejecting at the handshake rather than per event is the point —
43//! otherwise every handler would have to re-check, and the one that
44//! forgot would be the hole.
45
46use async_trait::async_trait;
47use serde::Serialize;
48use socketioxide::extract::{AckSender, SocketRef};
49use socketioxide::SocketIo;
50use thiserror::Error;
51use wabot_core::injection::Container;
52
53/// Test harness. Behind `testing` (on by default) — it is small and
54/// depends on nothing extra, so gating it further would only make it
55/// awkward to reach from a dev-dependency.
56#[cfg(feature = "testing")]
57#[cfg(feature = "live-harness")]
58pub mod live;
59pub mod runtime;
60pub mod server;
61pub mod testing;
62
63pub use runtime::{register_socket_namespace, HandshakeEntry, SocketEventEntry, SocketEventFn};
64pub use server::{run_socket_controllers, socket_layer, SocketServerConfig};
65#[cfg(feature = "testing")]
66pub use testing::{EmittedEvent, SocketHarness};
67
68/// Re-exported so macro emissions and user code share one copy.
69pub use socketioxide;
70
71#[derive(Debug, Error)]
72pub enum SocketError {
73    /// The payload didn't match what the handler expects. Reported to
74    /// the client through its ack callback, like a 400.
75    #[error("invalid event payload: {0}")]
76    Validation(String),
77    /// The handshake was refused — the connection never opens.
78    #[error("handshake refused: {0}")]
79    Unauthorized(String),
80    #[error("{0}")]
81    Handler(String),
82}
83
84pub type SocketResult<T> = Result<T, SocketError>;
85
86impl SocketError {
87    /// What goes back through the ack: `{ "error": { "code", "message" } }`.
88    ///
89    /// A shape rather than a bare string because a client has to
90    /// branch on it, and parsing prose is how that goes wrong.
91    pub fn to_payload(&self) -> serde_json::Value {
92        let code = match self {
93            SocketError::Validation(_) => "INVALID_PAYLOAD",
94            SocketError::Unauthorized(_) => "UNAUTHORIZED",
95            SocketError::Handler(_) => "HANDLER_ERROR",
96        };
97        serde_json::json!({ "error": { "code": code, "message": self.to_string() } })
98    }
99}
100
101/// Runs at handshake, before any event is wired.
102///
103/// The socket is available, so a middleware can read the handshake
104/// auth payload or headers; the container is the connection's own, so
105/// what it registers is visible to every handler on that socket.
106///
107/// Returning `Err` refuses the connection.
108#[async_trait]
109pub trait HandshakeMiddleware: Send + Sync {
110    async fn handle(&self, socket: &SocketRef, container: &Container) -> SocketResult<()>;
111}
112
113/// The connection's container, from inside an event handler.
114///
115/// Stored in the socket's extensions at handshake. `None` only if the
116/// socket was set up outside this framework.
117pub fn connection_container(socket: &SocketRef) -> Option<Container> {
118    socket.extensions.get::<Container>()
119}
120
121/// Where a handler's answer goes.
122///
123/// A real connection sends it to the client; a test captures it. Both
124/// go through the same [`ack_result`], so what a harness observes is
125/// what a client would have received — the dispatch has one
126/// implementation, not two.
127pub enum AckSink {
128    /// The client's callback.
129    Client(AckSender),
130    /// Captured in memory, for a test.
131    Captured(std::sync::Arc<parking_lot::Mutex<Option<serde_json::Value>>>),
132    /// Nothing to answer: a `connection` handler, or a client that
133    /// emitted without a callback. Socket.IO acks are optional, so
134    /// this is not an error.
135    None,
136}
137
138impl AckSink {
139    /// A sink that records what was sent, and the handle to read it.
140    pub fn capture() -> (
141        Self,
142        std::sync::Arc<parking_lot::Mutex<Option<serde_json::Value>>>,
143    ) {
144        let slot = std::sync::Arc::new(parking_lot::Mutex::new(None));
145        (Self::Captured(slot.clone()), slot)
146    }
147
148    pub fn send(self, value: &serde_json::Value) {
149        match self {
150            AckSink::Client(ack) => {
151                if let Err(error) = ack.send(value) {
152                    tracing::debug!(%error, "could not send the ack");
153                }
154            }
155            AckSink::Captured(slot) => *slot.lock() = Some(value.clone()),
156            AckSink::None => {}
157        }
158    }
159}
160
161/// Send `value` back through the ack.
162pub fn ack_with(ack: AckSink, value: &serde_json::Value) {
163    ack.send(value);
164}
165
166/// Helper the macro emits around a handler's return value.
167#[doc(hidden)]
168pub fn ack_result<T: Serialize>(ack: AckSink, result: SocketResult<T>) {
169    match result {
170        Ok(value) => match serde_json::to_value(&value) {
171            Ok(value) => ack.send(&value),
172            Err(error) => ack.send(
173                &SocketError::Handler(format!("could not serialize the response: {error}"))
174                    .to_payload(),
175            ),
176        },
177        Err(error) => {
178            tracing::warn!(%error, "socket event failed");
179            ack.send(&error.to_payload());
180        }
181    }
182}
183
184/// Everything a `#[socket_controller]` needs to attach itself.
185pub struct SocketControllerRegistration {
186    pub namespace: String,
187    pub handshake: Vec<HandshakeEntry>,
188    pub events: Vec<SocketEventEntry>,
189}
190
191impl SocketControllerRegistration {
192    /// Attach this controller to `io`.
193    pub fn attach(self, io: &SocketIo, container: Container) {
194        register_socket_namespace(io, container, self.namespace, self.handshake, self.events);
195    }
196
197    /// Event names in registration order.
198    pub fn event_names(&self) -> Vec<&'static str> {
199        self.events.iter().map(|entry| entry.event).collect()
200    }
201
202    /// Handshake middleware names in the order they run.
203    pub fn handshake_names(&self) -> Vec<&'static str> {
204        self.handshake.iter().map(|entry| entry.name).collect()
205    }
206}
207
208#[doc(hidden)]
209pub mod __reexport {
210    pub use async_trait::async_trait;
211    pub use serde_json;
212    pub use socketioxide::extract::{AckSender, Data, SocketRef};
213    pub use std::sync::Arc;
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn an_error_payload_is_a_shape_a_client_can_branch_on() {
222        let payload = SocketError::Validation("text is required".into()).to_payload();
223        assert_eq!(payload["error"]["code"], "INVALID_PAYLOAD");
224        assert!(payload["error"]["message"]
225            .as_str()
226            .unwrap()
227            .contains("text is required"));
228
229        assert_eq!(
230            SocketError::Unauthorized("no key".into()).to_payload()["error"]["code"],
231            "UNAUTHORIZED"
232        );
233        assert_eq!(
234            SocketError::Handler("boom".into()).to_payload()["error"]["code"],
235            "HANDLER_ERROR"
236        );
237    }
238}