strata-web-api 0.1.2

W3C Web Platform APIs in pure idiomatic Rust for Strata
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
//! Pure-Rust W3C WebSocket Client with RFC 6455 Frame Serialization, Handshake & TLS (`wss://`).
//!
//! Provides:
//! - Complete RFC 6455 frame encoding and decoding with masking and control frame processing.
//! - Cryptographic `Sec-WebSocket-Key` generation and SHA-1 `Sec-WebSocket-Accept` validation.
//! - Native TLS transport for `wss://` connections via Mozilla WebPKI root certificates and `rustls`.
//! - Asynchronous background worker stream reading, heartbeat Ping/Pong processing, and queueing.

use std::collections::VecDeque;
use std::fmt;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::tls::{create_tls_stream, HttpTransportStream};

const WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

/// Maximum default frame payload size before automatically fragmenting (64 KB).
pub const DEFAULT_MAX_FRAME_SIZE: usize = 65536;

/// RFC 6455 WebSocket Opcode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WsOpcode {
    Continuation = 0x0,
    Text = 0x1,
    Binary = 0x2,
    Close = 0x8,
    Ping = 0x9,
    Pong = 0xA,
}

impl WsOpcode {
    pub fn from_u8(val: u8) -> Option<Self> {
        match val {
            0x0 => Some(Self::Continuation),
            0x1 => Some(Self::Text),
            0x2 => Some(Self::Binary),
            0x8 => Some(Self::Close),
            0x9 => Some(Self::Ping),
            0xA => Some(Self::Pong),
            _ => None,
        }
    }

    pub fn is_control(&self) -> bool {
        matches!(self, Self::Close | Self::Ping | Self::Pong)
    }
}

/// Errors occurring during WebSocket communication.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsError {
    InvalidUrl(String),
    InvalidState(String),
    HandshakeFailed(String),
    ProtocolError(String),
    InvalidFrame(String),
    NetworkError(String),
    Closed,
}

impl fmt::Display for WsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidUrl(s) => write!(f, "Invalid WebSocket URL: {s}"),
            Self::InvalidState(s) => write!(f, "Invalid WebSocket state: {s}"),
            Self::HandshakeFailed(s) => write!(f, "WebSocket handshake failed: {s}"),
            Self::ProtocolError(s) => write!(f, "WebSocket protocol error: {s}"),
            Self::InvalidFrame(s) => write!(f, "Invalid WebSocket frame: {s}"),
            Self::NetworkError(s) => write!(f, "WebSocket network error: {s}"),
            Self::Closed => write!(f, "WebSocket is already closed"),
        }
    }
}

impl std::error::Error for WsError {}

/// State of the WebSocket connection per W3C specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WsState {
    Connecting = 0,
    Open = 1,
    Closing = 2,
    Closed = 3,
}

/// A decoded RFC 6455 WebSocket frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WsFrame {
    pub fin: bool,
    pub opcode: WsOpcode,
    pub payload: Vec<u8>,
    pub masked: bool,
}

/// High-level WebSocket message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsMessage {
    Text(String),
    Binary(Vec<u8>),
    Ping(Vec<u8>),
    Pong(Vec<u8>),
    Close(Option<u16>, String),
}

/// Computes FIPS 180-1 SHA-1 digest in pure Rust.
pub fn sha1(data: &[u8]) -> [u8; 20] {
    let mut h0 = 0x67452301u32;
    let mut h1 = 0xEFCDAB89u32;
    let mut h2 = 0x98BADCFEu32;
    let mut h3 = 0x10325476u32;
    let mut h4 = 0xC3D2E1F0u32;

    let mut msg = data.to_vec();
    let bit_len = (data.len() as u64) * 8;
    msg.push(0x80);
    while (msg.len() % 64) != 56 {
        msg.push(0x00);
    }
    msg.extend_from_slice(&bit_len.to_be_bytes());

    for chunk in msg.as_chunks::<64>().0 {
        let mut w = [0u32; 80];
        for i in 0..16 {
            w[i] = u32::from_be_bytes([
                chunk[i * 4],
                chunk[i * 4 + 1],
                chunk[i * 4 + 2],
                chunk[i * 4 + 3],
            ]);
        }
        for i in 16..80 {
            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
        }

        let mut a = h0;
        let mut b = h1;
        let mut c = h2;
        let mut d = h3;
        let mut e = h4;

        for (i, &w_i) in w.iter().enumerate() {
            let (f, k) = match i {
                0..=19 => ((b & c) | ((!b) & d), 0x5A827999u32),
                20..=39 => (b ^ c ^ d, 0x6ED9EBA1u32),
                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDCu32),
                _ => (b ^ c ^ d, 0xCA62C1D6u32),
            };
            let temp = a
                .rotate_left(5)
                .wrapping_add(f)
                .wrapping_add(e)
                .wrapping_add(k)
                .wrapping_add(w_i);
            e = d;
            d = c;
            c = b.rotate_left(30);
            b = a;
            a = temp;
        }

        h0 = h0.wrapping_add(a);
        h1 = h1.wrapping_add(b);
        h2 = h2.wrapping_add(c);
        h3 = h3.wrapping_add(d);
        h4 = h4.wrapping_add(e);
    }

    let mut out = [0u8; 20];
    out[0..4].copy_from_slice(&h0.to_be_bytes());
    out[4..8].copy_from_slice(&h1.to_be_bytes());
    out[8..12].copy_from_slice(&h2.to_be_bytes());
    out[12..16].copy_from_slice(&h3.to_be_bytes());
    out[16..20].copy_from_slice(&h4.to_be_bytes());
    out
}

