Skip to main content

subc_daemon/
server.rs

1use std::{
2    any::Any,
3    error::Error,
4    fmt, io,
5    net::SocketAddr,
6    sync::{
7        atomic::{AtomicU64, Ordering as AtomicOrdering},
8        Arc,
9    },
10    time::{Duration, Instant},
11};
12
13use subc_transport::{
14    authenticate_server, AuthError, AuthStage, DAEMON_ID_LEN, WATCHDOG_CLIENT_ROLE,
15};
16use tokio::{
17    io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, BufWriter},
18    net::TcpListener,
19    sync::{mpsc, Semaphore},
20    task::{JoinHandle, JoinSet},
21    time::timeout,
22};
23use tracing::{debug, info, warn};
24
25use crate::{
26    forwarding::{CloseReason, ConnectionCloseReceiver},
27    observability::ConnectedClients,
28    read_frame,
29    router::{FrameSink, RouteCtx, Router},
30    write_frame, FrameIoError, RouterError,
31};
32
33/// Bytes (envelope header plus body) one connection's egress queue may hold
34/// before a module-to-client enqueue must wait for room.
35///
36/// Sized for a client that is slow but still reading: one connection can
37/// multiplex many token streams, and at roughly 200-byte frames (21-byte header
38/// plus body) 4 MiB is about 19,000 queued frames, i.e. thousands of frames on
39/// each of several routes, enough to ride out a pause of seconds. It is also the
40/// most a stuck client can make the daemon hold for it: 4 MiB per connection,
41/// so even 128 stuck connections stay near 512 MiB rather than growing without
42/// bound. A single frame larger than the whole budget is still admitted into an
43/// empty queue on send paths that do not check its size first.
44///
45/// The router, however, refuses a module-to-client frame whose header-plus-body
46/// size exceeds the client connection's budget before queueing it, so the budget
47/// is also the largest module-to-client frame the daemon delivers. Modules read
48/// that limit from `subc_protocol::MAX_DELIVERED_FRAME_LEN`, so the budget is
49/// defined as that constant; giving it a different value would make the
50/// published limit wrong.
51pub const CONNECTION_EGRESS_BYTE_BUDGET: usize = subc_protocol::MAX_DELIVERED_FRAME_LEN;
52/// Let a reading client drain a short fanout burst, but never park a module's
53/// frame reader for more than 250 ms. The atomic backlog age is measured from
54/// the enqueue time of the frame the writer is on, or of the frame that made
55/// the queue non-empty. A blocked writer makes that age the stopped-reader
56/// signal; between frames it may be one frame older than the true head, which
57/// is acceptable for this bounded grace and avoids a lock on every frame.
58pub const CONNECTION_EGRESS_STALL_GRACE: Duration = Duration::from_millis(250);
59/// Frame-count backstop for the same queue (the tokio channel's capacity).
60/// The byte budget is the real bound; this one only matters for floods of tiny
61/// or empty frames, which cost bookkeeping per frame rather than bytes. 32,768
62/// frames times 128 bytes is exactly the 4 MiB budget, so for any mean frame of
63/// 128 bytes or more the byte budget binds first; below that (for example
64/// 21-byte empty frames, of which 4 MiB would be almost 200,000) the count
65/// does. The channel allocates slots lazily, so a large capacity costs nothing
66/// until it is used.
67pub const CONNECTION_EGRESS_FRAME_CAP: usize = 32 * 1024;
68/// A pending `route.open` holds one reserved slot in the connection's egress
69/// queue until its module answers, and its response is sent outside the byte
70/// budget. Eight concurrent opens per connection keep a reconnect burst
71/// parallel while bounding both the reserved slots and the bytes that bypass
72/// the budget.
73pub const MAX_PENDING_ROUTE_OPENS_PER_CONNECTION: usize = 8;
74/// A reconnect herd may spread one target's opens over many client connections.
75/// Two safe per-connection bursts retain useful parallelism without restoring
76/// the hundreds-of-binds fanout that serial dispatch used to suppress.
77pub(crate) const MAX_PENDING_ROUTE_BINDS_PER_TARGET: usize =
78    MAX_PENDING_ROUTE_OPENS_PER_CONNECTION * 2;
79pub const DEFAULT_AUTH_DEADLINE: Duration = Duration::from_secs(2);
80// Sized for the restart-herd shape: after a daemon bounce, every live client
81// connection plus all supervised children re-dial within the same second
82// (~120+ observed on the 2026-07-14 fleet). Handshakes are cheap loopback
83// HMAC exchanges; the deadline, not the permit count, is the DoS bound.
84pub const DEFAULT_MAX_UNAUTHENTICATED_CONNECTIONS: usize = 256;
85const CLOSE_DRAIN_GRACE: Duration = Duration::from_secs(2);
86const PRE_AUTH_REJECT_LOG_INTERVAL: Duration = Duration::from_secs(1);
87
88/// A connection's writer can outlive its reader while draining. Wake module
89/// deliveries when the reader exits, including task cancellation or a panic.
90struct ClientDeliveryGuard(FrameSink);
91
92impl Drop for ClientDeliveryGuard {
93    fn drop(&mut self) {
94        self.0.close_client_delivery();
95    }
96}
97
98#[derive(Clone, Copy, Debug)]
99enum PreAuthRejectStage {
100    WaitingForHandshakeSlot,
101    HandshakeDeadline,
102    InvalidProof,
103    MalformedMessage,
104    PeerClosed,
105    OtherAuthenticationFailure,
106}
107
108impl PreAuthRejectStage {
109    const fn index(self) -> usize {
110        match self {
111            Self::WaitingForHandshakeSlot => 0,
112            Self::HandshakeDeadline => 1,
113            Self::InvalidProof => 2,
114            Self::MalformedMessage => 3,
115            Self::PeerClosed => 4,
116            Self::OtherAuthenticationFailure => 5,
117        }
118    }
119
120    const fn stage(self) -> &'static str {
121        match self {
122            Self::WaitingForHandshakeSlot => "waiting_for_handshake_slot",
123            Self::HandshakeDeadline => "handshake_deadline",
124            Self::InvalidProof => "client_authentication",
125            Self::MalformedMessage => "malformed_message",
126            Self::PeerClosed => "peer_closed",
127            Self::OtherAuthenticationFailure => "authentication",
128        }
129    }
130
131    const fn reason(self) -> &'static str {
132        match self {
133            Self::WaitingForHandshakeSlot => "capacity_wait_timed_out",
134            Self::HandshakeDeadline => "handshake_deadline_expired",
135            Self::InvalidProof => "client_proof_mismatch",
136            Self::MalformedMessage => "malformed_or_oversized_message",
137            Self::PeerClosed => "peer_closed_before_authentication_completed",
138            Self::OtherAuthenticationFailure => "authentication_failed_before_routing",
139        }
140    }
141}
142
143#[derive(Debug)]
144struct PreAuthRejectRateLimit {
145    next_allowed_ns: AtomicU64,
146    suppressed: AtomicU64,
147}
148
149impl PreAuthRejectRateLimit {
150    const fn new() -> Self {
151        Self {
152            next_allowed_ns: AtomicU64::new(0),
153            suppressed: AtomicU64::new(0),
154        }
155    }
156}
157
158/// Rate-limit state for pre-authentication rejection logs, owned by one
159/// `ServerAuth` so each listener (and each test) counts only its own rejects.
160#[derive(Debug)]
161struct PreAuthRejectLog {
162    epoch: Instant,
163    limiter: PreAuthRejectLimiter,
164}
165
166impl PreAuthRejectLog {
167    fn new() -> Self {
168        Self {
169            epoch: Instant::now(),
170            limiter: PreAuthRejectLimiter::new(),
171        }
172    }
173}
174
175// Report accumulated rejects on the next allowed line instead of running a timer task.
176#[derive(Debug)]
177struct PreAuthRejectLimiter {
178    stages: [PreAuthRejectRateLimit; 6],
179}
180
181impl PreAuthRejectLimiter {
182    fn new() -> Self {
183        Self {
184            stages: std::array::from_fn(|_| PreAuthRejectRateLimit::new()),
185        }
186    }
187
188    fn allow_at(&self, stage: PreAuthRejectStage, now: Duration) -> Option<u64> {
189        let slot = &self.stages[stage.index()];
190        let now_ns = now.as_nanos().min(u64::MAX as u128) as u64;
191        let interval_ns = PRE_AUTH_REJECT_LOG_INTERVAL.as_nanos() as u64;
192        let mut next_allowed_ns = slot.next_allowed_ns.load(AtomicOrdering::Relaxed);
193
194        loop {
195            if now_ns < next_allowed_ns {
196                slot.suppressed.fetch_add(1, AtomicOrdering::Relaxed);
197                return None;
198            }
199
200            match slot.next_allowed_ns.compare_exchange_weak(
201                next_allowed_ns,
202                now_ns.saturating_add(interval_ns),
203                AtomicOrdering::Relaxed,
204                AtomicOrdering::Relaxed,
205            ) {
206                Ok(_) => return Some(slot.suppressed.swap(0, AtomicOrdering::Relaxed)),
207                Err(actual) => next_allowed_ns = actual,
208            }
209        }
210    }
211}
212
213fn log_pre_auth_rejection(
214    error: &ConnectionError,
215    peer_addr: SocketAddr,
216    elapsed: Duration,
217    now: Duration,
218    limiter: &PreAuthRejectLimiter,
219) {
220    let Some(stage) = error.pre_auth_reject_stage() else {
221        return;
222    };
223    let Some(suppressed_since_last) = limiter.allow_at(stage, now) else {
224        return;
225    };
226    let elapsed_ms = elapsed.as_millis().min(u64::MAX as u128) as u64;
227
228    info!(
229        peer_addr = %peer_addr,
230        elapsed_ms,
231        stage = stage.stage(),
232        reason = stage.reason(),
233        auth_stage = ?error.auth_stage(),
234        suppressed_since_last,
235        error = %error,
236        "subc TCP connection rejected before routing"
237    );
238}
239
240async fn handle_accepted_connection<S>(
241    stream: S,
242    router: Arc<Router>,
243    auth: ServerAuth,
244    peer_addr: SocketAddr,
245    accepted_at: Instant,
246) -> Result<(), ConnectionError>
247where
248    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
249{
250    let reject_log = Arc::clone(&auth.pre_auth_reject_log);
251    let result = handle_connection(stream, router, auth).await;
252    if let Err(error) = &result {
253        if error.is_quiet_reject() {
254            log_pre_auth_rejection(
255                error,
256                peer_addr,
257                accepted_at.elapsed(),
258                reject_log.epoch.elapsed(),
259                &reject_log.limiter,
260            );
261        } else {
262            warn!(?peer_addr, error = %error, "subc connection ended with error");
263        }
264    }
265    result
266}
267
268/// Authentication material and DoS bounds applied before a TCP connection may
269/// reach the frame router.
270#[derive(Clone)]
271pub struct ServerAuth {
272    key: Arc<[u8]>,
273    daemon_id: [u8; DAEMON_ID_LEN],
274    daemon_ver: Arc<str>,
275    deadline: Duration,
276    unauthenticated: Arc<Semaphore>,
277    connected_clients: ConnectedClients,
278    pre_auth_reject_log: Arc<PreAuthRejectLog>,
279}
280
281impl ServerAuth {
282    pub fn new(
283        key: Vec<u8>,
284        daemon_id: [u8; DAEMON_ID_LEN],
285        daemon_ver: impl Into<String>,
286    ) -> Self {
287        Self::with_limits(
288            key,
289            daemon_id,
290            daemon_ver,
291            DEFAULT_AUTH_DEADLINE,
292            DEFAULT_MAX_UNAUTHENTICATED_CONNECTIONS,
293        )
294    }
295
296    // Production limits are deliberately not config-routed: loosening pre-auth DoS posture changes attack surface.
297    pub fn with_limits(
298        key: Vec<u8>,
299        daemon_id: [u8; DAEMON_ID_LEN],
300        daemon_ver: impl Into<String>,
301        deadline: Duration,
302        max_unauthenticated: usize,
303    ) -> Self {
304        Self {
305            key: Arc::from(key),
306            daemon_id,
307            daemon_ver: Arc::from(daemon_ver.into()),
308            deadline,
309            unauthenticated: Arc::new(Semaphore::new(max_unauthenticated.max(1))),
310            connected_clients: ConnectedClients::new(),
311            pre_auth_reject_log: Arc::new(PreAuthRejectLog::new()),
312        }
313    }
314
315    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
316        self.connected_clients = connected_clients;
317        self
318    }
319}
320
321impl fmt::Debug for ServerAuth {
322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323        f.debug_struct("ServerAuth")
324            .field("key", &"<redacted>")
325            .field("daemon_id", &self.daemon_id)
326            .field("daemon_ver", &self.daemon_ver)
327            .field("deadline", &self.deadline)
328            .finish_non_exhaustive()
329    }
330}
331
332/// Serve an already-bound TCP listener. Each accepted connection gets its own
333/// async task so concurrent clients do not block the accept loop.
334pub async fn serve_listener(
335    listener: TcpListener,
336    router: Arc<Router>,
337    auth: ServerAuth,
338) -> Result<(), ServerError> {
339    serve_listener_with_accept(listener.local_addr().ok(), router, auth, || {
340        listener.accept()
341    })
342    .await
343}
344
345async fn serve_listener_with_accept<A, F>(
346    local_addr: Option<SocketAddr>,
347    router: Arc<Router>,
348    auth: ServerAuth,
349    mut accept: A,
350) -> Result<(), ServerError>
351where
352    A: FnMut() -> F,
353    F: std::future::Future<Output = io::Result<(tokio::net::TcpStream, SocketAddr)>>,
354{
355    let mut admission = router.forwarding().upgrade_admission.subscribe();
356    loop {
357        let (stream, peer_addr) = match accept_when_unpaused(&mut admission, &mut accept).await {
358            Ok(accepted) => accepted,
359            Err(source) => {
360                let kind = source.kind();
361                // Aborted/reset connections and interrupted syscalls affect one accept only.
362                // File-descriptor or socket-buffer exhaustion needs a short backoff to avoid spinning;
363                // other errors may mean the listener itself is unusable.
364                let exhausted = accept_resource_exhausted(&source);
365                if matches!(
366                    kind,
367                    io::ErrorKind::ConnectionAborted
368                        | io::ErrorKind::ConnectionReset
369                        | io::ErrorKind::Interrupted
370                ) || exhausted
371                {
372                    warn!(?local_addr, error = %source, "temporary TCP accept failure");
373                    if exhausted {
374                        tokio::time::sleep(Duration::from_millis(75)).await;
375                    }
376                    continue;
377                }
378                return Err(ServerError::Accept { local_addr, source });
379            }
380        };
381        let accepted_at = Instant::now();
382        // Every route frame is a discrete message whose reply the peer is waiting
383        // for, so there is never a later write for Nagle to coalesce with -- it can
384        // only hold a frame back until an ACK arrives.
385        //
386        // MEASURED: no effect on this transport. A 50-sample-per-arm sweep from
387        // 1 to 32 KiB over the full client->daemon->module->client path showed a
388        // flat 0.28-0.38ms p50 with no step at any buffer boundary, because a
389        // loopback ACK returns in microseconds and never reaches the delayed-ACK
390        // timer that makes Nagle expensive on a real network. Kept anyway: it is
391        // one syscall at accept, it removes the mechanism rather than relying on
392        // loopback staying fast, and Windows loopback was not part of that sweep.
393        // Do not cite it as a latency fix -- the measurement says it is not one.
394        //
395        // Failure is not fatal: the connection works, and refusing to serve a
396        // client over a socket option would be worse than anything it saves.
397        if let Err(source) = stream.set_nodelay(true) {
398            warn!(?peer_addr, error = %source, "could not disable Nagle on accepted connection");
399        }
400        debug!(?peer_addr, ?local_addr, "accepted subc TCP connection");
401        let router = Arc::clone(&router);
402        let auth = auth.clone();
403        tokio::spawn(async move {
404            let _ = handle_accepted_connection(stream, router, auth, peer_addr, accepted_at).await;
405        });
406    }
407}
408
409#[cfg_attr(not(unix), allow(dead_code))]
410fn temporary_accept_failure(source: &io::Error) -> bool {
411    matches!(
412        source.kind(),
413        io::ErrorKind::ConnectionAborted
414            | io::ErrorKind::ConnectionReset
415            | io::ErrorKind::Interrupted
416    ) || accept_resource_exhausted(source)
417}
418
419fn accept_resource_exhausted(error: &io::Error) -> bool {
420    // ENFILE/EMFILE/ENOBUFS by name rather than number: the numbers differ by
421    // platform (ENOBUFS is 55 on macOS and 105 on Linux, and each number means
422    // something unrelated on the other), so a literal list misclassifies.
423    // Winsock: WSAEMFILE and WSAENOBUFS.
424    #[cfg(unix)]
425    {
426        use rustix::io::Errno;
427        let exhausted = [Errno::NFILE, Errno::MFILE, Errno::NOBUFS];
428        error
429            .raw_os_error()
430            .is_some_and(|code| exhausted.iter().any(|e| e.raw_os_error() == code))
431    }
432    #[cfg(windows)]
433    {
434        matches!(error.raw_os_error(), Some(10024 | 10055))
435    }
436    #[cfg(not(any(unix, windows)))]
437    {
438        let _ = error;
439        false
440    }
441}
442
443/// Serve this daemon's local endpoint (a Unix-domain socket, or a Windows named
444/// pipe) until its accept loop fails.
445///
446/// Uses the TCP key handshake and router. Only an adopted module can register
447/// here with a resume token; plain HELLOs remain clients-only. A peer read
448/// failure costs that connection; a terminal accept error ends the listener.
449pub async fn serve_local_listener(
450    bound: crate::local_listener::BoundLocalListener,
451    router: Arc<Router>,
452    auth: ServerAuth,
453) -> Result<(), ServerError> {
454    match bound {
455        #[cfg(unix)]
456        crate::local_listener::BoundLocalListener::Unix { listener, path } => {
457            serve_unix_local(listener, path, router, auth).await
458        }
459        #[cfg(windows)]
460        crate::local_listener::BoundLocalListener::Windows {
461            pipe_name,
462            first_instance,
463        } => serve_pipe_local(pipe_name, first_instance, router, auth).await,
464        // The variants above exist only on their own platform.
465        #[allow(unreachable_patterns)]
466        _ => Err(ServerError::NoListeners),
467    }
468}
469
470#[cfg(unix)]
471async fn serve_unix_local(
472    listener: std::os::unix::net::UnixListener,
473    path: std::path::PathBuf,
474    router: Arc<Router>,
475    auth: ServerAuth,
476) -> Result<(), ServerError> {
477    serve_unix_local_with_start(listener, path, router, auth, None::<fn()>).await
478}
479
480#[cfg(any(target_os = "linux", target_os = "macos"))]
481pub(crate) async fn serve_resumed_local_listener(
482    bound: crate::local_listener::BoundLocalListener,
483    router: Arc<Router>,
484    auth: ServerAuth,
485    on_accepting: impl FnOnce() + Send,
486) -> Result<(), ServerError> {
487    match bound {
488        crate::local_listener::BoundLocalListener::Unix { listener, path } => {
489            serve_unix_local_with_start(listener, path, router, auth, Some(on_accepting)).await
490        }
491    }
492}
493
494#[cfg(unix)]
495async fn serve_unix_local_with_start(
496    listener: std::os::unix::net::UnixListener,
497    path: std::path::PathBuf,
498    router: Arc<Router>,
499    auth: ServerAuth,
500    on_accepting: Option<impl FnOnce() + Send>,
501) -> Result<(), ServerError> {
502    // The socket file is removed when this future ends, whether it returns or is
503    // dropped during shutdown, so a later daemon start finds no leftover.
504    let _release = SocketFileRelease(path.clone());
505    listener
506        .set_nonblocking(true)
507        .map_err(|source| local_accept_error(&path, source))?;
508    let listener = tokio::net::UnixListener::from_std(listener)
509        .map_err(|source| local_accept_error(&path, source))?;
510    let mut admission = router.forwarding().upgrade_admission.subscribe();
511    // A bound socket or a live TCP loop cannot accept a module's resume HELLO.
512    // Record readiness here, after the Unix socket enters the async accept loop.
513    if let Some(on_accepting) = on_accepting {
514        on_accepting();
515    }
516    loop {
517        let (stream, _addr) = match accept_when_unpaused(&mut admission, || listener.accept()).await
518        {
519            Ok(accepted) => accepted,
520            Err(source) if temporary_accept_failure(&source) => {
521                warn!(error = %source, "temporary local-socket accept failure");
522                if accept_resource_exhausted(&source) {
523                    tokio::time::sleep(Duration::from_millis(75)).await;
524                }
525                continue;
526            }
527            Err(source) => return Err(local_accept_error(&path, source)),
528        };
529        let (peer, diagnostic_pid) =
530            subc_os::local_peer::capture_unix_peer_with_diagnostic_pid(&stream);
531        let opener = diagnostic_pid.map(subc_os::local_peer::DiagnosticProcess::capture);
532        let router = Arc::clone(&router);
533        let auth = auth.clone();
534        tokio::spawn(async move {
535            let _ = handle_accepted_local_connection(stream, router, auth, peer, opener).await;
536        });
537    }
538}
539
540#[cfg(unix)]
541fn local_accept_error(endpoint: &std::path::Path, source: io::Error) -> ServerError {
542    ServerError::LocalAccept {
543        endpoint: endpoint.display().to_string(),
544        source,
545    }
546}
547
548#[cfg(unix)]
549struct SocketFileRelease(std::path::PathBuf);
550
551#[cfg(unix)]
552impl Drop for SocketFileRelease {
553    fn drop(&mut self) {
554        crate::local_listener::remove_unix_socket(&self.0);
555    }
556}
557
558#[cfg(windows)]
559async fn serve_pipe_local(
560    pipe_name: String,
561    first_instance: Option<tokio::net::windows::named_pipe::NamedPipeServer>,
562    router: Arc<Router>,
563    auth: ServerAuth,
564) -> Result<(), ServerError> {
565    // The end a client may connect to. An end exists whenever the loop is not
566    // accepting one, because Win32 refuses a client that finds none, and no
567    // other task accepts ends here.
568    let mut free = first_instance;
569    loop {
570        let server = match free.take() {
571            Some(server) => server,
572            None => create_pipe_instance(&pipe_name)?,
573        };
574        // Overlapped I/O: the accepted end is AsyncRead and AsyncWrite, so a
575        // connection's reader and writer never wait for each other. A
576        // synchronous handle would, and the daemon's reply would sit behind the
577        // reader's pending read while the client waited for that reply.
578        if let Err(source) = server.connect().await {
579            if temporary_accept_failure(&source) {
580                continue;
581            }
582            return Err(ServerError::LocalAccept {
583                endpoint: pipe_name.clone(),
584                source,
585            });
586        }
587        // The next end is made before this one is served, so a client that
588        // arrives while this one is being served still finds an end.
589        free = Some(create_pipe_instance(&pipe_name)?);
590        let router = Arc::clone(&router);
591        let auth = auth.clone();
592        // Refuse network clients before observing a process or reading a byte.
593        // The pipe's PIPE_REJECT_REMOTE_CLIENTS flag is the first gate.
594        let (peer, diagnostic_pid) =
595            match subc_os::local_peer::capture_pipe_client_with_diagnostic_pid(&server) {
596                Ok(capture) => capture,
597                Err(error) => {
598                    warn!(%error, "refused a non-local named-pipe client on the local endpoint");
599                    continue;
600                }
601            };
602        let opener = Some(subc_os::local_peer::DiagnosticProcess::capture(
603            diagnostic_pid,
604        ));
605        tokio::spawn(async move {
606            let _ = handle_accepted_local_connection(server, router, auth, peer, opener).await;
607        });
608    }
609}
610
611#[cfg(windows)]
612fn create_pipe_instance(
613    pipe_name: &str,
614) -> Result<tokio::net::windows::named_pipe::NamedPipeServer, ServerError> {
615    crate::local_listener::create_named_pipe_end(pipe_name).map_err(|source| {
616        ServerError::LocalAccept {
617            endpoint: pipe_name.to_owned(),
618            source,
619        }
620    })
621}
622
623/// Run the shared handshake with local peer credentials for resumable HELLOs.
624async fn handle_accepted_local_connection<S>(
625    stream: S,
626    router: Arc<Router>,
627    auth: ServerAuth,
628    peer: subc_os::local_peer::CapturedPeer,
629    opener: Option<subc_os::local_peer::DiagnosticProcess>,
630) -> Result<(), ConnectionError>
631where
632    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
633{
634    let result =
635        handle_connection_with_peer(stream, router, auth, LocalOrigin::Local, Some(peer), opener)
636            .await;
637    if let Err(error) = &result {
638        debug!(error = %error, "local-endpoint connection ended");
639    }
640    result
641}
642
643/// Where a connection came in. Only a spawn's inherited channel carries its
644/// launch context; local client sockets never acquire module authority.
645#[derive(Debug, Clone)]
646pub(crate) enum LocalOrigin {
647    Tcp,
648    Local,
649    RegistrationChannel(Arc<crate::supervise::RegistrationSpawn>),
650}
651
652/// Serve all already-bound loopback TCP listeners until one accept loop fails.
653pub async fn serve_listeners(
654    listeners: Vec<TcpListener>,
655    router: Arc<Router>,
656    auth: ServerAuth,
657) -> Result<(), ServerError> {
658    if listeners.is_empty() {
659        return Err(ServerError::NoListeners);
660    }
661    router.install_registration_service(auth.clone());
662
663    let (tx, mut rx) = mpsc::channel(listeners.len());
664    let mut accept_tasks = AbortTasksOnDrop::default();
665    for listener in listeners {
666        let router = Arc::clone(&router);
667        let auth = auth.clone();
668        let tx = tx.clone();
669        accept_tasks.push(tokio::spawn(async move {
670            let result = serve_listener(listener, router, auth).await;
671            let _ = tx.send(result).await;
672        }));
673    }
674    drop(tx);
675
676    rx.recv().await.unwrap_or(Ok(()))
677}
678
679#[derive(Default)]
680struct AbortTasksOnDrop {
681    handles: Vec<JoinHandle<()>>,
682}
683
684impl AbortTasksOnDrop {
685    fn push(&mut self, handle: JoinHandle<()>) {
686        self.handles.push(handle);
687    }
688}
689
690impl Drop for AbortTasksOnDrop {
691    fn drop(&mut self) {
692        for handle in &self.handles {
693            if !handle.is_finished() {
694                handle.abort();
695            }
696        }
697    }
698}
699
700#[derive(Debug)]
701enum ConnectionLoopExit {
702    PeerClosed,
703    CloseRequested(CloseReason),
704}
705
706#[derive(Default)]
707struct ConnectionTasks {
708    routes: JoinSet<Result<(), RouterError>>,
709    privileged: JoinSet<Result<(), RouterError>>,
710    activity: JoinSet<Result<(), RouterError>>,
711    #[cfg(test)]
712    refusal_before_send: Option<(
713        tokio::sync::oneshot::Sender<()>,
714        tokio::sync::oneshot::Receiver<()>,
715    )>,
716}
717
718impl ConnectionTasks {
719    async fn shutdown(&mut self) {
720        self.activity.abort_all();
721        self.routes.shutdown().await;
722        self.privileged.shutdown().await;
723        // Accepted appends belong to the writer queue, not these reply waiters.
724        self.activity.shutdown().await;
725    }
726}
727
728/// Run the authenticated frame read -> route loop for one connection.
729///
730/// Every accepted TCP connection must complete the key-auth prelude before any
731/// envelope bytes are read by the router. Outbound frames flow through a bounded
732/// [`FrameSink`] drained by one writer task. Inbound dispatch remains serial for
733/// every frame except `route.open`, activity operations and privileged requests;
734/// their bind, file and operator waits run in connection-owned tasks so
735/// unrelated frames can keep flowing.
736pub async fn handle_connection<S>(
737    stream: S,
738    router: Arc<Router>,
739    auth: ServerAuth,
740) -> Result<(), ConnectionError>
741where
742    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
743{
744    handle_connection_with_origin(stream, router, auth, LocalOrigin::Tcp).await
745}
746
747/// [`handle_connection`] for one endpoint kind: `origin` decides whether a
748/// module HELLO is refused before it can register.
749pub(crate) async fn handle_connection_with_origin<S>(
750    stream: S,
751    router: Arc<Router>,
752    auth: ServerAuth,
753    origin: LocalOrigin,
754) -> Result<(), ConnectionError>
755where
756    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
757{
758    handle_connection_with_peer(stream, router, auth, origin, None, None).await
759}
760
761fn clone_tcp_socket(stream: &tokio::net::TcpStream) -> io::Result<std::net::TcpStream> {
762    #[cfg(unix)]
763    let socket = {
764        use std::os::fd::AsFd;
765        stream.as_fd().try_clone_to_owned()?
766    };
767    #[cfg(windows)]
768    let socket = {
769        use std::os::windows::io::AsSocket;
770        stream.as_socket().try_clone_to_owned()?
771    };
772    Ok(socket.into())
773}
774
775struct ShutdownTcpOnDrop(std::net::TcpStream);
776
777impl Drop for ShutdownTcpOnDrop {
778    fn drop(&mut self) {
779        // Dropping our descriptors is not enough if a forked pre-exec child
780        // retained another copy of this endpoint. Shutdown affects every copy.
781        let _ = self.0.shutdown(std::net::Shutdown::Both);
782    }
783}
784
785async fn handle_connection_with_peer<S>(
786    mut stream: S,
787    router: Arc<Router>,
788    auth: ServerAuth,
789    origin: LocalOrigin,
790    peer: Option<subc_os::local_peer::CapturedPeer>,
791    opener: Option<subc_os::local_peer::DiagnosticProcess>,
792) -> Result<(), ConnectionError>
793where
794    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
795{
796    let channel_spawn = match &origin {
797        LocalOrigin::RegistrationChannel(spawn) => Some(spawn.clone()),
798        _ => None,
799    };
800    let mut upgrade_admission = router.forwarding().upgrade_admission.subscribe();
801    struct RetireRegistration(Option<Arc<crate::supervise::RegistrationSpawn>>);
802    impl Drop for RetireRegistration {
803        fn drop(&mut self) {
804            if let Some(spawn) = &self.0 {
805                spawn.retire_registration_channel();
806            }
807        }
808    }
809    let _registration_lifetime = RetireRegistration(channel_spawn.clone());
810    let channel_closed = async {
811        match &channel_spawn {
812            Some(spawn) => spawn.wait_closed().await,
813            None => std::future::pending().await,
814        }
815    };
816    tokio::pin!(channel_closed);
817    // Capture only socket facts here. Process-table lookup happens lazily on a
818    // blocking thread when privileged dispatch needs a caller description.
819    let endpoints = (&stream as &dyn Any)
820        .downcast_ref::<tokio::net::TcpStream>()
821        .and_then(|tcp| tcp.local_addr().ok().zip(tcp.peer_addr().ok()));
822    // Over-cap connections WAIT for a handshake slot (bounded by the auth deadline)
823    // instead of being reset. A restart herd — every client and supervised child
824    // re-dialing the fresh daemon at once — otherwise loses supervised modules to
825    // the permit lottery: each reset burns a module restart-budget slot, and a
826    // module that treats auth failure as fatal can exhaust its budget into
827    // state=failed within the boot window (2026-07-14 aft outage). On loopback
828    // with the pre-auth HMAC deadline, a bounded queue is strictly safer than a
829    // reset.
830    //
831    // Pre-auth time is governed by TWO deliberately separate budgets: the queue
832    // wait below is bounded by `auth.deadline`, and `authenticate_server` then
833    // starts a FRESH `auth.deadline` for the handshake itself. Total pre-auth
834    // occupancy per connection is therefore up to 2x the configured deadline.
835    // This is intentional, not an accounting slip: charging queue time against
836    // the handshake budget would hand a herd-queued supervised module a
837    // near-zero handshake window under CPU saturation, recreating the fatal
838    // auth-failure -> restart-budget-burn path this queue exists to prevent.
839    // On a loopback-only, key-authenticated listener the doubled bound is a
840    // per-connection occupancy cost, not a meaningful DoS surface.
841    // Each supervised child receives exactly one registration channel. It does
842    // not compete with unauthenticated TCP callers for a pre-auth pool slot.
843    let permit = if channel_spawn.is_some() {
844        None
845    } else {
846        Some(tokio::select! {
847            biased;
848            _ = wait_for_upgrade_listener_pause(&mut upgrade_admission) => return Ok(()),
849            _ = &mut channel_closed => return Ok(()),
850            result = tokio::time::timeout(auth.deadline, auth.unauthenticated.clone().acquire_owned()) => match result {
851                Ok(Ok(permit)) => permit,
852                Ok(Err(_)) | Err(_) => {
853                    let _ = stream.shutdown().await;
854                    return Err(ConnectionError::UnauthenticatedCapacity);
855                }
856            }
857        })
858    };
859    let handshake_budget = channel_spawn.as_ref().map_or(auth.deadline, |spawn| {
860        spawn
861            .deadline()
862            .saturating_duration_since(tokio::time::Instant::now())
863    });
864    let authenticated = tokio::select! {
865        biased;
866        _ = wait_for_upgrade_listener_pause(&mut upgrade_admission) => return Ok(()),
867        _ = &mut channel_closed => { let _ = stream.shutdown().await; return Ok(()); },
868        result = authenticate_server(
869        &mut stream,
870        auth.key.as_ref(),
871        &auth.daemon_id,
872        auth.daemon_ver.as_ref(),
873        handshake_budget,
874        ) => result.map_err(ConnectionError::Auth)?,
875    };
876    drop(permit);
877
878    // Keep shutdown until after writer drain, including when the connection
879    // future is cancelled. Authentication refusals retain their existing path.
880    let _tcp_shutdown = (&stream as &dyn Any)
881        .downcast_ref::<tokio::net::TcpStream>()
882        .map(|tcp| clone_tcp_socket(tcp).map(ShutdownTcpOnDrop))
883        .transpose()
884        .map_err(|err| ConnectionError::FrameIo(FrameIoError::Io(err)))?;
885
886    let mut connection = router.begin_connection();
887    let connection_id = connection.id();
888    if let LocalOrigin::RegistrationChannel(spawn) = &origin {
889        spawn.bind(connection_id);
890    }
891    router.record_caller_endpoints(connection_id, endpoints);
892    use crate::control::RouteOpenerConnection;
893    match &origin {
894        LocalOrigin::Local => {
895            router.record_local_connection(connection_id);
896            router.record_route_opener(connection_id, RouteOpenerConnection::Local(opener));
897        }
898        LocalOrigin::Tcp => router.record_route_opener(connection_id, RouteOpenerConnection::Tcp),
899        LocalOrigin::RegistrationChannel(_) => {}
900    }
901    if let Some(peer) = peer {
902        router.record_captured_peer(connection_id, peer);
903    }
904    // `authenticated.role` is CLIENT-SUPPLIED and unverified -- the handshake
905    // proves possession of the connection key, nothing about who is calling. So
906    // this exclusion is safe ONLY while the role decides a reporting question and
907    // never an authorization one: the watchdog's own loopback probe would
908    // otherwise inflate the very count it exists to sanity-check.
909    //
910    // The consequence of it being unverified, stated so nobody has to rediscover
911    // it: ANY client holding the key can claim this role and omit itself from
912    // `connected_clients`. That is a gauge a caller can lie to, and it is
913    // acceptable because the gauge informs an operator rather than gating
914    // anything. IF A ROLE IS EVER USED TO DECIDE ADMISSION, CAPACITY, OR PRIVILEGE,
915    // this stops being safe and the role must be attested rather than declared --
916    // the daemon already has the mechanism for that in the spawn-nonce path used
917    // for module identity.
918    let _connected_client = (authenticated.role != WATCHDOG_CLIENT_ROLE)
919        .then(|| auth.connected_clients.open(connection_id));
920    let close_receiver = connection.take_close_receiver();
921    debug!(
922        connection_id = connection_id.get(),
923        "subc authenticated connection opened"
924    );
925
926    let (read_half, write_half) = tokio::io::split(stream);
927    // Authentication is complete before this buffer can read ahead. The connection loop
928    // retains a partial frame read across completed route.open tasks; dropping the read
929    // happens only when a frame finishes or the connection ends.
930    let mut read_half = BufReader::new(read_half);
931    let (egress, rx) = connection_egress();
932    let delivery_guard = ClientDeliveryGuard(egress.clone());
933    let writer = tokio::spawn(drain_writer(write_half, rx));
934
935    let ctx = RouteCtx {
936        connection_id,
937        egress: egress.clone(),
938    };
939
940    let mut tasks = ConnectionTasks::default();
941    let registration_expired = async {
942        match &channel_spawn {
943            Some(spawn) => spawn.registration_expired().await,
944            None => std::future::pending().await,
945        }
946    };
947    let loop_result = tokio::select! {
948        _ = registration_expired => Ok(ConnectionLoopExit::CloseRequested(CloseReason::new("registration_timeout", "module did not complete HELLO before its spawn deadline"))),
949        _ = &mut channel_closed => Ok(ConnectionLoopExit::CloseRequested(CloseReason::new("registration_channel_closed", "the supervised launch ended"))),
950        result = connection_loop(
951        &mut read_half,
952        Arc::clone(&router),
953        ctx.clone(),
954        close_receiver,
955        &mut tasks,
956        origin,
957        ) => result,
958    };
959
960    // EOF and errors revoke an accepted or required registration before task
961    // withdrawal or writer drain can await. An unused legacy channel does not
962    // end its child's nonce authority. The TCP shutdown guard invalidates
963    // inherited endpoint copies after queued output has had its bounded drain.
964    if let Some(spawn) = &channel_spawn {
965        spawn.retire_registration_channel();
966    }
967    drop(delivery_guard);
968    // Every in-flight route.open must have FINISHED before `connection` drops,
969    // because that drop runs the forwarding cleanup for this id, and cleanup is
970    // also where the id's closing mark is lifted. Dropping a JoinSet only
971    // requests abort: a task already running on another worker keeps going
972    // until its next await, and could commit a route for this connection after
973    // cleanup has cleared it, with nothing left to refuse it and nothing to
974    // clean it up. shutdown() aborts and then waits.
975    // Include approval withdrawals and activity publishers before lifting the
976    // cleanup state or sweeping this connection's subscriptions and endpoints.
977    tasks.shutdown().await;
978
979    drop(ctx);
980    drop(egress);
981    drop(connection);
982
983    let close_reason = match &loop_result {
984        Ok(ConnectionLoopExit::CloseRequested(reason)) => Some(reason.to_string()),
985        Ok(ConnectionLoopExit::PeerClosed) | Err(_) => None,
986    };
987    let writer_result = finish_connection_writer(writer, connection_id.get()).await;
988
989    let result = if let Some(reason) = close_reason.as_deref() {
990        match writer_result {
991            Some(Ok(Ok(()))) | None => Ok(()),
992            Some(Ok(Err(writer_err))) => {
993                debug!(
994                    connection_id = connection_id.get(),
995                    close_reason = reason,
996                    writer_error = %writer_err,
997                    "writer failed after requested connection close"
998                );
999                Ok(())
1000            }
1001            Some(Err(join_err)) => {
1002                warn!(
1003                    connection_id = connection_id.get(),
1004                    close_reason = reason,
1005                    join_error = %join_err,
1006                    "writer task join failed after requested connection close"
1007                );
1008                Ok(())
1009            }
1010        }
1011    } else {
1012        match (loop_result, writer_result) {
1013            (Err(loop_err), Some(Ok(Ok(()))) | None) => Err(loop_err),
1014            (Err(loop_err), Some(Ok(Err(writer_err)))) => {
1015                warn!(
1016                    connection_id = connection_id.get(),
1017                    writer_error = %writer_err,
1018                    "writer failed while closing after connection error"
1019                );
1020                Err(loop_err)
1021            }
1022            (Err(loop_err), Some(Err(join_err))) => {
1023                warn!(
1024                    connection_id = connection_id.get(),
1025                    join_error = %join_err,
1026                    "writer task join failed while closing after connection error"
1027                );
1028                Err(loop_err)
1029            }
1030            (Ok(ConnectionLoopExit::PeerClosed), Some(Ok(Ok(()))) | None) => Ok(()),
1031            (Ok(ConnectionLoopExit::PeerClosed), Some(Ok(Err(writer_err)))) => {
1032                Err(ConnectionError::FrameIo(writer_err))
1033            }
1034            (Ok(ConnectionLoopExit::PeerClosed), Some(Err(join_err))) => Err(join_err),
1035            (Ok(ConnectionLoopExit::CloseRequested(_)), _) => {
1036                unreachable!("close requests are handled before normal writer result matching")
1037            }
1038        }
1039    };
1040
1041    match &result {
1042        Ok(()) => {
1043            if let Some(reason) = close_reason.as_deref() {
1044                debug!(
1045                    connection_id = connection_id.get(),
1046                    close_reason = reason,
1047                    "subc connection closed by request"
1048                );
1049            } else {
1050                debug!(
1051                    connection_id = connection_id.get(),
1052                    "subc connection closed"
1053                );
1054            }
1055        }
1056        Err(err) => debug!(
1057            connection_id = connection_id.get(),
1058            error = %err,
1059            "subc connection exited with error"
1060        ),
1061    }
1062
1063    result
1064}
1065
1066async fn finish_connection_writer(
1067    mut writer: JoinHandle<Result<(), FrameIoError>>,
1068    connection_id: u64,
1069) -> Option<Result<Result<(), FrameIoError>, ConnectionError>> {
1070    // Even after inbound EOF or an error, the peer may keep its receive side
1071    // open without reading. Give queued frames the same grace on every exit.
1072    match timeout(CLOSE_DRAIN_GRACE, &mut writer).await {
1073        Ok(result) => Some(result.map_err(ConnectionError::WriterTask)),
1074        Err(_) => {
1075            warn!(
1076                connection_id,
1077                grace = ?CLOSE_DRAIN_GRACE,
1078                "connection writer did not drain during teardown; aborting writer task"
1079            );
1080            writer.abort();
1081            let _ = writer.await;
1082            None
1083        }
1084    }
1085}
1086
1087#[cfg(all(test, unix))]
1088pub(crate) fn config_test_connection_loop(
1089    router: Arc<Router>,
1090) -> (
1091    crate::ConnectionId,
1092    tokio::io::DuplexStream,
1093    JoinHandle<Result<(), ConnectionError>>,
1094) {
1095    let mut connection = router.begin_connection();
1096    let id = connection.id();
1097    let close = connection.take_close_receiver();
1098    router.record_local_connection(id);
1099    let (client, server) = tokio::io::duplex(64 * 1024);
1100    let (mut read, mut write) = tokio::io::split(server);
1101    let (sender, mut outgoing) = tokio::sync::mpsc::channel::<crate::router::OutboundFrame>(8);
1102    let ctx = RouteCtx {
1103        connection_id: id,
1104        egress: crate::FrameSink::new(sender),
1105    };
1106    let writer = tokio::spawn(async move {
1107        while let Some(mut outbound) = outgoing.recv().await {
1108            if crate::write_frame(&mut write, &outbound.frame)
1109                .await
1110                .is_err()
1111                || tokio::io::AsyncWriteExt::flush(&mut write).await.is_err()
1112            {
1113                break;
1114            }
1115            if let Some(flushed) = outbound.flushed.take() {
1116                let _ = flushed.send(());
1117            }
1118        }
1119    });
1120    let task = tokio::spawn(async move {
1121        let mut tasks = ConnectionTasks::default();
1122        let result = connection_loop(
1123            &mut read,
1124            router,
1125            ctx.clone(),
1126            close,
1127            &mut tasks,
1128            LocalOrigin::Local,
1129        )
1130        .await;
1131        tasks.shutdown().await;
1132        drop(ctx);
1133        drop(connection);
1134        writer.abort();
1135        let _ = writer.await;
1136        result.map(|_| ())
1137    });
1138    (id, client, task)
1139}
1140
1141async fn connection_loop<R>(
1142    read_half: &mut R,
1143    router: Arc<Router>,
1144    ctx: RouteCtx,
1145    mut close_receiver: ConnectionCloseReceiver,
1146    tasks: &mut ConnectionTasks,
1147    origin: LocalOrigin,
1148) -> Result<ConnectionLoopExit, ConnectionError>
1149where
1150    R: AsyncRead + Unpin,
1151{
1152    #[cfg(test)]
1153    let mut refusal_before_send = tasks.refusal_before_send.take();
1154    let ConnectionTasks {
1155        routes: route_open_tasks,
1156        privileged: privileged_tasks,
1157        activity: activity_tasks,
1158        ..
1159    } = tasks;
1160    let forwarding = router.forwarding();
1161    let mut upgrade_admission = forwarding.upgrade_admission.subscribe();
1162    let (phase, _live_reader) = forwarding.start_upgrade_reader(ctx.connection_id);
1163    close_receiver.initialize_phase(phase);
1164    loop {
1165        while let Some(result) = activity_tasks.try_join_next() {
1166            finish_route_open_task(result)?;
1167        }
1168        while let Some(result) = privileged_tasks.try_join_next() {
1169            finish_route_open_task(result)?;
1170        }
1171        while let Some(result) = route_open_tasks.try_join_next() {
1172            finish_route_open_task(result)?;
1173        }
1174
1175        // Keep the same read future when a route.open completes: read_frame owns
1176        // partial header/body buffers that would be lost if that future were dropped.
1177        let read = read_frame(&mut *read_half);
1178        tokio::pin!(read);
1179        close_receiver.acknowledge_reader();
1180        let frame = loop {
1181            let can_read = !close_receiver.phase().clients_frozen();
1182            tokio::select! {
1183                biased;
1184                signal = close_receiver.next_signal() => {
1185                    match signal {
1186                        Ok(None) => close_receiver.acknowledge_reader(),
1187                        Ok(Some(reason)) => return Ok(ConnectionLoopExit::CloseRequested(reason)),
1188                        Err(error) => return Ok(ConnectionLoopExit::CloseRequested(close_reason(Err(error)))),
1189                    }
1190                }
1191                _ = wait_for_upgrade_listener_pause(&mut upgrade_admission), if matches!(&origin, LocalOrigin::RegistrationChannel(spawn) if !spawn.registered()) => {
1192                    return Ok(ConnectionLoopExit::PeerClosed);
1193                }
1194                result = route_open_tasks.join_next(), if !route_open_tasks.is_empty() => {
1195                    finish_route_open_task(
1196                        result.expect("a non-empty route.open JoinSet has a next task")
1197                    )?;
1198                }
1199                result = activity_tasks.join_next(), if !activity_tasks.is_empty() => {
1200                    finish_route_open_task(result.expect("non-empty activity task set"))?;
1201                }
1202                result = privileged_tasks.join_next(), if !privileged_tasks.is_empty() => {
1203                    finish_route_open_task(result.expect("non-empty privileged task set"))?;
1204                }
1205                result = &mut read, if can_read => {
1206                    break match result.map_err(ConnectionError::FrameIo)? {
1207                        Some(frame) => frame,
1208                        None => return Ok(ConnectionLoopExit::PeerClosed),
1209                    };
1210                }
1211            }
1212        };
1213
1214        // A close notification can lose an unbiased select to buffered input.
1215        // Terminal ingress fences both inline handling and every offload below.
1216        if ctx.egress.ingress_terminal() {
1217            return Ok(ConnectionLoopExit::PeerClosed);
1218        }
1219        let first = ctx.egress.first_ingress_frame();
1220        let hello = frame.header.ty == subc_protocol::FrameType::Hello;
1221        if hello && upgrade_admission.borrow().listeners_paused() {
1222            return Ok(ConnectionLoopExit::PeerClosed);
1223        }
1224        if frame.header.channel == 0 && frame.header.ty == subc_protocol::FrameType::Goodbye {
1225            activity_tasks.shutdown().await;
1226        }
1227        if let Some((code, message)) = hello_transport_refusal(&origin, &frame) {
1228            ctx.egress.terminate_ingress();
1229            let refusal = crate::control::control_error_frame(&frame, code, message)
1230                .map_err(ConnectionError::Router)?;
1231            // The connection ends as soon as the refusal is sent, so the bytes
1232            // must reach the socket first: a client that has not yet read its
1233            // reply would otherwise see only the end of the stream.
1234            let send_result = tokio::select! {
1235                close = &mut close_receiver => {
1236                    return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1237                }
1238                result = router.observe_connection_wait(&ctx, "reply_egress", send_refusal(&ctx.egress, refusal)) => result,
1239            };
1240            send_result.map_err(ConnectionError::Router)?;
1241            return Ok(ConnectionLoopExit::PeerClosed);
1242        }
1243
1244        if let LocalOrigin::RegistrationChannel(spawn) = &origin {
1245            let hello = frame.header.ty == subc_protocol::FrameType::Hello;
1246            if (!spawn.registered() && !hello) || (spawn.registered() && hello) {
1247                ctx.egress.terminate_ingress();
1248                spawn.retire_registration_channel();
1249                return Ok(ConnectionLoopExit::PeerClosed);
1250            }
1251        }
1252
1253        let control_dispatch = ControlDispatch::of(&frame);
1254        if control_dispatch == ControlDispatch::Activity {
1255            // Bound outstanding activity tasks as well as the disk queue,
1256            // so the reader never waits for either capacity when the disk stalls.
1257            if activity_tasks.len() >= 128 {
1258                let response = crate::control::control_error_frame(
1259                    &frame,
1260                    subc_control::ACTIVITY_UNAVAILABLE,
1261                    "activity queue full",
1262                )
1263                .map_err(ConnectionError::Router)?;
1264                let send_result = tokio::select! {
1265                    close = &mut close_receiver => {
1266                        return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1267                    }
1268                    result = router.observe_connection_wait(&ctx, "reply_egress", ctx.egress.send(response)) => result,
1269                };
1270                send_result.map_err(ConnectionError::Router)?;
1271            } else {
1272                // Reserved before the hand-off, so a CANCEL the reader handles
1273                // next finds this subscription even before it is installed.
1274                let reservation = router.reserve_activity_subscription(&ctx, &frame);
1275                let task_router = Arc::clone(&router);
1276                let task_ctx = ctx.clone();
1277                activity_tasks.spawn(async move {
1278                    let _reservation = reservation;
1279                    route_open_tail(&task_router, task_ctx, frame, Instant::now(), first).await
1280                });
1281            }
1282            continue;
1283        }
1284
1285        if let Some(target_module_id) = (control_dispatch == ControlDispatch::RouteOpen)
1286            .then(|| router.route_open_target(&frame))
1287            .flatten()
1288        {
1289            // A task can finish while the reader is waiting for the next frame.
1290            // Reap it before checking admission so completed work never occupies
1291            // one of the deliberately scarce connection slots.
1292            while let Some(result) = route_open_tasks.try_join_next() {
1293                finish_route_open_task(result)?;
1294            }
1295
1296            if route_open_tasks.len() >= MAX_PENDING_ROUTE_OPENS_PER_CONNECTION {
1297                // Never wait for capacity here: doing so would recreate the same
1298                // reader head-of-line stall with a smaller constant.
1299                let refusal = router
1300                    .route_open_capacity_refusal(
1301                        &ctx,
1302                        &frame,
1303                        &target_module_id,
1304                        route_open_tasks.len(),
1305                        MAX_PENDING_ROUTE_OPENS_PER_CONNECTION,
1306                    )
1307                    .map_err(ConnectionError::Router)?;
1308                let send_result = tokio::select! {
1309                    close = &mut close_receiver => {
1310                        return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1311                    }
1312                    result = router.observe_connection_wait(&ctx, "reply_egress", ctx.egress.send(refusal)) => result,
1313                };
1314                send_result.map_err(ConnectionError::Router)?;
1315                continue;
1316            }
1317
1318            let task_router = router.clone().track_cutover_task();
1319            let task_ctx = ctx.clone();
1320            // Start slow-dispatch timing before spawn so it covers the task's
1321            // full scheduler and handler lifetime, as inline timing did.
1322            let dispatch_started_at = Instant::now();
1323            route_open_tasks.spawn(async move {
1324                route_open_tail(
1325                    task_router.owner(),
1326                    task_ctx,
1327                    frame,
1328                    dispatch_started_at,
1329                    first,
1330                )
1331                .await
1332            });
1333            continue;
1334        }
1335
1336        if router.defers_config_approval(&frame) || router.defers_privileged_control(&ctx, &frame) {
1337            let reservation = match router.reserve_config_approval(&ctx, &frame) {
1338                Ok(reservation) => reservation,
1339                Err(error) => {
1340                    ctx.egress
1341                        .send(
1342                            crate::control::control_error_body_frame(
1343                                &frame,
1344                                subc_protocol::ErrorBody {
1345                                    code: error.code,
1346                                    message: error.detail,
1347                                    detail: None,
1348                                },
1349                            )
1350                            .map_err(ConnectionError::Router)?,
1351                        )
1352                        .await
1353                        .map_err(ConnectionError::Router)?;
1354                    continue;
1355                }
1356            };
1357            // Configuration prompts for the specific plan, not the generic
1358            // privileged operation. Only task lifetime/reader scheduling is shared.
1359            let task_router = Arc::clone(&router);
1360            let task_ctx = ctx.clone();
1361            let started = Instant::now();
1362            privileged_tasks.spawn(async move {
1363                // The future owns cleanup even if it is dropped before its
1364                // first poll or authorization refuses before approval begins.
1365                let _reservation = reservation;
1366                route_open_tail(&task_router, task_ctx, frame, started, first).await
1367            });
1368            continue;
1369        }
1370
1371        // Other frames still route serially: routing can backpressure reads,
1372        // and a connection close cancels the in-progress route.
1373        let route_result = tokio::select! {
1374            biased;
1375            _ = wait_for_upgrade_listener_pause(&mut upgrade_admission), if hello => {
1376                return Ok(ConnectionLoopExit::PeerClosed);
1377            }
1378            close = &mut close_receiver => {
1379                return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1380            }
1381            result = router.route_for_connection_ingress(&ctx, frame, None, first) => result,
1382        };
1383
1384        if let Err(err) = route_result {
1385            if let Some(reply) = router.prepare_routed_error(&err) {
1386                #[cfg(test)]
1387                if let Some((built, release)) = refusal_before_send.take() {
1388                    let _ = built.send(());
1389                    let _ = release.await;
1390                }
1391                warn!(
1392                    connection_id = ctx.connection_id.get(),
1393                    error = %err,
1394                    "routing failure recovered with ERROR frame"
1395                );
1396                let send_result = tokio::select! {
1397                    biased;
1398                    close = &mut close_receiver => {
1399                        return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1400                    }
1401                    result = router.observe_connection_wait(&ctx, "reply_egress", reply.send(&ctx.egress)) => result,
1402                };
1403                send_result.map_err(ConnectionError::Router)?;
1404            } else {
1405                debug!(
1406                    connection_id = ctx.connection_id.get(),
1407                    error = %err,
1408                    "fatal routing failure"
1409                );
1410                return Err(ConnectionError::Router(err));
1411            }
1412        }
1413    }
1414}
1415
1416async fn accept_when_unpaused<F, T>(
1417    admission: &mut tokio::sync::watch::Receiver<crate::control::upgrade_in_place::Admission>,
1418    mut accept: impl FnMut() -> F,
1419) -> T
1420where
1421    F: std::future::Future<Output = T>,
1422{
1423    loop {
1424        let _ = admission.wait_for(|phase| !phase.listeners_paused()).await;
1425        tokio::select! {
1426            biased;
1427            _ = wait_for_upgrade_listener_pause(admission) => {},
1428            accepted = accept() => {
1429                // If accept raced the pause, keep the socket unopened at the
1430                // protocol layer until unwind. Exec closes it like the backlog.
1431                let _ = admission.wait_for(|phase| !phase.listeners_paused()).await;
1432                return accepted;
1433            }
1434        }
1435    }
1436}
1437
1438async fn wait_for_upgrade_listener_pause(
1439    admission: &mut tokio::sync::watch::Receiver<crate::control::upgrade_in_place::Admission>,
1440) {
1441    let _ = admission.wait_for(|phase| phase.listeners_paused()).await;
1442}
1443
1444fn hello_transport_refusal(
1445    origin: &LocalOrigin,
1446    frame: &crate::Frame,
1447) -> Option<(&'static str, &'static str)> {
1448    use crate::supervise::resume_hello;
1449    if frame.header.ty != subc_protocol::FrameType::Hello {
1450        return None;
1451    }
1452    let local = matches!(origin, LocalOrigin::Local);
1453    let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
1454    if let Some(value) = value
1455        .as_ref()
1456        .filter(|value| resume_hello::has_resume_token(value))
1457    {
1458        if !local
1459            || !cfg!(any(target_os = "macos", target_os = "linux"))
1460            || frame.header.channel != 0
1461            || resume_hello::parse_resume_hash(value).is_none()
1462        {
1463            return Some((resume_hello::REFUSED, resume_hello::REFUSAL_MESSAGE));
1464        }
1465    } else if local {
1466        return Some((
1467            crate::local_listener::LOCAL_ENDPOINT_CLIENTS_ONLY,
1468            "the local endpoint serves clients only; modules register over TCP",
1469        ));
1470    }
1471    None
1472}
1473
1474/// Send a refusal before ending the connection. Unix waits for a writer flush;
1475/// other platforms retain their existing queue-only refusal policy.
1476async fn send_refusal(sink: &FrameSink, frame: crate::Frame) -> Result<(), RouterError> {
1477    #[cfg(unix)]
1478    {
1479        sink.send_flushed(frame).await
1480    }
1481    #[cfg(not(unix))]
1482    {
1483        sink.send(frame).await
1484    }
1485}
1486
1487#[derive(Clone, Copy, PartialEq, Eq)]
1488enum ControlDispatch {
1489    Activity,
1490    RouteOpen,
1491    Other,
1492}
1493
1494impl ControlDispatch {
1495    fn of(frame: &crate::Frame) -> Self {
1496        if frame.header.channel != 0 || frame.header.ty != subc_protocol::FrameType::Request {
1497            return Self::Other;
1498        }
1499        #[derive(serde::Deserialize)]
1500        struct Op<'a> {
1501            #[serde(borrow)]
1502            op: std::borrow::Cow<'a, str>,
1503        }
1504        let Ok(op) = serde_json::from_slice::<Op<'_>>(&frame.body) else {
1505            return Self::Other;
1506        };
1507        match op.op.as_ref() {
1508            subc_control::ops::ACTIVITY_RECORD
1509            | subc_control::ops::ACTIVITY_QUERY
1510            | subc_control::ops::ACTIVITY_SUBSCRIBE => Self::Activity,
1511            subc_control::ops::ROUTE_OPEN => Self::RouteOpen,
1512            _ => Self::Other,
1513        }
1514    }
1515}
1516
1517async fn route_open_tail(
1518    router: &Router,
1519    ctx: RouteCtx,
1520    frame: crate::Frame,
1521    dispatch_started_at: Instant,
1522    first: bool,
1523) -> Result<(), RouterError> {
1524    match router
1525        .route_for_connection_ingress(&ctx, frame, Some(dispatch_started_at), first)
1526        .await
1527    {
1528        Ok(()) => Ok(()),
1529        Err(err) => {
1530            let Some(reply) = router.prepare_routed_error(&err) else {
1531                return Err(err);
1532            };
1533            warn!(
1534                connection_id = ctx.connection_id.get(),
1535                error = %err,
1536                "routing failure recovered with ERROR frame"
1537            );
1538            router
1539                .observe_connection_wait(&ctx, "reply_egress", reply.send(&ctx.egress))
1540                .await
1541        }
1542    }
1543}
1544
1545fn finish_route_open_task(
1546    result: Result<Result<(), RouterError>, tokio::task::JoinError>,
1547) -> Result<(), ConnectionError> {
1548    match result {
1549        Ok(Ok(())) => Ok(()),
1550        Ok(Err(err)) => Err(ConnectionError::Router(err)),
1551        Err(err) => Err(ConnectionError::Router(RouterError::backend(
1552            0,
1553            0,
1554            format!("route.open task failed: {err}"),
1555        ))),
1556    }
1557}
1558
1559fn close_reason(
1560    result: Result<CloseReason, tokio::sync::oneshot::error::RecvError>,
1561) -> CloseReason {
1562    result.unwrap_or_else(|_| {
1563        CloseReason::new(
1564            "close_registry_dropped",
1565            "connection close registration was dropped without a reason",
1566        )
1567    })
1568}
1569
1570/// The outbound queue for one daemon connection: a sink bounded by
1571/// [`CONNECTION_EGRESS_BYTE_BUDGET`] and [`CONNECTION_EGRESS_FRAME_CAP`], and
1572/// the receiver its writer drains.
1573pub(crate) fn connection_egress() -> (FrameSink, mpsc::Receiver<crate::router::OutboundFrame>) {
1574    let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(CONNECTION_EGRESS_FRAME_CAP);
1575    (
1576        FrameSink::with_byte_budget(tx, CONNECTION_EGRESS_BYTE_BUDGET),
1577        rx,
1578    )
1579}
1580
1581pub(crate) async fn drain_writer<W>(
1582    write_half: W,
1583    mut rx: mpsc::Receiver<crate::router::OutboundFrame>,
1584) -> Result<(), FrameIoError>
1585where
1586    W: AsyncWrite + Unpin,
1587{
1588    let mut writer = BufWriter::new(write_half);
1589    while let Some(outbound) = rx.recv().await {
1590        write_outbound(&mut writer, outbound).await?;
1591        while let Ok(outbound) = rx.try_recv() {
1592            write_outbound(&mut writer, outbound).await?;
1593        }
1594        writer.flush().await.map_err(FrameIoError::Io)?;
1595    }
1596    writer.flush().await.map_err(FrameIoError::Io)?;
1597    Ok(())
1598}
1599
1600/// Reply-path half of slow-control diagnosis: a channel-0 reply that sat in
1601/// the writer queue past the threshold is reported with its queue residency
1602/// and its own write duration separated, because "writer task not scheduled"
1603/// and "socket write blocked" are different defects and the sum hides which.
1604/// Data-plane frames are exempt: their latency is the client's own flow
1605/// control, and logging them would drown the control signal in bulk traffic.
1606async fn write_outbound<W>(
1607    writer: &mut BufWriter<W>,
1608    outbound: crate::router::OutboundFrame,
1609) -> Result<(), FrameIoError>
1610where
1611    W: AsyncWrite + Unpin,
1612{
1613    const SLOW_REPLY_QUEUE: Duration = Duration::from_millis(1000);
1614    let queued = outbound.enqueued_at.elapsed();
1615    // Held until this frame has been written, then dropped at the end of this
1616    // function, which gives its bytes back to the connection's egress budget.
1617    let charge = outbound.charge;
1618    if let Some(charge) = &charge {
1619        charge.taken_by_writer();
1620    }
1621    let frame = outbound.frame;
1622    #[cfg(all(
1623        feature = "test-support",
1624        any(target_os = "linux", target_os = "macos")
1625    ))]
1626    if let Some(gate) = outbound.fixture_flush_gate {
1627        crate::control::upgrade_in_place::wait_at_gate(&gate, 3)
1628            .await
1629            .map_err(FrameIoError::Io)?;
1630    }
1631    if frame.header.channel == 0 && queued >= SLOW_REPLY_QUEUE {
1632        let write_started = std::time::Instant::now();
1633        let result = write_frame(writer, &frame).await;
1634        tracing::warn!(
1635            corr = frame.header.corr,
1636            queued_ms = queued.as_millis() as u64,
1637            write_ms = write_started.elapsed().as_millis() as u64,
1638            "slow control reply write"
1639        );
1640        result?;
1641    } else {
1642        write_frame(writer, &frame).await?;
1643    }
1644    if let Some(flushed) = outbound.flushed {
1645        // Upgrade GOODBYE reserves every queue slot before entering this FIFO.
1646        // An earlier sender with a slot either queued before it or did not
1647        // send. Flushing GOODBYE therefore flushes all earlier writes too.
1648        writer.flush().await.map_err(FrameIoError::Io)?;
1649        let _ = flushed.send(());
1650    }
1651    Ok(())
1652}
1653
1654#[cfg(all(test, unix))]
1655#[tokio::test]
1656async fn shutdown_notice_ack_waits_for_socket_flush() {
1657    let (socket, mut peer) = tokio::io::duplex(1);
1658    let (tx, rx) = mpsc::channel(1);
1659    let sink = FrameSink::new(tx);
1660    let writer = tokio::spawn(drain_writer(socket, rx));
1661    let frame = crate::Frame::build(
1662        subc_protocol::FrameType::Push,
1663        subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
1664        0,
1665        0,
1666        0,
1667        b"notice".to_vec(),
1668    )
1669    .unwrap();
1670    let send = sink.send_flushed(frame);
1671    tokio::pin!(send);
1672    assert!(
1673        timeout(Duration::from_millis(20), &mut send).await.is_err(),
1674        "queueing bytes is not a socket flush acknowledgement"
1675    );
1676    let (sent, received) = timeout(Duration::from_secs(1), async {
1677        tokio::join!(&mut send, read_frame(&mut peer))
1678    })
1679    .await
1680    .unwrap();
1681    sent.unwrap();
1682    assert_eq!(received.unwrap().unwrap().body, b"notice");
1683    writer.abort();
1684}
1685
1686#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
1687#[tokio::test]
1688async fn close_requested_reader_stays_counted_while_its_request_is_parked() {
1689    closing_reader_accounts_for_dropped_request(false).await;
1690}
1691
1692#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
1693#[tokio::test]
1694async fn closing_reader_accounts_for_a_refusal_built_before_close() {
1695    closing_reader_accounts_for_dropped_request(true).await;
1696}
1697
1698#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
1699async fn closing_reader_accounts_for_dropped_request(already_built_refusal: bool) {
1700    use crate::{
1701        forwarding::{DataRoute, DataRouteState, RouteBindRelayOutcome},
1702        ConnectionId,
1703    };
1704    use subc_protocol::{
1705        manifest::Concurrency, Flags, Frame, FrameType, Priority, PROTOCOL_VERSION,
1706    };
1707
1708    let router = Arc::new(Router::default());
1709    let forwarding = router.forwarding();
1710    let mut connection = router.begin_connection();
1711    let (reader_sink, mut reader_replies) = connection_egress();
1712    let ctx = RouteCtx {
1713        connection_id: connection.id(),
1714        egress: reader_sink,
1715    };
1716    let (module_tx, mut module_rx) = mpsc::channel(1);
1717    let sink = FrameSink::new(module_tx);
1718    let module = ConnectionId::new(15_000);
1719    forwarding
1720        .register_module_connection(
1721            module,
1722            "blocked-module".into(),
1723            PROTOCOL_VERSION,
1724            Concurrency::ModuleManaged,
1725            sink.clone(),
1726        )
1727        .unwrap();
1728    let (client_sink, mut client_rx) = connection_egress();
1729    let route = forwarding
1730        .begin_route_bind_relay_for_test(ctx.connection_id, client_sink, 80, "blocked-module")
1731        .unwrap();
1732    forwarding
1733        .complete_pending_relay(module, route.corr, RouteBindRelayOutcome::Accepted)
1734        .unwrap();
1735    assert_eq!(client_rx.try_recv().unwrap().header.corr, 80);
1736    let flags = Flags::new(false, Priority::Passive, false);
1737    sink.try_send(Frame::build(FrameType::Push, flags, 0, 0, 81, vec![]).unwrap())
1738        .unwrap();
1739    let (mut peer, mut reader) = tokio::io::duplex(4096);
1740    let request = Frame::build(
1741        FrameType::Request,
1742        flags,
1743        route.client_channel,
1744        route.client_epoch,
1745        82,
1746        vec![],
1747    )
1748    .unwrap();
1749    crate::write_frame(&mut peer, &request).await.unwrap();
1750
1751    let mut tasks = ConnectionTasks::default();
1752    let refusal_pause = already_built_refusal.then(|| {
1753        let (built, seen) = tokio::sync::oneshot::channel();
1754        let (resume, wait) = tokio::sync::oneshot::channel();
1755        tasks.refusal_before_send = Some((built, wait));
1756        (seen, resume)
1757    });
1758    let loop_future = connection_loop(
1759        &mut reader,
1760        router,
1761        ctx.clone(),
1762        connection.take_close_receiver(),
1763        &mut tasks,
1764        LocalOrigin::Tcp,
1765    );
1766    tokio::pin!(loop_future);
1767    std::future::poll_fn(|cx| {
1768        assert!(std::future::Future::poll(loop_future.as_mut(), cx).is_pending());
1769        std::task::Poll::Ready(())
1770    })
1771    .await;
1772    let DataRoute::Client(DataRouteState::Bound(binding)) = forwarding
1773        .lookup_data_route(ctx.connection_id, route.client_channel, route.client_epoch)
1774        .unwrap()
1775    else {
1776        panic!("expected bound route");
1777    };
1778    assert_eq!(
1779        binding.flow.in_flight(),
1780        1,
1781        "the reader decoded the request and took credit before blocking on the writer"
1782    );
1783
1784    forwarding.upgrade_refusals.begin();
1785    let resume = if let Some((mut seen, resume)) = refusal_pause {
1786        forwarding.set_upgrade_admission(crate::control::upgrade_in_place::Admission::Fenced);
1787        std::future::poll_fn(|cx| {
1788            assert!(std::future::Future::poll(loop_future.as_mut(), cx).is_pending());
1789            std::task::Poll::Ready(())
1790        })
1791        .await;
1792        seen.try_recv()
1793            .expect("the reader already built its upgrade refusal");
1794        Some(resume)
1795    } else {
1796        None
1797    };
1798    assert!(forwarding.request_connection_close(
1799        ctx.connection_id,
1800        CloseReason::new("test_close", "reader is still dispatching")
1801    ));
1802    // Do not poll the reader again until the freeze has counted it.
1803    let readers = forwarding.freeze_upgrade_readers();
1804    let remaining = readers.subscribe();
1805    assert_eq!(
1806        *remaining.borrow(),
1807        1,
1808        "requesting close does not acknowledge the reader's current frame"
1809    );
1810    if let Some(resume) = resume {
1811        resume.send(()).unwrap();
1812    }
1813    assert!(matches!(
1814        loop_future.await.unwrap(),
1815        ConnectionLoopExit::CloseRequested(_)
1816    ));
1817    assert_eq!(
1818        *remaining.borrow(),
1819        0,
1820        "the reader has returned and no longer owns its frame"
1821    );
1822    assert_eq!(module_rx.try_recv().unwrap().header.corr, 81);
1823    assert!(module_rx.try_recv().is_err());
1824    assert!(reader_replies.try_recv().is_err());
1825    let tracked = usize::from(already_built_refusal);
1826    assert_eq!(
1827        forwarding.upgrade_refusals.receipt_for_test(&readers).await,
1828        (tracked, tracked, true),
1829        "only a daemon fence refusal already built before the close is counted"
1830    );
1831}
1832
1833#[cfg(all(test, unix))]
1834#[tokio::test]
1835async fn activity_and_other_control_ops_skip_the_typed_route_open_probe() {
1836    use subc_protocol::{Flags, Frame, FrameType, Priority};
1837    let router = Arc::new(Router::default());
1838    let (_id, mut client, server) = config_test_connection_loop(router.clone());
1839    let request = |corr, body: serde_json::Value| {
1840        Frame::build(
1841            FrameType::Request,
1842            Flags::new(false, Priority::Passive, false),
1843            0,
1844            0,
1845            corr,
1846            serde_json::to_vec(&body).unwrap(),
1847        )
1848        .unwrap()
1849    };
1850    for (i, op) in [
1851        "activity.query",
1852        "activity.record",
1853        "activity.subscribe",
1854        "server.describe",
1855    ]
1856    .into_iter()
1857    .enumerate()
1858    {
1859        let corr = 100 + i as u64;
1860        crate::write_frame(&mut client, &request(corr, serde_json::json!({"op":op})))
1861            .await
1862            .unwrap();
1863        assert_eq!(
1864            timeout(Duration::from_secs(2), read_frame(&mut client))
1865                .await
1866                .unwrap()
1867                .unwrap()
1868                .unwrap()
1869                .header
1870                .corr,
1871            corr
1872        );
1873        assert_eq!(
1874            router.route_open_probes_for_test(),
1875            0,
1876            "{op} must not reach the typed route.open probe"
1877        );
1878    }
1879    crate::write_frame(
1880        &mut client,
1881        &request(
1882            200,
1883            serde_json::json!({
1884                "op":"route.open",
1885                "target":subc_protocol::RouteTarget::ToolProvider { module_id: "no-module".into() },
1886                "identity":subc_protocol::BindIdentity::new("probe-fixture", "route"),
1887            }),
1888        ),
1889    )
1890    .await
1891    .unwrap();
1892    assert_eq!(
1893        timeout(Duration::from_secs(2), read_frame(&mut client))
1894            .await
1895            .unwrap()
1896            .unwrap()
1897            .unwrap()
1898            .header
1899            .corr,
1900        200
1901    );
1902    assert_eq!(router.route_open_probes_for_test(), 1);
1903    drop(client);
1904    server.await.unwrap().unwrap();
1905}
1906
1907#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
1908#[tokio::test]
1909async fn relayed_health_error_with_upgrade_body_does_not_enter_refusal_accounting() {
1910    use crate::{ConnectionId, ControlHandler, ForwardingTable, Registry};
1911    use subc_protocol::{
1912        manifest::{Concurrency, ModuleManifest},
1913        ErrorBody, Flags, Frame, FrameType, Priority, PROTOCOL_VERSION,
1914    };
1915    let registry = Arc::new(Registry::default());
1916    let forwarding = Arc::new(ForwardingTable::default());
1917    let router = Arc::new(Router::with_control_handler(Arc::new(
1918        ControlHandler::with_forwarding(registry.clone(), forwarding.clone()),
1919    )));
1920    let module_id = "receipt-probe";
1921    let module_connection = ConnectionId::new(400);
1922    let (module_sink, mut module_reader) = connection_egress();
1923    registry
1924        .register_with_control_ops(
1925            ModuleManifest::builder(module_id, "1.0.0").build(),
1926            PROTOCOL_VERSION,
1927            module_connection,
1928            vec!["health.check".into()],
1929        )
1930        .unwrap();
1931    forwarding
1932        .register_module_connection(
1933            module_connection,
1934            module_id.into(),
1935            PROTOCOL_VERSION,
1936            Concurrency::ModuleManaged,
1937            module_sink.clone(),
1938        )
1939        .unwrap();
1940    let (client_sink, mut replies) = connection_egress();
1941    let flags = Flags::new(false, Priority::Passive, false);
1942    let make = |ty, corr, body| Frame::build(ty, flags, 0, 0, corr, body).unwrap();
1943    let health = make(
1944        FrameType::Request,
1945        501,
1946        serde_json::to_vec(
1947            &serde_json::json!({"op":"supervisor.health_probe","module_id":module_id}),
1948        )
1949        .unwrap(),
1950    );
1951    let active = tokio::spawn({
1952        let router = router.clone();
1953        async move {
1954            router
1955                .route_for_connection(
1956                    &RouteCtx {
1957                        connection_id: ConnectionId::new(401),
1958                        egress: client_sink,
1959                    },
1960                    health,
1961                )
1962                .await
1963        }
1964    });
1965    let probe = timeout(Duration::from_secs(2), module_reader.recv())
1966        .await
1967        .unwrap()
1968        .unwrap();
1969    forwarding.upgrade_refusals.begin();
1970    forwarding.set_upgrade_admission(crate::control::upgrade_in_place::Admission::Fenced);
1971    let error = ErrorBody::module_reloading_for_daemon_upgrade("module-authored error");
1972    router
1973        .route_for_connection(
1974            &RouteCtx {
1975                connection_id: module_connection,
1976                egress: module_sink,
1977            },
1978            make(
1979                FrameType::Error,
1980                probe.header.corr,
1981                serde_json::to_vec(&error).unwrap(),
1982            ),
1983        )
1984        .await
1985        .unwrap();
1986    active.await.unwrap().unwrap();
1987    let reply = replies.try_recv().unwrap();
1988    assert_eq!(reply.header.corr, 501);
1989    assert_eq!(
1990        serde_json::from_slice::<ErrorBody>(&reply.body).unwrap(),
1991        error
1992    );
1993    assert!(
1994        reply.flushed.is_none(),
1995        "a module-authored error is not a tracked fence refusal"
1996    );
1997    assert_eq!(
1998        forwarding
1999            .upgrade_refusals
2000            .receipt_for_test(&Default::default())
2001            .await,
2002        (0, 0, true)
2003    );
2004}
2005
2006#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
2007#[tokio::test]
2008async fn upgrade_fence_refuses_health_and_flushes_queued_request_before_goodbye() {
2009    use crate::control::upgrade_in_place::Admission;
2010    use crate::{ControlHandler, ForwardingTable, Registry};
2011    use subc_protocol::{Flags, Frame, FrameType, Priority};
2012
2013    let (socket, mut peer) = tokio::io::duplex(1);
2014    let (sink, queued) = connection_egress();
2015    let writer = tokio::spawn(drain_writer(socket, queued));
2016    let frame = |ty, channel, corr, body| {
2017        Frame::build(
2018            ty,
2019            Flags::new(false, Priority::Passive, false),
2020            channel,
2021            0,
2022            corr,
2023            body,
2024        )
2025        .unwrap()
2026    };
2027    sink.try_send(frame(FrameType::Request, 1, 33, b"request".to_vec()))
2028        .unwrap();
2029
2030    let forwarding = Arc::new(ForwardingTable::default());
2031    forwarding.set_upgrade_admission(Admission::Fenced);
2032    let control = ControlHandler::with_forwarding(Arc::new(Registry::default()), forwarding);
2033    let (egress, _replies) = connection_egress();
2034    let probe = frame(
2035        FrameType::Request,
2036        0,
2037        44,
2038        serde_json::to_vec(
2039            &serde_json::json!({"op":"supervisor.health_probe", "module_id":"module"}),
2040        )
2041        .unwrap(),
2042    );
2043    let replies = control
2044        .handle_control_frame_timed(
2045            &RouteCtx {
2046                connection_id: crate::ConnectionId::new(15),
2047                egress,
2048            },
2049            probe,
2050            None,
2051        )
2052        .await
2053        .unwrap();
2054    let refused: subc_protocol::ErrorBody = serde_json::from_slice(&replies[0].body).unwrap();
2055    assert_eq!(refused.code, "upgrade_busy");
2056
2057    let notices = async {
2058        sink.send_flushed(frame(FrameType::Push, 0, 0, b"upgrading".to_vec()))
2059            .await
2060            .unwrap();
2061        sink.send_flushed(frame(FrameType::Goodbye, 0, 0, vec![]))
2062            .await
2063            .unwrap();
2064    };
2065    tokio::pin!(notices);
2066    std::future::poll_fn(|cx| {
2067        assert!(std::future::Future::poll(notices.as_mut(), cx).is_pending());
2068        std::task::Poll::Ready(())
2069    })
2070    .await;
2071    let (_, ()) = timeout(Duration::from_secs(2), async {
2072        tokio::join!(
2073            async {
2074                for expected in [FrameType::Request, FrameType::Push, FrameType::Goodbye] {
2075                    assert_eq!(
2076                        read_frame(&mut peer).await.unwrap().unwrap().header.ty,
2077                        expected
2078                    );
2079                }
2080            },
2081            &mut notices
2082        )
2083    })
2084    .await
2085    .unwrap();
2086    writer.abort();
2087}
2088
2089#[derive(Debug)]
2090pub enum ServerError {
2091    NoListeners,
2092    Accept {
2093        local_addr: Option<SocketAddr>,
2094        source: io::Error,
2095    },
2096    /// The local endpoint (a Unix-domain socket or a named pipe) could not be
2097    /// created or could not accept.
2098    LocalAccept {
2099        endpoint: String,
2100        source: io::Error,
2101    },
2102}
2103
2104impl fmt::Display for ServerError {
2105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2106        match self {
2107            Self::NoListeners => write!(f, "no TCP listeners were provided"),
2108            Self::Accept { local_addr, source } => match local_addr {
2109                Some(addr) => write!(f, "failed to accept TCP connection on {addr}: {source}"),
2110                None => write!(f, "failed to accept TCP connection: {source}"),
2111            },
2112            Self::LocalAccept { endpoint, source } => {
2113                write!(f, "local endpoint {endpoint} failed: {source}")
2114            }
2115        }
2116    }
2117}
2118
2119impl Error for ServerError {
2120    fn source(&self) -> Option<&(dyn Error + 'static)> {
2121        match self {
2122            Self::Accept { source, .. } | Self::LocalAccept { source, .. } => Some(source),
2123            Self::NoListeners => None,
2124        }
2125    }
2126}
2127
2128#[derive(Debug)]
2129pub enum ConnectionError {
2130    Auth(AuthError),
2131    UnauthenticatedCapacity,
2132    FrameIo(FrameIoError),
2133    Router(RouterError),
2134    WriterTask(tokio::task::JoinError),
2135}
2136
2137impl ConnectionError {
2138    fn is_quiet_reject(&self) -> bool {
2139        matches!(self, Self::Auth(_) | Self::UnauthenticatedCapacity)
2140    }
2141
2142    fn pre_auth_reject_stage(&self) -> Option<PreAuthRejectStage> {
2143        match self {
2144            Self::UnauthenticatedCapacity => Some(PreAuthRejectStage::WaitingForHandshakeSlot),
2145            Self::Auth(AuthError::Timeout { .. }) => Some(PreAuthRejectStage::HandshakeDeadline),
2146            Self::Auth(
2147                AuthError::InvalidClientAuth
2148                | AuthError::InvalidServerProof
2149                | AuthError::DaemonIdMismatch,
2150            ) => Some(PreAuthRejectStage::InvalidProof),
2151            Self::Auth(AuthError::MessageTooLarge { .. } | AuthError::JsonDecode { .. }) => {
2152                Some(PreAuthRejectStage::MalformedMessage)
2153            }
2154            Self::Auth(AuthError::UnexpectedEof { .. }) => Some(PreAuthRejectStage::PeerClosed),
2155            Self::Auth(AuthError::Io { source, .. })
2156                if matches!(
2157                    source.kind(),
2158                    io::ErrorKind::BrokenPipe
2159                        | io::ErrorKind::ConnectionAborted
2160                        | io::ErrorKind::ConnectionReset
2161                        | io::ErrorKind::UnexpectedEof
2162                ) =>
2163            {
2164                Some(PreAuthRejectStage::PeerClosed)
2165            }
2166            Self::Auth(_) => Some(PreAuthRejectStage::OtherAuthenticationFailure),
2167            Self::FrameIo(_) | Self::Router(_) | Self::WriterTask(_) => None,
2168        }
2169    }
2170
2171    fn auth_stage(&self) -> Option<AuthStage> {
2172        match self {
2173            Self::Auth(
2174                AuthError::Io { stage, .. }
2175                | AuthError::Timeout { stage, .. }
2176                | AuthError::UnexpectedEof { stage, .. }
2177                | AuthError::MessageTooLarge { stage, .. }
2178                | AuthError::JsonEncode { stage, .. }
2179                | AuthError::JsonDecode { stage, .. },
2180            ) => Some(*stage),
2181            Self::Auth(
2182                AuthError::Random(_)
2183                | AuthError::KeyTooShort { .. }
2184                | AuthError::InvalidServerProof
2185                | AuthError::DaemonIdMismatch
2186                | AuthError::InvalidClientAuth,
2187            )
2188            | Self::UnauthenticatedCapacity
2189            | Self::FrameIo(_)
2190            | Self::Router(_)
2191            | Self::WriterTask(_) => None,
2192        }
2193    }
2194}
2195
2196impl fmt::Display for ConnectionError {
2197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2198        match self {
2199            Self::Auth(err) => write!(f, "connection auth failed: {err}"),
2200            Self::UnauthenticatedCapacity => write!(
2201                f,
2202                "too many concurrent unauthenticated subc TCP connections"
2203            ),
2204            Self::FrameIo(err) => write!(f, "frame connection error: {err}"),
2205            Self::Router(err) => write!(f, "router connection error: {err}"),
2206            Self::WriterTask(err) => write!(f, "connection writer task failed: {err}"),
2207        }
2208    }
2209}
2210
2211impl Error for ConnectionError {
2212    fn source(&self) -> Option<&(dyn Error + 'static)> {
2213        match self {
2214            Self::Auth(err) => Some(err),
2215            Self::FrameIo(err) => Some(err),
2216            Self::Router(err) => Some(err),
2217            Self::WriterTask(err) => Some(err),
2218            Self::UnauthenticatedCapacity => None,
2219        }
2220    }
2221}
2222
2223#[cfg(all(test, unix))]
2224#[path = "server/peer_liveness_test.rs"]
2225mod peer_liveness_test;
2226
2227#[cfg(test)]
2228mod tests {
2229    use std::{
2230        future::Future,
2231        pin::Pin,
2232        sync::atomic::{AtomicUsize, Ordering},
2233        task::{Context, Poll},
2234    };
2235
2236    use super::*;
2237    use serde::{de::DeserializeOwned, Serialize};
2238    use subc_protocol::{
2239        DecodeError, ErrorBody, Flags, FrameType, Priority, HEADER_LEN, PROTOCOL_VERSION,
2240    };
2241    use tokio::io::{duplex, AsyncReadExt, AsyncWriteExt, ReadBuf};
2242
2243    use subc_transport::{
2244        authenticate_client, compute_proof, ClientAuth, ClientHello, ConnectionInfo, Endpoint,
2245        ServerProof, CLIENT_AUTH_DOMAIN, NONCE_LEN, SCHEMA_VERSION,
2246    };
2247
2248    use crate::{ControlHandler, EchoBackend, Frame, ReadStage, Registry};
2249
2250    const TEST_DEADLINE: Duration = Duration::from_secs(2);
2251    const TEST_DAEMON_VER: &str = "test-subc-server";
2252
2253    #[test]
2254    fn null_resume_token_is_an_ordinary_hello() {
2255        let frame = Frame::build(
2256            FrameType::Hello,
2257            Flags::new(false, Priority::Interactive, false),
2258            0,
2259            0,
2260            1,
2261            serde_json::to_vec(&serde_json::json!({
2262                "protocol_ver": PROTOCOL_VERSION,
2263                "manifest": subc_protocol::manifest::ModuleManifest::builder("fresh", "1.0.0")
2264                    .build(),
2265                "resume_token": null,
2266            }))
2267            .unwrap(),
2268        )
2269        .unwrap();
2270        assert_eq!(hello_transport_refusal(&LocalOrigin::Tcp, &frame), None);
2271        assert_eq!(
2272            hello_transport_refusal(&LocalOrigin::Local, &frame)
2273                .unwrap()
2274                .0,
2275            crate::local_listener::LOCAL_ENDPOINT_CLIENTS_ONLY
2276        );
2277        let control = ControlHandler::new(Arc::new(Registry::default()));
2278        let replies = control
2279            .handle_control(crate::ConnectionId::new(1), frame)
2280            .unwrap();
2281        assert_eq!(replies[0].header.ty, FrameType::HelloAck);
2282    }
2283
2284    /// Modules size their replies against the published limit, and the router
2285    /// refuses any module frame over the egress budget, so the two must be the
2286    /// same number. This fails if the budget is ever given its own value.
2287    #[test]
2288    fn egress_budget_is_the_published_delivered_frame_limit() {
2289        assert_eq!(
2290            CONNECTION_EGRESS_BYTE_BUDGET,
2291            subc_protocol::MAX_DELIVERED_FRAME_LEN
2292        );
2293    }
2294
2295    struct ObservedStream {
2296        inner: tokio::io::DuplexStream,
2297        write_blocked: Arc<tokio::sync::Notify>,
2298        dropped: Arc<AtomicUsize>,
2299        read_error: Option<tokio::sync::oneshot::Receiver<()>>,
2300    }
2301
2302    impl AsyncRead for ObservedStream {
2303        fn poll_read(
2304            mut self: Pin<&mut Self>,
2305            cx: &mut Context<'_>,
2306            buf: &mut ReadBuf<'_>,
2307        ) -> Poll<io::Result<()>> {
2308            if let Some(receiver) = self.read_error.as_mut() {
2309                match Pin::new(receiver).poll(cx) {
2310                    Poll::Ready(Ok(())) => {
2311                        self.read_error = None;
2312                        return Poll::Ready(Err(io::ErrorKind::ConnectionReset.into()));
2313                    }
2314                    Poll::Ready(Err(_)) => self.read_error = None,
2315                    Poll::Pending => {}
2316                }
2317            }
2318            Pin::new(&mut self.inner).poll_read(cx, buf)
2319        }
2320    }
2321
2322    impl AsyncWrite for ObservedStream {
2323        fn poll_write(
2324            mut self: Pin<&mut Self>,
2325            cx: &mut Context<'_>,
2326            buf: &[u8],
2327        ) -> Poll<io::Result<usize>> {
2328            let result = Pin::new(&mut self.inner).poll_write(cx, buf);
2329            if result.is_pending() {
2330                self.write_blocked.notify_one();
2331            }
2332            result
2333        }
2334
2335        fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
2336            Pin::new(&mut self.inner).poll_flush(cx)
2337        }
2338
2339        fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
2340            Pin::new(&mut self.inner).poll_shutdown(cx)
2341        }
2342    }
2343
2344    impl Drop for ObservedStream {
2345        fn drop(&mut self) {
2346            self.dropped.fetch_add(1, Ordering::SeqCst);
2347        }
2348    }
2349
2350    struct BlockedWriterConnection {
2351        client: tokio::io::DuplexStream,
2352        server: JoinHandle<Result<(), ConnectionError>>,
2353        stream_dropped: Arc<AtomicUsize>,
2354        read_error: Option<tokio::sync::oneshot::Sender<()>>,
2355        router: Arc<Router>,
2356    }
2357
2358    impl BlockedWriterConnection {
2359        async fn new() -> Self {
2360            let (mut client, inner) = duplex(256);
2361            let write_blocked = Arc::new(tokio::sync::Notify::new());
2362            let stream_dropped = Arc::new(AtomicUsize::new(0));
2363            let (read_error, receiver) = tokio::sync::oneshot::channel();
2364            let stream = ObservedStream {
2365                inner,
2366                write_blocked: Arc::clone(&write_blocked),
2367                dropped: Arc::clone(&stream_dropped),
2368                read_error: Some(receiver),
2369            };
2370            let (auth, conn) = test_auth();
2371            let router = echo_router();
2372            let server = tokio::spawn(handle_connection(stream, Arc::clone(&router), auth));
2373            authenticate(&mut client, &conn).await;
2374
2375            // Ignore any backpressure observed during authentication. The echo
2376            // reply is larger than the duplex capacity and the client never reads it.
2377            let _ = timeout(Duration::ZERO, write_blocked.notified()).await;
2378            write_frame(&mut client, &request(7, 1, &[b'x'; 1024]))
2379                .await
2380                .unwrap();
2381            timeout(TEST_DEADLINE, write_blocked.notified())
2382                .await
2383                .expect("writer should block on the unread echo reply");
2384            assert!(!server.is_finished());
2385            assert_eq!(stream_dropped.load(Ordering::SeqCst), 0);
2386            Self {
2387                client,
2388                server,
2389                stream_dropped,
2390                read_error: Some(read_error),
2391                router,
2392            }
2393        }
2394
2395        async fn finish(&mut self) -> Result<(), ConnectionError> {
2396            let started = tokio::time::Instant::now();
2397            let result = timeout(CLOSE_DRAIN_GRACE + Duration::from_secs(1), &mut self.server)
2398                .await
2399                .expect("connection teardown exceeded writer drain grace plus margin")
2400                .expect("connection task should not panic");
2401            assert!(started.elapsed() >= CLOSE_DRAIN_GRACE);
2402            assert_eq!(
2403                self.stream_dropped.load(Ordering::SeqCst),
2404                1,
2405                "writer must release its stream half before teardown completes"
2406            );
2407            result
2408        }
2409
2410        fn request_close(&self) {
2411            // Each fixture owns a fresh router, so its only connection has ID 1.
2412            assert!(self.router.forwarding().request_connection_close(
2413                crate::registry::ConnectionId::new(1),
2414                CloseReason::new("test_close", "test requested close"),
2415            ));
2416        }
2417    }
2418
2419    #[tokio::test(start_paused = true)]
2420    async fn peer_eof_bounds_blocked_writer_teardown() {
2421        let mut connection = BlockedWriterConnection::new().await;
2422        // Half-close only the client-to-server direction: the unread receive
2423        // buffer must stay alive so the server's writer cannot finish naturally.
2424        connection.client.shutdown().await.unwrap();
2425        connection.finish().await.unwrap();
2426    }
2427
2428    #[tokio::test]
2429    async fn tcp_teardown_sends_eof_while_another_endpoint_copy_is_open() {
2430        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2431        let mut peer = tokio::net::TcpStream::connect(listener.local_addr().unwrap())
2432            .await
2433            .unwrap();
2434        let (stream, _) = listener.accept().await.unwrap();
2435        // Model the descriptor held by a sibling between fork and exec without
2436        // making the test depend on process scheduling or descriptor inheritance.
2437        let inherited_copy = clone_tcp_socket(&stream).unwrap();
2438        let (auth, conn) = test_auth();
2439        let router = echo_router();
2440        let server = tokio::spawn(handle_connection(stream, Arc::clone(&router), auth));
2441        authenticate(&mut peer, &conn).await;
2442        write_frame(&mut peer, &request(7, 1, b"ready"))
2443            .await
2444            .unwrap();
2445        read_frame(&mut peer).await.unwrap().unwrap();
2446        assert!(router.forwarding().request_connection_close(
2447            crate::registry::ConnectionId::new(1),
2448            CloseReason::new("test_close", "test requested close"),
2449        ));
2450        timeout(TEST_DEADLINE, server)
2451            .await
2452            .unwrap()
2453            .unwrap()
2454            .unwrap();
2455        let mut byte = [0];
2456        assert_eq!(
2457            timeout(TEST_DEADLINE, peer.read(&mut byte))
2458                .await
2459                .expect("teardown must send EOF without waiting for inherited descriptors")
2460                .unwrap(),
2461            0,
2462        );
2463        drop(inherited_copy);
2464    }
2465
2466    #[tokio::test(start_paused = true)]
2467    async fn read_error_bounds_blocked_writer_teardown() {
2468        let mut connection = BlockedWriterConnection::new().await;
2469        connection.read_error.take().unwrap().send(()).unwrap();
2470        let error = connection.finish().await.unwrap_err();
2471        assert!(matches!(
2472            error,
2473            ConnectionError::FrameIo(FrameIoError::Io(error))
2474                if error.kind() == io::ErrorKind::ConnectionReset
2475        ));
2476    }
2477
2478    #[tokio::test(start_paused = true)]
2479    async fn close_requested_bounds_blocked_writer_teardown() {
2480        let mut connection = BlockedWriterConnection::new().await;
2481        connection.request_close();
2482        connection.finish().await.unwrap();
2483    }
2484
2485    #[tokio::test(start_paused = true)]
2486    async fn close_requested_flushes_queued_reply_before_grace() {
2487        let mut connection = BlockedWriterConnection::new().await;
2488        connection.request_close();
2489        let started = tokio::time::Instant::now();
2490        let reply = timeout(CLOSE_DRAIN_GRACE, read_frame(&mut connection.client))
2491            .await
2492            .expect("queued reply should flush before the grace expires")
2493            .unwrap()
2494            .unwrap();
2495        assert_eq!(reply.body, vec![b'x'; 1024]);
2496        timeout(CLOSE_DRAIN_GRACE, &mut connection.server)
2497            .await
2498            .unwrap()
2499            .unwrap()
2500            .unwrap();
2501        assert!(started.elapsed() < CLOSE_DRAIN_GRACE);
2502        assert_eq!(connection.stream_dropped.load(Ordering::SeqCst), 1);
2503    }
2504
2505    /// Reply-path stamp, slow polarity: a channel-0 reply whose queue residency
2506    /// exceeds the threshold must produce the slow-control-reply-write WARN with
2507    /// queued_ms reflecting the residency. Uses a backdated stamp rather than a
2508    /// real stall so the test is fast and deterministic.
2509    #[tokio::test]
2510    async fn stale_queued_control_reply_logs_slow_reply_write() {
2511        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
2512        let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(4);
2513        let reply = Frame::build_with_version(
2514            PROTOCOL_VERSION,
2515            FrameType::Error,
2516            Flags::new(false, Priority::Interactive, false),
2517            0,
2518            0,
2519            7,
2520            serde_json::to_vec(&ErrorBody {
2521                code: "test".into(),
2522                message: "reply".into(),
2523                detail: None,
2524            })
2525            .expect("body encodes"),
2526        )
2527        .expect("frame builds");
2528        tx.send(crate::router::OutboundFrame {
2529            frame: reply,
2530            enqueued_at: std::time::Instant::now() - Duration::from_millis(1500),
2531            flushed: None,
2532            #[cfg(all(
2533                feature = "test-support",
2534                any(target_os = "linux", target_os = "macos")
2535            ))]
2536            fixture_flush_gate: None,
2537            charge: None,
2538        })
2539        .await
2540        .expect("queued");
2541        drop(tx);
2542        let (write_half, mut read_half) = duplex(64 * 1024);
2543        drain_writer(write_half, rx).await.expect("writer drains");
2544        let mut sink = Vec::new();
2545        read_half.read_to_end(&mut sink).await.expect("read");
2546        assert!(!sink.is_empty(), "frame reached the socket");
2547        let captured = crate::router::test_log::captured_logs(&logs);
2548        assert!(
2549            captured.contains("slow control reply write") && captured.contains("corr=7"),
2550            "expected slow reply WARN naming corr, got: {captured}"
2551        );
2552        let queued_ms: u64 = captured
2553            .split("queued_ms=")
2554            .nth(1)
2555            .and_then(|s| s.split_whitespace().next())
2556            .and_then(|s| s.parse().ok())
2557            .expect("queued_ms present");
2558        assert!(
2559            queued_ms >= 1500,
2560            "queued_ms reflects residency: {queued_ms}"
2561        );
2562    }
2563
2564    /// Fast polarity: a promptly-drained control reply and a stale DATA-PLANE
2565    /// frame must both stay silent — the WARN is channel-0-only by design, and
2566    /// a healthy queue must add zero log volume.
2567    #[tokio::test]
2568    async fn fresh_control_and_stale_data_frames_log_nothing() {
2569        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
2570        let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(4);
2571        let control = Frame::build_with_version(
2572            PROTOCOL_VERSION,
2573            FrameType::Error,
2574            Flags::new(false, Priority::Interactive, false),
2575            0,
2576            0,
2577            8,
2578            serde_json::to_vec(&ErrorBody {
2579                code: "test".into(),
2580                message: "fresh".into(),
2581                detail: None,
2582            })
2583            .expect("body encodes"),
2584        )
2585        .expect("frame builds");
2586        tx.send(crate::router::OutboundFrame {
2587            frame: control,
2588            enqueued_at: std::time::Instant::now(),
2589            flushed: None,
2590            #[cfg(all(
2591                feature = "test-support",
2592                any(target_os = "linux", target_os = "macos")
2593            ))]
2594            fixture_flush_gate: None,
2595            charge: None,
2596        })
2597        .await
2598        .expect("queued");
2599        let data = Frame::build_with_version(
2600            PROTOCOL_VERSION,
2601            FrameType::Error,
2602            Flags::new(false, Priority::Interactive, false),
2603            9,
2604            1,
2605            9,
2606            serde_json::to_vec(&ErrorBody {
2607                code: "test".into(),
2608                message: "data".into(),
2609                detail: None,
2610            })
2611            .expect("body encodes"),
2612        )
2613        .expect("frame builds");
2614        tx.send(crate::router::OutboundFrame {
2615            frame: data,
2616            enqueued_at: std::time::Instant::now() - Duration::from_millis(5000),
2617            flushed: None,
2618            #[cfg(all(
2619                feature = "test-support",
2620                any(target_os = "linux", target_os = "macos")
2621            ))]
2622            fixture_flush_gate: None,
2623            charge: None,
2624        })
2625        .await
2626        .expect("queued");
2627        drop(tx);
2628        let (write_half, _read_half) = duplex(64 * 1024);
2629        drain_writer(write_half, rx).await.expect("writer drains");
2630        let captured = crate::router::test_log::captured_logs(&logs);
2631        assert!(
2632            !captured.contains("slow control reply write"),
2633            "no WARN for fresh control or stale data frames, got: {captured}"
2634        );
2635    }
2636
2637    struct CountingReader {
2638        bytes: Vec<u8>,
2639        offset: usize,
2640        first_read_end: Option<usize>,
2641        reads: Arc<AtomicUsize>,
2642    }
2643
2644    impl CountingReader {
2645        fn new(bytes: Vec<u8>, first_read_end: Option<usize>) -> (Self, Arc<AtomicUsize>) {
2646            let reads = Arc::new(AtomicUsize::new(0));
2647            (
2648                Self {
2649                    bytes,
2650                    offset: 0,
2651                    first_read_end,
2652                    reads: Arc::clone(&reads),
2653                },
2654                reads,
2655            )
2656        }
2657    }
2658
2659    impl AsyncRead for CountingReader {
2660        fn poll_read(
2661            mut self: Pin<&mut Self>,
2662            _cx: &mut Context<'_>,
2663            buf: &mut ReadBuf<'_>,
2664        ) -> Poll<io::Result<()>> {
2665            self.reads.fetch_add(1, Ordering::Relaxed);
2666            let available = self.bytes.len().saturating_sub(self.offset);
2667            let first_read_remaining = self
2668                .first_read_end
2669                .filter(|end| self.offset < *end)
2670                .map_or(available, |end| end - self.offset);
2671            let count = available.min(first_read_remaining).min(buf.remaining());
2672            let end = self.offset + count;
2673            buf.put_slice(&self.bytes[self.offset..end]);
2674            self.offset = end;
2675            Poll::Ready(Ok(()))
2676        }
2677    }
2678
2679    fn encode_frames(frames: &[Frame]) -> Vec<u8> {
2680        let mut bytes = Vec::new();
2681        for frame in frames {
2682            bytes.extend_from_slice(&frame.header.encode());
2683            bytes.extend_from_slice(&frame.body);
2684        }
2685        bytes
2686    }
2687
2688    async fn read_frames<R>(reader: &mut R, count: usize) -> Vec<Frame>
2689    where
2690        R: AsyncRead + Unpin,
2691    {
2692        let mut frames = Vec::with_capacity(count);
2693        for _ in 0..count {
2694            frames.push(read_frame(reader).await.unwrap().unwrap());
2695        }
2696        frames
2697    }
2698
2699    fn request(channel: u16, corr: u64, body: &[u8]) -> Frame {
2700        Frame::build(
2701            FrameType::Request,
2702            Flags::new(true, Priority::Interactive, false),
2703            channel,
2704            0,
2705            corr,
2706            body.to_vec(),
2707        )
2708        .unwrap()
2709    }
2710
2711    fn echo_router() -> Arc<Router> {
2712        let mut router = Router::with_default_self_handler();
2713        router.register_backend(7, EchoBackend).unwrap();
2714        router.register_backend(9, EchoBackend).unwrap();
2715        Arc::new(router)
2716    }
2717
2718    fn test_auth() -> (ServerAuth, ConnectionInfo) {
2719        test_auth_with_limit(4)
2720    }
2721
2722    fn test_auth_with_limit(max_unauthenticated: usize) -> (ServerAuth, ConnectionInfo) {
2723        test_auth_with_deadline_and_limit(TEST_DEADLINE, max_unauthenticated)
2724    }
2725
2726    fn test_auth_with_deadline_and_limit(
2727        deadline: Duration,
2728        max_unauthenticated: usize,
2729    ) -> (ServerAuth, ConnectionInfo) {
2730        let key = vec![0x42; 32];
2731        let daemon_id = [0x24; 16];
2732        let conn = ConnectionInfo {
2733            schema: SCHEMA_VERSION,
2734            wire_version: None,
2735            endpoints: vec![Endpoint {
2736                host: "127.0.0.1".to_owned(),
2737                port: 1,
2738            }],
2739            key: key.clone(),
2740            daemon_id,
2741            pid: std::process::id(),
2742            daemon_ver: TEST_DAEMON_VER.to_owned(),
2743        };
2744        (
2745            ServerAuth::with_limits(
2746                key,
2747                daemon_id,
2748                TEST_DAEMON_VER,
2749                deadline,
2750                max_unauthenticated,
2751            ),
2752            conn,
2753        )
2754    }
2755
2756    async fn authenticate<S>(stream: &mut S, conn: &ConnectionInfo)
2757    where
2758        S: AsyncRead + AsyncWrite + Unpin,
2759    {
2760        authenticate_client(stream, conn, TEST_DEADLINE)
2761            .await
2762            .expect("test client should authenticate")
2763    }
2764
2765    async fn write_auth_message<S, T>(stream: &mut S, value: &T)
2766    where
2767        S: AsyncWrite + Unpin,
2768        T: Serialize,
2769    {
2770        let body = serde_json::to_vec(value).expect("auth message encodes");
2771        stream
2772            .write_all(&(body.len() as u32).to_le_bytes())
2773            .await
2774            .expect("auth message length writes");
2775        stream
2776            .write_all(&body)
2777            .await
2778            .expect("auth message body writes");
2779    }
2780
2781    async fn read_auth_message<S, T>(stream: &mut S) -> T
2782    where
2783        S: AsyncRead + Unpin,
2784        T: DeserializeOwned,
2785    {
2786        let mut length = [0; 4];
2787        stream
2788            .read_exact(&mut length)
2789            .await
2790            .expect("auth message length reads");
2791        let mut body = vec![0; u32::from_le_bytes(length) as usize];
2792        stream
2793            .read_exact(&mut body)
2794            .await
2795            .expect("auth message body reads");
2796        serde_json::from_slice(&body).expect("auth message decodes")
2797    }
2798
2799    async fn send_wrong_key_client_auth<S>(stream: &mut S, conn: &ConnectionInfo)
2800    where
2801        S: AsyncRead + AsyncWrite + Unpin,
2802    {
2803        let hello = ClientHello {
2804            client_nonce: [0x57; NONCE_LEN],
2805            role: "client".to_owned(),
2806        };
2807        write_auth_message(stream, &hello).await;
2808        let proof: ServerProof = read_auth_message(stream).await;
2809        let mut wrong_key = conn.key.clone();
2810        wrong_key[0] ^= 0xff;
2811        let client_auth = ClientAuth {
2812            client_auth: compute_proof(
2813                &wrong_key,
2814                CLIENT_AUTH_DOMAIN,
2815                &hello.client_nonce,
2816                &proof.server_nonce,
2817                &conn.daemon_id,
2818            ),
2819        };
2820        write_auth_message(stream, &client_auth).await;
2821    }
2822
2823    fn assert_pre_auth_log(logs: &Arc<std::sync::Mutex<Vec<u8>>>, stage: &str, port: u16) {
2824        let captured = crate::router::test_log::captured_logs(logs);
2825        assert!(
2826            captured.contains(&format!("stage=\"{stage}\"")),
2827            "expected rejection stage {stage}, got: {captured}"
2828        );
2829        assert!(
2830            captured.contains(&format!("peer_addr=127.0.0.1:{port}")),
2831            "expected peer address, got: {captured}"
2832        );
2833        assert!(
2834            captured.contains("elapsed_ms=") && captured.contains("suppressed_since_last="),
2835            "expected elapsed time and suppression count, got: {captured}"
2836        );
2837        assert!(
2838            !captured.contains("WARN"),
2839            "pre-auth rejection must not be logged as a warning: {captured}"
2840        );
2841    }
2842
2843    #[tokio::test]
2844    async fn logs_handshake_deadline_pre_auth_rejection() {
2845        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2846        let deadline = Duration::from_millis(60);
2847        let (auth, _) = test_auth_with_deadline_and_limit(deadline, 4);
2848        let (client, server_stream) = duplex(512);
2849        let port = 41001;
2850        let server = handle_accepted_connection(
2851            server_stream,
2852            echo_router(),
2853            auth,
2854            SocketAddr::from(([127, 0, 0, 1], port)),
2855            Instant::now(),
2856        );
2857
2858        let error = tokio::time::timeout(deadline * 3, server)
2859            .await
2860            .expect("idle handshake should end at its deadline")
2861            .expect_err("idle handshake must be rejected");
2862        drop(client);
2863        assert!(matches!(
2864            error,
2865            ConnectionError::Auth(AuthError::Timeout {
2866                stage: AuthStage::ClientHello,
2867                ..
2868            })
2869        ));
2870        let captured = crate::router::test_log::captured_logs(&logs);
2871        assert!(
2872            captured.contains("reason=\"handshake_deadline_expired\""),
2873            "{captured}"
2874        );
2875        assert_pre_auth_log(&logs, "handshake_deadline", port);
2876    }
2877
2878    #[tokio::test]
2879    async fn logs_invalid_client_proof_pre_auth_rejection() {
2880        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2881        let (auth, conn) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2882        let (mut client, server_stream) = duplex(512);
2883        let port = 41002;
2884        let server = handle_accepted_connection(
2885            server_stream,
2886            echo_router(),
2887            auth,
2888            SocketAddr::from(([127, 0, 0, 1], port)),
2889            Instant::now(),
2890        );
2891
2892        let (error, ()) = tokio::join!(server, send_wrong_key_client_auth(&mut client, &conn));
2893        assert!(matches!(
2894            error,
2895            Err(ConnectionError::Auth(AuthError::InvalidClientAuth))
2896        ));
2897        let captured = crate::router::test_log::captured_logs(&logs);
2898        assert!(
2899            captured.contains("reason=\"client_proof_mismatch\""),
2900            "{captured}"
2901        );
2902        assert_pre_auth_log(&logs, "client_authentication", port);
2903    }
2904
2905    #[tokio::test]
2906    async fn logs_malformed_pre_auth_message() {
2907        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2908        let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2909        let (mut client, server_stream) = duplex(512);
2910        let port = 41003;
2911        let server = handle_accepted_connection(
2912            server_stream,
2913            echo_router(),
2914            auth,
2915            SocketAddr::from(([127, 0, 0, 1], port)),
2916            Instant::now(),
2917        );
2918        let send_malformed_message = async {
2919            let body = b"{";
2920            client
2921                .write_all(&(body.len() as u32).to_le_bytes())
2922                .await
2923                .expect("message length writes");
2924            client.write_all(body).await.expect("message body writes");
2925        };
2926
2927        let (error, ()) = tokio::join!(server, send_malformed_message);
2928        assert!(matches!(
2929            error,
2930            Err(ConnectionError::Auth(AuthError::JsonDecode {
2931                stage: AuthStage::ClientHello,
2932                ..
2933            }))
2934        ));
2935        let captured = crate::router::test_log::captured_logs(&logs);
2936        assert!(
2937            captured.contains("reason=\"malformed_or_oversized_message\""),
2938            "{captured}"
2939        );
2940        assert_pre_auth_log(&logs, "malformed_message", port);
2941    }
2942
2943    #[tokio::test]
2944    async fn logs_peer_close_during_handshake() {
2945        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2946        let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2947        let (client, server_stream) = duplex(512);
2948        let port = 41004;
2949        drop(client);
2950
2951        let error = handle_accepted_connection(
2952            server_stream,
2953            echo_router(),
2954            auth,
2955            SocketAddr::from(([127, 0, 0, 1], port)),
2956            Instant::now(),
2957        )
2958        .await
2959        .expect_err("closed peer must be rejected");
2960        assert!(matches!(
2961            error,
2962            ConnectionError::Auth(AuthError::UnexpectedEof {
2963                stage: AuthStage::ClientHello,
2964                actual: 0,
2965                ..
2966            })
2967        ));
2968        let captured = crate::router::test_log::captured_logs(&logs);
2969        assert!(
2970            captured.contains("reason=\"peer_closed_before_authentication_completed\""),
2971            "{captured}"
2972        );
2973        assert_pre_auth_log(&logs, "peer_closed", port);
2974    }
2975
2976    // Rejection-log rate limits belong to one listener. A process-wide limiter
2977    // let one listener's rejects silence another's for a second, which hid the
2978    // second listener's first rejection entirely.
2979    #[tokio::test]
2980    async fn each_listener_rate_limits_its_own_rejection_logs() {
2981        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2982        for port in [41011, 41012] {
2983            let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2984            let (client, server_stream) = duplex(512);
2985            drop(client);
2986            handle_accepted_connection(
2987                server_stream,
2988                echo_router(),
2989                auth,
2990                SocketAddr::from(([127, 0, 0, 1], port)),
2991                Instant::now(),
2992            )
2993            .await
2994            .expect_err("closed peer must be rejected");
2995        }
2996        let captured = crate::router::test_log::captured_logs(&logs);
2997        for port in [41011, 41012] {
2998            assert!(
2999                captured.contains(&format!("127.0.0.1:{port}")),
3000                "listener on port {port} logged nothing: {captured}"
3001            );
3002        }
3003    }
3004
3005    #[tokio::test]
3006    async fn logs_unauthenticated_capacity_rejection() {
3007        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
3008        let deadline = Duration::from_millis(60);
3009        let (auth, _) = test_auth_with_deadline_and_limit(deadline, 1);
3010        let held_slot = auth
3011            .unauthenticated
3012            .clone()
3013            .try_acquire_owned()
3014            .expect("the only pre-auth slot is available");
3015        let (client, server_stream) = duplex(512);
3016        let port = 41005;
3017        let server = handle_accepted_connection(
3018            server_stream,
3019            echo_router(),
3020            auth,
3021            SocketAddr::from(([127, 0, 0, 1], port)),
3022            Instant::now(),
3023        );
3024
3025        let error = tokio::time::timeout(deadline * 3, server)
3026            .await
3027            .expect("queued connection should end at the capacity deadline")
3028            .expect_err("connection without a free slot must be rejected");
3029        drop(held_slot);
3030        drop(client);
3031        assert!(matches!(error, ConnectionError::UnauthenticatedCapacity));
3032        let captured = crate::router::test_log::captured_logs(&logs);
3033        assert!(
3034            captured.contains("reason=\"capacity_wait_timed_out\""),
3035            "{captured}"
3036        );
3037        assert_pre_auth_log(&logs, "waiting_for_handshake_slot", port);
3038    }
3039
3040    #[test]
3041    fn pre_auth_rejection_limiter_suppresses_bursts_and_reports_count() {
3042        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
3043        let limiter = PreAuthRejectLimiter::new();
3044        let capacity = ConnectionError::UnauthenticatedCapacity;
3045        let handshake_timeout = ConnectionError::Auth(AuthError::Timeout {
3046            stage: AuthStage::ClientHello,
3047            deadline: Duration::from_millis(200),
3048        });
3049        let peer_addr = SocketAddr::from(([127, 0, 0, 1], 41006));
3050
3051        log_pre_auth_rejection(
3052            &capacity,
3053            peer_addr,
3054            Duration::from_millis(1),
3055            Duration::ZERO,
3056            &limiter,
3057        );
3058        for _ in 0..4 {
3059            log_pre_auth_rejection(
3060                &capacity,
3061                peer_addr,
3062                Duration::from_millis(2),
3063                Duration::from_millis(100),
3064                &limiter,
3065            );
3066        }
3067        log_pre_auth_rejection(
3068            &handshake_timeout,
3069            peer_addr,
3070            Duration::from_millis(3),
3071            Duration::from_millis(100),
3072            &limiter,
3073        );
3074        log_pre_auth_rejection(
3075            &capacity,
3076            peer_addr,
3077            Duration::from_millis(4),
3078            Duration::from_secs(1),
3079            &limiter,
3080        );
3081
3082        let captured = crate::router::test_log::captured_logs(&logs);
3083        assert_eq!(
3084            captured
3085                .matches("subc TCP connection rejected before routing")
3086                .count(),
3087            3,
3088            "one line per stage in a burst, then a later capacity line: {captured}"
3089        );
3090        assert!(
3091            captured.contains("suppressed_since_last=4"),
3092            "later capacity line should report the four hidden rejects: {captured}"
3093        );
3094        assert!(
3095            captured.contains("stage=\"handshake_deadline\""),
3096            "{captured}"
3097        );
3098    }
3099
3100    #[tokio::test]
3101    async fn buffered_frame_reader_coalesces_reads_and_preserves_short_reads() {
3102        let frames = vec![
3103            request(7, 1, b"first"),
3104            request(9, 2, b"second"),
3105            request(7, 3, b"third"),
3106            request(9, 4, b"fourth"),
3107        ];
3108        let bytes = encode_frames(&frames);
3109
3110        let (mut direct, direct_reads) = CountingReader::new(bytes.clone(), None);
3111        assert_eq!(read_frames(&mut direct, frames.len()).await, frames);
3112        assert_eq!(direct_reads.load(Ordering::Relaxed), frames.len() * 3);
3113
3114        let (buffered_source, buffered_reads) = CountingReader::new(bytes, None);
3115        let mut buffered = BufReader::new(buffered_source);
3116        assert_eq!(read_frames(&mut buffered, frames.len()).await, frames);
3117        assert_eq!(buffered_reads.load(Ordering::Relaxed), 1);
3118
3119        let split_frame = request(7, 5, b"split-body");
3120        let split_bytes = encode_frames(std::slice::from_ref(&split_frame));
3121        let (split_source, split_reads) = CountingReader::new(split_bytes, Some(10));
3122        let mut split_reader = BufReader::new(split_source);
3123        assert_eq!(
3124            read_frame(&mut split_reader).await.unwrap(),
3125            Some(split_frame)
3126        );
3127        assert_eq!(split_reads.load(Ordering::Relaxed), 2);
3128    }
3129
3130    #[tokio::test]
3131    async fn interleaved_channels_on_one_stream_demux_byte_identically_after_auth() {
3132        let (mut client, server_stream) = duplex(4096);
3133        let (auth, conn) = test_auth();
3134        let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3135        authenticate(&mut client, &conn).await;
3136        let frames = [
3137            request(7, 1, b"chan7-first\0opaque"),
3138            request(9, 2, b"chan9-middle-{json?}"),
3139            request(7, 3, b"chan7-second\xffbytes"),
3140        ];
3141
3142        for frame in &frames {
3143            crate::write_frame(&mut client, frame).await.unwrap();
3144        }
3145
3146        for expected in &frames {
3147            let response = crate::read_frame(&mut client).await.unwrap().unwrap();
3148            assert_eq!(response.header.ty, FrameType::Response);
3149            assert_eq!(response.header.channel, expected.header.channel);
3150            assert_eq!(response.header.corr, expected.header.corr);
3151            assert_eq!(response.body, expected.body);
3152        }
3153
3154        drop(client);
3155        server.await.unwrap().unwrap();
3156    }
3157
3158    #[tokio::test]
3159    async fn channel_zero_goes_to_subc_self_handler_after_auth() {
3160        let (mut client, server_stream) = duplex(512);
3161        let (auth, conn) = test_auth();
3162        let server = tokio::spawn(handle_connection(
3163            server_stream,
3164            Arc::new(Router::with_default_self_handler()),
3165            auth,
3166        ));
3167        authenticate(&mut client, &conn).await;
3168        let ping = Frame::build(
3169            FrameType::Ping,
3170            Flags::new(false, Priority::Passive, false),
3171            0,
3172            0,
3173            55,
3174            Vec::new(),
3175        )
3176        .unwrap();
3177
3178        crate::write_frame(&mut client, &ping).await.unwrap();
3179        let response = crate::read_frame(&mut client).await.unwrap().unwrap();
3180
3181        assert_eq!(response.header.ty, FrameType::Pong);
3182        assert_eq!(response.header.channel, 0);
3183        assert_eq!(response.header.corr, 55);
3184        assert!(response.body.is_empty());
3185
3186        drop(client);
3187        server.await.unwrap().unwrap();
3188    }
3189
3190    #[tokio::test]
3191    async fn unauthenticated_connection_is_rejected_before_routing() {
3192        let (mut client, server_stream) = duplex(512);
3193        let (auth, _conn) = test_auth();
3194        let registry = Arc::new(Registry::default());
3195        let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
3196            Arc::clone(&registry),
3197        ))));
3198        let server = tokio::spawn(handle_connection(server_stream, router, auth));
3199        let ping = Frame::build(
3200            FrameType::Ping,
3201            Flags::new(false, Priority::Passive, false),
3202            0,
3203            0,
3204            66,
3205            Vec::new(),
3206        )
3207        .unwrap();
3208
3209        crate::write_frame(&mut client, &ping).await.unwrap();
3210        if let Ok(Ok(Some(frame))) =
3211            tokio::time::timeout(Duration::from_millis(200), crate::read_frame(&mut client)).await
3212        {
3213            panic!("unauthenticated frame reached router: {frame:?}");
3214        }
3215
3216        let err = server.await.unwrap().unwrap_err();
3217        assert!(matches!(err, ConnectionError::Auth(_)));
3218        assert_eq!(registry.active_registration_count().unwrap(), 0);
3219    }
3220
3221    #[tokio::test]
3222    async fn over_cap_peer_queues_for_a_slot_and_authenticates_when_one_frees() {
3223        // Restart-herd contract: an over-cap pre-auth connection WAITS (bounded by
3224        // the auth deadline) instead of being reset. When the slot-holder finishes,
3225        // the queued peer must complete a normal handshake — the 2026-07-14 aft
3226        // outage was exactly a supervised child being reset out of this lottery.
3227        let (mut first_client, first_server_stream) = duplex(2048);
3228        let (mut second_client, second_server_stream) = duplex(2048);
3229        let (auth, conn) = test_auth_with_limit(1);
3230        let registry = Arc::new(Registry::default());
3231        let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
3232            Arc::clone(&registry),
3233        ))));
3234
3235        let first_server = tokio::spawn(handle_connection(
3236            first_server_stream,
3237            Arc::clone(&router),
3238            auth.clone(),
3239        ));
3240
3241        let second_server = tokio::spawn(handle_connection(
3242            second_server_stream,
3243            Arc::clone(&router),
3244            auth.clone(),
3245        ));
3246
3247        // The second peer must still be pending (not reset) while the slot is held.
3248        tokio::time::sleep(Duration::from_millis(50)).await;
3249        assert!(
3250            !second_server.is_finished(),
3251            "queued peer must not be reset"
3252        );
3253
3254        // First peer completes its handshake, freeing the slot; the queued second
3255        // peer then authenticates normally.
3256        authenticate(&mut first_client, &conn).await;
3257        authenticate(&mut second_client, &conn).await;
3258
3259        drop(first_client);
3260        drop(second_client);
3261        let _ = first_server.await;
3262        let _ = second_server.await;
3263        assert_eq!(registry.active_registration_count().unwrap(), 0);
3264    }
3265
3266    #[tokio::test]
3267    async fn over_cap_peer_is_rejected_when_no_slot_frees_within_deadline() {
3268        // The deadline stays the DoS bound: if no slot frees, the queued peer is
3269        // rejected at the deadline with a closed stream. The slot is held DIRECTLY
3270        // (not by another connection) so nothing can free it mid-test — a squatting
3271        // connection's own auth deadline would release the slot at exactly the
3272        // waiter's timeout, making the outcome racy.
3273        let (mut second_client, second_server_stream) = duplex(512);
3274        let (auth, conn) = test_auth_with_limit(1);
3275        let registry = Arc::new(Registry::default());
3276        let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
3277            Arc::clone(&registry),
3278        ))));
3279
3280        let held_slot = auth
3281            .unauthenticated
3282            .clone()
3283            .try_acquire_owned()
3284            .expect("sole pre-auth slot");
3285
3286        let second_server = tokio::spawn(handle_connection(
3287            second_server_stream,
3288            Arc::clone(&router),
3289            auth.clone(),
3290        ));
3291        let second_err = tokio::time::timeout(TEST_DEADLINE * 2, second_server)
3292            .await
3293            .expect("capacity reject should settle at the deadline")
3294            .expect("second connection task should not panic")
3295            .expect_err("queued peer must be rejected when no slot frees");
3296        drop(held_slot);
3297        assert!(matches!(
3298            second_err,
3299            ConnectionError::UnauthenticatedCapacity
3300        ));
3301        let mut closed = [0u8; 1];
3302        assert_eq!(
3303            second_client.read(&mut closed).await.unwrap(),
3304            0,
3305            "capacity-rejected peer should observe a closed stream"
3306        );
3307        assert_eq!(registry.active_registration_count().unwrap(), 0);
3308
3309        let (mut authed_client, authed_server_stream) = duplex(2048);
3310        let authed_server = tokio::spawn(handle_connection(
3311            authed_server_stream,
3312            Arc::clone(&router),
3313            auth,
3314        ));
3315        authenticate(&mut authed_client, &conn).await;
3316        let ping = Frame::build(
3317            FrameType::Ping,
3318            Flags::new(false, Priority::Passive, false),
3319            0,
3320            0,
3321            77,
3322            Vec::new(),
3323        )
3324        .unwrap();
3325        crate::write_frame(&mut authed_client, &ping).await.unwrap();
3326        let pong = crate::read_frame(&mut authed_client)
3327            .await
3328            .unwrap()
3329            .unwrap();
3330        assert_eq!(pong.header.ty, FrameType::Pong);
3331        assert_eq!(pong.header.channel, 0);
3332        assert_eq!(pong.header.corr, 77);
3333        assert_eq!(registry.active_registration_count().unwrap(), 0);
3334
3335        drop(authed_client);
3336        authed_server.await.unwrap().unwrap();
3337    }
3338
3339    #[tokio::test]
3340    async fn bind_ack_during_partial_frame_preserves_next_request() {
3341        use subc_control::ClientControlRequest;
3342        use subc_protocol::{
3343            manifest::{
3344                Concurrency, ExecutionMode, IdentityScope, ModuleManifest, ProviderRole, Tool,
3345            },
3346            session::{ModuleControlRequest, ModuleControlResponse},
3347            BindIdentity, ModuleHelloBody, RouteTarget,
3348        };
3349
3350        let mut configured_router = Router::with_default_self_handler();
3351        configured_router.register_backend(7, EchoBackend).unwrap();
3352        let router = Arc::new(configured_router);
3353        let (auth, conn) = test_auth();
3354        let (mut module, module_stream) = duplex(4096);
3355        let module_server = tokio::spawn(handle_connection(
3356            module_stream,
3357            Arc::clone(&router),
3358            auth.clone(),
3359        ));
3360        authenticate(&mut module, &conn).await;
3361        let manifest = ModuleManifest::builder("frame-test", "0.1.0")
3362            .protocol_ver(PROTOCOL_VERSION)
3363            .provides(vec![ProviderRole::ToolProvider {
3364                tools: vec![Tool {
3365                    name: "read".into(),
3366                    description: None,
3367                    execution_mode: ExecutionMode::Pure,
3368                    schema: serde_json::json!({"type": "object"}),
3369                }],
3370                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
3371                concurrency: Concurrency::ModuleManaged,
3372                emits_push: true,
3373                sub_supervises: true,
3374            }])
3375            .build();
3376        let hello = Frame::build(
3377            FrameType::Hello,
3378            Flags::new(false, Priority::Passive, false),
3379            0,
3380            0,
3381            1,
3382            serde_json::to_vec(&ModuleHelloBody {
3383                module_capabilities: None,
3384                resume_token: None,
3385                manifest,
3386                protocol_ver: PROTOCOL_VERSION,
3387                control_ops: None,
3388                launch_nonce: None,
3389            })
3390            .unwrap(),
3391        )
3392        .unwrap();
3393        crate::write_frame(&mut module, &hello).await.unwrap();
3394        assert_eq!(
3395            read_frame(&mut module).await.unwrap().unwrap().header.ty,
3396            FrameType::HelloAck
3397        );
3398
3399        let (mut client, client_stream) = duplex(4096);
3400        let client_server = tokio::spawn(handle_connection(client_stream, router, auth));
3401        authenticate(&mut client, &conn).await;
3402        let open = Frame::build(
3403            FrameType::Request,
3404            Flags::new(false, Priority::Passive, false),
3405            0,
3406            0,
3407            2,
3408            serde_json::to_vec(&ClientControlRequest::RouteOpen {
3409                busy_refusals: None,
3410                target: RouteTarget::ToolProvider {
3411                    module_id: "frame-test".into(),
3412                },
3413                identity: BindIdentity::new("unit", "session"),
3414                consumer_identity: None,
3415                consumer_capabilities: None,
3416                role_versions: None,
3417                admission_facts: None,
3418                scope: None,
3419            })
3420            .unwrap(),
3421        )
3422        .unwrap();
3423        crate::write_frame(&mut client, &open).await.unwrap();
3424        let bind = timeout(TEST_DEADLINE, read_frame(&mut module))
3425            .await
3426            .unwrap()
3427            .unwrap()
3428            .unwrap();
3429        assert!(matches!(
3430            serde_json::from_slice::<ModuleControlRequest>(&bind.body).unwrap(),
3431            ModuleControlRequest::RouteBind { .. }
3432        ));
3433
3434        let ping = request(7, 3, b"partial-frame-body");
3435        client.write_all(&ping.header.encode()).await.unwrap();
3436        // Give the connection reader time to consume the header while the bind is pending.
3437        tokio::time::sleep(Duration::from_millis(30)).await;
3438        let ack = Frame::build(
3439            FrameType::Response,
3440            Flags::new(false, Priority::Passive, false),
3441            0,
3442            0,
3443            bind.header.corr,
3444            serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap(),
3445        )
3446        .unwrap();
3447        crate::write_frame(&mut module, &ack).await.unwrap();
3448        let opened = timeout(TEST_DEADLINE, read_frame(&mut client))
3449            .await
3450            .unwrap()
3451            .unwrap();
3452        if opened.is_none() {
3453            panic!("client closed: {:?}", client_server.await);
3454        }
3455        let opened = opened.unwrap();
3456        assert_eq!(opened.header.corr, 2);
3457        client.write_all(&ping.body).await.unwrap();
3458        let pong = timeout(TEST_DEADLINE, read_frame(&mut client))
3459            .await
3460            .expect("partial frame must reach the router after the bind ack")
3461            .expect("frame must decode")
3462            .expect("connection must remain open");
3463        assert_eq!(pong.header.ty, FrameType::Response);
3464        assert_eq!(pong.header.corr, 3);
3465        assert_eq!(pong.body, ping.body);
3466        drop(client);
3467        drop(module);
3468        client_server.await.unwrap().unwrap();
3469        let _ = module_server.await.unwrap();
3470    }
3471
3472    #[tokio::test]
3473    async fn full_module_egress_health_probe_does_not_block_same_client_other_route() {
3474        use crate::ConnectionId;
3475        use subc_control::{ClientControlRequest, ClientControlResponse};
3476        use subc_protocol::{
3477            manifest::{
3478                Concurrency, ExecutionMode, IdentityScope, ModuleManifest, ProviderRole, Tool,
3479            },
3480            session::ModuleControlResponse,
3481            BindIdentity, ModuleHelloBody, RouteTarget,
3482        };
3483
3484        let probe_timeout = Duration::from_millis(100);
3485        let handler = Arc::new(
3486            ControlHandler::new(Arc::new(Registry::default()))
3487                .with_health_probe_timeout(probe_timeout),
3488        );
3489        let router = Arc::new(Router::with_control_handler(Arc::clone(&handler)));
3490        let hello = |name: &str| {
3491            Frame::build(
3492                FrameType::Hello,
3493                Flags::new(false, Priority::Passive, false),
3494                0,
3495                0,
3496                1,
3497                serde_json::to_vec(&ModuleHelloBody {
3498                    module_capabilities: None,
3499                    resume_token: None,
3500                    manifest: ModuleManifest::builder(name, "0.1.0")
3501                        .protocol_ver(PROTOCOL_VERSION)
3502                        .provides(vec![ProviderRole::ToolProvider {
3503                            tools: vec![Tool {
3504                                name: "read".into(),
3505                                description: None,
3506                                execution_mode: ExecutionMode::Pure,
3507                                schema: serde_json::json!({"type": "object"}),
3508                            }],
3509                            identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
3510                            concurrency: Concurrency::ModuleManaged,
3511                            emits_push: false,
3512                            sub_supervises: false,
3513                        }])
3514                        .build(),
3515                    protocol_ver: PROTOCOL_VERSION,
3516                    control_ops: Some(vec!["health.check".to_owned()]),
3517                    launch_nonce: None,
3518                })
3519                .unwrap(),
3520            )
3521            .unwrap()
3522        };
3523        let (blocked_tx, mut blocked_rx) = mpsc::channel(1);
3524        let blocked_ctx = RouteCtx {
3525            connection_id: ConnectionId::new(90001),
3526            egress: FrameSink::new(blocked_tx),
3527        };
3528        handler
3529            .handle_control_frame(&blocked_ctx, hello("blocked"))
3530            .await
3531            .unwrap();
3532        assert_eq!(
3533            blocked_rx.try_recv().unwrap().header.ty,
3534            FrameType::HelloAck
3535        );
3536        let filler = request(0, 99, b"queue filler");
3537        blocked_ctx.egress.try_send(filler.clone()).unwrap();
3538        assert!(
3539            blocked_ctx.egress.try_send(filler).is_err(),
3540            "module queue must actually be full"
3541        );
3542
3543        let (healthy_tx, mut healthy_rx) = mpsc::channel(8);
3544        let healthy_ctx = RouteCtx {
3545            connection_id: ConnectionId::new(90002),
3546            egress: FrameSink::new(healthy_tx),
3547        };
3548        handler
3549            .handle_control_frame(&healthy_ctx, hello("healthy"))
3550            .await
3551            .unwrap();
3552        assert_eq!(
3553            healthy_rx.try_recv().unwrap().header.ty,
3554            FrameType::HelloAck
3555        );
3556        let (auth, conn) = test_auth();
3557        let (mut client, client_stream) = duplex(4096);
3558        let client_server =
3559            tokio::spawn(handle_connection(client_stream, Arc::clone(&router), auth));
3560        authenticate(&mut client, &conn).await;
3561        let control_request = |corr, body: ClientControlRequest| {
3562            Frame::build(
3563                FrameType::Request,
3564                Flags::new(false, Priority::Interactive, false),
3565                0,
3566                0,
3567                corr,
3568                serde_json::to_vec(&body).unwrap(),
3569            )
3570            .unwrap()
3571        };
3572        crate::write_frame(
3573            &mut client,
3574            &control_request(
3575                2,
3576                ClientControlRequest::RouteOpen {
3577                    busy_refusals: None,
3578                    target: RouteTarget::ToolProvider {
3579                        module_id: "healthy".into(),
3580                    },
3581                    identity: BindIdentity::new("unit", "session"),
3582                    consumer_identity: None,
3583                    consumer_capabilities: None,
3584                    role_versions: None,
3585                    admission_facts: None,
3586                    scope: None,
3587                },
3588            ),
3589        )
3590        .await
3591        .unwrap();
3592        let bind = timeout(TEST_DEADLINE, healthy_rx.recv())
3593            .await
3594            .unwrap()
3595            .unwrap();
3596        handler
3597            .handle_control_frame(
3598                &healthy_ctx,
3599                Frame::build(
3600                    FrameType::Response,
3601                    Flags::new(false, Priority::Passive, false),
3602                    0,
3603                    0,
3604                    bind.header.corr,
3605                    serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap(),
3606                )
3607                .unwrap(),
3608            )
3609            .await
3610            .unwrap();
3611        let opened = timeout(TEST_DEADLINE, read_frame(&mut client))
3612            .await
3613            .unwrap()
3614            .unwrap()
3615            .unwrap();
3616        let (channel, epoch) =
3617            match serde_json::from_slice::<ClientControlResponse>(&opened.body).unwrap() {
3618                ClientControlResponse::RouteOpen {
3619                    route_channel,
3620                    route_epoch,
3621                    ..
3622                } => (route_channel, route_epoch),
3623                other => panic!("expected a healthy module route, got {other:?}"),
3624            };
3625
3626        let probe = control_request(
3627            3,
3628            ClientControlRequest::SupervisorHealthProbe {
3629                module_id: "blocked".into(),
3630            },
3631        );
3632        let mut ping = request(channel, 4, b"healthy request");
3633        ping.header.epoch = epoch;
3634        crate::write_frame(&mut client, &probe).await.unwrap();
3635        crate::write_frame(&mut client, &ping).await.unwrap();
3636        timeout(probe_timeout + Duration::from_secs(1), async {
3637            let timed_out = read_frame(&mut client).await.unwrap().unwrap();
3638            assert_eq!(timed_out.header.corr, 3);
3639            assert_eq!(timed_out.header.ty, FrameType::Error);
3640            let error: ErrorBody = serde_json::from_slice(&timed_out.body).unwrap();
3641            assert_eq!(error.code, "module_timeout");
3642            let forwarded = healthy_rx.recv().await.unwrap();
3643            assert_eq!(forwarded.header.corr, ping.header.corr);
3644            assert_eq!(forwarded.body, ping.body);
3645            let reply = Frame::build(
3646                FrameType::Response,
3647                ping.header.flags,
3648                forwarded.header.channel,
3649                forwarded.header.epoch,
3650                forwarded.header.corr,
3651                b"healthy response".to_vec(),
3652            )
3653            .unwrap();
3654            router
3655                .route_for_connection(&healthy_ctx, reply)
3656                .await
3657                .unwrap();
3658            let pong = read_frame(&mut client).await.unwrap().unwrap();
3659            assert_eq!(pong.header.ty, FrameType::Response);
3660            assert_eq!(pong.header.channel, channel);
3661            assert_eq!(pong.header.epoch, epoch);
3662            assert_eq!(pong.header.corr, 4);
3663            assert_eq!(pong.body, b"healthy response");
3664        })
3665        .await
3666        .expect(
3667            "the same client's healthy route must answer within the probe deadline plus margin",
3668        );
3669        assert_eq!(
3670            blocked_rx.len(),
3671            1,
3672            "the blocked module must remain undrained"
3673        );
3674        assert_eq!(blocked_rx.try_recv().unwrap().header.corr, 99);
3675        assert!(
3676            blocked_rx.try_recv().is_err(),
3677            "a timed-out probe must not be enqueued later"
3678        );
3679        drop(client);
3680        client_server.await.unwrap().unwrap();
3681    }
3682
3683    #[tokio::test]
3684    async fn aborted_accept_does_not_end_listener() {
3685        let listener = Arc::new(TcpListener::bind("127.0.0.1:0").await.unwrap());
3686        let addr = listener.local_addr().unwrap();
3687        let (auth, conn) = test_auth();
3688        let mut attempts = 0;
3689        let server = tokio::spawn(serve_listener_with_accept(
3690            Some(addr),
3691            echo_router(),
3692            auth,
3693            move || {
3694                attempts += 1;
3695                let result = if attempts == 1 {
3696                    Some(io::Error::from(io::ErrorKind::ConnectionAborted))
3697                } else {
3698                    None
3699                };
3700                let listener = Arc::clone(&listener);
3701                async move {
3702                    match result {
3703                        Some(err) => Err(err),
3704                        None => listener.accept().await,
3705                    }
3706                }
3707            },
3708        ));
3709        let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
3710        authenticate(&mut client, &conn).await;
3711        let ping = Frame::build(
3712            FrameType::Ping,
3713            Flags::new(false, Priority::Passive, false),
3714            0,
3715            0,
3716            77,
3717            Vec::new(),
3718        )
3719        .unwrap();
3720        crate::write_frame(&mut client, &ping).await.unwrap();
3721        let pong = timeout(TEST_DEADLINE, read_frame(&mut client))
3722            .await
3723            .unwrap()
3724            .unwrap()
3725            .unwrap();
3726        assert_eq!(pong.header.ty, FrameType::Pong);
3727        assert!(
3728            !server.is_finished(),
3729            "a temporary accept failure must not stop the listener"
3730        );
3731        server.abort();
3732    }
3733
3734    #[tokio::test]
3735    async fn exhausted_accept_backs_off_then_serves_connection() {
3736        let listener = Arc::new(TcpListener::bind("127.0.0.1:0").await.unwrap());
3737        let addr = listener.local_addr().unwrap();
3738        let (auth, conn) = test_auth();
3739        let mut attempts = 0;
3740        let server = tokio::spawn(serve_listener_with_accept(
3741            Some(addr),
3742            echo_router(),
3743            auth,
3744            move || {
3745                attempts += 1;
3746                // The platform's "too many open files" code: EMFILE on Unix,
3747                // WSAEMFILE on Windows. A bare 24 is ERROR_BAD_LENGTH on Windows.
3748                #[cfg(unix)]
3749                let emfile = rustix::io::Errno::MFILE.raw_os_error();
3750                #[cfg(windows)]
3751                let emfile = 10024;
3752                let error = (attempts == 1).then(|| io::Error::from_raw_os_error(emfile));
3753                let listener = Arc::clone(&listener);
3754                async move {
3755                    match error {
3756                        Some(err) => Err(err),
3757                        None => listener.accept().await,
3758                    }
3759                }
3760            },
3761        ));
3762        let started = Instant::now();
3763        let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
3764        authenticate(&mut client, &conn).await;
3765        assert!(
3766            started.elapsed() >= Duration::from_millis(50),
3767            "fd exhaustion must back off before retrying"
3768        );
3769        assert!(!server.is_finished());
3770        server.abort();
3771    }
3772
3773    #[tokio::test]
3774    async fn fatal_accept_error_still_stops_listener() {
3775        let (auth, _) = test_auth();
3776        let err = serve_listener_with_accept(None, echo_router(), auth, || async {
3777            Err(io::Error::from(io::ErrorKind::PermissionDenied))
3778        })
3779        .await
3780        .unwrap_err();
3781        assert!(
3782            matches!(err, ServerError::Accept { source, .. } if source.kind() == io::ErrorKind::PermissionDenied)
3783        );
3784    }
3785
3786    #[tokio::test]
3787    async fn serve_listeners_with_no_listeners_returns_typed_error() {
3788        let (auth, _conn) = test_auth();
3789        let err = serve_listeners(Vec::new(), echo_router(), auth)
3790            .await
3791            .expect_err("empty listener set must fail loudly");
3792        assert!(matches!(err, ServerError::NoListeners));
3793    }
3794
3795    #[tokio::test]
3796    async fn malformed_header_returns_typed_error_no_panic() {
3797        let (mut client, server_stream) = duplex(128);
3798        let (auth, conn) = test_auth();
3799        let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3800        authenticate(&mut client, &conn).await;
3801        let mut header = [0u8; HEADER_LEN];
3802        header[4] = PROTOCOL_VERSION;
3803        header[5] = 250;
3804
3805        client.write_all(&header).await.unwrap();
3806        drop(client);
3807
3808        let err = server.await.unwrap().unwrap_err();
3809        assert!(matches!(
3810            err,
3811            ConnectionError::FrameIo(FrameIoError::DecodeHeader(DecodeError::UnknownFrameType {
3812                byte: 250
3813            }))
3814        ));
3815    }
3816
3817    #[tokio::test]
3818    async fn truncated_body_returns_typed_error_no_panic() {
3819        let (mut client, server_stream) = duplex(128);
3820        let (auth, conn) = test_auth();
3821        let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3822        authenticate(&mut client, &conn).await;
3823        let frame = request(7, 8, b"abcd");
3824
3825        client.write_all(&frame.header.encode()).await.unwrap();
3826        client.write_all(b"ab").await.unwrap();
3827        drop(client);
3828
3829        let err = server.await.unwrap().unwrap_err();
3830        assert!(matches!(
3831            err,
3832            ConnectionError::FrameIo(FrameIoError::UnexpectedEof {
3833                stage: ReadStage::Body,
3834                expected: 4,
3835                actual: 2
3836            })
3837        ));
3838    }
3839
3840    #[tokio::test]
3841    async fn unknown_channel_is_returned_as_error_frame_and_connection_continues() {
3842        let (mut client, server_stream) = duplex(1024);
3843        let (auth, conn) = test_auth();
3844        let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3845        authenticate(&mut client, &conn).await;
3846        let unknown = request(42, 10, b"lost");
3847        let known = request(7, 11, b"still-routes");
3848
3849        crate::write_frame(&mut client, &unknown).await.unwrap();
3850        crate::write_frame(&mut client, &known).await.unwrap();
3851
3852        let error = crate::read_frame(&mut client).await.unwrap().unwrap();
3853        assert_eq!(error.header.ty, FrameType::Error);
3854        assert_eq!(error.header.channel, 42);
3855        assert_eq!(error.header.corr, 10);
3856        let error_body: ErrorBody = serde_json::from_slice(&error.body).unwrap();
3857        assert_eq!(error_body.code, "unknown_channel");
3858
3859        let response = crate::read_frame(&mut client).await.unwrap().unwrap();
3860        assert_eq!(response.header.ty, FrameType::Response);
3861        assert_eq!(response.header.channel, 7);
3862        assert_eq!(response.header.corr, 11);
3863        assert_eq!(response.body, b"still-routes");
3864
3865        drop(client);
3866        server.await.unwrap().unwrap();
3867    }
3868
3869    mod audit_findings {
3870        use super::*;
3871        include!("server_audit_tests.rs");
3872    }
3873}