use std::time::Duration;
use simulator_api::session_endpoint::{SESSION_TOKEN_HEADER, SessionGrant, SessionToken};
use solana_client::{nonblocking::rpc_client::RpcClient, rpc_client::RpcClientConfig};
use solana_commitment_config::CommitmentConfig;
use solana_rpc_client::http_sender::HttpSender;
use tokio::time::Instant;
use tokio_tungstenite::{
connect_async,
tungstenite::{
self,
client::IntoClientRequest,
handshake::client::Request,
http::{
HeaderValue, StatusCode,
header::{InvalidHeaderValue, USER_AGENT},
},
},
};
use crate::{error::err_chain, managed::Ws};
const ENDPOINT_FIRST_CONNECT_WINDOW: Duration = Duration::from_secs(20);
const ENDPOINT_FIRST_CONNECT_RETRY: Duration = Duration::from_secs(1);
const RPC_TIMEOUT: Duration = Duration::from_secs(30);
const RPC_POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) fn token_header(token: &SessionToken) -> Result<HeaderValue, InvalidHeaderValue> {
let mut value = HeaderValue::from_str(token.expose())?;
value.set_sensitive(true);
Ok(value)
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum RpcClientError {
#[error("the token is not a valid header value")]
Token(#[from] InvalidHeaderValue),
#[error("build the HTTP client")]
Build(#[from] reqwest::Error),
}
pub(crate) fn rpc_client(
grant: &SessionGrant,
commitment: CommitmentConfig,
) -> Result<RpcClient, RpcClientError> {
let mut headers = HttpSender::default_headers();
headers.insert(SESSION_TOKEN_HEADER, token_header(&grant.token)?);
let client = reqwest::Client::builder()
.default_headers(headers)
.timeout(RPC_TIMEOUT)
.pool_idle_timeout(RPC_POOL_IDLE_TIMEOUT)
.build()?;
Ok(RpcClient::new_sender(
HttpSender::new_with_client(grant.rpc_url(), client),
RpcClientConfig::with_commitment(commitment),
))
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum ControlConnectError {
#[error("the session's endpoint rejected the token")]
TokenRejected,
#[error("the grant gives no usable control request: {0}")]
Request(String),
#[error("{0}")]
Failed(String),
}
pub(crate) async fn connect_control(
grant: &SessionGrant,
user_agent: &str,
connect_timeout: Duration,
) -> Result<Ws, ControlConnectError> {
let request_error =
|e: &(dyn std::error::Error + 'static)| ControlConnectError::Request(err_chain(e));
let token = token_header(&grant.token).map_err(|e| request_error(&e))?;
let user_agent = HeaderValue::from_str(user_agent).map_err(|e| request_error(&e))?;
let mut request = grant
.control_url()
.into_client_request()
.map_err(|e| request_error(&e))?;
let headers = request.headers_mut();
headers.insert(SESSION_TOKEN_HEADER, token);
headers.insert(USER_AGENT, user_agent);
connect_session_socket(request, connect_timeout).await
}
pub(crate) async fn connect_session_socket(
request: Request,
timeout: Duration,
) -> Result<Ws, ControlConnectError> {
let (ws, _) = tokio::time::timeout(timeout, connect_async(request))
.await
.map_err(|_elapsed| {
ControlConnectError::Failed(format!("connect timeout after {timeout:?}"))
})?
.map_err(|e| match &e {
tungstenite::Error::Http(response) if response.status() == StatusCode::UNAUTHORIZED => {
ControlConnectError::TokenRejected
}
_ => ControlConnectError::Failed(format!("connect: {}", err_chain(&e))),
})?;
Ok(ws)
}
pub(crate) struct FirstConnect {
deadline: Instant,
}
impl FirstConnect {
pub(crate) fn start(now: Instant) -> Self {
Self {
deadline: now + ENDPOINT_FIRST_CONNECT_WINDOW,
}
}
pub(crate) fn retry_after(&self, now: Instant) -> Option<Duration> {
(now < self.deadline).then_some(ENDPOINT_FIRST_CONNECT_RETRY)
}
}
pub(crate) fn without_query(url: &str) -> &str {
url.split_once('?').map_or(url, |(base, _)| base)
}
#[cfg(test)]
pub(crate) mod testing {
use simulator_api::{
SessionId, SlotRange,
session_endpoint::{SessionEndpointUrl, SessionToken},
};
use tokio::{io::AsyncReadExt, net::TcpListener, task::JoinHandle};
use super::SessionGrant;
pub(crate) async fn read_request_head() -> (u16, JoinHandle<String>) {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
let port = listener.local_addr().expect("addr").port();
let head = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.expect("accept");
let mut buf = vec![0_u8; 4096];
let read = stream.read(&mut buf).await.expect("read");
String::from_utf8_lossy(&buf[..read]).into_owned()
});
(port, head)
}
pub(crate) fn loopback_grant(port: u16) -> SessionGrant {
SessionGrant {
session_id: SessionId::new(),
session_name: None,
task_id: None,
endpoint: SessionEndpointUrl::loopback(port),
token: SessionToken::generate(),
slots: SlotRange::new(100, 105).expect("slots"),
}
}
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::{testing::*, *};
#[rstest]
#[case::at_the_start(Duration::ZERO, Some(ENDPOINT_FIRST_CONNECT_RETRY))]
#[case::just_before_the_deadline(
ENDPOINT_FIRST_CONNECT_WINDOW - Duration::from_millis(1),
Some(ENDPOINT_FIRST_CONNECT_RETRY)
)]
#[case::at_the_deadline(ENDPOINT_FIRST_CONNECT_WINDOW, None)]
#[case::past_the_deadline(ENDPOINT_FIRST_CONNECT_WINDOW + Duration::from_secs(1), None)]
fn first_connect_retries_only_inside_its_window(
#[case] elapsed: Duration,
#[case] expected: Option<Duration>,
) {
let started = Instant::now();
let first = FirstConnect::start(started);
assert_eq!(first.retry_after(started + elapsed), expected);
}
#[tokio::test]
async fn rpc_client_sends_the_token_only_in_a_header() {
let (port, head) = read_request_head().await;
let grant = loopback_grant(port);
let token = grant.token.expose().to_lowercase();
let client = rpc_client(&grant, CommitmentConfig::confirmed()).expect("client");
let error = client
.get_slot()
.await
.expect_err("the server sends no answer");
let head = head.await.expect("join").to_lowercase();
let path = format!("post /backtest/{} ", grant.session_id).to_lowercase();
assert!(head.starts_with(&path), "{head}");
assert!(
head.contains(&format!("{SESSION_TOKEN_HEADER}: {token}")),
"{head}"
);
assert!(!format!("{error} {error:?}").contains(grant.token.expose()));
}
#[rstest]
#[case::with_a_query(
"http://127.0.0.1:1/backtest/s?token=secret",
"http://127.0.0.1:1/backtest/s"
)]
#[case::without_a_query("http://127.0.0.1:1/backtest/s", "http://127.0.0.1:1/backtest/s")]
fn without_query_drops_the_query(#[case] url: &str, #[case] expected: &str) {
assert_eq!(without_query(url), expected);
}
}