/// Standard base64 encoding.
pub fn base64_encode(data: &[u8]) -> String {
    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);

    for chunk in data.chunks(3) {
        let b0 = chunk[0] as usize;
        let b1 = chunk.get(1).copied().unwrap_or(0) as usize;
        let b2 = chunk.get(2).copied().unwrap_or(0) as usize;

        let triple = (b0 << 16) | (b1 << 8) | b2;

        out.push(TABLE[(triple >> 18) & 0x3F] as char);
        out.push(TABLE[(triple >> 12) & 0x3F] as char);

        if chunk.len() > 1 {
            out.push(TABLE[(triple >> 6) & 0x3F] as char);
        } else {
            out.push('=');
        }

        if chunk.len() > 2 {
            out.push(TABLE[triple & 0x3F] as char);
        } else {
            out.push('=');
        }
    }

    out
}

/// Computes the expected RFC 6455 `Sec-WebSocket-Accept` header value from client key.
pub fn compute_sec_websocket_accept(key: &str) -> String {
    let mut concat = key.trim().as_bytes().to_vec();
    concat.extend_from_slice(WS_GUID.as_bytes());
    let digest = sha1(&concat);
    base64_encode(&digest)
}

/// Fills a buffer with cryptographically secure pseudo-random bytes.
///
/// Uses `ring::rand::SystemRandom` backed by the OS CSPRNG, with fallbacks to `getrandom`
/// and `/dev/urandom` on Unix. Panics on total entropy failure rather than falling back to
/// predictable timestamps (preventing RFC 6455 §5.3 cache poisoning attacks).
fn fill_secure_random(buf: &mut [u8]) {
    use ring::rand::SecureRandom;
    let rng = ring::rand::SystemRandom::new();
    if rng.fill(buf).is_ok() {
        return;
    }

    if getrandom::getrandom(buf).is_ok() {
        return;
    }

    #[cfg(unix)]
    {
        if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
            if f.read_exact(buf).is_ok() {
                return;
            }
        }
    }

    panic!("RFC 6455 CSPRNG failure: unable to obtain secure cryptographic entropy for WebSocket operations");
}

/// Generates a cryptographically random 16-byte base64 nonce for `Sec-WebSocket-Key` (RFC 6455 §4.1).
pub fn generate_sec_websocket_key() -> String {
    let mut nonce = [0u8; 16];
    fill_secure_random(&mut nonce);
    base64_encode(&nonce)
}

/// Generates an unpredictable 32-bit masking key for client frames (RFC 6455 §5.3).
pub fn generate_mask_key() -> [u8; 4] {
    let mut key = [0u8; 4];
    fill_secure_random(&mut key);
    key
}

/// Encodes an RFC 6455 frame into bytes.
pub fn encode_frame(
    fin: bool,
    opcode: WsOpcode,
    payload: &[u8],
    masked: bool,
    mask_key: Option<[u8; 4]>,
) -> Vec<u8> {
    let mut frame = Vec::new();

    let byte0 = if fin { 0x80 } else { 0x00 } | (opcode as u8 & 0x0F);
    frame.push(byte0);

    let mask_bit = if masked { 0x80 } else { 0x00 };
    let len = payload.len();

    if len < 126 {
        frame.push(mask_bit | (len as u8));
    } else if len <= 0xFFFF {
        frame.push(mask_bit | 126);
        frame.extend_from_slice(&(len as u16).to_be_bytes());
    } else {
        frame.push(mask_bit | 127);
        frame.extend_from_slice(&(len as u64).to_be_bytes());
    }

    if masked {
        let key = mask_key.unwrap_or_else(generate_mask_key);
        frame.extend_from_slice(&key);
        for (i, &b) in payload.iter().enumerate() {
            frame.push(b ^ key[i % 4]);
        }
    } else {
        frame.extend_from_slice(payload);
    }

    frame
}

