Skip to main content

simulator_client/
geyser.rs

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