wynd 0.4.3

A simple websocket library for rust.
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#[cfg(test)]
mod tests {
    use crate::conn::{Connection, ConnectionHandle};

    use std::{
        io,
        net::SocketAddr,
        pin::Pin,
        sync::Arc,
        task::{Context, Poll},
        time::Duration,
    };
    use tokio::{
        io::{AsyncRead, AsyncWrite, ReadBuf},
        sync::{Mutex, mpsc},
        time::timeout,
    };
    use tokio_tungstenite::WebSocketStream;

    // Mock stream for testing
    #[derive(Debug)]
    struct MockStream {
        read_data: Vec<u8>,
        write_data: Vec<u8>,
        read_pos: usize,
        closed: bool,
    }

    impl MockStream {
        fn new() -> Self {
            Self {
                read_data: Vec::new(),
                write_data: Vec::new(),
                read_pos: 0,
                closed: false,
            }
        }
    }

    impl AsyncRead for MockStream {
        fn poll_read(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<io::Result<()>> {
            if self.closed {
                return Poll::Ready(Ok(()));
            }

            let remaining = self.read_data.len() - self.read_pos;
            if remaining == 0 {
                return Poll::Pending;
            }

            let to_copy = std::cmp::min(buf.remaining(), remaining);
            let data = &self.read_data[self.read_pos..self.read_pos + to_copy];
            buf.put_slice(data);
            self.read_pos += to_copy;

            Poll::Ready(Ok(()))
        }
    }

