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