o2-sdk 0.2.0

Rust SDK for the O2 Exchange — a fully on-chain order book DEX on the Fuel Network
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
#![cfg(feature = "integration")]
/// Unit tests for WebSocket functionality using a mock server.
///
/// These tests use an in-process mock WebSocket server to test all subscription types,
/// reconnection, heartbeat, and long-lived connection behavior without hitting testnet.
///
/// Run with: cargo test --features integration --test websocket_tests
use futures_util::{SinkExt, StreamExt};
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::sync::Mutex;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::Message as WsMsg;

use o2_sdk::models::*;
use o2_sdk::websocket::{DepthPrecision, O2WebSocket, WsConfig, WsLifecycleEvent};

/// Create a mock server that sends specific messages on connection.
async fn create_messaging_mock_server(messages: Vec<serde_json::Value>) -> String {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        if let Ok((stream, _)) = listener.accept().await {
            if let Ok(ws_stream) = accept_async(stream).await {
                let (mut sender, mut receiver) = ws_stream.split();

                // Send all messages immediately after connection
                for msg in &messages {
                    let text = serde_json::to_string(msg).unwrap();
                    let _ = sender.send(WsMsg::Text(text)).await;
                }

                // Keep connection alive
                while let Some(Ok(msg)) = receiver.next().await {
                    match msg {
                        WsMsg::Ping(data) => {
                            let _ = sender.send(WsMsg::Pong(data)).await;
                        }
                        WsMsg::Close(_) => break,
                        _ => {}
                    }
                }
            }
        }
    });

    tokio::time::sleep(Duration::from_millis(50)).await;
    format!("ws://{}", addr)
}

/// Create a mock server that drops connections after sending messages.
async fn create_reconnect_mock_server(
    first_messages: Vec<serde_json::Value>,
    second_messages: Vec<serde_json::Value>,
) -> String {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let connection_count = Arc::new(Mutex::new(0));

    tokio::spawn(async move {
        loop {
            if let Ok((stream, _)) = listener.accept().await {
                let mut count = connection_count.lock().await;
                *count += 1;
                let is_first = *count == 1;
                drop(count);

                if let Ok(ws_stream) = accept_async(stream).await {
                    let (mut sender, mut receiver) = ws_stream.split();

                    let messages = if is_first {
                        &first_messages
                    } else {
                        &second_messages
                    };

                    for msg in messages {
                        let text = serde_json::to_string(msg).unwrap();
                        let _ = sender.send(WsMsg::Text(text)).await;
                    }

                    if is_first {
                        // Drop connection after first message
                        tokio::time::sleep(Duration::from_millis(100)).await;
                        let _ = sender.send(WsMsg::Close(None)).await;
                        continue;
                    }

                    // Keep second connection alive
                    while let Some(Ok(msg)) = receiver.next().await {
                        match msg {
                            WsMsg::Ping(data) => {
                                let _ = sender.send(WsMsg::Pong(data)).await;
                            }
                            WsMsg::Close(_) => break,
                            _ => {}
                        }
                    }
                }
            }
        }
    });

    tokio::time::sleep(Duration::from_millis(50)).await;
    format!("ws://{}", addr)
}

/// Create a mock server that refuses all connections.
async fn create_refusing_mock_server() -> String {
    // Bind a port but don't accept connections
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        // Immediately drop all connections
        while let Ok((_stream, _)) = listener.accept().await {
            // Don't process the connection
        }
    });

    format!("ws://{}", addr)
}

