Skip to main content

simulator_client/
geyser.rs

1//! Reaching a session's Yellowstone endpoint through the manager.
2//!
3//! gRPC method paths are fixed by the proto, so [`SessionGeyserChannel`] names the session by
4//! prefixing each outgoing path and the manager strips it again. A client that cannot rewrite
5//! paths uses the header instead — see [`simulator_api::geyser_route`].
6
7use std::task::{Context, Poll};
8
9use http::{Request, Uri};
10use simulator_api::{SessionId, geyser_route::prefixed_path};
11use tonic::{body::Body, transport::Channel};
12use tower::Service;
13
14use crate::{
15    error::{BacktestClientError, BacktestClientResult},
16    urls::http_base_from_ws_url,
17};
18
19/// A transport that reaches one session's Yellowstone endpoint through the manager.
20///
21/// Wrap it in whichever generated client you use:
22///
23/// ```ignore
24/// let channel = SessionGeyserChannel::connect(&url, session_id).await?;
25/// let mut client = GeyserClient::new(channel);
26/// ```
27#[derive(Clone)]
28pub struct SessionGeyserChannel {
29    inner: Channel,
30    session_id: SessionId,
31}
32
33impl SessionGeyserChannel {
34    /// `url` takes any form the rest of the client accepts — bare host, `http(s)` or `ws(s)`;
35    /// only its origin is used. Lazy, so an unreachable manager surfaces on the first request.
36    pub fn connect(url: &str, session_id: SessionId) -> BacktestClientResult<Self> {
37        let origin = manager_origin(url);
38        let inner = Channel::from_shared(origin.clone())
39            .map_err(|e| BacktestClientError::InvalidUrl {
40                url: origin,
41                source: e,
42            })?
43            .connect_lazy();
44        Ok(Self { inner, session_id })
45    }
46}
47
48/// `None` leaves the request unprefixed, which the manager rejects by name rather than
49/// misrouting.
50fn with_session(session_id: &SessionId, uri: &Uri) -> Option<Uri> {
51    let method_path = uri.path_and_query().map(|p| p.as_str()).unwrap_or("/");
52    let mut parts = uri.clone().into_parts();
53    parts.path_and_query = Some(prefixed_path(session_id, method_path).parse().ok()?);
54    Uri::from_parts(parts).ok()
55}
56
57impl Service<Request<Body>> for SessionGeyserChannel {
58    type Response = <Channel as Service<Request<Body>>>::Response;
59    type Error = <Channel as Service<Request<Body>>>::Error;
60    type Future = <Channel as Service<Request<Body>>>::Future;
61
62    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
63        self.inner.poll_ready(cx)
64    }
65
66    fn call(&mut self, mut request: Request<Body>) -> Self::Future {
67        if let Some(uri) = with_session(&self.session_id, request.uri()) {
68            *request.uri_mut() = uri;
69        }
70        self.inner.call(request)
71    }
72}
73
74/// The `http(s)` origin of the manager, from any of the URL forms the client accepts.
75fn manager_origin(url: &str) -> String {
76    let absolute = if url.contains("://") {
77        url.to_string()
78    } else {
79        format!("https://{}", url.trim_end_matches('/'))
80    };
81    http_base_from_ws_url(&absolute)
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn manager_origin_drops_scheme_and_path_differences() {
90        for (name, input) in [
91            ("bare host", "sim.example.com"),
92            ("bare host with slash", "sim.example.com/"),
93            ("ws with path", "wss://sim.example.com/backtest"),
94            ("https origin", "https://sim.example.com"),
95        ] {
96            assert_eq!(manager_origin(input), "https://sim.example.com", "{name}");
97        }
98    }
99
100    /// Local development runs the manager on plain http, which must not be upgraded.
101    #[test]
102    fn manager_origin_keeps_an_insecure_scheme() {
103        assert_eq!(
104            manager_origin("ws://127.0.0.1:8080/backtest"),
105            "http://127.0.0.1:8080"
106        );
107    }
108
109    /// The manager routes on this prefix, so it has to land ahead of the proto's own path.
110    #[test]
111    fn the_session_prefix_lands_ahead_of_the_method_path() {
112        let session_id = SessionId::new();
113        let uri = "http://host/geyser.Geyser/Subscribe".parse().expect("uri");
114        let prefixed = with_session(&session_id, &uri).expect("prefixed");
115        assert_eq!(
116            prefixed.path(),
117            format!("/backtest/{session_id}/geyser.Geyser/Subscribe")
118        );
119        assert_eq!(prefixed.host(), uri.host(), "origin is untouched");
120    }
121}