Skip to main content

simulator_client/
geyser.rs

1//! Reaching a granted session's Yellowstone endpoint. A client that cannot rewrite paths uses the
2//! header instead — see [`simulator_api::geyser_route`].
3
4use std::task::{Context, Poll};
5
6use http::{HeaderValue, Request, Uri};
7use simulator_api::{
8    SessionId,
9    geyser_route::prefixed_path,
10    session_endpoint::{SESSION_TOKEN_HEADER, SessionGrant},
11};
12use tonic::{body::Body, transport::Channel};
13use tower::Service;
14
15use crate::{
16    endpoint::token_header,
17    error::{BacktestClientError, BacktestClientResult},
18};
19
20/// A transport for one granted session's Yellowstone endpoint. Wrap it in a generated Yellowstone
21/// client built against tonic 0.14, the version this crate uses:
22///
23/// ```ignore
24/// let channel = SessionGeyserChannel::connect_endpoint(&grant)?;
25/// let mut client = GeyserClient::new(channel);
26/// ```
27#[derive(Clone)]
28pub struct SessionGeyserChannel {
29    inner: Channel,
30    session_id: SessionId,
31    token: HeaderValue,
32}
33
34impl SessionGeyserChannel {
35    /// Sends the grant's token as `x-token` on every request. Lazy: an unreachable endpoint fails
36    /// on the first request.
37    ///
38    /// # Errors
39    ///
40    /// - [`BacktestClientError::InvalidSessionToken`] when the token is not a valid header value.
41    pub fn connect_endpoint(grant: &SessionGrant) -> BacktestClientResult<Self> {
42        let token = token_header(&grant.token).map_err(BacktestClientError::InvalidSessionToken)?;
43        let inner = Channel::from_shared(grant.endpoint.as_str().to_owned())
44            .unwrap_or_else(|e| unreachable!("a SessionEndpointUrl is an http(s) origin: {e}"))
45            .connect_lazy();
46        Ok(Self {
47            inner,
48            session_id: grant.session_id,
49            token,
50        })
51    }
52}
53
54/// `None` leaves the request unprefixed; the endpoint rejects it.
55fn with_session(session_id: &SessionId, uri: &Uri) -> Option<Uri> {
56    let method_path = uri.path_and_query().map(|p| p.as_str()).unwrap_or("/");
57    let mut parts = uri.clone().into_parts();
58    parts.path_and_query = Some(prefixed_path(session_id, method_path).parse().ok()?);
59    Uri::from_parts(parts).ok()
60}
61
62impl Service<Request<Body>> for SessionGeyserChannel {
63    type Response = <Channel as Service<Request<Body>>>::Response;
64    type Error = <Channel as Service<Request<Body>>>::Error;
65    type Future = <Channel as Service<Request<Body>>>::Future;
66
67    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
68        self.inner.poll_ready(cx)
69    }
70
71    fn call(&mut self, mut request: Request<Body>) -> Self::Future {
72        if let Some(uri) = with_session(&self.session_id, request.uri()) {
73            *request.uri_mut() = uri;
74        }
75        request
76            .headers_mut()
77            .insert(SESSION_TOKEN_HEADER, self.token.clone());
78        self.inner.call(request)
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn the_session_prefix_lands_ahead_of_the_method_path() {
88        let session_id = SessionId::new();
89        let uri = "http://host/geyser.Geyser/Subscribe".parse().expect("uri");
90        let prefixed = with_session(&session_id, &uri).expect("prefixed");
91        assert_eq!(
92            prefixed.path(),
93            format!("/backtest/{session_id}/geyser.Geyser/Subscribe")
94        );
95        assert_eq!(prefixed.host(), uri.host(), "origin is untouched");
96    }
97}