#[tokio::test]
async fn test_ws_depth_stream_receives_messages() {
    let messages = vec![
        json!({
            "action": "subscribe_depth_update",
            "market_id": "market1",
            "view": {
                "buys": [{"price": "100", "quantity": "10"}],
                "sells": []
            }
        }),
        json!({
            "action": "subscribe_depth",
            "market_id": "market1",
            "changes": {
                "buys": [{"price": "101", "quantity": "5"}],
                "sells": []
            }
        }),
        json!({
            "action": "subscribe_depth_update",
            "market_id": "market1",
            "view": {
                "buys": [{"price": "102", "quantity": "8"}],
                "sells": []
            }
        }),
    ];

    let url = create_messaging_mock_server(messages).await;
    let ws = O2WebSocket::connect(&url).await.unwrap();
    let mut stream = ws
        .stream_depth("market1", &DepthPrecision::new(1).unwrap())
        .await
        .unwrap();

    // Receive all 3 messages
    let mut received = vec![];
    for _ in 0..3 {
        if let Some(update) = tokio::time::timeout(Duration::from_secs(2), stream.next())
            .await
            .ok()
            .flatten()
        {
            received.push(update.unwrap());
        }
    }

    assert_eq!(received.len(), 3, "Should receive 3 depth updates");
    assert!(
        received[0].view.is_some() || received[0].changes.is_some(),
        "First update should have view or changes"
    );

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_orders_stream_receives_messages() {
    let messages = vec![json!({
        "action": "subscribe_orders",
        "orders": [{
            "order_id": "order123",
            "market_id": "market1",
            "side": "buy",
            "price": "100",
            "quantity": "10"
        }],
        "onchain_timestamp": "1234567890",
        "seen_timestamp": "1234567891"
    })];

    let url = create_messaging_mock_server(messages).await;
    let ws = O2WebSocket::connect(&url).await.unwrap();
    let identity = Identity::Address("test_address".to_string());
    let mut stream = ws.stream_orders(&[identity]).await.unwrap();

    let update = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .ok()
        .flatten();

    assert!(update.is_some(), "Should receive order update");
    let update = update.unwrap().unwrap();
    assert_eq!(update.action, "subscribe_orders");
    assert!(!update.orders.is_empty(), "Should have orders");

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_trades_stream_receives_messages() {
    let messages = vec![json!({
        "action": "subscribe_trades",
        "trades": [{
            "trade_id": "trade123",
            "price": "100",
            "quantity": "5",
            "timestamp": "1234567890"
        }],
        "market_id": "market1",
        "onchain_timestamp": "1234567890",
        "seen_timestamp": "1234567891"
    })];

    let url = create_messaging_mock_server(messages).await;
    let ws = O2WebSocket::connect(&url).await.unwrap();
    let mut stream = ws.stream_trades("market1").await.unwrap();

    let update = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .ok()
        .flatten();

    assert!(update.is_some(), "Should receive trade update");
    let update = update.unwrap().unwrap();
    assert_eq!(update.action, "subscribe_trades");
    assert_eq!(update.market_id.as_str(), "market1");

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_balances_stream_receives_messages() {
    let messages = vec![json!({
        "action": "subscribe_balances",
        "balance": [{
            "identity": {"Address": "test_address"},
            "asset_id": "asset123",
            "total_locked": "100",
            "total_unlocked": "200",
            "trading_account_balance": "300"
        }],
        "onchain_timestamp": "1234567890",
        "seen_timestamp": "1234567891"
    })];

    let url = create_messaging_mock_server(messages).await;
    let ws = O2WebSocket::connect(&url).await.unwrap();
    let identity = Identity::Address("test_address".to_string());
    let mut stream = ws.stream_balances(&[identity]).await.unwrap();

    let update = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .ok()
        .flatten();

    assert!(update.is_some(), "Should receive balance update");
    let update = update.unwrap().unwrap();
    assert_eq!(update.action, "subscribe_balances");
    assert!(!update.balance.is_empty(), "Should have balance entries");

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_nonce_stream_receives_messages() {
    let messages = vec![json!({
        "action": "subscribe_nonce",
        "contract_id": "contract123",
        "nonce": "42",
        "onchain_timestamp": "1234567890",
        "seen_timestamp": "1234567891"
    })];

    let url = create_messaging_mock_server(messages).await;
    let ws = O2WebSocket::connect(&url).await.unwrap();
    let identity = Identity::Address("test_address".to_string());
    let mut stream = ws.stream_nonce(&[identity]).await.unwrap();

    let update = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .ok()
        .flatten();

    assert!(update.is_some(), "Should receive nonce update");
    let update = update.unwrap().unwrap();
    assert_eq!(update.action, "subscribe_nonce");
    assert_eq!(update.nonce, 42);

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_reconnect_on_server_disconnect() {
    let first_messages = vec![json!({
        "action": "subscribe_depth",
        "market_id": "market1",
        "view": {"buys": [], "sells": []}
    })];

    let second_messages = vec![json!({
        "action": "subscribe_depth_update",
        "market_id": "market1",
        "view": {"buys": [{"price": "200", "quantity": "20"}], "sells": []}
    })];

    let url = create_reconnect_mock_server(first_messages, second_messages).await;

    let config = WsConfig {
        base_delay: Duration::from_millis(100),
        max_delay: Duration::from_millis(500),
        max_attempts: 3,
        ping_interval: Duration::from_secs(1),
        pong_timeout: Duration::from_secs(2),
    };

    let ws = O2WebSocket::connect_with_config(&url, config)
        .await
        .unwrap();
    let mut stream = ws
        .stream_depth("market1", &DepthPrecision::new(1).unwrap())
        .await
        .unwrap();
    let mut lifecycle = ws.subscribe_lifecycle();

    // Receive first message
    let first = tokio::time::timeout(Duration::from_secs(2), stream.next())
        .await
        .ok()
        .flatten();
    assert!(first.is_some(), "Should receive first message");

    // Wait for reconnection and second message.
    tokio::time::sleep(Duration::from_millis(500)).await;
    let second = tokio::time::timeout(Duration::from_secs(3), stream.next())
        .await
        .ok()
        .flatten()
        .and_then(Result::ok);
    assert!(second.is_some(), "Should receive message after reconnect");
    let mut reconnect_evt = None;
    for _ in 0..5 {
        let evt = tokio::time::timeout(Duration::from_secs(2), lifecycle.recv())
            .await
            .ok()
            .and_then(Result::ok);
        if evt
            .as_ref()
            .is_some_and(|e| matches!(e, WsLifecycleEvent::Reconnected { .. }))
        {
            reconnect_evt = evt;
            break;
        }
    }
    assert!(
        reconnect_evt
            .as_ref()
            .is_some_and(|evt| matches!(evt, WsLifecycleEvent::Reconnected { .. })),
        "Should emit reconnected lifecycle event"
    );

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_reconnect_resubscribes() {
    // This test verifies that both subscriptions are re-sent on reconnect.
    // We'll track subscription messages received by the server.
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("ws://{}", addr);
    let subscriptions_received = Arc::new(Mutex::new(Vec::new()));
    let subs_clone = subscriptions_received.clone();

    tokio::spawn(async move {
        let mut connection_num = 0;
        loop {
            if let Ok((stream, _)) = listener.accept().await {
                connection_num += 1;
                let is_first = connection_num == 1;
                let subs = subs_clone.clone();

                if let Ok(ws_stream) = accept_async(stream).await {
                    let (mut sender, mut receiver) = ws_stream.split();

                    // Collect subscription messages
                    let mut message_count = 0;
                    while let Some(Ok(msg)) = receiver.next().await {
                        match msg {
                            WsMsg::Text(text) => {
                                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
                                    if let Some(action) =
                                        json.get("action").and_then(|a| a.as_str())
                                    {
                                        subs.lock().await.push(action.to_string());
                                        message_count += 1;

                                        // After receiving 2 subscription messages on first connection, close it
                                        if is_first && message_count >= 2 {
                                            tokio::time::sleep(Duration::from_millis(100)).await;
                                            let _ = sender.send(WsMsg::Close(None)).await;
                                            break;
                                        }
                                    }
                                }
                            }
                            WsMsg::Ping(data) => {
                                let _ = sender.send(WsMsg::Pong(data)).await;
                            }
                            WsMsg::Close(_) => break,
                            _ => {}
                        }
                    }
                }
            }
        }
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    let config = WsConfig {
        base_delay: Duration::from_millis(100),
        max_delay: Duration::from_millis(500),
        max_attempts: 5,
        ping_interval: Duration::from_secs(10),
        pong_timeout: Duration::from_secs(20),
    };

    let ws = O2WebSocket::connect_with_config(&url, config)
        .await
        .unwrap();
    let _stream1 = ws
        .stream_depth("market1", &DepthPrecision::new(1).unwrap())
        .await
        .unwrap();
    let _stream2 = ws.stream_trades("market1").await.unwrap();

    // Wait for initial subscriptions and reconnection
    tokio::time::sleep(Duration::from_secs(2)).await;

    // Verify both subscriptions were re-sent after reconnect
    let subs = subscriptions_received.lock().await;
    let depth_count = subs.iter().filter(|s| *s == "subscribe_depth").count();
    let trades_count = subs.iter().filter(|s| *s == "subscribe_trades").count();

    assert!(
        depth_count >= 2,
        "Depth subscription should be sent twice (initial + reconnect), got {}",
        depth_count
    );
    assert!(
        trades_count >= 2,
        "Trades subscription should be sent twice (initial + reconnect), got {}",
        trades_count
    );

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_max_reconnect_attempts_exhausted() {
    let url = create_refusing_mock_server().await;

    let config = WsConfig {
        base_delay: Duration::from_millis(50),
        max_delay: Duration::from_millis(100),
        max_attempts: 2,
        ping_interval: Duration::from_secs(10),
        pong_timeout: Duration::from_secs(20),
    };

    // Connection will fail because server refuses connections
    let result = O2WebSocket::connect_with_config(&url, config).await;
    assert!(result.is_err(), "Should fail to connect to refusing server");
}

#[tokio::test]
async fn test_ws_disconnect_closes_streams() {
    let messages = vec![json!({
        "action": "subscribe_depth",
        "market_id": "market1",
        "view": {"buys": [], "sells": []}
    })];

    let url = create_messaging_mock_server(messages).await;
    let ws = O2WebSocket::connect(&url).await.unwrap();
    let mut stream = ws
        .stream_depth("market1", &DepthPrecision::new(1).unwrap())
        .await
        .unwrap();

    assert!(ws.is_connected(), "Should be connected");

    // Disconnect
    let _ = ws.disconnect().await;

    // Wait a bit for disconnect to propagate
    tokio::time::sleep(Duration::from_millis(100)).await;

    assert!(
        !ws.is_connected(),
        "Should not be connected after disconnect"
    );

    // Stream should return None after disconnect
    let next = stream.next().await;
    assert!(next.is_none(), "Stream should be closed after disconnect");
}

#[tokio::test]
async fn test_ws_multiple_subscribers_same_type() {
    let messages = vec![json!({
        "action": "subscribe_depth",
        "market_id": "market1",
        "view": {"buys": [{"price": "100", "quantity": "10"}], "sells": []}
    })];

    let url = create_messaging_mock_server(messages).await;
    let ws = O2WebSocket::connect(&url).await.unwrap();

    // Create two streams for the same subscription type
    let mut stream1 = ws
        .stream_depth("market1", &DepthPrecision::new(1).unwrap())
        .await
        .unwrap();
    let mut stream2 = ws
        .stream_depth("market1", &DepthPrecision::new(1).unwrap())
        .await
        .unwrap();

    // Both streams should receive the message
    let update1 = tokio::time::timeout(Duration::from_secs(2), stream1.next())
        .await
        .ok()
        .flatten();
    let update2 = tokio::time::timeout(Duration::from_secs(2), stream2.next())
        .await
        .ok()
        .flatten();

    assert!(update1.is_some(), "First stream should receive update");
    assert!(update2.is_some(), "Second stream should receive update");

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_unsubscribe_removes_tracking() {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("ws://{}", addr);
    let subscriptions = Arc::new(Mutex::new(Vec::new()));
    let subs_clone = subscriptions.clone();

    tokio::spawn(async move {
        let mut connection_num = 0;
        loop {
            if let Ok((stream, _)) = listener.accept().await {
                connection_num += 1;
                let is_first = connection_num == 1;
                let subs = subs_clone.clone();

                if let Ok(ws_stream) = accept_async(stream).await {
                    let (mut sender, mut receiver) = ws_stream.split();

                    while let Some(Ok(msg)) = receiver.next().await {
                        match msg {
                            WsMsg::Text(text) => {
                                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
                                    if let Some(action) =
                                        json.get("action").and_then(|a| a.as_str())
                                    {
                                        if connection_num == 2 {
                                            // Only track subscriptions on reconnect
                                            subs.lock().await.push(action.to_string());
                                        }
                                    }
                                }
                            }
                            WsMsg::Ping(data) => {
                                let _ = sender.send(WsMsg::Pong(data)).await;
                            }
                            WsMsg::Close(_) => break,
                            _ => {}
                        }
                    }

                    if is_first {
                        // Drop first connection after a delay
                        tokio::time::sleep(Duration::from_millis(300)).await;
                        let _ = sender.send(WsMsg::Close(None)).await;
                    }
                }
            }
        }
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    let config = WsConfig {
        base_delay: Duration::from_millis(100),
        max_delay: Duration::from_millis(500),
        max_attempts: 5,
        ping_interval: Duration::from_secs(10),
        pong_timeout: Duration::from_secs(20),
    };

    let ws = O2WebSocket::connect_with_config(&url, config)
        .await
        .unwrap();
    let _stream = ws
        .stream_depth("market1", &DepthPrecision::new(1).unwrap())
        .await
        .unwrap();

    tokio::time::sleep(Duration::from_millis(100)).await;

    // Unsubscribe before reconnect
    let _ = ws.unsubscribe_depth("market1").await;

    // Wait for reconnection to happen
    tokio::time::sleep(Duration::from_secs(2)).await;

    // Verify depth subscription was NOT re-sent on reconnect
    let subs = subscriptions.lock().await;
    assert!(
        !subs.contains(&"subscribe_depth".to_string()),
        "Depth subscription should not be re-sent after unsubscribe"
    );

    let _ = ws.disconnect().await;
}

#[tokio::test]
async fn test_ws_is_connected_state() {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("ws://{}", addr);

    tokio::spawn(async move {
        let mut connection_num = 0;
        loop {
            if let Ok((stream, _)) = listener.accept().await {
                connection_num += 1;
                let is_first = connection_num == 1;

                if let Ok(ws_stream) = accept_async(stream).await {
                    let (mut sender, mut receiver) = ws_stream.split();

                    if is_first {
                        // Drop first connection quickly
                        tokio::time::sleep(Duration::from_millis(50)).await;
                        let _ = sender.send(WsMsg::Close(None)).await;
                        continue;
                    }

                    // Keep subsequent connections alive
                    while let Some(Ok(msg)) = receiver.next().await {
                        match msg {
                            WsMsg::Ping(data) => {
                                let _ = sender.send(WsMsg::Pong(data)).await;
                            }
                            WsMsg::Close(_) => break,
                            _ => {}
                        }
                    }
                }
            }
        }
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    let config = WsConfig {
        base_delay: Duration::from_millis(100),
        max_delay: Duration::from_millis(500),
        max_attempts: 5,
        ping_interval: Duration::from_secs(10),
        pong_timeout: Duration::from_secs(20),
    };

    let ws = O2WebSocket::connect_with_config(&url, config)
        .await
        .unwrap();

    assert!(ws.is_connected(), "Should be connected after connect");

    // Wait for disconnect to be detected (server drops immediately, client needs time to notice)
    tokio::time::sleep(Duration::from_millis(500)).await;

    // The connection should be disconnected OR in the process of reconnecting
    // We'll wait for the reconnection to complete
    tokio::time::sleep(Duration::from_millis(500)).await;

    // After reconnection, should be connected again
    assert!(
        ws.is_connected(),
        "Should be connected again after reconnect"
    );

    // Explicit disconnect
    let _ = ws.disconnect().await;
    tokio::time::sleep(Duration::from_millis(100)).await;
    assert!(
        !ws.is_connected(),
        "Should be disconnected after explicit disconnect"
    );
}

#[tokio::test]
async fn test_ws_server_ping_response() {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("ws://{}", addr);
    let pong_received = Arc::new(Mutex::new(false));
    let pong_clone = pong_received.clone();

    tokio::spawn(async move {
        if let Ok((stream, _)) = listener.accept().await {
            if let Ok(ws_stream) = accept_async(stream).await {
                let (mut sender, mut receiver) = ws_stream.split();

                // Send a ping
                let _ = sender.send(WsMsg::Ping(vec![1, 2, 3])).await;

                // Wait for pong
                while let Some(Ok(msg)) = receiver.next().await {
                    if matches!(msg, WsMsg::Pong(_)) {
                        *pong_clone.lock().await = true;
                        break;
                    }
                }

                // Keep connection alive briefly
                tokio::time::sleep(Duration::from_secs(1)).await;
            }
        }
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    let ws = O2WebSocket::connect(&url).await.unwrap();

    // Wait for ping/pong exchange
    tokio::time::sleep(Duration::from_millis(500)).await;

    let pong = *pong_received.lock().await;
    assert!(pong, "Client should respond to server ping with pong");

    let _ = ws.disconnect().await;
}