use std::{
fmt,
sync::{
Arc,
atomic::{AtomicU64, AtomicUsize, Ordering},
},
time::{Duration, Instant},
};
use bon::Builder;
use futures::SinkExt;
use http::HeaderMap;
use rand::RngExt;
use simulator_api::{
BacktestRequest, CreateBacktestSessionRequest, SessionId,
client_identity::{ClientProduct, ClientSurface},
session_endpoint::SessionGrant,
};
use tokio::{
net::TcpStream,
sync::{Notify, OwnedSemaphorePermit, Semaphore, watch},
};
use tokio_tungstenite::{
MaybeTlsStream, WebSocketStream,
tungstenite::{Error as WsError, Message},
};
use tokio_util::sync::CancellationToken;
use crate::{endpoint::without_query, error::err_chain, urls::backtest_ws_url};
mod control;
pub(crate) mod grant;
mod parallel;
mod session;
mod subscription;
pub use control::ControlEvent;
pub use parallel::{ManagedParallelSession, ParallelSubSession};
pub use session::{CreateError, ManagedBacktestSession, ManagedEvent, ManagedSessionError};
pub use subscription::{
SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
spawn_action_subscription_manager, spawn_diagnostic_subscription_manager,
spawn_replacement_subscription_manager, spawn_transaction_subscription_manager,
};
#[doc(hidden)]
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
#[doc(hidden)]
pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
#[doc(hidden)]
pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
#[doc(hidden)]
pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
#[doc(hidden)]
pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
#[doc(hidden)]
pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
#[doc(hidden)]
pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
#[doc(hidden)]
pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
#[doc(hidden)]
pub const RECONNECT_JITTER: f64 = 0.2;
pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
#[doc(hidden)]
pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
#[doc(hidden)]
pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
#[expect(
clippy::cast_possible_truncation,
reason = "RECONNECT_MAX_TOTAL is 300s, well within u16"
)]
pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConnectionStatus {
Up,
Down,
Ended,
Failed(ConnectionFailure),
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ConnectionFailure {
#[error("{0}")]
RetriesExhausted(String),
#[error("the session's endpoint rejected the token")]
TokenRejected,
#[error("the session ended; the server no longer tracks it")]
SessionEnded,
#[error("{0}")]
Refused(String),
}
#[derive(Clone)]
#[non_exhaustive]
pub struct SessionInfo {
#[expect(missing_docs, reason = "self-explanatory session identifier")]
pub session_id: SessionId,
pub session_name: Option<String>,
pub rpc_endpoint: String,
pub task_id: Option<String>,
pub grant: SessionGrant,
}
impl SessionInfo {
pub(crate) fn from_grant(grant: SessionGrant) -> Self {
Self {
rpc_endpoint: grant.rpc_url_with_token(),
session_id: grant.session_id,
session_name: grant
.session_name
.as_ref()
.map(|name| name.as_str().to_owned()),
task_id: grant.task_id.clone(),
grant,
}
}
}
impl fmt::Debug for SessionInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
session_id,
session_name,
rpc_endpoint,
task_id,
grant,
} = self;
f.debug_struct("SessionInfo")
.field("session_id", session_id)
.field("session_name", session_name)
.field("rpc_endpoint", &without_query(rpc_endpoint))
.field("task_id", task_id)
.field("grant", grant)
.finish()
}
}
#[derive(Debug, Clone, Builder)]
pub struct StartSessionParams {
#[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
pub url: String,
pub api_key: String,
#[builder(default)]
pub extra_headers: HeaderMap,
pub create: CreateBacktestSessionRequest,
#[builder(default)]
pub parent_cancel: CancellationToken,
#[builder(default)]
pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
}
#[derive(Debug, Default)]
pub struct SubscriptionDiagnostics {
reconnects: AtomicU64,
}
impl SubscriptionDiagnostics {
pub(crate) fn record_reconnect(&self) {
self.reconnects.fetch_add(1, Ordering::Relaxed);
}
pub fn reconnects(&self) -> u64 {
self.reconnects.load(Ordering::Relaxed)
}
}
pub(crate) struct ReconnectBudget {
attempts: u32,
started_at: std::time::Instant,
current_backoff: Duration,
}
impl ReconnectBudget {
pub fn new() -> Self {
Self {
attempts: 0,
started_at: std::time::Instant::now(),
current_backoff: RECONNECT_INITIAL_BACKOFF,
}
}
pub fn reset(&mut self) {
self.attempts = 0;
self.started_at = std::time::Instant::now();
self.current_backoff = RECONNECT_INITIAL_BACKOFF;
}
pub fn attempt(&self) -> u32 {
self.attempts
}
pub fn discount_parked(&mut self, parked: Duration) {
self.started_at += parked;
}
pub fn next_backoff(&mut self) -> Option<Duration> {
if self.attempts >= RECONNECT_MAX_ATTEMPTS
|| self.started_at.elapsed() >= RECONNECT_MAX_TOTAL
{
return None;
}
self.attempts += 1;
let backoff = with_jitter(self.current_backoff);
self.current_backoff = std::cmp::min(
RECONNECT_MAX_BACKOFF,
Duration::from_secs_f64(
self.current_backoff.as_secs_f64() * RECONNECT_BACKOFF_MULTIPLIER,
),
);
Some(backoff)
}
}
#[doc(hidden)]
pub struct ReconnectCoordinator {
streaming: AtomicUsize,
drained: Notify,
handshake: Arc<Semaphore>,
}
impl Default for ReconnectCoordinator {
fn default() -> Self {
Self::new()
}
}
impl ReconnectCoordinator {
pub fn new() -> Self {
Self {
streaming: AtomicUsize::new(0),
drained: Notify::new(),
handshake: Arc::new(Semaphore::new(1)),
}
}
pub fn enter(self: &Arc<Self>) -> StreamingGuard {
self.streaming.fetch_add(1, Ordering::SeqCst);
StreamingGuard(Arc::clone(self))
}
pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
loop {
loop {
let drained = self.drained.notified();
if self.streaming.load(Ordering::SeqCst) == 0 {
break;
}
tokio::select! {
biased;
() = cancel.cancelled() => return None,
() = drained => {}
}
}
let permit = tokio::select! {
biased;
() = cancel.cancelled() => return None,
p = Arc::clone(&self.handshake).acquire_owned() => p.ok()?,
};
if self.streaming.load(Ordering::SeqCst) == 0 {
return Some(permit);
}
}
}
}
#[doc(hidden)]
pub struct StreamingGuard(Arc<ReconnectCoordinator>);
impl Drop for StreamingGuard {
fn drop(&mut self) {
self.0.streaming.fetch_sub(1, Ordering::SeqCst);
self.0.drained.notify_waiters();
}
}
fn with_jitter(d: Duration) -> Duration {
let jitter = rand::rng().random_range(-RECONNECT_JITTER..RECONNECT_JITTER);
let secs = (d.as_secs_f64() * (1.0 + jitter)).max(0.0);
Duration::from_secs_f64(secs)
}
pub(crate) async fn cancellable_sleep(delay: Duration, cancel: &CancellationToken) -> bool {
tokio::select! {
() = tokio::time::sleep(delay) => true,
() = cancel.cancelled() => false,
}
}
pub(crate) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
pub(super) fn managed_user_agent() -> String {
crate::client::user_agent(ClientProduct::Sdk, None, ClientSurface::Managed)
}
pub(super) async fn send_request(ws: &mut Ws, req: &BacktestRequest) -> Result<(), String> {
let text = serde_json::to_string(req).map_err(|e| format!("serialize: {}", err_chain(&e)))?;
ws.send(Message::Text(text))
.await
.map_err(|e| format!("send: {}", err_chain(&e)))
}
pub(super) enum MessageLoopExit {
SessionEnded,
Cancelled,
ConnectionLost(String),
Terminal,
}
pub(super) fn publish_status(
status_tx: &watch::Sender<ConnectionStatus>,
status: ConnectionStatus,
) {
status_tx.send_if_modified(|current| {
if *current == status {
false
} else {
*current = status;
true
}
});
}
pub(super) async fn graceful_close(ws: &mut Ws) {
drop(
tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, async {
drop(send_request(ws, &BacktestRequest::CloseBacktestSession).await);
drop(ws.close(None).await);
})
.await,
);
}
pub(super) enum InboundFrame {
Text(String),
Ignore,
Lost(String),
}
pub(super) fn classify_inbound(msg: Option<Result<Message, WsError>>) -> InboundFrame {
match msg {
Some(Ok(Message::Text(t))) => InboundFrame::Text(t),
Some(Ok(Message::Binary(b))) => match String::from_utf8(b) {
Ok(t) => InboundFrame::Text(t),
Err(_) => InboundFrame::Ignore,
},
Some(Ok(Message::Pong(_) | Message::Ping(_) | Message::Frame(_))) => InboundFrame::Ignore,
Some(Ok(Message::Close(frame))) => InboundFrame::Lost(format!("remote close: {frame:?}")),
Some(Err(e)) => InboundFrame::Lost(format!("ws read: {}", err_chain(&e))),
None => InboundFrame::Lost("ws stream ended".into()),
}
}
pub(super) async fn send_keepalive_ping(ws: &mut Ws, last_inbound: Instant) -> Option<String> {
if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
return Some(format!("no traffic for {:?}", last_inbound.elapsed()));
}
if let Err(e) = ws.send(Message::Ping(vec![])).await {
return Some(format!("ping send: {}", err_chain(&e)));
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn budget_exhausts_after_max_attempts() {
let mut b = ReconnectBudget::new();
for _ in 0..RECONNECT_MAX_ATTEMPTS {
assert!(b.next_backoff().is_some());
}
assert!(b.next_backoff().is_none());
}
#[test]
fn budget_reset_restores_full_budget() {
let mut b = ReconnectBudget::new();
b.next_backoff();
b.next_backoff();
b.reset();
assert_eq!(b.attempt(), 0);
}
#[test]
fn streaming_guard_balances_the_count() {
let coord = Arc::new(ReconnectCoordinator::new());
assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
let g = coord.enter();
assert_eq!(coord.streaming.load(Ordering::SeqCst), 1);
drop(g);
assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn reconnect_slot_available_when_link_is_quiet() {
let coord = Arc::new(ReconnectCoordinator::new());
let cancel = CancellationToken::new();
assert!(coord.reconnect_slot(&cancel).await.is_some());
}
#[tokio::test]
async fn reconnect_slot_unparks_when_last_sibling_leaves() {
let coord = Arc::new(ReconnectCoordinator::new());
let cancel = CancellationToken::new();
let guard = coord.enter();
let waiter = tokio::spawn({
let coord = Arc::clone(&coord);
let cancel = cancel.clone();
async move { coord.reconnect_slot(&cancel).await.is_some() }
});
tokio::task::yield_now().await;
assert!(!waiter.is_finished());
drop(guard); assert!(waiter.await.unwrap());
}
#[tokio::test]
async fn reconnect_slot_returns_none_on_cancel_while_parked() {
let coord = Arc::new(ReconnectCoordinator::new());
let _guard = coord.enter(); let cancel = CancellationToken::new();
cancel.cancel();
assert!(coord.reconnect_slot(&cancel).await.is_none());
}
#[test]
fn discount_parked_does_not_consume_the_budget() {
let mut b = ReconnectBudget::new();
b.discount_parked(2 * RECONNECT_MAX_TOTAL);
for _ in 0..RECONNECT_MAX_ATTEMPTS {
assert!(b.next_backoff().is_some());
}
}
}