Skip to main content

simulator_client/managed/
mod.rs

1//! Sessions that reconnect on their own.
2//!
3//! Use [`ManagedBacktestSession`] for one session, or [`ManagedParallelSession`] for a run
4//! the server splits across concurrent sessions. Each one:
5//!
6//! - creates the session;
7//! - reconnects a dropped connection;
8//! - closes the session on `shutdown`.
9//!
10//! # Parallel runs
11//!
12//! [`ManagedParallelSession::start_with_params`] returns when every child is attached. If one
13//! child fails, it closes the attached children and returns the error.
14//!
15//! # Connection drops
16//!
17//! - A dropped connection is retried with backoff, up to [`RECONNECT_MAX_ATTEMPTS`] attempts
18//!   within [`RECONNECT_MAX_TOTAL`]. The session keeps running on the server meanwhile, unless
19//!   `disconnect_timeout_secs` is 0.
20//! - The control channel reconnects. You see no gap in responses.
21//! - If the session has ended, the client stops with [`ManagedSessionError::ControlFailed`].
22//! - A subscription reconnects from the last slot it delivered and sends that slot again: dedupe
23//!   transactions by signature, and account diffs by (signature, account, slot).
24//! - When the budget runs out, the next continue fails: see the error table in the crate docs.
25
26use 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/// Timeout for the initial WebSocket connect (TCP + TLS + HTTP upgrade).
72#[doc(hidden)]
73pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
74
75/// Per server response while a connection is set up. A subscribe can wait ~100 s on a cold start.
76#[doc(hidden)]
77pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
78
79/// How often to send a WebSocket ping during an established connection.
80#[doc(hidden)]
81pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
82
83/// How long without inbound traffic before declaring the connection dead.
84/// Roughly three missed pings.
85#[doc(hidden)]
86pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
87
88/// Total budget for the graceful close handshake (close request + close frame).
89/// A supervisor's SIGTERM→SIGKILL grace must exceed this or the close is cut short.
90#[doc(hidden)]
91pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
92
93/// Wait before the first retry. Each later wait is [`RECONNECT_BACKOFF_MULTIPLIER`] times the
94/// previous one, up to [`RECONNECT_MAX_BACKOFF`].
95#[doc(hidden)]
96pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
97/// Longest wait between two retries.
98#[doc(hidden)]
99pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
100/// Factor applied to the wait after each failed retry.
101#[doc(hidden)]
102pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
103/// Random spread of each wait, as a fraction: `0.2` is ±20%.
104#[doc(hidden)]
105pub const RECONNECT_JITTER: f64 = 0.2;
106/// Time budget for retrying one connection. When it, or [`RECONNECT_MAX_ATTEMPTS`], runs out,
107/// the connection becomes [`ConnectionStatus::Failed`].
108pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
109/// Attempt budget for retrying one connection. See [`RECONNECT_MAX_TOTAL`].
110pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
111
112/// In a parallel run, the retries a dropped subscription makes right away. After these, it
113/// waits until the run's other sessions stop streaming, then reconnects into the freed link.
114#[doc(hidden)]
115pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
116
117/// A connection that stays `Up` for this long gets its full retry budget back.
118#[doc(hidden)]
119pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
120
121/// How long the server keeps a session alive with no client attached, when a single
122/// session's create leaves `disconnect_timeout_secs` unset.
123///
124/// Covers the whole retry budget ([`RECONNECT_MAX_TOTAL`]) plus a minute to reconnect, so a
125/// server restart does not lose the session. Stays under the server's cap
126/// ([`simulator_api::MAX_DISCONNECT_TIMEOUT_SECS`]). A parallel run keeps the server's own
127/// default.
128#[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/// State of one managed connection: the session control channel or a subscription.
135#[derive(Clone, Debug, PartialEq, Eq)]
136pub enum ConnectionStatus {
137    /// Connected and, for a subscription, subscribed.
138    Up,
139    /// Not connected yet, or reconnecting.
140    Down,
141    /// The session is over. Not a connection failure.
142    Ended,
143    /// Gave up. Terminal.
144    Failed(ConnectionFailure),
145}
146
147/// Why a managed connection gave up.
148#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
149pub enum ConnectionFailure {
150    /// The retry budget ran out.
151    #[error("{0}")]
152    RetriesExhausted(String),
153    /// The session's endpoint rejected the token.
154    #[error("the session's endpoint rejected the token")]
155    TokenRejected,
156    /// The session has ended.
157    #[error("the session ended; the server no longer tracks it")]
158    SessionEnded,
159    /// The server refused the connection.
160    #[error("{0}")]
161    Refused(String),
162}
163
164/// What the server reported when it created the session.
165#[derive(Clone)]
166#[non_exhaustive]
167pub struct SessionInfo {
168    #[expect(missing_docs, reason = "self-explanatory session identifier")]
169    pub session_id: SessionId,
170    /// A session of a parallel run carries the run's name.
171    pub session_name: Option<String>,
172    /// Absolute `http(s)` JSON-RPC URL for chain reads at the session's slot; serves state from
173    /// the first `ReadyForContinue` until `Completed` (502 after). Use
174    /// [`ManagedBacktestSession::rpc`], or pass it to `RpcClient::new`.
175    pub rpc_endpoint: String,
176    /// Opaque `task_id` reported by the server for this session, if any.
177    pub task_id: Option<String>,
178    /// Keep `grant.session_id` to attach from a new process.
179    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/// Parameters shared by [`ManagedBacktestSession`] and
217/// [`ManagedParallelSession`] startup.
218///
219/// A standalone session only needs `url`, `api_key` and `create`; the rest
220/// default to no extra headers, a session-owned cancellation token and its own
221/// counters.
222#[derive(Debug, Clone, Builder)]
223pub struct StartSessionParams {
224    /// The server's address. The builder normalizes it with [`crate::backtest_ws_url`]: a bare
225    /// host becomes `wss://<host>/backtest`, and a `ws://` or `wss://` URL gains `/backtest`
226    /// if it lacks it.
227    #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
228    pub url: String,
229    /// Your API key, sent as the `X-API-Key` header.
230    pub api_key: String,
231    /// Extra headers sent to the server when the session is created, beside the API key.
232    #[builder(default)]
233    pub extra_headers: HeaderMap,
234    /// The create request, built with [`crate::CreateSession`] and its `into_request`. Set
235    /// `parallel` on it to start a [`ManagedParallelSession`].
236    pub create: CreateBacktestSessionRequest,
237    /// Cancelling this aborts startup, or stops a started session; its calls then return
238    /// [`ManagedSessionError::Cancelled`] from `next_event`.
239    #[builder(default)]
240    pub parent_cancel: CancellationToken,
241    /// Collects counters from every subscription the session spawns;
242    /// share one across sessions to aggregate a whole run.
243    #[builder(default)]
244    pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
245}
246
247/// Subscription diagnostics counters, shared across every subscription manager a
248/// run spawns.
249#[derive(Debug, Default)]
250pub struct SubscriptionDiagnostics {
251    /// Excludes each subscription task's first connection.
252    reconnects: AtomicU64,
253}
254
255impl SubscriptionDiagnostics {
256    pub(crate) fn record_reconnect(&self) {
257        self.reconnects.fetch_add(1, Ordering::Relaxed);
258    }
259
260    /// Subscription reconnects so far, across every session sharing these counters. First
261    /// connections do not count.
262    pub fn reconnects(&self) -> u64 {
263        self.reconnects.load(Ordering::Relaxed)
264    }
265}
266
267/// Tracks reconnect attempts and enforces the reconnect policy.
268pub(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    /// Discount time the subscription spent parked behind the reconnect
294    /// coordinator. Parking is deliberate waiting for siblings to free the
295    /// link, not retry thrashing, so it must not count against the wall-clock
296    /// budget — otherwise a session that correctly steps aside for minutes is
297    /// failed the moment it reconnects. The attempt-count ceiling still bounds
298    /// total retries.
299    pub fn discount_parked(&mut self, parked: Duration) {
300        self.started_at += parked;
301    }
302
303    /// Record an attempt and return its backoff, or `None` if the budget is
304    /// exhausted.
305    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/// Coordinates subscription reconnects across a parallel batch sharing one
324/// bandwidth-constrained link.
325///
326/// A dropped subscription competing with its still-streaming siblings just
327/// starves — the handshake can't get through a saturated pipe. So once a session
328/// has burned its fast ungated attempts, it stops fighting and **parks until no
329/// sibling is streaming** (the connected sessions have finished and freed their
330/// bandwidth), then reconnects into the quiet link and resumes via
331/// `replayFromSlot`. Stepping aside also speeds the streaming siblings up, so the
332/// batch drains and the parked sessions recover — serially, one at a time, since
333/// at a tight rate only one stream fits.
334#[doc(hidden)]
335pub struct ReconnectCoordinator {
336    /// Subscriptions currently `Up` and streaming. A parked session waits for
337    /// this to reach zero before reconnecting.
338    streaming: AtomicUsize,
339    /// Woken whenever `streaming` decreases, so parked sessions re-check.
340    drained: Notify,
341    /// One in-flight reconnect handshake at a time, so the all-parked case
342    /// recovers serially rather than storming the link the moment it goes quiet.
343    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    /// Mark this subscription as streaming until the returned guard drops.
362    /// Call once a (re)subscribe succeeds; the guard's `Drop` decrements the
363    /// count and wakes any sibling parked in [`Self::reconnect_slot`]. RAII so
364    /// a panicking or aborted task can't leak the count and wedge the batch.
365    pub fn enter(self: &Arc<Self>) -> StreamingGuard {
366        self.streaming.fetch_add(1, Ordering::SeqCst);
367        StreamingGuard(Arc::clone(self))
368    }
369
370    /// Park until no sibling is streaming, then take the single reconnect slot.
371    /// The returned permit must be held across connect + subscribe and dropped
372    /// once [`Self::enter`] has been called (or the attempt failed), so the next
373    /// parked session proceeds only after this one is streaming again. Returns
374    /// `None` if cancelled.
375    pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
376        loop {
377            // Wait for the link to go quiet. Register interest before reading so
378            // a `leave()` between the check and the wait isn't lost.
379            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            // A sibling may have re-entered while we queued for the permit; if so,
396            // release it and wait for quiet again rather than reconnect into
397            // contention.
398            if self.streaming.load(Ordering::SeqCst) == 0 {
399                return Some(permit);
400            }
401        }
402    }
403}
404
405/// Holds a [`ReconnectCoordinator`]'s streaming count for the lifetime of one
406/// connection; decrements and wakes parked siblings on drop.
407#[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
423/// Sleep for `delay`, returning early on cancellation. Returns `true` if the
424/// sleep completed, `false` if cancelled.
425pub(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
432/// A managed control WebSocket stream.
433pub(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
439/// Serialize and send a `BacktestRequest` over a control WebSocket.
440pub(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    /// The server reported the session done, or the driver dropped the request channel.
449    SessionEnded,
450    /// Cancellation token fired. Still graceful-closes so the server reaps the
451    /// runtime now instead of after the disconnect timeout.
452    Cancelled,
453    /// Connection lost — attempt to reconnect.
454    ConnectionLost(String),
455    Terminal,
456}
457
458/// Publish a `ConnectionStatus` transition, suppressing no-op updates.
459pub(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
473/// Send `CloseBacktestSession` then the WS close frame, bounded by a single
474/// [`GRACEFUL_CLOSE_TIMEOUT`] budget. The close request makes the server reap
475/// the runtime(s) immediately instead of waiting out the disconnect timeout; the
476/// close frame is best-effort cleanup.
477pub(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
487/// An inbound control frame, classified for the message loop.
488pub(super) enum InboundFrame {
489    /// A text (or UTF-8 binary) payload to parse.
490    Text(String),
491    /// A frame with no application payload (ping/pong/raw/non-UTF-8 binary).
492    Ignore,
493    /// The connection ended or errored; carries the loss reason.
494    Lost(String),
495}
496
497/// Classify the result of `ws.next()` for a control message loop.
498pub(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
512/// Send a keepalive ping unless inbound traffic has been silent past the
513/// deadline. Returns the loss reason if the connection should be considered
514/// dead, else `None`.
515pub(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(); // streaming == 1, so a slot request must park
569
570        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        // While a sibling streams, the parked request stays pending.
577        tokio::task::yield_now().await;
578        assert!(!waiter.is_finished());
579
580        drop(guard); // streaming -> 0, wakes the parked request
581        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(); // keep the link busy so the request parks
588        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        // A long park must leave the full attempt budget intact afterwards.
597        b.discount_parked(2 * RECONNECT_MAX_TOTAL);
598        for _ in 0..RECONNECT_MAX_ATTEMPTS {
599            assert!(b.next_backoff().is_some());
600        }
601    }
602}