lamarge 0.5.1

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! The event WebSocket connector: `ws` over TCP (or the host's stream) for an `http` API, `wss`
//! over the client's own rustls configuration for an `https` one, at `<API base>/v1/stream` (the
//! base path kept).

use std::sync::Arc;

use futures_util::SinkExt as _;
use reqwest::Url;
use rustls::pki_types::ServerName;
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;
use tokio_tungstenite::{
    WebSocketStream,
    tungstenite::{self, Message, protocol::WebSocketConfig},
};

use crate::{
    Error, HostStream, Result,
    error::TransportError,
    transport::{Inner, MAX_ANSWER_BYTES, ops},
};

/// An open event WebSocket.
pub(super) type Socket = WebSocketStream<Box<dyn HostStream>>;

/// Where the event WebSocket of an API base is.
#[derive(Debug, PartialEq, Eq)]
struct Endpoint {
    url: String,
    host: String,
    port: u16,
    tls: bool,
}

/// The endpoint of `api`, an `http(s)` base URL without a trailing slash.
fn endpoint(api: &str) -> Result<Endpoint> {
    let invalid = || Error::Config(format!("api url {api:?}: no websocket endpoint").into());
    let (scheme, tls, rest) = if let Some(rest) = api.strip_prefix("https://") {
        ("wss", true, rest)
    } else if let Some(rest) = api.strip_prefix("http://") {
        ("ws", false, rest)
    } else {
        return Err(invalid());
    };
    let parsed = Url::parse(api).map_err(|_| invalid())?;
    // An IPv6 host is bracketed in a URL, not in a socket address or TLS name.
    let host = parsed.host_str().ok_or_else(invalid)?.trim_start_matches('[').trim_end_matches(']');
    let port = parsed.port_or_known_default().ok_or_else(invalid)?;
    Ok(Endpoint {
        url: format!("{scheme}://{rest}{}", ops::STREAM.path),
        host: host.to_owned(),
        port,
        tls,
    })
}

/// Opens the event WebSocket and sends `subscription` as its first frame.
pub(super) async fn connect(inner: &Inner, subscription: String) -> Result<Socket> {
    let endpoint = endpoint(&inner.api)?;
    let websocket = |error| Error::Transport(TransportError::websocket(error));
    let tcp: Box<dyn HostStream> = if let Some(connector) = &inner.stream_connector {
        connector
            .connect(&endpoint.host, endpoint.port)
            .await
            .map_err(|error| Error::Transport(TransportError::caller(error)))?
    } else {
        let tcp = TcpStream::connect((endpoint.host.as_str(), endpoint.port))
            .await
            .map_err(|error| websocket(tungstenite::Error::Io(error)))?;
        // Frames are small and latency matters more than packet count.
        let _ = tcp.set_nodelay(true);
        Box::new(tcp)
    };
    let io: Box<dyn HostStream> = if endpoint.tls {
        let name = ServerName::try_from(endpoint.host.clone()).map_err(|_| {
            Error::Config(format!("api host {:?}: not a TLS name", endpoint.host).into())
        })?;
        let tls = TlsConnector::from(Arc::clone(&inner.ws_tls))
            .connect(name, tcp)
            .await
            .map_err(|error| websocket(tungstenite::Error::Io(error)))?;
        Box::new(tls)
    } else {
        Box::new(tcp)
    };
    let config = WebSocketConfig::default().max_message_size(Some(MAX_ANSWER_BYTES));
    let (mut socket, _) =
        tokio_tungstenite::client_async_with_config(endpoint.url, io, Some(config))
            .await
            .map_err(websocket)?;
    socket.send(Message::text(subscription)).await.map_err(websocket)?;
    Ok(socket)
}

#[cfg(test)]
mod tests;