Skip to main content

subc_daemon/
router.rs

1use std::{
2    collections::HashMap,
3    error::Error,
4    fmt,
5    sync::{
6        atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
7        Arc, Mutex,
8    },
9    time::{Duration, Instant},
10};
11
12use subc_protocol::{error_codes, ErrorBody, Flags, FrameType, Priority};
13use tokio::sync::{mpsc, Notify};
14use tracing::{debug, warn};
15
16use crate::{
17    control::ControlHandler,
18    forwarding::{
19        principal_label, CloseReason, ConnectionCloseReceiver, DataRoute, DataRouteState,
20        ForwardingError, ForwardingTable, RouteBinding, RouteRelease, UndeliveredFrame,
21    },
22    registry::ConnectionId,
23    DaemonCounters, Frame, FrameBuildError,
24};
25
26/// One queued outbound frame plus the instant it entered the writer queue.
27///
28/// The stamp exists for the reply-path half of slow-control diagnosis: a
29/// handler can finish in microseconds while the reply sits in this queue
30/// waiting for the writer task to be scheduled, and without a per-item stamp
31/// that wait is invisible to every other timing point (the client's round
32/// trip is the only witness, and it cannot say which side ate the time).
33/// Constructed exclusively inside [`FrameSink`] so no caller can forget it.
34#[derive(Debug)]
35pub struct OutboundFrame {
36    pub frame: Frame,
37    pub enqueued_at: std::time::Instant,
38    pub(crate) flushed: Option<tokio::sync::oneshot::Sender<()>>,
39    /// This frame's share of the connection's queued-byte count. Dropping the
40    /// frame (after the writer has written it, or when the queue itself is
41    /// dropped with the frame still in it) gives the bytes back. `None` only for
42    /// frames built outside a [`FrameSink`], which exist in tests alone.
43    pub(crate) charge: Option<EgressCharge>,
44}
45
46impl OutboundFrame {
47    fn charged(frame: Frame, charge: EgressCharge) -> Self {
48        Self {
49            frame,
50            enqueued_at: charge.enqueued_at,
51            flushed: None,
52            charge: Some(charge),
53        }
54    }
55}
56
57/// Bytes a frame occupies in the connection's egress queue for budget
58/// purposes: the fixed envelope header plus the body.
59fn queued_frame_bytes(frame: &Frame) -> usize {
60    subc_protocol::HEADER_LEN + frame.body.len()
61}
62
63/// A point-in-time view of one connection's egress queue, for diagnosing why a
64/// frame did not fit.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub(crate) struct EgressBacklog {
67    pub queued_bytes: usize,
68    pub queued_frames: usize,
69    /// Now minus the enqueue time of the frame the writer most recently took
70    /// off the queue (the frame it is writing, or has just written), or, if
71    /// the writer has taken nothing since the queue was last empty, of the
72    /// frame that made the queue non-empty. While the writer is blocked on a
73    /// frame this is exactly the oldest frame's age; between frames it can be
74    /// one frame older than the true head. `None` when nothing is queued.
75    pub oldest_age: Option<Duration>,
76}
77
78/// Queued-byte accounting shared by every clone of one connection's
79/// [`FrameSink`] and by every frame that sink has admitted. Its per-frame
80/// accounting uses atomics: this is on the path of every frame a module sends
81/// to a client, so it takes no lock per frame.
82#[derive(Debug)]
83struct EgressAccounting {
84    // Shared by the connection's sink clones so even an invalid data frame
85    // spends the one opportunity to present a claim after authentication.
86    ingress_seen: AtomicBool,
87    ingress_terminal: AtomicBool,
88    egress_terminal: AtomicBool,
89    egress_stopped: Notify,
90    byte_budget: usize,
91    queued_bytes: AtomicUsize,
92    queued_frames: AtomicUsize,
93    /// Origin for the nanosecond timestamps in `oldest_enqueued_nanos`.
94    time_base: Instant,
95    /// Enqueue time, as nanoseconds after `time_base` plus one, of the frame
96    /// described by [`EgressBacklog::oldest_age`]; 0 means none.
97    oldest_enqueued_nanos: AtomicU64,
98    /// Awaited senders currently parked on `freed`. A release only pays for a
99    /// notification when this is non-zero.
100    waiters: AtomicUsize,
101    /// Woken when a charged frame releases its bytes while a sender waits, so
102    /// the awaited send can re-check for room.
103    freed: Notify,
104    client_delivery_closed: AtomicBool,
105    client_delivery_stopped: Notify,
106    #[cfg(test)]
107    retire_after_reserve: AtomicBool,
108}
109
110impl EgressAccounting {
111    fn new(byte_budget: usize) -> Self {
112        Self {
113            ingress_seen: AtomicBool::new(false),
114            ingress_terminal: AtomicBool::new(false),
115            egress_terminal: AtomicBool::new(false),
116            egress_stopped: Notify::new(),
117            byte_budget,
118            queued_bytes: AtomicUsize::new(0),
119            queued_frames: AtomicUsize::new(0),
120            time_base: tokio::time::Instant::now().into_std(),
121            oldest_enqueued_nanos: AtomicU64::new(0),
122            waiters: AtomicUsize::new(0),
123            freed: Notify::new(),
124            client_delivery_closed: AtomicBool::new(false),
125            client_delivery_stopped: Notify::new(),
126            #[cfg(test)]
127            retire_after_reserve: AtomicBool::new(false),
128        }
129    }
130
131    fn stamp(&self, at: Instant) -> u64 {
132        (at.saturating_duration_since(self.time_base).as_nanos() as u64).saturating_add(1)
133    }
134
135    /// Charge `bytes` if they fit in the budget. A frame larger than the whole
136    /// budget (bodies may be up to 64 MiB) is still admitted into an EMPTY
137    /// queue, since it could otherwise never be sent at all; it simply has the
138    /// queue to itself until it is written.
139    fn try_charge(self: &Arc<Self>, bytes: usize) -> Option<EgressCharge> {
140        // SeqCst pairs with `release`: either this load sees bytes a release
141        // just freed, or that release sees this sender counted in `waiters`.
142        let mut current = self.queued_bytes.load(Ordering::SeqCst);
143        loop {
144            if current != 0 && current.saturating_add(bytes) > self.byte_budget {
145                return None;
146            }
147            match self.queued_bytes.compare_exchange_weak(
148                current,
149                current + bytes,
150                Ordering::SeqCst,
151                Ordering::SeqCst,
152            ) {
153                Ok(_) => return Some(self.record(bytes)),
154                Err(actual) => current = actual,
155            }
156        }
157    }
158
159    /// Charge `bytes` regardless of the budget. Used only for a frame whose
160    /// queue slot was reserved in advance, which must be sendable.
161    fn charge_unconditionally(self: &Arc<Self>, bytes: usize) -> EgressCharge {
162        self.queued_bytes.fetch_add(bytes, Ordering::SeqCst);
163        self.record(bytes)
164    }
165
166    fn record(self: &Arc<Self>, bytes: usize) -> EgressCharge {
167        let enqueued_at = tokio::time::Instant::now().into_std();
168        let stamp = self.stamp(enqueued_at);
169        if self.queued_frames.fetch_add(1, Ordering::AcqRel) == 0 {
170            // This frame made the queue non-empty, so it is the head until the
171            // writer takes something.
172            self.oldest_enqueued_nanos.store(stamp, Ordering::Release);
173        }
174        EgressCharge {
175            accounting: Arc::clone(self),
176            bytes,
177            stamp,
178            enqueued_at,
179        }
180    }
181
182    /// The writer has taken the frame stamped `stamp` off the queue.
183    fn taken_by_writer(&self, stamp: u64) {
184        self.oldest_enqueued_nanos.store(stamp, Ordering::Release);
185    }
186
187    fn release(&self, bytes: usize, stamp: u64) {
188        self.queued_bytes.fetch_sub(bytes, Ordering::SeqCst);
189        if self.queued_frames.fetch_sub(1, Ordering::AcqRel) == 1 {
190            // The queue drained. Clear the marker only if it still names this
191            // frame, so a frame admitted in the meantime keeps its stamp.
192            let _ = self.oldest_enqueued_nanos.compare_exchange(
193                stamp,
194                0,
195                Ordering::AcqRel,
196                Ordering::Acquire,
197            );
198        }
199        if self.waiters.load(Ordering::SeqCst) != 0 {
200            self.freed.notify_waiters();
201        }
202    }
203
204    fn backlog(&self) -> EgressBacklog {
205        let queued_frames = self.queued_frames.load(Ordering::Acquire);
206        let stamp = self.oldest_enqueued_nanos.load(Ordering::Acquire);
207        let oldest_age = (queued_frames != 0 && stamp != 0).then(|| {
208            let enqueued = self.time_base + Duration::from_nanos(stamp - 1);
209            tokio::time::Instant::from_std(enqueued).elapsed()
210        });
211        EgressBacklog {
212            queued_bytes: self.queued_bytes.load(Ordering::Acquire),
213            queued_frames,
214            oldest_age,
215        }
216    }
217}
218
219/// One admitted frame's claim on its connection's egress byte budget,
220/// returned when the frame is dropped.
221#[derive(Debug)]
222pub(crate) struct EgressCharge {
223    accounting: Arc<EgressAccounting>,
224    bytes: usize,
225    stamp: u64,
226    enqueued_at: Instant,
227}
228
229impl EgressCharge {
230    /// Called by the connection writer when it takes this frame off the queue,
231    /// so the backlog's oldest-age figure follows the writer.
232    pub(crate) fn taken_by_writer(&self) {
233        self.accounting.taken_by_writer(self.stamp);
234    }
235}
236
237impl Drop for EgressCharge {
238    fn drop(&mut self) {
239        self.accounting.release(self.bytes, self.stamp);
240    }
241}
242
243/// A queue slot reserved ahead of time (a pending `route.open` holds one until
244/// its module answers). Sending through it never waits and never fails for
245/// lack of room: the slot is already held, and its frame is charged to the
246/// byte count outside the budget check. At most
247/// `MAX_PENDING_ROUTE_OPENS_PER_CONNECTION` such frames exist per connection.
248#[derive(Debug)]
249pub(crate) struct EgressPermit {
250    permit: mpsc::OwnedPermit<OutboundFrame>,
251    accounting: Arc<EgressAccounting>,
252}
253
254impl EgressPermit {
255    /// Enqueue `frame` in the reserved slot. Returns true when the connection's
256    /// writer had already gone away or egress was retired, so the frame will
257    /// never be written.
258    pub(crate) fn send(self, frame: Frame) -> bool {
259        if self.accounting.egress_terminal.load(Ordering::Acquire) {
260            return true;
261        }
262        let charge = self
263            .accounting
264            .charge_unconditionally(queued_frame_bytes(&frame));
265        let sender = self.permit.send(OutboundFrame::charged(frame, charge));
266        sender.is_closed()
267    }
268}
269
270/// An `OutboundFrame` is a stamped `Frame`; deref keeps every existing frame
271/// read (headers, bodies, assertions) working on queued items unchanged.
272impl std::ops::Deref for OutboundFrame {
273    type Target = Frame;
274
275    fn deref(&self) -> &Frame {
276        &self.frame
277    }
278}
279
280/// Shared tracing-capture helpers for timing-observability tests across
281/// modules (router dispatch, server reply path). Test-only.
282#[cfg(test)]
283pub(crate) mod test_log {
284    use std::{
285        io::Write,
286        sync::{Arc, Mutex, OnceLock},
287    };
288
289    #[derive(Clone)]
290    struct TestLogWriter(Arc<Mutex<Vec<u8>>>);
291
292    impl Write for TestLogWriter {
293        fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
294            self.0
295                .lock()
296                .expect("test log capture is not poisoned")
297                .extend(buffer);
298            Ok(buffer.len())
299        }
300
301        fn flush(&mut self) -> std::io::Result<()> {
302            Ok(())
303        }
304    }
305
306    pub(crate) fn log_capture(
307        level: tracing::Level,
308    ) -> (Arc<Mutex<Vec<u8>>>, tracing::dispatcher::DefaultGuard) {
309        // tracing-core's single-dispatch fast path registers callsites using
310        // the emitting thread's default subscriber. A parallel test with no
311        // subscriber can therefore cache `never` for a callsite this capture
312        // needs. Keep a second dispatch alive so registration considers all
313        // live subscribers instead. This registry is never installed as a
314        // default: each test still records only into its own thread's writer.
315        static INTEREST_ANCHOR: OnceLock<tracing::Dispatch> = OnceLock::new();
316        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
317        let output = Arc::new(Mutex::new(Vec::new()));
318        let writer = Arc::clone(&output);
319        let subscriber = tracing_subscriber::fmt()
320            .with_max_level(level)
321            .with_ansi(false)
322            .without_time()
323            .with_target(false)
324            .with_writer(move || TestLogWriter(Arc::clone(&writer)))
325            .finish();
326        let guard = tracing::subscriber::set_default(subscriber);
327        (output, guard)
328    }
329
330    pub(crate) fn captured_logs(output: &Arc<Mutex<Vec<u8>>>) -> String {
331        String::from_utf8(
332            output
333                .lock()
334                .expect("test log capture is not poisoned")
335                .clone(),
336        )
337        .expect("tracing output is UTF-8")
338    }
339
340    #[cfg(test)]
341    mod tests {
342        use super::*;
343
344        fn emit_capture_probe(source: &str) {
345            tracing::error!(source, "parallel capture probe");
346        }
347
348        #[test]
349        fn parallel_callsite_registration_keeps_the_test_capture_enabled() {
350            let (output, _guard) = log_capture(tracing::Level::ERROR);
351            // First register the very same callsite on a thread without a
352            // default subscriber, while the test's capture remains live.
353            std::thread::spawn(|| emit_capture_probe("other-thread"))
354                .join()
355                .expect("unsubscribed thread exits");
356            emit_capture_probe("captured-thread");
357
358            let logs = captured_logs(&output);
359            assert!(
360                logs.contains("captured-thread"),
361                "capture was disabled: {logs}"
362            );
363            assert!(!logs.contains("other-thread"), "capture leaked: {logs}");
364        }
365    }
366}
367
368/// Cheaply cloneable handle to one connection's bounded outbound frame queue.
369///
370/// Backends emit responses, streaming frames, and future PUSH frames through this
371/// single path. The queue is bounded twice: by queued BYTES (the budget that
372/// matters for memory and for how long a slow reader may pause), and by the
373/// `mpsc` channel's frame count (a backstop). The socket layer owns the sole
374/// receiver/writer.
375#[derive(Debug, Clone)]
376pub struct FrameSink {
377    tx: mpsc::Sender<OutboundFrame>,
378    accounting: Arc<EgressAccounting>,
379}
380
381impl FrameSink {
382    pub(crate) fn terminate_ingress(&self) {
383        self.accounting
384            .ingress_terminal
385            .store(true, Ordering::Release);
386    }
387
388    pub(crate) fn ingress_terminal(&self) -> bool {
389        self.accounting.ingress_terminal.load(Ordering::Acquire)
390    }
391
392    // Retirement fences every sink clone and reserved permit synchronously,
393    // including senders already waiting for bytes or a queue slot.
394    pub(crate) fn terminate_egress(&self) {
395        self.accounting
396            .egress_terminal
397            .store(true, Ordering::Release);
398        self.accounting.egress_stopped.notify_waiters();
399        self.accounting.freed.notify_waiters();
400    }
401
402    pub(crate) fn egress_terminal(&self) -> bool {
403        self.accounting.egress_terminal.load(Ordering::Acquire)
404    }
405
406    pub(crate) fn first_ingress_frame(&self) -> bool {
407        !self.accounting.ingress_seen.swap(true, Ordering::Relaxed)
408    }
409    /// A sink with the standard per-connection byte budget
410    /// ([`crate::server::CONNECTION_EGRESS_BYTE_BUDGET`]); the frame-count bound
411    /// is whatever capacity `tx`'s channel was created with.
412    pub fn new(tx: mpsc::Sender<OutboundFrame>) -> Self {
413        Self::with_byte_budget(tx, crate::server::CONNECTION_EGRESS_BYTE_BUDGET)
414    }
415
416    pub(crate) fn with_byte_budget(tx: mpsc::Sender<OutboundFrame>, byte_budget: usize) -> Self {
417        Self {
418            tx,
419            accounting: Arc::new(EgressAccounting::new(byte_budget)),
420        }
421    }
422
423    /// Wait until the frame's bytes fit the budget, then charge them. Awaited
424    /// senders (control replies, error replies, shutdown notices) are never
425    /// refused by the byte budget: they wait for the writer to free bytes, just
426    /// as they wait for a free slot, which is the same backpressure they had
427    /// when the queue was bounded by frame count alone. Returns `None` if the
428    /// writer goes away or egress is retired while waiting.
429    async fn charge_waiting(&self, bytes: usize) -> Option<EgressCharge> {
430        if self.egress_terminal() {
431            return None;
432        }
433        if let Some(charge) = self.accounting.try_charge(bytes) {
434            return Some(charge);
435        }
436        // Counted as a waiter for as long as this future is parked, including
437        // when it is cancelled, so releases notify only while someone waits.
438        struct Waiting<'a>(&'a AtomicUsize);
439        impl Drop for Waiting<'_> {
440            fn drop(&mut self) {
441                self.0.fetch_sub(1, Ordering::SeqCst);
442            }
443        }
444        self.accounting.waiters.fetch_add(1, Ordering::SeqCst);
445        let _waiting = Waiting(&self.accounting.waiters);
446        loop {
447            let freed = self.accounting.freed.notified();
448            tokio::pin!(freed);
449            // Register interest before checking, so a release that happens
450            // between the check and the await still wakes this sender.
451            freed.as_mut().enable();
452            if self.egress_terminal() {
453                return None;
454            }
455            if let Some(charge) = self.accounting.try_charge(bytes) {
456                return Some(charge);
457            }
458            tokio::select! {
459                _ = &mut freed => {}
460                _ = self.tx.closed() => return None,
461            }
462        }
463    }
464
465    // Queue admission must recheck retirement after waiting for a frame slot,
466    // including when the bytes were charged before retirement began. Ordinary
467    // sends silently discard retired traffic; flush callers must not report it
468    // as queued or written.
469    async fn send_outbound(&self, outbound: OutboundFrame) -> Result<bool, RouterError> {
470        let stopped = self.accounting.egress_stopped.notified();
471        tokio::pin!(stopped);
472        stopped.as_mut().enable();
473        if self.egress_terminal() {
474            return Ok(false);
475        }
476        let header = &outbound.frame.header;
477        let closed = || {
478            RouterError::backend_with_epoch(
479                header.channel,
480                header.epoch,
481                header.corr,
482                "connection writer closed",
483            )
484        };
485        let permit = tokio::select! {
486            biased;
487            _ = &mut stopped => return Ok(false),
488            permit = self.tx.reserve() => permit.map_err(|_| closed())?,
489        };
490        if self.egress_terminal() {
491            return Ok(false);
492        }
493        permit.send(outbound);
494        Ok(true)
495    }
496
497    pub async fn send(&self, frame: Frame) -> Result<(), RouterError> {
498        if self.egress_terminal() {
499            return Ok(());
500        }
501        let channel = frame.header.channel;
502        let epoch = frame.header.epoch;
503        let corr = frame.header.corr;
504        let closed =
505            || RouterError::backend_with_epoch(channel, epoch, corr, "connection writer closed");
506        let Some(charge) = self.charge_waiting(queued_frame_bytes(&frame)).await else {
507            return if self.egress_terminal() {
508                Ok(())
509            } else {
510                Err(closed())
511            };
512        };
513        self.send_outbound(OutboundFrame::charged(frame, charge))
514            .await
515            .map(|_| ())
516    }
517
518    /// Shutdown notices must leave the socket writer before an idle daemon exits.
519    /// Queue admission alone does not prove this; the writer acknowledges flush.
520    ///
521    /// The local endpoint uses it the same way for its clients-only refusal: the
522    /// connection closes right after the refusal is sent, so the writer must
523    /// flush it first.
524    pub async fn send_flushed(&self, frame: Frame) -> Result<(), RouterError> {
525        self.send_flushed_notifying_enqueue(frame, || {}).await
526    }
527
528    /// Notify the caller after queue admission, before waiting for the writer's
529    /// flush, so cancellation withdraws only requests that could have arrived.
530    pub(crate) async fn send_flushed_notifying_enqueue(
531        &self,
532        frame: Frame,
533        queued: impl FnOnce(),
534    ) -> Result<(), RouterError> {
535        let (tx, rx) = tokio::sync::oneshot::channel();
536        let charge = self
537            .charge_waiting(queued_frame_bytes(&frame))
538            .await
539            .ok_or_else(|| RouterError::backend(0, 0, "connection writer closed"))?;
540        let mut outbound = OutboundFrame::charged(frame, charge);
541        outbound.flushed = Some(tx);
542        if !self.send_outbound(outbound).await? {
543            return Err(RouterError::backend(0, 0, "connection egress retired"));
544        }
545        queued();
546        rx.await
547            .map_err(|_| RouterError::backend(0, 0, "connection flush failed"))
548    }
549
550    pub(crate) async fn reserve_owned(&self) -> Result<EgressPermit, RouterError> {
551        let stopped = self.accounting.egress_stopped.notified();
552        tokio::pin!(stopped);
553        stopped.as_mut().enable();
554        if self.egress_terminal() {
555            return Err(RouterError::backend(0, 0, "connection egress retired"));
556        }
557        let permit = tokio::select! {
558            biased;
559            _ = &mut stopped => return Err(RouterError::backend(0, 0, "connection egress retired")),
560            permit = self.tx.clone().reserve_owned() => permit
561                .map_err(|_| RouterError::backend(0, 0, "connection writer closed"))?,
562        };
563        #[cfg(test)]
564        if self
565            .accounting
566            .retire_after_reserve
567            .swap(false, Ordering::Relaxed)
568        {
569            self.terminate_egress();
570        }
571        if self.egress_terminal() {
572            return Err(RouterError::backend(0, 0, "connection egress retired"));
573        }
574        Ok(EgressPermit {
575            permit,
576            accounting: Arc::clone(&self.accounting),
577        })
578    }
579
580    #[cfg(test)]
581    pub(crate) fn try_reserve_owned(&self) -> Result<EgressPermit, RouterError> {
582        if self.egress_terminal() {
583            return Err(RouterError::backend(0, 0, "connection egress retired"));
584        }
585        let permit = self
586            .tx
587            .clone()
588            .try_reserve_owned()
589            .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
590        Ok(EgressPermit {
591            permit,
592            accounting: Arc::clone(&self.accounting),
593        })
594    }
595
596    pub(crate) fn is_closed(&self) -> bool {
597        self.tx.is_closed()
598    }
599
600    /// What the connection's egress queue holds right now.
601    pub(crate) fn backlog(&self) -> EgressBacklog {
602        self.accounting.backlog()
603    }
604
605    /// Stop module deliveries as soon as the client reader exits, without
606    /// waiting for the socket writer's separate teardown drain grace.
607    pub(crate) fn close_client_delivery(&self) {
608        self.accounting
609            .client_delivery_closed
610            .store(true, Ordering::Release);
611        self.accounting.client_delivery_stopped.notify_waiters();
612    }
613
614    /// A full queue can be a short fanout burst rather than a stopped reader.
615    /// Spend only the grace the atomic backlog age has not already used.
616    async fn send_to_client(&self, frame: Frame) -> Result<(), ClientDeliveryFailure> {
617        if self.egress_terminal() {
618            return Ok(());
619        }
620        let frame_type = frame.header.ty;
621        let flags = frame.header.flags;
622        let stopped = self.accounting.client_delivery_stopped.notified();
623        tokio::pin!(stopped);
624        stopped.as_mut().enable();
625        let failure = |cause, error| ClientDeliveryFailure {
626            diagnosis: ClientDeliveryDiagnosis {
627                frame_type,
628                flags,
629                cause,
630            },
631            error,
632        };
633        let closed = || {
634            RouterError::backend_with_epoch(
635                frame.header.channel,
636                frame.header.epoch,
637                frame.header.corr,
638                "client connection closed",
639            )
640        };
641        if self
642            .accounting
643            .client_delivery_closed
644            .load(Ordering::Acquire)
645        {
646            return Err(failure("client_closed", closed()));
647        }
648        let (frame, error) = match self.try_send_owned(frame) {
649            Ok(()) => return Ok(()),
650            Err(refused) => refused,
651        };
652        if self.is_closed() {
653            return Err(failure("client_closed", error));
654        }
655        let grace = crate::server::CONNECTION_EGRESS_STALL_GRACE;
656        let age = self.backlog().oldest_age.unwrap_or_default();
657        if age > grace {
658            return Err(failure("oldest_frame_older_than_250_ms", error));
659        }
660        let result = tokio::select! {
661            biased;
662            _ = &mut stopped => return Err(failure("client_closed", error)),
663            result = tokio::time::timeout(grace.saturating_sub(age), self.send(frame)) => result,
664        };
665        match result {
666            Ok(Ok(())) => Ok(()),
667            Ok(Err(error)) => Err(failure("client_closed", error)),
668            Err(_) => Err(failure("waited_250_ms_without_room", error)),
669        }
670    }
671
672    /// Enqueue without waiting. Fails when the frame's bytes would take the
673    /// queue past its byte budget, when the channel's frame-count backstop is
674    /// full, or when the writer is gone.
675    pub(crate) fn try_send(&self, frame: Frame) -> Result<(), RouterError> {
676        self.try_send_owned(frame).map_err(|(_, error)| error)
677    }
678
679    fn try_send_owned(&self, frame: Frame) -> Result<(), (Frame, RouterError)> {
680        if self.egress_terminal() {
681            return Ok(());
682        }
683        let channel = frame.header.channel;
684        let epoch = frame.header.epoch;
685        let corr = frame.header.corr;
686        let unavailable = |why: String| {
687            RouterError::backend_with_epoch(
688                channel,
689                epoch,
690                corr,
691                format!("connection writer unavailable: {why}"),
692            )
693        };
694        let bytes = queued_frame_bytes(&frame);
695        let Some(charge) = self.accounting.try_charge(bytes) else {
696            if self.tx.is_closed() {
697                return Err((frame, unavailable("channel closed".to_string())));
698            }
699            return Err((
700                frame,
701                unavailable(format!(
702                    "egress byte budget exhausted ({} queued bytes, frame of {bytes} bytes, budget {})",
703                    self.accounting.queued_bytes.load(Ordering::Acquire),
704                    self.accounting.byte_budget
705                )),
706            ));
707        };
708        // Return the refused frame for a bounded retry; dropping the rest of
709        // the outbound wrapper returns its charge.
710        if self.egress_terminal() {
711            return Ok(());
712        }
713        self.tx
714            .try_send(OutboundFrame::charged(frame, charge))
715            .map_err(|err| {
716                let error = unavailable(err.to_string());
717                (err.into_inner().frame, error)
718            })
719    }
720}
721
722#[derive(Debug)]
723struct ClientDeliveryFailure {
724    diagnosis: ClientDeliveryDiagnosis,
725    error: RouterError,
726}
727
728/// Header facts only: payloads can contain secrets and must never enter logs.
729#[derive(Debug)]
730pub(crate) struct ClientDeliveryDiagnosis {
731    pub frame_type: FrameType,
732    pub flags: Flags,
733    pub cause: &'static str,
734}
735
736impl fmt::Display for ClientDeliveryFailure {
737    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
738        self.error.fmt(f)
739    }
740}
741
742/// Minimum time between two route GOODBYEs the daemon sends one module
743/// connection for one channel in answer to the module's frames on a (channel,
744/// epoch) the daemon holds no route for.
745///
746/// A module that missed a GOODBYE keeps sending on that route (a streaming
747/// module, many frames a second), and every one of those frames lands here. One
748/// answer is enough when it arrives, so answering each frame would only flood
749/// the module's egress queue at the moment it is already behind. Five seconds
750/// is long enough for an answer queued behind a deep backlog to reach the module
751/// and take effect before a second is sent, and short enough that an answer
752/// the queue refused is retried by the next orphan frame well within a minute.
753const ORPHAN_ROUTE_GOODBYE_INTERVAL: Duration = Duration::from_secs(5);
754
755/// Once one connection has this many remembered channels, entries older than
756/// [`ORPHAN_ROUTE_GOODBYE_INTERVAL`] are pruned before another is added. An
757/// expired entry has no effect on rate limiting, so pruning never changes a
758/// decision; it keeps a module that orphaned many channels long ago from
759/// pinning memory for all of them. The map is bounded in any case by the
760/// 16-bit channel space and is dropped whole when the connection ends.
761const ORPHAN_ROUTE_GOODBYE_PRUNE_AT: usize = 256;
762
763/// When each module connection was last sent an orphan-route GOODBYE, per
764/// channel. Shared by the [`Router`] (which consults it) and every
765/// [`RouterConnection`] (which removes its own entry when the connection ends).
766#[derive(Debug, Default)]
767struct OrphanGoodbyeLimiter {
768    last_sent: Mutex<HashMap<ConnectionId, HashMap<u16, tokio::time::Instant>>>,
769}
770
771impl OrphanGoodbyeLimiter {
772    /// True, and the send recorded, when `channel` on `connection_id` has not
773    /// been answered within the interval.
774    fn claim(&self, connection_id: ConnectionId, channel: u16) -> bool {
775        let now = tokio::time::Instant::now();
776        let mut last_sent = self
777            .last_sent
778            .lock()
779            .unwrap_or_else(std::sync::PoisonError::into_inner);
780        let channels = last_sent.entry(connection_id).or_default();
781        if channels.get(&channel).is_some_and(|sent| {
782            now.saturating_duration_since(*sent) < ORPHAN_ROUTE_GOODBYE_INTERVAL
783        }) {
784            return false;
785        }
786        if channels.len() >= ORPHAN_ROUTE_GOODBYE_PRUNE_AT {
787            channels.retain(|_, sent| {
788                now.saturating_duration_since(*sent) < ORPHAN_ROUTE_GOODBYE_INTERVAL
789            });
790        }
791        channels.insert(channel, now);
792        true
793    }
794
795    fn forget_connection(&self, connection_id: ConnectionId) {
796        self.last_sent
797            .lock()
798            .unwrap_or_else(std::sync::PoisonError::into_inner)
799            .remove(&connection_id);
800    }
801}
802
803/// Per-route context shared with backends besides the frame itself.
804#[derive(Debug, Clone)]
805pub struct RouteCtx {
806    pub connection_id: ConnectionId,
807    pub egress: FrameSink,
808}
809
810/// Closed set of data-plane backends for non-zero channels.
811///
812/// Channel 0 is structurally special and remains `Router::control`, not an
813/// enum variant. Static/test backends live in `Router::backends`; the forwarding
814/// backend is selected dynamically only when a per-connection forwarding binding exists.
815#[derive(Debug, Clone)]
816pub enum Backend {
817    Echo(EchoBackend),
818    Forward(ForwardBackend),
819}
820
821impl From<EchoBackend> for Backend {
822    fn from(backend: EchoBackend) -> Self {
823        Self::Echo(backend)
824    }
825}
826
827impl From<ForwardBackend> for Backend {
828    fn from(backend: ForwardBackend) -> Self {
829        Self::Forward(backend)
830    }
831}
832
833impl Backend {
834    pub async fn handle(&self, ctx: RouteCtx, frame: Frame) -> Result<(), RouterError> {
835        match self {
836            Self::Echo(backend) => backend.handle(ctx, frame).await,
837            Self::Forward(backend) => backend.handle(ctx, frame).await,
838        }
839    }
840}
841
842/// I/O-agnostic splice router keyed by envelope `channel`.
843///
844/// Channel 0 is reserved for subc itself and is always dispatched to the
845/// dedicated control handler. Other channels must be explicitly registered.
846/// Unknown client-originated non-zero channels are translated to canonical JSON `ERROR` frames on
847/// the connection sink so the peer can continue using the same socket. Module-originated frames for
848/// released route channels are logged and dropped as the channel-gone race backstop.
849///
850/// DATA-PLANE BODIES ARE NEVER DECODED HERE, and the consequence is worth stating
851/// because it looks like a guarantee and is not. Additive fields in a request or
852/// response body reach the far side untouched — not because anything permits them,
853/// but because routing reads only the 21-byte header and treats the body as opaque
854/// bytes. That is a performance property, so **nothing prevents it from changing**:
855/// a future reason to inspect a body would convert a wire-transparent path into a
856/// filtering one, and nobody would think of it as a contract change.
857///
858/// So when a peer asks whether subc sees an additive field, the answer is per-path
859/// and this path's zero means WE NEVER LOOK rather than WE LOOK AT EVERYTHING. The
860/// control plane (typed enums at the frame boundary) and the MCP gateway (envelope
861/// unwrap plus a named struct) both narrow; only this one does not.
862pub struct Router {
863    backends: HashMap<u16, Backend>,
864    control: Arc<ControlHandler>,
865    forwarding: Arc<ForwardingTable>,
866    forward_backend: ForwardBackend,
867    counters: DaemonCounters,
868    next_connection_id: AtomicU64,
869    orphan_goodbyes: Arc<OrphanGoodbyeLimiter>,
870}
871
872impl Router {
873    pub fn with_control_handler(control: Arc<ControlHandler>) -> Self {
874        // The handler the router serves is the one a swap must tell when it
875        // promotes a candidate; this is where it first sits behind an `Arc`.
876        control.install_swap_promotion_observer();
877        let forwarding = control.forwarding();
878        let counters = control.counters();
879        Self {
880            backends: HashMap::new(),
881            control,
882            forwarding: Arc::clone(&forwarding),
883            forward_backend: ForwardBackend::new(forwarding),
884            counters,
885            // ConnectionId::LOCAL is 0; real socket ids start at 1 and never collide.
886            next_connection_id: AtomicU64::new(1),
887            orphan_goodbyes: Arc::default(),
888        }
889    }
890
891    /// Install only the inherited-channel service; the supervisor must not own
892    /// this router or retain it after the listeners have stopped serving.
893    pub(crate) fn install_registration_service(self: &Arc<Self>, auth: crate::server::ServerAuth) {
894        self.control
895            .install_registration_service(Arc::downgrade(self), auth);
896    }
897
898    pub fn with_default_self_handler() -> Self {
899        Self::with_control_handler(Arc::new(ControlHandler::default()))
900    }
901
902    pub fn forwarding(&self) -> Arc<ForwardingTable> {
903        Arc::clone(&self.forwarding)
904    }
905
906    pub fn register_backend(
907        &mut self,
908        channel: u16,
909        backend: impl Into<Backend>,
910    ) -> Result<(), RouterError> {
911        self.register_backend_arc(channel, Arc::new(backend.into()))
912    }
913
914    pub(crate) fn register_backend_arc(
915        &mut self,
916        channel: u16,
917        backend: Arc<Backend>,
918    ) -> Result<(), RouterError> {
919        if channel == 0 {
920            return Err(RouterError::ReservedChannelZero);
921        }
922        if self.backends.contains_key(&channel) {
923            return Err(RouterError::DuplicateChannel { channel });
924        }
925        self.backends.insert(channel, backend.as_ref().clone());
926        Ok(())
927    }
928
929    /// Start a connection-scoped routing context. Dropping the guard releases
930    /// any control-plane registrations owned by the connection.
931    fn record_module_frame_drop(&self, connection_id: ConnectionId) -> Result<(), RouterError> {
932        let module_id = self
933            .forwarding
934            .module_id_for_connection(connection_id)
935            .map_err(RouterError::Forwarding)?;
936        self.counters
937            .increment_module_frames_dropped_no_route(module_id.as_deref());
938        Ok(())
939    }
940
941    /// A module sent a non-request frame on a (channel, epoch) the daemon holds
942    /// no route for: most often a route the daemon released whose GOODBYE the
943    /// module never received, so the module still believes it is open and keeps
944    /// sending. Count the drop, and tell the module to let go of exactly that
945    /// (channel, epoch) with a route GOODBYE, at most once per
946    /// [`ORPHAN_ROUTE_GOODBYE_INTERVAL`] per connection and channel.
947    ///
948    /// The answer uses `try_send`: it is a best-effort nudge, and if the queue
949    /// refuses it, the module's next frame on that route after the interval
950    /// asks again. A GOODBYE from the module is not answered, since the module
951    /// is already letting go of the route.
952    fn handle_orphan_module_frame(&self, ctx: &RouteCtx, frame: &Frame) -> Result<(), RouterError> {
953        let channel = frame.header.channel;
954        let epoch = frame.header.epoch;
955        let module_id = self
956            .forwarding
957            .module_id_for_connection(ctx.connection_id)
958            .map_err(RouterError::Forwarding)?;
959        self.counters
960            .increment_module_frames_dropped_no_route(module_id.as_deref());
961        if self
962            .forwarding
963            .module_route_epoch_was_allocated(ctx.connection_id, channel, epoch)
964            .map_err(RouterError::Forwarding)?
965        {
966            self.counters
967                .increment_module_frames_dropped_released_route(module_id.as_deref());
968        }
969        if frame.header.ty == FrameType::Goodbye
970            || !self.orphan_goodbyes.claim(ctx.connection_id, channel)
971        {
972            return Ok(());
973        }
974        let goodbye = Frame::build_with_version(
975            frame.header.ver,
976            FrameType::Goodbye,
977            Flags::new(false, Priority::Passive, false),
978            channel,
979            epoch,
980            0,
981            Vec::new(),
982        )
983        .map_err(RouterError::FrameBuild)?;
984        match ctx.egress.try_send(goodbye) {
985            Ok(()) => {
986                self.counters.increment_module_orphan_route_goodbyes_sent();
987                debug!(
988                    connection_id = ctx.connection_id.get(),
989                    module_id = module_id.as_deref().unwrap_or("unknown"),
990                    channel,
991                    epoch,
992                    "answered module frame on a route the daemon does not hold with a route GOODBYE"
993                );
994            }
995            Err(err) => {
996                self.forwarding.warn_frame_drop(
997                    ctx.connection_id,
998                    channel,
999                    epoch,
1000                    "daemon_to_module",
1001                    if ctx.egress.is_closed() {
1002                        "endpoint_gone"
1003                    } else {
1004                        "egress_budget"
1005                    },
1006                );
1007                debug!(
1008                connection_id = ctx.connection_id.get(),
1009                module_id = module_id.as_deref().unwrap_or("unknown"),
1010                channel,
1011                epoch,
1012                error = %err,
1013                "could not enqueue route GOODBYE for module frame on a route the daemon does not hold; the next such frame retries"
1014                );
1015            }
1016        }
1017        Ok(())
1018    }
1019
1020    pub fn begin_connection(&self) -> RouterConnection {
1021        let raw = self.next_connection_id.fetch_add(1, Ordering::Relaxed);
1022        let id = ConnectionId::new(raw);
1023        let close_receiver = self.forwarding.register_connection_close(id);
1024        RouterConnection {
1025            id,
1026            control_handler: Arc::clone(&self.control),
1027            forwarding: Arc::clone(&self.forwarding),
1028            close_receiver: Some(close_receiver),
1029            orphan_goodbyes: Arc::clone(&self.orphan_goodbyes),
1030        }
1031    }
1032
1033    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
1034        self.control.route_open_target(frame)
1035    }
1036
1037    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
1038        self.control.record_local_connection(connection);
1039    }
1040
1041    pub(crate) fn record_captured_peer(
1042        &self,
1043        connection: ConnectionId,
1044        peer: subc_os::local_peer::CapturedPeer,
1045    ) {
1046        self.control.record_captured_peer(connection, peer);
1047    }
1048
1049    pub(crate) fn record_caller_endpoints(
1050        &self,
1051        connection: ConnectionId,
1052        endpoints: Option<(std::net::SocketAddr, std::net::SocketAddr)>,
1053    ) {
1054        self.control.record_caller_endpoints(connection, endpoints);
1055    }
1056
1057    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
1058        self.control.defers_privileged_control(ctx, frame)
1059    }
1060
1061    pub(crate) fn defers_config_approval(&self, frame: &Frame) -> bool {
1062        self.control.defers_config_approval(frame)
1063    }
1064
1065    pub(crate) fn reserve_config_approval(
1066        &self,
1067        ctx: &RouteCtx,
1068        frame: &Frame,
1069    ) -> Result<
1070        Option<crate::config_gate::runtime::ApprovalRequestGuard>,
1071        crate::config_gate::GateError,
1072    > {
1073        self.control.reserve_config_approval(ctx, frame)
1074    }
1075
1076    pub(crate) fn route_open_capacity_refusal(
1077        &self,
1078        ctx: &RouteCtx,
1079        frame: &Frame,
1080        target_module_id: &str,
1081        in_flight: usize,
1082        limit: usize,
1083    ) -> Result<Frame, RouterError> {
1084        self.control
1085            .route_open_capacity_refusal(ctx, frame, target_module_id, in_flight, limit)
1086    }
1087
1088    pub async fn route_for_connection(
1089        &self,
1090        ctx: &RouteCtx,
1091        frame: Frame,
1092    ) -> Result<(), RouterError> {
1093        self.route_for_connection_started(ctx, frame, None).await
1094    }
1095
1096    pub(crate) async fn observe_connection_wait<F: std::future::Future>(
1097        &self,
1098        ctx: &RouteCtx,
1099        kind: &'static str,
1100        future: F,
1101    ) -> F::Output {
1102        self.counters
1103            .observe_reader_wait(
1104                || {
1105                    let module = self
1106                        .forwarding
1107                        .module_id_for_connection(ctx.connection_id)
1108                        .ok()
1109                        .flatten();
1110                    let principal = if module.is_some() { "module" } else { "direct" };
1111                    (
1112                        module.unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
1113                        principal.into(),
1114                    )
1115                },
1116                kind,
1117                future,
1118            )
1119            .await
1120    }
1121
1122    pub(crate) async fn route_for_connection_started(
1123        &self,
1124        ctx: &RouteCtx,
1125        frame: Frame,
1126        dispatch_started_at: Option<Instant>,
1127    ) -> Result<(), RouterError> {
1128        // Embedded callers have no socket reader; mark at their ingress instead.
1129        let first = ctx.egress.first_ingress_frame();
1130        self.route_for_connection_ingress(ctx, frame, dispatch_started_at, first)
1131            .await
1132    }
1133
1134    pub(crate) async fn route_for_connection_ingress(
1135        &self,
1136        ctx: &RouteCtx,
1137        frame: Frame,
1138        dispatch_started_at: Option<Instant>,
1139        first: bool,
1140    ) -> Result<(), RouterError> {
1141        if ctx.egress.ingress_terminal() {
1142            return Ok(());
1143        }
1144        let channel = frame.header.channel;
1145        let epoch = frame.header.epoch;
1146        let corr = frame.header.corr;
1147        if channel == 0 {
1148            debug!(
1149                connection_id = ctx.connection_id.get(),
1150                corr,
1151                frame_type = ?frame.header.ty,
1152                "routing control frame"
1153            );
1154            // The connection loop dispatches every control operation directly
1155            // except `route.open`, activity writes, held config approvals and
1156            // privileged requests. Each
1157            // task passes a timestamp captured before
1158            // spawn, so slow-dispatch timing includes scheduler delay but no
1159            // wait in an application-owned queue.
1160            let dispatch_started_at = (frame.header.ty == FrameType::Request)
1161                .then(|| dispatch_started_at.unwrap_or_else(Instant::now));
1162            // Only review-producing requests need the post-flush receipt hook.
1163            // Probing every response would scan large catalog bodies again.
1164            let review_request = self.control.config_desktop_review_request(&frame);
1165            let responses = self
1166                .control
1167                .handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
1168                .await?;
1169            for response in responses {
1170                let view = if review_request {
1171                    self.control
1172                        .config_desktop_review_response(ctx.connection_id, &response)
1173                        .await
1174                } else {
1175                    None
1176                };
1177                if let Some(view) = view {
1178                    self.observe_connection_wait(
1179                        ctx,
1180                        "reply_egress",
1181                        self.control
1182                            .deliver_config_desktop_review(ctx, response, view),
1183                    )
1184                    .await?;
1185                    continue;
1186                }
1187                self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(response))
1188                    .await?;
1189            }
1190            return Ok(());
1191        }
1192
1193        let data_route = self
1194            .forwarding
1195            .lookup_data_route(ctx.connection_id, channel, epoch)
1196            .map_err(RouterError::Forwarding)?;
1197
1198        match data_route {
1199            DataRoute::Module(DataRouteState::EpochMismatch) => {
1200                self.forwarding.warn_frame_drop(
1201                    ctx.connection_id,
1202                    channel,
1203                    epoch,
1204                    "module_to_client",
1205                    "stale_epoch",
1206                );
1207                if frame.header.ty == FrameType::Request {
1208                    self.counters
1209                        .increment_module_requests_dropped_stale_route();
1210                    let err = RouterError::StaleRouteEpoch {
1211                        channel,
1212                        epoch,
1213                        corr,
1214                    };
1215                    if let Some(error_frame) = err.to_error_frame() {
1216                        self.observe_connection_wait(
1217                            ctx,
1218                            "reply_egress",
1219                            ctx.egress.send(error_frame),
1220                        )
1221                        .await?;
1222                    }
1223                } else {
1224                    self.handle_orphan_module_frame(ctx, &frame)?;
1225                }
1226                debug!(
1227                    connection_id = ctx.connection_id.get(),
1228                    channel, epoch, corr, "dropping module frame for stale route epoch"
1229                );
1230                return Ok(());
1231            }
1232            DataRoute::Module(DataRouteState::Reserved) => {
1233                self.forwarding.warn_frame_drop(
1234                    ctx.connection_id,
1235                    channel,
1236                    epoch,
1237                    "module_to_client",
1238                    "missing_binding",
1239                );
1240                if frame.header.ty == FrameType::Request {
1241                    self.counters
1242                        .increment_module_requests_dropped_stale_route();
1243                    let err = RouterError::UnknownChannel {
1244                        channel,
1245                        epoch,
1246                        corr,
1247                    };
1248                    if let Some(error_frame) = err.to_error_frame() {
1249                        self.observe_connection_wait(
1250                            ctx,
1251                            "reply_egress",
1252                            ctx.egress.send(error_frame),
1253                        )
1254                        .await?;
1255                    }
1256                } else {
1257                    self.record_module_frame_drop(ctx.connection_id)?;
1258                }
1259                debug!(
1260                    connection_id = ctx.connection_id.get(),
1261                    channel, epoch, corr, "dropping module frame for reserved route handle"
1262                );
1263                return Ok(());
1264            }
1265            DataRoute::Module(DataRouteState::Absent) => {
1266                self.forwarding.warn_frame_drop(
1267                    ctx.connection_id,
1268                    channel,
1269                    epoch,
1270                    "module_to_client",
1271                    "unknown_channel",
1272                );
1273                if frame.header.ty == FrameType::Request {
1274                    self.counters
1275                        .increment_module_requests_dropped_stale_route();
1276                    let err = RouterError::UnknownChannel {
1277                        channel,
1278                        epoch,
1279                        corr,
1280                    };
1281                    if let Some(error_frame) = err.to_error_frame() {
1282                        self.observe_connection_wait(
1283                            ctx,
1284                            "reply_egress",
1285                            ctx.egress.send(error_frame),
1286                        )
1287                        .await?;
1288                    }
1289                } else {
1290                    self.handle_orphan_module_frame(ctx, &frame)?;
1291                }
1292                debug!(
1293                    connection_id = ctx.connection_id.get(),
1294                    channel, epoch, corr, "dropping module frame for absent route handle"
1295                );
1296                return Ok(());
1297            }
1298            DataRoute::Module(DataRouteState::Bound(route)) => {
1299                if frame.header.ty == FrameType::Goodbye {
1300                    if let RouteRelease::Removed(target) = self
1301                        .forwarding
1302                        .release_module_route(ctx.connection_id, channel, epoch)
1303                        .map_err(RouterError::Forwarding)?
1304                    {
1305                        let mut goodbye = frame;
1306                        goodbye.header.channel = target.channel;
1307                        goodbye.header.epoch = target.epoch;
1308                        // A module must never be able to make a frame look
1309                        // daemon-authored, so the origin bit is cleared on
1310                        // every module frame relayed to a client.
1311                        goodbye.header.flags = goodbye.header.flags.without_daemon_origin();
1312                        if let Err(err) = self
1313                            .observe_connection_wait(
1314                                ctx,
1315                                "module_to_client",
1316                                target.sink.send_to_client(goodbye),
1317                            )
1318                            .await
1319                        {
1320                            if !target.close_on_delivery_failure() {
1321                                self.forwarding.warn_frame_drop(
1322                                    target.connection_id,
1323                                    target.channel,
1324                                    target.epoch,
1325                                    "module_to_client",
1326                                    err.diagnosis.cause,
1327                                );
1328                            }
1329                            if target.close_on_delivery_failure()
1330                                && self
1331                                    .forwarding
1332                                    .escalate_client_delivery_failure_diagnosed(
1333                                        target.connection_id,
1334                                        target.channel,
1335                                        target.epoch,
1336                                        CloseReason::new(
1337                                            "route_goodbye_delivery_failed",
1338                                            format!(
1339                                                "failed to enqueue route GOODBYE for client channel {}: {err}",
1340                                                target.channel
1341                                            ),
1342                                        ),
1343                                        UndeliveredFrame {
1344                                            module_id: Some(&route.module_id),
1345                                            sink: &target.sink,
1346                                        },
1347                                        Some(&err.diagnosis),
1348                                    )
1349                                    .map_err(RouterError::Forwarding)?
1350                            {
1351                                self.counters.increment_goodbye_relay_client_failed();
1352                            }
1353                        }
1354                    } else {
1355                        self.forwarding.warn_frame_drop(
1356                            ctx.connection_id,
1357                            channel,
1358                            epoch,
1359                            "module_to_client",
1360                            "missing_binding",
1361                        );
1362                    }
1363                    return Ok(());
1364                }
1365
1366                // Accounting allows an oversized frame to occupy an empty queue
1367                // on other send paths. Refuse it at this splice before admission,
1368                // so the next ordinary reply cannot close a multiplexed client.
1369                let bytes = queued_frame_bytes(&frame);
1370                let limit = route.client_sink.accounting.byte_budget;
1371                if bytes > limit {
1372                    let ty = frame.header.ty;
1373                    let flags = frame.header.flags;
1374                    drop(frame);
1375                    return self
1376                        .refuse_oversized_module_frame(ctx, &route, (ty, flags), corr, bytes)
1377                        .await;
1378                }
1379
1380                // A terminal frame ends the request at the module whether or not
1381                // the client can still take it, so its credit is released before
1382                // delivery is attempted. Releasing only after a successful
1383                // enqueue would leave a drain counting a finished request until
1384                // the client connection's cleanup removes the route.
1385                let releases_credit = is_terminal_frame(frame.header.ty);
1386                if releases_credit {
1387                    route.flow.release_corr(corr);
1388                }
1389                let mut frame = frame;
1390                frame.header.channel = route.client_channel;
1391                frame.header.epoch = route.client_epoch;
1392                // Responses, errors, stream data and ends, and reverse
1393                // requests all pass through here. A module must never be able
1394                // to make a frame look daemon-authored, so the origin bit a
1395                // module may have set is cleared; every other flag bit and
1396                // the body travel unchanged.
1397                frame.header.flags = frame.header.flags.without_daemon_origin();
1398                if let Err(err) = self
1399                    .counters
1400                    .observe_reader_wait(
1401                        || (route.module_id.clone(), principal_label(&route.principal)),
1402                        "module_to_client",
1403                        route.client_sink.send_to_client(frame),
1404                    )
1405                    .await
1406                {
1407                    if self
1408                        .forwarding
1409                        .escalate_client_delivery_failure_diagnosed(
1410                            route.client_connection_id,
1411                            route.client_channel,
1412                            route.client_epoch,
1413                            CloseReason::new(
1414                                "module_to_client_delivery_failed",
1415                                format!(
1416                                    "failed to enqueue module frame for client channel {} corr {corr}: {err}",
1417                                    route.client_channel
1418                                ),
1419                            ),
1420                            UndeliveredFrame {
1421                                module_id: Some(&route.module_id),
1422                                sink: &route.client_sink,
1423                            },
1424                            Some(&err.diagnosis),
1425                        )
1426                        .map_err(RouterError::Forwarding)?
1427                    {
1428                        self.counters
1429                            .increment_client_egress_close_delivery_failed();
1430                    }
1431                    return Ok(());
1432                }
1433                return Ok(());
1434            }
1435            DataRoute::Client(DataRouteState::EpochMismatch) => {
1436                self.forwarding.warn_frame_drop(
1437                    ctx.connection_id,
1438                    channel,
1439                    epoch,
1440                    "client_to_module",
1441                    "stale_epoch",
1442                );
1443                if frame.header.ty == FrameType::Request {
1444                    self.counters.increment_client_frames_dropped_stale_route();
1445                    // Dropped before forwarding; a re-bind retry cannot double-execute this request.
1446                    let err = RouterError::StaleRouteEpoch {
1447                        channel,
1448                        epoch,
1449                        corr,
1450                    };
1451                    if let Some(error_frame) = err.to_error_frame() {
1452                        self.observe_connection_wait(
1453                            ctx,
1454                            "reply_egress",
1455                            ctx.egress.send(error_frame),
1456                        )
1457                        .await?;
1458                    }
1459                }
1460                debug!(
1461                    connection_id = ctx.connection_id.get(),
1462                    channel, epoch, corr, "dropping client frame for stale route epoch"
1463                );
1464                return Ok(());
1465            }
1466            DataRoute::Client(DataRouteState::Reserved) => {
1467                self.forwarding.warn_frame_drop(
1468                    ctx.connection_id,
1469                    channel,
1470                    epoch,
1471                    "client_to_module",
1472                    "missing_binding",
1473                );
1474                if frame.header.ty == FrameType::Request {
1475                    let err = RouterError::UnknownChannel {
1476                        channel,
1477                        epoch,
1478                        corr,
1479                    };
1480                    if let Some(error_frame) = err.to_error_frame() {
1481                        self.observe_connection_wait(
1482                            ctx,
1483                            "reply_egress",
1484                            ctx.egress.send(error_frame),
1485                        )
1486                        .await?;
1487                    }
1488                }
1489                return Ok(());
1490            }
1491            DataRoute::Client(DataRouteState::Bound(route)) => {
1492                if frame.header.ty == FrameType::Goodbye {
1493                    let _ = self
1494                        .control
1495                        .handle_route_goodbye(ctx.connection_id, channel, epoch)?;
1496                    return Ok(());
1497                }
1498                return self.forward_backend.handle_bound(frame, route).await;
1499            }
1500            DataRoute::Client(DataRouteState::Absent) => {}
1501        }
1502
1503        if let Some(backend) = self.backends.get(&channel) {
1504            return backend.handle(ctx.clone(), frame).await.inspect_err(|_| {
1505                self.forwarding.warn_frame_drop(
1506                    ctx.connection_id,
1507                    channel,
1508                    epoch,
1509                    "client_to_backend",
1510                    "endpoint_gone",
1511                );
1512            });
1513        }
1514        self.forwarding.warn_frame_drop(
1515            ctx.connection_id,
1516            channel,
1517            epoch,
1518            "client_to_module",
1519            "unknown_channel",
1520        );
1521        if frame.header.ty == FrameType::Request {
1522            let err = RouterError::UnknownChannel {
1523                channel,
1524                epoch,
1525                corr,
1526            };
1527            if let Some(error_frame) = err.to_error_frame() {
1528                self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(error_frame))
1529                    .await?;
1530            }
1531        }
1532        Ok(())
1533    }
1534
1535    async fn refuse_oversized_module_frame(
1536        &self,
1537        ctx: &RouteCtx,
1538        route: &RouteBinding,
1539        header: (FrameType, Flags),
1540        corr: u64,
1541        bytes: usize,
1542    ) -> Result<(), RouterError> {
1543        let (ty, flags) = header;
1544        let limit = route.client_sink.accounting.byte_budget;
1545        if ty == FrameType::Push {
1546            // Deployed Rust clients cannot decode a new route.closed reason.
1547            // Until that vocabulary can be extended compatibly, an oversized
1548            // unsolicited push still closes the connection, with its cause named.
1549            let diagnosis = ClientDeliveryDiagnosis {
1550                frame_type: ty,
1551                flags,
1552                cause: "frame_too_large",
1553            };
1554            if self
1555                .forwarding
1556                .escalate_client_delivery_failure_diagnosed(
1557                    route.client_connection_id,
1558                    route.client_channel,
1559                    route.client_epoch,
1560                    CloseReason::new(
1561                        error_codes::FRAME_TOO_LARGE,
1562                        format!(
1563                            "oversized push: size={bytes} limit={limit} (header plus body bytes)"
1564                        ),
1565                    ),
1566                    UndeliveredFrame {
1567                        module_id: Some(&route.module_id),
1568                        sink: &route.client_sink,
1569                    },
1570                    Some(&diagnosis),
1571                )
1572                .map_err(RouterError::Forwarding)?
1573            {
1574                self.counters
1575                    .increment_client_egress_close_delivery_failed();
1576            }
1577            return Ok(());
1578        }
1579
1580        warn!(
1581            connection_id = route.client_connection_id.get(),
1582            module_id = %route.module_id,
1583            client_principal = %principal_label(&route.principal),
1584            client_channel = route.client_channel,
1585            frame_type = ?ty,
1586            frame_bytes = bytes,
1587            byte_limit = limit,
1588            "refusing oversized module-to-client frame with ERROR frame_too_large"
1589        );
1590        if ty == FrameType::Request {
1591            // A reverse request belongs to the module, not to a waiting client.
1592            // Answer its sender without forwarding any part of it to the client.
1593            let error = frame_too_large_error(
1594                route.module_channel,
1595                route.module_epoch,
1596                corr,
1597                bytes,
1598                limit,
1599            )?;
1600            self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(error))
1601                .await?;
1602        } else {
1603            // A refused stream chunk also ends the waiting request. Releasing
1604            // its credit prevents a finished request from keeping a drain alive.
1605            route.flow.release_corr(corr);
1606            let error = frame_too_large_error(
1607                route.client_channel,
1608                route.client_epoch,
1609                corr,
1610                bytes,
1611                limit,
1612            )?;
1613            // The replacement shares the reply's bounded burst grace, so a
1614            // stopped client cannot indefinitely stall the module frame reader.
1615            if let Err(err) = self
1616                .counters
1617                .observe_reader_wait(
1618                    || (route.module_id.clone(), principal_label(&route.principal)),
1619                    "module_to_client",
1620                    route.client_sink.send_to_client(error),
1621                )
1622                .await
1623            {
1624                if self
1625                    .forwarding
1626                    .escalate_client_delivery_failure_diagnosed(
1627                        route.client_connection_id,
1628                        route.client_channel,
1629                        route.client_epoch,
1630                        CloseReason::new(
1631                            "module_to_client_delivery_failed",
1632                            format!(
1633                                "failed to enqueue frame_too_large for client channel {} corr {corr}: {err}",
1634                                route.client_channel
1635                            ),
1636                        ),
1637                        UndeliveredFrame {
1638                            module_id: Some(&route.module_id),
1639                            sink: &route.client_sink,
1640                        },
1641                        Some(&err.diagnosis),
1642                    )
1643                    .map_err(RouterError::Forwarding)?
1644                {
1645                    self.counters
1646                        .increment_client_egress_close_delivery_failed();
1647                }
1648            }
1649        }
1650        Ok(())
1651    }
1652}
1653
1654impl Default for Router {
1655    fn default() -> Self {
1656        Self::with_default_self_handler()
1657    }
1658}
1659
1660/// Connection-scoped cleanup guard returned by [`Router::begin_connection`].
1661#[must_use]
1662pub struct RouterConnection {
1663    id: ConnectionId,
1664    control_handler: Arc<ControlHandler>,
1665    forwarding: Arc<ForwardingTable>,
1666    close_receiver: Option<ConnectionCloseReceiver>,
1667    orphan_goodbyes: Arc<OrphanGoodbyeLimiter>,
1668}
1669
1670impl RouterConnection {
1671    pub fn id(&self) -> ConnectionId {
1672        self.id
1673    }
1674
1675    pub(crate) fn take_close_receiver(&mut self) -> ConnectionCloseReceiver {
1676        self.close_receiver
1677            .take()
1678            .expect("connection close receiver can only be taken once")
1679    }
1680}
1681
1682impl Drop for RouterConnection {
1683    fn drop(&mut self) {
1684        self.orphan_goodbyes.forget_connection(self.id);
1685        // GOODBYE (explicit) and connection-drop cleanup both call the same
1686        // idempotent deregistration path.
1687        let _ = self.control_handler.cleanup_connection(self.id);
1688        // The read loop and its tasks have ended, but the writer can still
1689        // drain. Keep the connection-to-launch association until pending relays
1690        // and routes are gone.
1691        self.forwarding.unregister_connection_close(self.id);
1692    }
1693}
1694
1695/// Minimal in-memory backend used by tests and early wiring: it emits a
1696/// `RESPONSE` on the same channel/correlation id with the exact same body bytes.
1697#[derive(Debug, Default, Clone, Copy)]
1698pub struct EchoBackend;
1699
1700impl EchoBackend {
1701    pub async fn handle(&self, ctx: RouteCtx, frame: Frame) -> Result<(), RouterError> {
1702        let response = Frame::build_with_version(
1703            frame.header.ver,
1704            FrameType::Response,
1705            frame.header.flags,
1706            frame.header.channel,
1707            frame.header.epoch,
1708            frame.header.corr,
1709            frame.body,
1710        )
1711        .map_err(RouterError::FrameBuild)?;
1712        ctx.egress.send(response).await
1713    }
1714}
1715
1716/// Data-plane backend that splices client frames to the module connection bound at attach time.
1717#[derive(Debug, Clone)]
1718pub struct ForwardBackend {
1719    forwarding: Arc<ForwardingTable>,
1720}
1721
1722impl ForwardBackend {
1723    pub fn new(forwarding: Arc<ForwardingTable>) -> Self {
1724        Self { forwarding }
1725    }
1726
1727    pub async fn handle(&self, ctx: RouteCtx, frame: Frame) -> Result<(), RouterError> {
1728        let channel = frame.header.channel;
1729        let corr = frame.header.corr;
1730        let route = match self
1731            .forwarding
1732            .lookup_data_route(ctx.connection_id, channel, frame.header.epoch)
1733            .map_err(RouterError::Forwarding)?
1734        {
1735            DataRoute::Client(DataRouteState::Bound(route)) => route,
1736            DataRoute::Client(_) | DataRoute::Module(_) => {
1737                self.forwarding.warn_frame_drop(
1738                    ctx.connection_id,
1739                    channel,
1740                    frame.header.epoch,
1741                    "client_to_module",
1742                    "missing_binding",
1743                );
1744                return Err(RouterError::UnknownChannel {
1745                    channel,
1746                    epoch: frame.header.epoch,
1747                    corr,
1748                });
1749            }
1750        };
1751        self.handle_bound(frame, route).await
1752    }
1753
1754    pub(crate) async fn handle_bound(
1755        &self,
1756        frame: Frame,
1757        route: Arc<RouteBinding>,
1758    ) -> Result<(), RouterError> {
1759        let channel = frame.header.channel;
1760        let corr = frame.header.corr;
1761        let frame_type = frame.header.ty;
1762
1763        // CANCEL and other non-REQUEST frames bypass the request-credit window;
1764        // the original request's credit is freed only by the module's terminal frame.
1765        let acquired_credit = frame_type == FrameType::Request;
1766        if acquired_credit && route.flow.busy_refusals() {
1767            use crate::forwarding::RequestAdmission;
1768            match self
1769                .forwarding
1770                .try_admit_request(
1771                    &route,
1772                    frame.header.epoch,
1773                    corr,
1774                    frame.header.flags.is_subscription(),
1775                )
1776                .map_err(RouterError::Forwarding)?
1777            {
1778                RequestAdmission::Admitted => {}
1779                RequestAdmission::Busy(detail) => {
1780                    let principal = principal_label(&route.principal);
1781                    let counters = self.forwarding.counters_ref();
1782                    counters.increment_route_busy(&route.module_id, &principal);
1783                    if route.flow.should_warn_busy() {
1784                        warn!(module_id = %route.module_id, client_principal = %principal, client_channel = channel,
1785                            route_epoch = route.client_epoch, ?detail, "request refused: route_busy");
1786                    }
1787                    let error = RouterError::RouteBusy {
1788                        channel,
1789                        epoch: frame.header.epoch,
1790                        corr,
1791                        detail: Box::new(detail),
1792                    };
1793                    let refusal = error
1794                        .to_error_frame()
1795                        .expect("route_busy is a serializable wire error");
1796                    counters
1797                        .observe_reader_wait(
1798                            || (route.module_id.clone(), principal),
1799                            "route_busy_egress",
1800                            route.client_sink.send(refusal),
1801                        )
1802                        .await?;
1803                    return Ok(());
1804                }
1805                RequestAdmission::ModuleReloading => {
1806                    return Err(RouterError::route_error_with_epoch(
1807                        channel,
1808                        frame.header.epoch,
1809                        corr,
1810                        error_codes::MODULE_RELOADING,
1811                        format!("module endpoint for route channel {channel} is reloading"),
1812                    ));
1813                }
1814                RequestAdmission::Stale => {
1815                    return Err(RouterError::StaleRouteEpoch {
1816                        channel,
1817                        epoch: frame.header.epoch,
1818                        corr,
1819                    })
1820                }
1821            }
1822        } else if acquired_credit {
1823            let counters = self.forwarding.counters_ref();
1824            if let Err(err) = counters
1825                .observe_reader_wait(
1826                    || (route.module_id.clone(), principal_label(&route.principal)),
1827                    "legacy_credit",
1828                    route
1829                        .flow
1830                        .acquire_tagged(corr, frame.header.flags.is_subscription()),
1831                )
1832                .await
1833            {
1834                self.forwarding.warn_frame_drop(
1835                    route.client_connection_id,
1836                    channel,
1837                    frame.header.epoch,
1838                    "client_to_module",
1839                    "endpoint_gone",
1840                );
1841                // `module_reloading` here is answered BEFORE the frame is
1842                // forwarded, so the module never sees the request and callers
1843                // may re-dispatch it after reopening the route. That is a wire
1844                // guarantee documented on `error_codes::MODULE_RELOADING`; do
1845                // not emit this code for a request that already reached
1846                // `module_sink.send` below.
1847                if self
1848                    .forwarding
1849                    .endpoint_is_draining(route.module_endpoint)
1850                    .map_err(RouterError::Forwarding)?
1851                {
1852                    return Err(RouterError::route_error_with_epoch(
1853                        channel,
1854                        frame.header.epoch,
1855                        corr,
1856                        "module_reloading",
1857                        format!("module endpoint for route channel {channel} is reloading"),
1858                    ));
1859                }
1860                return Err(RouterError::backend_with_epoch(
1861                    channel,
1862                    frame.header.epoch,
1863                    corr,
1864                    format!("{err} for route channel {channel}"),
1865                ));
1866            }
1867        }
1868
1869        let mut frame = frame;
1870        frame.header.channel = route.module_channel;
1871        frame.header.epoch = route.module_epoch;
1872        // The origin bit is the daemon's own signal to clients. A client
1873        // frame carrying it must not reach a module appearing daemon-authored,
1874        // so it is cleared here; every other flag bit travels unchanged.
1875        frame.header.flags = frame.header.flags.without_daemon_origin();
1876        let counters = self.forwarding.counters_ref();
1877        let result = counters
1878            .observe_reader_wait(
1879                || (route.module_id.clone(), principal_label(&route.principal)),
1880                "module_queue",
1881                route.module_sink.send(frame),
1882            )
1883            .await
1884            .map_err(|err| {
1885                self.forwarding.warn_frame_drop(
1886                    route.client_connection_id,
1887                    channel,
1888                    route.client_epoch,
1889                    "client_to_module",
1890                    "endpoint_gone",
1891                );
1892                RouterError::backend_with_epoch(channel, route.client_epoch, corr, err.to_string())
1893            });
1894        if acquired_credit && result.is_err() {
1895            route.flow.release_corr(corr);
1896        }
1897        result
1898    }
1899}
1900
1901fn is_terminal_frame(frame_type: FrameType) -> bool {
1902    matches!(
1903        frame_type,
1904        FrameType::Response | FrameType::Error | FrameType::StreamEnd
1905    )
1906}
1907
1908/// Typed router errors. Routable failures can be translated to canonical JSON
1909/// `ERROR` frames with [`RouterError::to_error_frame`].
1910#[derive(Debug, Clone, PartialEq, Eq)]
1911pub enum RouterError {
1912    ReservedChannelZero,
1913    DuplicateChannel {
1914        channel: u16,
1915    },
1916    UnknownChannel {
1917        channel: u16,
1918        epoch: u32,
1919        corr: u64,
1920    },
1921    StaleRouteEpoch {
1922        channel: u16,
1923        epoch: u32,
1924        corr: u64,
1925    },
1926    RouteBusy {
1927        channel: u16,
1928        epoch: u32,
1929        corr: u64,
1930        detail: Box<subc_protocol::RouteBusyDetail>,
1931    },
1932    Backend {
1933        channel: u16,
1934        epoch: u32,
1935        corr: u64,
1936        message: String,
1937    },
1938    RouteError {
1939        channel: u16,
1940        epoch: u32,
1941        corr: u64,
1942        code: String,
1943        message: String,
1944    },
1945    FrameBuild(FrameBuildError),
1946    Forwarding(ForwardingError),
1947}
1948
1949impl RouterError {
1950    pub fn backend(channel: u16, corr: u64, message: impl Into<String>) -> Self {
1951        Self::backend_with_epoch(channel, 0, corr, message)
1952    }
1953
1954    pub fn backend_with_epoch(
1955        channel: u16,
1956        epoch: u32,
1957        corr: u64,
1958        message: impl Into<String>,
1959    ) -> Self {
1960        Self::Backend {
1961            channel,
1962            epoch,
1963            corr,
1964            message: message.into(),
1965        }
1966    }
1967
1968    pub fn route_error(
1969        channel: u16,
1970        corr: u64,
1971        code: impl Into<String>,
1972        message: impl Into<String>,
1973    ) -> Self {
1974        Self::route_error_with_epoch(channel, 0, corr, code, message)
1975    }
1976
1977    pub fn route_error_with_epoch(
1978        channel: u16,
1979        epoch: u32,
1980        corr: u64,
1981        code: impl Into<String>,
1982        message: impl Into<String>,
1983    ) -> Self {
1984        Self::RouteError {
1985            channel,
1986            epoch,
1987            corr,
1988            code: code.into(),
1989            message: message.into(),
1990        }
1991    }
1992
1993    /// Translate route failures that belong on the wire into an `ERROR` frame.
1994    pub fn to_error_frame(&self) -> Option<Frame> {
1995        match self {
1996            Self::RouteBusy {
1997                channel,
1998                epoch,
1999                corr,
2000                detail,
2001            } => {
2002                let body = serde_json::to_vec(&ErrorBody {
2003                    code: error_codes::ROUTE_BUSY.into(),
2004                    message: "route has no free request or watch credit; retry on the same route"
2005                        .into(),
2006                    detail: Some(serde_json::to_value(detail).ok()?),
2007                })
2008                .ok()?;
2009                Frame::build(
2010                    FrameType::Error,
2011                    daemon_error_flags(),
2012                    *channel,
2013                    *epoch,
2014                    *corr,
2015                    body,
2016                )
2017                .ok()
2018            }
2019            Self::UnknownChannel {
2020                channel,
2021                epoch,
2022                corr,
2023            } => error_frame(
2024                *channel,
2025                *epoch,
2026                *corr,
2027                error_codes::UNKNOWN_CHANNEL,
2028                format!("unknown channel {channel}"),
2029            ),
2030            Self::StaleRouteEpoch {
2031                channel,
2032                epoch,
2033                corr,
2034            } => error_frame(
2035                *channel,
2036                *epoch,
2037                *corr,
2038                error_codes::STALE_ROUTE_EPOCH,
2039                format!("stale route epoch for channel {channel}"),
2040            ),
2041            Self::Backend {
2042                channel,
2043                epoch,
2044                corr,
2045                message,
2046            } => error_frame(*channel, *epoch, *corr, "backend_error", message.clone()),
2047            Self::RouteError {
2048                channel,
2049                epoch,
2050                corr,
2051                code,
2052                message,
2053            } => error_frame(*channel, *epoch, *corr, code, message.clone()),
2054            Self::ReservedChannelZero
2055            | Self::DuplicateChannel { .. }
2056            | Self::FrameBuild(_)
2057            | Self::Forwarding(_) => None,
2058        }
2059    }
2060}
2061
2062/// Flags for an ERROR frame the daemon authors itself.
2063///
2064/// Bit 6 (`FLAG_DAEMON_ORIGIN`) tells the client the daemon wrote this
2065/// error, never a module. What a code then proves is per code: on a bound
2066/// route the daemon writes `module_reloading`, `unknown_channel` and
2067/// `stale_route_epoch` only before forwarding, so with the bit they mean the
2068/// request was not delivered, while `frame_too_large` replaces a reply the
2069/// module already produced. Every daemon-authored ERROR goes through here;
2070/// frames a module sent keep their own flags with the bit cleared at the
2071/// splice.
2072/// Nothing else about the flags differs: passive priority, not binary, not last.
2073pub(crate) fn daemon_error_flags() -> Flags {
2074    Flags::new(false, Priority::Passive, false).with_daemon_origin()
2075}
2076
2077fn error_frame(channel: u16, epoch: u32, corr: u64, code: &str, message: String) -> Option<Frame> {
2078    let body = serde_json::to_vec(&ErrorBody {
2079        code: code.to_string(),
2080        message,
2081        detail: None,
2082    })
2083    .ok()?;
2084
2085    Frame::build(
2086        FrameType::Error,
2087        daemon_error_flags(),
2088        channel,
2089        epoch,
2090        corr,
2091        body,
2092    )
2093    .ok()
2094}
2095
2096fn frame_too_large_error(
2097    channel: u16,
2098    epoch: u32,
2099    corr: u64,
2100    bytes: usize,
2101    limit: usize,
2102) -> Result<Frame, RouterError> {
2103    let body = serde_json::to_vec(&ErrorBody {
2104        code: error_codes::FRAME_TOO_LARGE.to_string(),
2105        message: format!(
2106            "module frame of {bytes} bytes exceeds client egress limit of {limit} bytes"
2107        ),
2108        detail: Some(serde_json::json!({ "frame_bytes": bytes, "byte_limit": limit })),
2109    })
2110    .expect("serializing a frame size error");
2111    Frame::build(
2112        FrameType::Error,
2113        daemon_error_flags(),
2114        channel,
2115        epoch,
2116        corr,
2117        body,
2118    )
2119    .map_err(RouterError::FrameBuild)
2120}
2121
2122impl fmt::Display for RouterError {
2123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2124        match self {
2125            Self::ReservedChannelZero => write!(f, "channel 0 is reserved for subc"),
2126            Self::DuplicateChannel { channel } => {
2127                write!(f, "backend already registered for channel {channel}")
2128            }
2129            Self::UnknownChannel { channel, corr, .. } => {
2130                write!(f, "unknown channel {channel} for corr {corr}")
2131            }
2132            Self::StaleRouteEpoch { channel, corr, .. } => {
2133                write!(f, "stale route epoch for channel {channel} corr {corr}")
2134            }
2135            Self::RouteBusy { channel, corr, .. } => {
2136                write!(f, "route busy on channel {channel} corr {corr}")
2137            }
2138            Self::Backend {
2139                channel,
2140                corr,
2141                message,
2142                ..
2143            } => write!(
2144                f,
2145                "backend error on channel {channel} corr {corr}: {message}"
2146            ),
2147            Self::RouteError {
2148                channel,
2149                corr,
2150                code,
2151                message,
2152                ..
2153            } => write!(
2154                f,
2155                "route error {code} on channel {channel} corr {corr}: {message}"
2156            ),
2157            Self::FrameBuild(err) => write!(f, "failed to build routed frame: {err}"),
2158            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
2159        }
2160    }
2161}
2162
2163impl Error for RouterError {
2164    fn source(&self) -> Option<&(dyn Error + 'static)> {
2165        match self {
2166            Self::FrameBuild(err) => Some(err),
2167            Self::Forwarding(err) => Some(err),
2168            Self::ReservedChannelZero
2169            | Self::DuplicateChannel { .. }
2170            | Self::UnknownChannel { .. }
2171            | Self::StaleRouteEpoch { .. }
2172            | Self::RouteBusy { .. }
2173            | Self::Backend { .. }
2174            | Self::RouteError { .. } => None,
2175        }
2176    }
2177}
2178
2179#[cfg(test)]
2180mod tests {
2181    include!("route_busy_router_tests.rs");
2182    use super::*;
2183    use crate::{
2184        forwarding::RouteBindRelayOutcome,
2185        supervise::{ModuleSpec, RestartPolicy, Supervisor, SupervisorHandle},
2186        ControlHandler, Registry,
2187    };
2188    use std::{
2189        sync::{mpsc as std_mpsc, Arc},
2190        time::Duration,
2191    };
2192    use subc_control::ModuleProtocol;
2193    use subc_protocol::{manifest::Concurrency, ErrorBody, Flags, FrameType, Priority};
2194    use tokio::sync::mpsc;
2195
2196    pub(crate) use crate::router::test_log::{captured_logs, log_capture};
2197
2198    fn logged_millis(logs: &str, field: &str) -> u64 {
2199        logs.split_whitespace()
2200            .find_map(|part| part.strip_prefix(field))
2201            .and_then(|value| value.parse().ok())
2202            .unwrap_or_else(|| panic!("missing numeric {field} in logs: {logs}"))
2203    }
2204
2205    fn request(channel: u16, corr: u64, body: &[u8]) -> Frame {
2206        Frame::build(
2207            FrameType::Request,
2208            Flags::new(true, Priority::Interactive, false),
2209            channel,
2210            0,
2211            corr,
2212            body.to_vec(),
2213        )
2214        .unwrap()
2215    }
2216
2217    fn ping(corr: u64) -> Frame {
2218        Frame::build(
2219            FrameType::Ping,
2220            Flags::new(false, Priority::Passive, false),
2221            0,
2222            0,
2223            corr,
2224            Vec::new(),
2225        )
2226        .unwrap()
2227    }
2228
2229    fn route_ctx() -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
2230        let (tx, rx) = mpsc::channel(8);
2231        (
2232            RouteCtx {
2233                connection_id: ConnectionId::LOCAL,
2234                egress: FrameSink::new(tx),
2235            },
2236            rx,
2237        )
2238    }
2239
2240    #[tokio::test]
2241    async fn retirement_egress_all_send_paths_drop_after_fence() {
2242        let (tx, mut rx) = mpsc::channel(8);
2243        let sink = FrameSink::new(tx);
2244        let reserved = sink.reserve_owned().await.unwrap();
2245        let immediate = sink.try_reserve_owned().unwrap();
2246        sink.terminate_egress();
2247        assert!(reserved.send(ping(1)));
2248        assert!(immediate.send(ping(2)));
2249        sink.send(ping(3)).await.unwrap();
2250        sink.try_send(ping(4)).unwrap();
2251        sink.send_to_client(ping(5)).await.unwrap();
2252        let queued = AtomicBool::new(false);
2253        assert!(sink
2254            .send_flushed_notifying_enqueue(ping(6), || queued.store(true, Ordering::Relaxed))
2255            .await
2256            .is_err());
2257        assert!(!queued.load(Ordering::Relaxed));
2258        assert!(sink.send_flushed(ping(7)).await.is_err());
2259        assert!(sink.reserve_owned().await.is_err());
2260        assert!(sink.try_reserve_owned().is_err());
2261        assert!(
2262            rx.try_recv().is_err(),
2263            "retired frames must not enter any writer queue"
2264        );
2265        assert_eq!(sink.backlog().queued_frames, 0);
2266        assert_eq!(sink.backlog().queued_bytes, 0);
2267    }
2268
2269    #[tokio::test]
2270    async fn retirement_egress_reservation_rechecks_after_slot_acquisition() {
2271        let (tx, mut rx) = mpsc::channel(1);
2272        let sink = FrameSink::new(tx);
2273        // Choose retirement after reserve returns its slot, not while waiting
2274        // on egress_stopped, so the final atomic recheck is exercised.
2275        sink.accounting
2276            .retire_after_reserve
2277            .store(true, Ordering::Relaxed);
2278        assert!(
2279            sink.reserve_owned().await.is_err(),
2280            "a slot acquired before retirement must not escape as a live reservation"
2281        );
2282        assert_eq!(
2283            sink.tx.capacity(),
2284            1,
2285            "refusal must release the reserved slot"
2286        );
2287        assert!(rx.try_recv().is_err());
2288    }
2289
2290    #[tokio::test]
2291    async fn retirement_egress_pending_budget_and_slot_sends_stop() {
2292        for budget in [1, usize::MAX] {
2293            let (tx, mut rx) = mpsc::channel(1);
2294            let sink = FrameSink::with_byte_budget(tx, budget);
2295            sink.try_send(ping(1)).unwrap();
2296            let sending = sink.send(ping(2));
2297            tokio::pin!(sending);
2298            assert!(poll_once(sending.as_mut()).await.is_pending());
2299            sink.terminate_egress();
2300            tokio::time::timeout(Duration::from_secs(2), sending)
2301                .await
2302                .unwrap()
2303                .unwrap();
2304            drop(rx.try_recv().unwrap());
2305            assert!(
2306                rx.try_recv().is_err(),
2307                "a send parked before retirement must not enqueue afterward"
2308            );
2309            assert_eq!(sink.backlog().queued_bytes, 0);
2310        }
2311    }
2312
2313    #[tokio::test]
2314    async fn retirement_egress_pending_flush_and_reservation_stop() {
2315        let (tx, mut rx) = mpsc::channel(1);
2316        let sink = FrameSink::new(tx);
2317        sink.try_send(ping(1)).unwrap();
2318        let queued = AtomicBool::new(false);
2319        let sending =
2320            sink.send_flushed_notifying_enqueue(ping(2), || queued.store(true, Ordering::Relaxed));
2321        let reserving = sink.reserve_owned();
2322        tokio::pin!(sending, reserving);
2323        assert!(poll_once(sending.as_mut()).await.is_pending());
2324        assert!(poll_once(reserving.as_mut()).await.is_pending());
2325        sink.terminate_egress();
2326        assert!(tokio::time::timeout(Duration::from_secs(2), sending)
2327            .await
2328            .unwrap()
2329            .is_err());
2330        assert!(tokio::time::timeout(Duration::from_secs(2), reserving)
2331            .await
2332            .unwrap()
2333            .is_err());
2334        assert!(!queued.load(Ordering::Relaxed));
2335        drop(rx.try_recv().unwrap());
2336        assert!(rx.try_recv().is_err());
2337        assert_eq!(sink.backlog().queued_bytes, 0);
2338    }
2339
2340    #[tokio::test]
2341    async fn echo_backend_returns_response_with_byte_identical_body() {
2342        let mut router = Router::with_default_self_handler();
2343        router.register_backend(7, EchoBackend).unwrap();
2344        let (ctx, mut rx) = route_ctx();
2345        let body = b"{not parsed}\0\xff";
2346
2347        router
2348            .route_for_connection(&ctx, request(7, 123, body))
2349            .await
2350            .unwrap();
2351        let response = rx.recv().await.unwrap();
2352
2353        assert_eq!(response.header.ty, FrameType::Response);
2354        assert_eq!(response.header.channel, 7);
2355        assert_eq!(response.header.corr, 123);
2356        assert_eq!(response.body, body);
2357        assert!(rx.try_recv().is_err());
2358    }
2359
2360    #[tokio::test]
2361    async fn unknown_channel_emits_canonical_error_frame() {
2362        let router = Router::with_default_self_handler();
2363        let (ctx, mut rx) = route_ctx();
2364
2365        router
2366            .route_for_connection(&ctx, request(99, 5, b"payload"))
2367            .await
2368            .unwrap();
2369        let error_frame = rx.recv().await.unwrap();
2370
2371        assert_eq!(error_frame.header.ty, FrameType::Error);
2372        assert_eq!(error_frame.header.channel, 99);
2373        assert_eq!(error_frame.header.corr, 5);
2374        let body: ErrorBody = serde_json::from_slice(&error_frame.body).unwrap();
2375        assert_eq!(body.code, "unknown_channel");
2376        assert_eq!(body.message, "unknown channel 99");
2377    }
2378
2379    /// Every ERROR the daemon authors carries the daemon-origin bit, so a
2380    /// client can tell a daemon refusal from a module's reply. Both the
2381    /// unknown-channel and the stale-epoch errors below are received on the
2382    /// client's own egress, not merely built.
2383    #[tokio::test]
2384    async fn daemon_authored_data_plane_errors_carry_daemon_origin() {
2385        let router = Router::with_default_self_handler();
2386        let (ctx, mut rx) = route_ctx();
2387        router
2388            .route_for_connection(&ctx, request(99, 5, b"payload"))
2389            .await
2390            .unwrap();
2391        let unknown = rx.recv().await.unwrap();
2392        assert_eq!(unknown.header.ty, FrameType::Error);
2393        let body: ErrorBody = serde_json::from_slice(&unknown.body).unwrap();
2394        assert_eq!(body.code, "unknown_channel");
2395        assert!(
2396            unknown.header.flags.is_daemon_origin(),
2397            "unknown_channel must carry daemon origin: {:?}",
2398            unknown.header.flags
2399        );
2400
2401        let (
2402            router,
2403            _forwarding,
2404            client_ctx,
2405            mut client_rx,
2406            _module_ctx,
2407            _module_egress_rx,
2408            _module_rx,
2409            pending,
2410        ) = dynamic_route_fixture(true);
2411        let _ = client_rx.recv().await;
2412        router
2413            .route_for_connection(
2414                &client_ctx,
2415                route_frame(
2416                    FrameType::Request,
2417                    pending.client_channel,
2418                    pending.client_epoch + 1,
2419                    702,
2420                ),
2421            )
2422            .await
2423            .unwrap();
2424        let stale = client_rx.recv().await.unwrap();
2425        assert_eq!(stale.header.ty, FrameType::Error);
2426        let body: ErrorBody = serde_json::from_slice(&stale.body).unwrap();
2427        assert_eq!(body.code, "stale_route_epoch");
2428        assert!(
2429            stale.header.flags.is_daemon_origin(),
2430            "stale_route_epoch must carry daemon origin: {:?}",
2431            stale.header.flags
2432        );
2433    }
2434
2435    /// A module ERROR that spoofs a daemon code with the daemon-origin bit
2436    /// set must reach the client with the bit cleared and the body
2437    /// byte-identical: the bit means the daemon wrote the frame, and a module
2438    /// must never be able to claim that.
2439    #[tokio::test]
2440    async fn module_error_with_daemon_bit_is_stripped_before_client_delivery() {
2441        let (
2442            router,
2443            _forwarding,
2444            client_ctx,
2445            mut client_rx,
2446            module_ctx,
2447            _module_egress_rx,
2448            mut module_rx,
2449            pending,
2450        ) = dynamic_route_fixture(true);
2451        let _ = client_rx.recv().await;
2452        // Open flow credit the way a real request would, so the terminal
2453        // error exercises the credit-release path too.
2454        router
2455            .route_for_connection(
2456                &client_ctx,
2457                route_frame(
2458                    FrameType::Request,
2459                    pending.client_channel,
2460                    pending.client_epoch,
2461                    701,
2462                ),
2463            )
2464            .await
2465            .unwrap();
2466        let _ = module_rx.recv().await;
2467
2468        let body = serde_json::to_vec(&ErrorBody::new("module_reloading", "try again")).unwrap();
2469        let spoof = Frame::build(
2470            FrameType::Error,
2471            Flags::new(false, Priority::Interactive, false).with_daemon_origin(),
2472            pending.module_channel,
2473            pending.module_epoch,
2474            701,
2475            body.clone(),
2476        )
2477        .unwrap();
2478        router
2479            .route_for_connection(&module_ctx, spoof)
2480            .await
2481            .unwrap();
2482        let delivered = client_rx.recv().await.unwrap();
2483        assert_eq!(delivered.header.ty, FrameType::Error);
2484        assert_eq!(delivered.header.channel, pending.client_channel);
2485        assert_eq!(delivered.header.epoch, pending.client_epoch);
2486        assert_eq!(delivered.header.corr, 701);
2487        assert!(
2488            !delivered.header.flags.is_daemon_origin(),
2489            "module-set daemon origin must be cleared: {:?}",
2490            delivered.header.flags
2491        );
2492        assert_eq!(delivered.body, body, "the body travels byte-identical");
2493    }
2494
2495    /// Clearing the origin bit strips exactly that bit: priority, LAST and
2496    /// subscription survive the splice unchanged.
2497    #[tokio::test]
2498    async fn module_response_with_daemon_bit_is_stripped_preserving_other_flags() {
2499        use subc_protocol::FLAG_SUBSCRIPTION;
2500        let (
2501            router,
2502            _forwarding,
2503            client_ctx,
2504            mut client_rx,
2505            module_ctx,
2506            _module_egress_rx,
2507            mut module_rx,
2508            pending,
2509        ) = dynamic_route_fixture(true);
2510        let _ = client_rx.recv().await;
2511        router
2512            .route_for_connection(
2513                &client_ctx,
2514                route_frame(
2515                    FrameType::Request,
2516                    pending.client_channel,
2517                    pending.client_epoch,
2518                    701,
2519                ),
2520            )
2521            .await
2522            .unwrap();
2523        let _ = module_rx.recv().await;
2524
2525        let sent_flags = Flags(
2526            Flags::new(true, Priority::Background, true).0
2527                | FLAG_SUBSCRIPTION
2528                | subc_protocol::FLAG_DAEMON_ORIGIN,
2529        );
2530        assert!(sent_flags.is_daemon_origin());
2531        let response = Frame::build(
2532            FrameType::Response,
2533            sent_flags,
2534            pending.module_channel,
2535            pending.module_epoch,
2536            701,
2537            b"route-body".to_vec(),
2538        )
2539        .unwrap();
2540        router
2541            .route_for_connection(&module_ctx, response)
2542            .await
2543            .unwrap();
2544        let delivered = client_rx.recv().await.unwrap();
2545        assert_eq!(delivered.header.ty, FrameType::Response);
2546        assert!(
2547            !delivered.header.flags.is_daemon_origin(),
2548            "module-set daemon origin must be cleared: {:?}",
2549            delivered.header.flags
2550        );
2551        assert!(
2552            delivered.header.flags.is_binary(),
2553            "binary flag must survive: {:?}",
2554            delivered.header.flags
2555        );
2556        assert!(
2557            delivered.header.flags.is_last(),
2558            "LAST flag must survive: {:?}",
2559            delivered.header.flags
2560        );
2561        assert!(
2562            delivered.header.flags.is_subscription(),
2563            "subscription flag must survive: {:?}",
2564            delivered.header.flags
2565        );
2566        assert_eq!(
2567            delivered.header.flags.priority(),
2568            Some(Priority::Background),
2569            "priority must survive"
2570        );
2571    }
2572
2573    /// A client frame carrying the origin bit must not reach the module
2574    /// looking daemon-authored either: the splice clears it symmetrically.
2575    #[tokio::test]
2576    async fn client_frame_with_daemon_bit_is_stripped_before_module_delivery() {
2577        let (
2578            router,
2579            _forwarding,
2580            client_ctx,
2581            mut client_rx,
2582            _module_ctx,
2583            _module_egress_rx,
2584            mut module_rx,
2585            pending,
2586        ) = dynamic_route_fixture(true);
2587        let _ = client_rx.recv().await;
2588        let spoof = Frame::build(
2589            FrameType::Request,
2590            Flags::new(false, Priority::Interactive, false).with_daemon_origin(),
2591            pending.client_channel,
2592            pending.client_epoch,
2593            701,
2594            b"route-body".to_vec(),
2595        )
2596        .unwrap();
2597        router
2598            .route_for_connection(&client_ctx, spoof)
2599            .await
2600            .unwrap();
2601        let delivered = module_rx.recv().await.unwrap();
2602        assert_eq!(delivered.header.ty, FrameType::Request);
2603        assert!(
2604            !delivered.header.flags.is_daemon_origin(),
2605            "client-set daemon origin must be cleared: {:?}",
2606            delivered.header.flags
2607        );
2608    }
2609
2610    #[tokio::test]
2611    async fn channel_zero_uses_control_handler_not_backend_registry() {
2612        let mut router = Router::with_default_self_handler();
2613        router.register_backend(1, EchoBackend).unwrap();
2614        let (ctx, mut rx) = route_ctx();
2615
2616        router.route_for_connection(&ctx, ping(77)).await.unwrap();
2617        let response = rx.recv().await.unwrap();
2618
2619        assert_eq!(response.header.ty, FrameType::Pong);
2620        assert_eq!(response.header.channel, 0);
2621        assert_eq!(response.header.corr, 77);
2622        assert!(response.body.is_empty());
2623    }
2624
2625    #[tokio::test]
2626    async fn slow_control_dispatch_logs_decoded_op_and_elapsed_time() {
2627        let control = Arc::new(
2628            ControlHandler::new(Arc::new(Registry::default()))
2629                .with_control_dispatch_delay(Duration::from_millis(1050)),
2630        );
2631        let router = Router::with_control_handler(control);
2632        let (ctx, mut rx) = route_ctx();
2633        let (output, guard) = log_capture(tracing::Level::WARN);
2634
2635        router
2636            .route_for_connection(&ctx, request(0, 41, br#"{"op":"server.describe"}"#))
2637            .await
2638            .expect("slow request routes");
2639        assert!(rx.recv().await.is_some(), "request receives a response");
2640        drop(guard);
2641
2642        let logs = captured_logs(&output);
2643        assert!(logs.contains("slow control dispatch"));
2644        assert!(logs.contains("op=server.describe"));
2645        assert!(logs.contains("connection_id=0"));
2646        assert!(logs.contains("corr=41"));
2647        assert!(
2648            logged_millis(&logs, "elapsed_ms=") >= 1050,
2649            "elapsed must include the injected handler delay: {logs}"
2650        );
2651    }
2652
2653    #[tokio::test]
2654    async fn fast_control_dispatch_emits_arrival_without_slow_warning() {
2655        let router = Router::with_default_self_handler();
2656        let (ctx, mut rx) = route_ctx();
2657        let (output, guard) = log_capture(tracing::Level::DEBUG);
2658
2659        router
2660            .route_for_connection(&ctx, request(0, 42, br#"{"op":"server.describe"}"#))
2661            .await
2662            .expect("fast request routes");
2663        assert!(rx.recv().await.is_some(), "request receives a response");
2664        drop(guard);
2665
2666        let logs = captured_logs(&output);
2667        assert!(logs.contains("control dispatch op=server.describe connection_id=0 corr=42"));
2668        assert!(!logs.contains("slow control dispatch"));
2669    }
2670
2671    #[tokio::test]
2672    async fn control_dispatch_arrival_is_hidden_at_info() {
2673        let router = Router::with_default_self_handler();
2674        let (ctx, mut rx) = route_ctx();
2675        let (output, guard) = log_capture(tracing::Level::INFO);
2676
2677        router
2678            .route_for_connection(&ctx, request(0, 43, br#"{"op":"server.describe"}"#))
2679            .await
2680            .expect("fast request routes");
2681        assert!(rx.recv().await.is_some(), "request receives a response");
2682        drop(guard);
2683
2684        assert!(
2685            !captured_logs(&output).contains("control dispatch"),
2686            "arrival logging must stay hidden at INFO"
2687        );
2688    }
2689
2690    #[tokio::test]
2691    async fn supervisor_list_logs_contended_snapshot_lock_only() {
2692        let registry = Arc::new(Registry::default());
2693        let handle = SupervisorHandle::new();
2694        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
2695            .with_handle(handle.clone());
2696        let module = supervisor
2697            .supervise_configured(
2698                ModuleSpec {
2699                    script: None,
2700                    carry_containment: false,
2701                    module_id: "held-module".to_string(),
2702                    program: "test-module".into(),
2703                    args: Vec::new(),
2704                    env: Vec::new(),
2705                    reserved: false,
2706                    reserved_prefixes: Vec::new(),
2707                    protocol: ModuleProtocol::Subc,
2708                    overlap: Default::default(),
2709                },
2710                false,
2711            )
2712            .expect("disabled test module is supervised");
2713        let router = Router::with_control_handler(Arc::new(
2714            ControlHandler::new(Arc::clone(&registry)).with_supervisor(handle),
2715        ));
2716        let (ctx, mut rx) = route_ctx();
2717        let (acquired, ready) = std_mpsc::channel();
2718        // Park the disabled supervisor actor before holding its snapshot. The
2719        // detached list reader, not actor startup, must be the lock contender.
2720        tokio::task::yield_now().await;
2721        let holder = module.hold_snapshot_for_test(acquired, Duration::from_millis(400));
2722        ready.recv().expect("holder acquired snapshot lock");
2723        let (output, guard) = log_capture(tracing::Level::WARN);
2724
2725        router
2726            .route_for_connection(&ctx, request(0, 44, br#"{"op":"supervisor.list"}"#))
2727            .await
2728            .expect("list request routes after the lock releases");
2729        assert!(
2730            rx.recv().await.is_some(),
2731            "list request receives a response"
2732        );
2733        holder.join().expect("snapshot holder exits cleanly");
2734        drop(guard);
2735
2736        let logs = captured_logs(&output);
2737        assert!(logs.contains("slow snapshot lock"));
2738        assert!(logs.contains("module_id=held-module"));
2739        assert!(logs.contains("caller=list"));
2740        assert!(
2741            logged_millis(&logs, "waited_ms=") >= 250,
2742            "wait must exceed the slow-lock threshold: {logs}"
2743        );
2744
2745        let (output, guard) = log_capture(tracing::Level::WARN);
2746        router
2747            .route_for_connection(&ctx, request(0, 45, br#"{"op":"supervisor.list"}"#))
2748            .await
2749            .expect("uncontended list request routes");
2750        assert!(
2751            rx.recv().await.is_some(),
2752            "uncontended list receives a response"
2753        );
2754        drop(guard);
2755        assert!(
2756            !captured_logs(&output).contains("slow snapshot lock"),
2757            "uncontended list acquisition must not warn"
2758        );
2759    }
2760
2761    #[tokio::test]
2762    async fn full_module_to_client_sink_requests_client_close_without_erroring_module() {
2763        let forwarding = Arc::new(ForwardingTable::default());
2764        let control = Arc::new(ControlHandler::with_forwarding(
2765            Arc::new(crate::Registry::default()),
2766            Arc::clone(&forwarding),
2767        ));
2768        let router = Router::with_control_handler(control);
2769        let module_connection = ConnectionId::new(10);
2770        let client_connection = ConnectionId::new(20);
2771        let mut close_receiver = forwarding.register_connection_close(client_connection);
2772        let (module_tx, _module_rx) = mpsc::channel(1);
2773        forwarding
2774            .register_module_connection(
2775                module_connection,
2776                "full-sink-provider".to_string(),
2777                1,
2778                Concurrency::ModuleManaged,
2779                FrameSink::new(module_tx),
2780            )
2781            .unwrap();
2782        let (client_tx, mut client_rx) = mpsc::channel(1);
2783        let pending = forwarding
2784            .begin_route_bind_relay_for_test(
2785                client_connection,
2786                FrameSink::new(client_tx),
2787                700,
2788                "full-sink-provider",
2789            )
2790            .unwrap();
2791        forwarding
2792            .complete_pending_relay(
2793                module_connection,
2794                pending.corr,
2795                RouteBindRelayOutcome::Accepted,
2796            )
2797            .unwrap();
2798
2799        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
2800        let module_ctx = RouteCtx {
2801            connection_id: module_connection,
2802            egress: FrameSink::new(module_egress_tx),
2803        };
2804        let terminal = Frame::build(
2805            FrameType::Response,
2806            Flags::new(false, Priority::Interactive, true),
2807            pending.module_channel,
2808            pending.module_epoch,
2809            701,
2810            b"terminal".to_vec(),
2811        )
2812        .unwrap();
2813
2814        router
2815            .route_for_connection(&module_ctx, terminal)
2816            .await
2817            .unwrap();
2818        let reason = tokio::time::timeout(Duration::from_secs(1), &mut close_receiver)
2819            .await
2820            .expect("close request should be sent for the full client sink")
2821            .expect("close sender should include a reason");
2822        assert!(
2823            reason
2824                .to_string()
2825                .contains("module_to_client_delivery_failed"),
2826            "unexpected close reason: {reason}"
2827        );
2828        assert_eq!(client_rx.try_recv().unwrap().header.corr, 700);
2829        assert!(client_rx.try_recv().is_err());
2830        assert_eq!(
2831            router.counters.snapshot()["client_egress_close_delivery_failed"],
2832            1
2833        );
2834    }
2835
2836    /// A terminal frame ends the request at the module even when the client
2837    /// cannot take it, so the drain must stop counting it at once rather than
2838    /// when the client connection's cleanup later removes the route.
2839    #[tokio::test]
2840    async fn terminal_frame_releases_its_credit_even_when_client_delivery_fails() {
2841        let forwarding = Arc::new(ForwardingTable::default());
2842        let control = Arc::new(ControlHandler::with_forwarding(
2843            Arc::new(crate::Registry::default()),
2844            Arc::clone(&forwarding),
2845        ));
2846        let router = Router::with_control_handler(control);
2847        let module_connection = ConnectionId::new(11);
2848        let client_connection = ConnectionId::new(21);
2849        let _close_receiver = forwarding.register_connection_close(client_connection);
2850        let (module_tx, _module_rx) = mpsc::channel(1);
2851        forwarding
2852            .register_module_connection(
2853                module_connection,
2854                "credit-provider".to_string(),
2855                1,
2856                Concurrency::ModuleManaged,
2857                FrameSink::new(module_tx),
2858            )
2859            .unwrap();
2860        // Capacity one, filled by the route.open response, so the terminal
2861        // frame below cannot be enqueued for the client.
2862        let (client_tx, _client_rx) = mpsc::channel(1);
2863        let pending = forwarding
2864            .begin_route_bind_relay_for_test(
2865                client_connection,
2866                FrameSink::new(client_tx),
2867                800,
2868                "credit-provider",
2869            )
2870            .unwrap();
2871        forwarding
2872            .complete_pending_relay(
2873                module_connection,
2874                pending.corr,
2875                RouteBindRelayOutcome::Accepted,
2876            )
2877            .unwrap();
2878        let DataRoute::Client(DataRouteState::Bound(route)) = forwarding
2879            .lookup_data_route(
2880                client_connection,
2881                pending.client_channel,
2882                pending.client_epoch,
2883            )
2884            .unwrap()
2885        else {
2886            panic!("expected a bound client route");
2887        };
2888        route.flow.acquire_tagged(801, false).await.unwrap();
2889        assert_eq!(route.flow.drain_in_flight(), 1);
2890
2891        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
2892        let module_ctx = RouteCtx {
2893            connection_id: module_connection,
2894            egress: FrameSink::new(module_egress_tx),
2895        };
2896        let terminal = Frame::build(
2897            FrameType::Response,
2898            Flags::new(false, Priority::Interactive, true),
2899            pending.module_channel,
2900            pending.module_epoch,
2901            801,
2902            b"terminal".to_vec(),
2903        )
2904        .unwrap();
2905        router
2906            .route_for_connection(&module_ctx, terminal)
2907            .await
2908            .unwrap();
2909
2910        assert_eq!(
2911            router.counters.snapshot()["client_egress_close_delivery_failed"],
2912            1,
2913            "the client delivery must have failed for this test to mean anything"
2914        );
2915        assert_eq!(
2916            route.flow.drain_in_flight(),
2917            0,
2918            "the module's terminal frame must release its credit even though the client could not take it"
2919        );
2920    }
2921
2922    #[tokio::test]
2923    async fn full_route_goodbye_sink_requests_target_close_without_erroring_module() {
2924        let forwarding = Arc::new(ForwardingTable::default());
2925        let control = Arc::new(ControlHandler::with_forwarding(
2926            Arc::new(crate::Registry::default()),
2927            Arc::clone(&forwarding),
2928        ));
2929        let router = Router::with_control_handler(control);
2930        let module_connection = ConnectionId::new(30);
2931        let client_connection = ConnectionId::new(40);
2932        let mut close_receiver = forwarding.register_connection_close(client_connection);
2933        let (module_tx, _module_rx) = mpsc::channel(1);
2934        forwarding
2935            .register_module_connection(
2936                module_connection,
2937                "goodbye-full-provider".to_string(),
2938                1,
2939                Concurrency::ModuleManaged,
2940                FrameSink::new(module_tx),
2941            )
2942            .unwrap();
2943        let (client_tx, mut client_rx) = mpsc::channel(1);
2944        let pending = forwarding
2945            .begin_route_bind_relay_for_test(
2946                client_connection,
2947                FrameSink::new(client_tx),
2948                800,
2949                "goodbye-full-provider",
2950            )
2951            .unwrap();
2952        forwarding
2953            .complete_pending_relay(
2954                module_connection,
2955                pending.corr,
2956                RouteBindRelayOutcome::Accepted,
2957            )
2958            .unwrap();
2959
2960        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
2961        let module_ctx = RouteCtx {
2962            connection_id: module_connection,
2963            egress: FrameSink::new(module_egress_tx),
2964        };
2965        let goodbye = Frame::build(
2966            FrameType::Goodbye,
2967            Flags::new(false, Priority::Passive, true),
2968            pending.module_channel,
2969            pending.module_epoch,
2970            801,
2971            Vec::new(),
2972        )
2973        .unwrap();
2974
2975        router
2976            .route_for_connection(&module_ctx, goodbye)
2977            .await
2978            .unwrap();
2979        let reason = tokio::time::timeout(Duration::from_secs(1), &mut close_receiver)
2980            .await
2981            .expect("close request should be sent for the full GOODBYE sink")
2982            .expect("close sender should include a reason");
2983        assert!(
2984            reason.to_string().contains("route_goodbye_delivery_failed"),
2985            "unexpected close reason: {reason}"
2986        );
2987        assert_eq!(client_rx.try_recv().unwrap().header.corr, 800);
2988        assert!(client_rx.try_recv().is_err());
2989        assert_eq!(router.counters.snapshot()["goodbye_relay_client_failed"], 1);
2990        assert_eq!(router.counters.snapshot()["route_released_epoch_fenced"], 1);
2991    }
2992
2993    /// One module and one client connection with `routes` routes bound between
2994    /// them. The client uses a real connection egress queue (the same byte
2995    /// budget and frame-count backstop as a live connection), and its route.open
2996    /// responses are drained so the queue starts empty.
2997    async fn multi_route_client(
2998        module_id: &str,
2999        module_connection: ConnectionId,
3000        client_connection: ConnectionId,
3001        routes: usize,
3002    ) -> (
3003        Router,
3004        FrameSink,
3005        mpsc::Receiver<OutboundFrame>,
3006        RouteCtx,
3007        Vec<crate::forwarding::PendingRouteBindRelay>,
3008        ConnectionCloseReceiver,
3009    ) {
3010        let forwarding = Arc::new(ForwardingTable::default());
3011        let control = Arc::new(ControlHandler::with_forwarding(
3012            Arc::new(crate::Registry::default()),
3013            Arc::clone(&forwarding),
3014        ));
3015        let router = Router::with_control_handler(control);
3016        let close_receiver = forwarding.register_connection_close(client_connection);
3017        let (module_tx, _module_rx) = mpsc::channel(8);
3018        forwarding
3019            .register_module_connection(
3020                module_connection,
3021                module_id.to_string(),
3022                1,
3023                Concurrency::ModuleManaged,
3024                FrameSink::new(module_tx),
3025            )
3026            .unwrap();
3027        let (client_sink, mut client_rx) = crate::server::connection_egress();
3028        let mut bound = Vec::with_capacity(routes);
3029        for index in 0..routes {
3030            let pending = forwarding
3031                .begin_route_bind_relay_for_test(
3032                    client_connection,
3033                    client_sink.clone(),
3034                    900 + index as u64,
3035                    module_id,
3036                )
3037                .unwrap();
3038            forwarding
3039                .complete_pending_relay(
3040                    module_connection,
3041                    pending.corr,
3042                    RouteBindRelayOutcome::Accepted,
3043                )
3044                .unwrap();
3045            assert_eq!(
3046                client_rx.recv().await.unwrap().header.corr,
3047                900 + index as u64
3048            );
3049            bound.push(pending);
3050        }
3051        let (module_egress_tx, _module_egress_rx) = mpsc::channel(8);
3052        let module_ctx = RouteCtx {
3053            connection_id: module_connection,
3054            egress: FrameSink::new(module_egress_tx),
3055        };
3056        (
3057            router,
3058            client_sink,
3059            client_rx,
3060            module_ctx,
3061            bound,
3062            close_receiver,
3063        )
3064    }
3065
3066    /// Per-frame cost of the egress sink's admission and release accounting:
3067    /// one million 200-byte frames enqueued with `try_send` and taken off the
3068    /// queue the way the connection writer does, in batches of 1,000 so the
3069    /// queue stays well inside its budget. Prints nanoseconds per frame; it is
3070    /// a measurement, not a gate. Run with
3071    /// `cargo test --release -p subc-daemon --lib egress_sink_per_frame_cost -- --ignored --nocapture`.
3072    #[test]
3073    #[ignore = "timing measurement, run on demand"]
3074    fn egress_sink_per_frame_cost() {
3075        const FRAMES: usize = 1_000_000;
3076        const BATCH: usize = 1_000;
3077        let (sink, mut rx) = crate::server::connection_egress();
3078        let template = stream_frame(9, 1, 0, vec![b't'; 200]);
3079        let started = Instant::now();
3080        for _ in 0..FRAMES / BATCH {
3081            for _ in 0..BATCH {
3082                sink.try_send(template.clone()).unwrap();
3083            }
3084            for _ in 0..BATCH {
3085                let outbound = rx.try_recv().unwrap();
3086                if let Some(charge) = &outbound.charge {
3087                    charge.taken_by_writer();
3088                }
3089                drop(std::hint::black_box(outbound));
3090            }
3091        }
3092        let elapsed = started.elapsed();
3093        assert_eq!(sink.backlog().queued_bytes, 0);
3094        println!(
3095            "egress sink: {FRAMES} frames in {elapsed:?}, {:.1} ns/frame",
3096            elapsed.as_nanos() as f64 / FRAMES as f64
3097        );
3098    }
3099
3100    fn stream_frame(channel: u16, epoch: u32, corr: u64, body: Vec<u8>) -> Frame {
3101        Frame::build(
3102            FrameType::StreamData,
3103            Flags::new(false, Priority::Interactive, false),
3104            channel,
3105            epoch,
3106            corr,
3107            body,
3108        )
3109        .unwrap()
3110    }
3111
3112    fn module_route_for_test(
3113        router: &Router,
3114        ctx: &RouteCtx,
3115        route: &crate::forwarding::PendingRouteBindRelay,
3116    ) -> Arc<RouteBinding> {
3117        match router
3118            .forwarding
3119            .lookup_data_route(ctx.connection_id, route.module_channel, route.module_epoch)
3120            .unwrap()
3121        {
3122            DataRoute::Module(DataRouteState::Bound(binding)) => binding,
3123            other => panic!("expected a bound module route, got {other:?}"),
3124        }
3125    }
3126
3127    fn assert_frame_size_error(frame: &Frame, channel: u16, epoch: u32, corr: u64, bytes: usize) {
3128        assert_eq!(frame.header.ty, FrameType::Error);
3129        assert_eq!(frame.header.channel, channel);
3130        assert_eq!(frame.header.epoch, epoch);
3131        assert_eq!(frame.header.corr, corr);
3132        assert!(frame.header.flags.is_daemon_origin());
3133        let body: ErrorBody = serde_json::from_slice(&frame.body).unwrap();
3134        assert_eq!(body.code, error_codes::FRAME_TOO_LARGE);
3135        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3136        assert!(body.message.contains(&bytes.to_string()));
3137        assert!(body.message.contains(&limit.to_string()));
3138        assert_eq!(
3139            body.detail,
3140            Some(serde_json::json!({ "frame_bytes": bytes, "byte_limit": limit }))
3141        );
3142    }
3143
3144    #[tokio::test]
3145    async fn module_egress_response_oversized_reply_keeps_connection_and_other_route() {
3146        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3147        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3148            "oversize-provider",
3149            ConnectionId::new(80),
3150            ConnectionId::new(81),
3151            2,
3152        )
3153        .await;
3154        let binding = module_route_for_test(&router, &ctx, &routes[0]);
3155        binding.flow.acquire_tagged(101, false).await.unwrap();
3156        module_route_for_test(&router, &ctx, &routes[1])
3157            .flow
3158            .acquire_tagged(102, false)
3159            .await
3160            .unwrap();
3161        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3162        let oversized = Frame::build(
3163            FrameType::Response,
3164            Flags::new(false, Priority::Interactive, true),
3165            routes[0].module_channel,
3166            routes[0].module_epoch,
3167            101,
3168            vec![b'x'; limit - subc_protocol::HEADER_LEN + 1],
3169        )
3170        .unwrap();
3171        assert_eq!(sink.backlog().queued_bytes, 0);
3172        router.route_for_connection(&ctx, oversized).await.unwrap();
3173
3174        // Reproduce a large reply followed by ordinary traffic on another route
3175        // before the client reads anything. The large reply must not monopolize
3176        // the queue and make that second delivery close the shared connection.
3177        router
3178            .route_for_connection(
3179                &ctx,
3180                route_frame(
3181                    FrameType::Response,
3182                    routes[1].module_channel,
3183                    routes[1].module_epoch,
3184                    102,
3185                ),
3186            )
3187            .await
3188            .unwrap();
3189        assert!(
3190            close.try_recv().is_err(),
3191            "an oversized reply must not close the multiplexed client"
3192        );
3193        let error = rx.try_recv().expect("the waiting client gets an ERROR");
3194        assert_frame_size_error(
3195            &error,
3196            routes[0].client_channel,
3197            routes[0].client_epoch,
3198            101,
3199            limit + 1,
3200        );
3201        let second = rx.try_recv().expect("the other route's reply arrives");
3202        assert_eq!(second.header.ty, FrameType::Response);
3203        assert_eq!(second.header.channel, routes[1].client_channel);
3204        assert_eq!(second.header.epoch, routes[1].client_epoch);
3205        assert_eq!(second.header.corr, 102);
3206        assert_eq!(second.body, b"route-body");
3207        assert_eq!(binding.flow.drain_in_flight(), 0);
3208        for route in &routes {
3209            module_route_for_test(&router, &ctx, route);
3210        }
3211        assert!(rx.try_recv().is_err());
3212        drop((error, second));
3213        assert_eq!(sink.backlog().queued_bytes, 0);
3214        assert_eq!(
3215            router.counters.snapshot()["client_egress_close_delivery_failed"],
3216            0
3217        );
3218
3219        let captured = test_log::captured_logs(&logs);
3220        let warnings: Vec<_> = captured
3221            .lines()
3222            .filter(|line| line.contains("WARN"))
3223            .collect();
3224        assert_eq!(warnings.len(), 1, "{captured}");
3225        let warning = warnings[0];
3226        for expected in [
3227            "module_id=oversize-provider".to_string(),
3228            "client_principal=direct".to_string(),
3229            format!("client_channel={}", routes[0].client_channel),
3230            format!("frame_bytes={}", limit + 1),
3231            format!("byte_limit={limit}"),
3232        ] {
3233            assert!(warning.contains(&expected), "missing {expected}: {warning}");
3234        }
3235    }
3236
3237    async fn poll_once<F: std::future::Future>(
3238        mut future: std::pin::Pin<&mut F>,
3239    ) -> std::task::Poll<F::Output> {
3240        std::future::poll_fn(|cx| std::task::Poll::Ready(future.as_mut().poll(cx))).await
3241    }
3242
3243    fn fill_client_budget(sink: &FrameSink, route: &crate::forwarding::PendingRouteBindRelay) {
3244        sink.try_send(
3245            Frame::build(
3246                FrameType::Response,
3247                Flags::new(false, Priority::Interactive, true),
3248                route.client_channel,
3249                route.client_epoch,
3250                100,
3251                vec![
3252                    b'x';
3253                    crate::server::CONNECTION_EGRESS_BYTE_BUDGET - subc_protocol::HEADER_LEN
3254                ],
3255            )
3256            .unwrap(),
3257        )
3258        .unwrap();
3259        assert_eq!(
3260            sink.backlog().queued_bytes,
3261            crate::server::CONNECTION_EGRESS_BYTE_BUDGET
3262        );
3263    }
3264
3265    async fn assert_full_client_burst_survives(ty: FrameType, oversized: bool) {
3266        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3267            "draining-burst",
3268            ConnectionId::new(92),
3269            ConnectionId::new(93),
3270            2,
3271        )
3272        .await;
3273        fill_client_budget(&sink, &routes[0]);
3274        let frame = if oversized {
3275            Frame::build(
3276                ty,
3277                Flags::new(false, Priority::Interactive, false),
3278                routes[1].module_channel,
3279                routes[1].module_epoch,
3280                101,
3281                vec![b's'; crate::server::CONNECTION_EGRESS_BYTE_BUDGET],
3282            )
3283            .unwrap()
3284        } else {
3285            route_frame(ty, routes[1].module_channel, routes[1].module_epoch, 101)
3286        };
3287        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3288        assert!(poll_once(delivery.as_mut()).await.is_pending());
3289        assert!(
3290            close.try_recv().is_err(),
3291            "fresh bursts must not close: {ty:?}"
3292        );
3293        tokio::time::advance(Duration::from_millis(50)).await;
3294        let queued = rx.try_recv().unwrap();
3295        queued.charge.as_ref().unwrap().taken_by_writer();
3296        drop(queued);
3297        assert!(matches!(
3298            poll_once(delivery.as_mut()).await,
3299            std::task::Poll::Ready(Ok(()))
3300        ));
3301        let delivered = rx
3302            .try_recv()
3303            .expect("the burst frame must be delivered after draining");
3304        assert_eq!(delivered.header.channel, routes[1].client_channel);
3305        assert_eq!(delivered.header.epoch, routes[1].client_epoch);
3306        assert_eq!(delivered.header.corr, 101);
3307        if oversized {
3308            assert_frame_size_error(
3309                &delivered,
3310                routes[1].client_channel,
3311                routes[1].client_epoch,
3312                101,
3313                crate::server::CONNECTION_EGRESS_BYTE_BUDGET + subc_protocol::HEADER_LEN,
3314            );
3315        } else {
3316            assert_eq!(delivered.header.ty, ty);
3317        }
3318        assert!(rx.try_recv().is_err());
3319        assert!(close.try_recv().is_err());
3320        assert_eq!(
3321            router.counters.snapshot()["client_egress_close_delivery_failed"],
3322            0
3323        );
3324        assert_eq!(router.counters.snapshot()["goodbye_relay_client_failed"], 0);
3325    }
3326
3327    #[tokio::test(start_paused = true)]
3328    async fn module_egress_fresh_full_queue_burst_survives() {
3329        for ty in [
3330            FrameType::Response,
3331            FrameType::StreamData,
3332            FrameType::Request,
3333            FrameType::Push,
3334        ] {
3335            assert_full_client_burst_survives(ty, false).await;
3336        }
3337    }
3338
3339    #[tokio::test(start_paused = true)]
3340    async fn module_goodbye_fresh_full_queue_burst_survives() {
3341        assert_full_client_burst_survives(FrameType::Goodbye, false).await;
3342    }
3343
3344    #[tokio::test(start_paused = true)]
3345    async fn frame_count_backstop_also_allows_a_draining_burst() {
3346        let (tx, mut rx) = mpsc::channel(1);
3347        let sink = FrameSink::with_byte_budget(tx, 2_000);
3348        sink.try_send(stream_frame(1, 1, 1, vec![b'x'; 100]))
3349            .unwrap();
3350        let mut delivery = Box::pin(sink.send_to_client(stream_frame(1, 1, 2, vec![b'y'; 100])));
3351        assert!(poll_once(delivery.as_mut()).await.is_pending());
3352        assert!(
3353            sink.backlog().queued_bytes < 2_000,
3354            "only frame capacity is exhausted"
3355        );
3356        tokio::time::advance(Duration::from_millis(50)).await;
3357        drop(rx.try_recv().unwrap());
3358        assert!(matches!(
3359            poll_once(delivery.as_mut()).await,
3360            std::task::Poll::Ready(Ok(()))
3361        ));
3362        assert_eq!(rx.try_recv().unwrap().header.corr, 2);
3363    }
3364
3365    #[tokio::test(start_paused = true)]
3366    async fn oversized_reply_replacement_fresh_full_queue_burst_survives() {
3367        for ty in [FrameType::Response, FrameType::StreamData] {
3368            assert_full_client_burst_survives(ty, true).await;
3369        }
3370    }
3371
3372    #[tokio::test(start_paused = true)]
3373    async fn module_egress_stopped_reader_closes_without_waiting() {
3374        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3375        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3376            "oldest-stopped-reader",
3377            ConnectionId::new(94),
3378            ConnectionId::new(95),
3379            2,
3380        )
3381        .await;
3382        fill_client_budget(&sink, &routes[0]);
3383        // The writer has taken the head but cannot finish writing it. Its
3384        // bytes stay charged, and the atomic age still diagnoses that stall.
3385        let writing = rx.try_recv().unwrap();
3386        writing.charge.as_ref().unwrap().taken_by_writer();
3387        tokio::time::advance(Duration::from_millis(251)).await;
3388        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(251)));
3389        assert_eq!(sink.backlog().queued_bytes, queued_frame_bytes(&writing));
3390        let started = tokio::time::Instant::now();
3391        let frame = stream_frame(
3392            routes[0].module_channel,
3393            routes[0].module_epoch,
3394            101,
3395            b"secret-body-never-log".to_vec(),
3396        );
3397        let flags = frame.header.flags.0;
3398        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3399        assert!(
3400            matches!(
3401                poll_once(delivery.as_mut()).await,
3402                std::task::Poll::Ready(Ok(()))
3403            ),
3404            "an oldest frame older than 250 ms must close immediately, without a new wait"
3405        );
3406        assert_eq!(started.elapsed(), Duration::ZERO);
3407        assert!(close
3408            .try_recv()
3409            .unwrap()
3410            .to_string()
3411            .contains("module_to_client_delivery_failed"));
3412        let captured = test_log::captured_logs(&logs);
3413        for expected in [
3414            "frame_type=Some(StreamData)".to_string(),
3415            format!("frame_flags=Some({flags})"),
3416            "oldest_queued_ms=251".to_string(),
3417            "close_cause=\"oldest_frame_older_than_250_ms\"".to_string(),
3418        ] {
3419            assert!(
3420                captured.contains(&expected),
3421                "missing {expected}: {captured}"
3422            );
3423        }
3424        assert!(!captured.contains("secret-body-never-log"));
3425    }
3426
3427    #[tokio::test(start_paused = true)]
3428    async fn client_gone_mid_wait_resumes_module_reader_immediately() {
3429        for writer_gone in [false, true] {
3430            let (router, sink, mut rx, ctx, routes, _close) = multi_route_client(
3431                "gone-during-burst",
3432                ConnectionId::new(96),
3433                ConnectionId::new(97),
3434                1,
3435            )
3436            .await;
3437            fill_client_budget(&sink, &routes[0]);
3438            let frame = route_frame(
3439                FrameType::Response,
3440                routes[0].module_channel,
3441                routes[0].module_epoch,
3442                101,
3443            );
3444            let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3445            assert!(poll_once(delivery.as_mut()).await.is_pending());
3446            tokio::time::advance(Duration::from_millis(50)).await;
3447            let started = tokio::time::Instant::now();
3448            if writer_gone {
3449                rx.close();
3450            } else {
3451                sink.close_client_delivery();
3452            }
3453            assert!(
3454                matches!(
3455                    poll_once(delivery.as_mut()).await,
3456                    std::task::Poll::Ready(Ok(()))
3457                ),
3458                "client teardown must wake the module reader before the writer drains"
3459            );
3460            assert_eq!(started.elapsed(), Duration::ZERO);
3461            assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 0);
3462            assert_eq!(rx.try_recv().unwrap().header.corr, 100);
3463            assert!(rx.try_recv().is_err());
3464        }
3465    }
3466
3467    #[tokio::test(start_paused = true)]
3468    async fn cancelled_module_delivery_releases_waiter_without_closing_client() {
3469        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3470            "cancelled-burst",
3471            ConnectionId::new(98),
3472            ConnectionId::new(99),
3473            1,
3474        )
3475        .await;
3476        fill_client_budget(&sink, &routes[0]);
3477        let frame = route_frame(
3478            FrameType::Response,
3479            routes[0].module_channel,
3480            routes[0].module_epoch,
3481            101,
3482        );
3483        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3484        assert!(poll_once(delivery.as_mut()).await.is_pending());
3485        assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 1);
3486        drop(delivery);
3487        assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 0);
3488        tokio::time::advance(Duration::from_secs(1)).await;
3489        assert!(close.try_recv().is_err());
3490        drop(rx.try_recv().unwrap());
3491        assert_eq!(sink.backlog().queued_bytes, 0);
3492        assert!(sink.backlog().oldest_age.is_none());
3493    }
3494
3495    #[tokio::test(start_paused = true)]
3496    async fn egress_atomic_age_follows_writer_and_clears_when_drained() {
3497        let (sink, mut rx) = crate::server::connection_egress();
3498        sink.try_send(stream_frame(1, 1, 1, vec![b'x'; 100]))
3499            .unwrap();
3500        tokio::time::advance(Duration::from_millis(200)).await;
3501        sink.try_send(stream_frame(2, 1, 2, vec![b'y'; 100]))
3502            .unwrap();
3503        let writing = rx.try_recv().unwrap();
3504        writing.charge.as_ref().unwrap().taken_by_writer();
3505        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(200)));
3506        drop(writing);
3507        // Between frames the lock-free marker can still name the previous
3508        // head. The next writer take advances it without scanning the queue.
3509        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(200)));
3510        tokio::time::advance(Duration::from_millis(50)).await;
3511        let next = rx.try_recv().unwrap();
3512        next.charge.as_ref().unwrap().taken_by_writer();
3513        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(50)));
3514        assert!(
3515            sink.backlog().queued_bytes > 0,
3516            "in-flight bytes remain charged until written"
3517        );
3518        drop(next);
3519        assert_eq!(sink.backlog().queued_bytes, 0);
3520        assert_eq!(sink.backlog().oldest_age, None);
3521    }
3522
3523    #[tokio::test(start_paused = true)]
3524    async fn module_egress_response_full_client_waits_only_remaining_grace() {
3525        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3526            "backpressure-provider",
3527            ConnectionId::new(82),
3528            ConnectionId::new(83),
3529            2,
3530        )
3531        .await;
3532        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3533        // Exactly the limit, including its header, must be admitted to an empty
3534        // queue. Leave it unread to deterministically exhaust only byte capacity.
3535        router
3536            .route_for_connection(
3537                &ctx,
3538                Frame::build(
3539                    FrameType::Response,
3540                    Flags::new(false, Priority::Interactive, true),
3541                    routes[0].module_channel,
3542                    routes[0].module_epoch,
3543                    201,
3544                    vec![b'x'; limit - subc_protocol::HEADER_LEN],
3545                )
3546                .unwrap(),
3547            )
3548            .await
3549            .unwrap();
3550        assert_eq!(sink.backlog().queued_bytes, limit);
3551        assert_eq!(sink.backlog().queued_frames, 1);
3552        let ordinary = route_frame(
3553            FrameType::Response,
3554            routes[1].module_channel,
3555            routes[1].module_epoch,
3556            202,
3557        );
3558        assert!(queued_frame_bytes(&ordinary) < limit);
3559        // A fitting reply gets only the unused portion of the oldest frame's
3560        // 250 ms grace, not an immediate close or a fresh 250 ms wait.
3561        tokio::time::advance(Duration::from_millis(100)).await;
3562        let mut delivery = Box::pin(router.route_for_connection(&ctx, ordinary));
3563        assert!(poll_once(delivery.as_mut()).await.is_pending());
3564        assert!(close.try_recv().is_err());
3565        tokio::time::advance(Duration::from_millis(149)).await;
3566        assert!(poll_once(delivery.as_mut()).await.is_pending());
3567        assert!(close.try_recv().is_err());
3568        tokio::time::advance(Duration::from_millis(1)).await;
3569        assert!(matches!(
3570            poll_once(delivery.as_mut()).await,
3571            std::task::Poll::Ready(Ok(()))
3572        ));
3573        drop(delivery);
3574        let reason = close.try_recv().expect("the full client must close");
3575        assert!(reason
3576            .to_string()
3577            .contains("module_to_client_delivery_failed"));
3578        assert!(!reason.to_string().contains("frame_too_large"));
3579        assert_eq!(
3580            router.counters.snapshot()["client_egress_close_delivery_failed"],
3581            1
3582        );
3583        let admitted = rx.try_recv().expect("the budget-sized frame was admitted");
3584        assert_eq!(admitted.header.ty, FrameType::Response);
3585        assert_eq!(admitted.header.corr, 201);
3586        assert!(
3587            rx.try_recv().is_err(),
3588            "no oversized-frame ERROR is substituted for backpressure"
3589        );
3590    }
3591
3592    #[tokio::test(start_paused = true)]
3593    async fn oversized_reply_to_a_full_client_waits_only_remaining_grace() {
3594        let (router, sink, _rx, ctx, routes, mut close) = multi_route_client(
3595            "full-oversize-provider",
3596            ConnectionId::new(90),
3597            ConnectionId::new(91),
3598            2,
3599        )
3600        .await;
3601        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3602        // Fill the client's queue to its budget and leave it unread.
3603        router
3604            .route_for_connection(
3605                &ctx,
3606                Frame::build(
3607                    FrameType::Response,
3608                    Flags::new(false, Priority::Interactive, true),
3609                    routes[0].module_channel,
3610                    routes[0].module_epoch,
3611                    501,
3612                    vec![b'x'; limit - subc_protocol::HEADER_LEN],
3613                )
3614                .unwrap(),
3615            )
3616            .await
3617            .unwrap();
3618        assert_eq!(sink.backlog().queued_bytes, limit);
3619        let oversized = Frame::build(
3620            FrameType::Response,
3621            Flags::new(false, Priority::Interactive, true),
3622            routes[1].module_channel,
3623            routes[1].module_epoch,
3624            502,
3625            vec![b'y'; limit - subc_protocol::HEADER_LEN + 1],
3626        )
3627        .unwrap();
3628        // The replacement ERROR gets the same bounded burst grace as the
3629        // ordinary reply; oversized payloads themselves are never queued.
3630        tokio::time::advance(Duration::from_millis(80)).await;
3631        let mut delivery = Box::pin(router.route_for_connection(&ctx, oversized));
3632        assert!(poll_once(delivery.as_mut()).await.is_pending());
3633        assert!(close.try_recv().is_err());
3634        tokio::time::advance(Duration::from_millis(169)).await;
3635        assert!(poll_once(delivery.as_mut()).await.is_pending());
3636        assert!(close.try_recv().is_err());
3637        tokio::time::advance(Duration::from_millis(1)).await;
3638        assert!(matches!(
3639            poll_once(delivery.as_mut()).await,
3640            std::task::Poll::Ready(Ok(()))
3641        ));
3642        drop(delivery);
3643        let reason = close.try_recv().expect("the full client must close");
3644        assert!(reason
3645            .to_string()
3646            .contains("module_to_client_delivery_failed"));
3647    }
3648
3649    #[tokio::test]
3650    async fn oversized_reverse_request_errors_module_without_reaching_client() {
3651        let (router, _sink, mut rx, mut ctx, routes, mut close) = multi_route_client(
3652            "reverse-oversize-provider",
3653            ConnectionId::new(84),
3654            ConnectionId::new(85),
3655            2,
3656        )
3657        .await;
3658        let (module_tx, mut module_rx) = mpsc::channel(8);
3659        ctx.egress = FrameSink::new(module_tx);
3660        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3661        router
3662            .route_for_connection(
3663                &ctx,
3664                Frame::build(
3665                    FrameType::Request,
3666                    Flags::new(false, Priority::Interactive, false),
3667                    routes[0].module_channel,
3668                    routes[0].module_epoch,
3669                    301,
3670                    vec![b'r'; limit - subc_protocol::HEADER_LEN + 1],
3671                )
3672                .unwrap(),
3673            )
3674            .await
3675            .unwrap();
3676        assert!(
3677            rx.try_recv().is_err(),
3678            "the reverse request never reaches the client"
3679        );
3680        let error = module_rx.try_recv().expect("the module gets the refusal");
3681        assert_frame_size_error(
3682            &error,
3683            routes[0].module_channel,
3684            routes[0].module_epoch,
3685            301,
3686            limit + 1,
3687        );
3688        assert!(module_rx.try_recv().is_err());
3689        for (index, route) in routes.iter().enumerate() {
3690            module_route_for_test(&router, &ctx, route);
3691            router
3692                .route_for_connection(
3693                    &ctx,
3694                    route_frame(
3695                        FrameType::Response,
3696                        route.module_channel,
3697                        route.module_epoch,
3698                        302 + index as u64,
3699                    ),
3700                )
3701                .await
3702                .unwrap();
3703            let reply = rx.try_recv().expect("both routes still deliver");
3704            assert_eq!(reply.header.ty, FrameType::Response);
3705            assert_eq!(reply.header.channel, route.client_channel);
3706        }
3707        assert!(close.try_recv().is_err());
3708        assert_eq!(
3709            router.counters.snapshot()["client_egress_close_delivery_failed"],
3710            0
3711        );
3712    }
3713
3714    #[tokio::test]
3715    async fn oversized_push_closes_client_with_precise_warn() {
3716        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3717        let (router, _sink, mut rx, ctx, routes, mut close) = multi_route_client(
3718            "push-oversize-provider",
3719            ConnectionId::new(86),
3720            ConnectionId::new(87),
3721            2,
3722        )
3723        .await;
3724        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3725        router
3726            .route_for_connection(
3727                &ctx,
3728                Frame::build(
3729                    FrameType::Push,
3730                    Flags::new(false, Priority::Interactive, false),
3731                    routes[0].module_channel,
3732                    routes[0].module_epoch,
3733                    0,
3734                    vec![b'p'; limit - subc_protocol::HEADER_LEN + 1],
3735                )
3736                .unwrap(),
3737            )
3738            .await
3739            .unwrap();
3740        let reason = close
3741            .try_recv()
3742            .expect("unsolicited oversize still closes the client");
3743        assert!(reason
3744            .to_string()
3745            .contains("frame_too_large: oversized push"));
3746        assert!(
3747            rx.try_recv().is_err(),
3748            "no part of the oversized push is forwarded"
3749        );
3750        let captured = test_log::captured_logs(&logs);
3751        let warnings: Vec<_> = captured
3752            .lines()
3753            .filter(|line| line.contains("WARN"))
3754            .collect();
3755        assert_eq!(warnings.len(), 1, "{captured}");
3756        let warning = warnings[0];
3757        for expected in [
3758            "oversized push".to_string(),
3759            "module_id=\"push-oversize-provider\"".to_string(),
3760            "principals=direct".to_string(),
3761            format!("client_channel={}", routes[0].client_channel),
3762            format!("size={}", limit + 1),
3763            format!("limit={limit}"),
3764        ] {
3765            assert!(warning.contains(&expected), "missing {expected}: {warning}");
3766        }
3767        assert_eq!(
3768            router.counters.snapshot()["client_egress_close_delivery_failed"],
3769            1
3770        );
3771    }
3772
3773    #[tokio::test]
3774    async fn oversized_stream_and_error_frames_end_request_even_with_queued_traffic() {
3775        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3776            "stream-oversize-provider",
3777            ConnectionId::new(88),
3778            ConnectionId::new(89),
3779            2,
3780        )
3781        .await;
3782        let binding = module_route_for_test(&router, &ctx, &routes[0]);
3783        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3784        for ty in [
3785            FrameType::StreamData,
3786            FrameType::StreamEnd,
3787            FrameType::Error,
3788        ] {
3789            binding.flow.acquire_tagged(401, false).await.unwrap();
3790            sink.try_send(route_frame(
3791                FrameType::Response,
3792                routes[1].client_channel,
3793                routes[1].client_epoch,
3794                402,
3795            ))
3796            .unwrap();
3797            router
3798                .route_for_connection(
3799                    &ctx,
3800                    Frame::build(
3801                        ty,
3802                        Flags::new(false, Priority::Interactive, false),
3803                        routes[0].module_channel,
3804                        routes[0].module_epoch,
3805                        401,
3806                        vec![b's'; limit - subc_protocol::HEADER_LEN + 1],
3807                    )
3808                    .unwrap(),
3809                )
3810                .await
3811                .unwrap();
3812            assert!(close.try_recv().is_err());
3813            assert_eq!(rx.try_recv().unwrap().header.corr, 402);
3814            let error = rx
3815                .try_recv()
3816                .expect("every correlated oversize frame becomes ERROR");
3817            assert_frame_size_error(
3818                &error,
3819                routes[0].client_channel,
3820                routes[0].client_epoch,
3821                401,
3822                limit + 1,
3823            );
3824            assert_eq!(binding.flow.drain_in_flight(), 0, "{ty:?} ends the request");
3825            assert!(rx.try_recv().is_err());
3826        }
3827    }
3828
3829    /// An awaited send (a control or error reply) is never refused by the byte
3830    /// budget: it parks until the writer frees bytes. If a release could miss a
3831    /// parked sender, that reply would hang for the connection's lifetime, so
3832    /// this pins the wakeup: the send stays parked while the queue is full and
3833    /// completes as soon as one frame leaves it.
3834    #[tokio::test]
3835    async fn awaited_send_parked_behind_a_full_byte_budget_wakes_when_bytes_free() {
3836        let (tx, mut rx) = mpsc::channel(1024);
3837        let sink = FrameSink::with_byte_budget(tx, 2_000);
3838        let mut queued = 0u64;
3839        while sink
3840            .try_send(stream_frame(7, 1, queued, vec![b'x'; 200]))
3841            .is_ok()
3842        {
3843            queued += 1;
3844        }
3845        assert!(queued > 0, "the budget admitted nothing");
3846
3847        let parked = tokio::spawn({
3848            let sink = sink.clone();
3849            async move { sink.send(stream_frame(0, 0, 999, vec![b'r'; 200])).await }
3850        });
3851        tokio::time::sleep(Duration::from_millis(100)).await;
3852        assert!(
3853            !parked.is_finished(),
3854            "the awaited send must wait while the byte budget is full"
3855        );
3856
3857        // The writer takes one frame and drops it, releasing its bytes.
3858        drop(rx.recv().await.expect("a queued frame"));
3859        tokio::time::timeout(Duration::from_secs(2), parked)
3860            .await
3861            .expect("the parked send was never woken after bytes were freed")
3862            .unwrap()
3863            .unwrap();
3864    }
3865
3866    /// A client multiplexing several token streams pauses its reader while the
3867    /// module keeps producing small frames. Far more frames than the old
3868    /// 64-frame queue allowed, but far fewer bytes than the budget, must all be
3869    /// held without closing the connection and delivered in order afterwards.
3870    #[tokio::test]
3871    async fn paused_client_reader_keeps_connection_through_small_frame_burst() {
3872        const ROUTES: usize = 4;
3873        const FRAMES_PER_ROUTE: usize = 250;
3874        let (router, client_sink, mut client_rx, module_ctx, routes, mut close_receiver) =
3875            multi_route_client(
3876                "burst-provider",
3877                ConnectionId::new(60),
3878                ConnectionId::new(61),
3879                ROUTES,
3880            )
3881            .await;
3882
3883        // The reader is paused: nothing is received until every frame is sent.
3884        for seq in 0..FRAMES_PER_ROUTE as u64 {
3885            for (index, route) in routes.iter().enumerate() {
3886                let body = format!("route-{index}-token-{seq:05}-{}", "t".repeat(170));
3887                router
3888                    .route_for_connection(
3889                        &module_ctx,
3890                        stream_frame(
3891                            route.module_channel,
3892                            route.module_epoch,
3893                            seq,
3894                            body.into_bytes(),
3895                        ),
3896                    )
3897                    .await
3898                    .unwrap();
3899            }
3900        }
3901
3902        let backlog = client_sink.backlog();
3903        assert_eq!(backlog.queued_frames, ROUTES * FRAMES_PER_ROUTE);
3904        assert!(backlog.queued_bytes < crate::server::CONNECTION_EGRESS_BYTE_BUDGET);
3905        assert!(
3906            close_receiver.try_recv().is_err(),
3907            "a paused reader under the byte budget must not be closed"
3908        );
3909        assert_eq!(
3910            router.counters.snapshot()["client_egress_close_delivery_failed"],
3911            0
3912        );
3913
3914        // The reader resumes: every frame arrives, in order within each route.
3915        let mut next_seq = vec![0u64; ROUTES];
3916        for _ in 0..ROUTES * FRAMES_PER_ROUTE {
3917            let frame = client_rx.try_recv().expect("every queued frame arrives");
3918            let index = routes
3919                .iter()
3920                .position(|route| route.client_channel == frame.header.channel)
3921                .expect("frame arrives on one of the bound client channels");
3922            assert_eq!(frame.header.corr, next_seq[index], "route {index} order");
3923            let expected_prefix = format!("route-{index}-token-{:05}-", next_seq[index]);
3924            assert!(frame.body.starts_with(expected_prefix.as_bytes()));
3925            next_seq[index] += 1;
3926        }
3927        assert!(client_rx.try_recv().is_err());
3928        assert_eq!(next_seq, vec![FRAMES_PER_ROUTE as u64; ROUTES]);
3929        assert_eq!(client_sink.backlog().queued_bytes, 0);
3930    }
3931
3932    /// A client that never reads exhausts its byte budget and the oldest
3933    /// frame's 250 ms grace, then closes with one header-only diagnosis.
3934    #[tokio::test(start_paused = true)]
3935    async fn never_reading_client_is_closed_at_byte_budget_with_warn_diagnosis() {
3936        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3937        const BODY: usize = 16 * 1024;
3938        let (router, client_sink, _client_rx, module_ctx, routes, mut close_receiver) =
3939            multi_route_client(
3940                "stuck-reader-provider",
3941                ConnectionId::new(70),
3942                ConnectionId::new(71),
3943                2,
3944            )
3945            .await;
3946
3947        let mut admitted = 0usize;
3948        let mut sent = 0u64;
3949        let started = tokio::time::Instant::now();
3950        while router.counters.snapshot()["client_egress_close_delivery_failed"] == 0 {
3951            assert!(sent < 1_000, "the byte budget never refused a frame");
3952            let route = &routes[(sent % 2) as usize];
3953            router
3954                .route_for_connection(
3955                    &module_ctx,
3956                    stream_frame(
3957                        route.module_channel,
3958                        route.module_epoch,
3959                        sent,
3960                        vec![b'z'; BODY],
3961                    ),
3962                )
3963                .await
3964                .unwrap();
3965            sent += 1;
3966            admitted = client_sink.backlog().queued_frames;
3967        }
3968        assert_eq!(
3969            started.elapsed(),
3970            crate::server::CONNECTION_EGRESS_STALL_GRACE
3971        );
3972        // The budget, not the frame-count backstop, did the refusing.
3973        let frame_bytes = subc_protocol::HEADER_LEN + BODY;
3974        assert_eq!(
3975            admitted,
3976            crate::server::CONNECTION_EGRESS_BYTE_BUDGET / frame_bytes
3977        );
3978        let reason = close_receiver
3979            .try_recv()
3980            .expect("the client connection must be asked to close");
3981        assert!(reason
3982            .to_string()
3983            .contains("module_to_client_delivery_failed"));
3984
3985        // A second refused frame for the same connection adds no second WARN.
3986        router
3987            .route_for_connection(
3988                &module_ctx,
3989                stream_frame(
3990                    routes[0].module_channel,
3991                    routes[0].module_epoch,
3992                    sent,
3993                    vec![b'z'; BODY],
3994                ),
3995            )
3996            .await
3997            .unwrap();
3998
3999        let captured = test_log::captured_logs(&logs);
4000        let warn_lines = captured
4001            .lines()
4002            .filter(|line| {
4003                line.contains("closing client connection: its egress queue could not take a frame")
4004            })
4005            .collect::<Vec<_>>();
4006        assert_eq!(warn_lines.len(), 1, "exactly one WARN, got: {captured}");
4007        let line = warn_lines[0];
4008        assert!(line.contains("WARN"), "{line}");
4009        assert!(line.contains("connection_id=71"), "{line}");
4010        assert!(
4011            line.contains("module_id=\"stuck-reader-provider\""),
4012            "{line}"
4013        );
4014        assert!(line.contains("client_channel="), "{line}");
4015        assert!(line.contains("principals=direct"), "{line}");
4016        let queued_bytes: usize = line
4017            .split("queued_bytes=")
4018            .nth(1)
4019            .and_then(|rest| rest.split_whitespace().next())
4020            .and_then(|value| value.parse().ok())
4021            .expect("queued_bytes is logged");
4022        assert_eq!(queued_bytes, admitted * frame_bytes);
4023        assert!(
4024            line.contains(&format!("queued_frames={admitted}")),
4025            "{line}"
4026        );
4027        assert!(line.contains("oldest_queued_ms="), "{line}");
4028        assert!(line.contains("oldest_queued_ms=250"), "{line}");
4029        assert!(line.contains("frame_type=Some(StreamData)"), "{line}");
4030        assert!(
4031            line.contains(&format!(
4032                "frame_flags=Some({})",
4033                Flags::new(false, Priority::Interactive, false).0
4034            )),
4035            "{line}"
4036        );
4037        assert!(
4038            line.contains("close_cause=\"waited_250_ms_without_room\""),
4039            "{line}"
4040        );
4041        assert!(
4042            !line.contains(&"z".repeat(20)),
4043            "body bytes must never be logged: {line}"
4044        );
4045    }
4046
4047    fn route_frame(ty: FrameType, channel: u16, epoch: u32, corr: u64) -> Frame {
4048        Frame::build(
4049            ty,
4050            Flags::new(false, Priority::Interactive, false),
4051            channel,
4052            epoch,
4053            corr,
4054            if ty == FrameType::Request || ty == FrameType::Response {
4055                b"route-body".to_vec()
4056            } else {
4057                Vec::new()
4058            },
4059        )
4060        .unwrap()
4061    }
4062
4063    type DynamicRouteFixture = (
4064        Router,
4065        Arc<ForwardingTable>,
4066        RouteCtx,
4067        mpsc::Receiver<crate::router::OutboundFrame>,
4068        RouteCtx,
4069        mpsc::Receiver<crate::router::OutboundFrame>,
4070        mpsc::Receiver<crate::router::OutboundFrame>,
4071        crate::forwarding::PendingRouteBindRelay,
4072    );
4073
4074    fn dynamic_route_fixture(commit: bool) -> DynamicRouteFixture {
4075        dynamic_route_fixture_with_busy(commit, false)
4076    }
4077
4078    fn dynamic_route_fixture_with_busy(commit: bool, busy_refusals: bool) -> DynamicRouteFixture {
4079        let forwarding = Arc::new(ForwardingTable::default());
4080        let control = Arc::new(crate::ControlHandler::with_forwarding(
4081            Arc::new(crate::Registry::default()),
4082            Arc::clone(&forwarding),
4083        ));
4084        let router = Router::with_control_handler(control);
4085        let module_connection = ConnectionId::new(500);
4086        let client_connection = ConnectionId::new(501);
4087        let (module_tx, module_rx) = mpsc::channel(if busy_refusals { 64 } else { 8 });
4088        forwarding
4089            .register_module_connection(
4090                module_connection,
4091                "epoch-router".into(),
4092                2,
4093                Concurrency::ModuleManaged,
4094                FrameSink::new(module_tx),
4095            )
4096            .unwrap();
4097        let (client_tx, client_rx) = mpsc::channel(if busy_refusals { 64 } else { 8 });
4098        let client_sink = FrameSink::new(client_tx);
4099        let pending = forwarding
4100            .begin_route_bind_relay_with_busy_for_test(
4101                client_connection,
4102                client_sink.clone(),
4103                700,
4104                "epoch-router",
4105                busy_refusals,
4106            )
4107            .unwrap();
4108        if commit {
4109            forwarding
4110                .complete_pending_relay(
4111                    module_connection,
4112                    pending.corr,
4113                    RouteBindRelayOutcome::Accepted,
4114                )
4115                .unwrap();
4116        }
4117        let (module_egress_tx, module_egress_rx) = mpsc::channel(8);
4118        (
4119            router,
4120            forwarding,
4121            RouteCtx {
4122                connection_id: client_connection,
4123                egress: client_sink,
4124            },
4125            client_rx,
4126            RouteCtx {
4127                connection_id: module_connection,
4128                egress: FrameSink::new(module_egress_tx),
4129            },
4130            module_egress_rx,
4131            module_rx,
4132            pending,
4133        )
4134    }
4135
4136    #[tokio::test]
4137    async fn route_epochs_validate_both_directions_and_rewrite_to_peer_handle() {
4138        let (
4139            router,
4140            _forwarding,
4141            client_ctx,
4142            mut client_rx,
4143            module_ctx,
4144            _module_egress_rx,
4145            mut module_rx,
4146            pending,
4147        ) = dynamic_route_fixture(true);
4148        let route_open = client_rx.recv().await.unwrap();
4149        assert_eq!(route_open.header.corr, 700);
4150
4151        router
4152            .route_for_connection(
4153                &client_ctx,
4154                route_frame(
4155                    FrameType::Request,
4156                    pending.client_channel,
4157                    pending.client_epoch,
4158                    701,
4159                ),
4160            )
4161            .await
4162            .unwrap();
4163        let forwarded = module_rx.recv().await.unwrap();
4164        assert_eq!(forwarded.header.channel, pending.module_channel);
4165        assert_eq!(forwarded.header.epoch, pending.module_epoch);
4166
4167        router
4168            .route_for_connection(
4169                &module_ctx,
4170                route_frame(
4171                    FrameType::Response,
4172                    pending.module_channel,
4173                    pending.module_epoch,
4174                    701,
4175                ),
4176            )
4177            .await
4178            .unwrap();
4179        let delivered = client_rx.recv().await.unwrap();
4180        assert_eq!(delivered.header.channel, pending.client_channel);
4181        assert_eq!(delivered.header.epoch, pending.client_epoch);
4182
4183        router
4184            .route_for_connection(
4185                &client_ctx,
4186                route_frame(
4187                    FrameType::Request,
4188                    pending.client_channel,
4189                    pending.client_epoch + 1,
4190                    702,
4191                ),
4192            )
4193            .await
4194            .unwrap();
4195        router
4196            .route_for_connection(
4197                &module_ctx,
4198                route_frame(
4199                    FrameType::Response,
4200                    pending.module_channel,
4201                    pending.module_epoch + 1,
4202                    703,
4203                ),
4204            )
4205            .await
4206            .unwrap();
4207        let stale_error = client_rx.recv().await.unwrap();
4208        assert_eq!(stale_error.header.ty, FrameType::Error);
4209        assert_eq!(stale_error.header.channel, pending.client_channel);
4210        assert_eq!(stale_error.header.epoch, pending.client_epoch + 1);
4211        assert_eq!(stale_error.header.corr, 702);
4212        let body: ErrorBody = serde_json::from_slice(&stale_error.body).unwrap();
4213        assert_eq!(body.code, "stale_route_epoch");
4214        assert!(module_rx.try_recv().is_err());
4215        assert!(client_rx.try_recv().is_err());
4216        let counters = router.counters.snapshot();
4217        assert_eq!(counters["client_frames_dropped_stale_route"], 1);
4218        assert_eq!(counters["module_frames_dropped_no_route"], 1);
4219    }
4220
4221    #[tokio::test]
4222    async fn accepted_route_publishes_route_open_before_immediate_reverse_request() {
4223        let (
4224            router,
4225            _,
4226            _client_ctx,
4227            mut client_rx,
4228            module_ctx,
4229            _module_egress_rx,
4230            _module_rx,
4231            pending,
4232        ) = dynamic_route_fixture(true);
4233        router
4234            .route_for_connection(
4235                &module_ctx,
4236                route_frame(
4237                    FrameType::Request,
4238                    pending.module_channel,
4239                    pending.module_epoch,
4240                    800,
4241                ),
4242            )
4243            .await
4244            .unwrap();
4245
4246        let first = client_rx.recv().await.unwrap();
4247        let second = client_rx.recv().await.unwrap();
4248        assert_eq!(first.header.channel, 0);
4249        assert_eq!(first.header.corr, 700);
4250        assert_eq!(second.header.channel, pending.client_channel);
4251        assert_eq!(second.header.epoch, pending.client_epoch);
4252        assert_eq!(second.header.corr, 800);
4253    }
4254
4255    #[tokio::test]
4256    async fn reserved_slot_ingress_errors_only_matching_client_requests() {
4257        let (
4258            router,
4259            _forwarding,
4260            client_ctx,
4261            mut client_rx,
4262            _module_ctx,
4263            _module_egress_rx,
4264            mut module_rx,
4265            pending,
4266        ) = dynamic_route_fixture(false);
4267        router
4268            .route_for_connection(
4269                &client_ctx,
4270                route_frame(
4271                    FrameType::Request,
4272                    pending.client_channel,
4273                    pending.client_epoch,
4274                    900,
4275                ),
4276            )
4277            .await
4278            .unwrap();
4279        let error = client_rx.recv().await.unwrap();
4280        assert_eq!(error.header.ty, FrameType::Error);
4281        assert_eq!(error.header.channel, pending.client_channel);
4282        assert_eq!(error.header.epoch, pending.client_epoch);
4283        assert_eq!(error.header.corr, 900);
4284
4285        router
4286            .route_for_connection(
4287                &client_ctx,
4288                route_frame(
4289                    FrameType::Response,
4290                    pending.client_channel,
4291                    pending.client_epoch,
4292                    901,
4293                ),
4294            )
4295            .await
4296            .unwrap();
4297        router
4298            .route_for_connection(
4299                &client_ctx,
4300                route_frame(
4301                    FrameType::Request,
4302                    pending.client_channel,
4303                    pending.client_epoch + 1,
4304                    902,
4305                ),
4306            )
4307            .await
4308            .unwrap();
4309        let stale_error = client_rx.recv().await.unwrap();
4310        assert_eq!(stale_error.header.ty, FrameType::Error);
4311        assert_eq!(stale_error.header.channel, pending.client_channel);
4312        assert_eq!(stale_error.header.epoch, pending.client_epoch + 1);
4313        assert_eq!(stale_error.header.corr, 902);
4314        let body: ErrorBody = serde_json::from_slice(&stale_error.body).unwrap();
4315        assert_eq!(body.code, "stale_route_epoch");
4316        assert!(module_rx.try_recv().is_err());
4317        let counters = router.counters.snapshot();
4318        assert_eq!(counters["client_frames_dropped_stale_route"], 1);
4319        assert_eq!(counters["module_frames_dropped_no_route"], 0);
4320    }
4321
4322    #[tokio::test]
4323    async fn dropped_module_route_goodbye_increments_counter() {
4324        let (
4325            router,
4326            _forwarding,
4327            client_ctx,
4328            mut client_rx,
4329            _module_ctx,
4330            _module_egress_rx,
4331            mut module_rx,
4332            pending,
4333        ) = dynamic_route_fixture(true);
4334        let _ = client_rx.recv().await;
4335        module_rx.close();
4336
4337        router
4338            .route_for_connection(
4339                &client_ctx,
4340                route_frame(
4341                    FrameType::Goodbye,
4342                    pending.client_channel,
4343                    pending.client_epoch,
4344                    999,
4345                ),
4346            )
4347            .await
4348            .unwrap();
4349
4350        let counters = router.counters.snapshot();
4351        assert_eq!(counters["goodbye_relay_module_dropped"], 1);
4352        assert_eq!(
4353            counters["goodbye_relay_module_dropped_by_module"],
4354            serde_json::json!({ "epoch-router": 1 })
4355        );
4356        assert_eq!(counters["route_released_epoch_fenced"], 1);
4357    }
4358
4359    #[tokio::test]
4360    async fn module_request_on_stale_epoch_receives_stale_route_epoch() {
4361        let (
4362            router,
4363            _forwarding,
4364            _client_ctx,
4365            _client_rx,
4366            module_ctx,
4367            mut module_egress_rx,
4368            mut module_rx,
4369            pending,
4370        ) = dynamic_route_fixture(true);
4371
4372        router
4373            .route_for_connection(
4374                &module_ctx,
4375                route_frame(
4376                    FrameType::Request,
4377                    pending.module_channel,
4378                    pending.module_epoch + 1,
4379                    1_000,
4380                ),
4381            )
4382            .await
4383            .unwrap();
4384
4385        let error = module_egress_rx.try_recv().unwrap();
4386        assert_eq!(error.header.ty, FrameType::Error);
4387        assert_eq!(error.header.channel, pending.module_channel);
4388        assert_eq!(error.header.epoch, pending.module_epoch + 1);
4389        assert_eq!(error.header.corr, 1_000);
4390        let body: ErrorBody = serde_json::from_slice(&error.body).unwrap();
4391        assert_eq!(body.code, "stale_route_epoch");
4392        assert!(module_rx.try_recv().is_err());
4393        let counters = router.counters.snapshot();
4394        assert_eq!(counters["module_requests_dropped_stale_route"], 1);
4395        assert_eq!(counters["module_frames_dropped_no_route"], 0);
4396    }
4397
4398    #[tokio::test(start_paused = true)]
4399    async fn stale_epoch_drop_warns_once_per_minute_with_suppressed_count() {
4400        let (output, _guard) = test_log::log_capture(tracing::Level::WARN);
4401        let (
4402            router,
4403            _forwarding,
4404            client_ctx,
4405            mut client_rx,
4406            _module_ctx,
4407            _module_egress_rx,
4408            mut module_rx,
4409            pending,
4410        ) = dynamic_route_fixture(true);
4411        let _ = client_rx.recv().await;
4412        for corr in 1..=3 {
4413            router
4414                .route_for_connection(
4415                    &client_ctx,
4416                    route_frame(
4417                        FrameType::Request,
4418                        pending.client_channel,
4419                        pending.client_epoch + 1,
4420                        corr,
4421                    ),
4422                )
4423                .await
4424                .unwrap();
4425            assert_eq!(client_rx.recv().await.unwrap().header.ty, FrameType::Error);
4426        }
4427        assert!(module_rx.try_recv().is_err());
4428        let logs = test_log::captured_logs(&output);
4429        assert_eq!(
4430            logs.matches("dropping data-plane frame").count(),
4431            1,
4432            "{logs}"
4433        );
4434        assert!(logs.contains("WARN"), "{logs}");
4435        assert!(
4436            logs.contains(&format!("connection_id={}", client_ctx.connection_id.get())),
4437            "{logs}"
4438        );
4439        assert!(
4440            logs.contains(&format!("channel={}", pending.client_channel)),
4441            "{logs}"
4442        );
4443        assert!(
4444            logs.contains(&format!("epoch={}", pending.client_epoch + 1)),
4445            "{logs}"
4446        );
4447        assert!(
4448            logs.contains("client_to_module") && logs.contains("stale_epoch"),
4449            "{logs}"
4450        );
4451        assert!(logs.contains("suppressed=0"), "{logs}");
4452
4453        tokio::time::advance(Duration::from_secs(60)).await;
4454        router
4455            .route_for_connection(
4456                &client_ctx,
4457                route_frame(
4458                    FrameType::Request,
4459                    pending.client_channel,
4460                    pending.client_epoch + 2,
4461                    4,
4462                ),
4463            )
4464            .await
4465            .unwrap();
4466        let logs = test_log::captured_logs(&output);
4467        assert_eq!(
4468            logs.matches("dropping data-plane frame").count(),
4469            2,
4470            "{logs}"
4471        );
4472        assert!(logs.contains("suppressed=2"), "{logs}");
4473    }
4474
4475    #[tokio::test]
4476    async fn module_request_on_reserved_or_absent_route_receives_unknown_channel() {
4477        let (
4478            reserved_router,
4479            _forwarding,
4480            _client_ctx,
4481            _client_rx,
4482            reserved_module_ctx,
4483            mut reserved_module_egress_rx,
4484            _module_rx,
4485            reserved,
4486        ) = dynamic_route_fixture(false);
4487        reserved_router
4488            .route_for_connection(
4489                &reserved_module_ctx,
4490                route_frame(
4491                    FrameType::Request,
4492                    reserved.module_channel,
4493                    reserved.module_epoch,
4494                    1_001,
4495                ),
4496            )
4497            .await
4498            .unwrap();
4499        let reserved_error = reserved_module_egress_rx.try_recv().unwrap();
4500        let reserved_body: ErrorBody = serde_json::from_slice(&reserved_error.body).unwrap();
4501        assert_eq!(reserved_error.header.ty, FrameType::Error);
4502        assert_eq!(reserved_error.header.channel, reserved.module_channel);
4503        assert_eq!(reserved_error.header.epoch, reserved.module_epoch);
4504        assert_eq!(reserved_error.header.corr, 1_001);
4505        assert_eq!(reserved_body.code, "unknown_channel");
4506        assert_eq!(
4507            reserved_router.counters.snapshot()["module_requests_dropped_stale_route"],
4508            1
4509        );
4510
4511        let (
4512            absent_router,
4513            _forwarding,
4514            _client_ctx,
4515            _client_rx,
4516            absent_module_ctx,
4517            mut absent_module_egress_rx,
4518            _module_rx,
4519            absent,
4520        ) = dynamic_route_fixture(false);
4521        absent_router
4522            .route_for_connection(
4523                &absent_module_ctx,
4524                route_frame(
4525                    FrameType::Request,
4526                    absent.module_channel + 1,
4527                    absent.module_epoch,
4528                    1_002,
4529                ),
4530            )
4531            .await
4532            .unwrap();
4533        let absent_error = absent_module_egress_rx.try_recv().unwrap();
4534        let absent_body: ErrorBody = serde_json::from_slice(&absent_error.body).unwrap();
4535        assert_eq!(absent_error.header.ty, FrameType::Error);
4536        assert_eq!(absent_error.header.channel, absent.module_channel + 1);
4537        assert_eq!(absent_error.header.epoch, absent.module_epoch);
4538        assert_eq!(absent_error.header.corr, 1_002);
4539        assert_eq!(absent_body.code, "unknown_channel");
4540        assert_eq!(
4541            absent_router.counters.snapshot()["module_requests_dropped_stale_route"],
4542            1
4543        );
4544    }
4545
4546    #[tokio::test]
4547    async fn non_request_module_frame_on_dead_route_is_counted_without_error() {
4548        let (
4549            router,
4550            forwarding,
4551            client_ctx,
4552            mut client_rx,
4553            module_ctx,
4554            mut module_egress_rx,
4555            mut module_rx,
4556            pending,
4557        ) = dynamic_route_fixture(true);
4558        let (other_module_tx, _other_module_rx) = mpsc::channel(8);
4559        forwarding
4560            .register_module_connection(
4561                ConnectionId::new(502),
4562                "other-module".into(),
4563                2,
4564                Concurrency::ModuleManaged,
4565                FrameSink::new(other_module_tx),
4566            )
4567            .unwrap();
4568        let _ = client_rx.recv().await.unwrap();
4569
4570        router
4571            .route_for_connection(
4572                &client_ctx,
4573                route_frame(
4574                    FrameType::Goodbye,
4575                    pending.client_channel,
4576                    pending.client_epoch,
4577                    1_003,
4578                ),
4579            )
4580            .await
4581            .unwrap();
4582        let _ = module_rx.recv().await.unwrap();
4583
4584        router
4585            .route_for_connection(
4586                &module_ctx,
4587                route_frame(
4588                    FrameType::StreamData,
4589                    pending.module_channel,
4590                    pending.module_epoch,
4591                    1_004,
4592                ),
4593            )
4594            .await
4595            .unwrap();
4596
4597        // No ERROR goes back for a non-request frame. The one reply is the
4598        // route GOODBYE telling the module to let go of the released route.
4599        let reply = module_egress_rx.try_recv().unwrap();
4600        assert_eq!(reply.header.ty, FrameType::Goodbye);
4601        assert!(module_egress_rx.try_recv().is_err());
4602        let counters = router.counters.snapshot();
4603        assert_eq!(counters["module_frames_dropped_no_route"], 1);
4604        assert_eq!(
4605            counters["module_frames_dropped_no_route_by_module"],
4606            serde_json::json!({ "epoch-router": 1 })
4607        );
4608        assert_eq!(counters["module_requests_dropped_stale_route"], 0);
4609    }
4610
4611    /// Drain whatever the module connection's queue holds right now, the way a
4612    /// module's reader would before it stalls.
4613    fn drain_now(rx: &mut mpsc::Receiver<OutboundFrame>) {
4614        while rx.try_recv().is_ok() {}
4615    }
4616
4617    /// A module that stops reading for a moment when a client closes one of
4618    /// its routes still learns the route is gone: the GOODBYE its full egress
4619    /// queue refused is delivered as soon as it reads again, rather than
4620    /// dropped, which would leave the module holding the route for the rest of
4621    /// its connection.
4622    #[tokio::test]
4623    async fn route_goodbye_refused_by_stalled_module_is_delivered_when_it_resumes_reading() {
4624        const BUDGET: usize = 4_096;
4625        let forwarding = Arc::new(ForwardingTable::default());
4626        let control = Arc::new(ControlHandler::with_forwarding(
4627            Arc::new(Registry::default()),
4628            Arc::clone(&forwarding),
4629        ));
4630        let router = Router::with_control_handler(control);
4631        let module_connection = ConnectionId::new(80);
4632        let client_connection = ConnectionId::new(81);
4633        let (module_tx, mut module_rx) = mpsc::channel(64);
4634        let module_sink = FrameSink::with_byte_budget(module_tx, BUDGET);
4635        forwarding
4636            .register_module_connection(
4637                module_connection,
4638                "stalled-provider".into(),
4639                2,
4640                Concurrency::ModuleManaged,
4641                module_sink.clone(),
4642            )
4643            .unwrap();
4644        let (client_tx, mut client_rx) = mpsc::channel(8);
4645        let client_sink = FrameSink::new(client_tx);
4646        let pending = forwarding
4647            .begin_route_bind_relay_for_test(
4648                client_connection,
4649                client_sink.clone(),
4650                1_100,
4651                "stalled-provider",
4652            )
4653            .unwrap();
4654        forwarding
4655            .complete_pending_relay(
4656                module_connection,
4657                pending.corr,
4658                RouteBindRelayOutcome::Accepted,
4659            )
4660            .unwrap();
4661        let _ = client_rx.recv().await.unwrap();
4662        drain_now(&mut module_rx);
4663
4664        // The module stalls: its queue holds more than the byte budget, so the
4665        // queue refuses anything further.
4666        module_sink
4667            .try_send(stream_frame(9, 1, 0, vec![b'f'; BUDGET]))
4668            .unwrap();
4669        assert!(module_sink
4670            .try_send(stream_frame(9, 1, 1, Vec::new()))
4671            .is_err());
4672
4673        let client_ctx = RouteCtx {
4674            connection_id: client_connection,
4675            egress: client_sink,
4676        };
4677        router
4678            .route_for_connection(
4679                &client_ctx,
4680                route_frame(
4681                    FrameType::Goodbye,
4682                    pending.client_channel,
4683                    pending.client_epoch,
4684                    1_101,
4685                ),
4686            )
4687            .await
4688            .unwrap();
4689        tokio::task::yield_now().await;
4690        assert_eq!(
4691            router.counters.snapshot()["goodbye_relay_module_dropped"],
4692            0,
4693            "a GOODBYE refused by a momentarily full module queue must not be dropped"
4694        );
4695
4696        // The module reads again: the filler comes off, then the GOODBYE.
4697        let filler = module_rx.recv().await.unwrap();
4698        assert_eq!(filler.header.ty, FrameType::StreamData);
4699        drop(filler);
4700        let goodbye = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
4701            .await
4702            .expect("the refused GOODBYE must be delivered once the module frees room")
4703            .unwrap();
4704        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
4705        assert_eq!(goodbye.header.channel, pending.module_channel);
4706        assert_eq!(goodbye.header.epoch, pending.module_epoch);
4707        assert_eq!(
4708            router.counters.snapshot()["goodbye_relay_module_dropped"],
4709            0
4710        );
4711    }
4712
4713    /// A module still sending on a route the daemon released is told, with a
4714    /// route GOODBYE for exactly the (channel, epoch) it sent on. The same
4715    /// happens for a stale epoch on a channel whose route moved on and for a
4716    /// channel that never had a route; only the first is counted as traffic on
4717    /// a released route.
4718    #[tokio::test]
4719    async fn module_frame_on_route_the_daemon_does_not_hold_is_answered_with_goodbye() {
4720        let (
4721            router,
4722            _forwarding,
4723            client_ctx,
4724            mut client_rx,
4725            module_ctx,
4726            mut module_egress_rx,
4727            mut module_rx,
4728            pending,
4729        ) = dynamic_route_fixture(true);
4730        let _ = client_rx.recv().await.unwrap();
4731        router
4732            .route_for_connection(
4733                &client_ctx,
4734                route_frame(
4735                    FrameType::Goodbye,
4736                    pending.client_channel,
4737                    pending.client_epoch,
4738                    1_200,
4739                ),
4740            )
4741            .await
4742            .unwrap();
4743        drain_now(&mut module_rx);
4744
4745        let cases = [
4746            // Released route: the daemon allocated this (channel, epoch).
4747            (pending.module_channel, pending.module_epoch),
4748            // A channel the daemon never allocated on this connection.
4749            (pending.module_channel + 1, 1),
4750        ];
4751        for (channel, epoch) in cases {
4752            router
4753                .route_for_connection(
4754                    &module_ctx,
4755                    route_frame(FrameType::StreamData, channel, epoch, 1_201),
4756                )
4757                .await
4758                .unwrap();
4759            let reply = module_egress_rx
4760                .try_recv()
4761                .expect("a frame on a route the daemon does not hold is answered");
4762            assert_eq!(reply.header.ty, FrameType::Goodbye);
4763            assert_eq!(reply.header.channel, channel);
4764            assert_eq!(reply.header.epoch, epoch);
4765            assert_eq!(reply.header.corr, 0);
4766            assert!(module_egress_rx.try_recv().is_err());
4767        }
4768
4769        // A GOODBYE from the module for a route the daemon already released
4770        // is not answered: the module is letting go already.
4771        router
4772            .route_for_connection(
4773                &module_ctx,
4774                route_frame(FrameType::Goodbye, pending.module_channel + 2, 1, 0),
4775            )
4776            .await
4777            .unwrap();
4778        assert!(module_egress_rx.try_recv().is_err());
4779
4780        let counters = router.counters.snapshot();
4781        assert_eq!(counters["module_frames_dropped_no_route"], 3);
4782        assert_eq!(counters["module_frames_dropped_released_route"], 1);
4783        assert_eq!(
4784            counters["module_frames_dropped_released_route_by_module"],
4785            serde_json::json!({ "epoch-router": 1 })
4786        );
4787        assert_eq!(counters["module_orphan_route_goodbyes_sent"], 2);
4788    }
4789
4790    /// A chatty orphan (a streaming module still producing on a route it
4791    /// missed the GOODBYE for) is answered once per interval, not once per
4792    /// frame, and answered again once the interval has passed.
4793    #[tokio::test(start_paused = true)]
4794    async fn burst_of_orphan_module_frames_is_answered_once_per_interval() {
4795        let (
4796            router,
4797            _forwarding,
4798            client_ctx,
4799            mut client_rx,
4800            module_ctx,
4801            mut module_egress_rx,
4802            mut module_rx,
4803            pending,
4804        ) = dynamic_route_fixture(true);
4805        let _ = client_rx.recv().await.unwrap();
4806        router
4807            .route_for_connection(
4808                &client_ctx,
4809                route_frame(
4810                    FrameType::Goodbye,
4811                    pending.client_channel,
4812                    pending.client_epoch,
4813                    1_300,
4814                ),
4815            )
4816            .await
4817            .unwrap();
4818        drain_now(&mut module_rx);
4819
4820        let send_burst = |corr: u64| {
4821            route_frame(
4822                FrameType::StreamData,
4823                pending.module_channel,
4824                pending.module_epoch,
4825                corr,
4826            )
4827        };
4828        for corr in 0..20 {
4829            router
4830                .route_for_connection(&module_ctx, send_burst(corr))
4831                .await
4832                .unwrap();
4833        }
4834        let mut replies = 0;
4835        while let Ok(reply) = module_egress_rx.try_recv() {
4836            assert_eq!(reply.header.ty, FrameType::Goodbye);
4837            replies += 1;
4838        }
4839        assert_eq!(replies, 1, "a burst within the interval gets one GOODBYE");
4840
4841        tokio::time::advance(ORPHAN_ROUTE_GOODBYE_INTERVAL).await;
4842        router
4843            .route_for_connection(&module_ctx, send_burst(20))
4844            .await
4845            .unwrap();
4846        let retry = module_egress_rx
4847            .try_recv()
4848            .expect("the first orphan frame after the interval is answered again");
4849        assert_eq!(retry.header.channel, pending.module_channel);
4850        assert_eq!(retry.header.epoch, pending.module_epoch);
4851
4852        let counters = router.counters.snapshot();
4853        assert_eq!(counters["module_frames_dropped_no_route"], 21);
4854        assert_eq!(counters["module_orphan_route_goodbyes_sent"], 2);
4855    }
4856
4857    /// The rate-limit memory is per connection and goes away with it.
4858    #[test]
4859    fn orphan_goodbye_rate_limit_state_is_released_with_the_connection() {
4860        let router = Router::with_default_self_handler();
4861        let connection = router.begin_connection();
4862        let id = connection.id();
4863        assert!(router.orphan_goodbyes.claim(id, 7));
4864        assert!(!router.orphan_goodbyes.claim(id, 7));
4865        assert!(router.orphan_goodbyes.claim(id, 8));
4866        drop(connection);
4867        assert!(router
4868            .orphan_goodbyes
4869            .last_sent
4870            .lock()
4871            .unwrap()
4872            .get(&id)
4873            .is_none());
4874    }
4875
4876    #[test]
4877    fn channel_zero_cannot_be_registered_as_backend() {
4878        let mut router = Router::with_default_self_handler();
4879
4880        let err = router.register_backend(0, EchoBackend).unwrap_err();
4881
4882        assert_eq!(err, RouterError::ReservedChannelZero);
4883    }
4884}