use std::{collections::BTreeMap, time::Duration};
use futures::StreamExt;
use http::{HeaderMap, StatusCode};
use simulator_api::{
BacktestError, BacktestRequest, BacktestResponse, ControlSessionId,
CreateBacktestSessionRequest, CreateBacktestSessionRequestV1, SessionId,
session_endpoint::{ParallelGrant, SessionGrant},
};
use tokio_tungstenite::{
connect_async,
tungstenite::{
Error as WsError, Message, client::IntoClientRequest, http::HeaderValue,
protocol::frame::coding::CloseCode,
},
};
use tracing::warn;
use super::{
CONNECT_TIMEOUT, CreateError, GRACEFUL_CLOSE_TIMEOUT, InboundFrame, ManagedSessionError,
ReconnectBudget, Ws, classify_inbound, managed_user_agent, send_request,
};
use crate::error::{err_chain, from_json};
const GRANT_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
const LIVENESS_CHECK_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone)]
pub(crate) struct ManagementTarget {
pub url: String,
pub api_key: String,
pub extra_headers: HeaderMap,
pub user_agent: String,
pub connect_timeout: Duration,
}
impl ManagementTarget {
pub(super) fn managed(url: String, api_key: String, extra_headers: HeaderMap) -> Self {
Self {
url,
api_key,
extra_headers,
user_agent: managed_user_agent(),
connect_timeout: CONNECT_TIMEOUT,
}
}
}
pub(crate) struct SingleCreate(CreateBacktestSessionRequestV1);
impl TryFrom<CreateBacktestSessionRequest> for SingleCreate {
type Error = CreateError;
fn try_from(create: CreateBacktestSessionRequest) -> Result<Self, Self::Error> {
let create = CreateBacktestSessionRequestV1::from(create);
if create.parallel {
Err(CreateError::ParallelRequest)
} else {
Ok(Self(create))
}
}
}
impl SingleCreate {
pub(crate) fn with_default_disconnect_timeout(mut self, secs: u16) -> Self {
self.0.request.disconnect_timeout_secs.get_or_insert(secs);
self
}
}
pub(crate) struct ParallelCreate(CreateBacktestSessionRequestV1);
impl TryFrom<CreateBacktestSessionRequest> for ParallelCreate {
type Error = CreateError;
fn try_from(create: CreateBacktestSessionRequest) -> Result<Self, Self::Error> {
let create = CreateBacktestSessionRequestV1::from(create);
if create.parallel {
Ok(Self(create))
} else {
Err(CreateError::SingleRequest)
}
}
}
pub(crate) enum GrantError {
ApiKeyRejected(StatusCode),
Create(CreateError),
}
impl From<GrantError> for ManagedSessionError {
fn from(error: GrantError) -> Self {
match error {
GrantError::ApiKeyRejected(status) => Self::ApiKeyRejected(status),
GrantError::Create(error) => Self::Create(error),
}
}
}
pub(crate) enum AttachError {
ApiKeyRejected(StatusCode),
Connection(String),
Protocol(String),
}
enum ExchangeError {
ApiKeyRejected(StatusCode),
NotSent(String),
Draining(String),
LostAfterSend(String),
Protocol(String),
}
impl From<ExchangeError> for AttachError {
fn from(error: ExchangeError) -> Self {
match error {
ExchangeError::ApiKeyRejected(status) => Self::ApiKeyRejected(status),
ExchangeError::NotSent(why)
| ExchangeError::Draining(why)
| ExchangeError::LostAfterSend(why) => Self::Connection(why),
ExchangeError::Protocol(why) => Self::Protocol(why),
}
}
}
enum Resend {
Never,
AfterLostSend,
}
async fn connect_management(target: &ManagementTarget) -> Result<Ws, ExchangeError> {
let ManagementTarget {
url,
api_key,
extra_headers,
user_agent,
connect_timeout,
} = target;
let mut request = url
.as_str()
.into_client_request()
.map_err(|e| ExchangeError::NotSent(format!("build request: {}", err_chain(&e))))?;
request.headers_mut().extend(extra_headers.clone());
request.headers_mut().insert(
"X-API-Key",
HeaderValue::from_str(api_key)
.map_err(|e| ExchangeError::NotSent(format!("api key header: {}", err_chain(&e))))?,
);
request.headers_mut().insert(
"user-agent",
HeaderValue::from_str(user_agent)
.map_err(|e| ExchangeError::NotSent(format!("build user-agent: {e}")))?,
);
let (ws, _) = tokio::time::timeout(*connect_timeout, connect_async(request))
.await
.map_err(|_elapsed| {
ExchangeError::NotSent(format!("connect timeout after {connect_timeout:?}"))
})?
.map_err(|e| match &e {
WsError::Http(response)
if matches!(
response.status(),
StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN
) =>
{
ExchangeError::ApiKeyRejected(response.status())
}
_ => ExchangeError::NotSent(format!("connect: {}", err_chain(&e))),
})?;
Ok(ws)
}
pub(crate) async fn request_session_grant(
management: &ManagementTarget,
create: SingleCreate,
) -> Result<SessionGrant, GrantError> {
let message = BacktestRequest::CreateBacktestSessionV2(create.0);
match send_create(management, &message, Resend::Never).await? {
BacktestResponse::SessionGranted(grant) => Ok(grant),
BacktestResponse::Error(error) => Err(GrantError::Create(CreateError::Rejected(error))),
BacktestResponse::SessionsGranted(run) => {
Err(GrantError::Create(CreateError::Protocol(format!(
"management answered with the parallel run {}; start a parallel create \
with ManagedParallelSession",
run.control_session_id
))))
}
BacktestResponse::Status { .. }
| BacktestResponse::SessionCreated { .. }
| BacktestResponse::SessionAttached { .. }
| BacktestResponse::SessionsCreatedV2 { .. }
| BacktestResponse::ParallelSessionAttachedV2 { .. }
| BacktestResponse::ReadyForContinue
| BacktestResponse::SlotNotification(_)
| BacktestResponse::Paused(_)
| BacktestResponse::DiscoveryBatch(_)
| BacktestResponse::Success
| BacktestResponse::Completed { .. }
| BacktestResponse::SessionEventV2 { .. } => {
Err(GrantError::Create(CreateError::Protocol(
"management answered the create with a response that is not a grant; \
it may be too old for this client"
.to_owned(),
)))
}
}
}
pub(crate) async fn request_parallel_grant(
management: &ManagementTarget,
create: ParallelCreate,
) -> Result<ParallelGrant, GrantError> {
let message = BacktestRequest::CreateBacktestSessionV2(create.0);
match send_create(management, &message, Resend::AfterLostSend).await? {
BacktestResponse::SessionsGranted(run) => Ok(run),
BacktestResponse::Error(error) => Err(GrantError::Create(CreateError::Rejected(error))),
BacktestResponse::SessionGranted(grant) => {
Err(GrantError::Create(CreateError::Protocol(format!(
"management answered the parallel create with the single session {}",
grant.session_id
))))
}
BacktestResponse::Status { .. }
| BacktestResponse::SessionCreated { .. }
| BacktestResponse::SessionAttached { .. }
| BacktestResponse::SessionsCreatedV2 { .. }
| BacktestResponse::ParallelSessionAttachedV2 { .. }
| BacktestResponse::ReadyForContinue
| BacktestResponse::SlotNotification(_)
| BacktestResponse::Paused(_)
| BacktestResponse::DiscoveryBatch(_)
| BacktestResponse::Success
| BacktestResponse::Completed { .. }
| BacktestResponse::SessionEventV2 { .. } => {
Err(GrantError::Create(CreateError::Protocol(
"management answered the create with a response that is not a grant; \
it may be too old for this client"
.to_owned(),
)))
}
}
}
pub(crate) async fn request_attach(
management: &ManagementTarget,
session_id: SessionId,
) -> Result<BacktestResponse, AttachError> {
let message = BacktestRequest::AttachBacktestSession {
session_id,
last_sequence: None,
};
Ok(exchange(management, &message).await?)
}
async fn send_create(
management: &ManagementTarget,
message: &BacktestRequest,
resend: Resend,
) -> Result<BacktestResponse, GrantError> {
let mut budget = ReconnectBudget::new();
let mut lost_after_send = None;
loop {
let why = match exchange(management, message).await {
Ok(response) => return Ok(response),
Err(ExchangeError::ApiKeyRejected(status)) => {
return Err(GrantError::ApiKeyRejected(status));
}
Err(ExchangeError::Protocol(why)) => {
return Err(GrantError::Create(CreateError::Protocol(why)));
}
Err(ExchangeError::NotSent(why)) => format!("connect: {why}"),
Err(ExchangeError::Draining(reason)) => format!("management draining: {reason}"),
Err(ExchangeError::LostAfterSend(reason)) => match resend {
Resend::Never => {
return Err(GrantError::Create(CreateError::LostAfterSend { reason }));
}
Resend::AfterLostSend => {
let why = format!("create: {reason}");
lost_after_send = Some(reason);
why
}
},
};
let Some(delay) = budget.next_backoff() else {
let error = match lost_after_send {
Some(reason) => CreateError::LostAfterSend { reason },
None => CreateError::Connection(why),
};
return Err(GrantError::Create(error));
};
warn!(attempt = budget.attempt(), error = %why, ?delay, "create failed, retrying");
tokio::time::sleep(delay).await;
}
}
#[derive(Clone, Copy)]
enum CheckSubject {
Session(SessionId),
Child {
run: ControlSessionId,
session: SessionId,
},
}
pub(crate) struct LivenessCheck {
management: ManagementTarget,
subject: CheckSubject,
}
pub(crate) enum Liveness {
Alive,
Ended,
Unknown(String),
}
impl LivenessCheck {
pub(super) fn session(management: ManagementTarget, grant: &SessionGrant) -> Self {
Self {
management,
subject: CheckSubject::Session(grant.session_id),
}
}
pub(super) fn child(
management: ManagementTarget,
run: ControlSessionId,
grant: &SessionGrant,
) -> Self {
Self {
management,
subject: CheckSubject::Child {
run,
session: grant.session_id,
},
}
}
pub(crate) async fn ask(&self) -> Liveness {
let unknown = |error: AttachError| {
Liveness::Unknown(match error {
AttachError::ApiKeyRejected(status) => {
format!("management rejected the API key: {status}")
}
AttachError::Connection(why) | AttachError::Protocol(why) => why,
})
};
let answer = async {
let (session, response) = match self.subject {
CheckSubject::Session(session) => {
(session, request_attach(&self.management, session).await)
}
CheckSubject::Child { run, session } => {
let message = BacktestRequest::AttachParallelControlSessionV2 {
control_session_id: run,
last_sequences: BTreeMap::new(),
};
(
session,
exchange(&self.management, &message)
.await
.map_err(AttachError::from),
)
}
};
match response {
Ok(response) => liveness_from(session, response),
Err(error) => unknown(error),
}
};
tokio::time::timeout(LIVENESS_CHECK_TIMEOUT, answer)
.await
.unwrap_or_else(|_| {
Liveness::Unknown(format!(
"management did not answer within {LIVENESS_CHECK_TIMEOUT:?}"
))
})
}
}
fn liveness_from(session: SessionId, response: BacktestResponse) -> Liveness {
match response {
BacktestResponse::SessionGranted(_) => Liveness::Alive,
BacktestResponse::SessionsGranted(run) => {
if run.sessions.iter().any(|child| child.session_id == session) {
Liveness::Alive
} else {
Liveness::Ended
}
}
BacktestResponse::Error(BacktestError::SessionNotFound { .. }) => Liveness::Ended,
BacktestResponse::Error(BacktestError::SessionOwnershipBusy { .. }) => Liveness::Alive,
BacktestResponse::Error(error) => refused(&error),
BacktestResponse::SessionCreated { .. }
| BacktestResponse::SessionAttached { .. }
| BacktestResponse::SessionsCreatedV2 { .. }
| BacktestResponse::ParallelSessionAttachedV2 { .. }
| BacktestResponse::ReadyForContinue
| BacktestResponse::SlotNotification(_)
| BacktestResponse::Paused(_)
| BacktestResponse::DiscoveryBatch(_)
| BacktestResponse::Success
| BacktestResponse::Completed { .. }
| BacktestResponse::Status { .. }
| BacktestResponse::SessionEventV2 { .. } => unexpected(&response),
}
}
fn refused(error: &BacktestError) -> Liveness {
Liveness::Unknown(format!(
"management refused the attach: {}",
err_chain(error)
))
}
fn unexpected(response: &BacktestResponse) -> Liveness {
Liveness::Unknown(format!("management answered the attach with {response:?}"))
}
async fn exchange(
management: &ManagementTarget,
message: &BacktestRequest,
) -> Result<BacktestResponse, ExchangeError> {
let mut ws = connect_management(management).await?;
send_request(&mut ws, message)
.await
.map_err(ExchangeError::LostAfterSend)?;
let response = next_answer(&mut ws).await?;
drop(tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, ws.close(None)).await);
Ok(response)
}
async fn next_answer(ws: &mut Ws) -> Result<BacktestResponse, ExchangeError> {
loop {
let frame = tokio::time::timeout(GRANT_RESPONSE_TIMEOUT, ws.next())
.await
.map_err(|_elapsed| {
ExchangeError::LostAfterSend(format!(
"no frame from management within {GRANT_RESPONSE_TIMEOUT:?}"
))
})?;
if let Some(Ok(Message::Close(Some(close)))) = &frame
&& close.code == CloseCode::Restart
{
return Err(ExchangeError::Draining(close.reason.to_string()));
}
let text = match classify_inbound(frame) {
InboundFrame::Text(text) => text,
InboundFrame::Ignore => continue,
InboundFrame::Lost(why) => return Err(ExchangeError::LostAfterSend(why)),
};
let response = from_json::<BacktestResponse>(text.as_bytes()).map_err(|e| {
ExchangeError::Protocol(format!(
"management sent a frame this client cannot read: {}",
err_chain(&e)
))
})?;
match response {
BacktestResponse::Status { .. } => {}
answer => return Ok(answer),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::endpoint::testing::read_request_head;
async fn handshake_head(extra_headers: HeaderMap) -> String {
let (port, head) = read_request_head().await;
drop(
connect_management(&ManagementTarget {
url: format!("ws://127.0.0.1:{port}"),
api_key: "k".to_owned(),
extra_headers,
user_agent: managed_user_agent(),
connect_timeout: CONNECT_TIMEOUT,
})
.await,
);
head.await.expect("join")
}
fn header_value(head: &str, name: &str) -> Option<String> {
head.lines().find_map(|line| {
let (key, value) = line.split_once(':')?;
key.eq_ignore_ascii_case(name)
.then(|| value.trim().to_string())
})
}
#[tokio::test]
async fn connect_management_identifies_itself_as_managed() {
let head = handshake_head(HeaderMap::new()).await;
let user_agent =
header_value(&head, "user-agent").expect("connect_management sent a User-Agent");
assert_eq!(
simulator_api::client_identity::classify(Some(&user_agent)).0,
simulator_api::client_identity::ClientKind::Managed,
);
}
#[tokio::test]
async fn connect_management_sends_the_extra_headers_beside_the_api_key() {
let extra_headers = HeaderMap::from_iter([(
http::HeaderName::from_static("x-extra"),
HeaderValue::from_static("extra"),
)]);
let head = handshake_head(extra_headers).await;
assert_eq!(header_value(&head, "x-extra").as_deref(), Some("extra"));
assert_eq!(header_value(&head, "x-api-key").as_deref(), Some("k"));
}
}