simulator-client 0.31.0

Async WebSocket client for the Solana simulator backtest API
Documentation
//! Reaching a granted session's Yellowstone endpoint. A client that cannot rewrite paths uses the
//! header instead — see [`simulator_api::geyser_route`].

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

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

use crate::{
    endpoint::token_header,
    error::{BacktestClientError, BacktestClientResult},
};

/// A transport for one granted session's Yellowstone endpoint. Wrap it in a generated Yellowstone
/// client built against tonic 0.14, the version this crate uses:
///
/// ```ignore
/// let channel = SessionGeyserChannel::connect_endpoint(&grant)?;
/// let mut client = GeyserClient::new(channel);
/// ```
#[derive(Clone)]
pub struct SessionGeyserChannel {
    inner: Channel,
    session_id: SessionId,
    token: HeaderValue,
}

impl SessionGeyserChannel {
    /// Sends the grant's token as `x-token` on every request. Lazy: an unreachable endpoint fails
    /// on the first request.
    ///
    /// # Errors
    ///
    /// - [`BacktestClientError::InvalidSessionToken`] when the token is not a valid header value.
    pub fn connect_endpoint(grant: &SessionGrant) -> BacktestClientResult<Self> {
        let token = token_header(&grant.token).map_err(BacktestClientError::InvalidSessionToken)?;
        let inner = Channel::from_shared(grant.endpoint.as_str().to_owned())
            .unwrap_or_else(|e| unreachable!("a SessionEndpointUrl is an http(s) origin: {e}"))
            .connect_lazy();
        Ok(Self {
            inner,
            session_id: grant.session_id,
            token,
        })
    }
}

/// `None` leaves the request unprefixed; the endpoint rejects it.
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;
        }
        request
            .headers_mut()
            .insert(SESSION_TOKEN_HEADER, self.token.clone());
        self.inner.call(request)
    }
}

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

    #[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");
    }
}