/// Decodes an RFC 6455 frame from a byte buffer.
pub fn decode_frame(buf: &[u8]) -> Result<Option<(WsFrame, usize)>, WsError> {
    if buf.len() < 2 {
        return Ok(None);
    }

    let byte0 = buf[0];
    let fin = (byte0 & 0x80) != 0;
    let opcode_raw = byte0 & 0x0F;
    let opcode = WsOpcode::from_u8(opcode_raw)
        .ok_or_else(|| WsError::InvalidFrame(format!("Unknown opcode: 0x{opcode_raw:X}")))?;

    let byte1 = buf[1];
    let masked = (byte1 & 0x80) != 0;
    let payload_indicator = byte1 & 0x7F;

    let mut cursor = 2;

    let payload_len: usize = if payload_indicator < 126 {
        payload_indicator as usize
    } else if payload_indicator == 126 {
        if opcode.is_control() {
            return Err(WsError::ProtocolError(
                "Control frames must not have payload length > 125 bytes (RFC 6455 §5.5)".into(),
            ));
        }
        if buf.len() < cursor + 2 {
            return Ok(None);
        }
        let len_bytes: [u8; 2] = [buf[cursor], buf[cursor + 1]];
        cursor += 2;
        u16::from_be_bytes(len_bytes) as usize
    } else {
        if opcode.is_control() {
            return Err(WsError::ProtocolError(
                "Control frames must not have payload length > 125 bytes (RFC 6455 §5.5)".into(),
            ));
        }
        if buf.len() < cursor + 8 {
            return Ok(None);
        }
        let mut len_bytes = [0u8; 8];
        len_bytes.copy_from_slice(&buf[cursor..cursor + 8]);
        cursor += 8;
        u64::from_be_bytes(len_bytes) as usize
    };

    if opcode.is_control() && !fin {
        return Err(WsError::ProtocolError(
            "Control frames must not be fragmented (FIN must be true, RFC 6455 §5.5)".into(),
        ));
    }

    let mask_key = if masked {
        if buf.len() < cursor + 4 {
            return Ok(None);
        }
        let key = [
            buf[cursor],
            buf[cursor + 1],
            buf[cursor + 2],
            buf[cursor + 3],
        ];
        cursor += 4;
        Some(key)
    } else {
        None
    };

    if buf.len() < cursor + payload_len {
        return Ok(None);
    }

    let mut payload = buf[cursor..cursor + payload_len].to_vec();
    if let Some(key) = mask_key {
        for (i, b) in payload.iter_mut().enumerate() {
            *b ^= key[i % 4];
        }
    }

    cursor += payload_len;

    Ok(Some((
        WsFrame {
            fin,
            opcode,
            payload,
            masked,
        },
        cursor,
    )))
}

#[derive(Debug, Clone)]
struct ParsedWsUrl {
    is_secure: bool,
    host: String,
    port: u16,
    path: String,
}

fn parse_ws_url(url: &str) -> Result<ParsedWsUrl, WsError> {
    let (is_secure, rest) = if let Some(s) = url.strip_prefix("wss://") {
        (true, s)
    } else if let Some(s) = url.strip_prefix("ws://") {
        (false, s)
    } else {
        return Err(WsError::InvalidUrl(format!(
            "URL must start with ws:// or wss://: {url}"
        )));
    };

    let (host_port, path) = match rest.find('/') {
        Some(pos) => (&rest[..pos], &rest[pos..]),
        None => (rest, "/"),
    };

    let (host, port) = match host_port.find(':') {
        Some(pos) => {
            let h = &host_port[..pos];
            let p = host_port[pos + 1..]
                .parse::<u16>()
                .map_err(|e| WsError::InvalidUrl(format!("Invalid port: {e}")))?;
            (h.to_string(), p)
        }
        None => {
            let p = if is_secure { 443 } else { 80 };
            (host_port.to_string(), p)
        }
    };

    Ok(ParsedWsUrl {
        is_secure,
        host,
        port,
        path: path.to_string(),
    })
}

/// Ongoing fragmented message tracking state.
#[derive(Debug, Clone)]
pub struct WsFragment {
    pub opcode: WsOpcode,
    pub buffer: Vec<u8>,
}

