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//! - opens the session control channel and returns once the server has created the session;
7//! - opens one WebSocket on the session's RPC endpoint per `subscribe_*` call;
8//! - waits until every connection is up before it sends a continue;
9//! - reconnects a dropped connection and reattaches to the session;
10//! - closes the session on `shutdown`.
11//!
12//! # Connection drops
13//!
14//! - A dropped connection is retried with backoff, up to [`RECONNECT_MAX_ATTEMPTS`] attempts
15//!   within [`RECONNECT_MAX_TOTAL`]. The session keeps running on the server meanwhile.
16//! - The session control channel reattaches and the server replays the responses you missed.
17//!   You see no gap.
18//! - A subscription resumes from the last slot it delivered and sends that slot again: dedupe
19//!   transactions by signature, and account diffs by (signature, account, slot).
20//! - When the budget runs out, the next continue fails with
21//!   [`ManagedSessionError::ControlFailed`] or [`ManagedSessionError::SubscriptionFailed`].
22//! - A rejected API key (HTTP 401 or 403) is never retried: `start` fails with
23//!   [`ManagedSessionError::ApiKeyRejected`].
24
25use 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/// Timeout for the initial WebSocket connect (TCP + TLS + HTTP upgrade).
70#[doc(hidden)]
71pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
72
73/// Timeout for each server response while a connection is set up: the create, reattach and
74/// subscribe replies. An established connection is checked with pings instead
75/// ([`KEEPALIVE_MISS_DEADLINE`]).
76// Generous because the server can hold a subscribe until the session has started (~100 s on a
77// cold start); a shorter timeout reports a healthy session as "subscribe ack timeout".
78#[doc(hidden)]
79pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
80
81/// How often to send a WebSocket ping during an established connection.
82#[doc(hidden)]
83pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
84
85/// How long without inbound traffic before declaring the connection dead.
86/// Roughly three missed pings.
87#[doc(hidden)]
88pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
89
90/// Total budget for the graceful close handshake (close request + close frame).
91/// A supervisor's SIGTERM→SIGKILL grace must exceed this or the close is cut short.
92#[doc(hidden)]
93pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
94
95/// Wait before the first retry. Each later wait is [`RECONNECT_BACKOFF_MULTIPLIER`] times the
96/// previous one, up to [`RECONNECT_MAX_BACKOFF`].
97#[doc(hidden)]
98pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
99/// Longest wait between two retries.
100#[doc(hidden)]
101pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
102/// Factor applied to the wait after each failed retry.
103#[doc(hidden)]
104pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
105/// Random spread of each wait, as a fraction: `0.2` is ±20%.
106#[doc(hidden)]
107pub const RECONNECT_JITTER: f64 = 0.2;
108/// Time budget for retrying one connection. When it, or [`RECONNECT_MAX_ATTEMPTS`], runs out,
109/// the connection becomes [`ConnectionStatus::Failed`].
110pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
111/// Attempt budget for retrying one connection. See [`RECONNECT_MAX_TOTAL`].
112pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
113
114/// In a parallel run, the retries a dropped subscription makes right away. After these, it
115/// waits until the run's other sessions stop streaming, then reconnects into the freed link.
116#[doc(hidden)]
117pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
118
119/// A connection that stays `Up` for this long gets its full retry budget back.
120#[doc(hidden)]
121pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
122
123/// How long the server keeps a session alive with no client attached, when a single
124/// session's create leaves `disconnect_timeout_secs` unset.
125///
126/// Covers the whole retry budget ([`RECONNECT_MAX_TOTAL`]) plus a minute to reattach, so a
127/// server restart does not lose the session. Stays under the server's cap
128/// ([`simulator_api::MAX_DISCONNECT_TIMEOUT_SECS`]). A parallel run keeps the server's own
129/// default.
130pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
131
132/// State of one managed connection: the session control channel or a subscription.
133#[derive(Clone, Debug, PartialEq, Eq)]
134pub enum ConnectionStatus {
135    /// Connected and, for a subscription, subscribed.
136    Up,
137    /// Not connected yet, or reconnecting.
138    Down,
139    /// Gave up, for the reason given. Terminal: the retry budget ran out, the API key was
140    /// rejected, or the server ended the session.
141    Failed(String),
142}
143
144/// What the server reported when it created the session.
145#[derive(Clone, Debug)]
146pub struct SessionInfo {
147    #[allow(missing_docs)]
148    pub session_id: SessionId,
149    /// A session of a parallel run carries the run's name.
150    pub session_name: Option<String>,
151    /// Absolute `http(s)` JSON-RPC URL for chain reads at the session's slot; serves state from
152    /// the first `ReadyForContinue` until `Completed` (502 after). Use
153    /// [`ManagedBacktestSession::rpc`], or pass it to `RpcClient::new`.
154    pub rpc_endpoint: String,
155    /// Opaque `task_id` reported by the server for this session, if any.
156    pub task_id: Option<String>,
157}
158
159/// Parameters shared by [`ManagedBacktestSession`] and
160/// [`ManagedParallelSession`] startup.
161///
162/// A standalone session only needs `url`, `api_key` and `create`; the rest
163/// default to no extra headers, a session-owned cancellation token and its own
164/// counters.
165#[derive(Debug, Clone, Builder)]
166pub struct StartSessionParams {
167    /// The server's address. The builder normalizes it with [`crate::backtest_ws_url`]: a bare
168    /// host becomes `wss://<host>/backtest`, and a `ws://` or `wss://` URL gains `/backtest`
169    /// if it lacks it.
170    #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
171    pub url: String,
172    /// Your API key, sent as the `X-API-Key` header.
173    pub api_key: String,
174    /// Extra headers sent when the session control channel connects, beside the API key.
175    #[builder(default)]
176    pub extra_headers: HeaderMap,
177    /// The create request, built with [`crate::CreateSession`] and its `into_request`. Set
178    /// `parallel` on it to start a [`ManagedParallelSession`].
179    pub create: CreateBacktestSessionRequest,
180    /// Cancelling this aborts startup, or stops a started session; its calls then return
181    /// [`ManagedSessionError::Cancelled`] from `next_event`.
182    #[builder(default)]
183    pub parent_cancel: CancellationToken,
184    /// Collects counters from every subscription the session spawns;
185    /// share one across sessions to aggregate a whole run.
186    #[builder(default)]
187    pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
188}
189
190/// Subscription diagnostics counters, shared across every subscription manager a
191/// run spawns.
192#[derive(Debug, Default)]
193pub struct SubscriptionDiagnostics {
194    /// Excludes each subscription task's first connection.
195    reconnects: AtomicU64,
196}
197
198impl SubscriptionDiagnostics {
199    pub(crate) fn record_reconnect(&self) {
200        self.reconnects.fetch_add(1, Ordering::Relaxed);
201    }
202
203    /// Subscription reconnects so far, across every session sharing these counters. First
204    /// connections do not count.
205    pub fn reconnects(&self) -> u64 {
206        self.reconnects.load(Ordering::Relaxed)
207    }
208}
209
210/// Tracks reconnect attempts and enforces the reconnect policy.
211pub(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    /// Discount time the subscription spent parked behind the reconnect
237    /// coordinator. Parking is deliberate waiting for siblings to free the
238    /// link, not retry thrashing, so it must not count against the wall-clock
239    /// budget — otherwise a session that correctly steps aside for minutes is
240    /// failed the moment it reconnects. The attempt-count ceiling still bounds
241    /// total retries.
242    pub fn discount_parked(&mut self, parked: Duration) {
243        self.started_at += parked;
244    }
245
246    /// Record an attempt and return its backoff, or `None` if the budget is
247    /// exhausted.
248    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/// Coordinates subscription reconnects across a parallel batch sharing one
267/// bandwidth-constrained link.
268///
269/// A dropped subscription competing with its still-streaming siblings just
270/// starves — the handshake can't get through a saturated pipe. So once a session
271/// has burned its fast ungated attempts, it stops fighting and **parks until no
272/// sibling is streaming** (the connected sessions have finished and freed their
273/// bandwidth), then reconnects into the quiet link and resumes via
274/// `replayFromSlot`. Stepping aside also speeds the streaming siblings up, so the
275/// batch drains and the parked sessions recover — serially, one at a time, since
276/// at a tight rate only one stream fits.
277#[doc(hidden)]
278pub struct ReconnectCoordinator {
279    /// Subscriptions currently `Up` and streaming. A parked session waits for
280    /// this to reach zero before reconnecting.
281    streaming: AtomicUsize,
282    /// Woken whenever `streaming` decreases, so parked sessions re-check.
283    drained: Notify,
284    /// One in-flight reconnect handshake at a time, so the all-parked case
285    /// recovers serially rather than storming the link the moment it goes quiet.
286    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    /// Mark this subscription as streaming until the returned guard drops.
305    /// Call once a (re)subscribe succeeds; the guard's `Drop` decrements the
306    /// count and wakes any sibling parked in [`Self::reconnect_slot`]. RAII so
307    /// a panicking or aborted task can't leak the count and wedge the batch.
308    pub fn enter(self: &Arc<Self>) -> StreamingGuard {
309        self.streaming.fetch_add(1, Ordering::SeqCst);
310        StreamingGuard(self.clone())
311    }
312
313    /// Park until no sibling is streaming, then take the single reconnect slot.
314    /// The returned permit must be held across connect + subscribe and dropped
315    /// once [`Self::enter`] has been called (or the attempt failed), so the next
316    /// parked session proceeds only after this one is streaming again. Returns
317    /// `None` if cancelled.
318    pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
319        loop {
320            // Wait for the link to go quiet. Register interest before reading so
321            // a `leave()` between the check and the wait isn't lost.
322            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            // A sibling may have re-entered while we queued for the permit; if so,
339            // release it and wait for quiet again rather than reconnect into
340            // contention.
341            if self.streaming.load(Ordering::SeqCst) == 0 {
342                return Some(permit);
343            }
344        }
345    }
346}
347
348/// Holds a [`ReconnectCoordinator`]'s streaming count for the lifetime of one
349/// connection; decrements and wakes parked siblings on drop.
350#[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
366/// Sleep for `delay`, returning early on cancellation. Returns `true` if the
367/// sleep completed, `false` if cancelled.
368pub(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
375/// A managed control WebSocket stream.
376pub(super) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
377
378/// Why [`connect_ws`] failed.
379pub(super) enum ConnectError {
380    /// The upgrade was refused with 401/403: the key is bad, so retrying only
381    /// stalls the caller for the whole reconnect budget.
382    ApiKeyRejected(StatusCode),
383    /// Anything else, worth retrying.
384    Other(String),
385}
386
387/// Open a control WebSocket to `url`, attaching `extra_headers` and the API-key
388/// and identity headers, bounded by [`CONNECT_TIMEOUT`]. Shared by the
389/// single-session and parallel managers.
390pub(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
431/// Serialize and send a `BacktestRequest` over a control WebSocket.
432pub(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
439/// Resolve a server-reported `rpc_endpoint` to an absolute URL: pass through an
440/// already-absolute endpoint, otherwise join it onto the control `base`.
441pub(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
449/// Outcome of a control-WS handshake (create/attach/resume).
450pub(super) enum HandshakeError {
451    /// Recoverable (network blip, or the session is momentarily contended).
452    Transient(String),
453    /// Unrecoverable — the server rejected the session outright.
454    Fatal(CreateError),
455}
456
457/// Classify a `BacktestError` returned during a handshake `stage`: a contended
458/// session is expected to become claimable shortly (transient); anything else is
459/// fatal.
460pub(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
472/// Why a control task's message loop exited. Shared by the single-session and
473/// parallel control managers.
474pub(super) enum MessageLoopExit {
475    /// Server reported the session(s) done, or the driver(s) dropped the request
476    /// channel. Calls for a graceful WS close.
477    SessionEnded,
478    /// Cancellation token fired. Still graceful-closes so the server reaps the
479    /// runtime now instead of after the disconnect timeout.
480    Cancelled,
481    /// Connection lost — attempt to reconnect.
482    ConnectionLost(String),
483    /// Protocol or application error with no sensible recovery.
484    Terminal(String),
485}
486
487/// Publish a `ConnectionStatus` transition, suppressing no-op updates.
488pub(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
502/// Send `CloseBacktestSession` then the WS close frame, bounded by a single
503/// [`GRACEFUL_CLOSE_TIMEOUT`] budget. The close request makes the server reap
504/// the runtime(s) immediately instead of waiting out the disconnect timeout; the
505/// close frame is best-effort cleanup.
506pub(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
514/// An inbound control frame, classified for the message loop.
515pub(super) enum InboundFrame {
516    /// A text (or UTF-8 binary) payload to parse.
517    Text(String),
518    /// A frame with no application payload (ping/pong/raw/non-UTF-8 binary).
519    Ignore,
520    /// The connection ended or errored; carries the loss reason.
521    Lost(String),
522}
523
524/// Classify the result of `ws.next()` for a control message loop.
525pub(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
539/// Send a keepalive ping unless inbound traffic has been silent past the
540/// deadline. Returns the loss reason if the connection should be considered
541/// dead, else `None`.
542pub(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
552/// A control WebSocket task: connect, handshake, run a message loop, reconnect.
553/// [`run_control_loop`] drives the shared connect/backoff/exit state machine;
554/// implementors supply the protocol-specific handshake and message loop.
555pub(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    /// Prefix for reconnect log lines, e.g. `"control"` / `"parallel control"`.
561    fn label(&self) -> &'static str;
562    fn status_tx(&self) -> &watch::Sender<ConnectionStatus>;
563    /// Fail the pending create one-shot with `error` (no-op once fired).
564    fn fail_pending(&mut self, error: ManagedSessionError);
565    /// Create on first connect, attach/resume on reconnect.
566    fn handshake(&mut self, ws: Ws) -> impl Future<Output = Result<Ws, HandshakeError>> + Send;
567    /// Drive the established connection until it exits.
568    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
580/// Drive a [`ControlConnection`] through its connect → handshake → run →
581/// reconnect lifecycle until the session ends, is cancelled, or the reconnect
582/// budget is exhausted.
583pub(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                // The create resolved before the message loop started: nothing is pending.
654                task.publish(ConnectionStatus::Failed(why));
655                return;
656            }
657        }
658    }
659}
660
661#[cfg(test)]
662mod tests {
663    use super::*;
664
665    /// The request head `connect_ws` sends with API key `k`. Never completes the handshake;
666    /// the headers are in the request head.
667    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    /// The only connect path that sends the managed form.
695    #[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(); // streaming == 1, so a slot request must park
758
759        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        // While a sibling streams, the parked request stays pending.
766        tokio::task::yield_now().await;
767        assert!(!waiter.is_finished());
768
769        drop(guard); // streaming -> 0, wakes the parked request
770        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(); // keep the link busy so the request parks
777        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        // A long park must leave the full attempt budget intact afterwards.
786        b.discount_parked(2 * RECONNECT_MAX_TOTAL);
787        for _ in 0..RECONNECT_MAX_ATTEMPTS {
788            assert!(b.next_backoff().is_some());
789        }
790    }
791}