1use std::{
21 future::Future,
22 sync::{
23 Arc,
24 atomic::{AtomicU64, AtomicUsize, Ordering},
25 },
26 time::{Duration, Instant},
27};
28
29use bon::Builder;
30use futures::SinkExt;
31use http::HeaderMap;
32use rand::RngExt;
33use simulator_api::{
34 BacktestError, BacktestRequest, CreateBacktestSessionRequest, SessionId,
35 client_identity::{ClientProduct, ClientSurface},
36};
37use tokio::{
38 net::TcpStream,
39 sync::{Notify, OwnedSemaphorePermit, Semaphore, watch},
40};
41use tokio_tungstenite::{
42 MaybeTlsStream, WebSocketStream, connect_async,
43 tungstenite::{Error as WsError, Message, client::IntoClientRequest, http::HeaderValue},
44};
45use tokio_util::sync::CancellationToken;
46use tracing::warn;
47
48use crate::{error::err_chain, urls::backtest_ws_url};
49
50mod control;
51mod parallel;
52mod session;
53mod subscription;
54
55pub use control::{ControlEvent, ControlHandle, spawn_control_manager};
56pub use parallel::{ManagedParallelSession, ParallelSubSession};
57pub use session::{ManagedBacktestSession, ManagedEvent, ManagedSessionError};
58pub use subscription::{
59 SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
60 spawn_action_subscription_manager, spawn_diagnostic_subscription_manager,
61 spawn_replacement_subscription_manager, spawn_transaction_subscription_manager,
62};
63
64pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
66
67pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
78
79pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
81
82pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
85
86pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
89
90pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
91pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
92pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
93pub const RECONNECT_JITTER: f64 = 0.2;
94pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
95pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
96
97pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
101
102pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
104
105pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
114
115#[derive(Clone, Debug, PartialEq, Eq)]
120pub enum ConnectionStatus {
121 Up,
122 Down,
123 Failed(String),
124}
125
126#[derive(Clone, Debug)]
128pub struct SessionInfo {
129 pub session_id: SessionId,
130 pub session_name: Option<String>,
132 pub rpc_endpoint: String,
133 pub task_id: Option<String>,
135}
136
137#[derive(Debug, Clone, Builder)]
144pub struct StartSessionParams {
145 #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
147 pub url: String,
148 pub api_key: String,
149 #[builder(default)]
151 pub extra_headers: HeaderMap,
152 pub create: CreateBacktestSessionRequest,
153 #[builder(default)]
155 pub parent_cancel: CancellationToken,
156 #[builder(default)]
159 pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
160}
161
162#[derive(Debug, Default)]
165pub struct SubscriptionDiagnostics {
166 reconnects: AtomicU64,
168}
169
170impl SubscriptionDiagnostics {
171 pub(crate) fn record_reconnect(&self) {
172 self.reconnects.fetch_add(1, Ordering::Relaxed);
173 }
174
175 pub fn reconnects(&self) -> u64 {
176 self.reconnects.load(Ordering::Relaxed)
177 }
178}
179
180pub(crate) struct ReconnectBudget {
182 attempts: u32,
183 started_at: std::time::Instant,
184 current_backoff: Duration,
185}
186
187impl ReconnectBudget {
188 pub fn new() -> Self {
189 Self {
190 attempts: 0,
191 started_at: std::time::Instant::now(),
192 current_backoff: RECONNECT_INITIAL_BACKOFF,
193 }
194 }
195
196 pub fn reset(&mut self) {
197 self.attempts = 0;
198 self.started_at = std::time::Instant::now();
199 self.current_backoff = RECONNECT_INITIAL_BACKOFF;
200 }
201
202 pub fn attempt(&self) -> u32 {
203 self.attempts
204 }
205
206 pub fn discount_parked(&mut self, parked: Duration) {
213 self.started_at += parked;
214 }
215
216 pub fn next_backoff(&mut self) -> Option<Duration> {
219 if self.attempts >= RECONNECT_MAX_ATTEMPTS
220 || self.started_at.elapsed() >= RECONNECT_MAX_TOTAL
221 {
222 return None;
223 }
224 self.attempts += 1;
225 let backoff = with_jitter(self.current_backoff);
226 self.current_backoff = std::cmp::min(
227 RECONNECT_MAX_BACKOFF,
228 Duration::from_secs_f64(
229 self.current_backoff.as_secs_f64() * RECONNECT_BACKOFF_MULTIPLIER,
230 ),
231 );
232 Some(backoff)
233 }
234}
235
236pub struct ReconnectCoordinator {
248 streaming: AtomicUsize,
251 drained: Notify,
253 handshake: Arc<Semaphore>,
256}
257
258impl Default for ReconnectCoordinator {
259 fn default() -> Self {
260 Self::new()
261 }
262}
263
264impl ReconnectCoordinator {
265 pub fn new() -> Self {
266 Self {
267 streaming: AtomicUsize::new(0),
268 drained: Notify::new(),
269 handshake: Arc::new(Semaphore::new(1)),
270 }
271 }
272
273 pub fn enter(self: &Arc<Self>) -> StreamingGuard {
278 self.streaming.fetch_add(1, Ordering::SeqCst);
279 StreamingGuard(self.clone())
280 }
281
282 pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
288 loop {
289 loop {
292 let drained = self.drained.notified();
293 if self.streaming.load(Ordering::SeqCst) == 0 {
294 break;
295 }
296 tokio::select! {
297 biased;
298 _ = cancel.cancelled() => return None,
299 _ = drained => {}
300 }
301 }
302 let permit = tokio::select! {
303 biased;
304 _ = cancel.cancelled() => return None,
305 p = self.handshake.clone().acquire_owned() => p.ok()?,
306 };
307 if self.streaming.load(Ordering::SeqCst) == 0 {
311 return Some(permit);
312 }
313 }
314 }
315}
316
317pub struct StreamingGuard(Arc<ReconnectCoordinator>);
320
321impl Drop for StreamingGuard {
322 fn drop(&mut self) {
323 self.0.streaming.fetch_sub(1, Ordering::SeqCst);
324 self.0.drained.notify_waiters();
325 }
326}
327
328fn with_jitter(d: Duration) -> Duration {
329 let jitter = rand::rng().random_range(-RECONNECT_JITTER..RECONNECT_JITTER);
330 let secs = (d.as_secs_f64() * (1.0 + jitter)).max(0.0);
331 Duration::from_secs_f64(secs)
332}
333
334pub(crate) async fn cancellable_sleep(delay: Duration, cancel: &CancellationToken) -> bool {
337 tokio::select! {
338 _ = tokio::time::sleep(delay) => true,
339 _ = cancel.cancelled() => false,
340 }
341}
342
343pub(super) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
345
346pub(super) async fn connect_ws(
350 url: &str,
351 api_key: &str,
352 extra_headers: &HeaderMap,
353) -> Result<Ws, String> {
354 let mut request = url
355 .into_client_request()
356 .map_err(|e| format!("build request: {}", err_chain(&e)))?;
357 request.headers_mut().extend(extra_headers.clone());
358 request.headers_mut().insert(
359 "X-API-Key",
360 HeaderValue::from_str(api_key).map_err(|e| format!("api key header: {}", err_chain(&e)))?,
361 );
362 request.headers_mut().insert(
363 "user-agent",
364 HeaderValue::from_str(&crate::client::user_agent(
365 ClientProduct::Sdk,
366 None,
367 ClientSurface::Managed,
368 ))
369 .map_err(|e| format!("build user-agent: {e}"))?,
370 );
371
372 let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
373 .await
374 .map_err(|_| format!("connect timeout after {CONNECT_TIMEOUT:?}"))?
375 .map_err(|e| format!("connect: {}", err_chain(&e)))?;
376 Ok(connect.0)
377}
378
379pub(super) async fn send_request(ws: &mut Ws, req: &BacktestRequest) -> Result<(), String> {
381 let text = serde_json::to_string(req).map_err(|e| format!("serialize: {}", err_chain(&e)))?;
382 ws.send(Message::Text(text))
383 .await
384 .map_err(|e| format!("send: {}", err_chain(&e)))
385}
386
387pub(super) fn resolve_rpc_url(base: &str, endpoint: &str) -> String {
390 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
391 endpoint.to_string()
392 } else {
393 format!("{}/{}", base, endpoint.trim_start_matches('/'))
394 }
395}
396
397pub(super) enum HandshakeError {
399 Transient(String),
401 Fatal(String),
403}
404
405pub(super) fn handshake_error_for_response(
409 stage: &'static str,
410 err: BacktestError,
411) -> HandshakeError {
412 match err {
413 BacktestError::SessionOwnershipBusy { .. } => {
414 HandshakeError::Transient(format!("{stage} contended: {}", err_chain(&err)))
415 }
416 _ => HandshakeError::Fatal(format!("{stage} rejected: {}", err_chain(&err))),
417 }
418}
419
420pub(super) enum MessageLoopExit {
423 SessionEnded,
426 Cancelled,
429 ConnectionLost(String),
431 Terminal(String),
433}
434
435pub(super) fn publish_status(
437 status_tx: &watch::Sender<ConnectionStatus>,
438 status: ConnectionStatus,
439) {
440 status_tx.send_if_modified(|current| {
441 if *current == status {
442 false
443 } else {
444 *current = status;
445 true
446 }
447 });
448}
449
450pub(super) async fn graceful_close(ws: &mut Ws) {
455 let _ = tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, async {
456 let _ = send_request(ws, &BacktestRequest::CloseBacktestSession).await;
457 let _ = ws.close(None).await;
458 })
459 .await;
460}
461
462pub(super) enum InboundFrame {
464 Text(String),
466 Ignore,
468 Lost(String),
470}
471
472pub(super) fn classify_inbound(msg: Option<Result<Message, WsError>>) -> InboundFrame {
474 match msg {
475 Some(Ok(Message::Text(t))) => InboundFrame::Text(t),
476 Some(Ok(Message::Binary(b))) => match String::from_utf8(b) {
477 Ok(t) => InboundFrame::Text(t),
478 Err(_) => InboundFrame::Ignore,
479 },
480 Some(Ok(Message::Pong(_) | Message::Ping(_) | Message::Frame(_))) => InboundFrame::Ignore,
481 Some(Ok(Message::Close(frame))) => InboundFrame::Lost(format!("remote close: {frame:?}")),
482 Some(Err(e)) => InboundFrame::Lost(format!("ws read: {}", err_chain(&e))),
483 None => InboundFrame::Lost("ws stream ended".into()),
484 }
485}
486
487pub(super) async fn send_keepalive_ping(ws: &mut Ws, last_inbound: Instant) -> Option<String> {
491 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
492 return Some(format!("no traffic for {:?}", last_inbound.elapsed()));
493 }
494 if let Err(e) = ws.send(Message::Ping(vec![])).await {
495 return Some(format!("ping send: {}", err_chain(&e)));
496 }
497 None
498}
499
500pub(super) trait ControlConnection: Send + 'static {
504 fn url(&self) -> &str;
505 fn api_key(&self) -> &str;
506 fn extra_headers(&self) -> &HeaderMap;
507 fn cancel(&self) -> &CancellationToken;
508 fn label(&self) -> &'static str;
510 fn status_tx(&self) -> &watch::Sender<ConnectionStatus>;
511 fn fail_pending(&mut self, reason: String);
513 fn handshake(&mut self, ws: Ws) -> impl Future<Output = Result<Ws, HandshakeError>> + Send;
515 fn message_loop(&mut self, ws: Ws) -> impl Future<Output = MessageLoopExit> + Send;
517
518 fn publish(&self, status: ConnectionStatus) {
519 publish_status(self.status_tx(), status);
520 }
521
522 fn finish_failed(&mut self, reason: String) {
523 self.fail_pending(reason.clone());
524 self.publish(ConnectionStatus::Failed(reason));
525 }
526}
527
528pub(super) async fn run_control_loop<T: ControlConnection>(mut task: T) {
532 let mut budget = ReconnectBudget::new();
533
534 loop {
535 if task.cancel().is_cancelled() {
536 task.fail_pending("cancelled before session created".to_string());
537 return;
538 }
539 task.publish(ConnectionStatus::Down);
540
541 let ws = match connect_ws(task.url(), task.api_key(), task.extra_headers()).await {
542 Ok(ws) => ws,
543 Err(why) => {
544 if let Some(delay) = budget.next_backoff() {
545 warn!(attempt = budget.attempt(), error = %why, ?delay, "{} connect failed, retrying", task.label());
546 if !cancellable_sleep(delay, task.cancel()).await {
547 return;
548 }
549 continue;
550 }
551 task.finish_failed(format!("connect: {why}"));
552 return;
553 }
554 };
555
556 let ws = match task.handshake(ws).await {
557 Ok(ws) => ws,
558 Err(HandshakeError::Fatal(why)) => {
559 task.finish_failed(format!("handshake: {why}"));
560 return;
561 }
562 Err(HandshakeError::Transient(why)) => {
563 if let Some(delay) = budget.next_backoff() {
564 warn!(attempt = budget.attempt(), error = %why, ?delay, "{} handshake failed, retrying", task.label());
565 if !cancellable_sleep(delay, task.cancel()).await {
566 return;
567 }
568 continue;
569 }
570 task.finish_failed(format!("handshake: {why}"));
571 return;
572 }
573 };
574
575 task.publish(ConnectionStatus::Up);
576 let connected_at = Instant::now();
577
578 match task.message_loop(ws).await {
579 MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
580 MessageLoopExit::ConnectionLost(why) => {
581 if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
582 budget.reset();
583 }
584 if let Some(delay) = budget.next_backoff() {
585 warn!(attempt = budget.attempt(), reason = %why, ?delay, "{} connection lost, reconnecting", task.label());
586 if !cancellable_sleep(delay, task.cancel()).await {
587 return;
588 }
589 continue;
590 }
591 task.finish_failed(format!("connection lost: {why}"));
592 return;
593 }
594 MessageLoopExit::Terminal(why) => {
595 task.finish_failed(why);
596 return;
597 }
598 }
599 }
600}
601
602#[cfg(test)]
603mod tests {
604 use super::*;
605
606 async fn handshake_head(extra_headers: &HeaderMap) -> String {
609 use tokio::io::AsyncReadExt;
610
611 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
612 .await
613 .expect("bind");
614 let addr = listener.local_addr().expect("addr");
615 let accepted = tokio::spawn(async move {
616 let (mut stream, _) = listener.accept().await.expect("accept");
617 let mut buf = vec![0_u8; 4096];
618 let read = stream.read(&mut buf).await.expect("read");
619 String::from_utf8_lossy(&buf[..read]).to_string()
620 });
621
622 let _ = connect_ws(&format!("ws://{addr}"), "k", extra_headers).await;
623
624 accepted.await.expect("join")
625 }
626
627 fn header_value(head: &str, name: &str) -> Option<String> {
628 head.lines().find_map(|line| {
629 let (key, value) = line.split_once(':')?;
630 key.eq_ignore_ascii_case(name)
631 .then(|| value.trim().to_string())
632 })
633 }
634
635 #[tokio::test]
637 async fn connect_ws_identifies_itself_as_managed() {
638 let head = handshake_head(&HeaderMap::new()).await;
639 let user_agent = header_value(&head, "user-agent").expect("connect_ws sent a User-Agent");
640 assert_eq!(
641 simulator_api::client_identity::classify(Some(&user_agent)).0,
642 simulator_api::client_identity::ClientKind::Managed,
643 );
644 }
645
646 #[tokio::test]
647 async fn connect_ws_sends_the_extra_headers_beside_the_api_key() {
648 let extra_headers = HeaderMap::from_iter([(
649 http::HeaderName::from_static("x-extra"),
650 HeaderValue::from_static("extra"),
651 )]);
652
653 let head = handshake_head(&extra_headers).await;
654
655 assert_eq!(header_value(&head, "x-extra").as_deref(), Some("extra"));
656 assert_eq!(header_value(&head, "x-api-key").as_deref(), Some("k"));
657 }
658
659 #[test]
660 fn budget_exhausts_after_max_attempts() {
661 let mut b = ReconnectBudget::new();
662 for _ in 0..RECONNECT_MAX_ATTEMPTS {
663 assert!(b.next_backoff().is_some());
664 }
665 assert!(b.next_backoff().is_none());
666 }
667
668 #[test]
669 fn budget_reset_restores_full_budget() {
670 let mut b = ReconnectBudget::new();
671 b.next_backoff();
672 b.next_backoff();
673 b.reset();
674 assert_eq!(b.attempt(), 0);
675 }
676
677 #[test]
678 fn streaming_guard_balances_the_count() {
679 let coord = Arc::new(ReconnectCoordinator::new());
680 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
681 let g = coord.enter();
682 assert_eq!(coord.streaming.load(Ordering::SeqCst), 1);
683 drop(g);
684 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
685 }
686
687 #[tokio::test]
688 async fn reconnect_slot_available_when_link_is_quiet() {
689 let coord = Arc::new(ReconnectCoordinator::new());
690 let cancel = CancellationToken::new();
691 assert!(coord.reconnect_slot(&cancel).await.is_some());
692 }
693
694 #[tokio::test]
695 async fn reconnect_slot_unparks_when_last_sibling_leaves() {
696 let coord = Arc::new(ReconnectCoordinator::new());
697 let cancel = CancellationToken::new();
698 let guard = coord.enter(); let waiter = tokio::spawn({
701 let coord = coord.clone();
702 let cancel = cancel.clone();
703 async move { coord.reconnect_slot(&cancel).await.is_some() }
704 });
705
706 tokio::task::yield_now().await;
708 assert!(!waiter.is_finished());
709
710 drop(guard); assert!(waiter.await.unwrap());
712 }
713
714 #[tokio::test]
715 async fn reconnect_slot_returns_none_on_cancel_while_parked() {
716 let coord = Arc::new(ReconnectCoordinator::new());
717 let _guard = coord.enter(); let cancel = CancellationToken::new();
719 cancel.cancel();
720 assert!(coord.reconnect_slot(&cancel).await.is_none());
721 }
722
723 #[test]
724 fn discount_parked_does_not_consume_the_budget() {
725 let mut b = ReconnectBudget::new();
726 b.discount_parked(2 * RECONNECT_MAX_TOTAL);
728 for _ in 0..RECONNECT_MAX_ATTEMPTS {
729 assert!(b.next_backoff().is_some());
730 }
731 }
732}