Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

17.3 KB
Raw Blame
//! WebSocket connections: one I/O thread per socket, asleep in `poll` until the socket is readable,
//! the page queued something to send (a byte on a wake socket), or a liveness deadline passes.
//!
//! The thread owns the tungstenite state machine. Reads are non-blocking (drained until
//! `WouldBlock` after each wake-up) and writes are blocking, so a send never waits on a read and
//! nothing polls. Events go to the main thread through an inbox; a task is posted only when the
//! inbox goes from empty to non-empty, so a burst of frames costs one wake-up.
//!
//! Liveness: Chromium relies on TCP to notice a dead peer, which after sleep or a Wi-Fi change can
//! take minutes. Here a ping goes out after `IDLE_PING` of silence, and right away when the network
//! changes or the machine wakes (`Cmd::Probe`); no answer within the deadline closes the socket
//! with 1006, so the page's reconnect logic runs promptly.

use std::collections::VecDeque;
use std::io::{self, Read, Write};
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use tungstenite::client::IntoClientRequest;
use tungstenite::protocol::frame::coding::CloseCode;
use tungstenite::protocol::{CloseFrame, WebSocketConfig};
use tungstenite::{Message, WebSocket};

use crate::conn::{self, Cancel, NetError, Purpose, Stream};
use crate::http::Url;

const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
const IDLE_PING: Duration = Duration::from_secs(30);
const PING_TIMEOUT: Duration = Duration::from_secs(10);
const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
/// How long we wait for the server's close frame after `close()` (Chromium's closing-handshake
/// timeout; then the socket closes with 1006 and no error event).
const CLOSE_TIMEOUT: Duration = Duration::from_secs(60);
/// After the closing handshake the server should drop TCP; Chromium waits 2 s before doing it.
const CLOSE_LINGER: Duration = Duration::from_secs(2);

pub enum Cmd {
    Text(String),
    Binary(Vec<u8>),
    Close(Option<(u16, String)>),
    Probe,
}

pub enum Event {
    Open { protocol: String, extensions: String },
    Text(String),
    Binary(Vec<u8>),
    Close { code: u16, reason: String, clean: bool, error: bool },
}

pub struct Shared {
    cmds: Mutex<VecDeque<Cmd>>,
    /// Bytes queued by `send` and not yet written (WebSocket.bufferedAmount).
    pub buffered: AtomicU64,
    inbox: Mutex<Vec<Event>>,
    cancel: Cancel,
    open: AtomicBool,
    /// The page went away: exit without events.
    teardown: AtomicBool,
    wake_tx: UnixStream,
}

impl Shared {
    pub fn push(&self, cmd: Cmd) {
        match &cmd {
            Cmd::Text(s) => {
                self.buffered.fetch_add(s.len() as u64, Ordering::Relaxed);
            }
            Cmd::Binary(b) => {
                self.buffered.fetch_add(b.len() as u64, Ordering::Relaxed);
            }
            _ => {}
        }
        let close = matches!(cmd, Cmd::Close(_));
        self.cmds.lock().unwrap().push_back(cmd);
        if close {
            // close() while connecting fails the connection; once open, the I/O thread runs the
            // closing handshake.
            self.cancel_if_connecting();
        }
        self.wake();
    }

    fn cancel_if_connecting(&self) {
        if !self.open.load(Ordering::SeqCst) {
            self.cancel.cancel();
        }
    }

    fn wake(&self) {
        // Non-blocking: a full buffer already means "wake up".
        let _ = (&self.wake_tx).write(&[1]);
    }

    /// The page is going away: stop at once (a best-effort 1001 "going away" if open).
    pub fn teardown(&self) {
        self.teardown.store(true, Ordering::SeqCst);
        self.cancel_if_connecting();
        self.wake();
    }

    pub fn take_events(&self) -> Vec<Event> {
        std::mem::take(&mut *self.inbox.lock().unwrap())
    }
}

pub struct Params {
    pub url: String,
    pub protocols: Vec<String>,
    pub origin: String,
    pub user_agent: String,
    pub accept_language: String,
}

