simulator_client/managed/
mod.rs1use std::{
27 fmt,
28 sync::{
29 Arc,
30 atomic::{AtomicU64, AtomicUsize, Ordering},
31 },
32 time::{Duration, Instant},
33};
34
35use bon::Builder;
36use futures::SinkExt;
37use http::HeaderMap;
38use rand::RngExt;
39use simulator_api::{
40 BacktestRequest, CreateBacktestSessionRequest, SessionId,
41 client_identity::{ClientProduct, ClientSurface},
42 session_endpoint::SessionGrant,
43};
44use tokio::{
45 net::TcpStream,
46 sync::{Notify, OwnedSemaphorePermit, Semaphore, watch},
47};
48use tokio_tungstenite::{
49 MaybeTlsStream, WebSocketStream,
50 tungstenite::{Error as WsError, Message},
51};
52use tokio_util::sync::CancellationToken;
53
54use crate::{endpoint::without_query, error::err_chain, urls::backtest_ws_url};
55
56mod control;
57pub(crate) mod grant;
58mod parallel;
59mod session;
60mod subscription;
61
62pub use control::ControlEvent;
63pub use parallel::{ManagedParallelSession, ParallelSubSession};
64pub use session::{CreateError, ManagedBacktestSession, ManagedEvent, ManagedSessionError};
65pub use subscription::{
66 SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
67 spawn_action_subscription_manager, spawn_diagnostic_subscription_manager,
68 spawn_replacement_subscription_manager, spawn_transaction_subscription_manager,
69};
70
71#[doc(hidden)]
73pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
74
75#[doc(hidden)]
77pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
78
79#[doc(hidden)]
81pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
82
83#[doc(hidden)]
86pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
87
88#[doc(hidden)]
91pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
92
93#[doc(hidden)]
96pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
97#[doc(hidden)]
99pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
100#[doc(hidden)]
102pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
103#[doc(hidden)]
105pub const RECONNECT_JITTER: f64 = 0.2;
106pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
109pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
111
112#[doc(hidden)]
115pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
116
117#[doc(hidden)]
119pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
120
121#[expect(
129 clippy::cast_possible_truncation,
130 reason = "RECONNECT_MAX_TOTAL is 300s, well within u16"
131)]
132pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
133
134#[derive(Clone, Debug, PartialEq, Eq)]
136pub enum ConnectionStatus {
137 Up,
139 Down,
141 Ended,
143 Failed(ConnectionFailure),
145}
146
147#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
149pub enum ConnectionFailure {
150 #[error("{0}")]
152 RetriesExhausted(String),
153 #[error("the session's endpoint rejected the token")]
155 TokenRejected,
156 #[error("the session ended; the server no longer tracks it")]
158 SessionEnded,
159 #[error("{0}")]
161 Refused(String),
162}
163
164#[derive(Clone)]
166#[non_exhaustive]
167pub struct SessionInfo {
168 #[expect(missing_docs, reason = "self-explanatory session identifier")]
169 pub session_id: SessionId,
170 pub session_name: Option<String>,
172 pub rpc_endpoint: String,
176 pub task_id: Option<String>,
178 pub grant: SessionGrant,
180}
181
182impl SessionInfo {
183 pub(crate) fn from_grant(grant: SessionGrant) -> Self {
184 Self {
185 rpc_endpoint: grant.rpc_url_with_token(),
186 session_id: grant.session_id,
187 session_name: grant
188 .session_name
189 .as_ref()
190 .map(|name| name.as_str().to_owned()),
191 task_id: grant.task_id.clone(),
192 grant,
193 }
194 }
195}
196
197impl fmt::Debug for SessionInfo {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 let Self {
200 session_id,
201 session_name,
202 rpc_endpoint,
203 task_id,
204 grant,
205 } = self;
206 f.debug_struct("SessionInfo")
207 .field("session_id", session_id)
208 .field("session_name", session_name)
209 .field("rpc_endpoint", &without_query(rpc_endpoint))
210 .field("task_id", task_id)
211 .field("grant", grant)
212 .finish()
213 }
214}
215
216#[derive(Debug, Clone, Builder)]
223pub struct StartSessionParams {
224 #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
228 pub url: String,
229 pub api_key: String,
231 #[builder(default)]
233 pub extra_headers: HeaderMap,
234 pub create: CreateBacktestSessionRequest,
237 #[builder(default)]
240 pub parent_cancel: CancellationToken,
241 #[builder(default)]
244 pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
245}
246
247#[derive(Debug, Default)]
250pub struct SubscriptionDiagnostics {
251 reconnects: AtomicU64,
253}
254
255impl SubscriptionDiagnostics {
256 pub(crate) fn record_reconnect(&self) {
257 self.reconnects.fetch_add(1, Ordering::Relaxed);
258 }
259
260 pub fn reconnects(&self) -> u64 {
263 self.reconnects.load(Ordering::Relaxed)
264 }
265}
266
267pub(crate) struct ReconnectBudget {
269 attempts: u32,
270 started_at: std::time::Instant,
271 current_backoff: Duration,
272}
273
274impl ReconnectBudget {
275 pub fn new() -> Self {
276 Self {
277 attempts: 0,
278 started_at: std::time::Instant::now(),
279 current_backoff: RECONNECT_INITIAL_BACKOFF,
280 }
281 }
282
283 pub fn reset(&mut self) {
284 self.attempts = 0;
285 self.started_at = std::time::Instant::now();
286 self.current_backoff = RECONNECT_INITIAL_BACKOFF;
287 }
288
289 pub fn attempt(&self) -> u32 {
290 self.attempts
291 }
292
293 pub fn discount_parked(&mut self, parked: Duration) {
300 self.started_at += parked;
301 }
302
303 pub fn next_backoff(&mut self) -> Option<Duration> {
306 if self.attempts >= RECONNECT_MAX_ATTEMPTS
307 || self.started_at.elapsed() >= RECONNECT_MAX_TOTAL
308 {
309 return None;
310 }
311 self.attempts += 1;
312 let backoff = with_jitter(self.current_backoff);
313 self.current_backoff = std::cmp::min(
314 RECONNECT_MAX_BACKOFF,
315 Duration::from_secs_f64(
316 self.current_backoff.as_secs_f64() * RECONNECT_BACKOFF_MULTIPLIER,
317 ),
318 );
319 Some(backoff)
320 }
321}
322
323#[doc(hidden)]
335pub struct ReconnectCoordinator {
336 streaming: AtomicUsize,
339 drained: Notify,
341 handshake: Arc<Semaphore>,
344}
345
346impl Default for ReconnectCoordinator {
347 fn default() -> Self {
348 Self::new()
349 }
350}
351
352impl ReconnectCoordinator {
353 pub fn new() -> Self {
354 Self {
355 streaming: AtomicUsize::new(0),
356 drained: Notify::new(),
357 handshake: Arc::new(Semaphore::new(1)),
358 }
359 }
360
361 pub fn enter(self: &Arc<Self>) -> StreamingGuard {
366 self.streaming.fetch_add(1, Ordering::SeqCst);
367 StreamingGuard(Arc::clone(self))
368 }
369
370 pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
376 loop {
377 loop {
380 let drained = self.drained.notified();
381 if self.streaming.load(Ordering::SeqCst) == 0 {
382 break;
383 }
384 tokio::select! {
385 biased;
386 () = cancel.cancelled() => return None,
387 () = drained => {}
388 }
389 }
390 let permit = tokio::select! {
391 biased;
392 () = cancel.cancelled() => return None,
393 p = Arc::clone(&self.handshake).acquire_owned() => p.ok()?,
394 };
395 if self.streaming.load(Ordering::SeqCst) == 0 {
399 return Some(permit);
400 }
401 }
402 }
403}
404
405#[doc(hidden)]
408pub struct StreamingGuard(Arc<ReconnectCoordinator>);
409
410impl Drop for StreamingGuard {
411 fn drop(&mut self) {
412 self.0.streaming.fetch_sub(1, Ordering::SeqCst);
413 self.0.drained.notify_waiters();
414 }
415}
416
417fn with_jitter(d: Duration) -> Duration {
418 let jitter = rand::rng().random_range(-RECONNECT_JITTER..RECONNECT_JITTER);
419 let secs = (d.as_secs_f64() * (1.0 + jitter)).max(0.0);
420 Duration::from_secs_f64(secs)
421}
422
423pub(crate) async fn cancellable_sleep(delay: Duration, cancel: &CancellationToken) -> bool {
426 tokio::select! {
427 () = tokio::time::sleep(delay) => true,
428 () = cancel.cancelled() => false,
429 }
430}
431
432pub(crate) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
434
435pub(super) fn managed_user_agent() -> String {
436 crate::client::user_agent(ClientProduct::Sdk, None, ClientSurface::Managed)
437}
438
439pub(super) async fn send_request(ws: &mut Ws, req: &BacktestRequest) -> Result<(), String> {
441 let text = serde_json::to_string(req).map_err(|e| format!("serialize: {}", err_chain(&e)))?;
442 ws.send(Message::Text(text))
443 .await
444 .map_err(|e| format!("send: {}", err_chain(&e)))
445}
446
447pub(super) enum MessageLoopExit {
448 SessionEnded,
450 Cancelled,
453 ConnectionLost(String),
455 Terminal,
456}
457
458pub(super) fn publish_status(
460 status_tx: &watch::Sender<ConnectionStatus>,
461 status: ConnectionStatus,
462) {
463 status_tx.send_if_modified(|current| {
464 if *current == status {
465 false
466 } else {
467 *current = status;
468 true
469 }
470 });
471}
472
473pub(super) async fn graceful_close(ws: &mut Ws) {
478 drop(
479 tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, async {
480 drop(send_request(ws, &BacktestRequest::CloseBacktestSession).await);
481 drop(ws.close(None).await);
482 })
483 .await,
484 );
485}
486
487pub(super) enum InboundFrame {
489 Text(String),
491 Ignore,
493 Lost(String),
495}
496
497pub(super) fn classify_inbound(msg: Option<Result<Message, WsError>>) -> InboundFrame {
499 match msg {
500 Some(Ok(Message::Text(t))) => InboundFrame::Text(t),
501 Some(Ok(Message::Binary(b))) => match String::from_utf8(b) {
502 Ok(t) => InboundFrame::Text(t),
503 Err(_) => InboundFrame::Ignore,
504 },
505 Some(Ok(Message::Pong(_) | Message::Ping(_) | Message::Frame(_))) => InboundFrame::Ignore,
506 Some(Ok(Message::Close(frame))) => InboundFrame::Lost(format!("remote close: {frame:?}")),
507 Some(Err(e)) => InboundFrame::Lost(format!("ws read: {}", err_chain(&e))),
508 None => InboundFrame::Lost("ws stream ended".into()),
509 }
510}
511
512pub(super) async fn send_keepalive_ping(ws: &mut Ws, last_inbound: Instant) -> Option<String> {
516 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
517 return Some(format!("no traffic for {:?}", last_inbound.elapsed()));
518 }
519 if let Err(e) = ws.send(Message::Ping(vec![])).await {
520 return Some(format!("ping send: {}", err_chain(&e)));
521 }
522 None
523}
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528
529 #[test]
530 fn budget_exhausts_after_max_attempts() {
531 let mut b = ReconnectBudget::new();
532 for _ in 0..RECONNECT_MAX_ATTEMPTS {
533 assert!(b.next_backoff().is_some());
534 }
535 assert!(b.next_backoff().is_none());
536 }
537
538 #[test]
539 fn budget_reset_restores_full_budget() {
540 let mut b = ReconnectBudget::new();
541 b.next_backoff();
542 b.next_backoff();
543 b.reset();
544 assert_eq!(b.attempt(), 0);
545 }
546
547 #[test]
548 fn streaming_guard_balances_the_count() {
549 let coord = Arc::new(ReconnectCoordinator::new());
550 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
551 let g = coord.enter();
552 assert_eq!(coord.streaming.load(Ordering::SeqCst), 1);
553 drop(g);
554 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
555 }
556
557 #[tokio::test]
558 async fn reconnect_slot_available_when_link_is_quiet() {
559 let coord = Arc::new(ReconnectCoordinator::new());
560 let cancel = CancellationToken::new();
561 assert!(coord.reconnect_slot(&cancel).await.is_some());
562 }
563
564 #[tokio::test]
565 async fn reconnect_slot_unparks_when_last_sibling_leaves() {
566 let coord = Arc::new(ReconnectCoordinator::new());
567 let cancel = CancellationToken::new();
568 let guard = coord.enter(); let waiter = tokio::spawn({
571 let coord = Arc::clone(&coord);
572 let cancel = cancel.clone();
573 async move { coord.reconnect_slot(&cancel).await.is_some() }
574 });
575
576 tokio::task::yield_now().await;
578 assert!(!waiter.is_finished());
579
580 drop(guard); assert!(waiter.await.unwrap());
582 }
583
584 #[tokio::test]
585 async fn reconnect_slot_returns_none_on_cancel_while_parked() {
586 let coord = Arc::new(ReconnectCoordinator::new());
587 let _guard = coord.enter(); let cancel = CancellationToken::new();
589 cancel.cancel();
590 assert!(coord.reconnect_slot(&cancel).await.is_none());
591 }
592
593 #[test]
594 fn discount_parked_does_not_consume_the_budget() {
595 let mut b = ReconnectBudget::new();
596 b.discount_parked(2 * RECONNECT_MAX_TOTAL);
598 for _ in 0..RECONNECT_MAX_ATTEMPTS {
599 assert!(b.next_backoff().is_some());
600 }
601 }
602}