1use std::{
26 future::Future,
27 sync::{
28 Arc,
29 atomic::{AtomicU64, AtomicUsize, Ordering},
30 },
31 time::{Duration, Instant},
32};
33
34use bon::Builder;
35use futures::SinkExt;
36use http::{HeaderMap, StatusCode};
37use rand::RngExt;
38use simulator_api::{
39 BacktestError, BacktestRequest, CreateBacktestSessionRequest, SessionId,
40 client_identity::{ClientProduct, ClientSurface},
41};
42use tokio::{
43 net::TcpStream,
44 sync::{Notify, OwnedSemaphorePermit, Semaphore, watch},
45};
46use tokio_tungstenite::{
47 MaybeTlsStream, WebSocketStream, connect_async,
48 tungstenite::{Error as WsError, Message, client::IntoClientRequest, http::HeaderValue},
49};
50use tokio_util::sync::CancellationToken;
51use tracing::warn;
52
53use crate::{error::err_chain, urls::backtest_ws_url};
54
55mod control;
56mod parallel;
57mod session;
58mod subscription;
59
60pub use control::{ControlEvent, ControlHandle, spawn_control_manager};
61pub use parallel::{ManagedParallelSession, ParallelSubSession};
62pub use session::{CreateError, ManagedBacktestSession, ManagedEvent, ManagedSessionError};
63pub use subscription::{
64 SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
65 spawn_action_subscription_manager, spawn_diagnostic_subscription_manager,
66 spawn_replacement_subscription_manager, spawn_transaction_subscription_manager,
67};
68
69#[doc(hidden)]
71pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
72
73#[doc(hidden)]
79pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
80
81#[doc(hidden)]
83pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
84
85#[doc(hidden)]
88pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
89
90#[doc(hidden)]
93pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
94
95#[doc(hidden)]
98pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
99#[doc(hidden)]
101pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
102#[doc(hidden)]
104pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
105#[doc(hidden)]
107pub const RECONNECT_JITTER: f64 = 0.2;
108pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
111pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
113
114#[doc(hidden)]
117pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
118
119#[doc(hidden)]
121pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
122
123pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
131
132#[derive(Clone, Debug, PartialEq, Eq)]
134pub enum ConnectionStatus {
135 Up,
137 Down,
139 Failed(String),
142}
143
144#[derive(Clone, Debug)]
146pub struct SessionInfo {
147 #[allow(missing_docs)]
148 pub session_id: SessionId,
149 pub session_name: Option<String>,
151 pub rpc_endpoint: String,
155 pub task_id: Option<String>,
157}
158
159#[derive(Debug, Clone, Builder)]
166pub struct StartSessionParams {
167 #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
171 pub url: String,
172 pub api_key: String,
174 #[builder(default)]
176 pub extra_headers: HeaderMap,
177 pub create: CreateBacktestSessionRequest,
180 #[builder(default)]
183 pub parent_cancel: CancellationToken,
184 #[builder(default)]
187 pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
188}
189
190#[derive(Debug, Default)]
193pub struct SubscriptionDiagnostics {
194 reconnects: AtomicU64,
196}
197
198impl SubscriptionDiagnostics {
199 pub(crate) fn record_reconnect(&self) {
200 self.reconnects.fetch_add(1, Ordering::Relaxed);
201 }
202
203 pub fn reconnects(&self) -> u64 {
206 self.reconnects.load(Ordering::Relaxed)
207 }
208}
209
210pub(crate) struct ReconnectBudget {
212 attempts: u32,
213 started_at: std::time::Instant,
214 current_backoff: Duration,
215}
216
217impl ReconnectBudget {
218 pub fn new() -> Self {
219 Self {
220 attempts: 0,
221 started_at: std::time::Instant::now(),
222 current_backoff: RECONNECT_INITIAL_BACKOFF,
223 }
224 }
225
226 pub fn reset(&mut self) {
227 self.attempts = 0;
228 self.started_at = std::time::Instant::now();
229 self.current_backoff = RECONNECT_INITIAL_BACKOFF;
230 }
231
232 pub fn attempt(&self) -> u32 {
233 self.attempts
234 }
235
236 pub fn discount_parked(&mut self, parked: Duration) {
243 self.started_at += parked;
244 }
245
246 pub fn next_backoff(&mut self) -> Option<Duration> {
249 if self.attempts >= RECONNECT_MAX_ATTEMPTS
250 || self.started_at.elapsed() >= RECONNECT_MAX_TOTAL
251 {
252 return None;
253 }
254 self.attempts += 1;
255 let backoff = with_jitter(self.current_backoff);
256 self.current_backoff = std::cmp::min(
257 RECONNECT_MAX_BACKOFF,
258 Duration::from_secs_f64(
259 self.current_backoff.as_secs_f64() * RECONNECT_BACKOFF_MULTIPLIER,
260 ),
261 );
262 Some(backoff)
263 }
264}
265
266#[doc(hidden)]
278pub struct ReconnectCoordinator {
279 streaming: AtomicUsize,
282 drained: Notify,
284 handshake: Arc<Semaphore>,
287}
288
289impl Default for ReconnectCoordinator {
290 fn default() -> Self {
291 Self::new()
292 }
293}
294
295impl ReconnectCoordinator {
296 pub fn new() -> Self {
297 Self {
298 streaming: AtomicUsize::new(0),
299 drained: Notify::new(),
300 handshake: Arc::new(Semaphore::new(1)),
301 }
302 }
303
304 pub fn enter(self: &Arc<Self>) -> StreamingGuard {
309 self.streaming.fetch_add(1, Ordering::SeqCst);
310 StreamingGuard(self.clone())
311 }
312
313 pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
319 loop {
320 loop {
323 let drained = self.drained.notified();
324 if self.streaming.load(Ordering::SeqCst) == 0 {
325 break;
326 }
327 tokio::select! {
328 biased;
329 _ = cancel.cancelled() => return None,
330 _ = drained => {}
331 }
332 }
333 let permit = tokio::select! {
334 biased;
335 _ = cancel.cancelled() => return None,
336 p = self.handshake.clone().acquire_owned() => p.ok()?,
337 };
338 if self.streaming.load(Ordering::SeqCst) == 0 {
342 return Some(permit);
343 }
344 }
345 }
346}
347
348#[doc(hidden)]
351pub struct StreamingGuard(Arc<ReconnectCoordinator>);
352
353impl Drop for StreamingGuard {
354 fn drop(&mut self) {
355 self.0.streaming.fetch_sub(1, Ordering::SeqCst);
356 self.0.drained.notify_waiters();
357 }
358}
359
360fn with_jitter(d: Duration) -> Duration {
361 let jitter = rand::rng().random_range(-RECONNECT_JITTER..RECONNECT_JITTER);
362 let secs = (d.as_secs_f64() * (1.0 + jitter)).max(0.0);
363 Duration::from_secs_f64(secs)
364}
365
366pub(crate) async fn cancellable_sleep(delay: Duration, cancel: &CancellationToken) -> bool {
369 tokio::select! {
370 _ = tokio::time::sleep(delay) => true,
371 _ = cancel.cancelled() => false,
372 }
373}
374
375pub(super) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
377
378pub(super) enum ConnectError {
380 ApiKeyRejected(StatusCode),
383 Other(String),
385}
386
387pub(super) async fn connect_ws(
391 url: &str,
392 api_key: &str,
393 extra_headers: &HeaderMap,
394) -> Result<Ws, ConnectError> {
395 let mut request = url
396 .into_client_request()
397 .map_err(|e| ConnectError::Other(format!("build request: {}", err_chain(&e))))?;
398 request.headers_mut().extend(extra_headers.clone());
399 request.headers_mut().insert(
400 "X-API-Key",
401 HeaderValue::from_str(api_key)
402 .map_err(|e| ConnectError::Other(format!("api key header: {}", err_chain(&e))))?,
403 );
404 request.headers_mut().insert(
405 "user-agent",
406 HeaderValue::from_str(&crate::client::user_agent(
407 ClientProduct::Sdk,
408 None,
409 ClientSurface::Managed,
410 ))
411 .map_err(|e| ConnectError::Other(format!("build user-agent: {e}")))?,
412 );
413
414 let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
415 .await
416 .map_err(|_| ConnectError::Other(format!("connect timeout after {CONNECT_TIMEOUT:?}")))?
417 .map_err(|e| match &e {
418 WsError::Http(response)
419 if matches!(
420 response.status(),
421 StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN
422 ) =>
423 {
424 ConnectError::ApiKeyRejected(response.status())
425 }
426 _ => ConnectError::Other(format!("connect: {}", err_chain(&e))),
427 })?;
428 Ok(connect.0)
429}
430
431pub(super) async fn send_request(ws: &mut Ws, req: &BacktestRequest) -> Result<(), String> {
433 let text = serde_json::to_string(req).map_err(|e| format!("serialize: {}", err_chain(&e)))?;
434 ws.send(Message::Text(text))
435 .await
436 .map_err(|e| format!("send: {}", err_chain(&e)))
437}
438
439pub(super) fn resolve_rpc_url(base: &str, endpoint: &str) -> String {
442 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
443 endpoint.to_string()
444 } else {
445 format!("{}/{}", base, endpoint.trim_start_matches('/'))
446 }
447}
448
449pub(super) enum HandshakeError {
451 Transient(String),
453 Fatal(CreateError),
455}
456
457pub(super) fn handshake_error_for_response(
461 stage: &'static str,
462 err: BacktestError,
463) -> HandshakeError {
464 match err {
465 BacktestError::SessionOwnershipBusy { .. } => {
466 HandshakeError::Transient(format!("{stage} contended: {}", err_chain(&err)))
467 }
468 _ => HandshakeError::Fatal(CreateError::Rejected(err)),
469 }
470}
471
472pub(super) enum MessageLoopExit {
475 SessionEnded,
478 Cancelled,
481 ConnectionLost(String),
483 Terminal(String),
485}
486
487pub(super) fn publish_status(
489 status_tx: &watch::Sender<ConnectionStatus>,
490 status: ConnectionStatus,
491) {
492 status_tx.send_if_modified(|current| {
493 if *current == status {
494 false
495 } else {
496 *current = status;
497 true
498 }
499 });
500}
501
502pub(super) async fn graceful_close(ws: &mut Ws) {
507 let _ = tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, async {
508 let _ = send_request(ws, &BacktestRequest::CloseBacktestSession).await;
509 let _ = ws.close(None).await;
510 })
511 .await;
512}
513
514pub(super) enum InboundFrame {
516 Text(String),
518 Ignore,
520 Lost(String),
522}
523
524pub(super) fn classify_inbound(msg: Option<Result<Message, WsError>>) -> InboundFrame {
526 match msg {
527 Some(Ok(Message::Text(t))) => InboundFrame::Text(t),
528 Some(Ok(Message::Binary(b))) => match String::from_utf8(b) {
529 Ok(t) => InboundFrame::Text(t),
530 Err(_) => InboundFrame::Ignore,
531 },
532 Some(Ok(Message::Pong(_) | Message::Ping(_) | Message::Frame(_))) => InboundFrame::Ignore,
533 Some(Ok(Message::Close(frame))) => InboundFrame::Lost(format!("remote close: {frame:?}")),
534 Some(Err(e)) => InboundFrame::Lost(format!("ws read: {}", err_chain(&e))),
535 None => InboundFrame::Lost("ws stream ended".into()),
536 }
537}
538
539pub(super) async fn send_keepalive_ping(ws: &mut Ws, last_inbound: Instant) -> Option<String> {
543 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
544 return Some(format!("no traffic for {:?}", last_inbound.elapsed()));
545 }
546 if let Err(e) = ws.send(Message::Ping(vec![])).await {
547 return Some(format!("ping send: {}", err_chain(&e)));
548 }
549 None
550}
551
552pub(super) trait ControlConnection: Send + 'static {
556 fn url(&self) -> &str;
557 fn api_key(&self) -> &str;
558 fn extra_headers(&self) -> &HeaderMap;
559 fn cancel(&self) -> &CancellationToken;
560 fn label(&self) -> &'static str;
562 fn status_tx(&self) -> &watch::Sender<ConnectionStatus>;
563 fn fail_pending(&mut self, error: ManagedSessionError);
565 fn handshake(&mut self, ws: Ws) -> impl Future<Output = Result<Ws, HandshakeError>> + Send;
567 fn message_loop(&mut self, ws: Ws) -> impl Future<Output = MessageLoopExit> + Send;
569
570 fn publish(&self, status: ConnectionStatus) {
571 publish_status(self.status_tx(), status);
572 }
573
574 fn finish_failed(&mut self, error: CreateError) {
575 self.publish(ConnectionStatus::Failed(error.to_string()));
576 self.fail_pending(ManagedSessionError::Create(error));
577 }
578}
579
580pub(super) async fn run_control_loop<T: ControlConnection>(mut task: T) {
584 let mut budget = ReconnectBudget::new();
585
586 loop {
587 if task.cancel().is_cancelled() {
588 task.fail_pending(ManagedSessionError::Cancelled);
589 return;
590 }
591 task.publish(ConnectionStatus::Down);
592
593 let ws = match connect_ws(task.url(), task.api_key(), task.extra_headers()).await {
594 Ok(ws) => ws,
595 Err(ConnectError::ApiKeyRejected(status)) => {
596 let rejected = ManagedSessionError::ApiKeyRejected(status);
597 task.publish(ConnectionStatus::Failed(format!("connect: {rejected}")));
598 task.fail_pending(rejected);
599 return;
600 }
601 Err(ConnectError::Other(why)) => {
602 if let Some(delay) = budget.next_backoff() {
603 warn!(attempt = budget.attempt(), error = %why, ?delay, "{} connect failed, retrying", task.label());
604 if !cancellable_sleep(delay, task.cancel()).await {
605 return;
606 }
607 continue;
608 }
609 task.finish_failed(CreateError::Connection(format!("connect: {why}")));
610 return;
611 }
612 };
613
614 let ws = match task.handshake(ws).await {
615 Ok(ws) => ws,
616 Err(HandshakeError::Fatal(error)) => {
617 task.finish_failed(error);
618 return;
619 }
620 Err(HandshakeError::Transient(why)) => {
621 if let Some(delay) = budget.next_backoff() {
622 warn!(attempt = budget.attempt(), error = %why, ?delay, "{} handshake failed, retrying", task.label());
623 if !cancellable_sleep(delay, task.cancel()).await {
624 return;
625 }
626 continue;
627 }
628 task.finish_failed(CreateError::Connection(format!("handshake: {why}")));
629 return;
630 }
631 };
632
633 task.publish(ConnectionStatus::Up);
634 let connected_at = Instant::now();
635
636 match task.message_loop(ws).await {
637 MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
638 MessageLoopExit::ConnectionLost(why) => {
639 if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
640 budget.reset();
641 }
642 if let Some(delay) = budget.next_backoff() {
643 warn!(attempt = budget.attempt(), reason = %why, ?delay, "{} connection lost, reconnecting", task.label());
644 if !cancellable_sleep(delay, task.cancel()).await {
645 return;
646 }
647 continue;
648 }
649 task.finish_failed(CreateError::Connection(format!("connection lost: {why}")));
650 return;
651 }
652 MessageLoopExit::Terminal(why) => {
653 task.publish(ConnectionStatus::Failed(why));
655 return;
656 }
657 }
658 }
659}
660
661#[cfg(test)]
662mod tests {
663 use super::*;
664
665 async fn handshake_head(extra_headers: &HeaderMap) -> String {
668 use tokio::io::AsyncReadExt;
669
670 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
671 .await
672 .expect("bind");
673 let addr = listener.local_addr().expect("addr");
674 let accepted = tokio::spawn(async move {
675 let (mut stream, _) = listener.accept().await.expect("accept");
676 let mut buf = vec![0_u8; 4096];
677 let read = stream.read(&mut buf).await.expect("read");
678 String::from_utf8_lossy(&buf[..read]).to_string()
679 });
680
681 let _ = connect_ws(&format!("ws://{addr}"), "k", extra_headers).await;
682
683 accepted.await.expect("join")
684 }
685
686 fn header_value(head: &str, name: &str) -> Option<String> {
687 head.lines().find_map(|line| {
688 let (key, value) = line.split_once(':')?;
689 key.eq_ignore_ascii_case(name)
690 .then(|| value.trim().to_string())
691 })
692 }
693
694 #[tokio::test]
696 async fn connect_ws_identifies_itself_as_managed() {
697 let head = handshake_head(&HeaderMap::new()).await;
698 let user_agent = header_value(&head, "user-agent").expect("connect_ws sent a User-Agent");
699 assert_eq!(
700 simulator_api::client_identity::classify(Some(&user_agent)).0,
701 simulator_api::client_identity::ClientKind::Managed,
702 );
703 }
704
705 #[tokio::test]
706 async fn connect_ws_sends_the_extra_headers_beside_the_api_key() {
707 let extra_headers = HeaderMap::from_iter([(
708 http::HeaderName::from_static("x-extra"),
709 HeaderValue::from_static("extra"),
710 )]);
711
712 let head = handshake_head(&extra_headers).await;
713
714 assert_eq!(header_value(&head, "x-extra").as_deref(), Some("extra"));
715 assert_eq!(header_value(&head, "x-api-key").as_deref(), Some("k"));
716 }
717
718 #[test]
719 fn budget_exhausts_after_max_attempts() {
720 let mut b = ReconnectBudget::new();
721 for _ in 0..RECONNECT_MAX_ATTEMPTS {
722 assert!(b.next_backoff().is_some());
723 }
724 assert!(b.next_backoff().is_none());
725 }
726
727 #[test]
728 fn budget_reset_restores_full_budget() {
729 let mut b = ReconnectBudget::new();
730 b.next_backoff();
731 b.next_backoff();
732 b.reset();
733 assert_eq!(b.attempt(), 0);
734 }
735
736 #[test]
737 fn streaming_guard_balances_the_count() {
738 let coord = Arc::new(ReconnectCoordinator::new());
739 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
740 let g = coord.enter();
741 assert_eq!(coord.streaming.load(Ordering::SeqCst), 1);
742 drop(g);
743 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
744 }
745
746 #[tokio::test]
747 async fn reconnect_slot_available_when_link_is_quiet() {
748 let coord = Arc::new(ReconnectCoordinator::new());
749 let cancel = CancellationToken::new();
750 assert!(coord.reconnect_slot(&cancel).await.is_some());
751 }
752
753 #[tokio::test]
754 async fn reconnect_slot_unparks_when_last_sibling_leaves() {
755 let coord = Arc::new(ReconnectCoordinator::new());
756 let cancel = CancellationToken::new();
757 let guard = coord.enter(); let waiter = tokio::spawn({
760 let coord = coord.clone();
761 let cancel = cancel.clone();
762 async move { coord.reconnect_slot(&cancel).await.is_some() }
763 });
764
765 tokio::task::yield_now().await;
767 assert!(!waiter.is_finished());
768
769 drop(guard); assert!(waiter.await.unwrap());
771 }
772
773 #[tokio::test]
774 async fn reconnect_slot_returns_none_on_cancel_while_parked() {
775 let coord = Arc::new(ReconnectCoordinator::new());
776 let _guard = coord.enter(); let cancel = CancellationToken::new();
778 cancel.cancel();
779 assert!(coord.reconnect_slot(&cancel).await.is_none());
780 }
781
782 #[test]
783 fn discount_parked_does_not_consume_the_budget() {
784 let mut b = ReconnectBudget::new();
785 b.discount_parked(2 * RECONNECT_MAX_TOTAL);
787 for _ in 0..RECONNECT_MAX_ATTEMPTS {
788 assert!(b.next_backoff().is_some());
789 }
790 }
791}