Skip to main content

strata_web_api/
websocket.rs

1//! Pure-Rust W3C WebSocket Client with RFC 6455 Frame Serialization, Handshake & TLS (`wss://`).
2//!
3//! Provides:
4//! - Complete RFC 6455 frame encoding and decoding with masking and control frame processing.
5//! - Cryptographic `Sec-WebSocket-Key` generation and SHA-1 `Sec-WebSocket-Accept` validation.
6//! - Native TLS transport for `wss://` connections via Mozilla WebPKI root certificates and `rustls`.
7//! - Asynchronous background worker stream reading, heartbeat Ping/Pong processing, and queueing.
8
9use std::collections::VecDeque;
10use std::fmt;
11use std::io::{Read, Write};
12use std::net::TcpStream;
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Arc, Mutex};
15use std::time::Duration;
16
17use crate::tls::{create_tls_stream, HttpTransportStream};
18
19const WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
20
21/// Maximum default frame payload size before automatically fragmenting (64 KB).
22pub const DEFAULT_MAX_FRAME_SIZE: usize = 65536;
23
24/// RFC 6455 WebSocket Opcode.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum WsOpcode {
27    Continuation = 0x0,
28    Text = 0x1,
29    Binary = 0x2,
30    Close = 0x8,
31    Ping = 0x9,
32    Pong = 0xA,
33}
34
35impl WsOpcode {
36    pub fn from_u8(val: u8) -> Option<Self> {
37        match val {
38            0x0 => Some(Self::Continuation),
39            0x1 => Some(Self::Text),
40            0x2 => Some(Self::Binary),
41            0x8 => Some(Self::Close),
42            0x9 => Some(Self::Ping),
43            0xA => Some(Self::Pong),
44            _ => None,
45        }
46    }
47
48    pub fn is_control(&self) -> bool {
49        matches!(self, Self::Close | Self::Ping | Self::Pong)
50    }
51}
52
53/// Errors occurring during WebSocket communication.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum WsError {
56    InvalidUrl(String),
57    InvalidState(String),
58    HandshakeFailed(String),
59    ProtocolError(String),
60    InvalidFrame(String),
61    NetworkError(String),
62    Closed,
63}
64
65impl fmt::Display for WsError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::InvalidUrl(s) => write!(f, "Invalid WebSocket URL: {s}"),
69            Self::InvalidState(s) => write!(f, "Invalid WebSocket state: {s}"),
70            Self::HandshakeFailed(s) => write!(f, "WebSocket handshake failed: {s}"),
71            Self::ProtocolError(s) => write!(f, "WebSocket protocol error: {s}"),
72            Self::InvalidFrame(s) => write!(f, "Invalid WebSocket frame: {s}"),
73            Self::NetworkError(s) => write!(f, "WebSocket network error: {s}"),
74            Self::Closed => write!(f, "WebSocket is already closed"),
75        }
76    }
77}
78
79impl std::error::Error for WsError {}
80
81/// State of the WebSocket connection per W3C specification.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum WsState {
84    Connecting = 0,
85    Open = 1,
86    Closing = 2,
87    Closed = 3,
88}
89
90/// A decoded RFC 6455 WebSocket frame.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct WsFrame {
93    pub fin: bool,
94    pub opcode: WsOpcode,
95    pub payload: Vec<u8>,
96    pub masked: bool,
97}
98
99/// High-level WebSocket message.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub enum WsMessage {
102    Text(String),
103    Binary(Vec<u8>),
104    Ping(Vec<u8>),
105    Pong(Vec<u8>),
106    Close(Option<u16>, String),
107}
108
109/// Computes FIPS 180-1 SHA-1 digest in pure Rust.
110pub fn sha1(data: &[u8]) -> [u8; 20] {
111    let mut h0 = 0x67452301u32;
112    let mut h1 = 0xEFCDAB89u32;
113    let mut h2 = 0x98BADCFEu32;
114    let mut h3 = 0x10325476u32;
115    let mut h4 = 0xC3D2E1F0u32;
116
117    let mut msg = data.to_vec();
118    let bit_len = (data.len() as u64) * 8;
119    msg.push(0x80);
120    while (msg.len() % 64) != 56 {
121        msg.push(0x00);
122    }
123    msg.extend_from_slice(&bit_len.to_be_bytes());
124
125    for chunk in msg.as_chunks::<64>().0 {
126        let mut w = [0u32; 80];
127        for i in 0..16 {
128            w[i] = u32::from_be_bytes([
129                chunk[i * 4],
130                chunk[i * 4 + 1],
131                chunk[i * 4 + 2],
132                chunk[i * 4 + 3],
133            ]);
134        }
135        for i in 16..80 {
136            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
137        }
138
139        let mut a = h0;
140        let mut b = h1;
141        let mut c = h2;
142        let mut d = h3;
143        let mut e = h4;
144
145        for (i, &w_i) in w.iter().enumerate() {
146            let (f, k) = match i {
147                0..=19 => ((b & c) | ((!b) & d), 0x5A827999u32),
148                20..=39 => (b ^ c ^ d, 0x6ED9EBA1u32),
149                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDCu32),
150                _ => (b ^ c ^ d, 0xCA62C1D6u32),
151            };
152            let temp = a
153                .rotate_left(5)
154                .wrapping_add(f)
155                .wrapping_add(e)
156                .wrapping_add(k)
157                .wrapping_add(w_i);
158            e = d;
159            d = c;
160            c = b.rotate_left(30);
161            b = a;
162            a = temp;
163        }
164
165        h0 = h0.wrapping_add(a);
166        h1 = h1.wrapping_add(b);
167        h2 = h2.wrapping_add(c);
168        h3 = h3.wrapping_add(d);
169        h4 = h4.wrapping_add(e);
170    }
171
172    let mut out = [0u8; 20];
173    out[0..4].copy_from_slice(&h0.to_be_bytes());
174    out[4..8].copy_from_slice(&h1.to_be_bytes());
175    out[8..12].copy_from_slice(&h2.to_be_bytes());
176    out[12..16].copy_from_slice(&h3.to_be_bytes());
177    out[16..20].copy_from_slice(&h4.to_be_bytes());
178    out
179}
180
181/// Standard base64 encoding.
182pub fn base64_encode(data: &[u8]) -> String {
183    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
184    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
185
186    for chunk in data.chunks(3) {
187        let b0 = chunk[0] as usize;
188        let b1 = chunk.get(1).copied().unwrap_or(0) as usize;
189        let b2 = chunk.get(2).copied().unwrap_or(0) as usize;
190
191        let triple = (b0 << 16) | (b1 << 8) | b2;
192
193        out.push(TABLE[(triple >> 18) & 0x3F] as char);
194        out.push(TABLE[(triple >> 12) & 0x3F] as char);
195
196        if chunk.len() > 1 {
197            out.push(TABLE[(triple >> 6) & 0x3F] as char);
198        } else {
199            out.push('=');
200        }
201
202        if chunk.len() > 2 {
203            out.push(TABLE[triple & 0x3F] as char);
204        } else {
205            out.push('=');
206        }
207    }
208
209    out
210}
211
212/// Computes the expected RFC 6455 `Sec-WebSocket-Accept` header value from client key.
213pub fn compute_sec_websocket_accept(key: &str) -> String {
214    let mut concat = key.trim().as_bytes().to_vec();
215    concat.extend_from_slice(WS_GUID.as_bytes());
216    let digest = sha1(&concat);
217    base64_encode(&digest)
218}
219
220/// Fills a buffer with cryptographically secure pseudo-random bytes.
221///
222/// Uses `ring::rand::SystemRandom` backed by the OS CSPRNG, with fallbacks to `getrandom`
223/// and `/dev/urandom` on Unix. Panics on total entropy failure rather than falling back to
224/// predictable timestamps (preventing RFC 6455 §5.3 cache poisoning attacks).
225fn fill_secure_random(buf: &mut [u8]) {
226    use ring::rand::SecureRandom;
227    let rng = ring::rand::SystemRandom::new();
228    if rng.fill(buf).is_ok() {
229        return;
230    }
231
232    if getrandom::getrandom(buf).is_ok() {
233        return;
234    }
235
236    #[cfg(unix)]
237    {
238        if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
239            if f.read_exact(buf).is_ok() {
240                return;
241            }
242        }
243    }
244
245    panic!("RFC 6455 CSPRNG failure: unable to obtain secure cryptographic entropy for WebSocket operations");
246}
247
248/// Generates a cryptographically random 16-byte base64 nonce for `Sec-WebSocket-Key` (RFC 6455 §4.1).
249pub fn generate_sec_websocket_key() -> String {
250    let mut nonce = [0u8; 16];
251    fill_secure_random(&mut nonce);
252    base64_encode(&nonce)
253}
254
255/// Generates an unpredictable 32-bit masking key for client frames (RFC 6455 §5.3).
256pub fn generate_mask_key() -> [u8; 4] {
257    let mut key = [0u8; 4];
258    fill_secure_random(&mut key);
259    key
260}
261
262/// Encodes an RFC 6455 frame into bytes.
263pub fn encode_frame(
264    fin: bool,
265    opcode: WsOpcode,
266    payload: &[u8],
267    masked: bool,
268    mask_key: Option<[u8; 4]>,
269) -> Vec<u8> {
270    let mut frame = Vec::new();
271
272    let byte0 = if fin { 0x80 } else { 0x00 } | (opcode as u8 & 0x0F);
273    frame.push(byte0);
274
275    let mask_bit = if masked { 0x80 } else { 0x00 };
276    let len = payload.len();
277
278    if len < 126 {
279        frame.push(mask_bit | (len as u8));
280    } else if len <= 0xFFFF {
281        frame.push(mask_bit | 126);
282        frame.extend_from_slice(&(len as u16).to_be_bytes());
283    } else {
284        frame.push(mask_bit | 127);
285        frame.extend_from_slice(&(len as u64).to_be_bytes());
286    }
287
288    if masked {
289        let key = mask_key.unwrap_or_else(generate_mask_key);
290        frame.extend_from_slice(&key);
291        for (i, &b) in payload.iter().enumerate() {
292            frame.push(b ^ key[i % 4]);
293        }
294    } else {
295        frame.extend_from_slice(payload);
296    }
297
298    frame
299}
300
301/// Decodes an RFC 6455 frame from a byte buffer.
302pub fn decode_frame(buf: &[u8]) -> Result<Option<(WsFrame, usize)>, WsError> {
303    if buf.len() < 2 {
304        return Ok(None);
305    }
306
307    let byte0 = buf[0];
308    let fin = (byte0 & 0x80) != 0;
309    let opcode_raw = byte0 & 0x0F;
310    let opcode = WsOpcode::from_u8(opcode_raw)
311        .ok_or_else(|| WsError::InvalidFrame(format!("Unknown opcode: 0x{opcode_raw:X}")))?;
312
313    let byte1 = buf[1];
314    let masked = (byte1 & 0x80) != 0;
315    let payload_indicator = byte1 & 0x7F;
316
317    let mut cursor = 2;
318
319    let payload_len: usize = if payload_indicator < 126 {
320        payload_indicator as usize
321    } else if payload_indicator == 126 {
322        if opcode.is_control() {
323            return Err(WsError::ProtocolError(
324                "Control frames must not have payload length > 125 bytes (RFC 6455 §5.5)".into(),
325            ));
326        }
327        if buf.len() < cursor + 2 {
328            return Ok(None);
329        }
330        let len_bytes: [u8; 2] = [buf[cursor], buf[cursor + 1]];
331        cursor += 2;
332        u16::from_be_bytes(len_bytes) as usize
333    } else {
334        if opcode.is_control() {
335            return Err(WsError::ProtocolError(
336                "Control frames must not have payload length > 125 bytes (RFC 6455 §5.5)".into(),
337            ));
338        }
339        if buf.len() < cursor + 8 {
340            return Ok(None);
341        }
342        let mut len_bytes = [0u8; 8];
343        len_bytes.copy_from_slice(&buf[cursor..cursor + 8]);
344        cursor += 8;
345        u64::from_be_bytes(len_bytes) as usize
346    };
347
348    if opcode.is_control() && !fin {
349        return Err(WsError::ProtocolError(
350            "Control frames must not be fragmented (FIN must be true, RFC 6455 §5.5)".into(),
351        ));
352    }
353
354    let mask_key = if masked {
355        if buf.len() < cursor + 4 {
356            return Ok(None);
357        }
358        let key = [
359            buf[cursor],
360            buf[cursor + 1],
361            buf[cursor + 2],
362            buf[cursor + 3],
363        ];
364        cursor += 4;
365        Some(key)
366    } else {
367        None
368    };
369
370    if buf.len() < cursor + payload_len {
371        return Ok(None);
372    }
373
374    let mut payload = buf[cursor..cursor + payload_len].to_vec();
375    if let Some(key) = mask_key {
376        for (i, b) in payload.iter_mut().enumerate() {
377            *b ^= key[i % 4];
378        }
379    }
380
381    cursor += payload_len;
382
383    Ok(Some((
384        WsFrame {
385            fin,
386            opcode,
387            payload,
388            masked,
389        },
390        cursor,
391    )))
392}
393
394#[derive(Debug, Clone)]
395struct ParsedWsUrl {
396    is_secure: bool,
397    host: String,
398    port: u16,
399    path: String,
400}
401
402fn parse_ws_url(url: &str) -> Result<ParsedWsUrl, WsError> {
403    let (is_secure, rest) = if let Some(s) = url.strip_prefix("wss://") {
404        (true, s)
405    } else if let Some(s) = url.strip_prefix("ws://") {
406        (false, s)
407    } else {
408        return Err(WsError::InvalidUrl(format!(
409            "URL must start with ws:// or wss://: {url}"
410        )));
411    };
412
413    let (host_port, path) = match rest.find('/') {
414        Some(pos) => (&rest[..pos], &rest[pos..]),
415        None => (rest, "/"),
416    };
417
418    let (host, port) = match host_port.find(':') {
419        Some(pos) => {
420            let h = &host_port[..pos];
421            let p = host_port[pos + 1..]
422                .parse::<u16>()
423                .map_err(|e| WsError::InvalidUrl(format!("Invalid port: {e}")))?;
424            (h.to_string(), p)
425        }
426        None => {
427            let p = if is_secure { 443 } else { 80 };
428            (host_port.to_string(), p)
429        }
430    };
431
432    Ok(ParsedWsUrl {
433        is_secure,
434        host,
435        port,
436        path: path.to_string(),
437    })
438}
439
440/// Ongoing fragmented message tracking state.
441#[derive(Debug, Clone)]
442pub struct WsFragment {
443    pub opcode: WsOpcode,
444    pub buffer: Vec<u8>,
445}
446
447/// W3C WebSocket client interface supporting `ws://` and TLS `wss://`.
448#[derive(Clone)]
449pub struct WebSocket {
450    pub url: String,
451    state: Arc<Mutex<WsState>>,
452    outgoing_queue: Arc<Mutex<Vec<Vec<u8>>>>,
453    received_messages: Arc<Mutex<VecDeque<WsMessage>>>,
454    closed_flag: Arc<AtomicBool>,
455    fragment_state: Arc<Mutex<Option<WsFragment>>>,
456    worker_handle: Arc<Mutex<Option<std::thread::JoinHandle<()>>>>,
457}
458
459impl WebSocket {
460    /// Creates an in-memory/mock WebSocket for offline testing.
461    pub fn new(url: &str) -> Self {
462        Self {
463            url: url.to_string(),
464            state: Arc::new(Mutex::new(WsState::Connecting)),
465            outgoing_queue: Arc::new(Mutex::new(Vec::new())),
466            received_messages: Arc::new(Mutex::new(VecDeque::new())),
467            closed_flag: Arc::new(AtomicBool::new(false)),
468            fragment_state: Arc::new(Mutex::new(None)),
469            worker_handle: Arc::new(Mutex::new(None)),
470        }
471    }
472
473    /// Establishes a real RFC 6455 WebSocket connection over plain TCP (`ws://`) or TLS (`wss://`).
474    pub fn connect(url: &str) -> Result<Self, WsError> {
475        let parsed = parse_ws_url(url)?;
476        let addr = format!("{}:{}", parsed.host, parsed.port);
477
478        let tcp = TcpStream::connect_timeout(
479            &addr
480                .parse()
481                .or_else(|_| {
482                    use std::net::ToSocketAddrs;
483                    addr.to_socket_addrs()
484                        .map_err(std::io::Error::other)?
485                        .next()
486                        .ok_or_else(|| {
487                            std::io::Error::new(
488                                std::io::ErrorKind::NotFound,
489                                "Host resolution failed",
490                            )
491                        })
492                })
493                .map_err(|e| WsError::NetworkError(format!("DNS/Socket resolution error: {e}")))?,
494            Duration::from_secs(10),
495        )
496        .map_err(|e| WsError::NetworkError(format!("TCP connection failed: {e}")))?;
497
498        let mut transport = if parsed.is_secure {
499            create_tls_stream(tcp, &parsed.host)
500                .map_err(|e| WsError::NetworkError(format!("TLS handshake failed: {e}")))?
501        } else {
502            HttpTransportStream::Plain(tcp)
503        };
504
505        // HTTP/1.1 Upgrade Handshake
506        let sec_key = generate_sec_websocket_key();
507        let expected_accept = compute_sec_websocket_accept(&sec_key);
508
509        let handshake_req = format!(
510            "GET {} HTTP/1.1\r\n\
511             Host: {}:{}\r\n\
512             Upgrade: websocket\r\n\
513             Connection: Upgrade\r\n\
514             Sec-WebSocket-Key: {}\r\n\
515             Sec-WebSocket-Version: 13\r\n\
516             User-Agent: Strata/0.1.0\r\n\r\n",
517            parsed.path, parsed.host, parsed.port, sec_key
518        );
519
520        transport.write_all(handshake_req.as_bytes()).map_err(|e| {
521            WsError::NetworkError(format!("Failed to write handshake request: {e}"))
522        })?;
523        transport.flush().map_err(|e| {
524            WsError::NetworkError(format!("Failed to flush handshake request: {e}"))
525        })?;
526
527        // Read handshake response
528        let mut response_buf = Vec::new();
529        let mut temp_buf = [0u8; 1024];
530        let mut accept_validated = false;
531
532        let initial_data = loop {
533            let n = transport.read(&mut temp_buf).map_err(|e| {
534                WsError::NetworkError(format!("Error reading handshake response: {e}"))
535            })?;
536            if n == 0 {
537                return Err(WsError::HandshakeFailed(
538                    "Connection closed by server during handshake".into(),
539                ));
540            }
541            response_buf.extend_from_slice(&temp_buf[..n]);
542
543            if let Some(pos) = response_buf.windows(4).position(|w| w == b"\r\n\r\n") {
544                let header_str = String::from_utf8_lossy(&response_buf[..pos]);
545                if !header_str.starts_with("HTTP/1.1 101")
546                    && !header_str.starts_with("HTTP/1.0 101")
547                {
548                    return Err(WsError::HandshakeFailed(format!(
549                        "Server returned non-101 status: {}",
550                        header_str.lines().next().unwrap_or("")
551                    )));
552                }
553
554                for line in header_str.lines() {
555                    if let Some((name, val)) = line.split_once(':') {
556                        if name.trim().eq_ignore_ascii_case("sec-websocket-accept") {
557                            if val.trim() == expected_accept {
558                                accept_validated = true;
559                            } else {
560                                return Err(WsError::ProtocolError(format!(
561                                    "Sec-WebSocket-Accept mismatch: expected {expected_accept}, got {}",
562                                    val.trim()
563                                )));
564                            }
565                        }
566                    }
567                }
568                let initial_data = response_buf[pos + 4..].to_vec();
569                break initial_data;
570            }
571        };
572
573        if !accept_validated {
574            return Err(WsError::ProtocolError(
575                "Missing Sec-WebSocket-Accept header in response".into(),
576            ));
577        }
578
579        let ws = Self {
580            url: url.to_string(),
581            state: Arc::new(Mutex::new(WsState::Open)),
582            outgoing_queue: Arc::new(Mutex::new(Vec::new())),
583            received_messages: Arc::new(Mutex::new(VecDeque::new())),
584            closed_flag: Arc::new(AtomicBool::new(false)),
585            fragment_state: Arc::new(Mutex::new(None)),
586            worker_handle: Arc::new(Mutex::new(None)),
587        };
588
589        // Configure socket options for low latency and non-blocking worker polling
590        let _ = transport.set_nodelay(true);
591        let _ = transport.set_read_timeout(Some(Duration::from_millis(15)));
592        let _ = transport.set_write_timeout(Some(Duration::from_secs(10)));
593
594        // Spawn background worker thread managing stream I/O
595        let worker_state = ws.state.clone();
596        let worker_outgoing = ws.outgoing_queue.clone();
597        let worker_received = ws.received_messages.clone();
598        let worker_closed = ws.closed_flag.clone();
599        let worker_fragment = ws.fragment_state.clone();
600
601        let handle = std::thread::Builder::new()
602            .name("strata-ws-worker".into())
603            .spawn(move || {
604                let mut read_buf = initial_data;
605                let mut temp = [0u8; 4096];
606                let mut last_ping = std::time::Instant::now();
607                let ping_interval = Duration::from_secs(30);
608
609                while !worker_closed.load(Ordering::Relaxed) {
610                    // 1. Drain and send outgoing frames
611                    let outgoing = worker_outgoing
612                        .lock()
613                        .map(|mut q| std::mem::take(&mut *q))
614                        .unwrap_or_default();
615
616                    for frame in outgoing {
617                        if transport.write_all(&frame).is_err() || transport.flush().is_err() {
618                            worker_closed.store(true, Ordering::Relaxed);
619                            break;
620                        }
621                    }
622
623                    if worker_closed.load(Ordering::Relaxed) {
624                        break;
625                    }
626
627                    // 2. Send periodic RFC 6455 Ping heartbeat
628                    if last_ping.elapsed() >= ping_interval {
629                        let ping =
630                            encode_frame(true, WsOpcode::Ping, b"strata-heartbeat", true, None);
631                        if transport.write_all(&ping).is_err() || transport.flush().is_err() {
632                            worker_closed.store(true, Ordering::Relaxed);
633                            break;
634                        }
635                        last_ping = std::time::Instant::now();
636                    }
637
638                    // 3. Read incoming frames with non-blocking 15ms window
639                    match transport.read(&mut temp) {
640                        Ok(0) => {
641                            worker_closed.store(true, Ordering::Relaxed);
642                            break;
643                        }
644                        Ok(n) => {
645                            read_buf.extend_from_slice(&temp[..n]);
646                        }
647                        Err(ref e)
648                            if e.kind() == std::io::ErrorKind::WouldBlock
649                                || e.kind() == std::io::ErrorKind::TimedOut =>
650                        {
651                            // Non-fatal read timeout: continue to process read_buf and service outgoing queue
652                        }
653                        Err(_) => {
654                            worker_closed.store(true, Ordering::Relaxed);
655                            break;
656                        }
657                    }
658
659                    // 4. Drain and process all complete frames present in read_buf
660                    let mut proto_violation = false;
661                    while let Ok(Some((frame, consumed))) = decode_frame(&read_buf) {
662                        read_buf.drain(..consumed);
663
664                        if frame.masked {
665                            // RFC 6455 §5.1: server frames must not be masked
666                            proto_violation = true;
667                            break;
668                        }
669
670                        match frame.opcode {
671                            WsOpcode::Text | WsOpcode::Binary => {
672                                if let Ok(mut frag) = worker_fragment.lock() {
673                                    if frag.is_some() {
674                                        proto_violation = true;
675                                        break;
676                                    }
677                                    if frame.fin {
678                                        if frame.opcode == WsOpcode::Text {
679                                            if let Ok(s) = String::from_utf8(frame.payload) {
680                                                if let Ok(mut msgs) = worker_received.lock() {
681                                                    msgs.push_back(WsMessage::Text(s));
682                                                }
683                                            }
684                                        } else if let Ok(mut msgs) = worker_received.lock() {
685                                            msgs.push_back(WsMessage::Binary(frame.payload));
686                                        }
687                                    } else {
688                                        *frag = Some(WsFragment {
689                                            opcode: frame.opcode,
690                                            buffer: frame.payload,
691                                        });
692                                    }
693                                }
694                            }
695                            WsOpcode::Continuation => {
696                                let mut completed_msg = None;
697                                if let Ok(mut frag_guard) = worker_fragment.lock() {
698                                    if let Some(ref mut fragment) = *frag_guard {
699                                        fragment.buffer.extend_from_slice(&frame.payload);
700                                        if frame.fin {
701                                            let fragment_val = frag_guard.take().unwrap();
702                                            match fragment_val.opcode {
703                                                WsOpcode::Text => {
704                                                    if let Ok(s) =
705                                                        String::from_utf8(fragment_val.buffer)
706                                                    {
707                                                        completed_msg = Some(WsMessage::Text(s));
708                                                    }
709                                                }
710                                                WsOpcode::Binary => {
711                                                    completed_msg = Some(WsMessage::Binary(
712                                                        fragment_val.buffer,
713                                                    ));
714                                                }
715                                                _ => {}
716                                            }
717                                        }
718                                    } else {
719                                        proto_violation = true;
720                                        break;
721                                    }
722                                }
723                                if let Some(msg) = completed_msg {
724                                    if let Ok(mut msgs) = worker_received.lock() {
725                                        msgs.push_back(msg);
726                                    }
727                                }
728                            }
729                            WsOpcode::Ping => {
730                                // Auto-reply with Pong per RFC 6455 §5.5.3
731                                let pong =
732                                    encode_frame(true, WsOpcode::Pong, &frame.payload, true, None);
733                                let _ = transport.write_all(&pong);
734                                let _ = transport.flush();
735                            }
736                            WsOpcode::Pong => {
737                                if let Ok(mut msgs) = worker_received.lock() {
738                                    msgs.push_back(WsMessage::Pong(frame.payload));
739                                }
740                            }
741                            WsOpcode::Close => {
742                                // Echo close frame per RFC 6455 §5.5.1
743                                let echo =
744                                    encode_frame(true, WsOpcode::Close, &frame.payload, true, None);
745                                let _ = transport.write_all(&echo);
746                                let _ = transport.flush();
747
748                                let (code, reason) = if frame.payload.len() >= 2 {
749                                    let code =
750                                        u16::from_be_bytes([frame.payload[0], frame.payload[1]]);
751                                    let r =
752                                        String::from_utf8_lossy(&frame.payload[2..]).to_string();
753                                    (Some(code), r)
754                                } else {
755                                    (None, String::new())
756                                };
757                                if let Ok(mut msgs) = worker_received.lock() {
758                                    msgs.push_back(WsMessage::Close(code, reason));
759                                }
760                                worker_closed.store(true, Ordering::Relaxed);
761                                if let Ok(mut s) = worker_state.lock() {
762                                    *s = WsState::Closed;
763                                }
764                                break;
765                            }
766                        }
767                    }
768
769                    if proto_violation {
770                        let close_frame =
771                            encode_frame(true, WsOpcode::Close, &1002u16.to_be_bytes(), true, None);
772                        let _ = transport.write_all(&close_frame);
773                        let _ = transport.flush();
774                        worker_closed.store(true, Ordering::Relaxed);
775                        if let Ok(mut s) = worker_state.lock() {
776                            *s = WsState::Closed;
777                        }
778                        break;
779                    }
780                }
781
782                // Final drain of any queued frames (e.g. Close frame queued by close())
783                let final_outgoing = worker_outgoing
784                    .lock()
785                    .map(|mut q| std::mem::take(&mut *q))
786                    .unwrap_or_default();
787                for frame in final_outgoing {
788                    let _ = transport.write_all(&frame);
789                    let _ = transport.flush();
790                }
791
792                if let Ok(mut s) = worker_state.lock() {
793                    *s = WsState::Closed;
794                }
795            })
796            .map_err(|e| WsError::NetworkError(format!("Failed to spawn WebSocket thread: {e}")))?;
797
798        if let Ok(mut handle_guard) = ws.worker_handle.lock() {
799            *handle_guard = Some(handle);
800        }
801
802        Ok(ws)
803    }
804
805    /// Mark the connection as Open.
806    pub fn set_open(&self) {
807        if let Ok(mut s) = self.state.lock() {
808            *s = WsState::Open;
809        }
810    }
811
812    /// Current connection state.
813    pub fn ready_state(&self) -> WsState {
814        self.state.lock().map(|s| *s).unwrap_or(WsState::Closed)
815    }
816
817    /// Whether the WebSocket is open.
818    pub fn is_open(&self) -> bool {
819        self.ready_state() == WsState::Open
820    }
821
822    /// Sends a text message over the WebSocket. If length exceeds `DEFAULT_MAX_FRAME_SIZE`, it is fragmented.
823    pub fn send_text(&self, text: &str) -> Result<(), WsError> {
824        if text.len() > DEFAULT_MAX_FRAME_SIZE {
825            self.send_text_fragmented(text, DEFAULT_MAX_FRAME_SIZE)
826        } else {
827            let state = self.ready_state();
828            if state != WsState::Open {
829                return Err(WsError::InvalidState(format!(
830                    "Cannot send in state {state:?}"
831                )));
832            }
833
834            let frame = encode_frame(true, WsOpcode::Text, text.as_bytes(), true, None);
835            if let Ok(mut q) = self.outgoing_queue.lock() {
836                q.push(frame);
837            }
838            Ok(())
839        }
840    }
841
842    /// Sends binary data over the WebSocket. If length exceeds `DEFAULT_MAX_FRAME_SIZE`, it is fragmented.
843    pub fn send_binary(&self, data: &[u8]) -> Result<(), WsError> {
844        if data.len() > DEFAULT_MAX_FRAME_SIZE {
845            self.send_binary_fragmented(data, DEFAULT_MAX_FRAME_SIZE)
846        } else {
847            let state = self.ready_state();
848            if state != WsState::Open {
849                return Err(WsError::InvalidState(format!(
850                    "Cannot send in state {state:?}"
851                )));
852            }
853
854            let frame = encode_frame(true, WsOpcode::Binary, data, true, None);
855            if let Ok(mut q) = self.outgoing_queue.lock() {
856                q.push(frame);
857            }
858            Ok(())
859        }
860    }
861
862    /// Sends a text message split into multiple frames with given chunk size.
863    pub fn send_text_fragmented(&self, text: &str, chunk_size: usize) -> Result<(), WsError> {
864        self.send_payload_fragmented(WsOpcode::Text, text.as_bytes(), chunk_size)
865    }
866
867    /// Sends binary data split into multiple frames with given chunk size.
868    pub fn send_binary_fragmented(&self, data: &[u8], chunk_size: usize) -> Result<(), WsError> {
869        self.send_payload_fragmented(WsOpcode::Binary, data, chunk_size)
870    }
871
872    /// Helper to send payload in fragmented RFC 6455 frames.
873    pub fn send_payload_fragmented(
874        &self,
875        opcode: WsOpcode,
876        payload: &[u8],
877        chunk_size: usize,
878    ) -> Result<(), WsError> {
879        let state = self.ready_state();
880        if state != WsState::Open {
881            return Err(WsError::InvalidState(format!(
882                "Cannot send in state {state:?}"
883            )));
884        }
885
886        let chunk_size = chunk_size.max(1);
887        let chunks: Vec<&[u8]> = payload.chunks(chunk_size).collect();
888        if chunks.is_empty() {
889            let frame = encode_frame(true, opcode, &[], true, None);
890            if let Ok(mut q) = self.outgoing_queue.lock() {
891                q.push(frame);
892            }
893            return Ok(());
894        }
895
896        let num_chunks = chunks.len();
897        for (i, chunk) in chunks.iter().enumerate() {
898            let fin = i == num_chunks - 1;
899            let op = if i == 0 {
900                opcode
901            } else {
902                WsOpcode::Continuation
903            };
904            let frame = encode_frame(fin, op, chunk, true, None);
905            if let Ok(mut q) = self.outgoing_queue.lock() {
906                q.push(frame);
907            }
908        }
909        Ok(())
910    }
911
912    /// Sends a Ping frame.
913    pub fn send_ping(&self, payload: &[u8]) -> Result<(), WsError> {
914        let frame = encode_frame(true, WsOpcode::Ping, payload, true, None);
915        if let Ok(mut q) = self.outgoing_queue.lock() {
916            q.push(frame);
917        }
918        Ok(())
919    }
920
921    /// Closes the WebSocket connection with status code and reason.
922    pub fn close(&self, code: u16, reason: &str) -> Result<(), WsError> {
923        if let Ok(mut s) = self.state.lock() {
924            if *s == WsState::Closed || *s == WsState::Closing {
925                return Ok(());
926            }
927            *s = WsState::Closing;
928        }
929
930        let mut payload = code.to_be_bytes().to_vec();
931        payload.extend_from_slice(reason.as_bytes());
932        let frame = encode_frame(true, WsOpcode::Close, &payload, true, None);
933        if let Ok(mut q) = self.outgoing_queue.lock() {
934            q.push(frame);
935        }
936
937        self.closed_flag.store(true, Ordering::Relaxed);
938        if let Ok(mut s) = self.state.lock() {
939            *s = WsState::Closed;
940        }
941
942        Ok(())
943    }
944
945    /// Ingests received raw bytes and decodes messages into the internal buffer.
946    pub fn ingest_incoming_bytes(&self, mut buf: &[u8]) -> Result<usize, WsError> {
947        let mut total_consumed = 0;
948        while let Some((frame, consumed)) = decode_frame(buf)? {
949            buf = &buf[consumed..];
950            total_consumed += consumed;
951
952            if frame.masked {
953                return Err(WsError::ProtocolError(
954                    "Frames received from server must not be masked (RFC 6455 §5.1)".into(),
955                ));
956            }
957
958            match frame.opcode {
959                WsOpcode::Text => {
960                    if let Ok(mut frag) = self.fragment_state.lock() {
961                        if frag.is_some() {
962                            return Err(WsError::ProtocolError(
963                                "Cannot start new data frame while fragmented frame is in progress (RFC 6455 §5.4)".into(),
964                            ));
965                        }
966                        if frame.fin {
967                            let s = String::from_utf8(frame.payload).map_err(|e| {
968                                WsError::ProtocolError(format!("Invalid UTF-8 in text frame: {e}"))
969                            })?;
970                            if let Ok(mut msgs) = self.received_messages.lock() {
971                                msgs.push_back(WsMessage::Text(s));
972                            }
973                        } else {
974                            *frag = Some(WsFragment {
975                                opcode: WsOpcode::Text,
976                                buffer: frame.payload,
977                            });
978                        }
979                    }
980                }
981                WsOpcode::Binary => {
982                    if let Ok(mut frag) = self.fragment_state.lock() {
983                        if frag.is_some() {
984                            return Err(WsError::ProtocolError(
985                                "Cannot start new data frame while fragmented frame is in progress (RFC 6455 §5.4)".into(),
986                            ));
987                        }
988                        if frame.fin {
989                            if let Ok(mut msgs) = self.received_messages.lock() {
990                                msgs.push_back(WsMessage::Binary(frame.payload));
991                            }
992                        } else {
993                            *frag = Some(WsFragment {
994                                opcode: WsOpcode::Binary,
995                                buffer: frame.payload,
996                            });
997                        }
998                    }
999                }
1000                WsOpcode::Continuation => {
1001                    let mut completed_msg = None;
1002                    if let Ok(mut frag_guard) = self.fragment_state.lock() {
1003                        if let Some(ref mut fragment) = *frag_guard {
1004                            fragment.buffer.extend_from_slice(&frame.payload);
1005                            if frame.fin {
1006                                let fragment_val = frag_guard.take().unwrap();
1007                                match fragment_val.opcode {
1008                                    WsOpcode::Text => {
1009                                        let s = String::from_utf8(fragment_val.buffer).map_err(
1010                                            |e| {
1011                                                WsError::ProtocolError(format!(
1012                                                    "Invalid UTF-8 in continuation frame: {e}"
1013                                                ))
1014                                            },
1015                                        )?;
1016                                        completed_msg = Some(WsMessage::Text(s));
1017                                    }
1018                                    WsOpcode::Binary => {
1019                                        completed_msg =
1020                                            Some(WsMessage::Binary(fragment_val.buffer));
1021                                    }
1022                                    _ => {}
1023                                }
1024                            }
1025                        } else {
1026                            return Err(WsError::ProtocolError(
1027                                "Unexpected continuation frame without initial fragmented frame"
1028                                    .into(),
1029                            ));
1030                        }
1031                    }
1032                    if let Some(msg) = completed_msg {
1033                        if let Ok(mut msgs) = self.received_messages.lock() {
1034                            msgs.push_back(msg);
1035                        }
1036                    }
1037                }
1038                WsOpcode::Ping => {
1039                    if let Ok(mut msgs) = self.received_messages.lock() {
1040                        msgs.push_back(WsMessage::Ping(frame.payload));
1041                    }
1042                }
1043                WsOpcode::Pong => {
1044                    if let Ok(mut msgs) = self.received_messages.lock() {
1045                        msgs.push_back(WsMessage::Pong(frame.payload));
1046                    }
1047                }
1048                WsOpcode::Close => {
1049                    let (code, reason) = if frame.payload.len() >= 2 {
1050                        let code = u16::from_be_bytes([frame.payload[0], frame.payload[1]]);
1051                        let r = String::from_utf8_lossy(&frame.payload[2..]).to_string();
1052                        (Some(code), r)
1053                    } else {
1054                        (None, String::new())
1055                    };
1056                    if let Ok(mut msgs) = self.received_messages.lock() {
1057                        msgs.push_back(WsMessage::Close(code, reason));
1058                    }
1059                }
1060            }
1061        }
1062        Ok(total_consumed)
1063    }
1064
1065    /// Pops the next received message from the queue, if any.
1066    pub fn poll_message(&self) -> Option<WsMessage> {
1067        self.received_messages.lock().ok()?.pop_front()
1068    }
1069
1070    /// Waits up to `timeout` for a message to arrive.
1071    pub fn recv_message_timeout(&self, timeout: Duration) -> Option<WsMessage> {
1072        let start = std::time::Instant::now();
1073        while start.elapsed() < timeout {
1074            if let Some(msg) = self.poll_message() {
1075                return Some(msg);
1076            }
1077            std::thread::sleep(Duration::from_millis(10));
1078        }
1079        None
1080    }
1081
1082    /// Drains all currently queued outgoing encoded frames.
1083    pub fn drain_outgoing_frames(&self) -> Vec<Vec<u8>> {
1084        self.outgoing_queue
1085            .lock()
1086            .map(|mut q| std::mem::take(&mut *q))
1087            .unwrap_or_default()
1088    }
1089}
1090
1091impl Drop for WebSocket {
1092    fn drop(&mut self) {
1093        // Only perform teardown when the last cloned handle drops
1094        if Arc::strong_count(&self.closed_flag) == 1 {
1095            self.closed_flag.store(true, Ordering::Relaxed);
1096            if let Ok(mut handle_guard) = self.worker_handle.lock() {
1097                if let Some(handle) = handle_guard.take() {
1098                    let _ = handle.join();
1099                }
1100            }
1101        }
1102    }
1103}