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