simulator_client/
geyser.rs1use 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#[derive(Clone)]
28pub struct SessionGeyserChannel {
29 inner: Channel,
30 session_id: SessionId,
31 token: HeaderValue,
32}
33
34impl SessionGeyserChannel {
35 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
54fn 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}