use std::task::{Context, Poll};
use http::{Request, Uri};
use simulator_api::{SessionId, geyser_route::prefixed_path};
use tonic::{body::Body, transport::Channel};
use tower::Service;
use crate::{
error::{BacktestClientError, BacktestClientResult},
urls::http_base_from_ws_url,
};
#[derive(Clone)]
pub struct SessionGeyserChannel {
inner: Channel,
session_id: SessionId,
}
impl SessionGeyserChannel {
pub fn connect(url: &str, session_id: SessionId) -> BacktestClientResult<Self> {
let origin = manager_origin(url);
let inner = Channel::from_shared(origin.clone())
.map_err(|e| BacktestClientError::InvalidUrl {
url: origin,
source: e,
})?
.connect_lazy();
Ok(Self { inner, session_id })
}
}
fn with_session(session_id: &SessionId, uri: &Uri) -> Option<Uri> {
let method_path = uri.path_and_query().map(|p| p.as_str()).unwrap_or("/");
let mut parts = uri.clone().into_parts();
parts.path_and_query = Some(prefixed_path(session_id, method_path).parse().ok()?);
Uri::from_parts(parts).ok()
}
impl Service<Request<Body>> for SessionGeyserChannel {
type Response = <Channel as Service<Request<Body>>>::Response;
type Error = <Channel as Service<Request<Body>>>::Error;
type Future = <Channel as Service<Request<Body>>>::Future;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut request: Request<Body>) -> Self::Future {
if let Some(uri) = with_session(&self.session_id, request.uri()) {
*request.uri_mut() = uri;
}
self.inner.call(request)
}
}
fn manager_origin(url: &str) -> String {
let absolute = if url.contains("://") {
url.to_string()
} else {
format!("https://{}", url.trim_end_matches('/'))
};
http_base_from_ws_url(&absolute)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manager_origin_drops_scheme_and_path_differences() {
for (name, input) in [
("bare host", "sim.example.com"),
("bare host with slash", "sim.example.com/"),
("ws with path", "wss://sim.example.com/backtest"),
("https origin", "https://sim.example.com"),
] {
assert_eq!(manager_origin(input), "https://sim.example.com", "{name}");
}
}
#[test]
fn manager_origin_keeps_an_insecure_scheme() {
assert_eq!(
manager_origin("ws://127.0.0.1:8080/backtest"),
"http://127.0.0.1:8080"
);
}
#[test]
fn the_session_prefix_lands_ahead_of_the_method_path() {
let session_id = SessionId::new();
let uri = "http://host/geyser.Geyser/Subscribe".parse().expect("uri");
let prefixed = with_session(&session_id, &uri).expect("prefixed");
assert_eq!(
prefixed.path(),
format!("/backtest/{session_id}/geyser.Geyser/Subscribe")
);
assert_eq!(prefixed.host(), uri.host(), "origin is untouched");
}
}