wabot-feature-socket-controller 0.2.0

Socket.IO controller framework — port of wabot-ts feature/socket-controller, built on socketioxide.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! A harness with a **real connection**. Port of
//! `wabot-ts/src/testing/socketHarness.ts`.
//!
//! ```ignore
//! let harness = LiveSocketHarness::start(layer).await?;
//! let mut client = harness.connect("/chat").await?;
//! let ack = client.emit_with_ack("join", json!({"room": "a"})).await?;
//! assert_eq!(ack[0]["ok"], json!(true));
//! ```
//!
//! ## Why this exists next to [`SocketHarness`]
//!
//! [`SocketHarness`] drives the *dispatch closure* with the answer
//! captured instead of sent. That covers validation, controller
//! resolution and acks without a network, and it is what most tests
//! want. What it cannot do is **be a connection**, so two things stay
//! out of its reach and they are exactly the two that carry security
//! weight: a **handshake middleware**, which decides whether a client
//! may connect at all, and a handler taking a `SocketRef` — rooms,
//! broadcasts, disconnects.
//!
//! This one binds an ephemeral port and speaks the wire, so those are
//! testable in `cargo test` rather than only in a script.
//!
//! [`SocketHarness`]: crate::testing::SocketHarness
//!
//! ## Why a hand-written client
//!
//! `rust_socketio` 0.6 does not interoperate with `socketioxide` 0.15
//! — a probe using *only those two crates*, with none of this
//! framework involved, could not complete a round trip. So the choice
//! was a hand-written client or no in-process test at all.
//!
//! It is ~200 lines because Socket.IO over a WebSocket is a small
//! text protocol: `0{…}` opens the engine, `40/ns,{auth}` joins a
//! namespace, `42/ns,id["event",args]` emits, `43/ns,id[…]` acks.
//! **What keeps it honest** is that the same server was verified
//! against the official `socket.io-client@4` in
//! the socket-rooms example — this client was checked against that
//! ground truth rather than being its own authority. If the two ever
//! disagree, the JS scripts are right.

use std::time::Duration;

use futures_util::{SinkExt, StreamExt};
use serde_json::Value;
use tokio::net::TcpStream;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};

use crate::server::socket_layer;

type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;

/// How long to wait for a frame before giving up.
///
/// A test that hangs tells you nothing; one that fails after two
/// seconds names the event it was waiting for.
const TIMEOUT: Duration = Duration::from_secs(2);

#[derive(Debug, thiserror::Error)]
pub enum LiveError {
    #[error("the connection was refused: {0}")]
    Refused(String),
    #[error("timed out waiting for {0}")]
    Timeout(String),
    #[error("socket error: {0}")]
    Socket(String),
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
}

type LiveResult<T> = Result<T, LiveError>;

/// A server bound to an ephemeral port on localhost.
pub struct LiveSocketHarness {
    address: std::net::SocketAddr,
    shutdown: Option<tokio::sync::oneshot::Sender<()>>,
}

impl LiveSocketHarness {
    /// Bind and serve `layer` on 127.0.0.1 with a port the OS picks.
    ///
    /// Port 0 rather than a fixed one so parallel tests can't collide
    /// — the same reason the REST harness binds no port at all.
    pub async fn start(layer: socketioxide::layer::SocketIoLayer) -> LiveResult<Self> {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let address = listener.local_addr()?;
        let app = axum::Router::new().layer(layer);

        let (shutdown, signal) = tokio::sync::oneshot::channel();
        tokio::spawn(async move {
            let _ = axum::serve(listener, app)
                .with_graceful_shutdown(async {
                    let _ = signal.await;
                })
                .await;
        });

        Ok(Self {
            address,
            shutdown: Some(shutdown),
        })
    }

    /// Build the layer *and* start it, for the common case.
    pub async fn start_with<F>(build: F) -> LiveResult<Self>
    where
        F: FnOnce(&socketioxide::SocketIo),
    {
        let (layer, io) = socket_layer();
        build(&io);
        Self::start(layer).await
    }

    pub fn address(&self) -> std::net::SocketAddr {
        self.address
    }

    /// Connect to `namespace`, with nothing else.
    pub async fn connect(&self, namespace: &str) -> LiveResult<LiveClient> {
        self.connect_with(namespace, None, None).await
    }

