use std::task::{Context, Poll};
use http::{HeaderValue, Request, Uri};
use simulator_api::{
SessionId,
geyser_route::prefixed_path,
session_endpoint::{SESSION_TOKEN_HEADER, SessionGrant},
};
use tonic::{body::Body, transport::Channel};
use tower::Service;
use crate::{
endpoint::token_header,
error::{BacktestClientError, BacktestClientResult},
};
#[derive(Clone)]
pub struct SessionGeyserChannel {
inner: Channel,
session_id: SessionId,
token: HeaderValue,
}
impl SessionGeyserChannel {
pub fn connect_endpoint(grant: &SessionGrant) -> BacktestClientResult<Self> {
let token = token_header(&grant.token).map_err(BacktestClientError::InvalidSessionToken)?;
let inner = Channel::from_shared(grant.endpoint.as_str().to_owned())
.unwrap_or_else(|e| unreachable!("a SessionEndpointUrl is an http(s) origin: {e}"))
.connect_lazy();
Ok(Self {
inner,
session_id: grant.session_id,
token,
})
}
}
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;
}
request
.headers_mut()
.insert(SESSION_TOKEN_HEADER, self.token.clone());
self.inner.call(request)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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");
}
}