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