Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(websocket): drain queued data before starting close timeout
ldm094889f12b921
diff --git a/moli-websocket/src/session.rs b/moli-websocket/src/session.rsindex af6b92ddb..a1aa29875 100644--- a/moli-websocket/src/session.rs+++ b/moli-websocket/src/session.rs@@ -15,6 +15,9 @@ type Delivery = Pin<Box<dyn Future<Output = EventResult> + Send>>;type Sending = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;const CLOSE_TIMEOUT: Duration = Duration::from_secs(5);+#[cfg(test)]+mod tests;+struct Outgoing {data: Vec<u8>,opcode: FrameOpcode,@@ -180,7 +183,6 @@ impl Session {fn begin_close(&mut self, payload: Vec<u8>, publish_closing: bool) {if self.closing.requested.is_none() {self.closing.requested = Some(payload);- self.closing.deadline = Some(Instant::now() + CLOSE_TIMEOUT);if publish_closing {self.outbox.push_back(Event::Closing {socket_id: self.socket_id,@@ -226,6 +228,11 @@ impl Session {if !self.closing.sent&& let Some(data) = self.closing.requested.clone(){+ // Local close waits for previously accepted data. Only submitting+ // Close starts its handshake deadline, not draining that data.+ self.closing+ .deadline+ .get_or_insert_with(|| Instant::now() + CLOSE_TIMEOUT);return Some((CurlWebSocketSend {token: 0,@@ -256,6 +263,11 @@ impl Session {payload,} => {self.closing.received = Some((code, reason));+ // A peer Close already starts the handshake, even if a data+ // frame is still in flight. Do not extend an existing deadline.+ self.closing+ .deadline+ .get_or_insert_with(|| Instant::now() + CLOSE_TIMEOUT);self.outgoing.clear();self.pongs.clear();self.begin_close(payload, false);diff --git a/moli-websocket/src/session/tests.rs b/moli-websocket/src/session/tests.rsnew file mode 100644index 000000000..df65a9938--- /dev/null+++ b/moli-websocket/src/session/tests.rs@@ -0,0 +1,118 @@+use super::CLOSE_TIMEOUT;+use crate::{Command, Event, FrameOpcode, spawn_connection, test_support::*};+use futures_util::{SinkExt, StreamExt};+use tokio::{+ net::{TcpListener, TcpSocket},+ sync::{mpsc, oneshot},+ time::{Duration, timeout},+};+use tokio_tungstenite::tungstenite::Message;++#[tokio::test]+async fn native_close_waits_for_queued_data_before_starting_timeout() {+ const MESSAGE_BYTES: usize = 32 * 1024 * 1024;+ // Set the receive window before accepting TCP, then stop reading after the+ // upgrade. The admitted message must outlive the closing-handshake timeout.+ let socket = TcpSocket::new_v4().unwrap();+ socket.set_recv_buffer_size(128 * 1024).unwrap();+ socket.bind("127.0.0.1:0".parse().unwrap()).unwrap();+ let listener = socket.listen(1).unwrap();+ let url = format!("ws://{}/drain-before-close", listener.local_addr().unwrap());+ let (resume_tx, resume_rx) = oneshot::channel();+ let server = tokio::spawn(async move {+ let (stream, _) = listener.accept().await.unwrap();+ let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();+ if resume_rx.await.is_err() {+ return;+ }+ let message = socket.next().await.unwrap().unwrap();+ let Message::Binary(data) = message else {+ panic!("all queued data must precede Close");+ };+ assert_eq!(data.len(), MESSAGE_BYTES);+ assert!(+ data.iter()+ .enumerate()+ .all(|(i, byte)| *byte == (i % 251) as u8)+ );+ assert!(matches!(socket.next().await, Some(Ok(Message::Close(_)))));+ socket.flush().await.unwrap();+ });+ let (tx, mut rx) = mpsc::channel(8);+ let handle = spawn_connection(80, url, Vec::new(), test_websocket_context(), tx);+ recv_open_event(&mut rx).await;+ handle+ .send(Command::SendBinary(+ (0..MESSAGE_BYTES).map(|i| (i % 251) as u8).collect(),+ ))+ .unwrap();+ handle+ .send(Command::Close {+ code: Some(1000),+ reason: String::new(),+ })+ .unwrap();+ // Closing confirms the session has processed Close, while TCP backpressure+ // prevents the preceding message from completing. No handshake timer applies.+ assert_closing(&mut rx, 80).await;+ let premature = timeout(CLOSE_TIMEOUT + Duration::from_secs(1), rx.recv()).await;+ assert!(+ premature.is_err(),+ "queued data was interrupted: {premature:?}"+ );+ resume_tx.send(()).unwrap();+ assert_frame_sent(&mut rx, 80, FrameOpcode::Binary, MESSAGE_BYTES).await;+ assert_buffered_amount_consumed(&mut rx, 80, MESSAGE_BYTES).await;+ assert_close(&mut rx, 80, 1000, "", true).await;+ timeout(Duration::from_secs(3), server)+ .await+ .unwrap()+ .unwrap();+}++#[tokio::test]+async fn native_close_still_times_out_when_peer_never_answers_close() {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("ws://{}/unanswered-close", listener.local_addr().unwrap());+ let (close_tx, close_rx) = oneshot::channel();+ let (finish_tx, finish_rx) = oneshot::channel();+ let server = tokio::spawn(async move {+ let (stream, _) = listener.accept().await.unwrap();+ let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();+ assert!(matches!(socket.next().await, Some(Ok(Message::Close(_)))));+ close_tx.send(()).unwrap();+ // Keep TCP open without flushing tungstenite's queued Close reply.+ let _ = finish_rx.await;+ });+ let (tx, mut rx) = mpsc::channel(8);+ let handle = spawn_connection(81, url, Vec::new(), test_websocket_context(), tx);+ recv_open_event(&mut rx).await;+ handle+ .send(Command::Close {+ code: Some(1000),+ reason: String::new(),+ })+ .unwrap();+ assert_closing(&mut rx, 81).await;+ timeout(Duration::from_secs(3), close_rx)+ .await+ .unwrap()+ .unwrap();+ let event = timeout(CLOSE_TIMEOUT + Duration::from_secs(1), rx.recv())+ .await+ .expect("a sent Close still has a handshake deadline")+ .unwrap();+ assert!(+ matches!(event, Event::Error { socket_id: 81, ref message } if message == "WebSocket closing handshake timed out"),+ "expected closing handshake timeout, got {event:?}"+ );+ assert_close(&mut rx, 81, 1006, "", false).await;+ assert!(+ timeout(Duration::from_secs(3), rx.recv())+ .await+ .unwrap()+ .is_none()+ );+ finish_tx.send(()).unwrap();+ server.await.unwrap();+}