Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(websocket): expose connection and interception capabilities

ldm0add886da122c
diff --git a/moli-renderer-v8/src/native_bridge/context_host/websockets.rs b/moli-renderer-v8/src/native_bridge/context_host/websockets.rs
index 097441374..60009f458 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/websockets.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/websockets.rs
@@ -2,19 +2,20 @@ mod commands;
mod events;
mod registration;
-use moli_websocket::CommandSender as WebSocketCommandSender;
+use moli_websocket::ConnectionHandle as WebSocketConnectionHandle;
use url::Url;
pub(super) struct WebSocketConnectionState {
pub(super) owner: super::WindowExecutionContextBinding,
pub(super) resource_loader: Option<crate::network::context::DocumentResourceLoader>,
pub(super) wrapper: v8::Global<v8::Object>,
- pub(super) command_tx: Option<WebSocketCommandSender>,
+ pub(super) connection: Option<WebSocketConnectionHandle>,
pub(super) url: Url,
pub(super) frame_id: Option<String>,
pub(super) document_url: Url,
pub(super) opened: bool,
- pub(super) synthetic: bool,
+ pub(super) synthetic_peer: Option<moli_websocket::SyntheticPeer>,
+ pub(super) handshake_controller: Option<moli_websocket::HandshakeController>,
pub(super) fetch_internal_id: Option<u64>,
pub(super) response_interception_pending: Option<u64>,
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/websockets/commands.rs b/moli-renderer-v8/src/native_bridge/context_host/websockets/commands.rs
index 28486984e..7501c2336 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/websockets/commands.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/websockets/commands.rs
@@ -1,5 +1,4 @@
use super::super::JsContextHost;
-use moli_websocket::Command as WebSocketCommand;
impl JsContextHost {
pub(crate) fn signal_websocket_stream_pull(&self, socket_id: u64) {
@@ -9,16 +8,16 @@ impl JsContextHost {
pub(crate) fn send_websocket_text(&self, socket_id: u64, text: String) -> bool {
self.websockets
.get(&socket_id)
- .and_then(|state| state.command_tx.as_ref())
- .map(|command_tx| command_tx.send(WebSocketCommand::SendText(text)).is_ok())
+ .and_then(|state| state.connection.as_ref())
+ .map(|connection| connection.send_text(text).is_ok())
.unwrap_or(false)
}
pub(crate) fn send_websocket_binary(&self, socket_id: u64, bytes: Vec<u8>) -> bool {
self.websockets
.get(&socket_id)
- .and_then(|state| state.command_tx.as_ref())
- .map(|command_tx| command_tx.send(WebSocketCommand::SendBinary(bytes)).is_ok())
+ .and_then(|state| state.connection.as_ref())
+ .map(|connection| connection.send_binary(bytes).is_ok())
.unwrap_or(false)
}
@@ -30,34 +29,24 @@ impl JsContextHost {
) -> bool {
self.websockets
.get(&socket_id)
- .and_then(|state| state.command_tx.as_ref())
- .map(|command_tx| {
- command_tx
- .send(WebSocketCommand::Close { code, reason })
- .is_ok()
- })
+ .and_then(|state| state.connection.as_ref())
+ .map(|connection| connection.close(code, reason).is_ok())
.unwrap_or(false)
}
pub(crate) fn receive_synthetic_websocket_text(&self, socket_id: u64, data: String) -> bool {
self.websockets
.get(&socket_id)
- .filter(|state| state.synthetic)
- .and_then(|state| state.command_tx.as_ref())
- .map(|command_tx| command_tx.send(WebSocketCommand::ReceiveText(data)).is_ok())
+ .and_then(|state| state.synthetic_peer.as_ref())
+ .map(|connection| connection.send_text(data).is_ok())
.unwrap_or(false)
}
pub(crate) fn receive_synthetic_websocket_binary(&self, socket_id: u64, data: Vec<u8>) -> bool {
self.websockets
.get(&socket_id)
- .filter(|state| state.synthetic)
- .and_then(|state| state.command_tx.as_ref())
- .map(|command_tx| {
- command_tx
- .send(WebSocketCommand::ReceiveBinary(data))
- .is_ok()
- })
+ .and_then(|state| state.synthetic_peer.as_ref())
+ .map(|connection| connection.send_binary(data).is_ok())
.unwrap_or(false)
}
@@ -69,13 +58,8 @@ impl JsContextHost {
) -> bool {
self.websockets
.get(&socket_id)
- .filter(|state| state.synthetic)
- .and_then(|state| state.command_tx.as_ref())
- .map(|command_tx| {
- command_tx
- .send(WebSocketCommand::ServerClose { code, reason })
- .is_ok()
- })
+ .and_then(|state| state.synthetic_peer.as_ref())
+ .map(|connection| connection.close(code, reason).is_ok())
.unwrap_or(false)
}
@@ -139,8 +123,8 @@ impl JsContextHost {
let Some(state) = self.websockets.remove(&socket_id) else {
return false;
};
- if let Some(command_tx) = state.command_tx {
- command_tx.cancel();
+ if let Some(connection) = state.connection {
+ connection.cancel();
}
let internal_ids = [state.fetch_internal_id, state.response_interception_pending]
.into_iter()
diff --git a/moli-renderer-v8/src/native_bridge/context_host/websockets/registration.rs b/moli-renderer-v8/src/native_bridge/context_host/websockets/registration.rs
index 77760c80f..f54d05c80 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/websockets/registration.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/websockets/registration.rs
@@ -8,8 +8,9 @@ use crate::types::{
SubresourceResponseBody,
};
use moli_websocket::{
- Command as WebSocketCommand, ConnectOptions as WebSocketConnectOptions, spawn_connection,
- spawn_failed_connection, spawn_synthetic_connection, websocket_cookie_url,
+ ConnectOptions as WebSocketConnectOptions, spawn_connection,
+ spawn_connection_with_handshake_pause, spawn_failed_connection, spawn_synthetic_connection,
+ websocket_cookie_url,
};
use url::Url;
@@ -62,26 +63,25 @@ impl JsContextHost {
.map(|loader| loader.tls_config().clone())
.unwrap_or_default(),
cookie_header: cookie_header_for_context,
- pause_after_handshake: false,
};
let dispatch_scope = owner.dispatch_scope();
let csp_failure_message = csp_outcome.into_blocking_violation().map(|violation| {
document_content_security_policy_error_message(&violation, "WebSocket")
});
- let (command_tx, fetch_internal_id) = if let Some(message) = csp_failure_message {
- let command_tx = spawn_failed_connection(
+ let (connection, fetch_internal_id) = if let Some(message) = csp_failure_message {
+ let connection = spawn_failed_connection(
socket_id,
message,
self.page_websocket_sender().event_sender(),
);
- (Some(command_tx), None)
+ (Some(connection), None)
} else if self.is_url_blocked(&url) {
- let command_tx = spawn_failed_connection(
+ let connection = spawn_failed_connection(
socket_id,
BLOCKED_BY_CLIENT_ERROR_TEXT.to_owned(),
self.page_websocket_sender().event_sender(),
);
- (Some(command_tx), None)
+ (Some(connection), None)
} else if cookie_header.is_ok()
&& self.should_intercept_subresource(SubresourceResourceType::WebSocket)
{
@@ -111,7 +111,7 @@ impl JsContextHost {
);
(None, Some(internal_id))
} else {
- let command_tx = match cookie_header {
+ let connection = match cookie_header {
Ok(_) => spawn_connection(
socket_id,
url.to_string(),
@@ -125,7 +125,7 @@ impl JsContextHost {
self.page_websocket_sender().event_sender(),
),
};
- (Some(command_tx), None)
+ (Some(connection), None)
};
self.websockets.insert(
socket_id,
@@ -133,12 +133,13 @@ impl JsContextHost {
owner,
resource_loader,
wrapper: v8::Global::new(scope, wrapper),
- command_tx,
+ connection,
url,
frame_id,
document_url,
opened: false,
- synthetic: false,
+ synthetic_peer: None,
+ handshake_controller: None,
fetch_internal_id,
response_interception_pending: None,
},
@@ -163,16 +164,30 @@ impl JsContextHost {
if headers_overridden {
context.cookie_header = None;
}
- context.pause_after_handshake = intercept_response;
- let command_tx = spawn_connection(
- pending.socket_id,
- url.to_string(),
- pending.protocols,
- context,
- event_sender,
- );
+ let (connection, handshake_controller) = if intercept_response {
+ let (connection, controller) = spawn_connection_with_handshake_pause(
+ pending.socket_id,
+ url.to_string(),
+ pending.protocols,
+ context,
+ event_sender,
+ );
+ (connection, Some(controller))
+ } else {
+ (
+ spawn_connection(
+ pending.socket_id,
+ url.to_string(),
+ pending.protocols,
+ context,
+ event_sender,
+ ),
+ None,
+ )
+ };
+ state.handshake_controller = handshake_controller;
state.url = url;
- state.command_tx = Some(command_tx);
+ state.connection = Some(connection);
state.response_interception_pending =
if intercept_response {
Some(state.fetch_internal_id.ok_or_else(|| {
@@ -193,8 +208,8 @@ impl JsContextHost {
let Some(state) = self.websockets.get_mut(&pending.socket_id) else {
return Err(format!("unknown pending WebSocket `{}`", pending.socket_id));
};
- let command_tx = spawn_failed_connection(pending.socket_id, error_text, event_sender);
- state.command_tx = Some(command_tx);
+ let connection = spawn_failed_connection(pending.socket_id, error_text, event_sender);
+ state.connection = Some(connection);
Ok(())
}
@@ -210,7 +225,7 @@ impl JsContextHost {
let Some(state) = self.websockets.get_mut(&pending.socket_id) else {
return Err(format!("unknown pending WebSocket `{}`", pending.socket_id));
};
- let command_tx = spawn_synthetic_connection(
+ let (connection, peer) = spawn_synthetic_connection(
pending.socket_id,
request_headers,
response_status,
@@ -218,8 +233,8 @@ impl JsContextHost {
event_sender,
);
state.url = request_url;
- state.command_tx = Some(command_tx);
- state.synthetic = true;
+ state.connection = Some(connection);
+ state.synthetic_peer = Some(peer);
Ok(())
}
@@ -268,21 +283,18 @@ impl JsContextHost {
response_status: Option<u16>,
response_headers: Option<Vec<(String, String)>>,
) -> Result<(), String> {
- let Some(state) = self.websockets.get(&pending.socket_id) else {
+ let Some(state) = self.websockets.get_mut(&pending.socket_id) else {
return Err(format!("unknown pending WebSocket `{}`", pending.socket_id));
};
- let Some(command_tx) = state.command_tx.as_ref() else {
+ let Some(controller) = state.handshake_controller.take() else {
return Err(format!(
- "pending WebSocket `{}` has no command sender",
+ "pending WebSocket `{}` has no handshake controller",
pending.socket_id
));
};
- command_tx
- .send(WebSocketCommand::ContinueOpen {
- response_status,
- response_headers,
- })
- .map_err(|_| format!("pending WebSocket `{}` is closed", pending.socket_id))
+ controller
+ .continue_open(response_status, response_headers)
+ .map_err(|error| format!("pending WebSocket `{}`: {error}", pending.socket_id))
}
pub(crate) fn fail_websocket_handshake_response(
@@ -290,18 +302,18 @@ impl JsContextHost {
pending: PendingWebSocketResponseState,
error_text: String,
) -> Result<(), String> {
- let Some(state) = self.websockets.get(&pending.socket_id) else {
+ let Some(state) = self.websockets.get_mut(&pending.socket_id) else {
return Err(format!("unknown pending WebSocket `{}`", pending.socket_id));
};
- let Some(command_tx) = state.command_tx.as_ref() else {
+ let Some(controller) = state.handshake_controller.take() else {
return Err(format!(
- "pending WebSocket `{}` has no command sender",
+ "pending WebSocket `{}` has no handshake controller",
pending.socket_id
));
};
- command_tx
- .send(WebSocketCommand::FailOpen(error_text))
- .map_err(|_| format!("pending WebSocket `{}` is closed", pending.socket_id))
+ controller
+ .fail(error_text)
+ .map_err(|error| format!("pending WebSocket `{}`: {error}", pending.socket_id))
}
}
diff --git a/moli-renderer-v8/src/worker/global_scope/fetch.rs b/moli-renderer-v8/src/worker/global_scope/fetch.rs
index 562848188..16c3dd19e 100644
--- a/moli-renderer-v8/src/worker/global_scope/fetch.rs
+++ b/moli-renderer-v8/src/worker/global_scope/fetch.rs
@@ -1290,7 +1290,6 @@ pub(crate) fn register_worker_websocket<'s>(
.map(ToOwned::to_owned),
tls: loader.request_client().tls_config().clone(),
cookie_header: cookie_header_for_context,
- pause_after_handshake: false,
};
let csp_failure = csp_outcome.into_failure_message();
@@ -1307,7 +1306,7 @@ pub(crate) fn register_worker_websocket<'s>(
.map(|error| format!("failed to build WebSocket cookie header: {error}"))
};
let network_recorded = failure_message.is_some();
- let (command_tx, load) = if let Some(error_text) = failure_message {
+ let (connection, load) = if let Some(error_text) = failure_message {
record_worker_websocket_subresource_failure(
&state.borrow(),
socket_id,
@@ -1326,25 +1325,25 @@ pub(crate) fn register_worker_websocket<'s>(
ResourceLoadDisposition::Ordinary,
None,
)?;
- let command_tx = spawn_connection(
+ let connection = spawn_connection(
socket_id,
url.to_string(),
protocols,
context,
websocket_event_tx,
);
- let cancel_tx = command_tx.clone();
+ let cancel_tx = connection.clone();
load.attach_consumer_cancel(move || {
cancel_tx.cancel();
});
- (command_tx, Some(load))
+ (connection, Some(load))
};
state.borrow_mut().websockets.insert(
socket_id,
WorkerWebSocketState {
wrapper: v8::Global::new(scope, wrapper),
- command_tx,
+ connection,
document_url,
url,
loader,
@@ -1362,13 +1361,13 @@ pub(crate) fn send_worker_websocket_text(
text: String,
) -> Option<bool> {
let state = get_worker_state(scope)?;
- let command_tx = state
+ let connection = state
.borrow()
.websockets
.get(&socket_id)?
- .command_tx
+ .connection
.clone();
- Some(command_tx.send(WebSocketCommand::SendText(text)).is_ok())
+ Some(connection.send_text(text).is_ok())
}
pub(crate) fn send_worker_websocket_binary(
@@ -1377,13 +1376,13 @@ pub(crate) fn send_worker_websocket_binary(
bytes: Vec<u8>,
) -> Option<bool> {
let state = get_worker_state(scope)?;
- let command_tx = state
+ let connection = state
.borrow()
.websockets
.get(&socket_id)?
- .command_tx
+ .connection
.clone();
- Some(command_tx.send(WebSocketCommand::SendBinary(bytes)).is_ok())
+ Some(connection.send_binary(bytes).is_ok())
}
pub(crate) fn close_worker_websocket(
@@ -1393,17 +1392,13 @@ pub(crate) fn close_worker_websocket(
reason: String,
) -> Option<bool> {
let state = get_worker_state(scope)?;
- let command_tx = state
+ let connection = state
.borrow()
.websockets
.get(&socket_id)?
- .command_tx
+ .connection
.clone();
- Some(
- command_tx
- .send(WebSocketCommand::Close { code, reason })
- .is_ok(),
- )
+ Some(connection.close(code, reason).is_ok())
}
pub(in crate::worker) fn dispatch_worker_websocket_event(
diff --git a/moli-renderer-v8/src/worker/global_scope/mod.rs b/moli-renderer-v8/src/worker/global_scope/mod.rs
index 84ff964b0..53131ad6f 100644
--- a/moli-renderer-v8/src/worker/global_scope/mod.rs
+++ b/moli-renderer-v8/src/worker/global_scope/mod.rs
@@ -43,9 +43,8 @@ use moli_storage_key::MoliStorageKey;
use moli_webapi_declare::{ObjectLiteralDeclaration, WebApiFunctionTemplate, WebApiObject};
use moli_webidl_callback::WebIdlCallbackInterface;
use moli_websocket::{
- Command as WebSocketCommand, CommandSender as WebSocketCommandSender,
- ConnectOptions as WebSocketConnectOptions, Event as WebSocketEvent, spawn_connection,
- spawn_failed_connection, websocket_cookie_url,
+ ConnectOptions as WebSocketConnectOptions, ConnectionHandle as WebSocketConnectionHandle,
+ Event as WebSocketEvent, spawn_connection, spawn_failed_connection, websocket_cookie_url,
};
use tokio::sync::mpsc;
use url::Url;
@@ -1275,7 +1274,7 @@ impl WorkerXhrResponse {
pub(super) struct WorkerWebSocketState {
pub(super) wrapper: v8::Global<v8::Object>,
- pub(super) command_tx: WebSocketCommandSender,
+ pub(super) connection: WebSocketConnectionHandle,
pub(super) document_url: Url,
pub(super) url: Url,
pub(super) loader: crate::network::context::WorkerResourceLoader,
diff --git a/moli-websocket/src/commands.rs b/moli-websocket/src/commands.rs
index 082a4fb95..9f4a2edad 100644
--- a/moli-websocket/src/commands.rs
+++ b/moli-websocket/src/commands.rs
@@ -1,6 +1,6 @@
//! Bounded synchronous admission. Reservations live until native completion,
//! rejection or cancellation, rather than being released at channel dequeue.
-use crate::{Command, CommandSendError};
+use crate::{Command, SendError};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
@@ -9,7 +9,7 @@ use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore, mpsc};
pub(crate) const MAX_QUEUED_BYTES: usize = 64 * 1024 * 1024;
pub(crate) const MAX_QUEUED_MESSAGES: usize = 256;
-const MAX_CONTROL_BYTES: usize = 64 * 1024;
+pub(crate) const MAX_CONTROL_BYTES: usize = 64 * 1024;
#[derive(Debug)]
struct Admission {
@@ -67,9 +67,9 @@ pub(crate) fn command_channel() -> (CommandPort, CommandReceiver) {
}
impl CommandPort {
- pub fn send(&self, command: Command) -> Result<(), CommandSendError> {
+ pub fn send(&self, command: Command) -> Result<(), SendError> {
if self.is_closed() {
- return Err(CommandSendError(command));
+ return Err(SendError::Closed);
}
if matches!(command, Command::Close { .. })
&& self.admission.close_queued.load(Ordering::Acquire)
@@ -81,7 +81,7 @@ impl CommandPort {
None => {
self.admission.failed.store(true, Ordering::Release);
self.admission.failure.notify_one();
- return Err(CommandSendError(command));
+ return Err(SendError::CapacityExceeded);
}
};
if matches!(command, Command::Close { .. })
@@ -94,7 +94,7 @@ impl CommandPort {
command,
reservation,
})
- .map_err(|error| CommandSendError(error.0.command))
+ .map_err(|_| SendError::Closed)
}
pub fn is_closed(&self) -> bool {
@@ -124,19 +124,7 @@ impl CommandPort {
let size = match command {
Command::Close { reason, .. }
| Command::ServerClose { reason, .. }
- | Command::FailOpen(reason) => reason.len(),
- Command::ContinueOpen {
- response_headers, ..
- } => response_headers
- .as_ref()
- .map(|headers| {
- headers.iter().fold(0usize, |sum, (name, value)| {
- sum.saturating_add(name.len())
- .saturating_add(value.len())
- .saturating_add(4)
- })
- })
- .unwrap_or(0),
+ | Command::Fail(reason) => reason.len(),
_ => unreachable!(),
};
if size > MAX_CONTROL_BYTES {
@@ -157,7 +145,7 @@ impl CommandReceiver {
if !self.failure_delivered && self.admission.failed.load(Ordering::Acquire) {
self.failure_delivered = true;
return Some(QueuedCommand {
- command: Command::FailOpen("WebSocket send queue capacity exceeded".to_owned()),
+ command: Command::Fail("WebSocket send queue capacity exceeded".to_owned()),
reservation: Reservation {
_permits: Vec::new(),
},
@@ -184,11 +172,14 @@ mod tests {
}
let pending_native_send = receiver.recv().await.unwrap();
assert!(
- port.send(Command::SendText(String::new())).is_err(),
+ matches!(
+ port.send(Command::SendText(String::new())),
+ Err(SendError::CapacityExceeded)
+ ),
"dequeue must not release the zero-length message count"
);
assert!(
- matches!(receiver.recv().await.unwrap().command, Command::FailOpen(_)),
+ matches!(receiver.recv().await.unwrap().command, Command::Fail(_)),
"overflow is delivered even when the data queue is full"
);
drop(pending_native_send);
diff --git a/moli-websocket/src/connection.rs b/moli-websocket/src/connection.rs
index e583ff26c..11f520e79 100644
--- a/moli-websocket/src/connection.rs
+++ b/moli-websocket/src/connection.rs
@@ -2,6 +2,7 @@ use crate::{
Command, ConnectOptions, Event,
commands::CommandReceiver,
events::{EventResult, EventSender, send_error_and_close, send_event},
+ handle::HandshakeDecision,
headers::header_map_entries,
limits::{acquire_pending_websocket_handshake_slot, acquire_websocket_connection_slot},
request::build_websocket_request,
@@ -15,6 +16,7 @@ pub(crate) async fn run_websocket_connection(
context: ConnectOptions,
mut command_rx: CommandReceiver,
event_tx: EventSender,
+ decision: Option<tokio::sync::oneshot::Receiver<HandshakeDecision>>,
) -> EventResult {
let Some(_connection_slot) = acquire_websocket_connection_slot() else {
send_error_and_close(
@@ -69,8 +71,7 @@ pub(crate) async fn run_websocket_connection(
// should only appear from direct crate users. Ignore them rather than
// queueing frames before the opening handshake has succeeded.
}
- Some(Command::ContinueOpen { .. }) => {}
- Some(Command::FailOpen(message)) => {
+ Some(Command::Fail(message)) => {
drop(pending_handshake_slot);
send_error_and_close(&event_tx, socket_id, message).await?;
return Ok(());
@@ -101,7 +102,7 @@ pub(crate) async fn run_websocket_connection(
let mut response_status = response.status().as_u16();
let mut response_headers = header_map_entries(response.headers());
- if context.pause_after_handshake {
+ if let Some(mut decision) = decision {
send_event(
&event_tx,
Event::HandshakeResponse {
@@ -119,41 +120,45 @@ pub(crate) async fn run_websocket_connection(
)
.await?;
loop {
- match command_rx.recv().await.map(|queued| queued.command) {
- Some(Command::ContinueOpen {
- response_status: override_status,
- response_headers: override_headers,
- }) => {
- if let Some(override_status) = override_status {
- response_status = override_status;
+ tokio::select! {
+ // A Close already admitted while paused must precede Open.
+ biased;
+ command = command_rx.recv() => {
+ match command.map(|queued| queued.command) {
+ Some(Command::Fail(message)) => {
+ drop(stream);
+ send_error_and_close(&event_tx, socket_id, message).await?;
+ return Ok(());
+ }
+ Some(Command::Close { .. }) => {
+ drop(stream);
+ send_error_and_close(
+ &event_tx, socket_id,
+ "WebSocket connection closed before opening".to_owned(),
+ ).await?;
+ return Ok(());
+ }
+ None => return Ok(()),
+ // The browser rejects sends until the Open event.
+ _ => {}
}
- if let Some(override_headers) = override_headers {
- response_headers = override_headers;
- }
- break;
- }
- Some(Command::FailOpen(message)) => {
- send_error_and_close(&event_tx, socket_id, message).await?;
- return Ok(());
}
- Some(Command::Close { .. }) => {
- send_error_and_close(
- &event_tx,
- socket_id,
- "WebSocket connection closed before opening".to_owned(),
- )
- .await?;
- return Ok(());
- }
- Some(Command::SendText(_))
- | Some(Command::SendBinary(_))
- | Some(Command::ReceiveText(_))
- | Some(Command::ReceiveBinary(_))
- | Some(Command::ServerClose { .. }) => {
- // Browser-visible `send()` throws until the open event, so crate users
- // cannot enqueue application data while a response-stage pause is active.
+ decision = &mut decision => {
+ match decision.unwrap_or_else(|_| HandshakeDecision::Fail(
+ "WebSocket handshake decision was dropped".to_owned(),
+ )) {
+ HandshakeDecision::Continue { response_status: status, response_headers: headers } => {
+ if let Some(status) = status { response_status = status; }
+ if let Some(headers) = headers { response_headers = headers; }
+ break;
+ }
+ HandshakeDecision::Fail(message) => {
+ drop(stream);
+ send_error_and_close(&event_tx, socket_id, message).await?;
+ return Ok(());
+ }
+ }
}
- None => return Ok(()),
}
}
}
diff --git a/moli-websocket/src/handle.rs b/moli-websocket/src/handle.rs
index 7bfefd267..4cdd18b8f 100644
--- a/moli-websocket/src/handle.rs
+++ b/moli-websocket/src/handle.rs
@@ -1,9 +1,10 @@
use std::sync::{
- Arc,
+ Arc, Weak,
atomic::{AtomicBool, Ordering},
};
-use crate::commands::CommandPort;
+use crate::commands::{CommandPort, MAX_CONTROL_BYTES};
+use tokio::sync::oneshot;
use tokio::task::AbortHandle;
use crate::Command;
@@ -12,7 +13,7 @@ use crate::Command;
///
/// Clones keep the connection alive. Dropping the last handle or calling
/// `cancel` releases the connection even while its handshake, write, or event
-/// sink is waiting. Use `Command::Close` for the graceful closing handshake.
+/// sink is waiting. Use `close` for the graceful closing handshake.
#[derive(Clone, Debug)]
pub struct ConnectionHandle {
inner: Arc<ConnectionControl>,
@@ -36,10 +37,31 @@ impl ConnectionHandle {
}
}
+ /// Admits browser-validated text without waiting for network I/O or delivery.
+ pub fn send_text(&self, text: String) -> Result<(), SendError> {
+ self.send(Command::SendText(text))
+ }
+
+ /// Admits browser-validated binary data without waiting for network I/O.
+ pub fn send_binary(&self, data: Vec<u8>) -> Result<(), SendError> {
+ self.send(Command::SendBinary(data))
+ }
+
+ /// Requests graceful closure after previously admitted messages are sent.
+ pub fn close(&self, code: Option<u16>, reason: String) -> Result<(), SendError> {
+ self.send(Command::Close { code, reason })
+ }
+
+ pub(crate) fn synthetic_peer(&self) -> SyntheticPeer {
+ SyntheticPeer {
+ inner: Arc::downgrade(&self.inner),
+ }
+ }
+
/// Enqueues a command without waiting for network I/O or event delivery.
- pub fn send(&self, command: Command) -> Result<(), CommandSendError> {
+ pub(crate) fn send(&self, command: Command) -> Result<(), SendError> {
if self.inner.cancelled.load(Ordering::Acquire) {
- return Err(CommandSendError(command));
+ return Err(SendError::Closed);
}
self.inner.command_tx.send(command)
}
@@ -53,22 +75,116 @@ impl ConnectionHandle {
self.inner.task.abort();
}
+ /// Whether command admission has ended, independently of JS readyState.
pub fn is_closed(&self) -> bool {
self.inner.cancelled.load(Ordering::Acquire) || self.inner.command_tx.is_closed()
}
}
-/// A command rejected because the connection is no longer available.
-#[derive(Debug)]
-pub struct CommandSendError(pub Command);
+/// Why synchronous connection admission failed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SendError {
+ Closed,
+ CapacityExceeded,
+}
-impl std::fmt::Display for CommandSendError {
+impl std::fmt::Display for SendError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.write_str("WebSocket connection is closed")
+ f.write_str(match self {
+ Self::Closed => "WebSocket connection is closed",
+ Self::CapacityExceeded => "WebSocket queue capacity exceeded",
+ })
+ }
+}
+impl std::error::Error for SendError {}
+
+/// A single decision for a connection paused after its native handshake.
+///
+/// Decisions apply after the handshake response. Dropping the controller
+/// without deciding fails the opening connection. It does not keep the
+/// connection alive after the last `ConnectionHandle` is dropped.
+#[derive(Debug)]
+pub struct HandshakeController {
+ decision: oneshot::Sender<HandshakeDecision>,
+}
+
+#[derive(Debug)]
+pub(crate) enum HandshakeDecision {
+ Continue {
+ response_status: Option<u16>,
+ response_headers: Option<Vec<(String, String)>>,
+ },
+ Fail(String),
+}
+
+impl HandshakeController {
+ pub(crate) fn new(decision: oneshot::Sender<HandshakeDecision>) -> Self {
+ Self { decision }
+ }
+
+ pub fn continue_open(
+ self,
+ response_status: Option<u16>,
+ response_headers: Option<Vec<(String, String)>>,
+ ) -> Result<(), SendError> {
+ self.decide(HandshakeDecision::Continue {
+ response_status,
+ response_headers,
+ })
+ }
+
+ pub fn fail(self, message: String) -> Result<(), SendError> {
+ self.decide(HandshakeDecision::Fail(message))
+ }
+
+ fn decide(self, decision: HandshakeDecision) -> Result<(), SendError> {
+ let bytes = match &decision {
+ HandshakeDecision::Continue {
+ response_headers, ..
+ } => response_headers
+ .as_ref()
+ .map(|headers| {
+ headers.iter().fold(0usize, |sum, (name, value)| {
+ sum.saturating_add(name.len())
+ .saturating_add(value.len())
+ .saturating_add(4)
+ })
+ })
+ .unwrap_or(0),
+ HandshakeDecision::Fail(message) => message.len(),
+ };
+ if bytes > MAX_CONTROL_BYTES {
+ let _ = self.decision.send(HandshakeDecision::Fail(
+ "WebSocket handshake decision capacity exceeded".to_owned(),
+ ));
+ return Err(SendError::CapacityExceeded);
+ }
+ self.decision.send(decision).map_err(|_| SendError::Closed)
}
}
-impl std::error::Error for CommandSendError {}
+/// The injecting peer of a synthetic connection. Only synthetic creation
+/// returns this capability; retaining it does not keep the client alive.
+#[derive(Clone, Debug)]
+pub struct SyntheticPeer {
+ inner: Weak<ConnectionControl>,
+}
+
+impl SyntheticPeer {
+ pub fn send_text(&self, text: String) -> Result<(), SendError> {
+ self.send(Command::ReceiveText(text))
+ }
+ pub fn send_binary(&self, data: Vec<u8>) -> Result<(), SendError> {
+ self.send(Command::ReceiveBinary(data))
+ }
+ pub fn close(&self, code: Option<u16>, reason: String) -> Result<(), SendError> {
+ self.send(Command::ServerClose { code, reason })
+ }
+ fn send(&self, command: Command) -> Result<(), SendError> {
+ let inner = self.inner.upgrade().ok_or(SendError::Closed)?;
+ ConnectionHandle { inner }.send(command)
+ }
+}
/// Child tasks must not outlive the connection task when it is cancelled.
#[derive(Debug)]
diff --git a/moli-websocket/src/lib.rs b/moli-websocket/src/lib.rs
index fcfef3e89..f069a2686 100644
--- a/moli-websocket/src/lib.rs
+++ b/moli-websocket/src/lib.rs
@@ -18,7 +18,7 @@ mod types;
pub use cookie::websocket_cookie_url;
pub use events::EventSender;
-pub use handle::{CommandSendError, ConnectionHandle};
+pub use handle::{ConnectionHandle, HandshakeController, SendError, SyntheticPeer};
pub use protocol::{
WebSocketCloseRequest, WebSocketCloseValidationError, WebSocketSubprotocolError,
WebSocketUrlError, close_info_code_from_number, default_close_code_for_reason,
@@ -26,8 +26,12 @@ pub use protocol::{
normalize_websocket_close_info, normalize_websocket_url, validate_subprotocols,
validate_websocket_close_request, websocket_url_is_potentially_trustworthy,
};
-pub use runtime::{spawn_connection, spawn_failed_connection, spawn_synthetic_connection};
-pub use types::{Command, CommandSender, ConnectOptions, Event, FrameOpcode};
+pub use runtime::{
+ spawn_connection, spawn_connection_with_handshake_pause, spawn_failed_connection,
+ spawn_synthetic_connection,
+};
+pub(crate) use types::Command;
+pub use types::{ConnectOptions, Event, FrameOpcode};
#[cfg(any(test, feature = "test-support"))]
pub mod test_support;
diff --git a/moli-websocket/src/native_tests.rs b/moli-websocket/src/native_tests.rs
index 179affa21..9782218a0 100644
--- a/moli-websocket/src/native_tests.rs
+++ b/moli-websocket/src/native_tests.rs
@@ -1,4 +1,4 @@
-use crate::{Command, Event, FrameOpcode, spawn_connection, test_support::*};
+use crate::{Event, FrameOpcode, spawn_connection, test_support::*};
use futures_util::{SinkExt, StreamExt};
use tokio::{
io::AsyncWriteExt,
@@ -27,21 +27,14 @@ async fn native_send_accounting_does_not_require_a_server_echo() {
let (tx, mut rx) = mpsc::channel(8);
let handle = spawn_connection(70, url, Vec::new(), test_websocket_context(), tx);
recv_open_event(&mut rx).await;
- handle
- .send(Command::SendText("without echo".to_owned()))
- .unwrap();
+ handle.send_text("without echo".to_owned()).unwrap();
assert_frame_sent(&mut rx, 70, FrameOpcode::Text, 12).await;
assert_buffered_amount_consumed(&mut rx, 70, 12).await;
timeout(Duration::from_secs(3), received_rx)
.await
.unwrap()
.unwrap();
- handle
- .send(Command::Close {
- code: Some(1000),
- reason: String::new(),
- })
- .unwrap();
+ handle.close(Some(1000), String::new()).unwrap();
assert_closing(&mut rx, 70).await;
assert_close(&mut rx, 70, 1000, "", true).await;
server.await.unwrap();
@@ -61,10 +54,7 @@ async fn native_local_close_without_peer_close_is_abnormal_once() {
let handle = spawn_connection(71, url, Vec::new(), test_websocket_context(), tx);
recv_open_event(&mut rx).await;
handle
- .send(Command::Close {
- code: Some(3001),
- reason: "not acknowledged".to_owned(),
- })
+ .close(Some(3001), "not acknowledged".to_owned())
.unwrap();
assert_closing(&mut rx, 71).await;
assert!(matches!(
@@ -118,12 +108,7 @@ async fn native_fragmented_utf8_and_ping_are_assembled_as_one_message() {
recv_open_event(&mut rx).await;
assert_text_message(&mut rx, 72, "🙂").await;
assert_binary_message(&mut rx, 72, &[]).await;
- handle
- .send(Command::Close {
- code: Some(1000),
- reason: String::new(),
- })
- .unwrap();
+ handle.close(Some(1000), String::new()).unwrap();
assert_closing(&mut rx, 72).await;
assert_close(&mut rx, 72, 1000, "", true).await;
server.await.unwrap();
@@ -184,12 +169,7 @@ async fn native_large_incoming_frame_keeps_chunk_offsets_and_utf8() {
let handle = spawn_connection(74, url, Vec::new(), test_websocket_context(), tx);
recv_open_event(&mut rx).await;
assert_text_message(&mut rx, 74, &expected).await;
- handle
- .send(Command::Close {
- code: Some(1000),
- reason: String::new(),
- })
- .unwrap();
+ handle.close(Some(1000), String::new()).unwrap();
assert_closing(&mut rx, 74).await;
assert_close(&mut rx, 74, 1000, "", true).await;
server.await.unwrap();
@@ -238,12 +218,7 @@ async fn native_close_handshake_finishes_while_message_sink_is_blocked() {
timeout(Duration::from_secs(3), blocked.notified())
.await
.unwrap();
- handle
- .send(Command::Close {
- code: Some(1000),
- reason: String::new(),
- })
- .unwrap();
+ handle.close(Some(1000), String::new()).unwrap();
timeout(Duration::from_secs(3), released_rx)
.await
.expect("physical close must not wait for the event sink or closing timeout")
diff --git a/moli-websocket/src/runtime.rs b/moli-websocket/src/runtime.rs
index f5d91602e..4593c69ab 100644
--- a/moli-websocket/src/runtime.rs
+++ b/moli-websocket/src/runtime.rs
@@ -3,9 +3,9 @@ use std::sync::OnceLock;
use crate::commands::command_channel;
use crate::{
- CommandSender, ConnectOptions, ConnectionHandle, connection::run_websocket_connection,
- events::EventSender, events::send_error_and_close,
- synthetic::run_synthetic_websocket_connection,
+ ConnectOptions, ConnectionHandle, HandshakeController, SyntheticPeer,
+ connection::run_websocket_connection, events::EventSender, events::send_error_and_close,
+ handle::HandshakeDecision, synthetic::run_synthetic_websocket_connection,
};
pub fn spawn_connection(
@@ -14,12 +14,44 @@ pub fn spawn_connection(
protocols: Vec<String>,
context: ConnectOptions,
event_tx: impl Into<EventSender>,
-) -> CommandSender {
- let event_tx = event_tx.into();
+) -> ConnectionHandle {
+ spawn_native_connection(socket_id, url, protocols, context, event_tx.into(), None)
+}
+
+/// Starts a native connection whose browser Open awaits one explicit decision.
+pub fn spawn_connection_with_handshake_pause(
+ socket_id: u64,
+ url: String,
+ protocols: Vec<String>,
+ context: ConnectOptions,
+ event_tx: impl Into<EventSender>,
+) -> (ConnectionHandle, HandshakeController) {
+ let (decision, receiver) = tokio::sync::oneshot::channel();
+ let connection = spawn_native_connection(
+ socket_id,
+ url,
+ protocols,
+ context,
+ event_tx.into(),
+ Some(receiver),
+ );
+ (connection, HandshakeController::new(decision))
+}
+
+fn spawn_native_connection(
+ socket_id: u64,
+ url: String,
+ protocols: Vec<String>,
+ context: ConnectOptions,
+ event_tx: EventSender,
+ decision: Option<tokio::sync::oneshot::Receiver<HandshakeDecision>>,
+) -> ConnectionHandle {
let (command_tx, command_rx) = command_channel();
let task = websocket_runtime().spawn(async move {
- let _ = run_websocket_connection(socket_id, url, protocols, context, command_rx, event_tx)
- .await;
+ let _ = run_websocket_connection(
+ socket_id, url, protocols, context, command_rx, event_tx, decision,
+ )
+ .await;
});
ConnectionHandle::new(command_tx, task.abort_handle())
}
@@ -28,7 +60,7 @@ pub fn spawn_failed_connection(
socket_id: u64,
message: String,
event_tx: impl Into<EventSender>,
-) -> CommandSender {
+) -> ConnectionHandle {
let event_tx = event_tx.into();
let (command_tx, _command_rx) = command_channel();
let task = websocket_runtime().spawn(async move {
@@ -43,7 +75,7 @@ pub fn spawn_synthetic_connection(
response_status: u16,
response_headers: Vec<(String, String)>,
event_tx: impl Into<EventSender>,
-) -> CommandSender {
+) -> (ConnectionHandle, SyntheticPeer) {
let event_tx = event_tx.into();
let (command_tx, command_rx) = command_channel();
let task = websocket_runtime().spawn(async move {
@@ -57,7 +89,9 @@ pub fn spawn_synthetic_connection(
)
.await;
});
- ConnectionHandle::new(command_tx, task.abort_handle())
+ let connection = ConnectionHandle::new(command_tx, task.abort_handle());
+ let peer = connection.synthetic_peer();
+ (connection, peer)
}
fn websocket_runtime() -> &'static tokio::runtime::Runtime {
diff --git a/moli-websocket/src/session.rs b/moli-websocket/src/session.rs
index 3e90b7d78..80946fae9 100644
--- a/moli-websocket/src/session.rs
+++ b/moli-websocket/src/session.rs
@@ -235,7 +235,7 @@ impl Session {
Err(error) => self.fail(error),
}
}
- Command::FailOpen(message) => self.fail(message),
+ Command::Fail(message) => self.fail(message),
_ => {}
}
}
diff --git a/moli-websocket/src/session/tests.rs b/moli-websocket/src/session/tests.rs
index f6814e9d7..97b8a81d8 100644
--- a/moli-websocket/src/session/tests.rs
+++ b/moli-websocket/src/session/tests.rs
@@ -42,16 +42,9 @@ async fn native_close_waits_for_queued_data_before_starting_timeout() {
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(),
- })
+ .send_binary((0..MESSAGE_BYTES).map(|i| (i % 251) as u8).collect())
.unwrap();
+ handle.close(Some(1000), 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;
@@ -87,12 +80,7 @@ async fn native_close_still_times_out_when_peer_never_answers_close() {
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();
+ handle.close(Some(1000), String::new()).unwrap();
assert_closing(&mut rx, 81).await;
timeout(Duration::from_secs(3), close_rx)
.await
@@ -169,9 +157,7 @@ async fn native_fragmented_sends_complete_while_incoming_sink_is_blocked() {
.await
.unwrap();
for byte in [17, 29] {
- handle
- .send(Command::SendBinary(vec![byte; MESSAGE_BYTES]))
- .unwrap();
+ handle.send_binary(vec![byte; MESSAGE_BYTES]).unwrap();
}
timeout(Duration::from_secs(3), received_rx)
.await
@@ -182,12 +168,7 @@ async fn native_fragmented_sends_complete_while_incoming_sink_is_blocked() {
assert_frame_sent(&mut rx, 82, FrameOpcode::Binary, MESSAGE_BYTES).await;
assert_buffered_amount_consumed(&mut rx, 82, MESSAGE_BYTES).await;
}
- handle
- .send(Command::Close {
- code: Some(1000),
- reason: String::new(),
- })
- .unwrap();
+ handle.close(Some(1000), String::new()).unwrap();
assert_closing(&mut rx, 82).await;
assert_close(&mut rx, 82, 1000, "", true).await;
server.await.unwrap();
diff --git a/moli-websocket/src/synthetic.rs b/moli-websocket/src/synthetic.rs
index 979e8afac..a8ffd944f 100644
--- a/moli-websocket/src/synthetic.rs
+++ b/moli-websocket/src/synthetic.rs
@@ -117,8 +117,7 @@ pub(crate) async fn run_synthetic_websocket_connection(
.await?;
return Ok(());
}
- Command::ContinueOpen { .. } => {}
- Command::FailOpen(message) => {
+ Command::Fail(message) => {
send_error_and_close(&event_tx, socket_id, message).await?;
return Ok(());
}
diff --git a/moli-websocket/src/test_support.rs b/moli-websocket/src/test_support.rs
index d550dda74..084ecccff 100644
--- a/moli-websocket/src/test_support.rs
+++ b/moli-websocket/src/test_support.rs
@@ -40,7 +40,6 @@ pub fn test_websocket_context() -> ConnectOptions {
proxy_bearer_token: None,
tls: Default::default(),
cookie_header: None,
- pause_after_handshake: false,
}
}
diff --git a/moli-websocket/src/tests.rs b/moli-websocket/src/tests.rs
index a8da138a3..67ea94f47 100644
--- a/moli-websocket/src/tests.rs
+++ b/moli-websocket/src/tests.rs
@@ -497,8 +497,8 @@ async fn websocket_rejected_handshake_or_open_event_releases_transport() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/closed-sink", listener.local_addr().unwrap());
let (command_tx, command_rx) = crate::commands::command_channel();
- let mut context = test_websocket_context();
- context.pause_after_handshake = pause_after_handshake;
+ let context = test_websocket_context();
+ let (_controller, decision) = tokio::sync::oneshot::channel();
let server = async move {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
@@ -512,6 +512,7 @@ async fn websocket_rejected_handshake_or_open_event_releases_transport() {
context,
command_rx,
EventSender::closed(),
+ pause_after_handshake.then_some(decision),
);
let (result, ()) = timeout(Duration::from_secs(3), async {
tokio::join!(client, server)
@@ -551,6 +552,7 @@ async fn websocket_rejected_message_event_releases_transport_and_writer() {
test_websocket_context(),
command_rx,
sink,
+ None,
);
let (result, ()) = timeout(Duration::from_secs(3), async {
tokio::join!(client, server)
@@ -637,7 +639,7 @@ async fn websocket_cancel_releases_blocked_sink_and_open_writer() {
handle.cancel();
handle.cancel();
assert!(retained.is_closed());
- assert!(retained.send(Command::SendBinary(vec![1])).is_err());
+ assert!(retained.send_binary(vec![1]).is_err());
timeout(Duration::from_secs(3), dropped_rx.recv())
.await
.expect("cancellation must release the blocked event future")
@@ -664,7 +666,7 @@ async fn websocket_failed_and_synthetic_delivery_cancel_on_last_handle_drop() {
}
});
let handle = if synthetic {
- spawn_synthetic_connection(63, Vec::new(), 101, Vec::new(), sink)
+ spawn_synthetic_connection(63, Vec::new(), 101, Vec::new(), sink).0
} else {
spawn_failed_connection(63, "rejected".to_owned(), sink)
};
@@ -682,7 +684,7 @@ async fn websocket_failed_and_synthetic_delivery_cancel_on_last_handle_drop() {
#[tokio::test]
async fn websocket_synthetic_connection_opens_accounts_send_and_closes_cleanly() {
let (event_tx, mut event_rx) = mpsc::channel(32);
- let command_tx = spawn_synthetic_connection(
+ let (command_tx, _peer) = spawn_synthetic_connection(
92,
vec![("Origin".to_owned(), "http://example.test".to_owned())],
101,
@@ -709,7 +711,7 @@ async fn websocket_synthetic_connection_opens_accounts_send_and_closes_cleanly()
}
command_tx
- .send(Command::SendText("hello".to_owned()))
+ .send_text("hello".to_owned())
.expect("send synthetic websocket text");
let event = timeout(Duration::from_secs(1), event_rx.recv())
.await
@@ -740,10 +742,7 @@ async fn websocket_synthetic_connection_opens_accounts_send_and_closes_cleanly()
}
command_tx
- .send(Command::Close {
- code: Some(1000),
- reason: "done".to_owned(),
- })
+ .close(Some(1000), "done".to_owned())
.expect("close synthetic websocket");
let event = timeout(Duration::from_secs(1), event_rx.recv())
.await
@@ -773,7 +772,7 @@ async fn websocket_synthetic_connection_opens_accounts_send_and_closes_cleanly()
#[tokio::test]
async fn websocket_synthetic_connection_can_receive_frames_and_server_close() {
let (event_tx, mut event_rx) = mpsc::channel(32);
- let command_tx = spawn_synthetic_connection(
+ let (_connection, peer) = spawn_synthetic_connection(
93,
vec![("Origin".to_owned(), "http://example.test".to_owned())],
101,
@@ -789,8 +788,7 @@ async fn websocket_synthetic_connection_can_receive_frames_and_server_close() {
Event::Open { socket_id: 93, .. }
));
- command_tx
- .send(Command::ReceiveText("server-text".to_owned()))
+ peer.send_text("server-text".to_owned())
.expect("inject synthetic websocket text");
match timeout(Duration::from_secs(1), event_rx.recv())
.await
@@ -804,8 +802,7 @@ async fn websocket_synthetic_connection_can_receive_frames_and_server_close() {
event => panic!("expected synthetic text message, got {event:?}"),
}
- command_tx
- .send(Command::ReceiveBinary(vec![1, 2, 3, 4]))
+ peer.send_binary(vec![1, 2, 3, 4])
.expect("inject synthetic websocket binary");
match timeout(Duration::from_secs(1), event_rx.recv())
.await
@@ -819,11 +816,7 @@ async fn websocket_synthetic_connection_can_receive_frames_and_server_close() {
event => panic!("expected synthetic binary message, got {event:?}"),
}
- command_tx
- .send(Command::ServerClose {
- code: Some(1000),
- reason: "server-done".to_owned(),
- })
+ peer.close(Some(1000), "server-done".to_owned())
.expect("inject synthetic websocket server close");
match timeout(Duration::from_secs(1), event_rx.recv())
.await
@@ -852,10 +845,7 @@ async fn websocket_transport_close_while_connecting_fails_before_open() {
let command_tx = spawn_connection(91, url, Vec::new(), test_websocket_context(), event_tx);
command_tx
- .send(Command::Close {
- code: None,
- reason: String::new(),
- })
+ .close(None, String::new())
.expect("send connecting close command");
let error = recv_handshake_failure_events(&mut event_rx).await;
@@ -868,9 +858,13 @@ async fn websocket_transport_close_while_connecting_fails_before_open() {
async fn websocket_transport_can_pause_after_handshake_before_open() {
let (url, server) = spawn_text_echo_websocket_server().await;
let (event_tx, mut event_rx) = mpsc::channel(32);
- let mut context = test_websocket_context();
- context.pause_after_handshake = true;
- let command_tx = spawn_connection(92, url, Vec::new(), context, event_tx);
+ let (command_tx, controller) = spawn_connection_with_handshake_pause(
+ 92,
+ url,
+ Vec::new(),
+ test_websocket_context(),
+ event_tx,
+ );
match timeout(Duration::from_secs(3), event_rx.recv())
.await
@@ -891,21 +885,15 @@ async fn websocket_transport_can_pause_after_handshake_before_open() {
timeout(Duration::from_millis(50), event_rx.recv())
.await
.is_err(),
- "websocket open must wait for ContinueOpen"
+ "websocket open must wait for the handshake decision"
);
- command_tx
- .send(Command::ContinueOpen {
- response_status: None,
- response_headers: None,
- })
+ controller
+ .continue_open(None, None)
.expect("continue paused websocket open");
let open = recv_open_event(&mut event_rx).await;
assert_eq!(open.socket_id, 92);
- let _ = command_tx.send(Command::Close {
- code: Some(1000),
- reason: "done".to_owned(),
- });
+ let _ = command_tx.close(Some(1000), "done".to_owned());
server
.await
.expect("websocket pause-after-handshake server should finish");
@@ -930,10 +918,7 @@ async fn websocket_transport_handshake_applies_context_headers_and_preserves_con
.expect("websocket headers should arrive")
.expect("websocket header sender should stay alive");
let open = recv_open_event(&mut event_rx).await;
- let _ = command_tx.send(Command::Close {
- code: Some(1000),
- reason: "done".to_owned(),
- });
+ let _ = command_tx.close(Some(1000), "done".to_owned());
server.await.expect("websocket header server should finish");
assert_eq!(open.socket_id, 1);
@@ -985,10 +970,7 @@ async fn websocket_transport_uses_explicit_http_proxy_connect_without_forwarding
.expect("websocket headers should arrive")
.expect("websocket header sender should stay alive");
let open = recv_open_event(&mut event_rx).await;
- let _ = command_tx.send(Command::Close {
- code: Some(1000),
- reason: "done".to_owned(),
- });
+ let _ = command_tx.close(Some(1000), "done".to_owned());
server.await.expect("websocket header server should finish");
proxy.await.expect("websocket proxy should finish");
@@ -1060,10 +1042,7 @@ async fn websocket_transport_respects_disabled_tls_verify_for_self_signed_wss()
.expect("websocket TLS headers should arrive")
.expect("websocket TLS header sender should stay alive");
let open = recv_open_event(&mut event_rx).await;
- let _ = command_tx.send(Command::Close {
- code: Some(1000),
- reason: "done".to_owned(),
- });
+ let _ = command_tx.close(Some(1000), "done".to_owned());
server
.await
.expect("websocket TLS header server should finish");
@@ -1228,10 +1207,7 @@ async fn websocket_transport_allows_server_to_omit_response_subprotocol() {
assert_eq!(open.socket_id, 4);
assert_eq!(open.protocol, "");
command_tx
- .send(Command::Close {
- code: Some(1000),
- reason: "no-protocol".to_owned(),
- })
+ .close(Some(1000), "no-protocol".to_owned())
.expect("send close command");
assert_closing(&mut event_rx, 4).await;
assert_close(&mut event_rx, 4, 1000, "no-protocol", true).await;
@@ -1250,24 +1226,21 @@ async fn websocket_transport_sends_text_binary_and_reports_buffered_amount_consu
assert_eq!(open.socket_id, 4);
command_tx
- .send(Command::SendText("hello".to_owned()))
+ .send_text("hello".to_owned())
.expect("send text command");
assert_frame_sent(&mut event_rx, 4, FrameOpcode::Text, 5).await;
assert_buffered_amount_consumed(&mut event_rx, 4, 5).await;
assert_text_message(&mut event_rx, 4, "hello").await;
command_tx
- .send(Command::SendBinary(vec![1, 2, 3, 4]))
+ .send_binary(vec![1, 2, 3, 4])
.expect("send binary command");
assert_frame_sent(&mut event_rx, 4, FrameOpcode::Binary, 4).await;
assert_buffered_amount_consumed(&mut event_rx, 4, 4).await;
assert_binary_message(&mut event_rx, 4, &[1, 2, 3, 4]).await;
command_tx
- .send(Command::Close {
- code: Some(1000),
- reason: "done".to_owned(),
- })
+ .close(Some(1000), "done".to_owned())
.expect("send close command");
assert_closing(&mut event_rx, 4).await;
assert_close(&mut event_rx, 4, 1000, "done", true).await;
@@ -1285,7 +1258,7 @@ async fn websocket_transport_reads_while_sending_many_large_messages() {
for _ in 0..50 {
command_tx
- .send(Command::SendBinary(vec![0; 65_536]))
+ .send_binary(vec![0; 65_536])
.expect("send large binary command");
}
@@ -1315,10 +1288,7 @@ async fn websocket_transport_reads_while_sending_many_large_messages() {
}
command_tx
- .send(Command::Close {
- code: Some(1000),
- reason: "backpressure".to_owned(),
- })
+ .close(Some(1000), "backpressure".to_owned())
.expect("send close command");
assert_closing(&mut event_rx, 40).await;
assert_close(&mut event_rx, 40, 1000, "backpressure", true).await;
@@ -1359,3 +1329,102 @@ async fn websocket_transport_handles_close_frame_in_handshake_packet() {
.await
.expect("websocket same-packet close server should finish");
}
+
+#[tokio::test]
+async fn websocket_dropped_handshake_controller_fails_open_and_releases_transport() {
+ use futures_util::StreamExt;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("ws://{}/decision", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.unwrap();
+ let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
+ assert!(socket.next().await.unwrap().is_err());
+ });
+ let (events, mut receiver) = mpsc::channel(4);
+ let (_connection, controller) = spawn_connection_with_handshake_pause(
+ 95,
+ url,
+ Vec::new(),
+ test_websocket_context(),
+ events,
+ );
+ assert!(matches!(
+ timeout(Duration::from_secs(3), receiver.recv())
+ .await
+ .unwrap(),
+ Some(Event::HandshakeResponse { .. })
+ ));
+ drop(controller);
+ assert_eq!(
+ recv_handshake_failure_events(&mut receiver).await,
+ "WebSocket handshake decision was dropped"
+ );
+ timeout(Duration::from_secs(3), server)
+ .await
+ .unwrap()
+ .unwrap();
+}
+
+#[tokio::test]
+async fn websocket_synthetic_peer_does_not_keep_client_alive() {
+ let (events, mut receiver) = mpsc::channel(4);
+ let (connection, peer) = spawn_synthetic_connection(96, Vec::new(), 101, Vec::new(), events);
+ recv_open_event(&mut receiver).await;
+ drop(connection);
+ assert_eq!(
+ peer.send_text("late message".to_owned()),
+ Err(SendError::Closed)
+ );
+ assert!(
+ timeout(Duration::from_secs(3), receiver.recv())
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn websocket_queued_close_precedes_handshake_continuation() {
+ use futures_util::StreamExt;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("ws://{}/close-before-open", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.unwrap();
+ let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
+ assert!(socket.next().await.unwrap().is_err());
+ });
+ let release = Arc::new(tokio::sync::Notify::new());
+ let release_sink = release.clone();
+ let (events, mut receiver) = mpsc::channel(4);
+ let sink = EventSender::with_async_sink(move |event| {
+ let events = events.clone();
+ let release = release_sink.clone();
+ async move {
+ let paused = matches!(event, Event::HandshakeResponse { .. });
+ let accepted = events.send(event).await.is_ok();
+ if paused {
+ release.notified().await;
+ }
+ accepted
+ }
+ });
+ let (connection, controller) =
+ spawn_connection_with_handshake_pause(97, url, Vec::new(), test_websocket_context(), sink);
+ assert!(matches!(
+ timeout(Duration::from_secs(3), receiver.recv())
+ .await
+ .unwrap(),
+ Some(Event::HandshakeResponse { .. })
+ ));
+ connection.close(Some(1000), String::new()).unwrap();
+ controller.continue_open(None, None).unwrap();
+ release.notify_one();
+ assert_eq!(
+ recv_handshake_failure_events(&mut receiver).await,
+ "WebSocket connection closed before opening"
+ );
+ timeout(Duration::from_secs(3), server)
+ .await
+ .unwrap()
+ .unwrap();
+}
diff --git a/moli-websocket/src/tests/tls.rs b/moli-websocket/src/tests/tls.rs
index 522c241d3..722005cec 100644
--- a/moli-websocket/src/tests/tls.rs
+++ b/moli-websocket/src/tests/tls.rs
@@ -22,9 +22,7 @@ async fn exercise_tls_connection(url: String, context: ConnectOptions, opens: bo
return;
}
recv_open_event(&mut receiver).await;
- connection
- .send(Command::SendText("TLS echo".to_owned()))
- .unwrap();
+ connection.send_text("TLS echo".to_owned()).unwrap();
let mut echoed = false;
loop {
match timeout(Duration::from_secs(5), receiver.recv())
@@ -35,12 +33,7 @@ async fn exercise_tls_connection(url: String, context: ConnectOptions, opens: bo
Event::TextMessage { data, .. } => {
assert_eq!(data, "TLS echo");
echoed = true;
- connection
- .send(Command::Close {
- code: Some(1000),
- reason: "done".to_owned(),
- })
- .unwrap();
+ connection.close(Some(1000), "done".to_owned()).unwrap();
}
Event::Close {
code, was_clean, ..
diff --git a/moli-websocket/src/types.rs b/moli-websocket/src/types.rs
index b76b3fcb6..7ba0fd250 100644
--- a/moli-websocket/src/types.rs
+++ b/moli-websocket/src/types.rs
@@ -8,7 +8,6 @@ pub struct ConnectOptions {
pub proxy_bearer_token: Option<String>,
pub tls: moli_curl::CurlTlsConfig,
pub cookie_header: Option<String>,
- pub pause_after_handshake: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -84,25 +83,12 @@ impl Event {
}
#[derive(Debug)]
-pub enum Command {
+pub(crate) enum Command {
SendText(String),
SendBinary(Vec<u8>),
ReceiveText(String),
ReceiveBinary(Vec<u8>),
- ContinueOpen {
- response_status: Option<u16>,
- response_headers: Option<Vec<(String, String)>>,
- },
- FailOpen(String),
- ServerClose {
- code: Option<u16>,
- reason: String,
- },
- Close {
- code: Option<u16>,
- reason: String,
- },
+ Fail(String),
+ ServerClose { code: Option<u16>, reason: String },
+ Close { code: Option<u16>, reason: String },
}
-
-/// Compatibility name for the connection's producer capability.
-pub type CommandSender = crate::ConnectionHandle;