moonproof-indexer-client 0.2.2

Rust client for the Midnight indexer's GraphQL API
Documentation
//! The WebSocket a subscription runs over: tungstenite on a host, the
//! browser's own `WebSocket` under `wasm32-unknown-unknown`. Both send
//! text frames and hand back what arrived, so the `graphql-transport-ws`
//! protocol above them is the same everywhere.

pub(crate) use imp::{connect, Socket};

/// One frame as it arrived.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Incoming {
    Text(String),
    Binary(Vec<u8>),
    Closed,
    /// Ping, pong and raw frames, which the socket answers itself.
    #[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>,
    }

    /// Open `url`, offering `protocols` in order of preference.
    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 {
        /// The subprotocol the server chose.
        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())
    }

    /// Install rustls' `ring` `CryptoProvider` as the process default, once.
    ///
    /// `wss://` connects build a rustls `ClientConfig` from the process-level
    /// default provider. With both `aws-lc-rs` and `ring` linked in the
    /// workspace, rustls refuses to auto-pick one and panics, so we choose
    /// `ring` explicitly. Idempotent: `install_default` errors (and we ignore)
    /// if a host binary already installed a provider.
    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,
    }

    /// Open `url`, offering `protocols` in order of preference. The
    /// browser connects in the background; sending waits for it.
    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 {
        /// The subprotocol the server chose; known once the socket is open.
        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())),
            })
        }
    }
}