Skip to main content

rig_tungstenite/
native.rs

1//! The backend itself, compiled on native targets only.
2
3pub 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/// A stateless websocket backend that takes handshake configuration from each
14/// request.
15#[derive(Clone, Copy, Debug, Default)]
16pub struct TungsteniteClient;
17
18impl TungsteniteClient {
19    /// The bundled backend.
20    #[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
39/// Build a tungstenite handshake request, returning an error for an invalid URI.
40/// Caller headers, including authentication, override generated handshake headers.
41fn 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/// A handshake that did not complete in time.
55#[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
80/// Convert a tungstenite failure to a transport error, preserving the status,
81/// headers, and body of a rejected upgrade. A connection that dropped or
82/// could not be made, and any TLS failure, is [`Error::Transient`]; a URL,
83/// request, message or protocol error that the same send meets again is
84/// [`Error::Permanent`].
85fn 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        // rustls reports a certificate it rejects as invalid data.
102        tungstenite::Error::Io(ref io) if io.kind() != std::io::ErrorKind::InvalidData => {
103            Error::transient(error)
104        }
105        // native-tls reports a handshake the peer reset as it reports a
106        // certificate it refused.
107        tungstenite::Error::Tls(_) => Error::transient(error),
108        error => Error::permanent(error),
109    }
110}
111
112#[cfg(test)]
113mod tests;