    /// Connect with a query string on the handshake request — what
    /// `socket.req_parts().uri.query()` reads.
    ///
    /// It goes on the **URL**, not in the namespace: they are
    /// different fields of the protocol, and putting a query in the
    /// namespace gets an "Invalid namespace" refusal that looks
    /// exactly like a middleware rejecting you.
    pub async fn connect_with_query(&self, namespace: &str, query: &str) -> LiveResult<LiveClient> {
        self.connect_with(namespace, Some(query), None).await
    }

    /// Connect carrying an auth payload — the other thing a handshake
    /// middleware can read.
    pub async fn connect_with_auth(
        &self,
        namespace: &str,
        auth: Option<Value>,
    ) -> LiveResult<LiveClient> {
        self.connect_with(namespace, None, auth).await
    }

    pub async fn connect_with(
        &self,
        namespace: &str,
        query: Option<&str>,
        auth: Option<Value>,
    ) -> LiveResult<LiveClient> {
        let extra = query
            .map(|query| format!("&{}", query.trim_start_matches(['?', '&'])))
            .unwrap_or_default();
        let url = format!(
            "ws://{}/socket.io/?EIO=4&transport=websocket{extra}",
            self.address
        );
        let (mut socket, _) = tokio_tungstenite::connect_async(&url)
            .await
            .map_err(|error| LiveError::Socket(error.to_string()))?;

        // Engine.IO opens with `0{…}`; nothing can be sent before it.
        let open = next_text(&mut socket, "the engine.io open packet").await?;
        if !open.starts_with('0') {
            return Err(LiveError::Socket(format!(
                "unexpected opening frame: {open}"
            )));
        }

        let namespace = normalize(namespace);
        let connect = match auth {
            Some(auth) => format!("40{namespace},{auth}"),
            None => format!("40{namespace},"),
        };
        socket
            .send(Message::Text(connect.into()))
            .await
            .map_err(|error| LiveError::Socket(error.to_string()))?;

        let mut client = LiveClient {
            socket,
            namespace,
            next_ack: 0,
            pending: Vec::new(),
        };

        // `40` accepts, `44` refuses — and a refused handshake is the
        // case worth testing, so it comes back as a typed error rather
        // than a hang.
        loop {
            let frame = client.next_frame("the namespace connect reply").await?;
            if frame.starts_with("40") {
                return Ok(client);
            }
            if frame.starts_with("44") {
                let payload = frame
                    .splitn(2, '{')
                    .nth(1)
                    .map(|rest| format!("{{{rest}"))
                    .unwrap_or_else(|| frame.clone());
                return Err(LiveError::Refused(payload));
            }
        }
    }
}

impl Drop for LiveSocketHarness {
    fn drop(&mut self) {
        if let Some(shutdown) = self.shutdown.take() {
            let _ = shutdown.send(());
        }
    }
}

/// One connected client.
pub struct LiveClient {
    socket: Socket,
    namespace: String,
    next_ack: u64,
    /// Events that arrived while waiting for something else. Kept
    /// rather than dropped: a server emit can easily land before the
    /// ack a test is awaiting, and losing it would make the test flaky
    /// in a way nobody could reproduce.
    pending: Vec<(String, Vec<Value>)>,
}

impl LiveClient {
    /// Emit and wait for the handler's ack.
    pub async fn emit_with_ack(&mut self, event: &str, payload: Value) -> LiveResult<Vec<Value>> {
        let id = self.next_ack;
        self.next_ack += 1;

        let frame = format!(
            "42{},{}{}",
            self.namespace,
            id,
            serde_json::json!([event, payload])
        );
        self.send(frame).await?;

        loop {
            let frame = self.next_frame(&format!("an ack for '{event}'")).await?;
            let Some(rest) = frame.strip_prefix("43") else {
                self.stash(&frame);
                continue;
            };
            let rest = rest
                .trim_start_matches(&self.namespace)
                .trim_start_matches(',');
            let (ack_id, body) = split_ack(rest);
            if ack_id != Some(id) {
                continue;
            }
            return Ok(serde_json::from_str(body).unwrap_or_default());
        }
    }

    /// Emit without waiting for anything.
    pub async fn emit(&mut self, event: &str, payload: Value) -> LiveResult<()> {
        let frame = format!(
            "42{},{}",
            self.namespace,
            serde_json::json!([event, payload])
        );
        self.send(frame).await
    }

