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