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.
128pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
129
130/// State of one managed connection: the session control channel or a subscription.
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub enum ConnectionStatus {
133    /// Connected and, for a subscription, subscribed.
134    Up,
135    /// Not connected yet, or reconnecting.
136    Down,
137    /// The session is over. Not a connection failure.
138    Ended,
139    /// Gave up. Terminal.
140    Failed(ConnectionFailure),
141}
142
143/// Why a managed connection gave up.
144#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
145pub enum ConnectionFailure {
146    /// The retry budget ran out.
147    #[error("{0}")]
148    RetriesExhausted(String),
149    /// The session's endpoint rejected the token.
150    #[error("the session's endpoint rejected the token")]
151    TokenRejected,
152    /// The session has ended.
153    #[error("the session ended; the server no longer tracks it")]
154    SessionEnded,
155    /// The server refused the connection.
156    #[error("{0}")]
157    Refused(String),
158}
159
160/// What the server reported when it created the session.
161#[derive(Clone)]
162#[non_exhaustive]
163pub struct SessionInfo {
164    #[allow(missing_docs)]
165    pub session_id: SessionId,
166    /// A session of a parallel run carries the run's name.
167    pub session_name: Option<String>,
168    /// Absolute `http(s)` JSON-RPC URL for chain reads at the session's slot; serves state from
169    /// the first `ReadyForContinue` until `Completed` (502 after). Use
170    /// [`ManagedBacktestSession::rpc`], or pass it to `RpcClient::new`.
171    pub rpc_endpoint: String,
172    /// Opaque `task_id` reported by the server for this session, if any.
173    pub task_id: Option<String>,
174    /// Keep `grant.session_id` to attach from a new process.
175    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/// Parameters shared by [`ManagedBacktestSession`] and
213/// [`ManagedParallelSession`] startup.
214///
215/// A standalone session only needs `url`, `api_key` and `create`; the rest
216/// default to no extra headers, a session-owned cancellation token and its own
217/// counters.
218#[derive(Debug, Clone, Builder)]
219pub struct StartSessionParams {
220    /// The server's address. The builder normalizes it with [`crate::backtest_ws_url`]: a bare
221    /// host becomes `wss://<host>/backtest`, and a `ws://` or `wss://` URL gains `/backtest`
222    /// if it lacks it.
223    #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
224    pub url: String,
225    /// Your API key, sent as the `X-API-Key` header.
226    pub api_key: String,
227    /// Extra headers sent to the server when the session is created, beside the API key.
228    #[builder(default)]
229    pub extra_headers: HeaderMap,
230    /// The create request, built with [`crate::CreateSession`] and its `into_request`. Set
231    /// `parallel` on it to start a [`ManagedParallelSession`].
232    pub create: CreateBacktestSessionRequest,
233    /// Cancelling this aborts startup, or stops a started session; its calls then return
234    /// [`ManagedSessionError::Cancelled`] from `next_event`.
235    #[builder(default)]
236    pub parent_cancel: CancellationToken,
237    /// Collects counters from every subscription the session spawns;
238    /// share one across sessions to aggregate a whole run.
239    #[builder(default)]
240    pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
241}
242
243/// Subscription diagnostics counters, shared across every subscription manager a
244/// run spawns.
245#[derive(Debug, Default)]
246pub struct SubscriptionDiagnostics {
247    /// Excludes each subscription task's first connection.
248    reconnects: AtomicU64,
249}
250
251impl SubscriptionDiagnostics {
252    pub(crate) fn record_reconnect(&self) {
253        self.reconnects.fetch_add(1, Ordering::Relaxed);
254    }
255
256    /// Subscription reconnects so far, across every session sharing these counters. First
257    /// connections do not count.
258    pub fn reconnects(&self) -> u64 {
259        self.reconnects.load(Ordering::Relaxed)
260    }
261}
262
263/// Tracks reconnect attempts and enforces the reconnect policy.
264pub(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    /// Discount time the subscription spent parked behind the reconnect
290    /// coordinator. Parking is deliberate waiting for siblings to free the
291    /// link, not retry thrashing, so it must not count against the wall-clock
292    /// budget — otherwise a session that correctly steps aside for minutes is
293    /// failed the moment it reconnects. The attempt-count ceiling still bounds
294    /// total retries.
295    pub fn discount_parked(&mut self, parked: Duration) {
296        self.started_at += parked;
297    }
298
299    /// Record an attempt and return its backoff, or `None` if the budget is
300    /// exhausted.
301    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/// Coordinates subscription reconnects across a parallel batch sharing one
320/// bandwidth-constrained link.
321///
322/// A dropped subscription competing with its still-streaming siblings just
323/// starves — the handshake can't get through a saturated pipe. So once a session
324/// has burned its fast ungated attempts, it stops fighting and **parks until no
325/// sibling is streaming** (the connected sessions have finished and freed their
326/// bandwidth), then reconnects into the quiet link and resumes via
327/// `replayFromSlot`. Stepping aside also speeds the streaming siblings up, so the
328/// batch drains and the parked sessions recover — serially, one at a time, since
329/// at a tight rate only one stream fits.
330#[doc(hidden)]
331pub struct ReconnectCoordinator {
332    /// Subscriptions currently `Up` and streaming. A parked session waits for
333    /// this to reach zero before reconnecting.
334    streaming: AtomicUsize,
335    /// Woken whenever `streaming` decreases, so parked sessions re-check.
336    drained: Notify,
337    /// One in-flight reconnect handshake at a time, so the all-parked case
338    /// recovers serially rather than storming the link the moment it goes quiet.
339    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    /// Mark this subscription as streaming until the returned guard drops.
358    /// Call once a (re)subscribe succeeds; the guard's `Drop` decrements the
359    /// count and wakes any sibling parked in [`Self::reconnect_slot`]. RAII so
360    /// a panicking or aborted task can't leak the count and wedge the batch.
361    pub fn enter(self: &Arc<Self>) -> StreamingGuard {
362        self.streaming.fetch_add(1, Ordering::SeqCst);
363        StreamingGuard(self.clone())
364    }
365
366    /// Park until no sibling is streaming, then take the single reconnect slot.
367    /// The returned permit must be held across connect + subscribe and dropped
368    /// once [`Self::enter`] has been called (or the attempt failed), so the next
369    /// parked session proceeds only after this one is streaming again. Returns
370    /// `None` if cancelled.
371    pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
372        loop {
373            // Wait for the link to go quiet. Register interest before reading so
374            // a `leave()` between the check and the wait isn't lost.
375            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            // A sibling may have re-entered while we queued for the permit; if so,
392            // release it and wait for quiet again rather than reconnect into
393            // contention.
394            if self.streaming.load(Ordering::SeqCst) == 0 {
395                return Some(permit);
396            }
397        }
398    }
399}
400
401/// Holds a [`ReconnectCoordinator`]'s streaming count for the lifetime of one
402/// connection; decrements and wakes parked siblings on drop.
403#[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
419/// Sleep for `delay`, returning early on cancellation. Returns `true` if the
420/// sleep completed, `false` if cancelled.
421pub(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
428/// A managed control WebSocket stream.
429pub(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
435/// Serialize and send a `BacktestRequest` over a control WebSocket.
436pub(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    /// The server reported the session done, or the driver dropped the request channel.
445    SessionEnded,
446    /// Cancellation token fired. Still graceful-closes so the server reaps the
447    /// runtime now instead of after the disconnect timeout.
448    Cancelled,
449    /// Connection lost — attempt to reconnect.
450    ConnectionLost(String),
451    Terminal,
452}
453
454/// Publish a `ConnectionStatus` transition, suppressing no-op updates.
455pub(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
469/// Send `CloseBacktestSession` then the WS close frame, bounded by a single
470/// [`GRACEFUL_CLOSE_TIMEOUT`] budget. The close request makes the server reap
471/// the runtime(s) immediately instead of waiting out the disconnect timeout; the
472/// close frame is best-effort cleanup.
473pub(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
481/// An inbound control frame, classified for the message loop.
482pub(super) enum InboundFrame {
483    /// A text (or UTF-8 binary) payload to parse.
484    Text(String),
485    /// A frame with no application payload (ping/pong/raw/non-UTF-8 binary).
486    Ignore,
487    /// The connection ended or errored; carries the loss reason.
488    Lost(String),
489}
490
491/// Classify the result of `ws.next()` for a control message loop.
492pub(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
506/// Send a keepalive ping unless inbound traffic has been silent past the
507/// deadline. Returns the loss reason if the connection should be considered
508/// dead, else `None`.
509pub(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(); // streaming == 1, so a slot request must park
563
564        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        // While a sibling streams, the parked request stays pending.
571        tokio::task::yield_now().await;
572        assert!(!waiter.is_finished());
573
574        drop(guard); // streaming -> 0, wakes the parked request
575        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(); // keep the link busy so the request parks
582        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        // A long park must leave the full attempt budget intact afterwards.
591        b.discount_parked(2 * RECONNECT_MAX_TOTAL);
592        for _ in 0..RECONNECT_MAX_ATTEMPTS {
593            assert!(b.next_backoff().is_some());
594        }
595    }
596}