/// W3C WebSocket client interface supporting `ws://` and TLS `wss://`.
#[derive(Clone)]
pub struct WebSocket {
    pub url: String,
    state: Arc<Mutex<WsState>>,
    outgoing_queue: Arc<Mutex<Vec<Vec<u8>>>>,
    received_messages: Arc<Mutex<VecDeque<WsMessage>>>,
    closed_flag: Arc<AtomicBool>,
    fragment_state: Arc<Mutex<Option<WsFragment>>>,
    worker_handle: Arc<Mutex<Option<std::thread::JoinHandle<()>>>>,
}

impl WebSocket {
    /// Creates an in-memory/mock WebSocket for offline testing.
    pub fn new(url: &str) -> Self {
        Self {
            url: url.to_string(),
            state: Arc::new(Mutex::new(WsState::Connecting)),
            outgoing_queue: Arc::new(Mutex::new(Vec::new())),
            received_messages: Arc::new(Mutex::new(VecDeque::new())),
            closed_flag: Arc::new(AtomicBool::new(false)),
            fragment_state: Arc::new(Mutex::new(None)),
            worker_handle: Arc::new(Mutex::new(None)),
        }
    }

    /// Establishes a real RFC 6455 WebSocket connection over plain TCP (`ws://`) or TLS (`wss://`).
    pub fn connect(url: &str) -> Result<Self, WsError> {
        let parsed = parse_ws_url(url)?;
        let addr = format!("{}:{}", parsed.host, parsed.port);

        let tcp = TcpStream::connect_timeout(
            &addr
                .parse()
                .or_else(|_| {
                    use std::net::ToSocketAddrs;
                    addr.to_socket_addrs()
                        .map_err(std::io::Error::other)?
                        .next()
                        .ok_or_else(|| {
                            std::io::Error::new(
                                std::io::ErrorKind::NotFound,
                                "Host resolution failed",
                            )
                        })
                })
                .map_err(|e| WsError::NetworkError(format!("DNS/Socket resolution error: {e}")))?,
            Duration::from_secs(10),
        )
        .map_err(|e| WsError::NetworkError(format!("TCP connection failed: {e}")))?;

        let mut transport = if parsed.is_secure {
            create_tls_stream(tcp, &parsed.host)
                .map_err(|e| WsError::NetworkError(format!("TLS handshake failed: {e}")))?
        } else {
            HttpTransportStream::Plain(tcp)
        };

        // HTTP/1.1 Upgrade Handshake
        let sec_key = generate_sec_websocket_key();
        let expected_accept = compute_sec_websocket_accept(&sec_key);

        let handshake_req = format!(
            "GET {} HTTP/1.1\r\n\
             Host: {}:{}\r\n\
             Upgrade: websocket\r\n\
             Connection: Upgrade\r\n\
             Sec-WebSocket-Key: {}\r\n\
             Sec-WebSocket-Version: 13\r\n\
             User-Agent: Strata/0.1.0\r\n\r\n",
            parsed.path, parsed.host, parsed.port, sec_key
        );

        transport.write_all(handshake_req.as_bytes()).map_err(|e| {
            WsError::NetworkError(format!("Failed to write handshake request: {e}"))
        })?;
        transport.flush().map_err(|e| {
            WsError::NetworkError(format!("Failed to flush handshake request: {e}"))
        })?;

        // Read handshake response
        let mut response_buf = Vec::new();
        let mut temp_buf = [0u8; 1024];
        let mut accept_validated = false;

        let initial_data = loop {
            let n = transport.read(&mut temp_buf).map_err(|e| {
                WsError::NetworkError(format!("Error reading handshake response: {e}"))
            })?;
            if n == 0 {
                return Err(WsError::HandshakeFailed(
                    "Connection closed by server during handshake".into(),
                ));
            }
            response_buf.extend_from_slice(&temp_buf[..n]);

            if let Some(pos) = response_buf.windows(4).position(|w| w == b"\r\n\r\n") {
                let header_str = String::from_utf8_lossy(&response_buf[..pos]);
                if !header_str.starts_with("HTTP/1.1 101")
                    && !header_str.starts_with("HTTP/1.0 101")
                {
                    return Err(WsError::HandshakeFailed(format!(
                        "Server returned non-101 status: {}",
                        header_str.lines().next().unwrap_or("")
                    )));
                }

                for line in header_str.lines() {
                    if let Some((name, val)) = line.split_once(':') {
                        if name.trim().eq_ignore_ascii_case("sec-websocket-accept") {
                            if val.trim() == expected_accept {
                                accept_validated = true;
                            } else {
                                return Err(WsError::ProtocolError(format!(
                                    "Sec-WebSocket-Accept mismatch: expected {expected_accept}, got {}",
                                    val.trim()
                                )));
                            }
                        }
                    }
                }
                let initial_data = response_buf[pos + 4..].to_vec();
                break initial_data;
            }
        };

        if !accept_validated {
            return Err(WsError::ProtocolError(
                "Missing Sec-WebSocket-Accept header in response".into(),
            ));
        }

        let ws = Self {
            url: url.to_string(),
            state: Arc::new(Mutex::new(WsState::Open)),
            outgoing_queue: Arc::new(Mutex::new(Vec::new())),
            received_messages: Arc::new(Mutex::new(VecDeque::new())),
            closed_flag: Arc::new(AtomicBool::new(false)),
            fragment_state: Arc::new(Mutex::new(None)),
            worker_handle: Arc::new(Mutex::new(None)),
        };

        // Configure socket options for low latency and non-blocking worker polling
        let _ = transport.set_nodelay(true);
        let _ = transport.set_read_timeout(Some(Duration::from_millis(15)));
        let _ = transport.set_write_timeout(Some(Duration::from_secs(10)));

        // Spawn background worker thread managing stream I/O
        let worker_state = ws.state.clone();
        let worker_outgoing = ws.outgoing_queue.clone();
        let worker_received = ws.received_messages.clone();
        let worker_closed = ws.closed_flag.clone();
        let worker_fragment = ws.fragment_state.clone();

        let handle = std::thread::Builder::new()
            .name("strata-ws-worker".into())
            .spawn(move || {
                let mut read_buf = initial_data;
                let mut temp = [0u8; 4096];
                let mut last_ping = std::time::Instant::now();
                let ping_interval = Duration::from_secs(30);

                while !worker_closed.load(Ordering::Relaxed) {
                    // 1. Drain and send outgoing frames
                    let outgoing = worker_outgoing
                        .lock()
                        .map(|mut q| std::mem::take(&mut *q))
                        .unwrap_or_default();

                    for frame in outgoing {
                        if transport.write_all(&frame).is_err() || transport.flush().is_err() {
                            worker_closed.store(true, Ordering::Relaxed);
                            break;
                        }
                    }

                    if worker_closed.load(Ordering::Relaxed) {
                        break;
                    }

                    // 2. Send periodic RFC 6455 Ping heartbeat
                    if last_ping.elapsed() >= ping_interval {
                        let ping =
                            encode_frame(true, WsOpcode::Ping, b"strata-heartbeat", true, None);
                        if transport.write_all(&ping).is_err() || transport.flush().is_err() {
                            worker_closed.store(true, Ordering::Relaxed);
                            break;
                        }
                        last_ping = std::time::Instant::now();
                    }

                    // 3. Read incoming frames with non-blocking 15ms window
                    match transport.read(&mut temp) {
                        Ok(0) => {
                            worker_closed.store(true, Ordering::Relaxed);
                            break;
                        }
                        Ok(n) => {
                            read_buf.extend_from_slice(&temp[..n]);
                        }
                        Err(ref e)
                            if e.kind() == std::io::ErrorKind::WouldBlock
                                || e.kind() == std::io::ErrorKind::TimedOut =>
                        {
                            // Non-fatal read timeout: continue to process read_buf and service outgoing queue
                        }
                        Err(_) => {
                            worker_closed.store(true, Ordering::Relaxed);
                            break;
                        }
                    }

                    // 4. Drain and process all complete frames present in read_buf
                    let mut proto_violation = false;
                    while let Ok(Some((frame, consumed))) = decode_frame(&read_buf) {
                        read_buf.drain(..consumed);

                        if frame.masked {
                            // RFC 6455 §5.1: server frames must not be masked
                            proto_violation = true;
                            break;
                        }

                        match frame.opcode {
                            WsOpcode::Text | WsOpcode::Binary => {
                                if let Ok(mut frag) = worker_fragment.lock() {
                                    if frag.is_some() {
                                        proto_violation = true;
                                        break;
                                    }
                                    if frame.fin {
                                        if frame.opcode == WsOpcode::Text {
                                            if let Ok(s) = String::from_utf8(frame.payload) {
                                                if let Ok(mut msgs) = worker_received.lock() {
                                                    msgs.push_back(WsMessage::Text(s));
                                                }
                                            }
                                        } else if let Ok(mut msgs) = worker_received.lock() {
                                            msgs.push_back(WsMessage::Binary(frame.payload));
                                        }
                                    } else {
                                        *frag = Some(WsFragment {
                                            opcode: frame.opcode,
                                            buffer: frame.payload,
                                        });
                                    }
                                }
                            }
                            WsOpcode::Continuation => {
                                let mut completed_msg = None;
                                if let Ok(mut frag_guard) = worker_fragment.lock() {
                                    if let Some(ref mut fragment) = *frag_guard {
                                        fragment.buffer.extend_from_slice(&frame.payload);
                                        if frame.fin {
                                            let fragment_val = frag_guard.take().unwrap();
                                            match fragment_val.opcode {
                                                WsOpcode::Text => {
                                                    if let Ok(s) =
                                                        String::from_utf8(fragment_val.buffer)
                                                    {
                                                        completed_msg = Some(WsMessage::Text(s));
                                                    }
                                                }
                                                WsOpcode::Binary => {
                                                    completed_msg = Some(WsMessage::Binary(
                                                        fragment_val.buffer,
                                                    ));
                                                }
                                                _ => {}
                                            }
                                        }
                                    } else {
                                        proto_violation = true;
                                        break;
                                    }
                                }
                                if let Some(msg) = completed_msg {
                                    if let Ok(mut msgs) = worker_received.lock() {
                                        msgs.push_back(msg);
                                    }
                                }
                            }
                            WsOpcode::Ping => {
                                // Auto-reply with Pong per RFC 6455 §5.5.3
                                let pong =
                                    encode_frame(true, WsOpcode::Pong, &frame.payload, true, None);
                                let _ = transport.write_all(&pong);
                                let _ = transport.flush();
                            }
                            WsOpcode::Pong => {
                                if let Ok(mut msgs) = worker_received.lock() {
                                    msgs.push_back(WsMessage::Pong(frame.payload));
                                }
                            }
                            WsOpcode::Close => {
                                // Echo close frame per RFC 6455 §5.5.1
                                let echo =
                                    encode_frame(true, WsOpcode::Close, &frame.payload, true, None);
                                let _ = transport.write_all(&echo);
                                let _ = transport.flush();

                                let (code, reason) = if frame.payload.len() >= 2 {
                                    let code =
                                        u16::from_be_bytes([frame.payload[0], frame.payload[1]]);
                                    let r =
                                        String::from_utf8_lossy(&frame.payload[2..]).to_string();
                                    (Some(code), r)
                                } else {
                                    (None, String::new())
                                };
                                if let Ok(mut msgs) = worker_received.lock() {
                                    msgs.push_back(WsMessage::Close(code, reason));
                                }
                                worker_closed.store(true, Ordering::Relaxed);
                                if let Ok(mut s) = worker_state.lock() {
                                    *s = WsState::Closed;
                                }
                                break;
                            }
                        }
                    }

                    if proto_violation {
                        let close_frame =
                            encode_frame(true, WsOpcode::Close, &1002u16.to_be_bytes(), true, None);
                        let _ = transport.write_all(&close_frame);
                        let _ = transport.flush();
                        worker_closed.store(true, Ordering::Relaxed);
                        if let Ok(mut s) = worker_state.lock() {
                            *s = WsState::Closed;
                        }
                        break;
                    }
                }

                // Final drain of any queued frames (e.g. Close frame queued by close())
                let final_outgoing = worker_outgoing
                    .lock()
                    .map(|mut q| std::mem::take(&mut *q))
                    .unwrap_or_default();
                for frame in final_outgoing {
                    let _ = transport.write_all(&frame);
                    let _ = transport.flush();
                }

                if let Ok(mut s) = worker_state.lock() {
                    *s = WsState::Closed;
                }
            })
            .map_err(|e| WsError::NetworkError(format!("Failed to spawn WebSocket thread: {e}")))?;

        if let Ok(mut handle_guard) = ws.worker_handle.lock() {
            *handle_guard = Some(handle);
        }

        Ok(ws)
    }

