wabot_feature_socket_controller/runtime.rs
1//! Per-connection wiring — the part every `#[socket_controller]`
2//! shares. Port of `runSocketControllers.ts`.
3
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7
8use socketioxide::extract::{AckSender, Data, SocketRef};
9use socketioxide::handler::ConnectHandler;
10use socketioxide::SocketIo;
11use wabot_core::injection::Container;
12
13use crate::{HandshakeMiddleware, SocketError};
14
15/// One `#[on_socket_event]` method, type-erased.
16#[derive(Clone)]
17pub struct SocketEventEntry {
18 /// The event name a client emits.
19 pub event: &'static str,
20 pub invoke: SocketEventFn,
21}
22
23/// Deserialize + validate + dispatch + ack, all inside the closure the
24/// macro emits.
25/// The socket is `Option` because a test drives the same closure
26/// without a live connection — see `AckSink` for the other half of
27/// that. A handler that asked for a `SocketRef` and gets `None`
28/// reports it rather than pretending.
29pub type SocketEventFn = Arc<
30 dyn Fn(
31 Container,
32 Option<SocketRef>,
33 serde_json::Value,
34 crate::AckSink,
35 ) -> Pin<Box<dyn Future<Output = ()> + Send>>
36 + Send
37 + Sync,
38>;
39
40/// A handshake middleware, built from the connection's container so it
41/// can depend on request-scoped things.
42#[derive(Clone)]
43pub struct HandshakeEntry {
44 pub name: &'static str,
45 #[allow(clippy::type_complexity)]
46 pub build: Arc<dyn Fn(&Container) -> Arc<dyn HandshakeMiddleware> + Send + Sync>,
47}
48
49/// The event name that means "the socket just connected" rather than
50/// something the client emitted. Matches TS.
51pub const CONNECTION_EVENT: &str = "connection";
52
53/// Attach one controller's namespace to `io`.
54///
55/// Called by the macro-emitted `register_socket_handlers`; call it
56/// directly to wire a controller built by hand.
57pub fn register_socket_namespace(
58 io: &SocketIo,
59 parent: Container,
60 namespace: String,
61 handshake: Vec<HandshakeEntry>,
62 events: Vec<SocketEventEntry>,
63) {
64 tracing::info!(namespace = %namespace, events = events.len(), "config socket namespace");
65
66 // The handshake runs as a socketioxide **connect middleware**, not
67 // at the top of the connect handler, and that ordering is load
68 // bearing: a middleware runs before the client is told the
69 // connection succeeded, whereas anything awaited inside the
70 // handler leaves a window where the client has already started
71 // emitting and no listener is attached yet. Those events are
72 // dropped silently — the first version of this did exactly that,
73 // and every event test timed out.
74 //
75 // So: middleware authenticates and can refuse; the handler then
76 // wires listeners with no `await` before them.
77 let middleware_namespace = namespace.clone();
78 let middleware = move |socket: SocketRef| {
79 let parent = parent.clone();
80 let handshake = handshake.clone();
81 let namespace = middleware_namespace.clone();
82 async move {
83 // One container per connection, reused by every event on
84 // this socket — the socket analogue of the per-request
85 // container.
86 let container = parent.create_child();
87 for entry in &handshake {
88 let middleware = (entry.build)(&container);
89 if let Err(error) = middleware.handle(&socket, &container).await {
90 tracing::warn!(
91 namespace = %namespace,
92 middleware = entry.name,
93 %error,
94 "handshake refused"
95 );
96 // Returning Err refuses the connection: socketioxide
97 // sends `connect_error` and the namespace is never
98 // joined, so no handler can run for a socket that
99 // failed to authenticate.
100 return Err(error);
101 }
102 }
103 socket.extensions.insert(container);
104 Ok::<(), SocketError>(())
105 }
106 };
107
108 // **Synchronous** on purpose. An async connect handler is only
109 // polled when the runtime gets to it, which can be after the
110 // client — already told the connection succeeded — has emitted its
111 // first event; that packet finds no listener and is dropped. This
112 // registers every listener inline, before socketioxide processes
113 // another packet, and defers only the `connection` handler.
114 let handler = move |socket: SocketRef| {
115 // The middleware put it there; a socket that reaches the
116 // handler has passed the handshake.
117 let Some(container) = socket.extensions.get::<Container>() else {
118 tracing::error!("socket reached the handler without a connection container");
119 socket.disconnect().ok();
120 return;
121 };
122
123 let mut on_connection: Option<SocketEventEntry> = None;
124 for entry in events.clone() {
125 if entry.event == CONNECTION_EVENT {
126 on_connection = Some(entry);
127 continue;
128 }
129
130 let container = container.clone();
131 let invoke = entry.invoke.clone();
132 socket.on(
133 entry.event,
134 move |socket: SocketRef, Data::<serde_json::Value>(payload), ack: AckSender| {
135 let container = container.clone();
136 let invoke = invoke.clone();
137 async move {
138 (invoke)(
139 container,
140 Some(socket),
141 payload,
142 crate::AckSink::Client(ack),
143 )
144 .await;
145 }
146 },
147 );
148 }
149
150 // Every listener is attached by the time this runs, so a
151 // `connection` handler that emits can't beat them into place.
152 //
153 // No ack: a connection isn't a client emit, so there is no
154 // callback to answer. Whatever the handler returns is dropped,
155 // which the macro's docs say plainly.
156 if let Some(entry) = on_connection {
157 let socket = socket.clone();
158 tokio::spawn(async move {
159 (entry.invoke)(
160 container,
161 Some(socket),
162 serde_json::Value::Null,
163 crate::AckSink::None,
164 )
165 .await;
166 });
167 }
168 };
169
170 io.ns(namespace, handler.with(middleware));
171}
172
173/// Deserialize + validate an event payload, reporting a bad one the
174/// way the client can act on.
175///
176/// Shared by every generated handler so one place decides what
177/// "invalid" means.
178pub fn parse_payload<T>(payload: serde_json::Value) -> Result<T, SocketError>
179where
180 T: serde::de::DeserializeOwned + wabot_core::validation::Validate,
181{
182 let value: T = serde_json::from_value(payload)
183 .map_err(|error| SocketError::Validation(error.to_string()))?;
184 value
185 .validate()
186 .map_err(|error| SocketError::Validation(error.to_string()))?;
187 Ok(value)
188}