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
use futures_util::StreamExt as _;

use super::*;
use crate::{Client, Environment, StreamConnector, StreamFuture};

/// Hands the SDK one end of an in-memory pipe and serves a WebSocket on the other.
struct Pipe(std::sync::Mutex<Option<tokio::io::DuplexStream>>, std::sync::Mutex<Vec<String>>);

impl StreamConnector for Pipe {
    fn connect<'a>(&'a self, host: &'a str, port: u16) -> StreamFuture<'a> {
        self.1.lock().unwrap().push(format!("{host}:{port}"));
        let end = self.0.lock().unwrap().take();
        Box::pin(async move {
            let stream: Box<dyn HostStream> = Box::new(end.ok_or("connected once")?);
            Ok(stream)
        })
    }
}

#[tokio::test]
#[expect(
    clippy::result_large_err,
    reason = "tungstenite's handshake callback returns its response"
)]
async fn a_host_connector_carries_the_event_websocket() {
    let (ours, theirs) = tokio::io::duplex(1 << 16);
    let pipe = std::sync::Arc::new(Pipe(Some(ours).into(), Vec::new().into()));
    // Nothing listens there: only the pipe can carry the connection.
    let (api_url, app_origin) =
        ("http://127.0.0.1:9/base".to_owned(), "http://127.0.0.1:9".to_owned());
    let client = Client::builder(Environment::Custom { api_url, app_origin })
        .stream_connector(std::sync::Arc::clone(&pipe))
        .build()
        .unwrap();
    let server = tokio::spawn(async move {
        let mut path = String::new();
        let callback = |request: &tungstenite::handshake::server::Request, response| {
            path = request.uri().path().to_owned();
            Ok(response)
        };
        let mut socket = tokio_tungstenite::accept_hdr_async(theirs, callback).await.unwrap();
        let first = socket.next().await.unwrap().unwrap();
        (path, first.into_text().unwrap().to_string())
    });
    let _socket = connect(client.inner(), r#"{"subscribe":"public"}"#.to_owned()).await.unwrap();
    let (path, first) = server.await.unwrap();
    assert_eq!(path, "/base/v1/stream");
    assert_eq!(first, r#"{"subscribe":"public"}"#);
    assert_eq!(*pipe.1.lock().unwrap(), ["127.0.0.1:9"]);

    let Err(error) = connect(client.inner(), String::new()).await else {
        panic!("the pipe connects once")
    };
    assert!(matches!(error, Error::Transport(_)), "a host failure is a lost connection: {error:?}");
}

#[test]
fn endpoints_follow_the_api_scheme_and_keep_its_path() {
    let cases = [
        (
            "https://api.lamarge.trade",
            "wss://api.lamarge.trade/v1/stream",
            "api.lamarge.trade",
            443,
            true,
        ),
        (
            "https://api.example.com:8443/base",
            "wss://api.example.com:8443/base/v1/stream",
            "api.example.com",
            8443,
            true,
        ),
        (
            "http://127.0.0.1:8080/api",
            "ws://127.0.0.1:8080/api/v1/stream",
            "127.0.0.1",
            8080,
            false,
        ),
        ("http://localhost", "ws://localhost/v1/stream", "localhost", 80, false),
        ("http://[::1]:9", "ws://[::1]:9/v1/stream", "::1", 9, false),
    ];
    for (api, url, host, port, tls) in cases {
        let expected = Endpoint { url: url.to_owned(), host: host.to_owned(), port, tls };
        assert_eq!(endpoint(api).unwrap(), expected, "{api}");
    }
    assert!(matches!(endpoint("ftp://api.example.com"), Err(Error::Config(_))));
}