    /// Mark the connection as Open.
    pub fn set_open(&self) {
        if let Ok(mut s) = self.state.lock() {
            *s = WsState::Open;
        }
    }

    /// Current connection state.
    pub fn ready_state(&self) -> WsState {
        self.state.lock().map(|s| *s).unwrap_or(WsState::Closed)
    }

    /// Whether the WebSocket is open.
    pub fn is_open(&self) -> bool {
        self.ready_state() == WsState::Open
    }

    /// Sends a text message over the WebSocket. If length exceeds `DEFAULT_MAX_FRAME_SIZE`, it is fragmented.
    pub fn send_text(&self, text: &str) -> Result<(), WsError> {
        if text.len() > DEFAULT_MAX_FRAME_SIZE {
            self.send_text_fragmented(text, DEFAULT_MAX_FRAME_SIZE)
        } else {
            let state = self.ready_state();
            if state != WsState::Open {
                return Err(WsError::InvalidState(format!(
                    "Cannot send in state {state:?}"
                )));
            }

            let frame = encode_frame(true, WsOpcode::Text, text.as_bytes(), true, None);
            if let Ok(mut q) = self.outgoing_queue.lock() {
                q.push(frame);
            }
            Ok(())
        }
    }

    /// Sends binary data over the WebSocket. If length exceeds `DEFAULT_MAX_FRAME_SIZE`, it is fragmented.
    pub fn send_binary(&self, data: &[u8]) -> Result<(), WsError> {
        if data.len() > DEFAULT_MAX_FRAME_SIZE {
            self.send_binary_fragmented(data, DEFAULT_MAX_FRAME_SIZE)
        } else {
            let state = self.ready_state();
            if state != WsState::Open {
                return Err(WsError::InvalidState(format!(
                    "Cannot send in state {state:?}"
                )));
            }

            let frame = encode_frame(true, WsOpcode::Binary, data, true, None);
            if let Ok(mut q) = self.outgoing_queue.lock() {
                q.push(frame);
            }
            Ok(())
        }
    }