/// Open a socket. `notify` runs on the I/O thread whenever events become available; it posts a
/// main-thread task that calls `take_events`.
pub fn open(p: Params, notify: impl Fn() + Send + 'static) -> io::Result<Arc<Shared>> {
    let (wake_tx, wake_rx) = UnixStream::pair()?;
    wake_tx.set_nonblocking(true)?;
    wake_rx.set_nonblocking(true)?;
    let shared = Arc::new(Shared {
        cmds: Mutex::new(VecDeque::new()),
        buffered: AtomicU64::new(0),
        inbox: Mutex::new(Vec::new()),
        cancel: Cancel::default(),
        open: AtomicBool::new(false),
        teardown: AtomicBool::new(false),
        wake_tx,
    });
    let s = shared.clone();
    std::thread::Builder::new().name("net-websocket".into()).stack_size(256 * 1024).spawn(move || {
        let mut io = Io { shared: s, wake_rx, notify: Box::new(notify), pending: Vec::new() };
        io.run(p);
    })?;
    Ok(shared)
}

struct Io {
    shared: Arc<Shared>,
    wake_rx: UnixStream,
    notify: Box<dyn Fn() + Send>,
    pending: Vec<Event>,
}

enum Flow {
    Continue,
    Done(Option<Event>),
}

fn abnormal(error: bool) -> Event {
    Event::Close { code: 1006, reason: String::new(), clean: false, error }
}

impl Io {
    fn emit(&mut self, ev: Event) {
        self.pending.push(ev);
    }

    fn flush_events(&mut self) {
        if self.pending.is_empty() || self.shared.teardown.load(Ordering::SeqCst) {
            self.pending.clear();
            return;
        }
        let was_empty = {
            let mut inbox = self.shared.inbox.lock().unwrap();
            let was_empty = inbox.is_empty();
            inbox.append(&mut self.pending);
            was_empty
        };
        if was_empty {
            (self.notify)();
        }
    }

    fn run(&mut self, p: Params) {
        let ws = match self.connect(&p) {
            Ok(ws) => ws,
            Err(e) => {
                if !self.shared.teardown.load(Ordering::SeqCst) {
                    if !self.shared.cancel.is_cancelled() {
                        eprintln!("[net] WebSocket connection to '{}' failed: {e}", p.url);
                    }
                    self.emit(abnormal(true));
                    self.flush_events();
                }
                return;
            }
        };
        self.session(ws);
        self.flush_events();
    }