    /// Wait for the server to emit `event`, returning its arguments.
    pub async fn wait_for(&mut self, event: &str) -> LiveResult<Vec<Value>> {
        if let Some(index) = self.pending.iter().position(|(name, _)| name == event) {
            return Ok(self.pending.remove(index).1);
        }
        loop {
            let frame = self.next_frame(&format!("the '{event}' event")).await?;
            if let Some((name, args)) = parse_event(&frame, &self.namespace) {
                if name == event {
                    return Ok(args);
                }
                self.pending.push((name, args));
            }
        }
    }

    /// Whether the server emitted `event` within the window — for
    /// asserting something did **not** happen.
    pub async fn saw(&mut self, event: &str) -> bool {
        self.wait_for(event).await.is_ok()
    }

    pub async fn close(mut self) {
        let _ = self.socket.close(None).await;
    }

    async fn send(&mut self, frame: String) -> LiveResult<()> {
        self.socket
            .send(Message::Text(frame.into()))
            .await
            .map_err(|error| LiveError::Socket(error.to_string()))
    }

    fn stash(&mut self, frame: &str) {
        if let Some(parsed) = parse_event(frame, &self.namespace) {
            self.pending.push(parsed);
        }
    }

    /// The next frame that isn't engine.io housekeeping.
    async fn next_frame(&mut self, waiting_for: &str) -> LiveResult<String> {
        loop {
            let text = next_text(&mut self.socket, waiting_for).await?;
            // `2` is a ping and must be answered, or the server drops
            // the connection mid-test.
            if text == "2" {
                self.send("3".into()).await?;
                continue;
            }
            return Ok(text);
        }
    }
}

async fn next_text(socket: &mut Socket, waiting_for: &str) -> LiveResult<String> {
    loop {
        let message = tokio::time::timeout(TIMEOUT, socket.next())
            .await
            .map_err(|_| LiveError::Timeout(waiting_for.to_string()))?
            .ok_or_else(|| LiveError::Socket("the connection closed".into()))?
            .map_err(|error| LiveError::Socket(error.to_string()))?;

        match message {
            Message::Text(text) => return Ok(text.to_string()),
            Message::Close(_) => return Err(LiveError::Socket("the server closed it".into())),
            _ => continue,
        }
    }
}

fn normalize(namespace: &str) -> String {
    match namespace {
        "" | "/" => "/".to_string(),
        other if other.starts_with('/') => other.to_string(),
        other => format!("/{other}"),
    }
}

/// `42/ns,["event",arg…]` → the event name and its arguments.
fn parse_event(frame: &str, namespace: &str) -> Option<(String, Vec<Value>)> {
    let rest = frame.strip_prefix("42")?;
    let rest = rest.strip_prefix(namespace).unwrap_or(rest);
    let rest = rest.trim_start_matches(',');
    // An emit from the server may carry an ack id we don't use.
    let body = rest.trim_start_matches(|c: char| c.is_ascii_digit());
    let mut args: Vec<Value> = serde_json::from_str(body).ok()?;
    if args.is_empty() {
        return None;
    }
    let name = args.remove(0).as_str()?.to_string();
    Some((name, args))
}

/// `3["ok"]` → (Some(3), `["ok"]`).
fn split_ack(rest: &str) -> (Option<u64>, &str) {
    let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
    let body = &rest[digits.len()..];
    (digits.parse().ok(), body)
}

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

    #[test]
    fn a_namespace_is_normalized_the_way_the_protocol_wants_it() {
        assert_eq!(normalize(""), "/");
        assert_eq!(normalize("/"), "/");
        assert_eq!(normalize("chat"), "/chat");
        assert_eq!(normalize("/chat"), "/chat");
    }

    #[test]
    fn an_event_frame_is_parsed() {
        let (name, args) = parse_event(r#"42/chat,["message",{"text":"hi"}]"#, "/chat").unwrap();
        assert_eq!(name, "message");
        assert_eq!(args[0]["text"], "hi");
    }

    /// The root namespace has no name in the frame at all, which is
    /// the case a naive `strip_prefix` gets wrong.
    #[test]
    fn an_event_on_the_root_namespace_is_parsed() {
        let (name, args) = parse_event(r#"42["tick",1]"#, "/").unwrap();
        assert_eq!(name, "tick");
        assert_eq!(args[0], 1);
    }

    #[test]
    fn an_ack_id_is_split_from_its_body() {
        assert_eq!(
            split_ack(r#"7[{"ok":true}]"#),
            (Some(7), r#"[{"ok":true}]"#)
        );
        assert_eq!(split_ack("[]"), (None, "[]"));
    }
}