simulator_client/
geyser.rs1use 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#[derive(Clone)]
31pub struct SessionGeyserChannel {
32 inner: Channel,
33 session_id: SessionId,
34}
35
36impl SessionGeyserChannel {
37 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
55fn 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
81fn 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 #[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 #[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}