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)]
28pub struct SessionGeyserChannel {
29 inner: Channel,
30 session_id: SessionId,
31}
32
33impl SessionGeyserChannel {
34 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
48fn 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
74fn 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 #[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 #[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}