Skip to main content

simulator_client/managed/
mod.rs

1//! Connection-managed wrappers over the backtest WebSocket protocol.
2//!
3//! Most callers should use [`ManagedBacktestSession`]. It owns the control and
4//! subscription manager tasks, waits for session creation, gates `Continue`
5//! sends on live connections, and provides one shutdown path.
6//!
7//! The control and subscription WebSockets are each owned by a dedicated task
8//! that handles its own lifecycle: connect, handshake, keepalive, reconnect.
9//! Workload code interacts via channels and a status watcher, never with the
10//! WebSocket directly.
11//!
12//! Reconnect doubles as session handoff. The management service closes live
13//! control WebSockets with code `1012` when it is redeployed; the session
14//! itself keeps running and waits to be claimed. The control task's reconnect
15//! handshake sends `AttachBacktestSession` + `ResumeAttachedSession` instead of
16//! a create, so the session resumes with the responses missed in between
17//! replayed from the last observed sequence number. Nothing above this layer
18//! observes the restart beyond a [`ConnectionStatus::Down`] blip.
19
20use std::{
21    future::Future,
22    sync::{
23        Arc,
24        atomic::{AtomicU64, AtomicUsize, Ordering},
25    },
26    time::{Duration, Instant},
27};
28
29use bon::Builder;
30use futures::SinkExt;
31use http::HeaderMap;
32use rand::RngExt;
33use simulator_api::{
34    BacktestError, BacktestRequest, CreateBacktestSessionRequest, SessionId,
35    client_identity::{ClientProduct, ClientSurface},
36};
37use tokio::{
38    net::TcpStream,
39    sync::{Notify, OwnedSemaphorePermit, Semaphore, watch},
40};
41use tokio_tungstenite::{
42    MaybeTlsStream, WebSocketStream, connect_async,
43    tungstenite::{Error as WsError, Message, client::IntoClientRequest, http::HeaderValue},
44};
45use tokio_util::sync::CancellationToken;
46use tracing::warn;
47
48use crate::{error::err_chain, urls::backtest_ws_url};
49
50mod control;
51mod parallel;
52mod session;
53mod subscription;
54
55pub use control::{ControlEvent, ControlHandle, spawn_control_manager};
56pub use parallel::{ManagedParallelSession, ParallelSubSession};
57pub use session::{ManagedBacktestSession, ManagedEvent, ManagedSessionError};
58pub use subscription::{
59    SubscriptionHandle, SubscriptionNotification, spawn_account_diff_subscription_manager,
60    spawn_action_subscription_manager, spawn_diagnostic_subscription_manager,
61    spawn_replacement_subscription_manager, spawn_transaction_subscription_manager,
62};
63
64/// Timeout for the initial WebSocket connect (TCP + TLS + HTTP upgrade).
65pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
66
67/// Timeout for any single response during a handshake (Create, Attach, Resume,
68/// subscribe ack). Does not apply to per-message reads during an established
69/// session — those are bounded by ping/pong liveness instead.
70///
71/// Set generously because the management service can park subscribe upgrades
72/// for the duration of session startup (observed ~100s on cold runtimes); a
73/// shorter timeout fires before management can forward the subscribe message
74/// and gets reported as "subscribe ack timeout" even though the session is
75/// fine. The proper fix is server-side (reject parked upgrades cleanly), but
76/// this keeps the client from giving up early in the meantime.
77pub const HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
78
79/// How often to send a WebSocket ping during an established connection.
80pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
81
82/// How long without inbound traffic before declaring the connection dead.
83/// Roughly three missed pings.
84pub const KEEPALIVE_MISS_DEADLINE: Duration = Duration::from_secs(45);
85
86/// Total budget for the graceful close handshake (close request + close frame).
87/// A supervisor's SIGTERM→SIGKILL grace must exceed this or the close is cut short.
88pub const GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
89
90pub const RECONNECT_INITIAL_BACKOFF: Duration = Duration::from_secs(1);
91pub const RECONNECT_MAX_BACKOFF: Duration = Duration::from_secs(30);
92pub const RECONNECT_BACKOFF_MULTIPLIER: f64 = 2.0;
93pub const RECONNECT_JITTER: f64 = 0.2;
94pub const RECONNECT_MAX_TOTAL: Duration = Duration::from_secs(5 * 60);
95pub const RECONNECT_MAX_ATTEMPTS: u32 = 20;
96
97/// Reconnect attempts that fire immediately, before the cross-session reconnect
98/// gate engages. A transient drop recovers fast; only once these rapid retries
99/// are exhausted does a session fall back to waiting for siblings to drain.
100pub const RECONNECT_UNGATED_ATTEMPTS: u32 = 5;
101
102/// A connection that stays `Up` for this long resets the reconnect counter.
103pub const RECONNECT_UPTIME_RESET: Duration = Duration::from_secs(30);
104
105/// `disconnect_timeout_secs` applied to a single-session create that leaves it
106/// unset — how long the server keeps the session alive with no client attached.
107///
108/// The server's own default is tens of seconds, which is shorter than the
109/// reconnect budget below: a session whose management host is redeployed gets
110/// reclaimed while this client is still retrying. Cover the whole budget plus a
111/// margin for the attach + resume handshake. Stays under the server's cap
112/// ([`simulator_api::MAX_DISCONNECT_TIMEOUT_SECS`]).
113pub const DEFAULT_DISCONNECT_TIMEOUT_SECS: u16 = RECONNECT_MAX_TOTAL.as_secs() as u16 + 60;
114
115/// Connection state as observed from outside the manager task.
116///
117/// `Down` is a transient "currently not connected, manager is retrying"
118/// state. `Failed` is terminal; the retry budget was exhausted.
119#[derive(Clone, Debug, PartialEq, Eq)]
120pub enum ConnectionStatus {
121    Up,
122    Down,
123    Failed(String),
124}
125
126/// Identity of a created backtest session.
127#[derive(Clone, Debug)]
128pub struct SessionInfo {
129    pub session_id: SessionId,
130    /// A parallel sub-session carries its run's name.
131    pub session_name: Option<String>,
132    pub rpc_endpoint: String,
133    /// Opaque `task_id` reported by the server for this session, if any.
134    pub task_id: Option<String>,
135}
136
137/// Parameters shared by [`ManagedBacktestSession`] and
138/// [`ManagedParallelSession`] startup.
139///
140/// A standalone session only needs `url`, `api_key` and `create`; the rest
141/// default to no extra headers, a session-owned cancellation token and its own
142/// counters.
143#[derive(Debug, Clone, Builder)]
144pub struct StartSessionParams {
145    /// Backtest WebSocket base URL.
146    #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
147    pub url: String,
148    pub api_key: String,
149    /// Extra headers sent on the control websocket handshake, beside the API key.
150    #[builder(default)]
151    pub extra_headers: HeaderMap,
152    pub create: CreateBacktestSessionRequest,
153    /// Cancelling this aborts startup and stops the manager tasks.
154    #[builder(default)]
155    pub parent_cancel: CancellationToken,
156    /// Collects data-plane counters from every subscription the session spawns;
157    /// share one across sessions to aggregate a whole run.
158    #[builder(default)]
159    pub subscription_diagnostics: Arc<SubscriptionDiagnostics>,
160}
161
162/// Data-plane diagnostics counters, shared across every subscription manager a
163/// run spawns.
164#[derive(Debug, Default)]
165pub struct SubscriptionDiagnostics {
166    /// Excludes each subscription task's first connection.
167    reconnects: AtomicU64,
168}
169
170impl SubscriptionDiagnostics {
171    pub(crate) fn record_reconnect(&self) {
172        self.reconnects.fetch_add(1, Ordering::Relaxed);
173    }
174
175    pub fn reconnects(&self) -> u64 {
176        self.reconnects.load(Ordering::Relaxed)
177    }
178}
179
180/// Tracks reconnect attempts and enforces the reconnect policy.
181pub(crate) struct ReconnectBudget {
182    attempts: u32,
183    started_at: std::time::Instant,
184    current_backoff: Duration,
185}
186
187impl ReconnectBudget {
188    pub fn new() -> Self {
189        Self {
190            attempts: 0,
191            started_at: std::time::Instant::now(),
192            current_backoff: RECONNECT_INITIAL_BACKOFF,
193        }
194    }
195
196    pub fn reset(&mut self) {
197        self.attempts = 0;
198        self.started_at = std::time::Instant::now();
199        self.current_backoff = RECONNECT_INITIAL_BACKOFF;
200    }
201
202    pub fn attempt(&self) -> u32 {
203        self.attempts
204    }
205
206    /// Discount time the subscription spent parked behind the reconnect
207    /// coordinator. Parking is deliberate waiting for siblings to free the
208    /// link, not retry thrashing, so it must not count against the wall-clock
209    /// budget — otherwise a session that correctly steps aside for minutes is
210    /// failed the moment it reconnects. The attempt-count ceiling still bounds
211    /// total retries.
212    pub fn discount_parked(&mut self, parked: Duration) {
213        self.started_at += parked;
214    }
215
216    /// Record an attempt and return its backoff, or `None` if the budget is
217    /// exhausted.
218    pub fn next_backoff(&mut self) -> Option<Duration> {
219        if self.attempts >= RECONNECT_MAX_ATTEMPTS
220            || self.started_at.elapsed() >= RECONNECT_MAX_TOTAL
221        {
222            return None;
223        }
224        self.attempts += 1;
225        let backoff = with_jitter(self.current_backoff);
226        self.current_backoff = std::cmp::min(
227            RECONNECT_MAX_BACKOFF,
228            Duration::from_secs_f64(
229                self.current_backoff.as_secs_f64() * RECONNECT_BACKOFF_MULTIPLIER,
230            ),
231        );
232        Some(backoff)
233    }
234}
235
236/// Coordinates subscription reconnects across a parallel batch sharing one
237/// bandwidth-constrained link.
238///
239/// A dropped subscription competing with its still-streaming siblings just
240/// starves — the handshake can't get through a saturated pipe. So once a session
241/// has burned its fast ungated attempts, it stops fighting and **parks until no
242/// sibling is streaming** (the connected sessions have finished and freed their
243/// bandwidth), then reconnects into the quiet link and resumes via
244/// `replayFromSlot`. Stepping aside also speeds the streaming siblings up, so the
245/// batch drains and the parked sessions recover — serially, one at a time, since
246/// at a tight rate only one stream fits.
247pub struct ReconnectCoordinator {
248    /// Subscriptions currently `Up` and streaming. A parked session waits for
249    /// this to reach zero before reconnecting.
250    streaming: AtomicUsize,
251    /// Woken whenever `streaming` decreases, so parked sessions re-check.
252    drained: Notify,
253    /// One in-flight reconnect handshake at a time, so the all-parked case
254    /// recovers serially rather than storming the link the moment it goes quiet.
255    handshake: Arc<Semaphore>,
256}
257
258impl Default for ReconnectCoordinator {
259    fn default() -> Self {
260        Self::new()
261    }
262}
263
264impl ReconnectCoordinator {
265    pub fn new() -> Self {
266        Self {
267            streaming: AtomicUsize::new(0),
268            drained: Notify::new(),
269            handshake: Arc::new(Semaphore::new(1)),
270        }
271    }
272
273    /// Mark this subscription as streaming until the returned guard drops.
274    /// Call once a (re)subscribe succeeds; the guard's `Drop` decrements the
275    /// count and wakes any sibling parked in [`Self::reconnect_slot`]. RAII so
276    /// a panicking or aborted task can't leak the count and wedge the batch.
277    pub fn enter(self: &Arc<Self>) -> StreamingGuard {
278        self.streaming.fetch_add(1, Ordering::SeqCst);
279        StreamingGuard(self.clone())
280    }
281
282    /// Park until no sibling is streaming, then take the single reconnect slot.
283    /// The returned permit must be held across connect + subscribe and dropped
284    /// once [`Self::enter`] has been called (or the attempt failed), so the next
285    /// parked session proceeds only after this one is streaming again. Returns
286    /// `None` if cancelled.
287    pub async fn reconnect_slot(&self, cancel: &CancellationToken) -> Option<OwnedSemaphorePermit> {
288        loop {
289            // Wait for the link to go quiet. Register interest before reading so
290            // a `leave()` between the check and the wait isn't lost.
291            loop {
292                let drained = self.drained.notified();
293                if self.streaming.load(Ordering::SeqCst) == 0 {
294                    break;
295                }
296                tokio::select! {
297                    biased;
298                    _ = cancel.cancelled() => return None,
299                    _ = drained => {}
300                }
301            }
302            let permit = tokio::select! {
303                biased;
304                _ = cancel.cancelled() => return None,
305                p = self.handshake.clone().acquire_owned() => p.ok()?,
306            };
307            // A sibling may have re-entered while we queued for the permit; if so,
308            // release it and wait for quiet again rather than reconnect into
309            // contention.
310            if self.streaming.load(Ordering::SeqCst) == 0 {
311                return Some(permit);
312            }
313        }
314    }
315}
316
317/// Holds a [`ReconnectCoordinator`]'s streaming count for the lifetime of one
318/// connection; decrements and wakes parked siblings on drop.
319pub struct StreamingGuard(Arc<ReconnectCoordinator>);
320
321impl Drop for StreamingGuard {
322    fn drop(&mut self) {
323        self.0.streaming.fetch_sub(1, Ordering::SeqCst);
324        self.0.drained.notify_waiters();
325    }
326}
327
328fn with_jitter(d: Duration) -> Duration {
329    let jitter = rand::rng().random_range(-RECONNECT_JITTER..RECONNECT_JITTER);
330    let secs = (d.as_secs_f64() * (1.0 + jitter)).max(0.0);
331    Duration::from_secs_f64(secs)
332}
333
334/// Sleep for `delay`, returning early on cancellation. Returns `true` if the
335/// sleep completed, `false` if cancelled.
336pub(crate) async fn cancellable_sleep(delay: Duration, cancel: &CancellationToken) -> bool {
337    tokio::select! {
338        _ = tokio::time::sleep(delay) => true,
339        _ = cancel.cancelled() => false,
340    }
341}
342
343/// A managed control WebSocket stream.
344pub(super) type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
345
346/// Open a control WebSocket to `url`, attaching `extra_headers` and the API-key
347/// and identity headers, bounded by [`CONNECT_TIMEOUT`]. Shared by the
348/// single-session and parallel managers.
349pub(super) async fn connect_ws(
350    url: &str,
351    api_key: &str,
352    extra_headers: &HeaderMap,
353) -> Result<Ws, String> {
354    let mut request = url
355        .into_client_request()
356        .map_err(|e| format!("build request: {}", err_chain(&e)))?;
357    request.headers_mut().extend(extra_headers.clone());
358    request.headers_mut().insert(
359        "X-API-Key",
360        HeaderValue::from_str(api_key).map_err(|e| format!("api key header: {}", err_chain(&e)))?,
361    );
362    request.headers_mut().insert(
363        "user-agent",
364        HeaderValue::from_str(&crate::client::user_agent(
365            ClientProduct::Sdk,
366            None,
367            ClientSurface::Managed,
368        ))
369        .map_err(|e| format!("build user-agent: {e}"))?,
370    );
371
372    let connect = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request))
373        .await
374        .map_err(|_| format!("connect timeout after {CONNECT_TIMEOUT:?}"))?
375        .map_err(|e| format!("connect: {}", err_chain(&e)))?;
376    Ok(connect.0)
377}
378
379/// Serialize and send a `BacktestRequest` over a control WebSocket.
380pub(super) async fn send_request(ws: &mut Ws, req: &BacktestRequest) -> Result<(), String> {
381    let text = serde_json::to_string(req).map_err(|e| format!("serialize: {}", err_chain(&e)))?;
382    ws.send(Message::Text(text))
383        .await
384        .map_err(|e| format!("send: {}", err_chain(&e)))
385}
386
387/// Resolve a server-reported `rpc_endpoint` to an absolute URL: pass through an
388/// already-absolute endpoint, otherwise join it onto the control `base`.
389pub(super) fn resolve_rpc_url(base: &str, endpoint: &str) -> String {
390    if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
391        endpoint.to_string()
392    } else {
393        format!("{}/{}", base, endpoint.trim_start_matches('/'))
394    }
395}
396
397/// Outcome of a control-WS handshake (create/attach/resume).
398pub(super) enum HandshakeError {
399    /// Recoverable (network blip, or the session is momentarily contended).
400    Transient(String),
401    /// Unrecoverable — the server rejected the session outright.
402    Fatal(String),
403}
404
405/// Classify a `BacktestError` returned during a handshake `stage`: a contended
406/// session is expected to become claimable shortly (transient); anything else is
407/// fatal.
408pub(super) fn handshake_error_for_response(
409    stage: &'static str,
410    err: BacktestError,
411) -> HandshakeError {
412    match err {
413        BacktestError::SessionOwnershipBusy { .. } => {
414            HandshakeError::Transient(format!("{stage} contended: {}", err_chain(&err)))
415        }
416        _ => HandshakeError::Fatal(format!("{stage} rejected: {}", err_chain(&err))),
417    }
418}
419
420/// Why a control task's message loop exited. Shared by the single-session and
421/// parallel control managers.
422pub(super) enum MessageLoopExit {
423    /// Server reported the session(s) done, or the driver(s) dropped the request
424    /// channel. Calls for a graceful WS close.
425    SessionEnded,
426    /// Cancellation token fired. Still graceful-closes so the server reaps the
427    /// runtime now instead of after the disconnect timeout.
428    Cancelled,
429    /// Connection lost — attempt to reconnect.
430    ConnectionLost(String),
431    /// Protocol or application error with no sensible recovery.
432    Terminal(String),
433}
434
435/// Publish a `ConnectionStatus` transition, suppressing no-op updates.
436pub(super) fn publish_status(
437    status_tx: &watch::Sender<ConnectionStatus>,
438    status: ConnectionStatus,
439) {
440    status_tx.send_if_modified(|current| {
441        if *current == status {
442            false
443        } else {
444            *current = status;
445            true
446        }
447    });
448}
449
450/// Send `CloseBacktestSession` then the WS close frame, bounded by a single
451/// [`GRACEFUL_CLOSE_TIMEOUT`] budget. The close request makes the server reap
452/// the runtime(s) immediately instead of waiting out the disconnect timeout; the
453/// close frame is best-effort cleanup.
454pub(super) async fn graceful_close(ws: &mut Ws) {
455    let _ = tokio::time::timeout(GRACEFUL_CLOSE_TIMEOUT, async {
456        let _ = send_request(ws, &BacktestRequest::CloseBacktestSession).await;
457        let _ = ws.close(None).await;
458    })
459    .await;
460}
461
462/// An inbound control frame, classified for the message loop.
463pub(super) enum InboundFrame {
464    /// A text (or UTF-8 binary) payload to parse.
465    Text(String),
466    /// A frame with no application payload (ping/pong/raw/non-UTF-8 binary).
467    Ignore,
468    /// The connection ended or errored; carries the loss reason.
469    Lost(String),
470}
471
472/// Classify the result of `ws.next()` for a control message loop.
473pub(super) fn classify_inbound(msg: Option<Result<Message, WsError>>) -> InboundFrame {
474    match msg {
475        Some(Ok(Message::Text(t))) => InboundFrame::Text(t),
476        Some(Ok(Message::Binary(b))) => match String::from_utf8(b) {
477            Ok(t) => InboundFrame::Text(t),
478            Err(_) => InboundFrame::Ignore,
479        },
480        Some(Ok(Message::Pong(_) | Message::Ping(_) | Message::Frame(_))) => InboundFrame::Ignore,
481        Some(Ok(Message::Close(frame))) => InboundFrame::Lost(format!("remote close: {frame:?}")),
482        Some(Err(e)) => InboundFrame::Lost(format!("ws read: {}", err_chain(&e))),
483        None => InboundFrame::Lost("ws stream ended".into()),
484    }
485}
486
487/// Send a keepalive ping unless inbound traffic has been silent past the
488/// deadline. Returns the loss reason if the connection should be considered
489/// dead, else `None`.
490pub(super) async fn send_keepalive_ping(ws: &mut Ws, last_inbound: Instant) -> Option<String> {
491    if last_inbound.elapsed() > KEEPALIVE_MISS_DEADLINE {
492        return Some(format!("no traffic for {:?}", last_inbound.elapsed()));
493    }
494    if let Err(e) = ws.send(Message::Ping(vec![])).await {
495        return Some(format!("ping send: {}", err_chain(&e)));
496    }
497    None
498}
499
500/// A control WebSocket task: connect, handshake, run a message loop, reconnect.
501/// [`run_control_loop`] drives the shared connect/backoff/exit state machine;
502/// implementors supply the protocol-specific handshake and message loop.
503pub(super) trait ControlConnection: Send + 'static {
504    fn url(&self) -> &str;
505    fn api_key(&self) -> &str;
506    fn extra_headers(&self) -> &HeaderMap;
507    fn cancel(&self) -> &CancellationToken;
508    /// Prefix for reconnect log lines, e.g. `"control"` / `"parallel control"`.
509    fn label(&self) -> &'static str;
510    fn status_tx(&self) -> &watch::Sender<ConnectionStatus>;
511    /// Fail the pending create one-shot with `reason` (no-op once fired).
512    fn fail_pending(&mut self, reason: String);
513    /// Create on first connect, attach/resume on reconnect.
514    fn handshake(&mut self, ws: Ws) -> impl Future<Output = Result<Ws, HandshakeError>> + Send;
515    /// Drive the established connection until it exits.
516    fn message_loop(&mut self, ws: Ws) -> impl Future<Output = MessageLoopExit> + Send;
517
518    fn publish(&self, status: ConnectionStatus) {
519        publish_status(self.status_tx(), status);
520    }
521
522    fn finish_failed(&mut self, reason: String) {
523        self.fail_pending(reason.clone());
524        self.publish(ConnectionStatus::Failed(reason));
525    }
526}
527
528/// Drive a [`ControlConnection`] through its connect → handshake → run →
529/// reconnect lifecycle until the session ends, is cancelled, or the reconnect
530/// budget is exhausted.
531pub(super) async fn run_control_loop<T: ControlConnection>(mut task: T) {
532    let mut budget = ReconnectBudget::new();
533
534    loop {
535        if task.cancel().is_cancelled() {
536            task.fail_pending("cancelled before session created".to_string());
537            return;
538        }
539        task.publish(ConnectionStatus::Down);
540
541        let ws = match connect_ws(task.url(), task.api_key(), task.extra_headers()).await {
542            Ok(ws) => ws,
543            Err(why) => {
544                if let Some(delay) = budget.next_backoff() {
545                    warn!(attempt = budget.attempt(), error = %why, ?delay, "{} connect failed, retrying", task.label());
546                    if !cancellable_sleep(delay, task.cancel()).await {
547                        return;
548                    }
549                    continue;
550                }
551                task.finish_failed(format!("connect: {why}"));
552                return;
553            }
554        };
555
556        let ws = match task.handshake(ws).await {
557            Ok(ws) => ws,
558            Err(HandshakeError::Fatal(why)) => {
559                task.finish_failed(format!("handshake: {why}"));
560                return;
561            }
562            Err(HandshakeError::Transient(why)) => {
563                if let Some(delay) = budget.next_backoff() {
564                    warn!(attempt = budget.attempt(), error = %why, ?delay, "{} handshake failed, retrying", task.label());
565                    if !cancellable_sleep(delay, task.cancel()).await {
566                        return;
567                    }
568                    continue;
569                }
570                task.finish_failed(format!("handshake: {why}"));
571                return;
572            }
573        };
574
575        task.publish(ConnectionStatus::Up);
576        let connected_at = Instant::now();
577
578        match task.message_loop(ws).await {
579            MessageLoopExit::SessionEnded | MessageLoopExit::Cancelled => return,
580            MessageLoopExit::ConnectionLost(why) => {
581                if connected_at.elapsed() >= RECONNECT_UPTIME_RESET {
582                    budget.reset();
583                }
584                if let Some(delay) = budget.next_backoff() {
585                    warn!(attempt = budget.attempt(), reason = %why, ?delay, "{} connection lost, reconnecting", task.label());
586                    if !cancellable_sleep(delay, task.cancel()).await {
587                        return;
588                    }
589                    continue;
590                }
591                task.finish_failed(format!("connection lost: {why}"));
592                return;
593            }
594            MessageLoopExit::Terminal(why) => {
595                task.finish_failed(why);
596                return;
597            }
598        }
599    }
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605
606    /// The request head `connect_ws` sends with API key `k`. Never completes the handshake;
607    /// the headers are in the request head.
608    async fn handshake_head(extra_headers: &HeaderMap) -> String {
609        use tokio::io::AsyncReadExt;
610
611        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
612            .await
613            .expect("bind");
614        let addr = listener.local_addr().expect("addr");
615        let accepted = tokio::spawn(async move {
616            let (mut stream, _) = listener.accept().await.expect("accept");
617            let mut buf = vec![0_u8; 4096];
618            let read = stream.read(&mut buf).await.expect("read");
619            String::from_utf8_lossy(&buf[..read]).to_string()
620        });
621
622        let _ = connect_ws(&format!("ws://{addr}"), "k", extra_headers).await;
623
624        accepted.await.expect("join")
625    }
626
627    fn header_value(head: &str, name: &str) -> Option<String> {
628        head.lines().find_map(|line| {
629            let (key, value) = line.split_once(':')?;
630            key.eq_ignore_ascii_case(name)
631                .then(|| value.trim().to_string())
632        })
633    }
634
635    /// The only connect path that sends the managed form.
636    #[tokio::test]
637    async fn connect_ws_identifies_itself_as_managed() {
638        let head = handshake_head(&HeaderMap::new()).await;
639        let user_agent = header_value(&head, "user-agent").expect("connect_ws sent a User-Agent");
640        assert_eq!(
641            simulator_api::client_identity::classify(Some(&user_agent)).0,
642            simulator_api::client_identity::ClientKind::Managed,
643        );
644    }
645
646    #[tokio::test]
647    async fn connect_ws_sends_the_extra_headers_beside_the_api_key() {
648        let extra_headers = HeaderMap::from_iter([(
649            http::HeaderName::from_static("x-extra"),
650            HeaderValue::from_static("extra"),
651        )]);
652
653        let head = handshake_head(&extra_headers).await;
654
655        assert_eq!(header_value(&head, "x-extra").as_deref(), Some("extra"));
656        assert_eq!(header_value(&head, "x-api-key").as_deref(), Some("k"));
657    }
658
659    #[test]
660    fn budget_exhausts_after_max_attempts() {
661        let mut b = ReconnectBudget::new();
662        for _ in 0..RECONNECT_MAX_ATTEMPTS {
663            assert!(b.next_backoff().is_some());
664        }
665        assert!(b.next_backoff().is_none());
666    }
667
668    #[test]
669    fn budget_reset_restores_full_budget() {
670        let mut b = ReconnectBudget::new();
671        b.next_backoff();
672        b.next_backoff();
673        b.reset();
674        assert_eq!(b.attempt(), 0);
675    }
676
677    #[test]
678    fn streaming_guard_balances_the_count() {
679        let coord = Arc::new(ReconnectCoordinator::new());
680        assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
681        let g = coord.enter();
682        assert_eq!(coord.streaming.load(Ordering::SeqCst), 1);
683        drop(g);
684        assert_eq!(coord.streaming.load(Ordering::SeqCst), 0);
685    }
686
687    #[tokio::test]
688    async fn reconnect_slot_available_when_link_is_quiet() {
689        let coord = Arc::new(ReconnectCoordinator::new());
690        let cancel = CancellationToken::new();
691        assert!(coord.reconnect_slot(&cancel).await.is_some());
692    }
693
694    #[tokio::test]
695    async fn reconnect_slot_unparks_when_last_sibling_leaves() {
696        let coord = Arc::new(ReconnectCoordinator::new());
697        let cancel = CancellationToken::new();
698        let guard = coord.enter(); // streaming == 1, so a slot request must park
699
700        let waiter = tokio::spawn({
701            let coord = coord.clone();
702            let cancel = cancel.clone();
703            async move { coord.reconnect_slot(&cancel).await.is_some() }
704        });
705
706        // While a sibling streams, the parked request stays pending.
707        tokio::task::yield_now().await;
708        assert!(!waiter.is_finished());
709
710        drop(guard); // streaming -> 0, wakes the parked request
711        assert!(waiter.await.unwrap());
712    }
713
714    #[tokio::test]
715    async fn reconnect_slot_returns_none_on_cancel_while_parked() {
716        let coord = Arc::new(ReconnectCoordinator::new());
717        let _guard = coord.enter(); // keep the link busy so the request parks
718        let cancel = CancellationToken::new();
719        cancel.cancel();
720        assert!(coord.reconnect_slot(&cancel).await.is_none());
721    }
722
723    #[test]
724    fn discount_parked_does_not_consume_the_budget() {
725        let mut b = ReconnectBudget::new();
726        // A long park must leave the full attempt budget intact afterwards.
727        b.discount_parked(2 * RECONNECT_MAX_TOTAL);
728        for _ in 0..RECONNECT_MAX_ATTEMPTS {
729            assert!(b.next_backoff().is_some());
730        }
731    }
732}