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
121pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
129
130#[derive(Clone, Debug, PartialEq, Eq)]
132pub enum ConnectionStatus {
133 Up,
135 Down,
137 Ended,
139 Failed(ConnectionFailure),
141}
142
143#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
145pub enum ConnectionFailure {
146 #[error("{0}")]
148 RetriesExhausted(String),
149 #[error("the session's endpoint rejected the token")]
151 TokenRejected,
152 #[error("the session ended; the server no longer tracks it")]
154 SessionEnded,
155 #[error("{0}")]
157 Refused(String),
158}
159
160#[derive(Clone)]
162#[non_exhaustive]
163pub struct SessionInfo {
164 #[allow(missing_docs)]
165 pub session_id: SessionId,
166 pub session_name: Option<String>,
168 pub rpc_endpoint: String,
172 pub task_id: Option<String>,
174 pub grant: SessionGrant,
176}
177
178impl SessionInfo {
179 pub(crate) fn from_grant(grant: SessionGrant) -> Self {
180 Self {
181 rpc_endpoint: grant.rpc_url_with_token(),
182 session_id: grant.session_id,
183 session_name: grant
184 .session_name
185 .as_ref()
186 .map(|name| name.as_str().to_owned()),
187 task_id: grant.task_id.clone(),
188 grant,
189 }
190 }
191}
192
193impl fmt::Debug for SessionInfo {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 let Self {
196 session_id,
197 session_name,
198 rpc_endpoint,
199 task_id,
200 grant,
201 } = self;
202 f.debug_struct("SessionInfo")
203 .field("session_id", session_id)
204 .field("session_name", session_name)
205 .field("rpc_endpoint", &without_query(rpc_endpoint))
206 .field("task_id", task_id)
207 .field("grant", grant)
208 .finish()
209 }
210}
211
212#[derive(Debug, Clone, Builder)]
219pub struct StartSessionParams {
220 #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
224 pub url: String,
225 pub api_key: String,
227 #[builder(default)]
229 pub extra_headers: HeaderMap,
230 pub create: CreateBacktestSessionRequest,
233 #[builder(default)]
236 pub parent_cancel: CancellationToken,
237 #[builder(default)]
240 pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
241}
242
243#[derive(Debug, Default)]
246pub struct SubscriptionDiagnostics {
247 reconnects: AtomicU64,
249}
250
251impl SubscriptionDiagnostics {
252 pub(crate) fn record_reconnect(&self) {
253 self.reconnects.fetch_add(1, Ordering::Relaxed);
254 }
255
256 pub fn reconnects(&self) -> u64 {
259 self.reconnects.load(Ordering::Relaxed)
260 }
261}
262
263pub(crate) struct ReconnectBudget {
265 attempts: u32,
266 started_at: std::time::Instant,
267 current_backoff: Duration,
268}
269
270impl ReconnectBudget {
271 pub fn new() -> Self {
272 Self {
273 attempts: 0,
274 started_at: std::time::Instant::now(),
275 current_backoff: RECONNECT_INITIAL_BACKOFF,
276 }
277 }
278
279 pub fn reset(&mut self) {
280 self.attempts = 0;
281 self.started_at = std::time::Instant::now();
282 self.current_backoff = RECONNECT_INITIAL_BACKOFF;
283 }
284
285 pub fn attempt(&self) -> u32 {
286 self.attempts
287 }
288
289 pub fn discount_parked(&mut self, parked: Duration) {
296 self.started_at += parked;
297 }
298
299 pub fn next_backoff(&mut self) -> Option<Duration> {
302 if self.attempts >= RECONNECT_MAX_ATTEMPTS
303 || self.started_at.elapsed() >= RECONNECT_MAX_TOTAL
304 {
305 return None;
306 }
307 self.attempts += 1;
308 let backoff = with_jitter(self.current_backoff);
309 self.current_backoff = std::cmp::min(
310 RECONNECT_MAX_BACKOFF,
311 Duration::from_secs_f64(
312 self.current_backoff.as_secs_f64() * RECONNECT_BACKOFF_MULTIPLIER,
313 ),
314 );
315 Some(backoff)
316 }
317}
318
319#[doc(hidden)]
331pub struct ReconnectCoordinator {
332 streaming: AtomicUsize,
335 drained: Notify,
337 handshake: Arc<Semaphore>,
340}
341
342impl Default for ReconnectCoordinator {
343 fn default() -> Self {
344 Self::new()
345 }
346}
347
348impl ReconnectCoordinator {
349 pub fn new() -> Self {
350 Self {
351 streaming: AtomicUsize::new(0),
352 drained: Notify::new(),
353 handshake: Arc::new(Semaphore::new(1)),
354 }
355 }
356
357 pub fn enter(self: &Arc<Self>) -> StreamingGuard {
362 self.streaming.fetch_add(1, Ordering::SeqCst);
363 StreamingGuard(self.clone())
364 }
365
366 pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
372 loop {
373 loop {
376 let drained = self.drained.notified();
377 if self.streaming.load(Ordering::SeqCst) == 0 {
378 break;
379 }
380 tokio::select! {
381 biased;
382 _ = cancel.cancelled() => return None,
383 _ = drained => {}
384 }
385 }
386 let permit = tokio::select! {
387 biased;
388 _ = cancel.cancelled() => return None,
389 p = self.handshake.clone().acquire_owned() => p.ok()?,
390 };
391 if self.streaming.load(Ordering::SeqCst) == 0 {
395 return Some(permit);
396 }
397 }
398 }
399}
400
401#[doc(hidden)]
404pub struct StreamingGuard(Arc<ReconnectCoordinator>);
405
406impl Drop for StreamingGuard {
407 fn drop(&mut self) {
408 self.0.streaming.fetch_sub(1, Ordering::SeqCst);
409 self.0.drained.notify_waiters();
410 }
411}
412
413fn with_jitter(d: Duration) -> Duration {
414 let jitter = rand::rng().random_range(-RECONNECT_JITTER..RECONNECT_JITTER);
415 let secs = (d.as_secs_f64() * (1.0 + jitter)).max(0.0);
416 Duration::from_secs_f64(secs)
417}
418
419pub(crate) async fn cancellable_sleep(delay: Duration, cancel: &CancellationToken) -> bool {
422 tokio::select! {
423 _ = tokio::time::sleep(delay) => true,
424 _ = cancel.cancelled() => false,
425 }
426}
427
428pub(crate) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
430
431pub(super) fn managed_user_agent() -> String {
432 crate::client::user_agent(ClientProduct::Sdk, None, ClientSurface::Managed)
433}
434
435pub(super) async fn send_request(ws: &mut Ws, req: &BacktestRequest) -> Result<(), String> {
437 let text = serde_json::to_string(req).map_err(|e| format!("serialize: {}", err_chain(&e)))?;
438 ws.send(Message::Text(text))
439 .await
440 .map_err(|e| format!("send: {}", err_chain(&e)))
441}
442
443pub(super) enum MessageLoopExit {
444 SessionEnded,
446 Cancelled,
449 ConnectionLost(String),
451 Terminal,
452}
453
454pub(super) fn publish_status(
456 status_tx: &watch::Sender<ConnectionStatus>,
457 status: ConnectionStatus,
458) {
459 status_tx.send_if_modified(|current| {
460 if *current == status {
461 false
462 } else {
463 *current = status;
464 true
465 }
466 });
467}
468
469pub(super) async fn graceful_close(ws: &mut Ws) {
474 let _ = tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, async {
475 let _ = send_request(ws, &BacktestRequest::CloseBacktestSession).await;
476 let _ = ws.close(None).await;
477 })
478 .await;
479}
480
481pub(super) enum InboundFrame {
483 Text(String),
485 Ignore,
487 Lost(String),
489}
490
491pub(super) fn classify_inbound(msg: Option<Result<Message, WsError>>) -> InboundFrame {
493 match msg {
494 Some(Ok(Message::Text(t))) => InboundFrame::Text(t),
495 Some(Ok(Message::Binary(b))) => match String::from_utf8(b) {
496 Ok(t) => InboundFrame::Text(t),
497 Err(_) => InboundFrame::Ignore,
498 },
499 Some(Ok(Message::Pong(_) | Message::Ping(_) | Message::Frame(_))) => InboundFrame::Ignore,
500 Some(Ok(Message::Close(frame))) => InboundFrame::Lost(format!("remote close: {frame:?}")),
501 Some(Err(e)) => InboundFrame::Lost(format!("ws read: {}", err_chain(&e))),
502 None => InboundFrame::Lost("ws stream ended".into()),
503 }
504}
505
506pub(super) async fn send_keepalive_ping(ws: &mut Ws, last_inbound: Instant) -> Option<String> {
510 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
511 return Some(format!("no traffic for {:?}", last_inbound.elapsed()));
512 }
513 if let Err(e) = ws.send(Message::Ping(vec![])).await {
514 return Some(format!("ping send: {}", err_chain(&e)));
515 }
516 None
517}
518
519#[cfg(test)]
520mod tests {
521 use super::*;
522
523 #[test]
524 fn budget_exhausts_after_max_attempts() {
525 let mut b = ReconnectBudget::new();
526 for _ in 0..RECONNECT_MAX_ATTEMPTS {
527 assert!(b.next_backoff().is_some());
528 }
529 assert!(b.next_backoff().is_none());
530 }
531
532 #[test]
533 fn budget_reset_restores_full_budget() {
534 let mut b = ReconnectBudget::new();
535 b.next_backoff();
536 b.next_backoff();
537 b.reset();
538 assert_eq!(b.attempt(), 0);
539 }
540
541 #[test]
542 fn streaming_guard_balances_the_count() {
543 let coord = Arc::new(ReconnectCoordinator::new());
544 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
545 let g = coord.enter();
546 assert_eq!(coord.streaming.load(Ordering::SeqCst), 1);
547 drop(g);
548 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
549 }
550
551 #[tokio::test]
552 async fn reconnect_slot_available_when_link_is_quiet() {
553 let coord = Arc::new(ReconnectCoordinator::new());
554 let cancel = CancellationToken::new();
555 assert!(coord.reconnect_slot(&cancel).await.is_some());
556 }
557
558 #[tokio::test]
559 async fn reconnect_slot_unparks_when_last_sibling_leaves() {
560 let coord = Arc::new(ReconnectCoordinator::new());
561 let cancel = CancellationToken::new();
562 let guard = coord.enter(); let waiter = tokio::spawn({
565 let coord = coord.clone();
566 let cancel = cancel.clone();
567 async move { coord.reconnect_slot(&cancel).await.is_some() }
568 });
569
570 tokio::task::yield_now().await;
572 assert!(!waiter.is_finished());
573
574 drop(guard); assert!(waiter.await.unwrap());
576 }
577
578 #[tokio::test]
579 async fn reconnect_slot_returns_none_on_cancel_while_parked() {
580 let coord = Arc::new(ReconnectCoordinator::new());
581 let _guard = coord.enter(); let cancel = CancellationToken::new();
583 cancel.cancel();
584 assert!(coord.reconnect_slot(&cancel).await.is_none());
585 }
586
587 #[test]
588 fn discount_parked_does_not_consume_the_budget() {
589 let mut b = ReconnectBudget::new();
590 b.discount_parked(2 * RECONNECT_MAX_TOTAL);
592 for _ in 0..RECONNECT_MAX_ATTEMPTS {
593 assert!(b.next_backoff().is_some());
594 }
595 }
596}