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_route_opener(
1042        &self,
1043        connection: ConnectionId,
1044        opener: crate::control::RouteOpenerConnection,
1045    ) {
1046        self.control.record_route_opener(connection, opener);
1047    }
1048
1049    /// Reserve an `activity.subscribe` correlation before the reader hands the
1050    /// request to a task; hold the result for the task's lifetime.
1051    pub(crate) fn reserve_activity_subscription(
1052        &self,
1053        ctx: &RouteCtx,
1054        frame: &Frame,
1055    ) -> Option<impl Send + 'static> {
1056        self.control
1057            .reserve_activity_subscription(ctx.connection_id, frame)
1058    }
1059
1060    pub(crate) fn record_captured_peer(
1061        &self,
1062        connection: ConnectionId,
1063        peer: subc_os::local_peer::CapturedPeer,
1064    ) {
1065        self.control.record_captured_peer(connection, peer);
1066    }
1067
1068    pub(crate) fn record_caller_endpoints(
1069        &self,
1070        connection: ConnectionId,
1071        endpoints: Option<(std::net::SocketAddr, std::net::SocketAddr)>,
1072    ) {
1073        self.control.record_caller_endpoints(connection, endpoints);
1074    }
1075
1076    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
1077        self.control.defers_privileged_control(ctx, frame)
1078    }
1079
1080    pub(crate) fn defers_config_approval(&self, frame: &Frame) -> bool {
1081        self.control.defers_config_approval(frame)
1082    }
1083
1084    pub(crate) fn reserve_config_approval(
1085        &self,
1086        ctx: &RouteCtx,
1087        frame: &Frame,
1088    ) -> Result<
1089        Option<crate::config_gate::runtime::ApprovalRequestGuard>,
1090        crate::config_gate::GateError,
1091    > {
1092        self.control.reserve_config_approval(ctx, frame)
1093    }
1094
1095    pub(crate) fn route_open_capacity_refusal(
1096        &self,
1097        ctx: &RouteCtx,
1098        frame: &Frame,
1099        target_module_id: &str,
1100        in_flight: usize,
1101        limit: usize,
1102    ) -> Result<Frame, RouterError> {
1103        self.control
1104            .route_open_capacity_refusal(ctx, frame, target_module_id, in_flight, limit)
1105    }
1106
1107    pub async fn route_for_connection(
1108        &self,
1109        ctx: &RouteCtx,
1110        frame: Frame,
1111    ) -> Result<(), RouterError> {
1112        self.route_for_connection_started(ctx, frame, None).await
1113    }
1114
1115    pub(crate) async fn observe_connection_wait<F: std::future::Future>(
1116        &self,
1117        ctx: &RouteCtx,
1118        kind: &'static str,
1119        future: F,
1120    ) -> F::Output {
1121        self.counters
1122            .observe_reader_wait(
1123                || {
1124                    let module = self
1125                        .forwarding
1126                        .module_id_for_connection(ctx.connection_id)
1127                        .ok()
1128                        .flatten();
1129                    let principal = if module.is_some() { "module" } else { "direct" };
1130                    (
1131                        module.unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
1132                        principal.into(),
1133                    )
1134                },
1135                kind,
1136                future,
1137            )
1138            .await
1139    }
1140
1141    pub(crate) async fn route_for_connection_started(
1142        &self,
1143        ctx: &RouteCtx,
1144        frame: Frame,
1145        dispatch_started_at: Option<Instant>,
1146    ) -> Result<(), RouterError> {
1147        // Embedded callers have no socket reader; mark at their ingress instead.
1148        let first = ctx.egress.first_ingress_frame();
1149        self.route_for_connection_ingress(ctx, frame, dispatch_started_at, first)
1150            .await
1151    }
1152
1153    pub(crate) async fn route_for_connection_ingress(
1154        &self,
1155        ctx: &RouteCtx,
1156        frame: Frame,
1157        dispatch_started_at: Option<Instant>,
1158        first: bool,
1159    ) -> Result<(), RouterError> {
1160        if ctx.egress.ingress_terminal() {
1161            return Ok(());
1162        }
1163        let channel = frame.header.channel;
1164        let epoch = frame.header.epoch;
1165        let corr = frame.header.corr;
1166        if channel == 0 {
1167            debug!(
1168                connection_id = ctx.connection_id.get(),
1169                corr,
1170                frame_type = ?frame.header.ty,
1171                "routing control frame"
1172            );
1173            // The connection loop dispatches every control operation directly
1174            // except `route.open`, activity writes, held config approvals and
1175            // privileged requests. Each
1176            // task passes a timestamp captured before
1177            // spawn, so slow-dispatch timing includes scheduler delay but no
1178            // wait in an application-owned queue.
1179            let dispatch_started_at = (frame.header.ty == FrameType::Request)
1180                .then(|| dispatch_started_at.unwrap_or_else(Instant::now));
1181            // Only review-producing requests need the post-flush receipt hook.
1182            // Probing every response would scan large catalog bodies again.
1183            let review_request = self.control.config_desktop_review_request(&frame);
1184            let responses = self
1185                .control
1186                .handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
1187                .await?;
1188            for response in responses {
1189                let view = if review_request {
1190                    self.control
1191                        .config_desktop_review_response(ctx.connection_id, &response)
1192                        .await
1193                } else {
1194                    None
1195                };
1196                if let Some(view) = view {
1197                    self.observe_connection_wait(
1198                        ctx,
1199                        "reply_egress",
1200                        self.control
1201                            .deliver_config_desktop_review(ctx, response, view),
1202                    )
1203                    .await?;
1204                    continue;
1205                }
1206                self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(response))
1207                    .await?;
1208            }
1209            return Ok(());
1210        }
1211
1212        let data_route = self
1213            .forwarding
1214            .lookup_data_route(ctx.connection_id, channel, epoch)
1215            .map_err(RouterError::Forwarding)?;
1216
1217        match data_route {
1218            DataRoute::Module(DataRouteState::EpochMismatch) => {
1219                self.forwarding.warn_frame_drop(
1220                    ctx.connection_id,
1221                    channel,
1222                    epoch,
1223                    "module_to_client",
1224                    "stale_epoch",
1225                );
1226                if frame.header.ty == FrameType::Request {
1227                    self.counters
1228                        .increment_module_requests_dropped_stale_route();
1229                    let err = RouterError::StaleRouteEpoch {
1230                        channel,
1231                        epoch,
1232                        corr,
1233                    };
1234                    if let Some(error_frame) = err.to_error_frame() {
1235                        self.observe_connection_wait(
1236                            ctx,
1237                            "reply_egress",
1238                            ctx.egress.send(error_frame),
1239                        )
1240                        .await?;
1241                    }
1242                } else {
1243                    self.handle_orphan_module_frame(ctx, &frame)?;
1244                }
1245                debug!(
1246                    connection_id = ctx.connection_id.get(),
1247                    channel, epoch, corr, "dropping module frame for stale route epoch"
1248                );
1249                return Ok(());
1250            }
1251            DataRoute::Module(DataRouteState::Reserved) => {
1252                self.forwarding.warn_frame_drop(
1253                    ctx.connection_id,
1254                    channel,
1255                    epoch,
1256                    "module_to_client",
1257                    "missing_binding",
1258                );
1259                if frame.header.ty == FrameType::Request {
1260                    self.counters
1261                        .increment_module_requests_dropped_stale_route();
1262                    let err = RouterError::UnknownChannel {
1263                        channel,
1264                        epoch,
1265                        corr,
1266                    };
1267                    if let Some(error_frame) = err.to_error_frame() {
1268                        self.observe_connection_wait(
1269                            ctx,
1270                            "reply_egress",
1271                            ctx.egress.send(error_frame),
1272                        )
1273                        .await?;
1274                    }
1275                } else {
1276                    self.record_module_frame_drop(ctx.connection_id)?;
1277                }
1278                debug!(
1279                    connection_id = ctx.connection_id.get(),
1280                    channel, epoch, corr, "dropping module frame for reserved route handle"
1281                );
1282                return Ok(());
1283            }
1284            DataRoute::Module(DataRouteState::Absent) => {
1285                self.forwarding.warn_frame_drop(
1286                    ctx.connection_id,
1287                    channel,
1288                    epoch,
1289                    "module_to_client",
1290                    "unknown_channel",
1291                );
1292                if frame.header.ty == FrameType::Request {
1293                    self.counters
1294                        .increment_module_requests_dropped_stale_route();
1295                    let err = RouterError::UnknownChannel {
1296                        channel,
1297                        epoch,
1298                        corr,
1299                    };
1300                    if let Some(error_frame) = err.to_error_frame() {
1301                        self.observe_connection_wait(
1302                            ctx,
1303                            "reply_egress",
1304                            ctx.egress.send(error_frame),
1305                        )
1306                        .await?;
1307                    }
1308                } else {
1309                    self.handle_orphan_module_frame(ctx, &frame)?;
1310                }
1311                debug!(
1312                    connection_id = ctx.connection_id.get(),
1313                    channel, epoch, corr, "dropping module frame for absent route handle"
1314                );
1315                return Ok(());
1316            }
1317            DataRoute::Module(DataRouteState::Bound(route)) => {
1318                if frame.header.ty == FrameType::Goodbye {
1319                    if let RouteRelease::Removed(target) = self
1320                        .forwarding
1321                        .release_module_route(ctx.connection_id, channel, epoch)
1322                        .map_err(RouterError::Forwarding)?
1323                    {
1324                        let mut goodbye = frame;
1325                        goodbye.header.channel = target.channel;
1326                        goodbye.header.epoch = target.epoch;
1327                        // A module must never be able to make a frame look
1328                        // daemon-authored, so the origin bit is cleared on
1329                        // every module frame relayed to a client.
1330                        goodbye.header.flags = goodbye.header.flags.without_daemon_origin();
1331                        if let Err(err) = self
1332                            .observe_connection_wait(
1333                                ctx,
1334                                "module_to_client",
1335                                target.sink.send_to_client(goodbye),
1336                            )
1337                            .await
1338                        {
1339                            if !target.close_on_delivery_failure() {
1340                                self.forwarding.warn_frame_drop(
1341                                    target.connection_id,
1342                                    target.channel,
1343                                    target.epoch,
1344                                    "module_to_client",
1345                                    err.diagnosis.cause,
1346                                );
1347                            }
1348                            if target.close_on_delivery_failure()
1349                                && self
1350                                    .forwarding
1351                                    .escalate_client_delivery_failure_diagnosed(
1352                                        target.connection_id,
1353                                        target.channel,
1354                                        target.epoch,
1355                                        CloseReason::new(
1356                                            "route_goodbye_delivery_failed",
1357                                            format!(
1358                                                "failed to enqueue route GOODBYE for client channel {}: {err}",
1359                                                target.channel
1360                                            ),
1361                                        ),
1362                                        UndeliveredFrame {
1363                                            module_id: Some(&route.module_id),
1364                                            sink: &target.sink,
1365                                        },
1366                                        Some(&err.diagnosis),
1367                                    )
1368                                    .map_err(RouterError::Forwarding)?
1369                            {
1370                                self.counters.increment_goodbye_relay_client_failed();
1371                            }
1372                        }
1373                    } else {
1374                        self.forwarding.warn_frame_drop(
1375                            ctx.connection_id,
1376                            channel,
1377                            epoch,
1378                            "module_to_client",
1379                            "missing_binding",
1380                        );
1381                    }
1382                    return Ok(());
1383                }
1384
1385                // A request whose client delivery already ended with
1386                // frame_too_large is still running at the module; its frames
1387                // are dropped here until its terminal releases the credit.
1388                if frame.header.ty != FrameType::Request
1389                    && route
1390                        .flow
1391                        .drop_refused_frame(corr, is_terminal_frame(frame.header.ty))
1392                {
1393                    return Ok(());
1394                }
1395
1396                // Accounting allows an oversized frame to occupy an empty queue
1397                // on other send paths. Refuse it at this splice before admission,
1398                // so the next ordinary reply cannot close a multiplexed client.
1399                let bytes = queued_frame_bytes(&frame);
1400                let limit = route.client_sink.accounting.byte_budget;
1401                if bytes > limit {
1402                    let ty = frame.header.ty;
1403                    let flags = frame.header.flags;
1404                    drop(frame);
1405                    return self
1406                        .refuse_oversized_module_frame(ctx, &route, (ty, flags), corr, bytes)
1407                        .await;
1408                }
1409
1410                // A terminal frame ends the request at the module. Its credit
1411                // is retired once the reply is on the client's queue, or once
1412                // the bounded send has failed and the delivery-failure path
1413                // below owns settlement, but not while the reply still waits
1414                // for room: a restart drain must not report quiescence and
1415                // close the route ahead of the final reply.
1416                let releases_credit = is_terminal_frame(frame.header.ty);
1417                let mut frame = frame;
1418                frame.header.channel = route.client_channel;
1419                frame.header.epoch = route.client_epoch;
1420                // Responses, errors, stream data and ends, and reverse
1421                // requests all pass through here. A module must never be able
1422                // to make a frame look daemon-authored, so the origin bit a
1423                // module may have set is cleared; every other flag bit and
1424                // the body travel unchanged.
1425                frame.header.flags = frame.header.flags.without_daemon_origin();
1426                let delivered = self
1427                    .counters
1428                    .observe_reader_wait(
1429                        || (route.module_id.clone(), principal_label(&route.principal)),
1430                        "module_to_client",
1431                        route.client_sink.send_to_client(frame),
1432                    )
1433                    .await;
1434                // On a failure, the credit is retired only after the escalation
1435                // has marked the client closing, so a drain cannot see the
1436                // request finished before the delivery-failure path owns it.
1437                let escalated = match &delivered {
1438                    Ok(()) => Ok(false),
1439                    Err(err) => self.forwarding.escalate_client_delivery_failure_diagnosed(
1440                        route.client_connection_id,
1441                        route.client_channel,
1442                        route.client_epoch,
1443                        CloseReason::new(
1444                            "module_to_client_delivery_failed",
1445                            format!(
1446                                "failed to enqueue module frame for client channel {} corr {corr}: {err}",
1447                                route.client_channel
1448                            ),
1449                        ),
1450                        UndeliveredFrame {
1451                            module_id: Some(&route.module_id),
1452                            sink: &route.client_sink,
1453                        },
1454                        Some(&err.diagnosis),
1455                    ),
1456                };
1457                if releases_credit {
1458                    route.flow.release_corr(corr);
1459                }
1460                if escalated.map_err(RouterError::Forwarding)? {
1461                    self.counters
1462                        .increment_client_egress_close_delivery_failed();
1463                }
1464                return Ok(());
1465            }
1466            DataRoute::Client(DataRouteState::EpochMismatch) => {
1467                self.forwarding.warn_frame_drop(
1468                    ctx.connection_id,
1469                    channel,
1470                    epoch,
1471                    "client_to_module",
1472                    "stale_epoch",
1473                );
1474                if frame.header.ty == FrameType::Request {
1475                    self.counters.increment_client_frames_dropped_stale_route();
1476                    // Dropped before forwarding; a re-bind retry cannot double-execute this request.
1477                    let err = RouterError::StaleRouteEpoch {
1478                        channel,
1479                        epoch,
1480                        corr,
1481                    };
1482                    if let Some(error_frame) = err.to_error_frame() {
1483                        self.observe_connection_wait(
1484                            ctx,
1485                            "reply_egress",
1486                            ctx.egress.send(error_frame),
1487                        )
1488                        .await?;
1489                    }
1490                }
1491                debug!(
1492                    connection_id = ctx.connection_id.get(),
1493                    channel, epoch, corr, "dropping client frame for stale route epoch"
1494                );
1495                return Ok(());
1496            }
1497            DataRoute::Client(DataRouteState::Reserved) => {
1498                self.forwarding.warn_frame_drop(
1499                    ctx.connection_id,
1500                    channel,
1501                    epoch,
1502                    "client_to_module",
1503                    "missing_binding",
1504                );
1505                if frame.header.ty == FrameType::Request {
1506                    let err = RouterError::UnknownChannel {
1507                        channel,
1508                        epoch,
1509                        corr,
1510                    };
1511                    if let Some(error_frame) = err.to_error_frame() {
1512                        self.observe_connection_wait(
1513                            ctx,
1514                            "reply_egress",
1515                            ctx.egress.send(error_frame),
1516                        )
1517                        .await?;
1518                    }
1519                }
1520                return Ok(());
1521            }
1522            DataRoute::Client(DataRouteState::Bound(route)) => {
1523                if frame.header.ty == FrameType::Goodbye {
1524                    let _ = self
1525                        .control
1526                        .handle_route_goodbye(ctx.connection_id, channel, epoch)?;
1527                    return Ok(());
1528                }
1529                return self.forward_backend.handle_bound(frame, route).await;
1530            }
1531            DataRoute::Client(DataRouteState::Absent) => {}
1532        }
1533
1534        if let Some(backend) = self.backends.get(&channel) {
1535            return backend.handle(ctx.clone(), frame).await.inspect_err(|_| {
1536                self.forwarding.warn_frame_drop(
1537                    ctx.connection_id,
1538                    channel,
1539                    epoch,
1540                    "client_to_backend",
1541                    "endpoint_gone",
1542                );
1543            });
1544        }
1545        self.forwarding.warn_frame_drop(
1546            ctx.connection_id,
1547            channel,
1548            epoch,
1549            "client_to_module",
1550            "unknown_channel",
1551        );
1552        if frame.header.ty == FrameType::Request {
1553            let err = RouterError::UnknownChannel {
1554                channel,
1555                epoch,
1556                corr,
1557            };
1558            if let Some(error_frame) = err.to_error_frame() {
1559                self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(error_frame))
1560                    .await?;
1561            }
1562        }
1563        Ok(())
1564    }
1565
1566    async fn refuse_oversized_module_frame(
1567        &self,
1568        ctx: &RouteCtx,
1569        route: &RouteBinding,
1570        header: (FrameType, Flags),
1571        corr: u64,
1572        bytes: usize,
1573    ) -> Result<(), RouterError> {
1574        let (ty, flags) = header;
1575        let limit = route.client_sink.accounting.byte_budget;
1576        if ty == FrameType::Push {
1577            // Deployed Rust clients cannot decode a new route.closed reason.
1578            // Until that vocabulary can be extended compatibly, an oversized
1579            // unsolicited push still closes the connection, with its cause named.
1580            let diagnosis = ClientDeliveryDiagnosis {
1581                frame_type: ty,
1582                flags,
1583                cause: "frame_too_large",
1584            };
1585            if self
1586                .forwarding
1587                .escalate_client_delivery_failure_diagnosed(
1588                    route.client_connection_id,
1589                    route.client_channel,
1590                    route.client_epoch,
1591                    CloseReason::new(
1592                        error_codes::FRAME_TOO_LARGE,
1593                        format!(
1594                            "oversized push: size={bytes} limit={limit} (header plus body bytes)"
1595                        ),
1596                    ),
1597                    UndeliveredFrame {
1598                        module_id: Some(&route.module_id),
1599                        sink: &route.client_sink,
1600                    },
1601                    Some(&diagnosis),
1602                )
1603                .map_err(RouterError::Forwarding)?
1604            {
1605                self.counters
1606                    .increment_client_egress_close_delivery_failed();
1607            }
1608            return Ok(());
1609        }
1610
1611        warn!(
1612            connection_id = route.client_connection_id.get(),
1613            module_id = %route.module_id,
1614            client_principal = %principal_label(&route.principal),
1615            client_channel = route.client_channel,
1616            frame_type = ?ty,
1617            frame_bytes = bytes,
1618            byte_limit = limit,
1619            "refusing oversized module-to-client frame with ERROR frame_too_large"
1620        );
1621        if ty == FrameType::Request {
1622            // A reverse request belongs to the module, not to a waiting client.
1623            // Answer its sender without forwarding any part of it to the client.
1624            let error = frame_too_large_error(
1625                route.module_channel,
1626                route.module_epoch,
1627                corr,
1628                bytes,
1629                limit,
1630            )?;
1631            self.observe_connection_wait(ctx, "reply_egress", ctx.egress.send(error))
1632                .await?;
1633        } else {
1634            let terminal = is_terminal_frame(ty);
1635            if !terminal {
1636                // A refused stream chunk ends the request for the client only:
1637                // the module is still running it, so it keeps its credit, its
1638                // later frames are dropped, and the module is asked to stop.
1639                route.flow.refuse_client_delivery(corr);
1640                self.cancel_refused_module_request(route, corr);
1641            }
1642            let error = frame_too_large_error(
1643                route.client_channel,
1644                route.client_epoch,
1645                corr,
1646                bytes,
1647                limit,
1648            )?;
1649            // The replacement shares the reply's bounded burst grace, so a
1650            // stopped client cannot indefinitely stall the module frame reader.
1651            let delivered = self
1652                .counters
1653                .observe_reader_wait(
1654                    || (route.module_id.clone(), principal_label(&route.principal)),
1655                    "module_to_client",
1656                    route.client_sink.send_to_client(error),
1657                )
1658                .await;
1659            let escalated = match &delivered {
1660                Ok(()) => Ok(false),
1661                Err(err) => self.forwarding.escalate_client_delivery_failure_diagnosed(
1662                    route.client_connection_id,
1663                    route.client_channel,
1664                    route.client_epoch,
1665                    CloseReason::new(
1666                        "module_to_client_delivery_failed",
1667                        format!(
1668                            "failed to enqueue frame_too_large for client channel {} corr {corr}: {err}",
1669                            route.client_channel
1670                        ),
1671                    ),
1672                    UndeliveredFrame {
1673                        module_id: Some(&route.module_id),
1674                        sink: &route.client_sink,
1675                    },
1676                    Some(&err.diagnosis),
1677                ),
1678            };
1679            if terminal {
1680                // A refused terminal also ended the request at the module. Its
1681                // credit is retired once the replacement is queued, or once
1682                // its send has failed and the escalation above owns it, as for
1683                // a delivered terminal.
1684                route.flow.release_corr(corr);
1685            }
1686            if escalated.map_err(RouterError::Forwarding)? {
1687                self.counters
1688                    .increment_client_egress_close_delivery_failed();
1689            }
1690        }
1691        Ok(())
1692    }
1693
1694    /// Ask the module to stop a request whose client delivery was refused. The
1695    /// CANCEL is best effort and never waits: the module's own reader must not
1696    /// stall on that module's egress, and the request keeps its credit either
1697    /// way until the module's terminal arrives.
1698    fn cancel_refused_module_request(&self, route: &RouteBinding, corr: u64) {
1699        let cancel = Frame::build_with_version(
1700            route.module_negotiated_ver,
1701            FrameType::Cancel,
1702            Flags::new(false, Priority::Passive, false),
1703            route.module_channel,
1704            route.module_epoch,
1705            corr,
1706            Vec::new(),
1707        );
1708        let sent = cancel.map_err(|err| err.to_string()).and_then(|cancel| {
1709            route
1710                .module_sink
1711                .try_send(cancel)
1712                .map_err(|err| err.to_string())
1713        });
1714        if let Err(error) = sent {
1715            warn!(
1716                module_id = %route.module_id,
1717                module_channel = route.module_channel,
1718                corr,
1719                %error,
1720                "could not send CANCEL for a request whose stream chunk was refused as too large"
1721            );
1722        }
1723    }
1724}
1725
1726impl Default for Router {
1727    fn default() -> Self {
1728        Self::with_default_self_handler()
1729    }
1730}
1731
1732/// Connection-scoped cleanup guard returned by [`Router::begin_connection`].
1733#[must_use]
1734pub struct RouterConnection {
1735    id: ConnectionId,
1736    control_handler: Arc<ControlHandler>,
1737    forwarding: Arc<ForwardingTable>,
1738    close_receiver: Option<ConnectionCloseReceiver>,
1739    orphan_goodbyes: Arc<OrphanGoodbyeLimiter>,
1740}
1741
1742impl RouterConnection {
1743    pub fn id(&self) -> ConnectionId {
1744        self.id
1745    }
1746
1747    pub(crate) fn take_close_receiver(&mut self) -> ConnectionCloseReceiver {
1748        self.close_receiver
1749            .take()
1750            .expect("connection close receiver can only be taken once")
1751    }
1752}
1753
1754impl Drop for RouterConnection {
1755    fn drop(&mut self) {
1756        self.orphan_goodbyes.forget_connection(self.id);
1757        // GOODBYE (explicit) and connection-drop cleanup both call the same
1758        // idempotent deregistration path.
1759        let _ = self.control_handler.cleanup_connection(self.id);
1760        // The read loop and its tasks have ended, but the writer can still
1761        // drain. Keep the connection-to-launch association until pending relays
1762        // and routes are gone.
1763        self.forwarding.unregister_connection_close(self.id);
1764    }
1765}
1766
1767/// Minimal in-memory backend used by tests and early wiring: it emits a
1768/// `RESPONSE` on the same channel/correlation id with the exact same body bytes.
1769#[derive(Debug, Default, Clone, Copy)]
1770pub struct EchoBackend;
1771
1772impl EchoBackend {
1773    pub async fn handle(&self, ctx: RouteCtx, frame: Frame) -> Result<(), RouterError> {
1774        let response = Frame::build_with_version(
1775            frame.header.ver,
1776            FrameType::Response,
1777            frame.header.flags,
1778            frame.header.channel,
1779            frame.header.epoch,
1780            frame.header.corr,
1781            frame.body,
1782        )
1783        .map_err(RouterError::FrameBuild)?;
1784        ctx.egress.send(response).await
1785    }
1786}
1787
1788/// Data-plane backend that splices client frames to the module connection bound at attach time.
1789#[derive(Debug, Clone)]
1790pub struct ForwardBackend {
1791    forwarding: Arc<ForwardingTable>,
1792}
1793
1794impl ForwardBackend {
1795    pub fn new(forwarding: Arc<ForwardingTable>) -> Self {
1796        Self { forwarding }
1797    }
1798
1799    pub async fn handle(&self, ctx: RouteCtx, frame: Frame) -> Result<(), RouterError> {
1800        let channel = frame.header.channel;
1801        let corr = frame.header.corr;
1802        let route = match self
1803            .forwarding
1804            .lookup_data_route(ctx.connection_id, channel, frame.header.epoch)
1805            .map_err(RouterError::Forwarding)?
1806        {
1807            DataRoute::Client(DataRouteState::Bound(route)) => route,
1808            DataRoute::Client(_) | DataRoute::Module(_) => {
1809                self.forwarding.warn_frame_drop(
1810                    ctx.connection_id,
1811                    channel,
1812                    frame.header.epoch,
1813                    "client_to_module",
1814                    "missing_binding",
1815                );
1816                return Err(RouterError::UnknownChannel {
1817                    channel,
1818                    epoch: frame.header.epoch,
1819                    corr,
1820                });
1821            }
1822        };
1823        self.handle_bound(frame, route).await
1824    }
1825
1826    pub(crate) async fn handle_bound(
1827        &self,
1828        frame: Frame,
1829        route: Arc<RouteBinding>,
1830    ) -> Result<(), RouterError> {
1831        let channel = frame.header.channel;
1832        let corr = frame.header.corr;
1833        let frame_type = frame.header.ty;
1834
1835        // CANCEL and other non-REQUEST frames bypass the request-credit window;
1836        // the original request's credit is freed only by the module's terminal frame.
1837        let acquired_credit = frame_type == FrameType::Request;
1838        if acquired_credit && route.flow.busy_refusals() {
1839            use crate::forwarding::RequestAdmission;
1840            match self
1841                .forwarding
1842                .try_admit_request(
1843                    &route,
1844                    frame.header.epoch,
1845                    corr,
1846                    frame.header.flags.is_subscription(),
1847                )
1848                .map_err(RouterError::Forwarding)?
1849            {
1850                RequestAdmission::Admitted => {}
1851                RequestAdmission::Busy(detail) => {
1852                    let principal = principal_label(&route.principal);
1853                    let counters = self.forwarding.counters_ref();
1854                    counters.increment_route_busy(&route.module_id, &principal);
1855                    if route.flow.should_warn_busy() {
1856                        warn!(module_id = %route.module_id, client_principal = %principal, client_channel = channel,
1857                            route_epoch = route.client_epoch, ?detail, "request refused: route_busy");
1858                    }
1859                    let error = RouterError::RouteBusy {
1860                        channel,
1861                        epoch: frame.header.epoch,
1862                        corr,
1863                        detail: Box::new(detail),
1864                    };
1865                    let refusal = error
1866                        .to_error_frame()
1867                        .expect("route_busy is a serializable wire error");
1868                    counters
1869                        .observe_reader_wait(
1870                            || (route.module_id.clone(), principal),
1871                            "route_busy_egress",
1872                            route.client_sink.send(refusal),
1873                        )
1874                        .await?;
1875                    return Ok(());
1876                }
1877                RequestAdmission::ModuleReloading => {
1878                    return Err(RouterError::route_error_with_epoch(
1879                        channel,
1880                        frame.header.epoch,
1881                        corr,
1882                        error_codes::MODULE_RELOADING,
1883                        format!("module endpoint for route channel {channel} is reloading"),
1884                    ));
1885                }
1886                RequestAdmission::Stale => {
1887                    return Err(RouterError::StaleRouteEpoch {
1888                        channel,
1889                        epoch: frame.header.epoch,
1890                        corr,
1891                    })
1892                }
1893            }
1894        } else if !route.flow.busy_refusals() {
1895            // A legacy route queues a request that must wait for credit
1896            // instead of parking the connection reader on it.
1897            return self.offer_to_legacy_route(frame, route).await;
1898        }
1899        self.forward_to_module(frame, &route, acquired_credit).await
1900    }
1901
1902    /// Put a client frame on the module's queue. A frame that holds a request
1903    /// credit (`credited`) gives it back if it cannot be queued.
1904    async fn forward_to_module(
1905        &self,
1906        frame: Frame,
1907        route: &RouteBinding,
1908        credited: bool,
1909    ) -> Result<(), RouterError> {
1910        let channel = frame.header.channel;
1911        let corr = frame.header.corr;
1912        let mut frame = frame;
1913        frame.header.channel = route.module_channel;
1914        frame.header.epoch = route.module_epoch;
1915        // The origin bit is the daemon's own signal to clients. A client
1916        // frame carrying it must not reach a module appearing daemon-authored,
1917        // so it is cleared here; every other flag bit travels unchanged.
1918        frame.header.flags = frame.header.flags.without_daemon_origin();
1919        let counters = self.forwarding.counters_ref();
1920        let result = counters
1921            .observe_reader_wait(
1922                || (route.module_id.clone(), principal_label(&route.principal)),
1923                "module_queue",
1924                route.module_sink.send(frame),
1925            )
1926            .await
1927            .map_err(|err| {
1928                self.forwarding.warn_frame_drop(
1929                    route.client_connection_id,
1930                    channel,
1931                    route.client_epoch,
1932                    "client_to_module",
1933                    "endpoint_gone",
1934                );
1935                RouterError::backend_with_epoch(channel, route.client_epoch, corr, err.to_string())
1936            });
1937        if credited && result.is_err() {
1938            route.flow.release_corr(corr);
1939        }
1940        result
1941    }
1942}
1943
1944#[path = "router_legacy_waiting.rs"]
1945mod legacy_waiting;
1946
1947fn is_terminal_frame(frame_type: FrameType) -> bool {
1948    matches!(
1949        frame_type,
1950        FrameType::Response | FrameType::Error | FrameType::StreamEnd
1951    )
1952}
1953
1954/// Typed router errors. Routable failures can be translated to canonical JSON
1955/// `ERROR` frames with [`RouterError::to_error_frame`].
1956#[derive(Debug, Clone, PartialEq, Eq)]
1957pub enum RouterError {
1958    ReservedChannelZero,
1959    DuplicateChannel {
1960        channel: u16,
1961    },
1962    UnknownChannel {
1963        channel: u16,
1964        epoch: u32,
1965        corr: u64,
1966    },
1967    StaleRouteEpoch {
1968        channel: u16,
1969        epoch: u32,
1970        corr: u64,
1971    },
1972    RouteBusy {
1973        channel: u16,
1974        epoch: u32,
1975        corr: u64,
1976        detail: Box<subc_protocol::RouteBusyDetail>,
1977    },
1978    Backend {
1979        channel: u16,
1980        epoch: u32,
1981        corr: u64,
1982        message: String,
1983    },
1984    RouteError {
1985        channel: u16,
1986        epoch: u32,
1987        corr: u64,
1988        code: String,
1989        message: String,
1990    },
1991    FrameBuild(FrameBuildError),
1992    Forwarding(ForwardingError),
1993}
1994
1995impl RouterError {
1996    pub fn backend(channel: u16, corr: u64, message: impl Into<String>) -> Self {
1997        Self::backend_with_epoch(channel, 0, corr, message)
1998    }
1999
2000    pub fn backend_with_epoch(
2001        channel: u16,
2002        epoch: u32,
2003        corr: u64,
2004        message: impl Into<String>,
2005    ) -> Self {
2006        Self::Backend {
2007            channel,
2008            epoch,
2009            corr,
2010            message: message.into(),
2011        }
2012    }
2013
2014    pub fn route_error(
2015        channel: u16,
2016        corr: u64,
2017        code: impl Into<String>,
2018        message: impl Into<String>,
2019    ) -> Self {
2020        Self::route_error_with_epoch(channel, 0, corr, code, message)
2021    }
2022
2023    pub fn route_error_with_epoch(
2024        channel: u16,
2025        epoch: u32,
2026        corr: u64,
2027        code: impl Into<String>,
2028        message: impl Into<String>,
2029    ) -> Self {
2030        Self::RouteError {
2031            channel,
2032            epoch,
2033            corr,
2034            code: code.into(),
2035            message: message.into(),
2036        }
2037    }
2038
2039    /// Translate route failures that belong on the wire into an `ERROR` frame.
2040    pub fn to_error_frame(&self) -> Option<Frame> {
2041        match self {
2042            Self::RouteBusy {
2043                channel,
2044                epoch,
2045                corr,
2046                detail,
2047            } => {
2048                let body = serde_json::to_vec(&ErrorBody {
2049                    code: error_codes::ROUTE_BUSY.into(),
2050                    message: "route has no free request or watch credit; retry on the same route"
2051                        .into(),
2052                    detail: Some(serde_json::to_value(detail).ok()?),
2053                })
2054                .ok()?;
2055                Frame::build(
2056                    FrameType::Error,
2057                    daemon_error_flags(),
2058                    *channel,
2059                    *epoch,
2060                    *corr,
2061                    body,
2062                )
2063                .ok()
2064            }
2065            Self::UnknownChannel {
2066                channel,
2067                epoch,
2068                corr,
2069            } => error_frame(
2070                *channel,
2071                *epoch,
2072                *corr,
2073                error_codes::UNKNOWN_CHANNEL,
2074                format!("unknown channel {channel}"),
2075            ),
2076            Self::StaleRouteEpoch {
2077                channel,
2078                epoch,
2079                corr,
2080            } => error_frame(
2081                *channel,
2082                *epoch,
2083                *corr,
2084                error_codes::STALE_ROUTE_EPOCH,
2085                format!("stale route epoch for channel {channel}"),
2086            ),
2087            Self::Backend {
2088                channel,
2089                epoch,
2090                corr,
2091                message,
2092            } => error_frame(*channel, *epoch, *corr, "backend_error", message.clone()),
2093            Self::RouteError {
2094                channel,
2095                epoch,
2096                corr,
2097                code,
2098                message,
2099            } => error_frame(*channel, *epoch, *corr, code, message.clone()),
2100            Self::ReservedChannelZero
2101            | Self::DuplicateChannel { .. }
2102            | Self::FrameBuild(_)
2103            | Self::Forwarding(_) => None,
2104        }
2105    }
2106}
2107
2108/// Flags for an ERROR frame the daemon authors itself.
2109///
2110/// Bit 6 (`FLAG_DAEMON_ORIGIN`) tells the client the daemon wrote this
2111/// error, never a module. What a code then proves is per code: on a bound
2112/// route the daemon writes `module_reloading`, `unknown_channel` and
2113/// `stale_route_epoch` only before forwarding, so with the bit they mean the
2114/// request was not delivered, while `frame_too_large` replaces a reply the
2115/// module already produced. Every daemon-authored ERROR goes through here;
2116/// frames a module sent keep their own flags with the bit cleared at the
2117/// splice.
2118/// Nothing else about the flags differs: passive priority, not binary, not last.
2119pub(crate) fn daemon_error_flags() -> Flags {
2120    Flags::new(false, Priority::Passive, false).with_daemon_origin()
2121}
2122
2123fn error_frame(channel: u16, epoch: u32, corr: u64, code: &str, message: String) -> Option<Frame> {
2124    let body = serde_json::to_vec(&ErrorBody {
2125        code: code.to_string(),
2126        message,
2127        detail: None,
2128    })
2129    .ok()?;
2130
2131    Frame::build(
2132        FrameType::Error,
2133        daemon_error_flags(),
2134        channel,
2135        epoch,
2136        corr,
2137        body,
2138    )
2139    .ok()
2140}
2141
2142fn frame_too_large_error(
2143    channel: u16,
2144    epoch: u32,
2145    corr: u64,
2146    bytes: usize,
2147    limit: usize,
2148) -> Result<Frame, RouterError> {
2149    let body = serde_json::to_vec(&ErrorBody {
2150        code: error_codes::FRAME_TOO_LARGE.to_string(),
2151        message: format!(
2152            "module frame of {bytes} bytes exceeds client egress limit of {limit} bytes"
2153        ),
2154        detail: Some(serde_json::json!({ "frame_bytes": bytes, "byte_limit": limit })),
2155    })
2156    .expect("serializing a frame size error");
2157    Frame::build(
2158        FrameType::Error,
2159        daemon_error_flags(),
2160        channel,
2161        epoch,
2162        corr,
2163        body,
2164    )
2165    .map_err(RouterError::FrameBuild)
2166}
2167
2168impl fmt::Display for RouterError {
2169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2170        match self {
2171            Self::ReservedChannelZero => write!(f, "channel 0 is reserved for subc"),
2172            Self::DuplicateChannel { channel } => {
2173                write!(f, "backend already registered for channel {channel}")
2174            }
2175            Self::UnknownChannel { channel, corr, .. } => {
2176                write!(f, "unknown channel {channel} for corr {corr}")
2177            }
2178            Self::StaleRouteEpoch { channel, corr, .. } => {
2179                write!(f, "stale route epoch for channel {channel} corr {corr}")
2180            }
2181            Self::RouteBusy { channel, corr, .. } => {
2182                write!(f, "route busy on channel {channel} corr {corr}")
2183            }
2184            Self::Backend {
2185                channel,
2186                corr,
2187                message,
2188                ..
2189            } => write!(
2190                f,
2191                "backend error on channel {channel} corr {corr}: {message}"
2192            ),
2193            Self::RouteError {
2194                channel,
2195                corr,
2196                code,
2197                message,
2198                ..
2199            } => write!(
2200                f,
2201                "route error {code} on channel {channel} corr {corr}: {message}"
2202            ),
2203            Self::FrameBuild(err) => write!(f, "failed to build routed frame: {err}"),
2204            Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
2205        }
2206    }
2207}
2208
2209impl Error for RouterError {
2210    fn source(&self) -> Option<&(dyn Error + 'static)> {
2211        match self {
2212            Self::FrameBuild(err) => Some(err),
2213            Self::Forwarding(err) => Some(err),
2214            Self::ReservedChannelZero
2215            | Self::DuplicateChannel { .. }
2216            | Self::UnknownChannel { .. }
2217            | Self::StaleRouteEpoch { .. }
2218            | Self::RouteBusy { .. }
2219            | Self::Backend { .. }
2220            | Self::RouteError { .. } => None,
2221        }
2222    }
2223}
2224
2225#[cfg(test)]
2226mod tests {
2227    include!("route_busy_router_tests.rs");
2228    use super::*;
2229    use crate::{
2230        forwarding::RouteBindRelayOutcome,
2231        supervise::{ModuleSpec, RestartPolicy, Supervisor, SupervisorHandle},
2232        ControlHandler, Registry,
2233    };
2234    use std::{
2235        sync::{mpsc as std_mpsc, Arc},
2236        time::Duration,
2237    };
2238    use subc_control::ModuleProtocol;
2239    use subc_protocol::{manifest::Concurrency, ErrorBody, Flags, FrameType, Priority};
2240    use tokio::sync::mpsc;
2241
2242    pub(crate) use crate::router::test_log::{captured_logs, log_capture};
2243
2244    fn logged_millis(logs: &str, field: &str) -> u64 {
2245        logs.split_whitespace()
2246            .find_map(|part| part.strip_prefix(field))
2247            .and_then(|value| value.parse().ok())
2248            .unwrap_or_else(|| panic!("missing numeric {field} in logs: {logs}"))
2249    }
2250
2251    fn request(channel: u16, corr: u64, body: &[u8]) -> Frame {
2252        Frame::build(
2253            FrameType::Request,
2254            Flags::new(true, Priority::Interactive, false),
2255            channel,
2256            0,
2257            corr,
2258            body.to_vec(),
2259        )
2260        .unwrap()
2261    }
2262
2263    fn ping(corr: u64) -> Frame {
2264        Frame::build(
2265            FrameType::Ping,
2266            Flags::new(false, Priority::Passive, false),
2267            0,
2268            0,
2269            corr,
2270            Vec::new(),
2271        )
2272        .unwrap()
2273    }
2274
2275    fn route_ctx() -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
2276        let (tx, rx) = mpsc::channel(8);
2277        (
2278            RouteCtx {
2279                connection_id: ConnectionId::LOCAL,
2280                egress: FrameSink::new(tx),
2281            },
2282            rx,
2283        )
2284    }
2285
2286    #[tokio::test]
2287    async fn retirement_egress_all_send_paths_drop_after_fence() {
2288        let (tx, mut rx) = mpsc::channel(8);
2289        let sink = FrameSink::new(tx);
2290        let reserved = sink.reserve_owned().await.unwrap();
2291        let immediate = sink.try_reserve_owned().unwrap();
2292        sink.terminate_egress();
2293        assert!(reserved.send(ping(1)));
2294        assert!(immediate.send(ping(2)));
2295        sink.send(ping(3)).await.unwrap();
2296        sink.try_send(ping(4)).unwrap();
2297        sink.send_to_client(ping(5)).await.unwrap();
2298        let queued = AtomicBool::new(false);
2299        assert!(sink
2300            .send_flushed_notifying_enqueue(ping(6), || queued.store(true, Ordering::Relaxed))
2301            .await
2302            .is_err());
2303        assert!(!queued.load(Ordering::Relaxed));
2304        assert!(sink.send_flushed(ping(7)).await.is_err());
2305        assert!(sink.reserve_owned().await.is_err());
2306        assert!(sink.try_reserve_owned().is_err());
2307        assert!(
2308            rx.try_recv().is_err(),
2309            "retired frames must not enter any writer queue"
2310        );
2311        assert_eq!(sink.backlog().queued_frames, 0);
2312        assert_eq!(sink.backlog().queued_bytes, 0);
2313    }
2314
2315    #[tokio::test]
2316    async fn retirement_egress_reservation_rechecks_after_slot_acquisition() {
2317        let (tx, mut rx) = mpsc::channel(1);
2318        let sink = FrameSink::new(tx);
2319        // Choose retirement after reserve returns its slot, not while waiting
2320        // on egress_stopped, so the final atomic recheck is exercised.
2321        sink.accounting
2322            .retire_after_reserve
2323            .store(true, Ordering::Relaxed);
2324        assert!(
2325            sink.reserve_owned().await.is_err(),
2326            "a slot acquired before retirement must not escape as a live reservation"
2327        );
2328        assert_eq!(
2329            sink.tx.capacity(),
2330            1,
2331            "refusal must release the reserved slot"
2332        );
2333        assert!(rx.try_recv().is_err());
2334    }
2335
2336    #[tokio::test]
2337    async fn retirement_egress_pending_budget_and_slot_sends_stop() {
2338        for budget in [1, usize::MAX] {
2339            let (tx, mut rx) = mpsc::channel(1);
2340            let sink = FrameSink::with_byte_budget(tx, budget);
2341            sink.try_send(ping(1)).unwrap();
2342            let sending = sink.send(ping(2));
2343            tokio::pin!(sending);
2344            assert!(poll_once(sending.as_mut()).await.is_pending());
2345            sink.terminate_egress();
2346            tokio::time::timeout(Duration::from_secs(2), sending)
2347                .await
2348                .unwrap()
2349                .unwrap();
2350            drop(rx.try_recv().unwrap());
2351            assert!(
2352                rx.try_recv().is_err(),
2353                "a send parked before retirement must not enqueue afterward"
2354            );
2355            assert_eq!(sink.backlog().queued_bytes, 0);
2356        }
2357    }
2358
2359    #[tokio::test]
2360    async fn retirement_egress_pending_flush_and_reservation_stop() {
2361        let (tx, mut rx) = mpsc::channel(1);
2362        let sink = FrameSink::new(tx);
2363        sink.try_send(ping(1)).unwrap();
2364        let queued = AtomicBool::new(false);
2365        let sending =
2366            sink.send_flushed_notifying_enqueue(ping(2), || queued.store(true, Ordering::Relaxed));
2367        let reserving = sink.reserve_owned();
2368        tokio::pin!(sending, reserving);
2369        assert!(poll_once(sending.as_mut()).await.is_pending());
2370        assert!(poll_once(reserving.as_mut()).await.is_pending());
2371        sink.terminate_egress();
2372        assert!(tokio::time::timeout(Duration::from_secs(2), sending)
2373            .await
2374            .unwrap()
2375            .is_err());
2376        assert!(tokio::time::timeout(Duration::from_secs(2), reserving)
2377            .await
2378            .unwrap()
2379            .is_err());
2380        assert!(!queued.load(Ordering::Relaxed));
2381        drop(rx.try_recv().unwrap());
2382        assert!(rx.try_recv().is_err());
2383        assert_eq!(sink.backlog().queued_bytes, 0);
2384    }
2385
2386    #[tokio::test]
2387    async fn echo_backend_returns_response_with_byte_identical_body() {
2388        let mut router = Router::with_default_self_handler();
2389        router.register_backend(7, EchoBackend).unwrap();
2390        let (ctx, mut rx) = route_ctx();
2391        let body = b"{not parsed}\0\xff";
2392
2393        router
2394            .route_for_connection(&ctx, request(7, 123, body))
2395            .await
2396            .unwrap();
2397        let response = rx.recv().await.unwrap();
2398
2399        assert_eq!(response.header.ty, FrameType::Response);
2400        assert_eq!(response.header.channel, 7);
2401        assert_eq!(response.header.corr, 123);
2402        assert_eq!(response.body, body);
2403        assert!(rx.try_recv().is_err());
2404    }
2405
2406    #[tokio::test]
2407    async fn unknown_channel_emits_canonical_error_frame() {
2408        let router = Router::with_default_self_handler();
2409        let (ctx, mut rx) = route_ctx();
2410
2411        router
2412            .route_for_connection(&ctx, request(99, 5, b"payload"))
2413            .await
2414            .unwrap();
2415        let error_frame = rx.recv().await.unwrap();
2416
2417        assert_eq!(error_frame.header.ty, FrameType::Error);
2418        assert_eq!(error_frame.header.channel, 99);
2419        assert_eq!(error_frame.header.corr, 5);
2420        let body: ErrorBody = serde_json::from_slice(&error_frame.body).unwrap();
2421        assert_eq!(body.code, "unknown_channel");
2422        assert_eq!(body.message, "unknown channel 99");
2423    }
2424
2425    /// Every ERROR the daemon authors carries the daemon-origin bit, so a
2426    /// client can tell a daemon refusal from a module's reply. Both the
2427    /// unknown-channel and the stale-epoch errors below are received on the
2428    /// client's own egress, not merely built.
2429    #[tokio::test]
2430    async fn daemon_authored_data_plane_errors_carry_daemon_origin() {
2431        let router = Router::with_default_self_handler();
2432        let (ctx, mut rx) = route_ctx();
2433        router
2434            .route_for_connection(&ctx, request(99, 5, b"payload"))
2435            .await
2436            .unwrap();
2437        let unknown = rx.recv().await.unwrap();
2438        assert_eq!(unknown.header.ty, FrameType::Error);
2439        let body: ErrorBody = serde_json::from_slice(&unknown.body).unwrap();
2440        assert_eq!(body.code, "unknown_channel");
2441        assert!(
2442            unknown.header.flags.is_daemon_origin(),
2443            "unknown_channel must carry daemon origin: {:?}",
2444            unknown.header.flags
2445        );
2446
2447        let (
2448            router,
2449            _forwarding,
2450            client_ctx,
2451            mut client_rx,
2452            _module_ctx,
2453            _module_egress_rx,
2454            _module_rx,
2455            pending,
2456        ) = dynamic_route_fixture(true);
2457        let _ = client_rx.recv().await;
2458        router
2459            .route_for_connection(
2460                &client_ctx,
2461                route_frame(
2462                    FrameType::Request,
2463                    pending.client_channel,
2464                    pending.client_epoch + 1,
2465                    702,
2466                ),
2467            )
2468            .await
2469            .unwrap();
2470        let stale = client_rx.recv().await.unwrap();
2471        assert_eq!(stale.header.ty, FrameType::Error);
2472        let body: ErrorBody = serde_json::from_slice(&stale.body).unwrap();
2473        assert_eq!(body.code, "stale_route_epoch");
2474        assert!(
2475            stale.header.flags.is_daemon_origin(),
2476            "stale_route_epoch must carry daemon origin: {:?}",
2477            stale.header.flags
2478        );
2479    }
2480
2481    /// A module ERROR that spoofs a daemon code with the daemon-origin bit
2482    /// set must reach the client with the bit cleared and the body
2483    /// byte-identical: the bit means the daemon wrote the frame, and a module
2484    /// must never be able to claim that.
2485    #[tokio::test]
2486    async fn module_error_with_daemon_bit_is_stripped_before_client_delivery() {
2487        let (
2488            router,
2489            _forwarding,
2490            client_ctx,
2491            mut client_rx,
2492            module_ctx,
2493            _module_egress_rx,
2494            mut module_rx,
2495            pending,
2496        ) = dynamic_route_fixture(true);
2497        let _ = client_rx.recv().await;
2498        // Open flow credit the way a real request would, so the terminal
2499        // error exercises the credit-release path too.
2500        router
2501            .route_for_connection(
2502                &client_ctx,
2503                route_frame(
2504                    FrameType::Request,
2505                    pending.client_channel,
2506                    pending.client_epoch,
2507                    701,
2508                ),
2509            )
2510            .await
2511            .unwrap();
2512        let _ = module_rx.recv().await;
2513
2514        let body = serde_json::to_vec(&ErrorBody::new("module_reloading", "try again")).unwrap();
2515        let spoof = Frame::build(
2516            FrameType::Error,
2517            Flags::new(false, Priority::Interactive, false).with_daemon_origin(),
2518            pending.module_channel,
2519            pending.module_epoch,
2520            701,
2521            body.clone(),
2522        )
2523        .unwrap();
2524        router
2525            .route_for_connection(&module_ctx, spoof)
2526            .await
2527            .unwrap();
2528        let delivered = client_rx.recv().await.unwrap();
2529        assert_eq!(delivered.header.ty, FrameType::Error);
2530        assert_eq!(delivered.header.channel, pending.client_channel);
2531        assert_eq!(delivered.header.epoch, pending.client_epoch);
2532        assert_eq!(delivered.header.corr, 701);
2533        assert!(
2534            !delivered.header.flags.is_daemon_origin(),
2535            "module-set daemon origin must be cleared: {:?}",
2536            delivered.header.flags
2537        );
2538        assert_eq!(delivered.body, body, "the body travels byte-identical");
2539    }
2540
2541    /// Clearing the origin bit strips exactly that bit: priority, LAST and
2542    /// subscription survive the splice unchanged.
2543    #[tokio::test]
2544    async fn module_response_with_daemon_bit_is_stripped_preserving_other_flags() {
2545        use subc_protocol::FLAG_SUBSCRIPTION;
2546        let (
2547            router,
2548            _forwarding,
2549            client_ctx,
2550            mut client_rx,
2551            module_ctx,
2552            _module_egress_rx,
2553            mut module_rx,
2554            pending,
2555        ) = dynamic_route_fixture(true);
2556        let _ = client_rx.recv().await;
2557        router
2558            .route_for_connection(
2559                &client_ctx,
2560                route_frame(
2561                    FrameType::Request,
2562                    pending.client_channel,
2563                    pending.client_epoch,
2564                    701,
2565                ),
2566            )
2567            .await
2568            .unwrap();
2569        let _ = module_rx.recv().await;
2570
2571        let sent_flags = Flags(
2572            Flags::new(true, Priority::Background, true).0
2573                | FLAG_SUBSCRIPTION
2574                | subc_protocol::FLAG_DAEMON_ORIGIN,
2575        );
2576        assert!(sent_flags.is_daemon_origin());
2577        let response = Frame::build(
2578            FrameType::Response,
2579            sent_flags,
2580            pending.module_channel,
2581            pending.module_epoch,
2582            701,
2583            b"route-body".to_vec(),
2584        )
2585        .unwrap();
2586        router
2587            .route_for_connection(&module_ctx, response)
2588            .await
2589            .unwrap();
2590        let delivered = client_rx.recv().await.unwrap();
2591        assert_eq!(delivered.header.ty, FrameType::Response);
2592        assert!(
2593            !delivered.header.flags.is_daemon_origin(),
2594            "module-set daemon origin must be cleared: {:?}",
2595            delivered.header.flags
2596        );
2597        assert!(
2598            delivered.header.flags.is_binary(),
2599            "binary flag must survive: {:?}",
2600            delivered.header.flags
2601        );
2602        assert!(
2603            delivered.header.flags.is_last(),
2604            "LAST flag must survive: {:?}",
2605            delivered.header.flags
2606        );
2607        assert!(
2608            delivered.header.flags.is_subscription(),
2609            "subscription flag must survive: {:?}",
2610            delivered.header.flags
2611        );
2612        assert_eq!(
2613            delivered.header.flags.priority(),
2614            Some(Priority::Background),
2615            "priority must survive"
2616        );
2617    }
2618
2619    /// A client frame carrying the origin bit must not reach the module
2620    /// looking daemon-authored either: the splice clears it symmetrically.
2621    #[tokio::test]
2622    async fn client_frame_with_daemon_bit_is_stripped_before_module_delivery() {
2623        let (
2624            router,
2625            _forwarding,
2626            client_ctx,
2627            mut client_rx,
2628            _module_ctx,
2629            _module_egress_rx,
2630            mut module_rx,
2631            pending,
2632        ) = dynamic_route_fixture(true);
2633        let _ = client_rx.recv().await;
2634        let spoof = Frame::build(
2635            FrameType::Request,
2636            Flags::new(false, Priority::Interactive, false).with_daemon_origin(),
2637            pending.client_channel,
2638            pending.client_epoch,
2639            701,
2640            b"route-body".to_vec(),
2641        )
2642        .unwrap();
2643        router
2644            .route_for_connection(&client_ctx, spoof)
2645            .await
2646            .unwrap();
2647        let delivered = module_rx.recv().await.unwrap();
2648        assert_eq!(delivered.header.ty, FrameType::Request);
2649        assert!(
2650            !delivered.header.flags.is_daemon_origin(),
2651            "client-set daemon origin must be cleared: {:?}",
2652            delivered.header.flags
2653        );
2654    }
2655
2656    #[tokio::test]
2657    async fn channel_zero_uses_control_handler_not_backend_registry() {
2658        let mut router = Router::with_default_self_handler();
2659        router.register_backend(1, EchoBackend).unwrap();
2660        let (ctx, mut rx) = route_ctx();
2661
2662        router.route_for_connection(&ctx, ping(77)).await.unwrap();
2663        let response = rx.recv().await.unwrap();
2664
2665        assert_eq!(response.header.ty, FrameType::Pong);
2666        assert_eq!(response.header.channel, 0);
2667        assert_eq!(response.header.corr, 77);
2668        assert!(response.body.is_empty());
2669    }
2670
2671    #[tokio::test]
2672    async fn slow_control_dispatch_logs_decoded_op_and_elapsed_time() {
2673        let control = Arc::new(
2674            ControlHandler::new(Arc::new(Registry::default()))
2675                .with_control_dispatch_delay(Duration::from_millis(1050)),
2676        );
2677        let router = Router::with_control_handler(control);
2678        let (ctx, mut rx) = route_ctx();
2679        let (output, guard) = log_capture(tracing::Level::WARN);
2680
2681        router
2682            .route_for_connection(&ctx, request(0, 41, br#"{"op":"server.describe"}"#))
2683            .await
2684            .expect("slow request routes");
2685        assert!(rx.recv().await.is_some(), "request receives a response");
2686        drop(guard);
2687
2688        let logs = captured_logs(&output);
2689        assert!(logs.contains("slow control dispatch"));
2690        assert!(logs.contains("op=server.describe"));
2691        assert!(logs.contains("connection_id=0"));
2692        assert!(logs.contains("corr=41"));
2693        assert!(
2694            logged_millis(&logs, "elapsed_ms=") >= 1050,
2695            "elapsed must include the injected handler delay: {logs}"
2696        );
2697    }
2698
2699    #[tokio::test]
2700    async fn fast_control_dispatch_emits_arrival_without_slow_warning() {
2701        let router = Router::with_default_self_handler();
2702        let (ctx, mut rx) = route_ctx();
2703        let (output, guard) = log_capture(tracing::Level::DEBUG);
2704
2705        router
2706            .route_for_connection(&ctx, request(0, 42, br#"{"op":"server.describe"}"#))
2707            .await
2708            .expect("fast request routes");
2709        assert!(rx.recv().await.is_some(), "request receives a response");
2710        drop(guard);
2711
2712        let logs = captured_logs(&output);
2713        assert!(logs.contains("control dispatch op=server.describe connection_id=0 corr=42"));
2714        assert!(!logs.contains("slow control dispatch"));
2715    }
2716
2717    #[tokio::test]
2718    async fn control_dispatch_arrival_is_hidden_at_info() {
2719        let router = Router::with_default_self_handler();
2720        let (ctx, mut rx) = route_ctx();
2721        let (output, guard) = log_capture(tracing::Level::INFO);
2722
2723        router
2724            .route_for_connection(&ctx, request(0, 43, br#"{"op":"server.describe"}"#))
2725            .await
2726            .expect("fast request routes");
2727        assert!(rx.recv().await.is_some(), "request receives a response");
2728        drop(guard);
2729
2730        assert!(
2731            !captured_logs(&output).contains("control dispatch"),
2732            "arrival logging must stay hidden at INFO"
2733        );
2734    }
2735
2736    #[tokio::test]
2737    async fn supervisor_list_logs_contended_snapshot_lock_only() {
2738        let registry = Arc::new(Registry::default());
2739        let handle = SupervisorHandle::new();
2740        let supervisor = Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
2741            .with_handle(handle.clone());
2742        let module = supervisor
2743            .supervise_configured(
2744                ModuleSpec {
2745                    script: None,
2746                    carry_containment: false,
2747                    module_id: "held-module".to_string(),
2748                    program: "test-module".into(),
2749                    args: Vec::new(),
2750                    env: Vec::new(),
2751                    reserved: false,
2752                    reserved_prefixes: Vec::new(),
2753                    protocol: ModuleProtocol::Subc,
2754                    overlap: Default::default(),
2755                },
2756                false,
2757            )
2758            .expect("disabled test module is supervised");
2759        let router = Router::with_control_handler(Arc::new(
2760            ControlHandler::new(Arc::clone(&registry)).with_supervisor(handle),
2761        ));
2762        let (ctx, mut rx) = route_ctx();
2763        let (acquired, ready) = std_mpsc::channel();
2764        // Park the disabled supervisor actor before holding its snapshot. The
2765        // detached list reader, not actor startup, must be the lock contender.
2766        tokio::task::yield_now().await;
2767        let holder = module.hold_snapshot_for_test(acquired, Duration::from_millis(400));
2768        ready.recv().expect("holder acquired snapshot lock");
2769        let (output, guard) = log_capture(tracing::Level::WARN);
2770
2771        router
2772            .route_for_connection(&ctx, request(0, 44, br#"{"op":"supervisor.list"}"#))
2773            .await
2774            .expect("list request routes after the lock releases");
2775        assert!(
2776            rx.recv().await.is_some(),
2777            "list request receives a response"
2778        );
2779        holder.join().expect("snapshot holder exits cleanly");
2780        drop(guard);
2781
2782        let logs = captured_logs(&output);
2783        assert!(logs.contains("slow snapshot lock"));
2784        assert!(logs.contains("module_id=held-module"));
2785        assert!(logs.contains("caller=list"));
2786        assert!(
2787            logged_millis(&logs, "waited_ms=") >= 250,
2788            "wait must exceed the slow-lock threshold: {logs}"
2789        );
2790
2791        let (output, guard) = log_capture(tracing::Level::WARN);
2792        router
2793            .route_for_connection(&ctx, request(0, 45, br#"{"op":"supervisor.list"}"#))
2794            .await
2795            .expect("uncontended list request routes");
2796        assert!(
2797            rx.recv().await.is_some(),
2798            "uncontended list receives a response"
2799        );
2800        drop(guard);
2801        assert!(
2802            !captured_logs(&output).contains("slow snapshot lock"),
2803            "uncontended list acquisition must not warn"
2804        );
2805    }
2806
2807    #[tokio::test]
2808    async fn full_module_to_client_sink_requests_client_close_without_erroring_module() {
2809        let forwarding = Arc::new(ForwardingTable::default());
2810        let control = Arc::new(ControlHandler::with_forwarding(
2811            Arc::new(crate::Registry::default()),
2812            Arc::clone(&forwarding),
2813        ));
2814        let router = Router::with_control_handler(control);
2815        let module_connection = ConnectionId::new(10);
2816        let client_connection = ConnectionId::new(20);
2817        let mut close_receiver = forwarding.register_connection_close(client_connection);
2818        let (module_tx, _module_rx) = mpsc::channel(1);
2819        forwarding
2820            .register_module_connection(
2821                module_connection,
2822                "full-sink-provider".to_string(),
2823                1,
2824                Concurrency::ModuleManaged,
2825                FrameSink::new(module_tx),
2826            )
2827            .unwrap();
2828        let (client_tx, mut client_rx) = mpsc::channel(1);
2829        let pending = forwarding
2830            .begin_route_bind_relay_for_test(
2831                client_connection,
2832                FrameSink::new(client_tx),
2833                700,
2834                "full-sink-provider",
2835            )
2836            .unwrap();
2837        forwarding
2838            .complete_pending_relay(
2839                module_connection,
2840                pending.corr,
2841                RouteBindRelayOutcome::Accepted,
2842            )
2843            .unwrap();
2844
2845        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
2846        let module_ctx = RouteCtx {
2847            connection_id: module_connection,
2848            egress: FrameSink::new(module_egress_tx),
2849        };
2850        let terminal = Frame::build(
2851            FrameType::Response,
2852            Flags::new(false, Priority::Interactive, true),
2853            pending.module_channel,
2854            pending.module_epoch,
2855            701,
2856            b"terminal".to_vec(),
2857        )
2858        .unwrap();
2859
2860        router
2861            .route_for_connection(&module_ctx, terminal)
2862            .await
2863            .unwrap();
2864        let reason = tokio::time::timeout(Duration::from_secs(1), &mut close_receiver)
2865            .await
2866            .expect("close request should be sent for the full client sink")
2867            .expect("close sender should include a reason");
2868        assert!(
2869            reason
2870                .to_string()
2871                .contains("module_to_client_delivery_failed"),
2872            "unexpected close reason: {reason}"
2873        );
2874        assert_eq!(client_rx.try_recv().unwrap().header.corr, 700);
2875        assert!(client_rx.try_recv().is_err());
2876        assert_eq!(
2877            router.counters.snapshot()["client_egress_close_delivery_failed"],
2878            1
2879        );
2880    }
2881
2882    /// A terminal frame ends the request at the module even when the client
2883    /// cannot take it, so the drain must stop counting it at once rather than
2884    /// when the client connection's cleanup later removes the route.
2885    #[tokio::test]
2886    async fn terminal_frame_releases_its_credit_even_when_client_delivery_fails() {
2887        let forwarding = Arc::new(ForwardingTable::default());
2888        let control = Arc::new(ControlHandler::with_forwarding(
2889            Arc::new(crate::Registry::default()),
2890            Arc::clone(&forwarding),
2891        ));
2892        let router = Router::with_control_handler(control);
2893        let module_connection = ConnectionId::new(11);
2894        let client_connection = ConnectionId::new(21);
2895        let _close_receiver = forwarding.register_connection_close(client_connection);
2896        let (module_tx, _module_rx) = mpsc::channel(1);
2897        forwarding
2898            .register_module_connection(
2899                module_connection,
2900                "credit-provider".to_string(),
2901                1,
2902                Concurrency::ModuleManaged,
2903                FrameSink::new(module_tx),
2904            )
2905            .unwrap();
2906        // Capacity one, filled by the route.open response, so the terminal
2907        // frame below cannot be enqueued for the client.
2908        let (client_tx, _client_rx) = mpsc::channel(1);
2909        let pending = forwarding
2910            .begin_route_bind_relay_for_test(
2911                client_connection,
2912                FrameSink::new(client_tx),
2913                800,
2914                "credit-provider",
2915            )
2916            .unwrap();
2917        forwarding
2918            .complete_pending_relay(
2919                module_connection,
2920                pending.corr,
2921                RouteBindRelayOutcome::Accepted,
2922            )
2923            .unwrap();
2924        let DataRoute::Client(DataRouteState::Bound(route)) = forwarding
2925            .lookup_data_route(
2926                client_connection,
2927                pending.client_channel,
2928                pending.client_epoch,
2929            )
2930            .unwrap()
2931        else {
2932            panic!("expected a bound client route");
2933        };
2934        route.flow.acquire_tagged(801, false).await.unwrap();
2935        assert_eq!(route.flow.drain_in_flight(), 1);
2936
2937        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
2938        let module_ctx = RouteCtx {
2939            connection_id: module_connection,
2940            egress: FrameSink::new(module_egress_tx),
2941        };
2942        let terminal = Frame::build(
2943            FrameType::Response,
2944            Flags::new(false, Priority::Interactive, true),
2945            pending.module_channel,
2946            pending.module_epoch,
2947            801,
2948            b"terminal".to_vec(),
2949        )
2950        .unwrap();
2951        router
2952            .route_for_connection(&module_ctx, terminal)
2953            .await
2954            .unwrap();
2955
2956        assert_eq!(
2957            router.counters.snapshot()["client_egress_close_delivery_failed"],
2958            1,
2959            "the client delivery must have failed for this test to mean anything"
2960        );
2961        assert_eq!(
2962            route.flow.drain_in_flight(),
2963            0,
2964            "the module's terminal frame must release its credit even though the client could not take it"
2965        );
2966    }
2967
2968    #[tokio::test]
2969    async fn full_route_goodbye_sink_requests_target_close_without_erroring_module() {
2970        let forwarding = Arc::new(ForwardingTable::default());
2971        let control = Arc::new(ControlHandler::with_forwarding(
2972            Arc::new(crate::Registry::default()),
2973            Arc::clone(&forwarding),
2974        ));
2975        let router = Router::with_control_handler(control);
2976        let module_connection = ConnectionId::new(30);
2977        let client_connection = ConnectionId::new(40);
2978        let mut close_receiver = forwarding.register_connection_close(client_connection);
2979        let (module_tx, _module_rx) = mpsc::channel(1);
2980        forwarding
2981            .register_module_connection(
2982                module_connection,
2983                "goodbye-full-provider".to_string(),
2984                1,
2985                Concurrency::ModuleManaged,
2986                FrameSink::new(module_tx),
2987            )
2988            .unwrap();
2989        let (client_tx, mut client_rx) = mpsc::channel(1);
2990        let pending = forwarding
2991            .begin_route_bind_relay_for_test(
2992                client_connection,
2993                FrameSink::new(client_tx),
2994                800,
2995                "goodbye-full-provider",
2996            )
2997            .unwrap();
2998        forwarding
2999            .complete_pending_relay(
3000                module_connection,
3001                pending.corr,
3002                RouteBindRelayOutcome::Accepted,
3003            )
3004            .unwrap();
3005
3006        let (module_egress_tx, _module_egress_rx) = mpsc::channel(1);
3007        let module_ctx = RouteCtx {
3008            connection_id: module_connection,
3009            egress: FrameSink::new(module_egress_tx),
3010        };
3011        let goodbye = Frame::build(
3012            FrameType::Goodbye,
3013            Flags::new(false, Priority::Passive, true),
3014            pending.module_channel,
3015            pending.module_epoch,
3016            801,
3017            Vec::new(),
3018        )
3019        .unwrap();
3020
3021        router
3022            .route_for_connection(&module_ctx, goodbye)
3023            .await
3024            .unwrap();
3025        let reason = tokio::time::timeout(Duration::from_secs(1), &mut close_receiver)
3026            .await
3027            .expect("close request should be sent for the full GOODBYE sink")
3028            .expect("close sender should include a reason");
3029        assert!(
3030            reason.to_string().contains("route_goodbye_delivery_failed"),
3031            "unexpected close reason: {reason}"
3032        );
3033        assert_eq!(client_rx.try_recv().unwrap().header.corr, 800);
3034        assert!(client_rx.try_recv().is_err());
3035        assert_eq!(router.counters.snapshot()["goodbye_relay_client_failed"], 1);
3036        assert_eq!(router.counters.snapshot()["route_released_epoch_fenced"], 1);
3037    }
3038
3039    /// One module and one client connection with `routes` routes bound between
3040    /// them. The client uses a real connection egress queue (the same byte
3041    /// budget and frame-count backstop as a live connection), and its route.open
3042    /// responses are drained so the queue starts empty.
3043    async fn multi_route_client(
3044        module_id: &str,
3045        module_connection: ConnectionId,
3046        client_connection: ConnectionId,
3047        routes: usize,
3048    ) -> (
3049        Router,
3050        FrameSink,
3051        mpsc::Receiver<OutboundFrame>,
3052        RouteCtx,
3053        Vec<crate::forwarding::PendingRouteBindRelay>,
3054        ConnectionCloseReceiver,
3055    ) {
3056        let forwarding = Arc::new(ForwardingTable::default());
3057        let control = Arc::new(ControlHandler::with_forwarding(
3058            Arc::new(crate::Registry::default()),
3059            Arc::clone(&forwarding),
3060        ));
3061        let router = Router::with_control_handler(control);
3062        let close_receiver = forwarding.register_connection_close(client_connection);
3063        let (module_tx, _module_rx) = mpsc::channel(8);
3064        forwarding
3065            .register_module_connection(
3066                module_connection,
3067                module_id.to_string(),
3068                1,
3069                Concurrency::ModuleManaged,
3070                FrameSink::new(module_tx),
3071            )
3072            .unwrap();
3073        let (client_sink, mut client_rx) = crate::server::connection_egress();
3074        let mut bound = Vec::with_capacity(routes);
3075        for index in 0..routes {
3076            let pending = forwarding
3077                .begin_route_bind_relay_for_test(
3078                    client_connection,
3079                    client_sink.clone(),
3080                    900 + index as u64,
3081                    module_id,
3082                )
3083                .unwrap();
3084            forwarding
3085                .complete_pending_relay(
3086                    module_connection,
3087                    pending.corr,
3088                    RouteBindRelayOutcome::Accepted,
3089                )
3090                .unwrap();
3091            assert_eq!(
3092                client_rx.recv().await.unwrap().header.corr,
3093                900 + index as u64
3094            );
3095            bound.push(pending);
3096        }
3097        let (module_egress_tx, _module_egress_rx) = mpsc::channel(8);
3098        let module_ctx = RouteCtx {
3099            connection_id: module_connection,
3100            egress: FrameSink::new(module_egress_tx),
3101        };
3102        (
3103            router,
3104            client_sink,
3105            client_rx,
3106            module_ctx,
3107            bound,
3108            close_receiver,
3109        )
3110    }
3111
3112    /// Per-frame cost of the egress sink's admission and release accounting:
3113    /// one million 200-byte frames enqueued with `try_send` and taken off the
3114    /// queue the way the connection writer does, in batches of 1,000 so the
3115    /// queue stays well inside its budget. Prints nanoseconds per frame; it is
3116    /// a measurement, not a gate. Run with
3117    /// `cargo test --release -p subc-daemon --lib egress_sink_per_frame_cost -- --ignored --nocapture`.
3118    #[test]
3119    #[ignore = "timing measurement, run on demand"]
3120    fn egress_sink_per_frame_cost() {
3121        const FRAMES: usize = 1_000_000;
3122        const BATCH: usize = 1_000;
3123        let (sink, mut rx) = crate::server::connection_egress();
3124        let template = stream_frame(9, 1, 0, vec![b't'; 200]);
3125        let started = Instant::now();
3126        for _ in 0..FRAMES / BATCH {
3127            for _ in 0..BATCH {
3128                sink.try_send(template.clone()).unwrap();
3129            }
3130            for _ in 0..BATCH {
3131                let outbound = rx.try_recv().unwrap();
3132                if let Some(charge) = &outbound.charge {
3133                    charge.taken_by_writer();
3134                }
3135                drop(std::hint::black_box(outbound));
3136            }
3137        }
3138        let elapsed = started.elapsed();
3139        assert_eq!(sink.backlog().queued_bytes, 0);
3140        println!(
3141            "egress sink: {FRAMES} frames in {elapsed:?}, {:.1} ns/frame",
3142            elapsed.as_nanos() as f64 / FRAMES as f64
3143        );
3144    }
3145
3146    fn stream_frame(channel: u16, epoch: u32, corr: u64, body: Vec<u8>) -> Frame {
3147        Frame::build(
3148            FrameType::StreamData,
3149            Flags::new(false, Priority::Interactive, false),
3150            channel,
3151            epoch,
3152            corr,
3153            body,
3154        )
3155        .unwrap()
3156    }
3157
3158    fn module_route_for_test(
3159        router: &Router,
3160        ctx: &RouteCtx,
3161        route: &crate::forwarding::PendingRouteBindRelay,
3162    ) -> Arc<RouteBinding> {
3163        match router
3164            .forwarding
3165            .lookup_data_route(ctx.connection_id, route.module_channel, route.module_epoch)
3166            .unwrap()
3167        {
3168            DataRoute::Module(DataRouteState::Bound(binding)) => binding,
3169            other => panic!("expected a bound module route, got {other:?}"),
3170        }
3171    }
3172
3173    fn assert_frame_size_error(frame: &Frame, channel: u16, epoch: u32, corr: u64, bytes: usize) {
3174        assert_eq!(frame.header.ty, FrameType::Error);
3175        assert_eq!(frame.header.channel, channel);
3176        assert_eq!(frame.header.epoch, epoch);
3177        assert_eq!(frame.header.corr, corr);
3178        assert!(frame.header.flags.is_daemon_origin());
3179        let body: ErrorBody = serde_json::from_slice(&frame.body).unwrap();
3180        assert_eq!(body.code, error_codes::FRAME_TOO_LARGE);
3181        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3182        assert!(body.message.contains(&bytes.to_string()));
3183        assert!(body.message.contains(&limit.to_string()));
3184        assert_eq!(
3185            body.detail,
3186            Some(serde_json::json!({ "frame_bytes": bytes, "byte_limit": limit }))
3187        );
3188    }
3189
3190    #[tokio::test]
3191    async fn module_egress_response_oversized_reply_keeps_connection_and_other_route() {
3192        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3193        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3194            "oversize-provider",
3195            ConnectionId::new(80),
3196            ConnectionId::new(81),
3197            2,
3198        )
3199        .await;
3200        let binding = module_route_for_test(&router, &ctx, &routes[0]);
3201        binding.flow.acquire_tagged(101, false).await.unwrap();
3202        module_route_for_test(&router, &ctx, &routes[1])
3203            .flow
3204            .acquire_tagged(102, false)
3205            .await
3206            .unwrap();
3207        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3208        let oversized = Frame::build(
3209            FrameType::Response,
3210            Flags::new(false, Priority::Interactive, true),
3211            routes[0].module_channel,
3212            routes[0].module_epoch,
3213            101,
3214            vec![b'x'; limit - subc_protocol::HEADER_LEN + 1],
3215        )
3216        .unwrap();
3217        assert_eq!(sink.backlog().queued_bytes, 0);
3218        router.route_for_connection(&ctx, oversized).await.unwrap();
3219
3220        // Reproduce a large reply followed by ordinary traffic on another route
3221        // before the client reads anything. The large reply must not monopolize
3222        // the queue and make that second delivery close the shared connection.
3223        router
3224            .route_for_connection(
3225                &ctx,
3226                route_frame(
3227                    FrameType::Response,
3228                    routes[1].module_channel,
3229                    routes[1].module_epoch,
3230                    102,
3231                ),
3232            )
3233            .await
3234            .unwrap();
3235        assert!(
3236            close.try_recv().is_err(),
3237            "an oversized reply must not close the multiplexed client"
3238        );
3239        let error = rx.try_recv().expect("the waiting client gets an ERROR");
3240        assert_frame_size_error(
3241            &error,
3242            routes[0].client_channel,
3243            routes[0].client_epoch,
3244            101,
3245            limit + 1,
3246        );
3247        let second = rx.try_recv().expect("the other route's reply arrives");
3248        assert_eq!(second.header.ty, FrameType::Response);
3249        assert_eq!(second.header.channel, routes[1].client_channel);
3250        assert_eq!(second.header.epoch, routes[1].client_epoch);
3251        assert_eq!(second.header.corr, 102);
3252        assert_eq!(second.body, b"route-body");
3253        assert_eq!(binding.flow.drain_in_flight(), 0);
3254        for route in &routes {
3255            module_route_for_test(&router, &ctx, route);
3256        }
3257        assert!(rx.try_recv().is_err());
3258        drop((error, second));
3259        assert_eq!(sink.backlog().queued_bytes, 0);
3260        assert_eq!(
3261            router.counters.snapshot()["client_egress_close_delivery_failed"],
3262            0
3263        );
3264
3265        let captured = test_log::captured_logs(&logs);
3266        let warnings: Vec<_> = captured
3267            .lines()
3268            .filter(|line| line.contains("WARN"))
3269            .collect();
3270        assert_eq!(warnings.len(), 1, "{captured}");
3271        let warning = warnings[0];
3272        for expected in [
3273            "module_id=oversize-provider".to_string(),
3274            "client_principal=direct".to_string(),
3275            format!("client_channel={}", routes[0].client_channel),
3276            format!("frame_bytes={}", limit + 1),
3277            format!("byte_limit={limit}"),
3278        ] {
3279            assert!(warning.contains(&expected), "missing {expected}: {warning}");
3280        }
3281    }
3282
3283    async fn poll_once<F: std::future::Future>(
3284        mut future: std::pin::Pin<&mut F>,
3285    ) -> std::task::Poll<F::Output> {
3286        std::future::poll_fn(|cx| std::task::Poll::Ready(future.as_mut().poll(cx))).await
3287    }
3288
3289    fn fill_client_budget(sink: &FrameSink, route: &crate::forwarding::PendingRouteBindRelay) {
3290        sink.try_send(
3291            Frame::build(
3292                FrameType::Response,
3293                Flags::new(false, Priority::Interactive, true),
3294                route.client_channel,
3295                route.client_epoch,
3296                100,
3297                vec![
3298                    b'x';
3299                    crate::server::CONNECTION_EGRESS_BYTE_BUDGET - subc_protocol::HEADER_LEN
3300                ],
3301            )
3302            .unwrap(),
3303        )
3304        .unwrap();
3305        assert_eq!(
3306            sink.backlog().queued_bytes,
3307            crate::server::CONNECTION_EGRESS_BYTE_BUDGET
3308        );
3309    }
3310
3311    async fn assert_full_client_burst_survives(ty: FrameType, oversized: bool) {
3312        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3313            "draining-burst",
3314            ConnectionId::new(92),
3315            ConnectionId::new(93),
3316            2,
3317        )
3318        .await;
3319        fill_client_budget(&sink, &routes[0]);
3320        let frame = if oversized {
3321            Frame::build(
3322                ty,
3323                Flags::new(false, Priority::Interactive, false),
3324                routes[1].module_channel,
3325                routes[1].module_epoch,
3326                101,
3327                vec![b's'; crate::server::CONNECTION_EGRESS_BYTE_BUDGET],
3328            )
3329            .unwrap()
3330        } else {
3331            route_frame(ty, routes[1].module_channel, routes[1].module_epoch, 101)
3332        };
3333        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3334        assert!(poll_once(delivery.as_mut()).await.is_pending());
3335        assert!(
3336            close.try_recv().is_err(),
3337            "fresh bursts must not close: {ty:?}"
3338        );
3339        tokio::time::advance(Duration::from_millis(50)).await;
3340        let queued = rx.try_recv().unwrap();
3341        queued.charge.as_ref().unwrap().taken_by_writer();
3342        drop(queued);
3343        assert!(matches!(
3344            poll_once(delivery.as_mut()).await,
3345            std::task::Poll::Ready(Ok(()))
3346        ));
3347        let delivered = rx
3348            .try_recv()
3349            .expect("the burst frame must be delivered after draining");
3350        assert_eq!(delivered.header.channel, routes[1].client_channel);
3351        assert_eq!(delivered.header.epoch, routes[1].client_epoch);
3352        assert_eq!(delivered.header.corr, 101);
3353        if oversized {
3354            assert_frame_size_error(
3355                &delivered,
3356                routes[1].client_channel,
3357                routes[1].client_epoch,
3358                101,
3359                crate::server::CONNECTION_EGRESS_BYTE_BUDGET + subc_protocol::HEADER_LEN,
3360            );
3361        } else {
3362            assert_eq!(delivered.header.ty, ty);
3363        }
3364        assert!(rx.try_recv().is_err());
3365        assert!(close.try_recv().is_err());
3366        assert_eq!(
3367            router.counters.snapshot()["client_egress_close_delivery_failed"],
3368            0
3369        );
3370        assert_eq!(router.counters.snapshot()["goodbye_relay_client_failed"], 0);
3371    }
3372
3373    #[tokio::test(start_paused = true)]
3374    async fn module_egress_fresh_full_queue_burst_survives() {
3375        for ty in [
3376            FrameType::Response,
3377            FrameType::StreamData,
3378            FrameType::Request,
3379            FrameType::Push,
3380        ] {
3381            assert_full_client_burst_survives(ty, false).await;
3382        }
3383    }
3384
3385    #[tokio::test(start_paused = true)]
3386    async fn module_goodbye_fresh_full_queue_burst_survives() {
3387        assert_full_client_burst_survives(FrameType::Goodbye, false).await;
3388    }
3389
3390    #[tokio::test(start_paused = true)]
3391    async fn frame_count_backstop_also_allows_a_draining_burst() {
3392        let (tx, mut rx) = mpsc::channel(1);
3393        let sink = FrameSink::with_byte_budget(tx, 2_000);
3394        sink.try_send(stream_frame(1, 1, 1, vec![b'x'; 100]))
3395            .unwrap();
3396        let mut delivery = Box::pin(sink.send_to_client(stream_frame(1, 1, 2, vec![b'y'; 100])));
3397        assert!(poll_once(delivery.as_mut()).await.is_pending());
3398        assert!(
3399            sink.backlog().queued_bytes < 2_000,
3400            "only frame capacity is exhausted"
3401        );
3402        tokio::time::advance(Duration::from_millis(50)).await;
3403        drop(rx.try_recv().unwrap());
3404        assert!(matches!(
3405            poll_once(delivery.as_mut()).await,
3406            std::task::Poll::Ready(Ok(()))
3407        ));
3408        assert_eq!(rx.try_recv().unwrap().header.corr, 2);
3409    }
3410
3411    #[tokio::test(start_paused = true)]
3412    async fn oversized_reply_replacement_fresh_full_queue_burst_survives() {
3413        for ty in [FrameType::Response, FrameType::StreamData] {
3414            assert_full_client_burst_survives(ty, true).await;
3415        }
3416    }
3417
3418    #[tokio::test(start_paused = true)]
3419    async fn module_egress_stopped_reader_closes_without_waiting() {
3420        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3421        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3422            "oldest-stopped-reader",
3423            ConnectionId::new(94),
3424            ConnectionId::new(95),
3425            2,
3426        )
3427        .await;
3428        fill_client_budget(&sink, &routes[0]);
3429        // The writer has taken the head but cannot finish writing it. Its
3430        // bytes stay charged, and the atomic age still diagnoses that stall.
3431        let writing = rx.try_recv().unwrap();
3432        writing.charge.as_ref().unwrap().taken_by_writer();
3433        tokio::time::advance(Duration::from_millis(251)).await;
3434        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(251)));
3435        assert_eq!(sink.backlog().queued_bytes, queued_frame_bytes(&writing));
3436        let started = tokio::time::Instant::now();
3437        let frame = stream_frame(
3438            routes[0].module_channel,
3439            routes[0].module_epoch,
3440            101,
3441            b"secret-body-never-log".to_vec(),
3442        );
3443        let flags = frame.header.flags.0;
3444        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3445        assert!(
3446            matches!(
3447                poll_once(delivery.as_mut()).await,
3448                std::task::Poll::Ready(Ok(()))
3449            ),
3450            "an oldest frame older than 250 ms must close immediately, without a new wait"
3451        );
3452        assert_eq!(started.elapsed(), Duration::ZERO);
3453        assert!(close
3454            .try_recv()
3455            .unwrap()
3456            .to_string()
3457            .contains("module_to_client_delivery_failed"));
3458        let captured = test_log::captured_logs(&logs);
3459        for expected in [
3460            "frame_type=Some(StreamData)".to_string(),
3461            format!("frame_flags=Some({flags})"),
3462            "oldest_queued_ms=251".to_string(),
3463            "close_cause=\"oldest_frame_older_than_250_ms\"".to_string(),
3464        ] {
3465            assert!(
3466                captured.contains(&expected),
3467                "missing {expected}: {captured}"
3468            );
3469        }
3470        assert!(!captured.contains("secret-body-never-log"));
3471    }
3472
3473    #[tokio::test(start_paused = true)]
3474    async fn client_gone_mid_wait_resumes_module_reader_immediately() {
3475        for writer_gone in [false, true] {
3476            let (router, sink, mut rx, ctx, routes, _close) = multi_route_client(
3477                "gone-during-burst",
3478                ConnectionId::new(96),
3479                ConnectionId::new(97),
3480                1,
3481            )
3482            .await;
3483            fill_client_budget(&sink, &routes[0]);
3484            let frame = route_frame(
3485                FrameType::Response,
3486                routes[0].module_channel,
3487                routes[0].module_epoch,
3488                101,
3489            );
3490            let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3491            assert!(poll_once(delivery.as_mut()).await.is_pending());
3492            tokio::time::advance(Duration::from_millis(50)).await;
3493            let started = tokio::time::Instant::now();
3494            if writer_gone {
3495                rx.close();
3496            } else {
3497                sink.close_client_delivery();
3498            }
3499            assert!(
3500                matches!(
3501                    poll_once(delivery.as_mut()).await,
3502                    std::task::Poll::Ready(Ok(()))
3503                ),
3504                "client teardown must wake the module reader before the writer drains"
3505            );
3506            assert_eq!(started.elapsed(), Duration::ZERO);
3507            assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 0);
3508            assert_eq!(rx.try_recv().unwrap().header.corr, 100);
3509            assert!(rx.try_recv().is_err());
3510        }
3511    }
3512
3513    #[tokio::test(start_paused = true)]
3514    async fn cancelled_module_delivery_releases_waiter_without_closing_client() {
3515        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3516            "cancelled-burst",
3517            ConnectionId::new(98),
3518            ConnectionId::new(99),
3519            1,
3520        )
3521        .await;
3522        fill_client_budget(&sink, &routes[0]);
3523        let frame = route_frame(
3524            FrameType::Response,
3525            routes[0].module_channel,
3526            routes[0].module_epoch,
3527            101,
3528        );
3529        let mut delivery = Box::pin(router.route_for_connection(&ctx, frame));
3530        assert!(poll_once(delivery.as_mut()).await.is_pending());
3531        assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 1);
3532        drop(delivery);
3533        assert_eq!(sink.accounting.waiters.load(Ordering::SeqCst), 0);
3534        tokio::time::advance(Duration::from_secs(1)).await;
3535        assert!(close.try_recv().is_err());
3536        drop(rx.try_recv().unwrap());
3537        assert_eq!(sink.backlog().queued_bytes, 0);
3538        assert!(sink.backlog().oldest_age.is_none());
3539    }
3540
3541    #[tokio::test(start_paused = true)]
3542    async fn egress_atomic_age_follows_writer_and_clears_when_drained() {
3543        let (sink, mut rx) = crate::server::connection_egress();
3544        sink.try_send(stream_frame(1, 1, 1, vec![b'x'; 100]))
3545            .unwrap();
3546        tokio::time::advance(Duration::from_millis(200)).await;
3547        sink.try_send(stream_frame(2, 1, 2, vec![b'y'; 100]))
3548            .unwrap();
3549        let writing = rx.try_recv().unwrap();
3550        writing.charge.as_ref().unwrap().taken_by_writer();
3551        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(200)));
3552        drop(writing);
3553        // Between frames the lock-free marker can still name the previous
3554        // head. The next writer take advances it without scanning the queue.
3555        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(200)));
3556        tokio::time::advance(Duration::from_millis(50)).await;
3557        let next = rx.try_recv().unwrap();
3558        next.charge.as_ref().unwrap().taken_by_writer();
3559        assert_eq!(sink.backlog().oldest_age, Some(Duration::from_millis(50)));
3560        assert!(
3561            sink.backlog().queued_bytes > 0,
3562            "in-flight bytes remain charged until written"
3563        );
3564        drop(next);
3565        assert_eq!(sink.backlog().queued_bytes, 0);
3566        assert_eq!(sink.backlog().oldest_age, None);
3567    }
3568
3569    #[tokio::test(start_paused = true)]
3570    async fn module_egress_response_full_client_waits_only_remaining_grace() {
3571        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3572            "backpressure-provider",
3573            ConnectionId::new(82),
3574            ConnectionId::new(83),
3575            2,
3576        )
3577        .await;
3578        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3579        // Exactly the limit, including its header, must be admitted to an empty
3580        // queue. Leave it unread to deterministically exhaust only byte capacity.
3581        router
3582            .route_for_connection(
3583                &ctx,
3584                Frame::build(
3585                    FrameType::Response,
3586                    Flags::new(false, Priority::Interactive, true),
3587                    routes[0].module_channel,
3588                    routes[0].module_epoch,
3589                    201,
3590                    vec![b'x'; limit - subc_protocol::HEADER_LEN],
3591                )
3592                .unwrap(),
3593            )
3594            .await
3595            .unwrap();
3596        assert_eq!(sink.backlog().queued_bytes, limit);
3597        assert_eq!(sink.backlog().queued_frames, 1);
3598        let ordinary = route_frame(
3599            FrameType::Response,
3600            routes[1].module_channel,
3601            routes[1].module_epoch,
3602            202,
3603        );
3604        assert!(queued_frame_bytes(&ordinary) < limit);
3605        // A fitting reply gets only the unused portion of the oldest frame's
3606        // 250 ms grace, not an immediate close or a fresh 250 ms wait.
3607        tokio::time::advance(Duration::from_millis(100)).await;
3608        let mut delivery = Box::pin(router.route_for_connection(&ctx, ordinary));
3609        assert!(poll_once(delivery.as_mut()).await.is_pending());
3610        assert!(close.try_recv().is_err());
3611        tokio::time::advance(Duration::from_millis(149)).await;
3612        assert!(poll_once(delivery.as_mut()).await.is_pending());
3613        assert!(close.try_recv().is_err());
3614        tokio::time::advance(Duration::from_millis(1)).await;
3615        assert!(matches!(
3616            poll_once(delivery.as_mut()).await,
3617            std::task::Poll::Ready(Ok(()))
3618        ));
3619        drop(delivery);
3620        let reason = close.try_recv().expect("the full client must close");
3621        assert!(reason
3622            .to_string()
3623            .contains("module_to_client_delivery_failed"));
3624        assert!(!reason.to_string().contains("frame_too_large"));
3625        assert_eq!(
3626            router.counters.snapshot()["client_egress_close_delivery_failed"],
3627            1
3628        );
3629        let admitted = rx.try_recv().expect("the budget-sized frame was admitted");
3630        assert_eq!(admitted.header.ty, FrameType::Response);
3631        assert_eq!(admitted.header.corr, 201);
3632        assert!(
3633            rx.try_recv().is_err(),
3634            "no oversized-frame ERROR is substituted for backpressure"
3635        );
3636    }
3637
3638    #[tokio::test(start_paused = true)]
3639    async fn oversized_reply_to_a_full_client_waits_only_remaining_grace() {
3640        let (router, sink, _rx, ctx, routes, mut close) = multi_route_client(
3641            "full-oversize-provider",
3642            ConnectionId::new(90),
3643            ConnectionId::new(91),
3644            2,
3645        )
3646        .await;
3647        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3648        // Fill the client's queue to its budget and leave it unread.
3649        router
3650            .route_for_connection(
3651                &ctx,
3652                Frame::build(
3653                    FrameType::Response,
3654                    Flags::new(false, Priority::Interactive, true),
3655                    routes[0].module_channel,
3656                    routes[0].module_epoch,
3657                    501,
3658                    vec![b'x'; limit - subc_protocol::HEADER_LEN],
3659                )
3660                .unwrap(),
3661            )
3662            .await
3663            .unwrap();
3664        assert_eq!(sink.backlog().queued_bytes, limit);
3665        let oversized = Frame::build(
3666            FrameType::Response,
3667            Flags::new(false, Priority::Interactive, true),
3668            routes[1].module_channel,
3669            routes[1].module_epoch,
3670            502,
3671            vec![b'y'; limit - subc_protocol::HEADER_LEN + 1],
3672        )
3673        .unwrap();
3674        // The replacement ERROR gets the same bounded burst grace as the
3675        // ordinary reply; oversized payloads themselves are never queued.
3676        tokio::time::advance(Duration::from_millis(80)).await;
3677        let mut delivery = Box::pin(router.route_for_connection(&ctx, oversized));
3678        assert!(poll_once(delivery.as_mut()).await.is_pending());
3679        assert!(close.try_recv().is_err());
3680        tokio::time::advance(Duration::from_millis(169)).await;
3681        assert!(poll_once(delivery.as_mut()).await.is_pending());
3682        assert!(close.try_recv().is_err());
3683        tokio::time::advance(Duration::from_millis(1)).await;
3684        assert!(matches!(
3685            poll_once(delivery.as_mut()).await,
3686            std::task::Poll::Ready(Ok(()))
3687        ));
3688        drop(delivery);
3689        let reason = close.try_recv().expect("the full client must close");
3690        assert!(reason
3691            .to_string()
3692            .contains("module_to_client_delivery_failed"));
3693    }
3694
3695    #[tokio::test]
3696    async fn oversized_reverse_request_errors_module_without_reaching_client() {
3697        let (router, _sink, mut rx, mut ctx, routes, mut close) = multi_route_client(
3698            "reverse-oversize-provider",
3699            ConnectionId::new(84),
3700            ConnectionId::new(85),
3701            2,
3702        )
3703        .await;
3704        let (module_tx, mut module_rx) = mpsc::channel(8);
3705        ctx.egress = FrameSink::new(module_tx);
3706        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3707        router
3708            .route_for_connection(
3709                &ctx,
3710                Frame::build(
3711                    FrameType::Request,
3712                    Flags::new(false, Priority::Interactive, false),
3713                    routes[0].module_channel,
3714                    routes[0].module_epoch,
3715                    301,
3716                    vec![b'r'; limit - subc_protocol::HEADER_LEN + 1],
3717                )
3718                .unwrap(),
3719            )
3720            .await
3721            .unwrap();
3722        assert!(
3723            rx.try_recv().is_err(),
3724            "the reverse request never reaches the client"
3725        );
3726        let error = module_rx.try_recv().expect("the module gets the refusal");
3727        assert_frame_size_error(
3728            &error,
3729            routes[0].module_channel,
3730            routes[0].module_epoch,
3731            301,
3732            limit + 1,
3733        );
3734        assert!(module_rx.try_recv().is_err());
3735        for (index, route) in routes.iter().enumerate() {
3736            module_route_for_test(&router, &ctx, route);
3737            router
3738                .route_for_connection(
3739                    &ctx,
3740                    route_frame(
3741                        FrameType::Response,
3742                        route.module_channel,
3743                        route.module_epoch,
3744                        302 + index as u64,
3745                    ),
3746                )
3747                .await
3748                .unwrap();
3749            let reply = rx.try_recv().expect("both routes still deliver");
3750            assert_eq!(reply.header.ty, FrameType::Response);
3751            assert_eq!(reply.header.channel, route.client_channel);
3752        }
3753        assert!(close.try_recv().is_err());
3754        assert_eq!(
3755            router.counters.snapshot()["client_egress_close_delivery_failed"],
3756            0
3757        );
3758    }
3759
3760    #[tokio::test]
3761    async fn oversized_push_closes_client_with_precise_warn() {
3762        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
3763        let (router, _sink, mut rx, ctx, routes, mut close) = multi_route_client(
3764            "push-oversize-provider",
3765            ConnectionId::new(86),
3766            ConnectionId::new(87),
3767            2,
3768        )
3769        .await;
3770        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3771        router
3772            .route_for_connection(
3773                &ctx,
3774                Frame::build(
3775                    FrameType::Push,
3776                    Flags::new(false, Priority::Interactive, false),
3777                    routes[0].module_channel,
3778                    routes[0].module_epoch,
3779                    0,
3780                    vec![b'p'; limit - subc_protocol::HEADER_LEN + 1],
3781                )
3782                .unwrap(),
3783            )
3784            .await
3785            .unwrap();
3786        let reason = close
3787            .try_recv()
3788            .expect("unsolicited oversize still closes the client");
3789        assert!(reason
3790            .to_string()
3791            .contains("frame_too_large: oversized push"));
3792        assert!(
3793            rx.try_recv().is_err(),
3794            "no part of the oversized push is forwarded"
3795        );
3796        let captured = test_log::captured_logs(&logs);
3797        let warnings: Vec<_> = captured
3798            .lines()
3799            .filter(|line| line.contains("WARN"))
3800            .collect();
3801        assert_eq!(warnings.len(), 1, "{captured}");
3802        let warning = warnings[0];
3803        for expected in [
3804            "oversized push".to_string(),
3805            "module_id=\"push-oversize-provider\"".to_string(),
3806            "principals=direct".to_string(),
3807            format!("client_channel={}", routes[0].client_channel),
3808            format!("size={}", limit + 1),
3809            format!("limit={limit}"),
3810        ] {
3811            assert!(warning.contains(&expected), "missing {expected}: {warning}");
3812        }
3813        assert_eq!(
3814            router.counters.snapshot()["client_egress_close_delivery_failed"],
3815            1
3816        );
3817    }
3818
3819    #[tokio::test]
3820    async fn oversized_stream_and_error_frames_end_request_even_with_queued_traffic() {
3821        let (router, sink, mut rx, ctx, routes, mut close) = multi_route_client(
3822            "stream-oversize-provider",
3823            ConnectionId::new(88),
3824            ConnectionId::new(89),
3825            2,
3826        )
3827        .await;
3828        let binding = module_route_for_test(&router, &ctx, &routes[0]);
3829        let limit = crate::server::CONNECTION_EGRESS_BYTE_BUDGET;
3830        for ty in [
3831            FrameType::StreamData,
3832            FrameType::StreamEnd,
3833            FrameType::Error,
3834        ] {
3835            binding.flow.acquire_tagged(401, false).await.unwrap();
3836            sink.try_send(route_frame(
3837                FrameType::Response,
3838                routes[1].client_channel,
3839                routes[1].client_epoch,
3840                402,
3841            ))
3842            .unwrap();
3843            router
3844                .route_for_connection(
3845                    &ctx,
3846                    Frame::build(
3847                        ty,
3848                        Flags::new(false, Priority::Interactive, false),
3849                        routes[0].module_channel,
3850                        routes[0].module_epoch,
3851                        401,
3852                        vec![b's'; limit - subc_protocol::HEADER_LEN + 1],
3853                    )
3854                    .unwrap(),
3855                )
3856                .await
3857                .unwrap();
3858            assert!(close.try_recv().is_err());
3859            assert_eq!(rx.try_recv().unwrap().header.corr, 402);
3860            let error = rx
3861                .try_recv()
3862                .expect("every correlated oversize frame becomes ERROR");
3863            assert_frame_size_error(
3864                &error,
3865                routes[0].client_channel,
3866                routes[0].client_epoch,
3867                401,
3868                limit + 1,
3869            );
3870            if ty == FrameType::StreamData {
3871                // The module is still running the request: it keeps its
3872                // credit until the module's own terminal, which the client,
3873                // already told frame_too_large, never sees.
3874                assert_eq!(binding.flow.drain_in_flight(), 1);
3875                router
3876                    .route_for_connection(
3877                        &ctx,
3878                        route_frame(
3879                            FrameType::StreamEnd,
3880                            routes[0].module_channel,
3881                            routes[0].module_epoch,
3882                            401,
3883                        ),
3884                    )
3885                    .await
3886                    .unwrap();
3887            }
3888            assert_eq!(binding.flow.drain_in_flight(), 0, "{ty:?} ends the request");
3889            assert!(rx.try_recv().is_err());
3890        }
3891    }
3892
3893    /// An awaited send (a control or error reply) is never refused by the byte
3894    /// budget: it parks until the writer frees bytes. If a release could miss a
3895    /// parked sender, that reply would hang for the connection's lifetime, so
3896    /// this pins the wakeup: the send stays parked while the queue is full and
3897    /// completes as soon as one frame leaves it.
3898    #[tokio::test]
3899    async fn awaited_send_parked_behind_a_full_byte_budget_wakes_when_bytes_free() {
3900        let (tx, mut rx) = mpsc::channel(1024);
3901        let sink = FrameSink::with_byte_budget(tx, 2_000);
3902        let mut queued = 0u64;
3903        while sink
3904            .try_send(stream_frame(7, 1, queued, vec![b'x'; 200]))
3905            .is_ok()
3906        {
3907            queued += 1;
3908        }
3909        assert!(queued > 0, "the budget admitted nothing");
3910
3911        let parked = tokio::spawn({
3912            let sink = sink.clone();
3913            async move { sink.send(stream_frame(0, 0, 999, vec![b'r'; 200])).await }
3914        });
3915        tokio::time::sleep(Duration::from_millis(100)).await;
3916        assert!(
3917            !parked.is_finished(),
3918            "the awaited send must wait while the byte budget is full"
3919        );
3920
3921        // The writer takes one frame and drops it, releasing its bytes.
3922        drop(rx.recv().await.expect("a queued frame"));
3923        tokio::time::timeout(Duration::from_secs(2), parked)
3924            .await
3925            .expect("the parked send was never woken after bytes were freed")
3926            .unwrap()
3927            .unwrap();
3928    }
3929
3930    /// A client multiplexing several token streams pauses its reader while the
3931    /// module keeps producing small frames. Far more frames than the old
3932    /// 64-frame queue allowed, but far fewer bytes than the budget, must all be
3933    /// held without closing the connection and delivered in order afterwards.
3934    #[tokio::test]
3935    async fn paused_client_reader_keeps_connection_through_small_frame_burst() {
3936        const ROUTES: usize = 4;
3937        const FRAMES_PER_ROUTE: usize = 250;
3938        let (router, client_sink, mut client_rx, module_ctx, routes, mut close_receiver) =
3939            multi_route_client(
3940                "burst-provider",
3941                ConnectionId::new(60),
3942                ConnectionId::new(61),
3943                ROUTES,
3944            )
3945            .await;
3946
3947        // The reader is paused: nothing is received until every frame is sent.
3948        for seq in 0..FRAMES_PER_ROUTE as u64 {
3949            for (index, route) in routes.iter().enumerate() {
3950                let body = format!("route-{index}-token-{seq:05}-{}", "t".repeat(170));
3951                router
3952                    .route_for_connection(
3953                        &module_ctx,
3954                        stream_frame(
3955                            route.module_channel,
3956                            route.module_epoch,
3957                            seq,
3958                            body.into_bytes(),
3959                        ),
3960                    )
3961                    .await
3962                    .unwrap();
3963            }
3964        }
3965
3966        let backlog = client_sink.backlog();
3967        assert_eq!(backlog.queued_frames, ROUTES * FRAMES_PER_ROUTE);
3968        assert!(backlog.queued_bytes < crate::server::CONNECTION_EGRESS_BYTE_BUDGET);
3969        assert!(
3970            close_receiver.try_recv().is_err(),
3971            "a paused reader under the byte budget must not be closed"
3972        );
3973        assert_eq!(
3974            router.counters.snapshot()["client_egress_close_delivery_failed"],
3975            0
3976        );
3977
3978        // The reader resumes: every frame arrives, in order within each route.
3979        let mut next_seq = vec![0u64; ROUTES];
3980        for _ in 0..ROUTES * FRAMES_PER_ROUTE {
3981            let frame = client_rx.try_recv().expect("every queued frame arrives");
3982            let index = routes
3983                .iter()
3984                .position(|route| route.client_channel == frame.header.channel)
3985                .expect("frame arrives on one of the bound client channels");
3986            assert_eq!(frame.header.corr, next_seq[index], "route {index} order");
3987            let expected_prefix = format!("route-{index}-token-{:05}-", next_seq[index]);
3988            assert!(frame.body.starts_with(expected_prefix.as_bytes()));
3989            next_seq[index] += 1;
3990        }
3991        assert!(client_rx.try_recv().is_err());
3992        assert_eq!(next_seq, vec![FRAMES_PER_ROUTE as u64; ROUTES]);
3993        assert_eq!(client_sink.backlog().queued_bytes, 0);
3994    }
3995
3996    /// A client that never reads exhausts its byte budget and the oldest
3997    /// frame's 250 ms grace, then closes with one header-only diagnosis.
3998    #[tokio::test(start_paused = true)]
3999    async fn never_reading_client_is_closed_at_byte_budget_with_warn_diagnosis() {
4000        let (logs, _guard) = test_log::log_capture(tracing::Level::WARN);
4001        const BODY: usize = 16 * 1024;
4002        let (router, client_sink, _client_rx, module_ctx, routes, mut close_receiver) =
4003            multi_route_client(
4004                "stuck-reader-provider",
4005                ConnectionId::new(70),
4006                ConnectionId::new(71),
4007                2,
4008            )
4009            .await;
4010
4011        let mut admitted = 0usize;
4012        let mut sent = 0u64;
4013        let started = tokio::time::Instant::now();
4014        while router.counters.snapshot()["client_egress_close_delivery_failed"] == 0 {
4015            assert!(sent < 1_000, "the byte budget never refused a frame");
4016            let route = &routes[(sent % 2) as usize];
4017            router
4018                .route_for_connection(
4019                    &module_ctx,
4020                    stream_frame(
4021                        route.module_channel,
4022                        route.module_epoch,
4023                        sent,
4024                        vec![b'z'; BODY],
4025                    ),
4026                )
4027                .await
4028                .unwrap();
4029            sent += 1;
4030            admitted = client_sink.backlog().queued_frames;
4031        }
4032        assert_eq!(
4033            started.elapsed(),
4034            crate::server::CONNECTION_EGRESS_STALL_GRACE
4035        );
4036        // The budget, not the frame-count backstop, did the refusing.
4037        let frame_bytes = subc_protocol::HEADER_LEN + BODY;
4038        assert_eq!(
4039            admitted,
4040            crate::server::CONNECTION_EGRESS_BYTE_BUDGET / frame_bytes
4041        );
4042        let reason = close_receiver
4043            .try_recv()
4044            .expect("the client connection must be asked to close");
4045        assert!(reason
4046            .to_string()
4047            .contains("module_to_client_delivery_failed"));
4048
4049        // A second refused frame for the same connection adds no second WARN.
4050        router
4051            .route_for_connection(
4052                &module_ctx,
4053                stream_frame(
4054                    routes[0].module_channel,
4055                    routes[0].module_epoch,
4056                    sent,
4057                    vec![b'z'; BODY],
4058                ),
4059            )
4060            .await
4061            .unwrap();
4062
4063        let captured = test_log::captured_logs(&logs);
4064        let warn_lines = captured
4065            .lines()
4066            .filter(|line| {
4067                line.contains("closing client connection: its egress queue could not take a frame")
4068            })
4069            .collect::<Vec<_>>();
4070        assert_eq!(warn_lines.len(), 1, "exactly one WARN, got: {captured}");
4071        let line = warn_lines[0];
4072        assert!(line.contains("WARN"), "{line}");
4073        assert!(line.contains("connection_id=71"), "{line}");
4074        assert!(
4075            line.contains("module_id=\"stuck-reader-provider\""),
4076            "{line}"
4077        );
4078        assert!(line.contains("client_channel="), "{line}");
4079        assert!(line.contains("principals=direct"), "{line}");
4080        let queued_bytes: usize = line
4081            .split("queued_bytes=")
4082            .nth(1)
4083            .and_then(|rest| rest.split_whitespace().next())
4084            .and_then(|value| value.parse().ok())
4085            .expect("queued_bytes is logged");
4086        assert_eq!(queued_bytes, admitted * frame_bytes);
4087        assert!(
4088            line.contains(&format!("queued_frames={admitted}")),
4089            "{line}"
4090        );
4091        assert!(line.contains("oldest_queued_ms="), "{line}");
4092        assert!(line.contains("oldest_queued_ms=250"), "{line}");
4093        assert!(line.contains("frame_type=Some(StreamData)"), "{line}");
4094        assert!(
4095            line.contains(&format!(
4096                "frame_flags=Some({})",
4097                Flags::new(false, Priority::Interactive, false).0
4098            )),
4099            "{line}"
4100        );
4101        assert!(
4102            line.contains("close_cause=\"waited_250_ms_without_room\""),
4103            "{line}"
4104        );
4105        assert!(
4106            !line.contains(&"z".repeat(20)),
4107            "body bytes must never be logged: {line}"
4108        );
4109    }
4110
4111    fn route_frame(ty: FrameType, channel: u16, epoch: u32, corr: u64) -> Frame {
4112        Frame::build(
4113            ty,
4114            Flags::new(false, Priority::Interactive, false),
4115            channel,
4116            epoch,
4117            corr,
4118            if ty == FrameType::Request || ty == FrameType::Response {
4119                b"route-body".to_vec()
4120            } else {
4121                Vec::new()
4122            },
4123        )
4124        .unwrap()
4125    }
4126
4127    type DynamicRouteFixture = (
4128        Router,
4129        Arc<ForwardingTable>,
4130        RouteCtx,
4131        mpsc::Receiver<crate::router::OutboundFrame>,
4132        RouteCtx,
4133        mpsc::Receiver<crate::router::OutboundFrame>,
4134        mpsc::Receiver<crate::router::OutboundFrame>,
4135        crate::forwarding::PendingRouteBindRelay,
4136    );
4137
4138    fn dynamic_route_fixture(commit: bool) -> DynamicRouteFixture {
4139        dynamic_route_fixture_with_busy(commit, false)
4140    }
4141
4142    fn dynamic_route_fixture_with_busy(commit: bool, busy_refusals: bool) -> DynamicRouteFixture {
4143        let forwarding = Arc::new(ForwardingTable::default());
4144        let control = Arc::new(crate::ControlHandler::with_forwarding(
4145            Arc::new(crate::Registry::default()),
4146            Arc::clone(&forwarding),
4147        ));
4148        let router = Router::with_control_handler(control);
4149        let module_connection = ConnectionId::new(500);
4150        let client_connection = ConnectionId::new(501);
4151        let (module_tx, module_rx) = mpsc::channel(if busy_refusals { 64 } else { 8 });
4152        forwarding
4153            .register_module_connection(
4154                module_connection,
4155                "epoch-router".into(),
4156                2,
4157                Concurrency::ModuleManaged,
4158                FrameSink::new(module_tx),
4159            )
4160            .unwrap();
4161        let (client_tx, client_rx) = mpsc::channel(if busy_refusals { 64 } else { 8 });
4162        let client_sink = FrameSink::new(client_tx);
4163        let pending = forwarding
4164            .begin_route_bind_relay_with_busy_for_test(
4165                client_connection,
4166                client_sink.clone(),
4167                700,
4168                "epoch-router",
4169                busy_refusals,
4170            )
4171            .unwrap();
4172        if commit {
4173            forwarding
4174                .complete_pending_relay(
4175                    module_connection,
4176                    pending.corr,
4177                    RouteBindRelayOutcome::Accepted,
4178                )
4179                .unwrap();
4180        }
4181        let (module_egress_tx, module_egress_rx) = mpsc::channel(8);
4182        (
4183            router,
4184            forwarding,
4185            RouteCtx {
4186                connection_id: client_connection,
4187                egress: client_sink,
4188            },
4189            client_rx,
4190            RouteCtx {
4191                connection_id: module_connection,
4192                egress: FrameSink::new(module_egress_tx),
4193            },
4194            module_egress_rx,
4195            module_rx,
4196            pending,
4197        )
4198    }
4199
4200    #[tokio::test]
4201    async fn route_epochs_validate_both_directions_and_rewrite_to_peer_handle() {
4202        let (
4203            router,
4204            _forwarding,
4205            client_ctx,
4206            mut client_rx,
4207            module_ctx,
4208            _module_egress_rx,
4209            mut module_rx,
4210            pending,
4211        ) = dynamic_route_fixture(true);
4212        let route_open = client_rx.recv().await.unwrap();
4213        assert_eq!(route_open.header.corr, 700);
4214
4215        router
4216            .route_for_connection(
4217                &client_ctx,
4218                route_frame(
4219                    FrameType::Request,
4220                    pending.client_channel,
4221                    pending.client_epoch,
4222                    701,
4223                ),
4224            )
4225            .await
4226            .unwrap();
4227        let forwarded = module_rx.recv().await.unwrap();
4228        assert_eq!(forwarded.header.channel, pending.module_channel);
4229        assert_eq!(forwarded.header.epoch, pending.module_epoch);
4230
4231        router
4232            .route_for_connection(
4233                &module_ctx,
4234                route_frame(
4235                    FrameType::Response,
4236                    pending.module_channel,
4237                    pending.module_epoch,
4238                    701,
4239                ),
4240            )
4241            .await
4242            .unwrap();
4243        let delivered = client_rx.recv().await.unwrap();
4244        assert_eq!(delivered.header.channel, pending.client_channel);
4245        assert_eq!(delivered.header.epoch, pending.client_epoch);
4246
4247        router
4248            .route_for_connection(
4249                &client_ctx,
4250                route_frame(
4251                    FrameType::Request,
4252                    pending.client_channel,
4253                    pending.client_epoch + 1,
4254                    702,
4255                ),
4256            )
4257            .await
4258            .unwrap();
4259        router
4260            .route_for_connection(
4261                &module_ctx,
4262                route_frame(
4263                    FrameType::Response,
4264                    pending.module_channel,
4265                    pending.module_epoch + 1,
4266                    703,
4267                ),
4268            )
4269            .await
4270            .unwrap();
4271        let stale_error = client_rx.recv().await.unwrap();
4272        assert_eq!(stale_error.header.ty, FrameType::Error);
4273        assert_eq!(stale_error.header.channel, pending.client_channel);
4274        assert_eq!(stale_error.header.epoch, pending.client_epoch + 1);
4275        assert_eq!(stale_error.header.corr, 702);
4276        let body: ErrorBody = serde_json::from_slice(&stale_error.body).unwrap();
4277        assert_eq!(body.code, "stale_route_epoch");
4278        assert!(module_rx.try_recv().is_err());
4279        assert!(client_rx.try_recv().is_err());
4280        let counters = router.counters.snapshot();
4281        assert_eq!(counters["client_frames_dropped_stale_route"], 1);
4282        assert_eq!(counters["module_frames_dropped_no_route"], 1);
4283    }
4284
4285    #[tokio::test]
4286    async fn accepted_route_publishes_route_open_before_immediate_reverse_request() {
4287        let (
4288            router,
4289            _,
4290            _client_ctx,
4291            mut client_rx,
4292            module_ctx,
4293            _module_egress_rx,
4294            _module_rx,
4295            pending,
4296        ) = dynamic_route_fixture(true);
4297        router
4298            .route_for_connection(
4299                &module_ctx,
4300                route_frame(
4301                    FrameType::Request,
4302                    pending.module_channel,
4303                    pending.module_epoch,
4304                    800,
4305                ),
4306            )
4307            .await
4308            .unwrap();
4309
4310        let first = client_rx.recv().await.unwrap();
4311        let second = client_rx.recv().await.unwrap();
4312        assert_eq!(first.header.channel, 0);
4313        assert_eq!(first.header.corr, 700);
4314        assert_eq!(second.header.channel, pending.client_channel);
4315        assert_eq!(second.header.epoch, pending.client_epoch);
4316        assert_eq!(second.header.corr, 800);
4317    }
4318
4319    #[tokio::test]
4320    async fn reserved_slot_ingress_errors_only_matching_client_requests() {
4321        let (
4322            router,
4323            _forwarding,
4324            client_ctx,
4325            mut client_rx,
4326            _module_ctx,
4327            _module_egress_rx,
4328            mut module_rx,
4329            pending,
4330        ) = dynamic_route_fixture(false);
4331        router
4332            .route_for_connection(
4333                &client_ctx,
4334                route_frame(
4335                    FrameType::Request,
4336                    pending.client_channel,
4337                    pending.client_epoch,
4338                    900,
4339                ),
4340            )
4341            .await
4342            .unwrap();
4343        let error = client_rx.recv().await.unwrap();
4344        assert_eq!(error.header.ty, FrameType::Error);
4345        assert_eq!(error.header.channel, pending.client_channel);
4346        assert_eq!(error.header.epoch, pending.client_epoch);
4347        assert_eq!(error.header.corr, 900);
4348
4349        router
4350            .route_for_connection(
4351                &client_ctx,
4352                route_frame(
4353                    FrameType::Response,
4354                    pending.client_channel,
4355                    pending.client_epoch,
4356                    901,
4357                ),
4358            )
4359            .await
4360            .unwrap();
4361        router
4362            .route_for_connection(
4363                &client_ctx,
4364                route_frame(
4365                    FrameType::Request,
4366                    pending.client_channel,
4367                    pending.client_epoch + 1,
4368                    902,
4369                ),
4370            )
4371            .await
4372            .unwrap();
4373        let stale_error = client_rx.recv().await.unwrap();
4374        assert_eq!(stale_error.header.ty, FrameType::Error);
4375        assert_eq!(stale_error.header.channel, pending.client_channel);
4376        assert_eq!(stale_error.header.epoch, pending.client_epoch + 1);
4377        assert_eq!(stale_error.header.corr, 902);
4378        let body: ErrorBody = serde_json::from_slice(&stale_error.body).unwrap();
4379        assert_eq!(body.code, "stale_route_epoch");
4380        assert!(module_rx.try_recv().is_err());
4381        let counters = router.counters.snapshot();
4382        assert_eq!(counters["client_frames_dropped_stale_route"], 1);
4383        assert_eq!(counters["module_frames_dropped_no_route"], 0);
4384    }
4385
4386    #[tokio::test]
4387    async fn dropped_module_route_goodbye_increments_counter() {
4388        let (
4389            router,
4390            _forwarding,
4391            client_ctx,
4392            mut client_rx,
4393            _module_ctx,
4394            _module_egress_rx,
4395            mut module_rx,
4396            pending,
4397        ) = dynamic_route_fixture(true);
4398        let _ = client_rx.recv().await;
4399        module_rx.close();
4400
4401        router
4402            .route_for_connection(
4403                &client_ctx,
4404                route_frame(
4405                    FrameType::Goodbye,
4406                    pending.client_channel,
4407                    pending.client_epoch,
4408                    999,
4409                ),
4410            )
4411            .await
4412            .unwrap();
4413
4414        let counters = router.counters.snapshot();
4415        assert_eq!(counters["goodbye_relay_module_dropped"], 1);
4416        assert_eq!(
4417            counters["goodbye_relay_module_dropped_by_module"],
4418            serde_json::json!({ "epoch-router": 1 })
4419        );
4420        assert_eq!(counters["route_released_epoch_fenced"], 1);
4421    }
4422
4423    #[tokio::test]
4424    async fn module_request_on_stale_epoch_receives_stale_route_epoch() {
4425        let (
4426            router,
4427            _forwarding,
4428            _client_ctx,
4429            _client_rx,
4430            module_ctx,
4431            mut module_egress_rx,
4432            mut module_rx,
4433            pending,
4434        ) = dynamic_route_fixture(true);
4435
4436        router
4437            .route_for_connection(
4438                &module_ctx,
4439                route_frame(
4440                    FrameType::Request,
4441                    pending.module_channel,
4442                    pending.module_epoch + 1,
4443                    1_000,
4444                ),
4445            )
4446            .await
4447            .unwrap();
4448
4449        let error = module_egress_rx.try_recv().unwrap();
4450        assert_eq!(error.header.ty, FrameType::Error);
4451        assert_eq!(error.header.channel, pending.module_channel);
4452        assert_eq!(error.header.epoch, pending.module_epoch + 1);
4453        assert_eq!(error.header.corr, 1_000);
4454        let body: ErrorBody = serde_json::from_slice(&error.body).unwrap();
4455        assert_eq!(body.code, "stale_route_epoch");
4456        assert!(module_rx.try_recv().is_err());
4457        let counters = router.counters.snapshot();
4458        assert_eq!(counters["module_requests_dropped_stale_route"], 1);
4459        assert_eq!(counters["module_frames_dropped_no_route"], 0);
4460    }
4461
4462    #[tokio::test(start_paused = true)]
4463    async fn stale_epoch_drop_warns_once_per_minute_with_suppressed_count() {
4464        let (output, _guard) = test_log::log_capture(tracing::Level::WARN);
4465        let (
4466            router,
4467            _forwarding,
4468            client_ctx,
4469            mut client_rx,
4470            _module_ctx,
4471            _module_egress_rx,
4472            mut module_rx,
4473            pending,
4474        ) = dynamic_route_fixture(true);
4475        let _ = client_rx.recv().await;
4476        for corr in 1..=3 {
4477            router
4478                .route_for_connection(
4479                    &client_ctx,
4480                    route_frame(
4481                        FrameType::Request,
4482                        pending.client_channel,
4483                        pending.client_epoch + 1,
4484                        corr,
4485                    ),
4486                )
4487                .await
4488                .unwrap();
4489            assert_eq!(client_rx.recv().await.unwrap().header.ty, FrameType::Error);
4490        }
4491        assert!(module_rx.try_recv().is_err());
4492        let logs = test_log::captured_logs(&output);
4493        assert_eq!(
4494            logs.matches("dropping data-plane frame").count(),
4495            1,
4496            "{logs}"
4497        );
4498        assert!(logs.contains("WARN"), "{logs}");
4499        assert!(
4500            logs.contains(&format!("connection_id={}", client_ctx.connection_id.get())),
4501            "{logs}"
4502        );
4503        assert!(
4504            logs.contains(&format!("channel={}", pending.client_channel)),
4505            "{logs}"
4506        );
4507        assert!(
4508            logs.contains(&format!("epoch={}", pending.client_epoch + 1)),
4509            "{logs}"
4510        );
4511        assert!(
4512            logs.contains("client_to_module") && logs.contains("stale_epoch"),
4513            "{logs}"
4514        );
4515        assert!(logs.contains("suppressed=0"), "{logs}");
4516
4517        tokio::time::advance(Duration::from_secs(60)).await;
4518        router
4519            .route_for_connection(
4520                &client_ctx,
4521                route_frame(
4522                    FrameType::Request,
4523                    pending.client_channel,
4524                    pending.client_epoch + 2,
4525                    4,
4526                ),
4527            )
4528            .await
4529            .unwrap();
4530        let logs = test_log::captured_logs(&output);
4531        assert_eq!(
4532            logs.matches("dropping data-plane frame").count(),
4533            2,
4534            "{logs}"
4535        );
4536        assert!(logs.contains("suppressed=2"), "{logs}");
4537    }
4538
4539    #[tokio::test]
4540    async fn module_request_on_reserved_or_absent_route_receives_unknown_channel() {
4541        let (
4542            reserved_router,
4543            _forwarding,
4544            _client_ctx,
4545            _client_rx,
4546            reserved_module_ctx,
4547            mut reserved_module_egress_rx,
4548            _module_rx,
4549            reserved,
4550        ) = dynamic_route_fixture(false);
4551        reserved_router
4552            .route_for_connection(
4553                &reserved_module_ctx,
4554                route_frame(
4555                    FrameType::Request,
4556                    reserved.module_channel,
4557                    reserved.module_epoch,
4558                    1_001,
4559                ),
4560            )
4561            .await
4562            .unwrap();
4563        let reserved_error = reserved_module_egress_rx.try_recv().unwrap();
4564        let reserved_body: ErrorBody = serde_json::from_slice(&reserved_error.body).unwrap();
4565        assert_eq!(reserved_error.header.ty, FrameType::Error);
4566        assert_eq!(reserved_error.header.channel, reserved.module_channel);
4567        assert_eq!(reserved_error.header.epoch, reserved.module_epoch);
4568        assert_eq!(reserved_error.header.corr, 1_001);
4569        assert_eq!(reserved_body.code, "unknown_channel");
4570        assert_eq!(
4571            reserved_router.counters.snapshot()["module_requests_dropped_stale_route"],
4572            1
4573        );
4574
4575        let (
4576            absent_router,
4577            _forwarding,
4578            _client_ctx,
4579            _client_rx,
4580            absent_module_ctx,
4581            mut absent_module_egress_rx,
4582            _module_rx,
4583            absent,
4584        ) = dynamic_route_fixture(false);
4585        absent_router
4586            .route_for_connection(
4587                &absent_module_ctx,
4588                route_frame(
4589                    FrameType::Request,
4590                    absent.module_channel + 1,
4591                    absent.module_epoch,
4592                    1_002,
4593                ),
4594            )
4595            .await
4596            .unwrap();
4597        let absent_error = absent_module_egress_rx.try_recv().unwrap();
4598        let absent_body: ErrorBody = serde_json::from_slice(&absent_error.body).unwrap();
4599        assert_eq!(absent_error.header.ty, FrameType::Error);
4600        assert_eq!(absent_error.header.channel, absent.module_channel + 1);
4601        assert_eq!(absent_error.header.epoch, absent.module_epoch);
4602        assert_eq!(absent_error.header.corr, 1_002);
4603        assert_eq!(absent_body.code, "unknown_channel");
4604        assert_eq!(
4605            absent_router.counters.snapshot()["module_requests_dropped_stale_route"],
4606            1
4607        );
4608    }
4609
4610    #[tokio::test]
4611    async fn non_request_module_frame_on_dead_route_is_counted_without_error() {
4612        let (
4613            router,
4614            forwarding,
4615            client_ctx,
4616            mut client_rx,
4617            module_ctx,
4618            mut module_egress_rx,
4619            mut module_rx,
4620            pending,
4621        ) = dynamic_route_fixture(true);
4622        let (other_module_tx, _other_module_rx) = mpsc::channel(8);
4623        forwarding
4624            .register_module_connection(
4625                ConnectionId::new(502),
4626                "other-module".into(),
4627                2,
4628                Concurrency::ModuleManaged,
4629                FrameSink::new(other_module_tx),
4630            )
4631            .unwrap();
4632        let _ = client_rx.recv().await.unwrap();
4633
4634        router
4635            .route_for_connection(
4636                &client_ctx,
4637                route_frame(
4638                    FrameType::Goodbye,
4639                    pending.client_channel,
4640                    pending.client_epoch,
4641                    1_003,
4642                ),
4643            )
4644            .await
4645            .unwrap();
4646        let _ = module_rx.recv().await.unwrap();
4647
4648        router
4649            .route_for_connection(
4650                &module_ctx,
4651                route_frame(
4652                    FrameType::StreamData,
4653                    pending.module_channel,
4654                    pending.module_epoch,
4655                    1_004,
4656                ),
4657            )
4658            .await
4659            .unwrap();
4660
4661        // No ERROR goes back for a non-request frame. The one reply is the
4662        // route GOODBYE telling the module to let go of the released route.
4663        let reply = module_egress_rx.try_recv().unwrap();
4664        assert_eq!(reply.header.ty, FrameType::Goodbye);
4665        assert!(module_egress_rx.try_recv().is_err());
4666        let counters = router.counters.snapshot();
4667        assert_eq!(counters["module_frames_dropped_no_route"], 1);
4668        assert_eq!(
4669            counters["module_frames_dropped_no_route_by_module"],
4670            serde_json::json!({ "epoch-router": 1 })
4671        );
4672        assert_eq!(counters["module_requests_dropped_stale_route"], 0);
4673    }
4674
4675    /// Drain whatever the module connection's queue holds right now, the way a
4676    /// module's reader would before it stalls.
4677    fn drain_now(rx: &mut mpsc::Receiver<OutboundFrame>) {
4678        while rx.try_recv().is_ok() {}
4679    }
4680
4681    /// A module that stops reading for a moment when a client closes one of
4682    /// its routes still learns the route is gone: the GOODBYE its full egress
4683    /// queue refused is delivered as soon as it reads again, rather than
4684    /// dropped, which would leave the module holding the route for the rest of
4685    /// its connection.
4686    #[tokio::test]
4687    async fn route_goodbye_refused_by_stalled_module_is_delivered_when_it_resumes_reading() {
4688        const BUDGET: usize = 4_096;
4689        let forwarding = Arc::new(ForwardingTable::default());
4690        let control = Arc::new(ControlHandler::with_forwarding(
4691            Arc::new(Registry::default()),
4692            Arc::clone(&forwarding),
4693        ));
4694        let router = Router::with_control_handler(control);
4695        let module_connection = ConnectionId::new(80);
4696        let client_connection = ConnectionId::new(81);
4697        let (module_tx, mut module_rx) = mpsc::channel(64);
4698        let module_sink = FrameSink::with_byte_budget(module_tx, BUDGET);
4699        forwarding
4700            .register_module_connection(
4701                module_connection,
4702                "stalled-provider".into(),
4703                2,
4704                Concurrency::ModuleManaged,
4705                module_sink.clone(),
4706            )
4707            .unwrap();
4708        let (client_tx, mut client_rx) = mpsc::channel(8);
4709        let client_sink = FrameSink::new(client_tx);
4710        let pending = forwarding
4711            .begin_route_bind_relay_for_test(
4712                client_connection,
4713                client_sink.clone(),
4714                1_100,
4715                "stalled-provider",
4716            )
4717            .unwrap();
4718        forwarding
4719            .complete_pending_relay(
4720                module_connection,
4721                pending.corr,
4722                RouteBindRelayOutcome::Accepted,
4723            )
4724            .unwrap();
4725        let _ = client_rx.recv().await.unwrap();
4726        drain_now(&mut module_rx);
4727
4728        // The module stalls: its queue holds more than the byte budget, so the
4729        // queue refuses anything further.
4730        module_sink
4731            .try_send(stream_frame(9, 1, 0, vec![b'f'; BUDGET]))
4732            .unwrap();
4733        assert!(module_sink
4734            .try_send(stream_frame(9, 1, 1, Vec::new()))
4735            .is_err());
4736
4737        let client_ctx = RouteCtx {
4738            connection_id: client_connection,
4739            egress: client_sink,
4740        };
4741        router
4742            .route_for_connection(
4743                &client_ctx,
4744                route_frame(
4745                    FrameType::Goodbye,
4746                    pending.client_channel,
4747                    pending.client_epoch,
4748                    1_101,
4749                ),
4750            )
4751            .await
4752            .unwrap();
4753        tokio::task::yield_now().await;
4754        assert_eq!(
4755            router.counters.snapshot()["goodbye_relay_module_dropped"],
4756            0,
4757            "a GOODBYE refused by a momentarily full module queue must not be dropped"
4758        );
4759
4760        // The module reads again: the filler comes off, then the GOODBYE.
4761        let filler = module_rx.recv().await.unwrap();
4762        assert_eq!(filler.header.ty, FrameType::StreamData);
4763        drop(filler);
4764        let goodbye = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
4765            .await
4766            .expect("the refused GOODBYE must be delivered once the module frees room")
4767            .unwrap();
4768        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
4769        assert_eq!(goodbye.header.channel, pending.module_channel);
4770        assert_eq!(goodbye.header.epoch, pending.module_epoch);
4771        assert_eq!(
4772            router.counters.snapshot()["goodbye_relay_module_dropped"],
4773            0
4774        );
4775    }
4776
4777    /// A module still sending on a route the daemon released is told, with a
4778    /// route GOODBYE for exactly the (channel, epoch) it sent on. The same
4779    /// happens for a stale epoch on a channel whose route moved on and for a
4780    /// channel that never had a route; only the first is counted as traffic on
4781    /// a released route.
4782    #[tokio::test]
4783    async fn module_frame_on_route_the_daemon_does_not_hold_is_answered_with_goodbye() {
4784        let (
4785            router,
4786            _forwarding,
4787            client_ctx,
4788            mut client_rx,
4789            module_ctx,
4790            mut module_egress_rx,
4791            mut module_rx,
4792            pending,
4793        ) = dynamic_route_fixture(true);
4794        let _ = client_rx.recv().await.unwrap();
4795        router
4796            .route_for_connection(
4797                &client_ctx,
4798                route_frame(
4799                    FrameType::Goodbye,
4800                    pending.client_channel,
4801                    pending.client_epoch,
4802                    1_200,
4803                ),
4804            )
4805            .await
4806            .unwrap();
4807        drain_now(&mut module_rx);
4808
4809        let cases = [
4810            // Released route: the daemon allocated this (channel, epoch).
4811            (pending.module_channel, pending.module_epoch),
4812            // A channel the daemon never allocated on this connection.
4813            (pending.module_channel + 1, 1),
4814        ];
4815        for (channel, epoch) in cases {
4816            router
4817                .route_for_connection(
4818                    &module_ctx,
4819                    route_frame(FrameType::StreamData, channel, epoch, 1_201),
4820                )
4821                .await
4822                .unwrap();
4823            let reply = module_egress_rx
4824                .try_recv()
4825                .expect("a frame on a route the daemon does not hold is answered");
4826            assert_eq!(reply.header.ty, FrameType::Goodbye);
4827            assert_eq!(reply.header.channel, channel);
4828            assert_eq!(reply.header.epoch, epoch);
4829            assert_eq!(reply.header.corr, 0);
4830            assert!(module_egress_rx.try_recv().is_err());
4831        }
4832
4833        // A GOODBYE from the module for a route the daemon already released
4834        // is not answered: the module is letting go already.
4835        router
4836            .route_for_connection(
4837                &module_ctx,
4838                route_frame(FrameType::Goodbye, pending.module_channel + 2, 1, 0),
4839            )
4840            .await
4841            .unwrap();
4842        assert!(module_egress_rx.try_recv().is_err());
4843
4844        let counters = router.counters.snapshot();
4845        assert_eq!(counters["module_frames_dropped_no_route"], 3);
4846        assert_eq!(counters["module_frames_dropped_released_route"], 1);
4847        assert_eq!(
4848            counters["module_frames_dropped_released_route_by_module"],
4849            serde_json::json!({ "epoch-router": 1 })
4850        );
4851        assert_eq!(counters["module_orphan_route_goodbyes_sent"], 2);
4852    }
4853
4854    /// A chatty orphan (a streaming module still producing on a route it
4855    /// missed the GOODBYE for) is answered once per interval, not once per
4856    /// frame, and answered again once the interval has passed.
4857    #[tokio::test(start_paused = true)]
4858    async fn burst_of_orphan_module_frames_is_answered_once_per_interval() {
4859        let (
4860            router,
4861            _forwarding,
4862            client_ctx,
4863            mut client_rx,
4864            module_ctx,
4865            mut module_egress_rx,
4866            mut module_rx,
4867            pending,
4868        ) = dynamic_route_fixture(true);
4869        let _ = client_rx.recv().await.unwrap();
4870        router
4871            .route_for_connection(
4872                &client_ctx,
4873                route_frame(
4874                    FrameType::Goodbye,
4875                    pending.client_channel,
4876                    pending.client_epoch,
4877                    1_300,
4878                ),
4879            )
4880            .await
4881            .unwrap();
4882        drain_now(&mut module_rx);
4883
4884        let send_burst = |corr: u64| {
4885            route_frame(
4886                FrameType::StreamData,
4887                pending.module_channel,
4888                pending.module_epoch,
4889                corr,
4890            )
4891        };
4892        for corr in 0..20 {
4893            router
4894                .route_for_connection(&module_ctx, send_burst(corr))
4895                .await
4896                .unwrap();
4897        }
4898        let mut replies = 0;
4899        while let Ok(reply) = module_egress_rx.try_recv() {
4900            assert_eq!(reply.header.ty, FrameType::Goodbye);
4901            replies += 1;
4902        }
4903        assert_eq!(replies, 1, "a burst within the interval gets one GOODBYE");
4904
4905        tokio::time::advance(ORPHAN_ROUTE_GOODBYE_INTERVAL).await;
4906        router
4907            .route_for_connection(&module_ctx, send_burst(20))
4908            .await
4909            .unwrap();
4910        let retry = module_egress_rx
4911            .try_recv()
4912            .expect("the first orphan frame after the interval is answered again");
4913        assert_eq!(retry.header.channel, pending.module_channel);
4914        assert_eq!(retry.header.epoch, pending.module_epoch);
4915
4916        let counters = router.counters.snapshot();
4917        assert_eq!(counters["module_frames_dropped_no_route"], 21);
4918        assert_eq!(counters["module_orphan_route_goodbyes_sent"], 2);
4919    }
4920
4921    /// The rate-limit memory is per connection and goes away with it.
4922    #[test]
4923    fn orphan_goodbye_rate_limit_state_is_released_with_the_connection() {
4924        let router = Router::with_default_self_handler();
4925        let connection = router.begin_connection();
4926        let id = connection.id();
4927        assert!(router.orphan_goodbyes.claim(id, 7));
4928        assert!(!router.orphan_goodbyes.claim(id, 7));
4929        assert!(router.orphan_goodbyes.claim(id, 8));
4930        drop(connection);
4931        assert!(router
4932            .orphan_goodbyes
4933            .last_sent
4934            .lock()
4935            .unwrap()
4936            .get(&id)
4937            .is_none());
4938    }
4939
4940    #[test]
4941    fn channel_zero_cannot_be_registered_as_backend() {
4942        let mut router = Router::with_default_self_handler();
4943
4944        let err = router.register_backend(0, EchoBackend).unwrap_err();
4945
4946        assert_eq!(err, RouterError::ReservedChannelZero);
4947    }
4948
4949    mod audit_findings {
4950        use super::*;
4951        include!("router_audit_tests.rs");
4952    }
4953}