    /// Sends a text message split into multiple frames with given chunk size.
    pub fn send_text_fragmented(&self, text: &str, chunk_size: usize) -> Result<(), WsError> {
        self.send_payload_fragmented(WsOpcode::Text, text.as_bytes(), chunk_size)
    }

    /// Sends binary data split into multiple frames with given chunk size.
    pub fn send_binary_fragmented(&self, data: &[u8], chunk_size: usize) -> Result<(), WsError> {
        self.send_payload_fragmented(WsOpcode::Binary, data, chunk_size)
    }

    /// Helper to send payload in fragmented RFC 6455 frames.
    pub fn send_payload_fragmented(
        &self,
        opcode: WsOpcode,
        payload: &[u8],
        chunk_size: usize,
    ) -> Result<(), WsError> {
        let state = self.ready_state();
        if state != WsState::Open {
            return Err(WsError::InvalidState(format!(
                "Cannot send in state {state:?}"
            )));
        }

        let chunk_size = chunk_size.max(1);
        let chunks: Vec<&[u8]> = payload.chunks(chunk_size).collect();
        if chunks.is_empty() {
            let frame = encode_frame(true, opcode, &[], true, None);
            if let Ok(mut q) = self.outgoing_queue.lock() {
                q.push(frame);
            }
            return Ok(());
        }

        let num_chunks = chunks.len();
        for (i, chunk) in chunks.iter().enumerate() {
            let fin = i == num_chunks - 1;
            let op = if i == 0 {
                opcode
            } else {
                WsOpcode::Continuation
            };
            let frame = encode_frame(fin, op, chunk, true, None);
            if let Ok(mut q) = self.outgoing_queue.lock() {
                q.push(frame);
            }
        }
        Ok(())
    }

