pub(crate) use imp::{connect, Socket};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Incoming {
Text(String),
Binary(Vec<u8>),
Closed,
#[cfg_attr(
target_arch = "wasm32",
expect(
dead_code,
reason = "a browser's WebSocket never surfaces control frames"
)
)]
Control,
}
#[cfg(not(target_arch = "wasm32"))]
mod imp {
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::Message;
use tokio_tungstenite::tungstenite::Error as WsError;
use super::Incoming;
use crate::subscription::SubscriptionError;
type Stream = tokio_tungstenite::WebSocketStream<
tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
>;
pub(crate) struct Socket {
inner: Stream,
protocol: Option<String>,
}
pub(crate) async fn connect(
url: &str,
protocols: &[&str],
) -> Result<Socket, SubscriptionError> {
ensure_tls_provider();
let mut request = url
.into_client_request()
.map_err(|e| SubscriptionError::InvalidUrl(e.to_string()))?;
request.headers_mut().insert(
"Sec-WebSocket-Protocol",
HeaderValue::from_str(&protocols.join(", "))
.map_err(|e| SubscriptionError::InvalidUrl(e.to_string()))?,
);
let (inner, response) = tokio_tungstenite::connect_async(request)
.await
.map_err(websocket)?;
let protocol = response
.headers()
.get("Sec-WebSocket-Protocol")
.and_then(|v| v.to_str().ok())
.map(|p| p.trim().to_owned());
Ok(Socket { inner, protocol })
}
impl Socket {
pub(crate) fn protocol(&self) -> Option<String> {
self.protocol.clone()
}
pub(crate) async fn send_text(&mut self, text: String) -> Result<(), SubscriptionError> {
self.inner
.send(Message::Text(text.into()))
.await
.map_err(websocket)
}
pub(crate) async fn next(&mut self) -> Option<Result<Incoming, SubscriptionError>> {
Some(self.inner.next().await?.map(incoming).map_err(websocket))
}
}
fn incoming(message: Message) -> Incoming {
match message {
Message::Text(text) => Incoming::Text(text.as_str().to_owned()),
Message::Binary(bytes) => Incoming::Binary(bytes.to_vec()),
Message::Close(_) => Incoming::Closed,
Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => Incoming::Control,
}
}
#[expect(
clippy::needless_pass_by_value,
reason = "a map_err callback receives the error by value"
)]
fn websocket(error: WsError) -> SubscriptionError {
SubscriptionError::WebSocket(error.to_string())
}
fn ensure_tls_provider() {
use std::sync::Once;
static INSTALL: Once = Once::new();
INSTALL.call_once(|| {
let _ = rustls::crypto::ring::default_provider().install_default();
});
}
}
#[cfg(target_arch = "wasm32")]
mod imp {
use futures_util::{SinkExt, StreamExt};
use gloo_net::websocket::futures::WebSocket;
use gloo_net::websocket::{Message, WebSocketError};
use super::Incoming;
use crate::subscription::SubscriptionError;
pub(crate) struct Socket {
inner: WebSocket,
}
pub(crate) async fn connect(
url: &str,
protocols: &[&str],
) -> Result<Socket, SubscriptionError> {
WebSocket::open_with_protocols(url, protocols)
.map(|inner| Socket { inner })
.map_err(|e| SubscriptionError::InvalidUrl(e.to_string()))
}
impl Socket {
pub(crate) fn protocol(&self) -> Option<String> {
let protocol = self.inner.protocol();
(!protocol.is_empty()).then_some(protocol)
}
pub(crate) async fn send_text(&mut self, text: String) -> Result<(), SubscriptionError> {
self.inner
.send(Message::Text(text))
.await
.map_err(|e| SubscriptionError::WebSocket(e.to_string()))
}
pub(crate) async fn next(&mut self) -> Option<Result<Incoming, SubscriptionError>> {
Some(match self.inner.next().await? {
Ok(Message::Text(text)) => Ok(Incoming::Text(text)),
Ok(Message::Bytes(bytes)) => Ok(Incoming::Binary(bytes)),
Err(WebSocketError::ConnectionClose(_)) => Ok(Incoming::Closed),
Err(e) => Err(SubscriptionError::WebSocket(e.to_string())),
})
}
}
}