    fn connect(&mut self, p: &Params) -> Result<WebSocket<Stream>, NetError> {
        let url = Url::parse(&p.url)?;
        let conn = conn::connect(&url.ep, Purpose::WebSocket, &self.shared.cancel)?;
        let stream = conn.stream;
        let _ = stream.tcp().set_read_timeout(Some(HANDSHAKE_TIMEOUT));

        let bad = |e: tungstenite::Error| NetError::new("ERR_INVALID_URL", e.to_string());
        let mut req = p.url.as_str().into_client_request().map_err(bad)?;
        let h = req.headers_mut();
        let mut put = |k: &'static str, v: &str| {
            if let Ok(v) = v.parse() {
                h.insert(k, v);
            }
        };
        put("Pragma", "no-cache");
        put("Cache-Control", "no-cache");
        put("User-Agent", &p.user_agent);
        if !p.origin.is_empty() {
            put("Origin", &p.origin);
        }
        if !p.accept_language.is_empty() {
            put("Accept-Language", &p.accept_language);
        }
        if !p.protocols.is_empty() {
            put("Sec-WebSocket-Protocol", &p.protocols.join(", "));
        }
        let config = WebSocketConfig::default();
        let (mut ws, resp) = match tungstenite::client::client_with_config(req, stream, Some(config)) {
            Ok(r) => r,
            Err(tungstenite::HandshakeError::Failure(e)) => {
                if self.shared.cancel.is_cancelled() {
                    return Err(NetError::aborted());
                }
                let detail = match &e {
                    tungstenite::Error::Http(r) => format!("Unexpected response code: {}", r.status().as_u16()),
                    e => format!("Error during WebSocket handshake: {e}"),
                };
                return Err(NetError::new("ERR_WS_HANDSHAKE", detail));
            }
            Err(tungstenite::HandshakeError::Interrupted(_)) => return Err(NetError::new("ERR_TIMED_OUT", "handshake timed out")),
        };
        let header = |name: &str| resp.headers().get(name).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
        let protocol = header("sec-websocket-protocol");
        let extensions = header("sec-websocket-extensions");
        if !extensions.is_empty() {
            // We offered none; an extension we cannot speak would corrupt every frame.
            return Err(NetError::new("ERR_WS_HANDSHAKE", "server selected an extension that was not offered"));
        }
        // From here on, reads are drained without blocking; writes still block (bounded).
        let sock = ws.get_mut().sock_mut();
        sock.set_nonblocking_reads(true);
        let _ = sock.tcp.set_read_timeout(None);
        self.shared.cancel.release();
        self.shared.open.store(true, Ordering::SeqCst);
        if self.shared.cancel.is_cancelled() {
            return Err(NetError::aborted());
        }
        self.emit(Event::Open { protocol, extensions });
        self.flush_events();
        Ok(ws)
    }

    fn session(&mut self, mut ws: WebSocket<Stream>) {
        let sock_fd = ws.get_ref().tcp().as_raw_fd();
        let wake_fd = self.wake_rx.as_raw_fd();
        let mut st = State { last_rx: Instant::now(), ping_deadline: None, close_deadline: None, peer_close: None, we_closed: false };
        // Frames may have arrived together with the handshake response.
        let mut readable = true;
        loop {
            if self.shared.teardown.load(Ordering::SeqCst) {
                if !st.we_closed && st.peer_close.is_none() {
                    let _ = ws.close(Some(CloseFrame { code: CloseCode::Away, reason: "".into() }));
                }
                return;
            }
            if readable {
                if let Flow::Done(ev) = self.drain_reads(&mut ws, &mut st) {
                    if let Some(ev) = ev {
                        self.emit(ev);
                    }
                    return;
                }
            }
            if let Flow::Done(ev) = self.run_commands(&mut ws, &mut st) {
                if let Some(ev) = ev {
                    self.emit(ev);
                }
                return;
            }
            self.flush_events();

            let now = Instant::now();
            let mut deadline = st.ping_deadline.unwrap_or(st.last_rx + IDLE_PING);
            if let Some(c) = st.close_deadline {
                deadline = deadline.min(c);
            }
            let wait = deadline.saturating_duration_since(now);
            let timeout = if wait.is_zero() { 0 } else { (wait.as_millis() as i32).saturating_add(1) };
            let mut fds = [
                libc::pollfd { fd: sock_fd, events: libc::POLLIN, revents: 0 },
                libc::pollfd { fd: wake_fd, events: libc::POLLIN, revents: 0 },
            ];
            let n = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) };
            if n < 0 {
                let e = io::Error::last_os_error();
                if e.kind() == io::ErrorKind::Interrupted {
                    continue;
                }
                self.emit(abnormal(true));
                return;
            }
            readable = fds[0].revents != 0;
            if fds[1].revents != 0 {
                let mut sink = [0u8; 64];
                while matches!((&self.wake_rx).read(&mut sink), Ok(n) if n > 0) {}
            }

            let now = Instant::now();
            if st.close_deadline.is_some_and(|c| now >= c) {
                // Closing handshake done but the server kept TCP open: clean. No reply: 1006.
                let ev = match st.peer_close.take() {
                    Some((code, reason)) => Event::Close { code, reason, clean: true, error: false },
                    None => abnormal(false),
                };
                self.emit(ev);
                return;
            }
            if st.ping_deadline.is_some_and(|p| now >= p) && !readable {
                eprintln!("[net] WebSocket peer stopped answering; closing");
                self.emit(abnormal(true));
                return;
            }
            if st.ping_deadline.is_none() && st.close_deadline.is_none() && now >= st.last_rx + IDLE_PING {
                if ws.send(Message::Ping(Default::default())).is_err() {
                    self.emit(abnormal(true));
                    return;
                }
                st.ping_deadline = Some(now + PING_TIMEOUT);
            }
        }
    }

    fn drain_reads(&mut self, ws: &mut WebSocket<Stream>, st: &mut State) -> Flow {
        loop {
            match ws.read() {
                Ok(msg) => {
                    st.last_rx = Instant::now();
                    st.ping_deadline = None;
                    match msg {
                        Message::Text(t) => self.emit(Event::Text(t.as_str().to_owned())),
                        Message::Binary(b) => self.emit(Event::Binary(b.to_vec())),
                        Message::Close(frame) => {
                            st.peer_close = Some(frame.map(|f| (u16::from(f.code), f.reason.as_str().to_owned())).unwrap_or((1005, String::new())));
                            st.close_deadline = Some(st.last_rx + CLOSE_LINGER);
                        }
                        Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => {}
                    }
                }
                Err(tungstenite::Error::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => return Flow::Continue,
                Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => {
                    let (code, reason) = st.peer_close.take().unwrap_or((1005, String::new()));
                    return Flow::Done(Some(Event::Close { code, reason, clean: true, error: false }));
                }
                Err(e) => {
                    // A reset after both close frames were exchanged is still a clean close.
                    if let Some((code, reason)) = st.peer_close.take() {
                        return Flow::Done(Some(Event::Close { code, reason, clean: true, error: false }));
                    }
                    if !matches!(e, tungstenite::Error::Protocol(tungstenite::error::ProtocolError::ResetWithoutClosingHandshake)) {
                        eprintln!("[net] WebSocket error: {e}");
                    }
                    return Flow::Done(Some(abnormal(true)));
                }
            }
        }
    }

    fn run_commands(&mut self, ws: &mut WebSocket<Stream>, st: &mut State) -> Flow {
        loop {
            let Some(cmd) = self.shared.cmds.lock().unwrap().pop_front() else { return Flow::Continue };
            let closing = st.we_closed || st.peer_close.is_some();
            let result = match cmd {
                Cmd::Text(s) => {
                    let n = s.len() as u64;
                    let r = if closing { Ok(()) } else { ws.send(Message::text(s)) };
                    self.shared.buffered.fetch_sub(n, Ordering::Relaxed);
                    r
                }
                Cmd::Binary(b) => {
                    let n = b.len() as u64;
                    let r = if closing { Ok(()) } else { ws.send(Message::binary(b)) };
                    self.shared.buffered.fetch_sub(n, Ordering::Relaxed);
                    r
                }
                Cmd::Close(frame) => {
                    if closing {
                        Ok(())
                    } else {
                        st.we_closed = true;
                        st.close_deadline = Some(Instant::now() + CLOSE_TIMEOUT);
                        st.ping_deadline = None;
                        let frame = frame.map(|(code, reason)| CloseFrame { code: CloseCode::from(code), reason: reason.into() });
                        ws.close(frame)
                    }
                }
                Cmd::Probe => {
                    let now = Instant::now();
                    if closing {
                        Ok(())
                    } else if let Some(p) = st.ping_deadline {
                        st.ping_deadline = Some(p.min(now + PROBE_TIMEOUT));
                        Ok(())
                    } else {
                        st.ping_deadline = Some(now + PROBE_TIMEOUT);
                        ws.send(Message::Ping(Default::default()))
                    }
                }
            };
            match result {
                Ok(()) | Err(tungstenite::Error::Protocol(tungstenite::error::ProtocolError::SendAfterClosing)) => {}
                Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => {
                    let (code, reason) = st.peer_close.take().unwrap_or((1005, String::new()));
                    return Flow::Done(Some(Event::Close { code, reason, clean: true, error: false }));
                }
                Err(e) => {
                    eprintln!("[net] WebSocket send failed: {e}");
                    return Flow::Done(Some(abnormal(true)));
                }
            }
        }
    }
}

struct State {
    last_rx: Instant,
    /// A ping is outstanding; the peer is dead if nothing arrives by then.
    ping_deadline: Option<Instant>,
    close_deadline: Option<Instant>,
    /// The peer's close frame (code, reason).
    peer_close: Option<(u16, String)>,
    we_closed: bool,
}