Skip to main content

serial_mcp/serial/
manager.rs

1//! The multi-connection registry: `ConnectionManager`, its private registry
2//! state, duplicate-port lookup, reconnect-task supervision, and
3//! manager-only tests. Depends on the `config` and `connection` siblings.
4
5use std::collections::{HashMap, HashSet};
6use std::fmt;
7use std::sync::Arc;
8
9use tokio::sync::Mutex;
10
11use crate::error::{Result, SerialError};
12
13use super::config::{ConnectionConfig, ConnectionState, ConnectionSummary};
14use super::connection::SerialConnection;
15
16/// The connection-opening boundary used by [`ConnectionManager::open`].
17///
18/// This injects the *connection backend* only: reservation, registry, and
19/// lifecycle semantics live in the manager and are identical for every
20/// implementation. Production uses the internal `SystemConnectionOpener`;
21/// alternate backends (in-memory duplex streams, hardware simulators) can
22/// drive the entire public MCP surface without an OS serial port. This keeps
23/// such tests cross-platform.
24#[async_trait::async_trait]
25pub trait ConnectionOpener: Send + Sync {
26    /// Open a connection for `config` and return it. The returned
27    /// connection must honor the requested config fields (the manager
28    /// assumes nothing about the backend beyond this trait).
29    ///
30    /// The `async_trait` macro supplies the dyn-compatible boxed future
31    /// internally, keeping the trait object-safe across the supported
32    /// toolchains.
33    async fn open(&self, config: ConnectionConfig) -> Result<SerialConnection>;
34}
35
36/// Production opener: delegates to [`SerialConnection::open`], which builds
37/// the OS serial stream and wraps it in a [`SerialConnection`].
38#[derive(Debug)]
39struct SystemConnectionOpener;
40
41#[async_trait::async_trait]
42impl ConnectionOpener for SystemConnectionOpener {
43    async fn open(&self, config: ConnectionConfig) -> Result<SerialConnection> {
44        SerialConnection::open(config).await
45    }
46}
47
48/// Registry of currently open serial connections, indexed by an opaque
49/// connection id. Rejects opening the same port twice.
50pub struct ConnectionManager {
51    /// Injectable connection-opening boundary (production: OS serial open).
52    opener: Arc<dyn ConnectionOpener>,
53    /// Shared registry state. Wrapped in an `Arc` so the
54    /// [`OpeningReservationGuard`] can reach the registry from its `Drop`
55    /// (i.e. when a cancelled open must release its reservation).
56    state: Arc<Mutex<ConnectionRegistry>>,
57}
58
59impl fmt::Debug for ConnectionManager {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        // The opener is a backend, not registry state; callers never need
62        // to debug-inspect it, and we deliberately do not require
63        // implementations to provide a `Debug` impl.
64        f.debug_struct("ConnectionManager")
65            .field("opener", &"<dyn ConnectionOpener>")
66            .field("state", &self.state)
67            .finish()
68    }
69}
70
71impl Default for ConnectionManager {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77/// RAII owner of one `opening_ports` reservation.
78///
79/// The reservation is released exactly once, no matter how the owning
80/// `open` future ends:
81/// - normal success: the caller removes the reservation and disarms via
82///   [`clear`](Self::clear) while holding the registry lock (atomic with
83///   the connection insert);
84/// - normal failure: the caller propagates the error and this guard's
85///   `Drop` removes the reservation;
86/// - cancellation (the future dropped mid-await): this guard's `Drop`
87///   removes the reservation, so a cancelled open can never wedge the port.
88///
89/// `Drop` removes synchronously via `try_lock` when the registry is
90/// uncontended (the common cancellation case — nothing else holds the
91/// lock). When the lock is contended it falls back to a bounded async
92/// cleanup task on the current runtime, or a synchronous
93/// `blocking_lock` when there is no runtime at all (drop outside an
94/// async context). The fallback only ever waits for one short registry
95/// lock acquisition, never an unbounded queue.
96struct OpeningReservationGuard {
97    state: Arc<Mutex<ConnectionRegistry>>,
98    port: String,
99    active: bool,
100}
101
102impl OpeningReservationGuard {
103    fn new(state: Arc<Mutex<ConnectionRegistry>>, port: String) -> Self {
104        Self {
105            state,
106            port,
107            active: true,
108        }
109    }
110
111    /// Disarm the guard: the reservation was already released explicitly
112    /// (under the registry lock, atomically with the connection insert).
113    fn clear(&mut self) {
114        self.active = false;
115    }
116}
117
118impl Drop for OpeningReservationGuard {
119    fn drop(&mut self) {
120        if !self.active {
121            return;
122        }
123        match self.state.try_lock() {
124            Ok(mut state) => {
125                state.opening_ports.remove(&self.port);
126            }
127            Err(_) => {
128                // Contended: bounded async cleanup on the current runtime.
129                // The spawned task only waits for one registry lock
130                // acquisition, then removes the reservation.
131                let state = Arc::clone(&self.state);
132                let port = self.port.clone();
133                if let Ok(handle) = tokio::runtime::Handle::try_current() {
134                    // The JoinHandle is dropped immediately, which detaches
135                    // the task (it keeps running to completion).
136                    std::mem::drop(handle.spawn(async move {
137                        state.lock().await.opening_ports.remove(&port);
138                    }));
139                } else {
140                    // No runtime (drop in a plain sync context):
141                    // synchronous acquisition is safe here and cannot
142                    // deadlock the runtime.
143                    self.state.blocking_lock().opening_ports.remove(&self.port);
144                }
145            }
146        }
147    }
148}
149
150#[derive(Debug, Default)]
151struct ConnectionRegistry {
152    connections: HashMap<String, Arc<SerialConnection>>,
153    opening_ports: HashSet<String>,
154    closing_ports: HashSet<String>,
155    reconnect_tasks: HashMap<String, tokio::task::JoinHandle<()>>,
156}
157
158impl ConnectionManager {
159    pub fn new() -> Self {
160        Self::with_opener(Arc::new(SystemConnectionOpener))
161    }
162
163    /// Build a manager whose connection opening is performed by `opener`
164    /// instead of the production OS serial backend.
165    ///
166    /// Production never calls this — [`Self::new`] / [`Default`] use the
167    /// system opener. It exists so alternate connection backends (in-memory
168    /// duplex streams, hardware simulators) can exercise the whole public
169    /// MCP surface without an OS serial port, which also keeps such tests
170    /// cross-platform. This injects the connection backend only; port
171    /// reservation, registry, and lifecycle semantics are unchanged.
172    pub fn with_opener(opener: Arc<dyn ConnectionOpener>) -> Self {
173        Self {
174            opener,
175            state: Arc::new(Mutex::new(ConnectionRegistry::default())),
176        }
177    }
178
179    /// Open a new connection and store it. Returns the new connection id.
180    pub async fn open(&self, config: ConnectionConfig) -> Result<String> {
181        let port = config.port.clone();
182        let mut guard = {
183            let mut state = self.state.lock().await;
184            if let Some(connection) = find_connection_by_port(&state.connections, &port) {
185                return Err(SerialError::PortAlreadyOpen {
186                    port,
187                    connection_id: Some(connection.id().to_string()),
188                    name: connection.name().map(str::to_string),
189                });
190            }
191            if state.opening_ports.contains(&port) || state.closing_ports.contains(&port) {
192                return Err(SerialError::PortAlreadyOpening(port));
193            }
194            state.opening_ports.insert(port.clone());
195            OpeningReservationGuard::new(Arc::clone(&self.state), port.clone())
196        };
197
198        let opened = self.opener.open(config).await;
199
200        // Success or failure: the reservation is removed exactly once.
201        // On error, `?` propagates and the guard's `Drop` removes it. On
202        // success, removal happens here under the registry lock, atomic
203        // with the connection insert, then the guard is disarmed so its
204        // `Drop` becomes a no-op.
205        let mut state = self.state.lock().await;
206        let connection = Arc::new(opened?);
207        let id = connection.id().to_string();
208        state.opening_ports.remove(&port);
209        state.connections.insert(id.clone(), connection);
210        guard.clear();
211        Ok(id)
212    }
213
214    /// Insert an already-built [`SerialConnection`] (typically one backed
215    /// by an in-memory loopback) into the registry. Honours the same
216    /// port-uniqueness invariant as [`Self::open`].
217    ///
218    /// Exposed for integration tests that want to drive the MCP surface
219    /// against a fake connection without going through the OS serial layer.
220    pub async fn insert(&self, connection: SerialConnection) -> Result<String> {
221        let mut state = self.state.lock().await;
222        if let Some(existing) = find_connection_by_port(&state.connections, connection.port()) {
223            return Err(SerialError::PortAlreadyOpen {
224                port: connection.port().to_string(),
225                connection_id: Some(existing.id().to_string()),
226                name: existing.name().map(str::to_string),
227            });
228        }
229        if state.opening_ports.contains(connection.port())
230            || state.closing_ports.contains(connection.port())
231        {
232            return Err(SerialError::PortAlreadyOpening(
233                connection.port().to_string(),
234            ));
235        }
236        let id = connection.id().to_string();
237        state.connections.insert(id.clone(), Arc::new(connection));
238        Ok(id)
239    }
240
241    /// Remove a connection, cancel in-flight operations, flush RX, and close
242    /// the underlying port before allowing a reopen.
243    pub async fn close(&self, id: &str) -> Result<()> {
244        let connection = {
245            let mut state = self.state.lock().await;
246            let connection = state
247                .connections
248                .remove(id)
249                .ok_or_else(|| SerialError::ConnectionNotFound(id.to_string()))?;
250            state.closing_ports.insert(connection.port().to_string());
251            connection
252        };
253
254        let port = connection.port().to_string();
255        // Abort any running reconnect task for this connection.
256        {
257            let mut state = self.state.lock().await;
258            if let Some(handle) = state.reconnect_tasks.remove(id) {
259                handle.abort();
260            }
261        }
262        connection.log().closed();
263        let result = connection.close().await;
264
265        self.state.lock().await.closing_ports.remove(&port);
266        result
267    }
268
269    /// Look up an existing connection by id.
270    pub async fn get(&self, id: &str) -> Result<Arc<SerialConnection>> {
271        self.state
272            .lock()
273            .await
274            .connections
275            .get(id)
276            .cloned()
277            .ok_or_else(|| SerialError::ConnectionNotFound(id.to_string()))
278    }
279
280    /// Return all currently-registered connections with their ids.
281    pub async fn list_all(&self) -> Vec<(String, Arc<SerialConnection>)> {
282        self.state
283            .lock()
284            .await
285            .connections
286            .iter()
287            .map(|(k, v)| (k.clone(), Arc::clone(v)))
288            .collect()
289    }
290
291    /// Start a background reconnect task for the given connection.
292    /// The task retries `reconnect()` with exponential backoff,
293    /// respecting the connection's `ReconnectPolicy`. On success,
294    /// restarts the RX pump via `rx_sessions`.
295    pub async fn start_reconnect(
296        &self,
297        id: &str,
298        rx_sessions: Arc<crate::rx_session::RxSessionManager>,
299    ) {
300        let conn = match self.get(id).await {
301            Ok(c) => c,
302            Err(_) => return,
303        };
304        let policy = conn.reconnect_policy.lock().expect("poisoned").clone();
305        if !policy.enabled {
306            return;
307        }
308        // Avoid spawning a duplicate task. Prune finished handles first.
309        {
310            let mut state = self.state.lock().await;
311            state.reconnect_tasks.retain(|_, h| !h.is_finished());
312            if state.reconnect_tasks.contains_key(id) {
313                return;
314            }
315        }
316
317        let id_owned = id.to_string();
318        let conn_clone = Arc::clone(&conn);
319        let handle = tokio::spawn(async move {
320            let mut delay_ms = policy.initial_delay_ms;
321            let mut attempts: u32 = 0;
322            loop {
323                // Check if still disconnected / not cancelled.
324                let state = conn_clone.state();
325                if state == ConnectionState::Open || state == ConnectionState::Closed {
326                    break;
327                }
328                tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
329
330                match conn_clone.reconnect().await {
331                    Ok(()) => {
332                        // Reset attempt counter after successful reconnect.
333                        conn_clone.reset_reconnect_attempts();
334                        // Restart the RX pump so data flows again.
335                        if let Some(session) = rx_sessions.get(&id_owned).await {
336                            session.ensure_pump_running();
337                        }
338                        break;
339                    }
340                    Err(_e) => {
341                        attempts += 1;
342                        if policy.max_attempts > 0 && attempts >= policy.max_attempts {
343                            conn_clone
344                                .log()
345                                .record(None, crate::log_buffer::LogEvent::ReconnectExhausted);
346                            break;
347                        }
348                        // Exponential backoff with cap.
349                        delay_ms = ((delay_ms as f64) * policy.backoff_multiplier)
350                            .min(policy.max_delay_ms as f64)
351                            as u64;
352                    }
353                }
354            }
355            // Task completes: handle stays in reconnect_tasks; supervisor
356            // prunes finished handles on its next poll.
357        });
358
359        let mut state = self.state.lock().await;
360        state.reconnect_tasks.insert(id.to_string(), handle);
361    }
362
363    /// Cancel a running reconnect task for the given connection.
364    pub async fn cancel_reconnect(&self, id: &str) {
365        let mut state = self.state.lock().await;
366        if let Some(handle) = state.reconnect_tasks.remove(id) {
367            handle.abort();
368        }
369    }
370
371    /// Number of currently open connections.
372    pub async fn count(&self) -> usize {
373        self.state.lock().await.connections.len()
374    }
375
376    /// Lightweight snapshot of all currently-open connections. Cheap because
377    /// it only clones the id + port pair, not the underlying IO.
378    pub async fn list_open(&self) -> Vec<ConnectionSummary> {
379        self.state
380            .lock()
381            .await
382            .connections
383            .values()
384            .map(|c| c.summary())
385            .collect()
386    }
387}
388
389fn find_connection_by_port<'a>(
390    connections: &'a HashMap<String, Arc<SerialConnection>>,
391    port: &str,
392) -> Option<&'a Arc<SerialConnection>> {
393    connections.values().find(|c| c.port() == port)
394}
395
396#[cfg(test)]
397mod tests {
398    use std::sync::atomic::{AtomicUsize, Ordering};
399    use std::sync::Arc;
400
401    use tokio::sync::{watch, Notify};
402
403    use super::*;
404    use crate::serial::test_support::{loopback_connection, loopback_connection_with_config};
405    use crate::serial::{DataBits, FlowControl, Parity, StopBits};
406
407    fn test_config(port: &str) -> ConnectionConfig {
408        ConnectionConfig {
409            port: port.into(),
410            name: Some("opener-test".into()),
411            baud_rate: 9600,
412            data_bits: DataBits::Eight,
413            stop_bits: StopBits::One,
414            parity: Parity::None,
415            flow_control: FlowControl::None,
416            port_info: None,
417            log_capacity: 1024,
418            log_enabled: true,
419            tx_framing: None,
420            rx_framing: None,
421            rx_parser: None,
422            protocol: None,
423            rx_buffer_size: 8192,
424            max_buffered_bytes: 4096,
425        }
426    }
427
428    #[tokio::test]
429    async fn manager_rejects_duplicate_port() {
430        let mgr = ConnectionManager::new();
431        let (c1, _p1) = loopback_connection("port-a");
432        mgr.insert(c1).await.unwrap();
433        let (c2, _p2) = loopback_connection("port-a");
434        let err = mgr.insert(c2).await.unwrap_err();
435        assert!(matches!(err, SerialError::PortAlreadyOpen { .. }));
436    }
437
438    #[tokio::test]
439    async fn manager_duplicate_port_error_includes_owner_metadata() {
440        let mgr = ConnectionManager::new();
441        let (c1, _peer_a) = loopback_connection_with_config(ConnectionConfig {
442            port: "port-owner".into(),
443            name: Some("console".into()),
444            baud_rate: 115200,
445            data_bits: DataBits::Eight,
446            stop_bits: StopBits::One,
447            parity: Parity::None,
448            flow_control: FlowControl::None,
449            port_info: None,
450            log_capacity: 1024,
451            log_enabled: true,
452            tx_framing: None,
453            rx_framing: None,
454            rx_parser: None,
455            protocol: None,
456            rx_buffer_size: crate::limits::DEFAULT_RX_BUFFER_SIZE,
457            max_buffered_bytes: 32768,
458        });
459        let owner_id = mgr.insert(c1).await.unwrap();
460
461        let (c2, _p2) = loopback_connection("port-owner");
462        let err = mgr.insert(c2).await.unwrap_err();
463        match err {
464            SerialError::PortAlreadyOpen {
465                port,
466                connection_id,
467                name,
468            } => {
469                assert_eq!(port, "port-owner");
470                assert_eq!(connection_id.as_deref(), Some(owner_id.as_str()));
471                assert_eq!(name.as_deref(), Some("console"));
472            }
473            other => panic!("unexpected error: {other:?}"),
474        }
475    }
476
477    #[tokio::test]
478    async fn manager_close_then_get_returns_connection_not_found() {
479        let mgr = ConnectionManager::new();
480        let (c, _p) = loopback_connection("port-z");
481        let id = mgr.insert(c).await.unwrap();
482        mgr.close(&id).await.unwrap();
483        let err = mgr.get(&id).await.unwrap_err();
484        assert!(matches!(err, SerialError::ConnectionNotFound(_)));
485    }
486
487    #[tokio::test]
488    async fn manager_get_unknown_id_returns_connection_not_found() {
489        let mgr = ConnectionManager::new();
490        let err = mgr.get("does-not-exist").await.unwrap_err();
491        assert!(matches!(err, SerialError::ConnectionNotFound(_)));
492    }
493
494    /// The injected opener receives the exact config passed to the public
495    /// `open`, and the successful open becomes retrievable through the
496    /// manager (observable behavior, not opener helper-call counts alone).
497    #[tokio::test]
498    async fn injected_opener_receives_requested_config_and_open_is_retrievable() {
499        struct RecordingOpener {
500            configs: std::sync::Mutex<Vec<ConnectionConfig>>,
501        }
502        #[async_trait::async_trait]
503        impl ConnectionOpener for RecordingOpener {
504            async fn open(&self, config: ConnectionConfig) -> Result<SerialConnection> {
505                self.configs
506                    .lock()
507                    .expect("opener configs poisoned")
508                    .push(config.clone());
509                let (conn, _peer) = loopback_connection_with_config(config);
510                Ok(conn)
511            }
512        }
513
514        let opener = Arc::new(RecordingOpener {
515            configs: std::sync::Mutex::new(Vec::new()),
516        });
517        let mgr = ConnectionManager::with_opener(opener.clone());
518        let config = test_config("opener-port");
519        let id = mgr.open(config.clone()).await.unwrap();
520
521        // The opener received and used the requested config.
522        let received = opener
523            .configs
524            .lock()
525            .expect("opener configs poisoned")
526            .clone();
527        assert_eq!(received.len(), 1, "opener invoked exactly once");
528        let received_cfg = &received[0];
529        assert_eq!(received_cfg.port, "opener-port");
530        assert_eq!(received_cfg.name.as_deref(), Some("opener-test"));
531        assert_eq!(received_cfg.baud_rate, 9600);
532        assert_eq!(received_cfg.rx_buffer_size, 8192);
533        assert_eq!(received_cfg.max_buffered_bytes, 4096);
534
535        // The opened connection is retrievable and reflects the config.
536        let conn = mgr.get(&id).await.unwrap();
537        assert_eq!(conn.port(), "opener-port");
538        assert_eq!(conn.name(), Some("opener-test"));
539        assert_eq!(conn.baud_rate(), 9600);
540    }
541
542    /// An opener failure must release the same-port opening reservation so
543    /// a later open of the same port succeeds (a failed open must never
544    /// wedge the port).
545    #[tokio::test]
546    async fn opener_failure_releases_opening_reservation_for_later_open() {
547        struct FailFirstOpener {
548            failures: AtomicUsize,
549        }
550        #[async_trait::async_trait]
551        impl ConnectionOpener for FailFirstOpener {
552            async fn open(&self, config: ConnectionConfig) -> Result<SerialConnection> {
553                // One-shot: `swap(0)` never wraps (unlike `fetch_sub`,
554                // which would wrap to usize::MAX at zero).
555                if self.failures.swap(0, Ordering::SeqCst) > 0 {
556                    return Err(SerialError::IoError(std::io::Error::other(
557                        "injected opener failure",
558                    )));
559                }
560                let (conn, _peer) = loopback_connection_with_config(config);
561                Ok(conn)
562            }
563        }
564
565        let mgr = ConnectionManager::with_opener(Arc::new(FailFirstOpener {
566            failures: AtomicUsize::new(1),
567        }));
568        let config = test_config("reservation-port");
569
570        let first = mgr.open(config.clone()).await;
571        assert!(
572            matches!(first, Err(SerialError::IoError(_))),
573            "first open fails through the opener: {first:?}"
574        );
575
576        // The reservation was released: the same port opens successfully now.
577        let id = mgr
578            .open(config)
579            .await
580            .expect("opening reservation released after opener failure");
581        let conn = mgr.get(&id).await.unwrap();
582        assert_eq!(conn.port(), "reservation-port");
583    }
584
585    /// While an open is in flight, the opening reservation must stop a
586    /// concurrent same-port open BEFORE it reaches the opener, and the
587    /// in-flight open must still complete and register its connection.
588    /// The opener invocation count is paired with the observable results
589    /// (second open rejected, first open retrievable) so the assertion is
590    /// not a bare helper-call-count.
591    #[tokio::test]
592    async fn concurrent_same_port_open_reserves_port_and_second_open_is_rejected() {
593        struct GatedOpener {
594            entered: watch::Sender<bool>,
595            release: Arc<Notify>,
596            invocations: AtomicUsize,
597        }
598        #[async_trait::async_trait]
599        impl ConnectionOpener for GatedOpener {
600            async fn open(&self, config: ConnectionConfig) -> Result<SerialConnection> {
601                self.invocations.fetch_add(1, Ordering::SeqCst);
602                let _ = self.entered.send(true);
603                // Hold the reservation until the test proves the second
604                // open is rejected without invoking the opener again.
605                self.release.notified().await;
606                let (conn, _peer) = loopback_connection_with_config(config);
607                Ok(conn)
608            }
609        }
610
611        let (entered_tx, mut entered_rx) = watch::channel(false);
612        let release = Arc::new(Notify::new());
613        let opener = Arc::new(GatedOpener {
614            entered: entered_tx,
615            release: Arc::clone(&release),
616            invocations: AtomicUsize::new(0),
617        });
618        let mgr = Arc::new(ConnectionManager::with_opener(opener.clone()));
619        let config = test_config("concurrent-port");
620
621        // First open runs on its own task and signals once the opener is
622        // inside (reservation held).
623        let mgr_for_task = Arc::clone(&mgr);
624        let config_for_task = config.clone();
625        let first_task = tokio::spawn(async move { mgr_for_task.open(config_for_task).await });
626
627        tokio::time::timeout(
628            std::time::Duration::from_secs(5),
629            entered_rx.wait_for(|e| *e),
630        )
631        .await
632        .expect("first open reached the opener within the hang guard")
633        .expect("opener signalled entry");
634
635        // Second open on the same port: rejected as PortAlreadyOpening
636        // WITHOUT invoking the opener again.
637        let second = mgr.open(config).await.unwrap_err();
638        assert!(
639            matches!(second, SerialError::PortAlreadyOpening(ref port) if port == "concurrent-port"),
640            "concurrent same-port open rejected while opening: {second:?}"
641        );
642        assert_eq!(
643            opener.invocations.load(Ordering::SeqCst),
644            1,
645            "the reservation prevents a second opener invocation"
646        );
647
648        // Release the in-flight open: it completes and registers.
649        release.notify_one();
650        let first_id = first_task
651            .await
652            .expect("first open task")
653            .expect("first open succeeds after release");
654        let conn = mgr.get(&first_id).await.unwrap();
655        assert_eq!(conn.port(), "concurrent-port");
656        assert_eq!(mgr.count().await, 1, "exactly one connection registered");
657    }
658
659    /// A cancelled open must release its `opening_ports` reservation so a
660    /// later open of the same port succeeds — and a connection the opener
661    /// was about to produce must never register after the cancel.
662    ///
663    /// The cleanup is deterministic, not polled: `JoinHandle::await` only
664    /// resolves after the aborted task's future (and with it the
665    /// reservation guard) is dropped, so by the time the handle returns the
666    /// reservation is already gone and the immediate retry succeeds.
667    #[tokio::test]
668    async fn cancelled_open_releases_opening_reservation_for_later_open() {
669        struct CancelGatedOpener {
670            entered: watch::Sender<bool>,
671            invocations: AtomicUsize,
672        }
673        #[async_trait::async_trait]
674        impl ConnectionOpener for CancelGatedOpener {
675            async fn open(&self, config: ConnectionConfig) -> Result<SerialConnection> {
676                if self.invocations.fetch_add(1, Ordering::SeqCst) == 0 {
677                    // First call: signal entry and wait forever. The
678                    // test aborts this task; the guard's `Drop` then
679                    // releases the reservation.
680                    let _ = self.entered.send(true);
681                    std::future::pending::<()>().await;
682                    unreachable!("aborted before pending resolves");
683                }
684                // Second (and later) calls: succeed immediately — the
685                // opener must never wait on a cancelled predecessor.
686                let (conn, _peer) = loopback_connection_with_config(config);
687                Ok(conn)
688            }
689        }
690
691        let (entered_tx, mut entered_rx) = watch::channel(false);
692        let opener = Arc::new(CancelGatedOpener {
693            entered: entered_tx,
694            invocations: AtomicUsize::new(0),
695        });
696        let mgr = Arc::new(ConnectionManager::with_opener(opener.clone()));
697        let config = test_config("cancel-port");
698
699        let mgr_for_task = Arc::clone(&mgr);
700        let config_for_task = config.clone();
701        let task = tokio::spawn(async move { mgr_for_task.open(config_for_task).await });
702
703        tokio::time::timeout(
704            std::time::Duration::from_secs(5),
705            entered_rx.wait_for(|e| *e),
706        )
707        .await
708        .expect("hang guard: first open reached the opener")
709        .expect("opener signalled entry");
710
711        // Cancel the in-flight open; the reservation guard releases the
712        // port during task cancellation.
713        task.abort();
714        let join = tokio::time::timeout(std::time::Duration::from_secs(5), task)
715            .await
716            .expect("hang guard: cancelled open task joined");
717        assert!(
718            join.is_err(),
719            "open task was aborted, not completed: {join:?}"
720        );
721
722        // The same port opens successfully immediately after the cancel,
723        // through the opener again, and registers exactly one connection.
724        let id = tokio::time::timeout(std::time::Duration::from_secs(5), mgr.open(config))
725            .await
726            .expect("hang guard: second open after cancellation")
727            .expect("second open succeeds after cancellation cleanup");
728        let conn = mgr.get(&id).await.unwrap();
729        assert_eq!(conn.port(), "cancel-port");
730        assert_eq!(mgr.count().await, 1, "exactly one connection registered");
731        assert_eq!(
732            opener.invocations.load(Ordering::SeqCst),
733            2,
734            "the retry invoked the opener again"
735        );
736    }
737}