simulator-client 0.22.0

Async WebSocket client for the Solana simulator backtest API
Documentation
//! Reaching a session's Yellowstone endpoint through the manager.
//!
//! gRPC method paths are fixed by the proto, so [`SessionGeyserChannel`] names the session by
//! prefixing each outgoing path and the manager strips it again. A client that cannot rewrite
//! paths uses the header instead — see [`simulator_api::geyser_route`].

use std::task::{Context, Poll};

use http::{Request, Uri};
use simulator_api::{SessionId, geyser_route::prefixed_path};
use tonic::{body::Body, transport::Channel};
use tower::Service;

use crate::{
    error::{BacktestClientError, BacktestClientResult},
    urls::http_base_from_ws_url,
};

/// A transport that reaches one session's Yellowstone endpoint through the manager.
///
/// Wrap it in whichever generated client you use:
///
/// ```ignore
/// let channel = SessionGeyserChannel::connect(&url, session_id).await?;
/// let mut client = GeyserClient::new(channel);
/// ```
#[derive(Clone)]
pub struct SessionGeyserChannel {
    inner: Channel,
    session_id: SessionId,
}

impl SessionGeyserChannel {
    /// `url` takes any form the rest of the client accepts — bare host, `http(s)` or `ws(s)`;
    /// only its origin is used. Lazy, so an unreachable manager surfaces on the first request.
    pub fn connect(url: &str, session_id: SessionId) -> BacktestClientResult<Self> {
        let origin = manager_origin(url);
        let inner = Channel::from_shared(origin.clone())
            .map_err(|e| BacktestClientError::InvalidUrl {
                url: origin,
                source: e,
            })?
            .connect_lazy();
        Ok(Self { inner, session_id })
    }
}

/// `None` leaves the request unprefixed, which the manager rejects by name rather than
/// misrouting.
fn with_session(session_id: &SessionId, uri: &Uri) -> Option<Uri> {
    let method_path = uri.path_and_query().map(|p| p.as_str()).unwrap_or("/");
    let mut parts = uri.clone().into_parts();
    parts.path_and_query = Some(prefixed_path(session_id, method_path).parse().ok()?);
    Uri::from_parts(parts).ok()
}

impl Service<Request<Body>> for SessionGeyserChannel {
    type Response = <Channel as Service<Request<Body>>>::Response;
    type Error = <Channel as Service<Request<Body>>>::Error;
    type Future = <Channel as Service<Request<Body>>>::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut request: Request<Body>) -> Self::Future {
        if let Some(uri) = with_session(&self.session_id, request.uri()) {
            *request.uri_mut() = uri;
        }
        self.inner.call(request)
    }
}

/// The `http(s)` origin of the manager, from any of the URL forms the client accepts.
fn manager_origin(url: &str) -> String {
    let absolute = if url.contains("://") {
        url.to_string()
    } else {
        format!("https://{}", url.trim_end_matches('/'))
    };
    http_base_from_ws_url(&absolute)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn manager_origin_drops_scheme_and_path_differences() {
        for (name, input) in [
            ("bare host", "sim.example.com"),
            ("bare host with slash", "sim.example.com/"),
            ("ws with path", "wss://sim.example.com/backtest"),
            ("https origin", "https://sim.example.com"),
        ] {
            assert_eq!(manager_origin(input), "https://sim.example.com", "{name}");
        }
    }

    /// Local development runs the manager on plain http, which must not be upgraded.
    #[test]
    fn manager_origin_keeps_an_insecure_scheme() {
        assert_eq!(
            manager_origin("ws://127.0.0.1:8080/backtest"),
            "http://127.0.0.1:8080"
        );
    }

    /// The manager routes on this prefix, so it has to land ahead of the proto's own path.
    #[test]
    fn the_session_prefix_lands_ahead_of_the_method_path() {
        let session_id = SessionId::new();
        let uri = "http://host/geyser.Geyser/Subscribe".parse().expect("uri");
        let prefixed = with_session(&session_id, &uri).expect("prefixed");
        assert_eq!(
            prefixed.path(),
            format!("/backtest/{session_id}/geyser.Geyser/Subscribe")
        );
        assert_eq!(prefixed.host(), uri.host(), "origin is untouched");
    }
}