    /// Sends a Ping frame.
    pub fn send_ping(&self, payload: &[u8]) -> Result<(), WsError> {
        let frame = encode_frame(true, WsOpcode::Ping, payload, true, None);
        if let Ok(mut q) = self.outgoing_queue.lock() {
            q.push(frame);
        }
        Ok(())
    }

    /// Closes the WebSocket connection with status code and reason.
    pub fn close(&self, code: u16, reason: &str) -> Result<(), WsError> {
        if let Ok(mut s) = self.state.lock() {
            if *s == WsState::Closed || *s == WsState::Closing {
                return Ok(());
            }
            *s = WsState::Closing;
        }

        let mut payload = code.to_be_bytes().to_vec();
        payload.extend_from_slice(reason.as_bytes());
        let frame = encode_frame(true, WsOpcode::Close, &payload, true, None);
        if let Ok(mut q) = self.outgoing_queue.lock() {
            q.push(frame);
        }

        self.closed_flag.store(true, Ordering::Relaxed);
        if let Ok(mut s) = self.state.lock() {
            *s = WsState::Closed;
        }

        Ok(())
    }

    /// Ingests received raw bytes and decodes messages into the internal buffer.
    pub fn ingest_incoming_bytes(&self, mut buf: &[u8]) -> Result<usize, WsError> {
        let mut total_consumed = 0;
        while let Some((frame, consumed)) = decode_frame(buf)? {
            buf = &buf[consumed..];
            total_consumed += consumed;

            if frame.masked {
                return Err(WsError::ProtocolError(
                    "Frames received from server must not be masked (RFC 6455 §5.1)".into(),
                ));
            }

            match frame.opcode {
                WsOpcode::Text => {
                    if let Ok(mut frag) = self.fragment_state.lock() {
                        if frag.is_some() {
                            return Err(WsError::ProtocolError(
                                "Cannot start new data frame while fragmented frame is in progress (RFC 6455 §5.4)".into(),
                            ));
                        }
                        if frame.fin {
                            let s = String::from_utf8(frame.payload).map_err(|e| {
                                WsError::ProtocolError(format!("Invalid UTF-8 in text frame: {e}"))
                            })?;
                            if let Ok(mut msgs) = self.received_messages.lock() {
                                msgs.push_back(WsMessage::Text(s));
                            }
                        } else {
                            *frag = Some(WsFragment {
                                opcode: WsOpcode::Text,
                                buffer: frame.payload,
                            });
                        }
                    }
                }
                WsOpcode::Binary => {
                    if let Ok(mut frag) = self.fragment_state.lock() {
                        if frag.is_some() {
                            return Err(WsError::ProtocolError(
                                "Cannot start new data frame while fragmented frame is in progress (RFC 6455 §5.4)".into(),
                            ));
                        }
                        if frame.fin {
                            if let Ok(mut msgs) = self.received_messages.lock() {
                                msgs.push_back(WsMessage::Binary(frame.payload));
                            }
                        } else {
                            *frag = Some(WsFragment {
                                opcode: WsOpcode::Binary,
                                buffer: frame.payload,
                            });
                        }
                    }
                }
                WsOpcode::Continuation => {
                    let mut completed_msg = None;
                    if let Ok(mut frag_guard) = self.fragment_state.lock() {
                        if let Some(ref mut fragment) = *frag_guard {
                            fragment.buffer.extend_from_slice(&frame.payload);
                            if frame.fin {
                                let fragment_val = frag_guard.take().unwrap();
                                match fragment_val.opcode {
                                    WsOpcode::Text => {
                                        let s = String::from_utf8(fragment_val.buffer).map_err(
                                            |e| {
                                                WsError::ProtocolError(format!(
                                                    "Invalid UTF-8 in continuation frame: {e}"
                                                ))
                                            },
                                        )?;
                                        completed_msg = Some(WsMessage::Text(s));
                                    }
                                    WsOpcode::Binary => {
                                        completed_msg =
                                            Some(WsMessage::Binary(fragment_val.buffer));
                                    }
                                    _ => {}
                                }
                            }
                        } else {
                            return Err(WsError::ProtocolError(
                                "Unexpected continuation frame without initial fragmented frame"
                                    .into(),
                            ));
                        }
                    }
                    if let Some(msg) = completed_msg {
                        if let Ok(mut msgs) = self.received_messages.lock() {
                            msgs.push_back(msg);
                        }
                    }
                }
                WsOpcode::Ping => {
                    if let Ok(mut msgs) = self.received_messages.lock() {
                        msgs.push_back(WsMessage::Ping(frame.payload));
                    }
                }
                WsOpcode::Pong => {
                    if let Ok(mut msgs) = self.received_messages.lock() {
                        msgs.push_back(WsMessage::Pong(frame.payload));
                    }
                }
                WsOpcode::Close => {
                    let (code, reason) = if frame.payload.len() >= 2 {
                        let code = u16::from_be_bytes([frame.payload[0], frame.payload[1]]);
                        let r = String::from_utf8_lossy(&frame.payload[2..]).to_string();
                        (Some(code), r)
                    } else {
                        (None, String::new())
                    };
                    if let Ok(mut msgs) = self.received_messages.lock() {
                        msgs.push_back(WsMessage::Close(code, reason));
                    }
                }
            }
        }
        Ok(total_consumed)
    }

    /// Pops the next received message from the queue, if any.
    pub fn poll_message(&self) -> Option<WsMessage> {
        self.received_messages.lock().ok()?.pop_front()
    }

    /// Waits up to `timeout` for a message to arrive.
    pub fn recv_message_timeout(&self, timeout: Duration) -> Option<WsMessage> {
        let start = std::time::Instant::now();
        while start.elapsed() < timeout {
            if let Some(msg) = self.poll_message() {
                return Some(msg);
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        None
    }

    /// Drains all currently queued outgoing encoded frames.
    pub fn drain_outgoing_frames(&self) -> Vec<Vec<u8>> {
        self.outgoing_queue
            .lock()
            .map(|mut q| std::mem::take(&mut *q))
            .unwrap_or_default()
    }
}

impl Drop for WebSocket {
    fn drop(&mut self) {
        // Only perform teardown when the last cloned handle drops
        if Arc::strong_count(&self.closed_flag) == 1 {
            self.closed_flag.store(true, Ordering::Relaxed);
            if let Ok(mut handle_guard) = self.worker_handle.lock() {
                if let Some(handle) = handle_guard.take() {
                    let _ = handle.join();
                }
            }
        }
    }
}