    impl AsyncWrite for MockStream {
        fn poll_write(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<Result<usize, io::Error>> {
            if self.closed {
                return Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::BrokenPipe,
                    "Stream closed",
                )));
            }
            self.write_data.extend_from_slice(buf);
            Poll::Ready(Ok(buf.len()))
        }

        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
            Poll::Ready(Ok(()))
        }

        fn poll_shutdown(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Result<(), io::Error>> {
            self.closed = true;
            Poll::Ready(Ok(()))
        }
    }

    impl Unpin for MockStream {}

    // Helper function to create a mock WebSocket connection
    #[tokio::test]
    async fn test_connection_creation() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;

        let connection = Connection::new(42, ws_stream, addr);

        assert_eq!(connection.id(), 42);
        assert_eq!(connection.addr(), addr);
    }

    #[tokio::test]
    async fn test_connection_handle_creation() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let (writer, _reader) = futures::StreamExt::split(ws_stream);

        let handle = ConnectionHandle {
            id: 123,
            writer: Arc::new(Mutex::new(writer)),
            addr,
        };

        assert_eq!(handle.id(), 123);
        assert_eq!(handle.addr(), addr);
    }

    #[tokio::test]
    async fn test_on_open_handler() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let connection = Connection::new(1, ws_stream, addr);

        let (tx, mut rx) = mpsc::channel(1);

        connection
            .on_open(move |handle| {
                let tx = tx.clone();
                async move {
                    tx.send(handle.id()).await.unwrap();
                }
            })
            .await;

        // Wait for the handler to be called
        let received_id = timeout(Duration::from_millis(100), rx.recv())
            .await
            .expect("Handler should be called")
            .expect("Should receive connection ID");

        assert_eq!(received_id, 1);
    }

    #[tokio::test]
    async fn test_on_text_handler() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let connection = Connection::new(1, ws_stream, addr);

        let (tx, _) = mpsc::channel(1);

        connection.on_text(move |msg, _handle| {
            let tx = tx.clone();
            async move {
                tx.send(msg.data).await.unwrap();
            }
        });

        // Set up a minimal open handler to start the message loop
        connection.on_open(|_| async {}).await;

        // Note: In a real test, you'd need to simulate receiving a WebSocket text message
        // This would require a more sophisticated mock setup
    }

    #[tokio::test]
    async fn test_on_binary_handler() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let connection = Connection::new(1, ws_stream, addr);

        let (tx, _) = mpsc::channel(1);

        connection.on_binary(move |msg, _handle| {
            let tx = tx.clone();
            async move {
                tx.send(msg.data.len()).await.unwrap();
            }
        });

        // Set up a minimal open handler to start the message loop
        connection.on_open(|_| async {}).await;

        // Note: Similar to text handler test, would need sophisticated mock for real testing
    }

    #[tokio::test]
    async fn test_on_close_handler() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let connection = Connection::new(1, ws_stream, addr);

        let (tx, _) = mpsc::channel(1);

        connection.on_close(move |event| {
            let tx = tx.clone();
            async move {
                tx.send((event.code, event.reason)).await.unwrap();
            }
        });

        // Set up a minimal open handler to start the message loop
        connection.on_open(|_| async {}).await;

        // Note: In a real test, you'd simulate a WebSocket close event
    }

    #[tokio::test]
    async fn test_send_text_message() {
        // This test would require a more sophisticated mock that can capture
        // the actual WebSocket frames being sent
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let (writer, _reader) = futures::StreamExt::split(ws_stream);

        let handle = ConnectionHandle {
            id: 1,
            writer: Arc::new(Mutex::new(writer)),
            addr,
        };

        // In a real test environment, you'd verify the message was actually sent
        // For now, we just test that the method doesn't panic
        let _result = handle.send_text("Hello, World!").await;

        // The result depends on the mock implementation
        // In a proper test, you'd verify the WebSocket frame was written
    }

    #[tokio::test]
    async fn test_send_binary_message() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let (writer, _reader) = futures::StreamExt::split(ws_stream);

        let handle = ConnectionHandle {
            id: 1,
            writer: Arc::new(Mutex::new(writer)),
            addr,
        };

        let data = vec![1, 2, 3, 4, 5];
        let _result = handle.send_binary(data).await;

        // Similar to text test - in a proper test environment,
        // you'd verify the binary frame was actually sent
    }

    #[tokio::test]
    async fn test_close_connection() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let (writer, _reader) = futures::StreamExt::split(ws_stream);

        let handle = ConnectionHandle {
            id: 1,
            writer: Arc::new(Mutex::new(writer)),
            addr,
        };

        let _result = handle.close().await;

        // In a proper test, you'd verify a close frame was sent
    }

    #[tokio::test]
    async fn test_multiple_handlers() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let connection = Connection::new(1, ws_stream, addr);

        let (open_tx, mut open_rx) = mpsc::channel(1);
        let (text_tx, _text_rx) = mpsc::channel(1);
        let (close_tx, _close_rx) = mpsc::channel(1);

        // Set up all handlers
        connection.on_text(move |msg, _handle| {
            let tx = text_tx.clone();
            async move {
                tx.send(format!("Got: {}", msg.data)).await.unwrap();
            }
        });

        connection.on_close(move |event| {
            let tx = close_tx.clone();
            async move {
                tx.send(event.code).await.unwrap();
            }
        });

        connection
            .on_open(move |handle| {
                let tx = open_tx.clone();
                async move {
                    tx.send(handle.id()).await.unwrap();
                }
            })
            .await;

        // Verify open handler was called
        let received_id = timeout(Duration::from_millis(100), open_rx.recv())
            .await
            .expect("Open handler should be called")
            .expect("Should receive connection ID");

        assert_eq!(received_id, 1);
    }

    #[tokio::test]
    async fn test_concurrent_message_sending() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let (writer, _reader) = futures::StreamExt::split(ws_stream);

        let handle = Arc::new(ConnectionHandle {
            id: 1,
            writer: Arc::new(Mutex::new(writer)),
            addr,
        });

        // Test concurrent sending from multiple tasks
        let handles: Vec<_> = (0..5)
            .map(|i| {
                let handle = Arc::clone(&handle);
                tokio::spawn(async move {
                    // Instead of propagating the error, just assert success for test
                    handle
                        .send_text(&format!("Message {}", i))
                        .await
                        .expect("send_text should succeed");
                })
            })
            .collect();
        for task_handle in handles {
            let _result = task_handle.await.expect("Task should complete");
            // In a proper test, you'd verify all messages were sent correctly
        }
    }

    // Integration test with a more realistic WebSocket setup
    #[tokio::test]
    async fn test_connection_lifecycle() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let connection = Connection::new(1, ws_stream, addr);

        let (lifecycle_tx, mut lifecycle_rx) = mpsc::channel(10);

        // Track the connection lifecycle
        connection
            .on_open({
                let tx = lifecycle_tx.clone();
                move |handle| {
                    let tx = tx.clone();
                    async move {
                        tx.send(format!("OPEN:{}", handle.id())).await.unwrap();
                    }
                }
            })
            .await;

        connection.on_text({
            let tx = lifecycle_tx.clone();
            move |msg, handle| {
                let tx = tx.clone();
                async move {
                    tx.send(format!("TEXT:{}:{}", handle.id(), msg.data))
                        .await
                        .unwrap();
                }
            }
        });

        connection.on_binary({
            let tx = lifecycle_tx.clone();
            move |msg, handle| {
                let tx = tx.clone();
                async move {
                    tx.send(format!("BINARY:{}:{}", handle.id(), msg.data.len()))
                        .await
                        .unwrap();
                }
            }
        });

        connection.on_close({
            let tx = lifecycle_tx.clone();
            move |event| {
                let tx = tx.clone();
                async move {
                    tx.send(format!("CLOSE:{}:{}", event.code, event.reason))
                        .await
                        .unwrap();
                }
            }
        });

        // Wait for open event
        let open_event = timeout(Duration::from_millis(100), lifecycle_rx.recv())
            .await
            .expect("Should receive open event")
            .expect("Should get open event");

        assert_eq!(open_event, "OPEN:1");

        // In a full integration test, you'd continue by:
        // 1. Simulating incoming WebSocket messages
        // 2. Verifying text/binary handlers are called
        // 3. Simulating connection close
        // 4. Verifying close handler is called
    }

    #[test]
    fn test_connection_id_and_addr() {
        let id = 42;
        let addr: SocketAddr = "192.168.1.1:9000".parse().unwrap();

        // Test that we can create the basic properties
        assert_eq!(id, 42);
        assert_eq!(addr.ip().to_string(), "192.168.1.1");
        assert_eq!(addr.port(), 9000);
    }

    #[test]
    fn test_message_event_creation() {
        use crate::types::{BinaryMessageEvent, CloseEvent, TextMessageEvent};

        // Test TextMessageEvent
        let text_event = TextMessageEvent::new("Hello".to_string());
        assert_eq!(text_event.data, "Hello");

        // Test BinaryMessageEvent
        let binary_data = vec![1, 2, 3, 4, 5];
        let binary_event = BinaryMessageEvent::new(binary_data.clone());
        assert_eq!(binary_event.data, binary_data);

        // Test CloseEvent
        let close_event = CloseEvent::new(1000, "Normal closure".to_string());
        assert_eq!(close_event.code, 1000);
        assert_eq!(close_event.reason, "Normal closure");

        // Test CloseEvent display
        let close_event_display = format!("{}", close_event);
        assert_eq!(
            close_event_display,
            "CloseEvent { code: 1000, reason: Normal closure }"
        );
    }

    // Error handling tests
    #[tokio::test]
    async fn test_send_message_error_handling() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let (writer, _reader) = futures::StreamExt::split(ws_stream);

        let handle = ConnectionHandle {
            id: 1,
            writer: Arc::new(Mutex::new(writer)),
            addr,
        };

        // Test sending to a potentially closed connection
        // In a real test, you'd set up the mock to return an error
        let _result = handle.send_text("test").await;

        // Depending on your mock implementation, you can test error cases
    }

    // Performance/stress test
    #[tokio::test]
    async fn test_high_frequency_message_handling() {
        let stream = MockStream::new();
        let addr = "127.0.0.1:8080".parse().unwrap();
        let ws_stream = WebSocketStream::from_raw_socket(
            stream,
            tokio_tungstenite::tungstenite::protocol::Role::Server,
            None,
        )
        .await;
        let connection = Connection::new(1, ws_stream, addr);

        let message_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let counter = Arc::clone(&message_count);

        connection.on_text(move |_msg, _handle| {
            let counter = Arc::clone(&counter);
            async move {
                counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
        });

        connection.on_open(|_| async {}).await;

        // In a real test, you'd send many messages rapidly and verify
        // they're all handled correctly without blocking or dropping
    }
}