simulator_client/managed/
mod.rs1use std::{
13 future::Future,
14 sync::{
15 Arc,
16 atomic::{AtomicU64, AtomicUsize, Ordering},
17 },
18 time::{Duration, Instant},
19};
20
21use bon::Builder;
22use futures::SinkExt;
23use rand::RngExt;
24use simulator_api::{BacktestError, BacktestRequest, CreateBacktestSessionRequest, SessionId};
25use tokio::{
26 net::TcpStream,
27 sync::{Notify, OwnedSemaphorePermit, Semaphore, watch},
28};
29use tokio_tungstenite::{
30 MaybeTlsStream, WebSocketStream, connect_async,
31 tungstenite::{Error as WsError, Message, client::IntoClientRequest, http::HeaderValue},
32};
33use tokio_util::sync::CancellationToken;
34use tracing::warn;
35
36use crate::error::err_chain;
37
38mod control;
39mod parallel;
40mod session;
41mod subscription;
42
43pub use control::{ControlEvent, ControlHandle, spawn_control_manager};
44pub use parallel::{ManagedParallelSession, ParallelSubSession};
45pub use session::{ManagedBacktestSession, ManagedEvent, ManagedSessionError};
46pub use subscription::{
47 SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
48 spawn_action_subscription_manager, spawn_transaction_subscription_manager,
49};
50
51pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
53
54pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
65
66pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
68
69pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
72
73pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
76
77pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
78pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
79pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
80pub const RECONNECT_JITTER: f64 = 0.2;
81pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
82pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
83
84pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
88
89pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
91
92#[derive(Clone, Debug, PartialEq, Eq)]
97pub enum ConnectionStatus {
98 Up,
99 Down,
100 Failed(String),
101}
102
103#[derive(Clone, Debug)]
105pub struct SessionInfo {
106 pub session_id: SessionId,
107 pub rpc_endpoint: String,
108 pub task_id: Option<String>,
110}
111
112#[derive(Debug, Clone, Builder)]
118pub struct StartSessionParams {
119 pub url: String,
121 pub api_key: String,
122 pub create: CreateBacktestSessionRequest,
123 #[builder(default)]
125 pub parent_cancel: CancellationToken,
126 #[builder(default)]
129 pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
130}
131
132#[derive(Debug, Default)]
135pub struct SubscriptionDiagnostics {
136 reconnects: AtomicU64,
138}
139
140impl SubscriptionDiagnostics {
141 pub(crate) fn record_reconnect(&self) {
142 self.reconnects.fetch_add(1, Ordering::Relaxed);
143 }
144
145 pub fn reconnects(&self) -> u64 {
146 self.reconnects.load(Ordering::Relaxed)
147 }
148}
149
150pub(crate) struct ReconnectBudget {
152 attempts: u32,
153 started_at: std::time::Instant,
154 current_backoff: Duration,
155}
156
157impl ReconnectBudget {
158 pub fn new() -> Self {
159 Self {
160 attempts: 0,
161 started_at: std::time::Instant::now(),
162 current_backoff: RECONNECT_INITIAL_BACKOFF,
163 }
164 }
165
166 pub fn reset(&mut self) {
167 self.attempts = 0;
168 self.started_at = std::time::Instant::now();
169 self.current_backoff = RECONNECT_INITIAL_BACKOFF;
170 }
171
172 pub fn attempt(&self) -> u32 {
173 self.attempts
174 }
175
176 pub fn discount_parked(&mut self, parked: Duration) {
183 self.started_at += parked;
184 }
185
186 pub fn next_backoff(&mut self) -> Option<Duration> {
189 if self.attempts >= RECONNECT_MAX_ATTEMPTS
190 || self.started_at.elapsed() >= RECONNECT_MAX_TOTAL
191 {
192 return None;
193 }
194 self.attempts += 1;
195 let backoff = with_jitter(self.current_backoff);
196 self.current_backoff = std::cmp::min(
197 RECONNECT_MAX_BACKOFF,
198 Duration::from_secs_f64(
199 self.current_backoff.as_secs_f64() * RECONNECT_BACKOFF_MULTIPLIER,
200 ),
201 );
202 Some(backoff)
203 }
204}
205
206pub struct ReconnectCoordinator {
218 streaming: AtomicUsize,
221 drained: Notify,
223 handshake: Arc<Semaphore>,
226}
227
228impl Default for ReconnectCoordinator {
229 fn default() -> Self {
230 Self::new()
231 }
232}
233
234impl ReconnectCoordinator {
235 pub fn new() -> Self {
236 Self {
237 streaming: AtomicUsize::new(0),
238 drained: Notify::new(),
239 handshake: Arc::new(Semaphore::new(1)),
240 }
241 }
242
243 pub fn enter(self: &Arc<Self>) -> StreamingGuard {
248 self.streaming.fetch_add(1, Ordering::SeqCst);
249 StreamingGuard(self.clone())
250 }
251
252 pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
258 loop {
259 loop {
262 let drained = self.drained.notified();
263 if self.streaming.load(Ordering::SeqCst) == 0 {
264 break;
265 }
266 tokio::select! {
267 biased;
268 _ = cancel.cancelled() => return None,
269 _ = drained => {}
270 }
271 }
272 let permit = tokio::select! {
273 biased;
274 _ = cancel.cancelled() => return None,
275 p = self.handshake.clone().acquire_owned() => p.ok()?,
276 };
277 if self.streaming.load(Ordering::SeqCst) == 0 {
281 return Some(permit);
282 }
283 }
284 }
285}
286
287pub struct StreamingGuard(Arc<ReconnectCoordinator>);
290
291impl Drop for StreamingGuard {
292 fn drop(&mut self) {
293 self.0.streaming.fetch_sub(1, Ordering::SeqCst);
294 self.0.drained.notify_waiters();
295 }
296}
297
298fn with_jitter(d: Duration) -> Duration {
299 let jitter = rand::rng().random_range(-RECONNECT_JITTER..RECONNECT_JITTER);
300 let secs = (d.as_secs_f64() * (1.0 + jitter)).max(0.0);
301 Duration::from_secs_f64(secs)
302}
303
304pub(crate) async fn cancellable_sleep(delay: Duration, cancel: &CancellationToken) -> bool {
307 tokio::select! {
308 _ = tokio::time::sleep(delay) => true,
309 _ = cancel.cancelled() => false,
310 }
311}
312
313pub(super) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
315
316pub(super) async fn connect_ws(url: &str, api_key: &str) -> Result<Ws, String> {
319 let mut request = url
320 .into_client_request()
321 .map_err(|e| format!("build request: {}", err_chain(&e)))?;
322 request.headers_mut().insert(
323 "X-API-Key",
324 HeaderValue::from_str(api_key).map_err(|e| format!("api key header: {}", err_chain(&e)))?,
325 );
326
327 let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
328 .await
329 .map_err(|_| format!("connect timeout after {CONNECT_TIMEOUT:?}"))?
330 .map_err(|e| format!("connect: {}", err_chain(&e)))?;
331 Ok(connect.0)
332}
333
334pub(super) async fn send_request(ws: &mut Ws, req: &BacktestRequest) -> Result<(), String> {
336 let text = serde_json::to_string(req).map_err(|e| format!("serialize: {}", err_chain(&e)))?;
337 ws.send(Message::Text(text))
338 .await
339 .map_err(|e| format!("send: {}", err_chain(&e)))
340}
341
342pub(super) fn resolve_rpc_url(base: &str, endpoint: &str) -> String {
345 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
346 endpoint.to_string()
347 } else {
348 format!("{}/{}", base, endpoint.trim_start_matches('/'))
349 }
350}
351
352pub(super) enum HandshakeError {
354 Transient(String),
356 Fatal(String),
358}
359
360pub(super) fn handshake_error_for_response(
364 stage: &'static str,
365 err: BacktestError,
366) -> HandshakeError {
367 match err {
368 BacktestError::SessionOwnershipBusy { .. } => {
369 HandshakeError::Transient(format!("{stage} contended: {}", err_chain(&err)))
370 }
371 _ => HandshakeError::Fatal(format!("{stage} rejected: {}", err_chain(&err))),
372 }
373}
374
375pub(super) enum MessageLoopExit {
378 SessionEnded,
381 Cancelled,
384 ConnectionLost(String),
386 Terminal(String),
388}
389
390pub(super) fn publish_status(
392 status_tx: &watch::Sender<ConnectionStatus>,
393 status: ConnectionStatus,
394) {
395 status_tx.send_if_modified(|current| {
396 if *current == status {
397 false
398 } else {
399 *current = status;
400 true
401 }
402 });
403}
404
405pub(super) async fn graceful_close(ws: &mut Ws) {
410 let _ = tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, async {
411 let _ = send_request(ws, &BacktestRequest::CloseBacktestSession).await;
412 let _ = ws.close(None).await;
413 })
414 .await;
415}
416
417pub(super) enum InboundFrame {
419 Text(String),
421 Ignore,
423 Lost(String),
425}
426
427pub(super) fn classify_inbound(msg: Option<Result<Message, WsError>>) -> InboundFrame {
429 match msg {
430 Some(Ok(Message::Text(t))) => InboundFrame::Text(t),
431 Some(Ok(Message::Binary(b))) => match String::from_utf8(b) {
432 Ok(t) => InboundFrame::Text(t),
433 Err(_) => InboundFrame::Ignore,
434 },
435 Some(Ok(Message::Pong(_) | Message::Ping(_) | Message::Frame(_))) => InboundFrame::Ignore,
436 Some(Ok(Message::Close(frame))) => InboundFrame::Lost(format!("remote close: {frame:?}")),
437 Some(Err(e)) => InboundFrame::Lost(format!("ws read: {}", err_chain(&e))),
438 None => InboundFrame::Lost("ws stream ended".into()),
439 }
440}
441
442pub(super) async fn send_keepalive_ping(ws: &mut Ws, last_inbound: Instant) -> Option<String> {
446 if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
447 return Some(format!("no traffic for {:?}", last_inbound.elapsed()));
448 }
449 if let Err(e) = ws.send(Message::Ping(vec![])).await {
450 return Some(format!("ping send: {}", err_chain(&e)));
451 }
452 None
453}
454
455pub(super) trait ControlConnection: Send + 'static {
459 fn url(&self) -> &str;
460 fn api_key(&self) -> &str;
461 fn cancel(&self) -> &CancellationToken;
462 fn label(&self) -> &'static str;
464 fn status_tx(&self) -> &watch::Sender<ConnectionStatus>;
465 fn fail_pending(&mut self, reason: String);
467 fn handshake(&mut self, ws: Ws) -> impl Future<Output = Result<Ws, HandshakeError>> + Send;
469 fn message_loop(&mut self, ws: Ws) -> impl Future<Output = MessageLoopExit> + Send;
471
472 fn publish(&self, status: ConnectionStatus) {
473 publish_status(self.status_tx(), status);
474 }
475
476 fn finish_failed(&mut self, reason: String) {
477 self.fail_pending(reason.clone());
478 self.publish(ConnectionStatus::Failed(reason));
479 }
480}
481
482pub(super) async fn run_control_loop<T: ControlConnection>(mut task: T) {
486 let mut budget = ReconnectBudget::new();
487
488 loop {
489 if task.cancel().is_cancelled() {
490 task.fail_pending("cancelled before session created".to_string());
491 return;
492 }
493 task.publish(ConnectionStatus::Down);
494
495 let ws = match connect_ws(task.url(), task.api_key()).await {
496 Ok(ws) => ws,
497 Err(why) => {
498 if let Some(delay) = budget.next_backoff() {
499 warn!(attempt = budget.attempt(), error = %why, ?delay, "{} connect failed, retrying", task.label());
500 if !cancellable_sleep(delay, task.cancel()).await {
501 return;
502 }
503 continue;
504 }
505 task.finish_failed(format!("connect: {why}"));
506 return;
507 }
508 };
509
510 let ws = match task.handshake(ws).await {
511 Ok(ws) => ws,
512 Err(HandshakeError::Fatal(why)) => {
513 task.finish_failed(format!("handshake: {why}"));
514 return;
515 }
516 Err(HandshakeError::Transient(why)) => {
517 if let Some(delay) = budget.next_backoff() {
518 warn!(attempt = budget.attempt(), error = %why, ?delay, "{} handshake failed, retrying", task.label());
519 if !cancellable_sleep(delay, task.cancel()).await {
520 return;
521 }
522 continue;
523 }
524 task.finish_failed(format!("handshake: {why}"));
525 return;
526 }
527 };
528
529 task.publish(ConnectionStatus::Up);
530 let connected_at = Instant::now();
531
532 match task.message_loop(ws).await {
533 MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
534 MessageLoopExit::ConnectionLost(why) => {
535 if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
536 budget.reset();
537 }
538 if let Some(delay) = budget.next_backoff() {
539 warn!(attempt = budget.attempt(), reason = %why, ?delay, "{} connection lost, reconnecting", task.label());
540 if !cancellable_sleep(delay, task.cancel()).await {
541 return;
542 }
543 continue;
544 }
545 task.finish_failed(format!("connection lost: {why}"));
546 return;
547 }
548 MessageLoopExit::Terminal(why) => {
549 task.finish_failed(why);
550 return;
551 }
552 }
553 }
554}
555
556#[cfg(test)]
557mod tests {
558 use super::*;
559
560 #[test]
561 fn budget_exhausts_after_max_attempts() {
562 let mut b = ReconnectBudget::new();
563 for _ in 0..RECONNECT_MAX_ATTEMPTS {
564 assert!(b.next_backoff().is_some());
565 }
566 assert!(b.next_backoff().is_none());
567 }
568
569 #[test]
570 fn budget_reset_restores_full_budget() {
571 let mut b = ReconnectBudget::new();
572 b.next_backoff();
573 b.next_backoff();
574 b.reset();
575 assert_eq!(b.attempt(), 0);
576 }
577
578 #[test]
579 fn streaming_guard_balances_the_count() {
580 let coord = Arc::new(ReconnectCoordinator::new());
581 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
582 let g = coord.enter();
583 assert_eq!(coord.streaming.load(Ordering::SeqCst), 1);
584 drop(g);
585 assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
586 }
587
588 #[tokio::test]
589 async fn reconnect_slot_available_when_link_is_quiet() {
590 let coord = Arc::new(ReconnectCoordinator::new());
591 let cancel = CancellationToken::new();
592 assert!(coord.reconnect_slot(&cancel).await.is_some());
593 }
594
595 #[tokio::test]
596 async fn reconnect_slot_unparks_when_last_sibling_leaves() {
597 let coord = Arc::new(ReconnectCoordinator::new());
598 let cancel = CancellationToken::new();
599 let guard = coord.enter(); let waiter = tokio::spawn({
602 let coord = coord.clone();
603 let cancel = cancel.clone();
604 async move { coord.reconnect_slot(&cancel).await.is_some() }
605 });
606
607 tokio::task::yield_now().await;
609 assert!(!waiter.is_finished());
610
611 drop(guard); assert!(waiter.await.unwrap());
613 }
614
615 #[tokio::test]
616 async fn reconnect_slot_returns_none_on_cancel_while_parked() {
617 let coord = Arc::new(ReconnectCoordinator::new());
618 let _guard = coord.enter(); let cancel = CancellationToken::new();
620 cancel.cancel();
621 assert!(coord.reconnect_slot(&cancel).await.is_none());
622 }
623
624 #[test]
625 fn discount_parked_does_not_consume_the_budget() {
626 let mut b = ReconnectBudget::new();
627 b.discount_parked(2 * RECONNECT_MAX_TOTAL);
629 for _ in 0..RECONNECT_MAX_ATTEMPTS {
630 assert!(b.next_backoff().is_some());
631 }
632 }
633}