rig_tungstenite/
native.rs1pub use tokio_tungstenite;
4
5mod connection;
6
7use connection::Connection;
8use rig_http::http_client::{Error, NoBody, Request, Result};
9use rig_http::ws_client::{BoxedWebSocketConnection, ConnectOptions, WebSocketClientExt};
10use std::time::Duration;
11use tokio_tungstenite::tungstenite::{self, client::IntoClientRequest};
12
13#[derive(Clone, Copy, Debug, Default)]
16pub struct TungsteniteClient;
17
18impl TungsteniteClient {
19 #[must_use]
21 pub fn new() -> Self {
22 Self
23 }
24}
25
26impl WebSocketClientExt for TungsteniteClient {
27 async fn connect(
28 &self,
29 request: Request<NoBody>,
30 options: ConnectOptions,
31 ) -> Result<BoxedWebSocketConnection> {
32 let request = client_request(request)?;
33 let socket =
34 rig_http::runtime::bind(Box::pin(handshake(request, options.timeout)))?.await?;
35 Ok(Box::new(Connection(socket)))
36 }
37}
38
39fn client_request(request: Request<NoBody>) -> Result<tungstenite::handshake::client::Request> {
42 let (parts, _) = request.into_parts();
43 let mut request = parts
44 .uri
45 .to_string()
46 .into_client_request()
47 .map_err(from_tungstenite)?;
48 for (name, value) in &parts.headers {
49 request.headers_mut().insert(name, value.clone());
50 }
51 Ok(request)
52}
53
54#[derive(Debug, thiserror::Error)]
56#[error("timed out connecting the websocket after {0:?}")]
57struct ConnectTimeout(Duration);
58
59async fn handshake(
60 request: tungstenite::handshake::client::Request,
61 timeout: Option<Duration>,
62) -> Result<connection::Socket> {
63 let connect = async {
64 tokio_tungstenite::connect_async(request)
65 .await
66 .map(|(socket, _)| socket)
67 .map_err(from_tungstenite)
68 };
69
70 let Some(timeout) = timeout else {
71 return connect.await;
72 };
73
74 match rig_http::wasm_compat::timeout(timeout, connect).await {
75 Ok(result) => result,
76 Err(_) => Err(Error::transient(ConnectTimeout(timeout))),
77 }
78}
79
80fn from_tungstenite(error: tungstenite::Error) -> Error {
86 use tungstenite::error::{ProtocolError, UrlError};
87 match error {
88 tungstenite::Error::Http(response) => {
89 let (parts, body) = (*response).into_parts();
90 let body = body
91 .map(|body| String::from_utf8_lossy(&body).into_owned())
92 .unwrap_or_default();
93 Error::non_success_with_details(parts.status, parts.headers, body)
94 }
95 tungstenite::Error::ConnectionClosed
96 | tungstenite::Error::WriteBufferFull(_)
97 | tungstenite::Error::Url(UrlError::UnableToConnect(_))
98 | tungstenite::Error::Protocol(
99 ProtocolError::HandshakeIncomplete | ProtocolError::ResetWithoutClosingHandshake,
100 ) => Error::transient(error),
101 tungstenite::Error::Io(ref io) if io.kind() != std::io::ErrorKind::InvalidData => {
103 Error::transient(error)
104 }
105 tungstenite::Error::Tls(_) => Error::transient(error),
108 error => Error::permanent(error),
109 }
110}
111
112#[cfg(test)]
113mod tests;