use std::{
ops::ControlFlow,
time::{Duration, Instant},
};
use futures::StreamExt;
use simulator_api::{
BacktestError, BacktestRequest, BacktestResponse, BacktestStatus, ContinueParams,
ContinueToParams, DiscoveryBatchEvent, PausedEvent, SequencedResponse, SessionId,
SessionSummary, session_endpoint::SessionGrant,
};
use tokio::{
sync::{mpsc, oneshot, watch},
task::JoinHandle,
};
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};
use super::{
CONNECT_TIMEOUT, ConnectionFailure, ConnectionStatus, CreateError, HANDSHAKE_RESPONSE_TIMEOUT,
InboundFrame, KEEPALIVE_INTERVAL, ManagedSessionError, MessageLoopExit, RECONNECT_UPTIME_RESET,
ReconnectBudget, Ws, cancellable_sleep, classify_inbound, graceful_close,
grant::{Liveness, LivenessCheck},
managed_user_agent, publish_status, send_keepalive_ping, send_request,
};
use crate::{
endpoint::{ControlConnectError, FirstConnect, connect_control},
error::{err_chain, from_json},
};
#[derive(Debug)]
pub enum ControlEvent {
ReadyForContinue,
Paused(PausedEvent),
DiscoveryBatch(DiscoveryBatchEvent),
Slot(u64),
Status(BacktestStatus),
Completed {
summary: Option<SessionSummary>,
},
Error(BacktestError),
}
pub(super) struct ControlHandle {
continues: mpsc::Sender<ContinueParams>,
continue_tos: mpsc::Sender<ContinueToParams>,
pub events: mpsc::Receiver<ControlEvent>,
pub status: watch::Receiver<ConnectionStatus>,
attached: Option<oneshot::Receiver<Result<(), ManagedSessionError>>>,
join: JoinHandle<()>,
}
impl ControlHandle {
pub async fn wait_attached(&mut self) -> Result<(), ManagedSessionError> {
let rx = self
.attached
.take()
.ok_or(ManagedSessionError::ControlClosed)?;
rx.await
.map_err(|_recv_err| ManagedSessionError::ControlClosed)?
}
pub async fn send_continue(
&self,
params: ContinueParams,
) -> Result<(), mpsc::error::SendError<ContinueParams>> {
self.continues.send(params).await
}
pub async fn send_continue_to(
&self,
params: ContinueToParams,
) -> Result<(), mpsc::error::SendError<ContinueToParams>> {
self.continue_tos.send(params).await
}
pub async fn join(self) {
drop(self.continues);
drop(self.continue_tos);
drop(self.events);
drop(self.join.await);
}
}
pub(super) fn spawn_control_manager(
grant: SessionGrant,
check: LivenessCheck,
cancel: CancellationToken,
) -> ControlHandle {
let (continues_tx, continues_rx) = mpsc::channel::<ContinueParams>(1);
let (continue_tos_tx, continue_tos_rx) = mpsc::channel::<ContinueToParams>(1);
let (events_tx, events_rx) = mpsc::channel::<ControlEvent>(256);
let (status_tx, status_rx) = watch::channel(ConnectionStatus::Down);
let (attached_tx, attached_rx) = oneshot::channel::<Result<(), ManagedSessionError>>();
let manager = ControlTask {
grant,
last_sequence: None,
continues_rx,
continue_tos_rx,
events_tx,
status_tx,
cancel,
check,
};
let join = tokio::spawn(manager.run(attached_tx));
ControlHandle {
continues: continues_tx,
continue_tos: continue_tos_tx,
events: events_rx,
status: status_rx,
attached: Some(attached_rx),
join,
}
}
enum AttemptError {
Cancelled,
Retry(String),
TokenRejected,
Fatal(CreateError),
}
struct ControlTask {
grant: SessionGrant,
last_sequence: Option<u64>,
continues_rx: mpsc::Receiver<ContinueParams>,
continue_tos_rx: mpsc::Receiver<ContinueToParams>,
events_tx: mpsc::Sender<ControlEvent>,
status_tx: watch::Sender<ConnectionStatus>,
cancel: CancellationToken,
check: LivenessCheck,
}
impl ControlTask {
async fn run(mut self, attached: oneshot::Sender<Result<(), ManagedSessionError>>) {
let Some(ws) = self.first_attach(attached).await else {
return;
};
info!(session_id = %self.grant.session_id, "control attached to the session");
self.run_attached(ws).await;
}
async fn first_attach(
&self,
attached: oneshot::Sender<Result<(), ManagedSessionError>>,
) -> Option<Ws> {
let first = FirstConnect::start(tokio::time::Instant::now());
let error = loop {
let why = match self.attempt().await {
Ok(ws) => {
drop(attached.send(Ok(())));
return Some(ws);
}
Err(AttemptError::Retry(why)) => why,
Err(AttemptError::Cancelled) => break ManagedSessionError::Cancelled,
Err(AttemptError::TokenRejected) => {
break ManagedSessionError::SessionTokenRejected;
}
Err(AttemptError::Fatal(error)) => break ManagedSessionError::Create(error),
};
let Some(delay) = first.retry_after(tokio::time::Instant::now()) else {
break ManagedSessionError::Create(CreateError::EndpointUnreachable {
session_id: self.grant.session_id,
endpoint: self.grant.endpoint.clone(),
reason: why,
});
};
warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control connect failed, retrying");
cancellable_sleep(delay, &self.cancel).await;
};
drop(attached.send(Err(error)));
None
}
async fn run_attached(&mut self, mut ws: Ws) {
let mut budget = ReconnectBudget::new();
loop {
publish_status(&self.status_tx, ConnectionStatus::Up);
let connected_at = Instant::now();
let why = match self.message_loop(ws).await {
MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
MessageLoopExit::Terminal => {
publish_status(&self.status_tx, ConnectionStatus::Ended);
return;
}
MessageLoopExit::ConnectionLost(why) => format!("connection lost: {why}"),
};
if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
budget.reset();
}
let Some(reattached) = self.reattach(&mut budget, why).await else {
return;
};
ws = reattached;
debug!(session_id = %self.grant.session_id, "control reattached");
}
}
async fn reattach(&self, budget: &mut ReconnectBudget, mut why: String) -> Option<Ws> {
let Some(delay) = budget.next_backoff() else {
self.fail(ConnectionFailure::RetriesExhausted(why));
return None;
};
warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control reconnecting");
if !cancellable_sleep(delay, &self.cancel).await {
return None;
}
loop {
match self.attempt().await {
Ok(ws) => return Some(ws),
Err(AttemptError::Retry(failed)) => why = format!("connect failed: {failed}"),
Err(AttemptError::Cancelled) => return None,
Err(AttemptError::TokenRejected) => {
self.fail(ConnectionFailure::TokenRejected);
return None;
}
Err(AttemptError::Fatal(error)) => {
self.fail(ConnectionFailure::Refused(error.to_string()));
return None;
}
}
let Some(delay) = budget.next_backoff() else {
self.fail(ConnectionFailure::RetriesExhausted(why));
return None;
};
warn!(session_id = %self.grant.session_id, error = %why, ?delay, "control reconnecting");
if self.backoff_and_check(delay).await.is_break() {
return None;
}
}
}
async fn backoff_and_check(&self, delay: Duration) -> ControlFlow<()> {
let sleep = tokio::time::sleep(delay);
let ask = self.check.ask();
tokio::pin!(sleep, ask);
let liveness = tokio::select! {
biased;
() = self.cancel.cancelled() => return ControlFlow::Break(()),
liveness = &mut ask => liveness,
() = &mut sleep => tokio::select! {
biased;
() = self.cancel.cancelled() => return ControlFlow::Break(()),
liveness = &mut ask => liveness,
},
};
match liveness {
Liveness::Ended => {
info!(session_id = %self.grant.session_id, "management no longer knows the session");
self.fail(ConnectionFailure::SessionEnded);
return ControlFlow::Break(());
}
Liveness::Alive => {
debug!(session_id = %self.grant.session_id, "management still grants the session");
}
Liveness::Unknown(unknown) => {
warn!(session_id = %self.grant.session_id, error = %unknown, "management could not say whether the session runs");
}
}
tokio::select! {
biased;
() = self.cancel.cancelled() => ControlFlow::Break(()),
() = &mut sleep => ControlFlow::Continue(()),
}
}
fn fail(&self, failure: ConnectionFailure) {
publish_status(&self.status_tx, ConnectionStatus::Failed(failure));
}
async fn attempt(&self) -> Result<Ws, AttemptError> {
if self.cancel.is_cancelled() {
return Err(AttemptError::Cancelled);
}
publish_status(&self.status_tx, ConnectionStatus::Down);
tokio::select! {
biased;
() = self.cancel.cancelled() => Err(AttemptError::Cancelled),
attached = self.connect_and_attach() => attached,
}
}
async fn connect_and_attach(&self) -> Result<Ws, AttemptError> {
let mut ws = connect_control(&self.grant, &managed_user_agent(), CONNECT_TIMEOUT)
.await
.map_err(|e| match e {
ControlConnectError::TokenRejected => AttemptError::TokenRejected,
request @ ControlConnectError::Request(_) => {
AttemptError::Fatal(CreateError::Protocol(request.to_string()))
}
ControlConnectError::Failed(why) => AttemptError::Retry(why),
})?;
attach(&mut ws, self.grant.session_id, self.last_sequence).await?;
Ok(ws)
}
async fn message_loop(&mut self, mut ws: Ws) -> MessageLoopExit {
let mut ping_timer = tokio::time::interval(KEEPALIVE_INTERVAL);
ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut last_inbound = Instant::now();
let exit = loop {
tokio::select! {
biased;
() = self.cancel.cancelled() => break MessageLoopExit::Cancelled,
_ = ping_timer.tick() => {
if let Some(why) = send_keepalive_ping(&mut ws, last_inbound).await {
break MessageLoopExit::ConnectionLost(why);
}
}
msg = ws.next() => {
last_inbound = Instant::now();
match classify_inbound(msg) {
InboundFrame::Text(t) => {
if let Err(exit) = self.handle_text(&t).await {
break exit;
}
}
InboundFrame::Ignore => {}
InboundFrame::Lost(why) => break MessageLoopExit::ConnectionLost(why),
}
}
req = self.continues_rx.recv() => {
match req {
Some(params) => {
if let Err(e) = send_request(&mut ws, &BacktestRequest::Continue(params)).await {
break MessageLoopExit::ConnectionLost(format!("continue send: {e}"));
}
}
None => break MessageLoopExit::SessionEnded,
}
}
req = self.continue_tos_rx.recv() => {
match req {
Some(params) => {
if let Err(e) = send_request(&mut ws, &BacktestRequest::ContinueTo(params)).await {
break MessageLoopExit::ConnectionLost(format!("continue_to send: {e}"));
}
}
None => break MessageLoopExit::SessionEnded,
}
}
}
};
if matches!(
exit,
MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled
) {
graceful_close(&mut ws).await;
}
exit
}
async fn handle_text(&mut self, text: &str) -> Result<(), MessageLoopExit> {
let (seq, response) = match serde_json::from_str::<SequencedResponse>(text) {
Ok(s) => (Some(s.seq_id), s.response),
Err(_) => match serde_json::from_str::<BacktestResponse>(text) {
Ok(r) => (None, r),
Err(e) => {
warn!(error = %err_chain(&e), "discarding undeserializable control message");
return Ok(());
}
},
};
if let Some(s) = seq {
self.last_sequence = Some(s);
}
match response {
BacktestResponse::ReadyForContinue => {
drop(self.events_tx.send(ControlEvent::ReadyForContinue).await);
}
BacktestResponse::Paused(event) => {
drop(self.events_tx.send(ControlEvent::Paused(event)).await);
}
BacktestResponse::DiscoveryBatch(event) => {
drop(
self.events_tx
.send(ControlEvent::DiscoveryBatch(event))
.await,
);
}
BacktestResponse::SlotNotification(slot) => {
drop(self.events_tx.send(ControlEvent::Slot(slot)).await);
}
BacktestResponse::Completed { summary } => {
drop(
self.events_tx
.send(ControlEvent::Completed { summary })
.await,
);
return Err(MessageLoopExit::SessionEnded);
}
BacktestResponse::Error(err) => {
if matches!(&err, BacktestError::SimulationError { .. }) {
warn!(error = %err_chain(&err), "simulation error");
return Ok(());
}
let terminal = err.is_terminal();
drop(self.events_tx.send(ControlEvent::Error(err)).await);
if terminal {
return Err(MessageLoopExit::Terminal);
}
}
BacktestResponse::Status { status } => {
drop(self.events_tx.send(ControlEvent::Status(status)).await);
}
BacktestResponse::Success => {
}
other => {
debug!(?other, "ignoring unexpected control response");
}
}
Ok(())
}
}
async fn attach(
ws: &mut Ws,
session_id: SessionId,
last_sequence: Option<u64>,
) -> Result<(), AttemptError> {
send_request(
ws,
&BacktestRequest::AttachBacktestSession {
session_id,
last_sequence,
},
)
.await
.map_err(AttemptError::Retry)?;
let deadline = tokio::time::Instant::now() + HANDSHAKE_RESPONSE_TIMEOUT;
let text = loop {
let frame = tokio::time::timeout_at(deadline, ws.next())
.await
.map_err(|_elapsed| {
AttemptError::Retry(format!(
"attach timeout after {HANDSHAKE_RESPONSE_TIMEOUT:?}"
))
})?;
match classify_inbound(frame) {
InboundFrame::Text(text) => break text,
InboundFrame::Ignore => {}
InboundFrame::Lost(why) => return Err(AttemptError::Retry(why)),
}
};
let response = from_json::<BacktestResponse>(text.as_bytes()).map_err(|e| {
AttemptError::Fatal(CreateError::Protocol(format!(
"the session answered the attach with a frame this client cannot read: {}",
err_chain(&e)
)))
})?;
match response {
BacktestResponse::SessionAttached { .. } => Ok(()),
BacktestResponse::Error(err) => Err(AttemptError::Fatal(CreateError::Rejected(err))),
BacktestResponse::Status { .. }
| BacktestResponse::SessionCreated { .. }
| BacktestResponse::SessionGranted(_)
| BacktestResponse::SessionsGranted(_)
| BacktestResponse::SessionsCreatedV2 { .. }
| BacktestResponse::ParallelSessionAttachedV2 { .. }
| BacktestResponse::ReadyForContinue
| BacktestResponse::SlotNotification(_)
| BacktestResponse::Paused(_)
| BacktestResponse::DiscoveryBatch(_)
| BacktestResponse::Success
| BacktestResponse::Completed { .. }
| BacktestResponse::SessionEventV2 { .. } => {
Err(AttemptError::Fatal(CreateError::Protocol(
"the session answered the attach with neither sessionAttached nor error".to_owned(),
)))
}
}
}