use std::{collections::VecDeque, sync::Arc, time::Duration};
use futures::FutureExt;
use simulator_api::{
BacktestError, BacktestStatus, ContinueParams, ContinueToParams, CreateBacktestSessionRequest,
DiscoveryBatchEvent, PausedEvent, SessionId, SessionSummary,
session_endpoint::{SessionEndpointUrl, SessionGrant},
};
use solana_address::Address;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;
use solana_transaction_status::EncodedConfirmedTransactionWithStatusMeta;
use thiserror::Error;
use tokio::sync::{mpsc, watch};
use tokio_util::sync::CancellationToken;
use super::{
ConnectionFailure, ConnectionStatus, ControlEvent, DEFAULT_DISCONNECT_TIMEOUT_SECS,
ReconnectCoordinator, SessionInfo, StartSessionParams, SubscriptionDiagnostics,
SubscriptionHandle, SubscriptionNotification,
control::{ControlHandle, spawn_control_manager},
grant::{LivenessCheck, ManagementTarget, SingleCreate, request_session_grant},
spawn_account_diff_subscription_manager, spawn_action_subscription_manager,
spawn_diagnostic_subscription_manager, spawn_replacement_subscription_manager,
spawn_transaction_subscription_manager,
};
use crate::{
endpoint::rpc_client,
error::err_chain,
subscriptions::{
AccountDiffNotification, ActionResultNotification, DiagnosticNotification,
ReplacementNotification,
},
};
#[derive(Debug, Error)]
pub enum CreateError {
#[error("server rejected the request: {0}")]
Rejected(BacktestError),
#[error("{0}")]
Connection(String),
#[error(
"the connection to the server dropped after the create was sent ({reason}); a session \
may have started, and it ends itself when nobody attaches"
)]
LostAfterSend {
reason: String,
},
#[error("{0}")]
Protocol(String),
#[error("a parallel create needs ManagedParallelSession")]
ParallelRequest,
#[error("a single create needs ManagedBacktestSession")]
SingleRequest,
#[error("session {session_id} is not reachable at {endpoint}: {reason}")]
EndpointUnreachable {
session_id: SessionId,
endpoint: SessionEndpointUrl,
reason: String,
},
}
impl CreateError {
pub fn is_retryable(&self) -> bool {
match self {
Self::Rejected(err) => err.is_retryable(),
Self::Connection(_) => true,
Self::LostAfterSend { .. }
| Self::EndpointUnreachable { .. }
| Self::Protocol(_)
| Self::ParallelRequest
| Self::SingleRequest => false,
}
}
}
#[derive(Debug, Error)]
pub enum ManagedSessionError {
#[error("session create failed: {0}")]
Create(CreateError),
#[error("control channel closed")]
ControlClosed,
#[error("control failed: {0}")]
ControlFailed(String),
#[error("subscription failed: {0}")]
SubscriptionFailed(String),
#[error("cancelled")]
Cancelled,
#[error("API key rejected: HTTP {0}")]
ApiKeyRejected(http::StatusCode),
#[error("the session's endpoint rejected the token")]
SessionTokenRejected,
#[error("control closed while sending continue: {0}")]
ContinueSend(String),
#[error("server error: {0}")]
Remote(BacktestError),
#[error("session completed before it was ready to continue")]
CompletedBeforeReady,
}
impl ManagedSessionError {
pub fn is_retryable(&self) -> bool {
match self {
Self::Create(err) => err.is_retryable(),
Self::Remote(err) => err.is_retryable(),
Self::ControlFailed(_) | Self::SubscriptionFailed(_) | Self::SessionTokenRejected => {
true
}
Self::ControlClosed
| Self::ContinueSend(_)
| Self::Cancelled
| Self::ApiKeyRejected(_)
| Self::CompletedBeforeReady => false,
}
}
}
#[derive(Debug)]
pub enum ManagedEvent {
ReadyForContinue,
Paused(PausedEvent),
DiscoveryBatch(DiscoveryBatchEvent),
Slot(u64),
Status(BacktestStatus),
Completed {
summary: Option<SessionSummary>,
},
Error(BacktestError),
Transaction(Box<EncodedConfirmedTransactionWithStatusMeta>),
AccountDiff(AccountDiffNotification),
ActionResult(ActionResultNotification),
Diagnostic(DiagnosticNotification),
Replacement(Box<ReplacementNotification>),
}
const DEFAULT_COMPLETION_DRAIN_TIMEOUT: Duration = Duration::from_secs(60);
pub(super) enum DrainOutcome {
Complete(Vec<ManagedEvent>),
Stalled(Vec<ManagedEvent>),
TokenRejected(Vec<ManagedEvent>),
}
pub struct ManagedBacktestSession {
session_info: SessionInfo,
rpc: RpcClient,
control: Option<ControlHandle>,
subscriptions: Vec<SubscriptionHandle>,
session_cancel: CancellationToken,
post_completion: Option<VecDeque<ManagedEvent>>,
post_completion_error: Option<ManagedSessionError>,
completion_drain_timeout: Duration,
reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
subscription_diagnostics: Arc<SubscriptionDiagnostics>,
}
impl ManagedBacktestSession {
pub async fn start(
url: String,
api_key: String,
create: CreateBacktestSessionRequest,
) -> Result<Self, ManagedSessionError> {
Self::start_with_params(
StartSessionParams::builder()
.url(url)
.api_key(api_key)
.create(create)
.build(),
None,
)
.await
}
pub async fn start_with_params(
params: StartSessionParams,
reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
) -> Result<Self, ManagedSessionError> {
let StartSessionParams {
url,
api_key,
extra_headers,
create,
parent_cancel,
subscription_diagnostics,
} = params;
let create = SingleCreate::try_from(create)
.map_err(ManagedSessionError::Create)?
.with_default_disconnect_timeout(DEFAULT_DISCONNECT_TIMEOUT_SECS);
let management = ManagementTarget::managed(url, api_key, extra_headers);
let grant = parent_cancel
.run_until_cancelled(request_session_grant(&management, create))
.await
.ok_or(ManagedSessionError::Cancelled)??;
let check = LivenessCheck::session(management, &grant);
Self::attach_granted(
grant,
check,
&parent_cancel,
reconnect_coordinator,
subscription_diagnostics,
)
.await
}
pub(super) async fn attach_granted(
grant: SessionGrant,
check: LivenessCheck,
parent_cancel: &CancellationToken,
reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
subscription_diagnostics: Arc<SubscriptionDiagnostics>,
) -> Result<Self, ManagedSessionError> {
let rpc = rpc_client(&grant, CommitmentConfig::confirmed()).map_err(|e| {
ManagedSessionError::Create(CreateError::Protocol(format!(
"the grant gives no usable RPC client: {}",
err_chain(&e)
)))
})?;
let session_info = SessionInfo::from_grant(grant.clone());
let session_cancel = parent_cancel.child_token();
let mut control = spawn_control_manager(grant, check, session_cancel.clone());
tokio::select! {
biased;
() = parent_cancel.cancelled() => {
session_cancel.cancel();
control.join().await;
return Err(ManagedSessionError::Cancelled);
}
result = control.wait_attached() => result?,
}
Ok(Self {
session_info,
rpc,
control: Some(control),
subscriptions: Vec::new(),
session_cancel,
post_completion: None,
post_completion_error: None,
completion_drain_timeout: DEFAULT_COMPLETION_DRAIN_TIMEOUT,
reconnect_coordinator,
subscription_diagnostics,
})
}
pub fn session_info(&self) -> &SessionInfo {
&self.session_info
}
pub fn rpc(&self) -> &RpcClient {
&self.rpc
}
pub fn set_completion_drain_timeout(&mut self, idle_timeout: std::time::Duration) {
self.completion_drain_timeout = idle_timeout;
}
pub fn subscribe_transactions(&mut self, program_ids: Vec<Address>) {
self.subscriptions
.push(spawn_transaction_subscription_manager(
self.session_info.rpc_endpoint.clone(),
program_ids,
self.session_cancel.clone(),
self.reconnect_coordinator.clone(),
Arc::clone(&self.subscription_diagnostics),
));
}
pub fn subscribe_account_diffs(&mut self, program_ids: Vec<Address>) {
self.subscriptions
.push(spawn_account_diff_subscription_manager(
self.session_info.rpc_endpoint.clone(),
program_ids,
self.session_cancel.clone(),
self.reconnect_coordinator.clone(),
Arc::clone(&self.subscription_diagnostics),
));
}
pub fn subscribe_actions(&mut self) {
self.subscriptions.push(spawn_action_subscription_manager(
self.session_info.rpc_endpoint.clone(),
self.session_cancel.clone(),
self.reconnect_coordinator.clone(),
Arc::clone(&self.subscription_diagnostics),
));
}
pub fn subscribe_replacements(&mut self) {
self.subscriptions
.push(spawn_replacement_subscription_manager(
self.session_info.rpc_endpoint.clone(),
self.session_cancel.clone(),
self.reconnect_coordinator.clone(),
Arc::clone(&self.subscription_diagnostics),
));
}
pub fn subscribe_diagnostics(&mut self) {
self.subscriptions
.push(spawn_diagnostic_subscription_manager(
self.session_info.rpc_endpoint.clone(),
self.session_cancel.clone(),
self.reconnect_coordinator.clone(),
Arc::clone(&self.subscription_diagnostics),
));
}
pub async fn next_event(&mut self) -> Result<ManagedEvent, ManagedSessionError> {
if let Some(buffered) = self.post_completion.as_mut() {
if let Some(event) = buffered.pop_front() {
return Ok(event);
}
return Err(self
.post_completion_error
.take()
.unwrap_or(ManagedSessionError::ControlClosed));
}
tokio::task::coop::consume_budget().await;
let event = {
let cancel = self.session_cancel.clone();
let control = self
.control
.as_mut()
.ok_or(ManagedSessionError::ControlClosed)?;
let subscriptions = &mut self.subscriptions;
match recv_queued(&mut control.events) {
Some(event) => ManagedEvent::from(event),
None => {
if let Some(event) = try_next_subscription_event(subscriptions) {
return Ok(event);
}
tokio::select! {
biased;
() = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
event = control.events.recv() => match event {
Some(event) => ManagedEvent::from(event),
None => return Err(control_closed(&control.status)),
},
event = wait_any_subscription_event(subscriptions) => event,
}
}
}
};
let ManagedEvent::Completed { summary } = event else {
return Ok(event);
};
let (mut buffered, terminal): (VecDeque<ManagedEvent>, _) =
match drain_subscriptions_until_complete(
&mut self.subscriptions,
&self.session_cancel,
self.completion_drain_timeout,
)
.await
{
DrainOutcome::Complete(events) => {
(events.into(), Ok(ManagedEvent::Completed { summary }))
}
DrainOutcome::Stalled(events) => (
events.into(),
Err(ManagedSessionError::SubscriptionFailed(
"completion drain stalled: subscriptions did not deliver their \
end-of-stream terminals; the captured stream is incomplete"
.to_string(),
)),
),
DrainOutcome::TokenRejected(events) => (
events.into(),
Err(ManagedSessionError::SessionTokenRejected),
),
};
match terminal {
Ok(completed) => buffered.push_back(completed),
Err(err) => self.post_completion_error = Some(err),
}
let first = buffered.pop_front();
self.post_completion = Some(buffered);
match first {
Some(event) => Ok(event),
None => Err(self
.post_completion_error
.take()
.unwrap_or(ManagedSessionError::ControlClosed)),
}
}
pub async fn send_continue(
&mut self,
params: ContinueParams,
) -> Result<(), ManagedSessionError> {
self.wait_all_up().await?;
self.control_mut()?
.send_continue(params)
.await
.map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
}
pub async fn send_continue_to(
&mut self,
params: ContinueToParams,
) -> Result<(), ManagedSessionError> {
self.wait_all_up().await?;
self.control_mut()?
.send_continue_to(params)
.await
.map_err(|e| ManagedSessionError::ContinueSend(e.to_string()))
}
pub async fn wait_until_ready(&mut self) -> Result<(), ManagedSessionError> {
loop {
match self.next_event().await? {
ManagedEvent::ReadyForContinue => return Ok(()),
ManagedEvent::Completed { .. } => {
return Err(ManagedSessionError::CompletedBeforeReady);
}
ManagedEvent::Error(err) => return Err(ManagedSessionError::Remote(err)),
_ => {}
}
}
}
pub async fn run_to_completion(
mut self,
step: ContinueParams,
mut on_event: impl FnMut(ManagedEvent),
) -> Result<Option<SessionSummary>, ManagedSessionError> {
let result = async {
loop {
match self.next_event().await? {
ManagedEvent::ReadyForContinue => {
self.send_continue(step.clone()).await?;
}
ManagedEvent::Completed { summary } => return Ok(summary),
ManagedEvent::Error(err) => return Err(ManagedSessionError::Remote(err)),
other => on_event(other),
}
}
}
.await;
self.shutdown().await;
result
}
pub async fn shutdown(mut self) {
self.session_cancel.cancel();
if let Some(control) = self.control.take() {
control.join().await;
}
for sub in std::mem::take(&mut self.subscriptions) {
drop(sub.notifications);
drop(sub.join.await);
}
}
fn control_mut(&mut self) -> Result<&mut ControlHandle, ManagedSessionError> {
self.control
.as_mut()
.ok_or(ManagedSessionError::ControlClosed)
}
async fn wait_all_up(&self) -> Result<(), ManagedSessionError> {
let control = self
.control
.as_ref()
.ok_or(ManagedSessionError::ControlClosed)?
.status
.clone();
let subscriptions = self
.subscriptions
.iter()
.map(|s| s.status.clone())
.collect();
wait_connections_up(control, subscriptions, &self.session_cancel).await
}
}
fn failure_error(
reason: &ConnectionFailure,
failed: fn(String) -> ManagedSessionError,
) -> ManagedSessionError {
match reason {
ConnectionFailure::TokenRejected => ManagedSessionError::SessionTokenRejected,
ConnectionFailure::RetriesExhausted(_)
| ConnectionFailure::SessionEnded
| ConnectionFailure::Refused(_) => failed(reason.to_string()),
}
}
pub(super) async fn wait_connections_up(
mut control: watch::Receiver<ConnectionStatus>,
mut subscriptions: Vec<watch::Receiver<ConnectionStatus>>,
cancel: &CancellationToken,
) -> Result<(), ManagedSessionError> {
loop {
let control_status = control.borrow().clone();
match &control_status {
ConnectionStatus::Failed(why) => {
return Err(failure_error(why, ManagedSessionError::ControlFailed));
}
ConnectionStatus::Ended => return Err(ManagedSessionError::ControlClosed),
ConnectionStatus::Up | ConnectionStatus::Down => {}
}
let mut all_subscriptions_up = true;
for subscription in &subscriptions {
match &*subscription.borrow() {
ConnectionStatus::Failed(why) => {
return Err(failure_error(why, ManagedSessionError::SubscriptionFailed));
}
ConnectionStatus::Up => {}
_ => all_subscriptions_up = false,
}
}
if control_status == ConnectionStatus::Up && all_subscriptions_up {
return Ok(());
}
tokio::select! {
() = cancel.cancelled() => return Err(ManagedSessionError::Cancelled),
_ = control.changed() => {}
() = wait_any_subscription_change(&mut subscriptions) => {}
}
}
}
pub(super) async fn drain_subscriptions_until_complete(
subscriptions: &mut [SubscriptionHandle],
cancel: &CancellationToken,
idle_timeout: std::time::Duration,
) -> DrainOutcome {
let mut events = Vec::new();
if subscriptions.is_empty() {
return DrainOutcome::Complete(events);
}
loop {
while let Some(event) = try_next_subscription_event(subscriptions) {
events.push(event);
}
if subscriptions.iter().all(|s| s.notifications.is_closed()) {
let any_rejected = subscriptions.iter().any(|s| {
matches!(
*s.status.borrow(),
ConnectionStatus::Failed(ConnectionFailure::TokenRejected)
)
});
let any_failed = subscriptions
.iter()
.any(|s| matches!(*s.status.borrow(), ConnectionStatus::Failed(_)));
return match (any_rejected, any_failed) {
(true, _) => DrainOutcome::TokenRejected(events),
(false, true) => DrainOutcome::Stalled(events),
(false, false) => DrainOutcome::Complete(events),
};
}
tokio::select! {
biased;
() = cancel.cancelled() => return DrainOutcome::Complete(events),
() = tokio::time::sleep(idle_timeout) => {
let any_up = subscriptions.iter().any(|s| {
!s.notifications.is_closed()
&& matches!(*s.status.borrow(), ConnectionStatus::Up)
});
if any_up {
return DrainOutcome::Stalled(events);
}
}
received = recv_any_open_subscription(subscriptions) => {
if let Some(event) = received {
events.push(event);
}
}
}
}
}
impl Drop for ManagedBacktestSession {
fn drop(&mut self) {
self.session_cancel.cancel();
}
}
pub(super) async fn wait_any_subscription_change(
subscriptions: &mut [watch::Receiver<ConnectionStatus>],
) {
if subscriptions.is_empty() {
std::future::pending::<()>().await;
return;
}
drop(
futures::future::select_all(subscriptions.iter_mut().map(|s| Box::pin(s.changed()))).await,
);
}
pub(super) async fn wait_any_subscription_event(
subscriptions: &mut [SubscriptionHandle],
) -> ManagedEvent {
loop {
if let Some(event) = try_next_subscription_event(subscriptions) {
return event;
}
let futures: Vec<_> = subscriptions
.iter_mut()
.filter(|s| !s.notifications.is_closed())
.map(|s| Box::pin(s.notifications.recv()))
.collect();
if futures.is_empty() {
std::future::pending::<()>().await;
}
let (notification, _, _) = futures::future::select_all(futures).await;
if let Some(notification) = notification {
return notification.into();
}
}
}
pub(super) async fn recv_any_open_subscription(
subscriptions: &mut [SubscriptionHandle],
) -> Option<ManagedEvent> {
let futures: Vec<_> = subscriptions
.iter_mut()
.filter(|s| !s.notifications.is_closed())
.map(|s| Box::pin(s.notifications.recv()))
.collect();
if futures.is_empty() {
return None;
}
let (notification, _, _) = futures::future::select_all(futures).await;
notification.map(Into::into)
}
pub(super) fn try_next_subscription_event(
subscriptions: &mut [SubscriptionHandle],
) -> Option<ManagedEvent> {
for subscription in subscriptions {
if let Some(notification) = recv_queued(&mut subscription.notifications) {
return Some(notification.into());
}
}
None
}
fn recv_queued<T>(receiver: &mut mpsc::Receiver<T>) -> Option<T> {
tokio::task::coop::unconstrained(receiver.recv())
.now_or_never()
.flatten()
}
fn control_closed(status: &watch::Receiver<ConnectionStatus>) -> ManagedSessionError {
match &*status.borrow() {
ConnectionStatus::Failed(why) => failure_error(why, ManagedSessionError::ControlFailed),
ConnectionStatus::Up | ConnectionStatus::Down | ConnectionStatus::Ended => {
ManagedSessionError::ControlClosed
}
}
}
impl From<ControlEvent> for ManagedEvent {
fn from(event: ControlEvent) -> Self {
match event {
ControlEvent::ReadyForContinue => Self::ReadyForContinue,
ControlEvent::Paused(event) => Self::Paused(event),
ControlEvent::DiscoveryBatch(event) => Self::DiscoveryBatch(event),
ControlEvent::Slot(slot) => Self::Slot(slot),
ControlEvent::Status(status) => Self::Status(status),
ControlEvent::Completed { summary } => Self::Completed { summary },
ControlEvent::Error(error) => Self::Error(error),
}
}
}
impl From<SubscriptionNotification> for ManagedEvent {
fn from(notification: SubscriptionNotification) -> Self {
match notification {
SubscriptionNotification::Transaction(transaction) => Self::Transaction(transaction),
SubscriptionNotification::AccountDiff(diff) => Self::AccountDiff(diff),
SubscriptionNotification::ActionResult(result) => Self::ActionResult(result),
SubscriptionNotification::Diagnostic(sample) => Self::Diagnostic(sample),
SubscriptionNotification::Replacement(replacement) => Self::Replacement(replacement),
}
}
}
#[cfg(test)]
mod tests {
use std::{
future::Future,
pin::Pin,
task::{Poll, Waker},
};
use futures::{StreamExt, stream::FuturesUnordered};
use parking_lot::Mutex;
use simulator_api::MAX_DISCONNECT_TIMEOUT_SECS;
use super::*;
use crate::{
managed::RECONNECT_MAX_TOTAL,
subscriptions::{DiagnosticContext, DiagnosticNotification},
};
#[tokio::test]
async fn drain_reports_a_token_rejected_after_the_last_continue() {
let (_status_tx, status) =
watch::channel(ConnectionStatus::Failed(ConnectionFailure::TokenRejected));
let (sender, notifications) = mpsc::channel(1);
drop(sender);
let mut subscriptions = vec![SubscriptionHandle {
status,
notifications,
join: tokio::spawn(async {}),
}];
let outcome = drain_subscriptions_until_complete(
&mut subscriptions,
&CancellationToken::new(),
Duration::from_secs(1),
)
.await;
assert!(matches!(outcome, DrainOutcome::TokenRejected(_)));
}
fn notification() -> SubscriptionNotification {
SubscriptionNotification::Diagnostic(DiagnosticNotification {
context: DiagnosticContext { slot: 0 },
slot: 0,
probe_index: 0,
label: None,
market: String::new(),
usd_value: 0,
pairs: Vec::new(),
router_slot: None,
results: None,
account_hashes: Vec::new(),
err: None,
})
}
#[test]
fn subscription_reads_keep_a_sibling_wakeup_on_the_block_on_thread() {
const SENDERS: usize = 4;
const ROUNDS: usize = 2_000;
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
let (sender, notifications) = mpsc::channel(1_024);
let (_status_tx, status) = watch::channel(ConnectionStatus::Up);
let mut subscriptions = vec![SubscriptionHandle {
status,
notifications,
join: runtime.spawn(async {}),
}];
for _ in 0..SENDERS {
let sender = sender.clone();
std::thread::spawn(move || {
while sender.blocking_send(notification()).is_ok() {
#[expect(
clippy::disallowed_methods,
reason = "dedicated sender OS thread in concurrency test"
)]
std::thread::sleep(Duration::from_micros(20));
}
});
}
let (done_tx, done) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let sibling = Arc::new(Mutex::new(None::<Waker>));
let driver = {
let sibling = Arc::clone(&sibling);
async move {
for _ in 0..ROUNDS {
while try_next_subscription_event(&mut subscriptions).is_some() {}
if let Some(waker) = sibling.lock().as_ref() {
waker.wake_by_ref();
}
while try_next_subscription_event(&mut subscriptions).is_none() {}
wait_any_subscription_event(&mut subscriptions).await;
}
}
};
let sibling = std::future::poll_fn(move |cx| {
*sibling.lock() = Some(cx.waker().clone());
Poll::<()>::Pending
});
let idle = std::future::pending::<()>();
let mut sessions: FuturesUnordered<Pin<Box<dyn Future<Output = ()>>>> =
FuturesUnordered::new();
sessions.push(Box::pin(driver));
sessions.push(Box::pin(sibling));
sessions.push(Box::pin(idle));
runtime.block_on(sessions.next());
#[expect(
clippy::let_underscore_must_use,
reason = "receiver may have timed out"
)]
let _ = done_tx.send(());
});
assert!(
done.recv_timeout(Duration::from_secs(30)).is_ok(),
"the sessions stopped: a subscription read consumed the block_on thread's wakeup"
);
}
#[test]
fn default_disconnect_timeout_covers_the_reconnect_budget_without_clamping() {
assert!(u64::from(DEFAULT_DISCONNECT_TIMEOUT_SECS) > RECONNECT_MAX_TOTAL.as_secs());
const { assert!(DEFAULT_DISCONNECT_TIMEOUT_SECS <= MAX_DISCONNECT_TIMEOUT_SECS) };
}
}