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