Skip to main content

rings_node/extension/
dispatch.rs

1//! Per-namespace dispatch of inbound envelopes.
2//!
3//! ```text
4//!   inbox reader ──submit(from, bytes)──▶ queue[namespace] ──worker──▶ Route::dispatch
5//!                  (never waits; a refused       (one task per namespace, until stop)
6//!                   envelope is dropped, counted)        └──────────▶ Route::observe_link
7//!              ──PeerAdmitted(p)────────▶ Admitted(p), every queue (coalesced on unread churn)
8//!              ──PeerRetired(p)─────────▶ Retired(p), every queue  (withdraws unread Admitted(p)
9//!                                         when no queued envelope follows it)
10//!              ──MessageDropped(p)──────▶ Dropped(p), every queue, once per generation while unread
11//!              ──refused from admitted p─▶ Dropped(p), its queue, once per generation while unread
12//! ```
13//!
14//! Laws:
15//! - Each registered namespace's envelopes are dispatched in arrival order, one at a time.
16//! - Namespaces are independent: a protocol that waits holds back only its own queue.
17//! - Registration is checked once, here: an envelope enters a queue only with the [`Route`] its
18//!   namespace resolved to, so only registered namespaces get a queue and the number of tasks
19//!   is bounded by the registry.
20//! - Each queue bounds envelopes twice: by [`NAMESPACE_QUEUE_CAPACITY`] envelopes, and by
21//!   [`NAMESPACE_QUEUE_WEIGHT`] encoded bytes queued or in dispatch. A queue holding no bytes
22//!   admits any envelope, so a namespace holds at most `max(NAMESPACE_QUEUE_WEIGHT, one
23//!   envelope)`, and the largest envelope the transport carries still gets through.
24//! - Control facts ([`LinkFact`]) share the namespace's arrival order and are coalesced per peer
25//!   (`#1214`, [`FactTransition`]) so sustained peer churn while a protocol callback is pending
26//!   cannot accumulate an unbounded history:
27//!   - `Retired(p)` withdraws a matching unread `Admitted(p)` (together with any `Dropped(p)`
28//!     queued after that `Admitted(p)`) whenever no queued envelope follows that `Admitted(p)`
29//!     ([`FactTransition::WithdrewAdmission`]). When a queued envelope *does* follow `Admitted(p)`,
30//!     both `Admitted(p)` (before the envelope) and `Retired(p)` (after it) are retained so
31//!     queued envelopes always observe their link lifetime and protocol state is invalidated on
32//!     retirement.
33//!   - Within one link state, `Dropped(p)` is queued at most once while `p` is not already
34//!     waiting on `Retired(p)`, and consecutive duplicate `Admitted(p)` or `Retired(p)` facts are
35//!     coalesced ([`FactTransition::Coalesced`]).
36//!   - Consequently, an envelope-free queue retains at most [`NAMESPACE_RUN_FACT_BOUND_PER_PEER`]
37//!     (`4`) facts per peer (`[Dropped] [Retired] [Admitted] [Dropped]`). Across `k ≤
38//!     NAMESPACE_QUEUE_CAPACITY` queued envelopes, one peer retains at most
39//!     `3 · k + 4 ≤ NAMESPACE_PEER_FACT_BOUND` facts.
40//!   - An envelope refused by a full queue from an admitted peer records `Dropped(p)` for that
41//!     namespace (#966); a drop by the core's own inbox (`SwarmEvent::MessageDropped`, #969)
42//!     names no namespace and goes to every registered namespace. A refusal from a peer not
43//!     admitted makes none, since no link state rides a link that is not up. The fact names the
44//!     envelope's verified signer, which is the adjacent hop for a direct send; an overlay-routed
45//!     envelope from an admitted origin names that origin's link though another carried it, so the
46//!     fact may end link state that lost nothing, never miss state that did.
47//! - Every envelope that is not dispatched is counted by its [`DispatchDrop`] reason, and logged
48//!   at `warn`.
49//! - The workers end once the stop of the [`Backend::serve`](super::Backend::serve) that started
50//!   them is requested, abandoning what they still hold.
51
52use std::collections::BTreeMap;
53use std::collections::HashMap;
54use std::collections::VecDeque;
55use std::sync::atomic::AtomicU64;
56use std::sync::atomic::Ordering;
57use std::sync::Arc;
58use std::sync::Mutex;
59use std::sync::MutexGuard;
60use std::sync::PoisonError;
61use std::task::Poll;
62use std::task::Waker;
63
64use bytes::Bytes;
65use futures::future::poll_fn;
66use futures::FutureExt;
67use rings_core::dht::Did;
68use rings_core::lifecycle::StopToken;
69use rings_core::swarm::application::APPLICATION_INBOX_WEIGHT;
70use serde::Serialize;
71
72use crate::extension::ext::Core;
73use crate::extension::ext::Envelope;
74use crate::extension::ext::LinkFact;
75use crate::extension::ext::Route;
76use crate::tasks::NodeTasks;
77
78/// Envelopes one namespace may hold, queued or in dispatch, before further ones are dropped.
79const NAMESPACE_QUEUE_CAPACITY: usize = 256;
80
81/// Encoded bytes one namespace may hold, queued or in dispatch, before further envelopes are
82/// dropped: a quarter of the core inbox's [`APPLICATION_INBOX_WEIGHT`], so the few built-in
83/// namespaces together park about what the inbox itself retains.
84const NAMESPACE_QUEUE_WEIGHT: usize = APPLICATION_INBOX_WEIGHT / 4;
85
86/// Maximum control facts one peer may retain when no envelope waits in the namespace queue:
87/// `[Dropped] [Retired] [Admitted] [Dropped]`.
88const NAMESPACE_RUN_FACT_BOUND_PER_PEER: usize = 4;
89
90/// Maximum control facts one peer may retain across an entire namespace queue holding at most
91/// [`NAMESPACE_QUEUE_CAPACITY`] envelopes (`3 * k + 4` for `k <= NAMESPACE_QUEUE_CAPACITY`).
92const NAMESPACE_PEER_FACT_BOUND: usize =
93    3 * NAMESPACE_QUEUE_CAPACITY + NAMESPACE_RUN_FACT_BOUND_PER_PEER;
94
95/// Why the router dropped an envelope instead of dispatching it.
96#[derive(Clone, Copy, Debug, Eq, PartialEq)]
97pub(crate) enum DispatchDrop {
98    /// The custom message did not decode as an [`Envelope`].
99    Undecodable,
100    /// No protocol is registered under the envelope's namespace.
101    Unregistered,
102    /// The namespace's queue was full, by count or by bytes.
103    QueueFull,
104    /// No worker runs the namespace's queue: there was no runtime to start one.
105    Unserved,
106}
107
108/// The envelopes the router dropped, by [`DispatchDrop`] reason. Shared by a
109/// [`Provider`](crate::provider::Provider), which reads it, and the backends serving it.
110#[derive(Debug, Default)]
111pub(crate) struct DispatchDrops {
112    undecodable: AtomicU64,
113    unregistered: AtomicU64,
114    queue_full: AtomicU64,
115    unserved: AtomicU64,
116}
117
118/// A reading of the envelopes the router dropped, by reason; each count is cumulative since the
119/// provider was created.
120#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
121#[serde(rename_all = "camelCase")]
122pub struct DispatchDropCounters {
123    /// Custom messages that did not decode as an envelope.
124    pub undecodable: u64,
125    /// Envelopes of a namespace no protocol is registered under.
126    pub unregistered: u64,
127    /// Envelopes refused by their namespace's full queue.
128    pub queue_full: u64,
129    /// Envelopes of a namespace no worker could be started for.
130    pub unserved: u64,
131}
132
133impl DispatchDrops {
134    /// The counter of `reason`.
135    fn counter(&self, reason: DispatchDrop) -> &AtomicU64 {
136        match reason {
137            DispatchDrop::Undecodable => &self.undecodable,
138            DispatchDrop::Unregistered => &self.unregistered,
139            DispatchDrop::QueueFull => &self.queue_full,
140            DispatchDrop::Unserved => &self.unserved,
141        }
142    }
143
144    /// Count one envelope dropped for `reason`, and log it.
145    fn record(&self, reason: DispatchDrop) {
146        let dropped = self
147            .counter(reason)
148            .fetch_add(1, Ordering::Relaxed)
149            .saturating_add(1);
150        tracing::warn!(?reason, dropped, "application envelope dropped");
151    }
152
153    /// The counts so far.
154    pub(crate) fn counters(&self) -> DispatchDropCounters {
155        DispatchDropCounters {
156            undecodable: self.undecodable.load(Ordering::Relaxed),
157            unregistered: self.unregistered.load(Ordering::Relaxed),
158            queue_full: self.queue_full.load(Ordering::Relaxed),
159            unserved: self.unserved.load(Ordering::Relaxed),
160        }
161    }
162}
163
164/// One item waiting for its namespace's worker.
165enum Queued {
166    /// An envelope from `from`, holding `weight` encoded bytes until its dispatch ends.
167    Envelope {
168        route: Route,
169        from: Did,
170        payload: Bytes,
171        weight: usize,
172    },
173    /// A fact about the link to one peer.
174    Fact { route: Route, fact: LinkFact },
175}
176
177/// Monotonic position of an item in one [`NamespaceQueue`].
178type Position = u64;
179
180/// Named coalescing transition when recording a [`LinkFact`] (#1214).
181#[derive(Clone, Copy, Debug, Eq, PartialEq)]
182enum FactTransition {
183    /// The fact was appended to the queue in arrival order.
184    Queued,
185    /// `Retired(peer)` withdrew its matching unread `Admitted(peer)` (and any `Dropped(peer)`
186    /// after it) because no queued envelope depended on that unobserved link generation.
187    WithdrewAdmission,
188    /// A duplicate `Dropped`, `Admitted`, or `Retired` within the current link state was coalesced
189    /// into the fact already waiting.
190    Coalesced,
191    /// No worker serves this namespace queue.
192    Unserved,
193}
194
195/// Indexed positions of one peer's queued control facts, in ascending order.
196#[derive(Default)]
197struct PeerFacts {
198    /// Queued admissions (`true`) and retirements (`false`), by position.
199    lifecycle: VecDeque<(Position, bool)>,
200    /// Queued `Dropped` facts, by position.
201    drops: VecDeque<Position>,
202}
203
204impl PeerFacts {
205    fn last_lifecycle(&self) -> Option<Position> {
206        self.lifecycle.back().map(|(at, _)| *at)
207    }
208
209    fn len(&self) -> usize {
210        self.lifecycle.len() + self.drops.len()
211    }
212
213    fn is_empty(&self) -> bool {
214        self.lifecycle.is_empty() && self.drops.is_empty()
215    }
216}
217
218/// Whether a queue holding `held` bytes admits an envelope of `weight` more: always when it
219/// holds none.
220fn admits(held: usize, weight: usize) -> bool {
221    held == 0 || held.saturating_add(weight) <= NAMESPACE_QUEUE_WEIGHT
222}
223
224/// Shared state of one namespace's ordered queue.
225#[derive(Default)]
226struct Queue {
227    /// Producer dropped: worker drains remaining items and exits.
228    closed: bool,
229    /// Receiver dropped (no runtime or worker stopped): refuse envelopes as `Unserved`.
230    unserved: bool,
231    /// Queued items in arrival order, keyed by monotonic position so withdrawn admissions are
232    /// removed in place without shifting other items.
233    items: BTreeMap<Position, Queued>,
234    /// Next position to assign.
235    next: Position,
236    /// Position of the latest `Queued::Envelope` still waiting in `items`, if any.
237    last_envelope: Option<Position>,
238    /// Per-peer positions of queued control facts.
239    facts: BTreeMap<Did, PeerFacts>,
240    /// Envelopes currently waiting in `items` or executing `Route::dispatch`.
241    envelopes: usize,
242    /// Encoded envelope bytes currently waiting in `items` or executing `Route::dispatch`.
243    weight: usize,
244    /// Worker task waker when parked on an empty queue.
245    waker: Option<Waker>,
246}
247
248impl Queue {
249    /// Whether this queue admits one more envelope of `weight` bytes.
250    fn admits_envelope(&self, weight: usize) -> bool {
251        self.envelopes < NAMESPACE_QUEUE_CAPACITY && admits(self.weight, weight)
252    }
253
254    fn append(&mut self, queued: Queued) -> Position {
255        let at = self.next;
256        self.next = at.saturating_add(1);
257        self.items.insert(at, queued);
258        at
259    }
260
261    fn push_envelope(
262        &mut self,
263        route: Route,
264        from: Did,
265        payload: Bytes,
266        weight: usize,
267    ) -> Result<Option<Waker>, DispatchDrop> {
268        if self.unserved {
269            return Err(DispatchDrop::Unserved);
270        }
271        if !self.admits_envelope(weight) {
272            return Err(DispatchDrop::QueueFull);
273        }
274        self.envelopes = self.envelopes.saturating_add(1);
275        self.weight = self.weight.saturating_add(weight);
276        let at = self.append(Queued::Envelope {
277            route,
278            from,
279            payload,
280            weight,
281        });
282        self.last_envelope = Some(at);
283        Ok(self.waker.take())
284    }
285
286    fn release_envelope(&mut self, weight: usize) {
287        if !self.unserved {
288            self.envelopes = self.envelopes.saturating_sub(1);
289            self.weight = self.weight.saturating_sub(weight);
290        }
291    }
292
293    fn record_fact(&mut self, route: Route, fact: LinkFact) -> (FactTransition, Option<Waker>) {
294        if self.unserved {
295            return (FactTransition::Unserved, None);
296        }
297        let peer = fact.peer();
298        let result = match fact {
299            LinkFact::Admitted(_) => {
300                if self
301                    .facts
302                    .get(&peer)
303                    .and_then(|facts| facts.lifecycle.back())
304                    .is_some_and(|&(_, admitted)| admitted)
305                {
306                    (FactTransition::Coalesced, None)
307                } else {
308                    let at = self.append(Queued::Fact { route, fact });
309                    self.facts
310                        .entry(peer)
311                        .or_default()
312                        .lifecycle
313                        .push_back((at, true));
314                    (FactTransition::Queued, self.waker.take())
315                }
316            }
317            LinkFact::Retired(_) => {
318                let withdraw_at = self
319                    .facts
320                    .get(&peer)
321                    .and_then(|facts| facts.lifecycle.back())
322                    .and_then(|&(at, admitted)| {
323                        (admitted && self.last_envelope.is_none_or(|env_at| at > env_at))
324                            .then_some(at)
325                    });
326                if let Some(admitted_at) = withdraw_at {
327                    let mut remove_peer = false;
328                    let mut withdrawn_drops = Vec::new();
329                    if let Some(facts) = self.facts.get_mut(&peer) {
330                        facts.lifecycle.pop_back();
331                        while facts.drops.back().is_some_and(|&at| at > admitted_at) {
332                            if let Some(drop_at) = facts.drops.pop_back() {
333                                withdrawn_drops.push(drop_at);
334                            }
335                        }
336                        remove_peer = facts.is_empty();
337                    }
338                    if remove_peer {
339                        self.facts.remove(&peer);
340                    }
341                    self.items.remove(&admitted_at);
342                    for drop_at in withdrawn_drops {
343                        self.items.remove(&drop_at);
344                    }
345                    (FactTransition::WithdrewAdmission, None)
346                } else if self
347                    .facts
348                    .get(&peer)
349                    .and_then(|facts| facts.lifecycle.back())
350                    .is_some_and(|&(_, admitted)| !admitted)
351                {
352                    (FactTransition::Coalesced, None)
353                } else {
354                    let at = self.append(Queued::Fact { route, fact });
355                    self.facts
356                        .entry(peer)
357                        .or_default()
358                        .lifecycle
359                        .push_back((at, false));
360                    (FactTransition::Queued, self.waker.take())
361                }
362            }
363            LinkFact::Dropped(_) => {
364                let coalesced = self.facts.get(&peer).is_some_and(|facts| {
365                    let retired = facts
366                        .lifecycle
367                        .back()
368                        .is_some_and(|&(_, admitted)| !admitted);
369                    let since = facts.last_lifecycle();
370                    let drop_waiting = facts
371                        .drops
372                        .back()
373                        .is_some_and(|&at| since.is_none_or(|since| at > since));
374                    retired || drop_waiting
375                });
376                if coalesced {
377                    (FactTransition::Coalesced, None)
378                } else {
379                    let at = self.append(Queued::Fact { route, fact });
380                    self.facts.entry(peer).or_default().drops.push_back(at);
381                    (FactTransition::Queued, self.waker.take())
382                }
383            }
384        };
385        debug_assert!(self.facts.get(&peer).is_none_or(|facts| {
386            let bound = if self.last_envelope.is_none() {
387                NAMESPACE_RUN_FACT_BOUND_PER_PEER
388            } else {
389                NAMESPACE_PEER_FACT_BOUND
390            };
391            facts.len() <= bound
392        }));
393        result
394    }
395
396    fn take(&mut self) -> Option<Queued> {
397        let (at, queued) = self.items.pop_first()?;
398        match &queued {
399            Queued::Envelope { .. } => {
400                if self.last_envelope == Some(at) {
401                    self.last_envelope = None;
402                }
403            }
404            Queued::Fact { fact, .. } => {
405                let peer = fact.peer();
406                let mut remove_peer = false;
407                if let Some(facts) = self.facts.get_mut(&peer) {
408                    match fact {
409                        LinkFact::Admitted(_) | LinkFact::Retired(_) => {
410                            if facts.lifecycle.front().is_some_and(|&(pos, _)| pos == at) {
411                                facts.lifecycle.pop_front();
412                            } else {
413                                facts.lifecycle.retain(|&(pos, _)| pos != at);
414                            }
415                        }
416                        LinkFact::Dropped(_) => {
417                            if facts.drops.front() == Some(&at) {
418                                facts.drops.pop_front();
419                            } else {
420                                facts.drops.retain(|&pos| pos != at);
421                            }
422                        }
423                    }
424                    remove_peer = facts.is_empty();
425                }
426                if remove_peer {
427                    self.facts.remove(&peer);
428                }
429            }
430        }
431        Some(queued)
432    }
433
434    fn close_sender(&mut self) -> Option<Waker> {
435        self.closed = true;
436        self.waker.take()
437    }
438
439    fn close_receiver(&mut self) {
440        self.unserved = true;
441        self.items.clear();
442        self.facts.clear();
443        self.last_envelope = None;
444        self.envelopes = 0;
445        self.weight = 0;
446        self.waker = None;
447    }
448}
449
450#[derive(Default)]
451struct Shared {
452    queue: Mutex<Queue>,
453}
454
455impl Shared {
456    /// Every critical section leaves [`Queue`] consistent, so a poisoned lock remains valid.
457    fn lock(&self) -> MutexGuard<'_, Queue> {
458        self.queue.lock().unwrap_or_else(PoisonError::into_inner)
459    }
460}
461
462/// Producer handle for one namespace's queue.
463struct NamespaceQueue {
464    shared: Arc<Shared>,
465}
466
467/// Worker handle for one namespace's queue.
468struct NamespaceReceiver {
469    shared: Arc<Shared>,
470}
471
472/// Releases an envelope's count and byte weight once `Route::dispatch` finishes or is cancelled.
473struct EnvelopePermit {
474    shared: Arc<Shared>,
475    weight: usize,
476}
477
478impl Drop for EnvelopePermit {
479    fn drop(&mut self) {
480        self.shared.lock().release_envelope(self.weight);
481    }
482}
483
484impl Drop for NamespaceQueue {
485    fn drop(&mut self) {
486        let waker = self.shared.lock().close_sender();
487        if let Some(waker) = waker {
488            waker.wake();
489        }
490    }
491}
492
493impl Drop for NamespaceReceiver {
494    fn drop(&mut self) {
495        self.shared.lock().close_receiver();
496    }
497}
498
499fn channel() -> (NamespaceQueue, NamespaceReceiver) {
500    let shared = Arc::new(Shared::default());
501    (
502        NamespaceQueue {
503            shared: Arc::clone(&shared),
504        },
505        NamespaceReceiver { shared },
506    )
507}
508
509impl NamespaceReceiver {
510    async fn next(&self) -> Option<Queued> {
511        poll_fn(|cx| {
512            let mut queue = self.shared.lock();
513            if let Some(queued) = queue.take() {
514                return Poll::Ready(Some(queued));
515            }
516            if queue.closed {
517                return Poll::Ready(None);
518            }
519            queue.waker = Some(cx.waker().clone());
520            Poll::Pending
521        })
522        .await
523    }
524}
525
526/// The dispatch queue of every namespace that has received an envelope or link fact.
527pub(super) struct NamespaceQueues {
528    core: Core,
529    queues: HashMap<String, NamespaceQueue>,
530    drops: Arc<DispatchDrops>,
531    stop: StopToken,
532}
533
534impl NamespaceQueues {
535    /// No queue yet, over the registry of `core`, counting drops in `drops`; the workers end
536    /// once `stop` is requested.
537    pub(super) fn new(core: Core, drops: Arc<DispatchDrops>, stop: StopToken) -> Self {
538        Self {
539            core,
540            queues: HashMap::new(),
541            drops,
542            stop,
543        }
544    }
545
546    /// Queue the encoded envelope `bytes` from `from` for its namespace's worker, starting the
547    /// worker on first use; drop it, counted, when it is refused, telling the namespace of a drop
548    /// from an admitted peer ([`LinkFact::Dropped`]). Never waits.
549    ///
550    /// The envelope is read in place: its payload is a slice of `bytes`, and its namespace is
551    /// copied only when the namespace's queue is first made.
552    pub(super) fn submit(&mut self, from: Did, bytes: &Bytes) {
553        let Ok(envelope) = Envelope::view(bytes) else {
554            self.drops.record(DispatchDrop::Undecodable);
555            return;
556        };
557        let Some(route) = self.core.route(envelope.namespace) else {
558            self.drops.record(DispatchDrop::Unregistered);
559            return;
560        };
561        let queue = queue_of(
562            &mut self.queues,
563            self.core.tasks(),
564            &self.stop,
565            envelope.namespace,
566        );
567        let weight = bytes.len();
568        let payload = bytes.slice_ref(envelope.payload);
569        match queue.submit_envelope(route.clone(), from, payload, weight) {
570            Ok(()) => {}
571            Err(DispatchDrop::QueueFull) => {
572                self.drops.record(DispatchDrop::QueueFull);
573                if self.core.peer_admitted(from) {
574                    queue.tell(route, LinkFact::Dropped(from));
575                }
576            }
577            Err(reason) => self.drops.record(reason),
578        }
579    }
580
581    /// Queue `fact` for every registered namespace, behind the envelopes already queued: an
582    /// admission, a retirement, or a drop by the core's inbox, which names no namespace. Never
583    /// waits; coalesces per-peer churn according to [`FactTransition`].
584    pub(super) fn submit_link_fact(&mut self, fact: LinkFact) {
585        for (namespace, route) in self.core.routes() {
586            let queue = queue_of(&mut self.queues, self.core.tasks(), &self.stop, &namespace);
587            queue.tell(route, fact);
588        }
589    }
590}
591
592impl NamespaceQueue {
593    fn submit_envelope(
594        &self,
595        route: Route,
596        from: Did,
597        payload: Bytes,
598        weight: usize,
599    ) -> Result<(), DispatchDrop> {
600        let waker = self
601            .shared
602            .lock()
603            .push_envelope(route, from, payload, weight)?;
604        if let Some(waker) = waker {
605            waker.wake();
606        }
607        Ok(())
608    }
609
610    /// Record `fact` for `route` under the queue's coalescing policy.
611    fn tell(&self, route: Route, fact: LinkFact) -> FactTransition {
612        let (transition, waker) = self.shared.lock().record_fact(route, fact);
613        if let Some(waker) = waker {
614            waker.wake();
615        }
616        if transition == FactTransition::Unserved {
617            tracing::error!(?fact, "no worker to deliver a link fact");
618        }
619        transition
620    }
621}
622
623/// The queue of `namespace` in `queues`, starting its worker as a node task of `tasks`, which
624/// ends once `stop` is requested or the node stops, on first use.
625fn queue_of<'queues>(
626    queues: &'queues mut HashMap<String, NamespaceQueue>,
627    tasks: &NodeTasks,
628    stop: &StopToken,
629    namespace: &str,
630) -> &'queues NamespaceQueue {
631    if !queues.contains_key(namespace) {
632        queues.insert(namespace.to_owned(), spawn_worker(tasks, stop.clone()));
633    }
634    &queues[namespace]
635}
636
637/// Start the worker of one namespace as a node task of `tasks`: it dispatches its envelopes in
638/// order until its queue is dropped, `stop` is requested, or the node stops. Without a runtime
639/// to run it, the receiver is dropped immediately, so every envelope is dropped and counted.
640fn spawn_worker(tasks: &NodeTasks, stop: StopToken) -> NamespaceQueue {
641    let (queue, receiver) = channel();
642    let drain = drain(receiver);
643    let worker = async move {
644        let stopped = stop.stopped().fuse();
645        let drain = drain.fuse();
646        futures::pin_mut!(stopped, drain);
647        futures::select_biased! {
648            () = stopped => {},
649            () = drain => {},
650        }
651    };
652    if tasks.spawn(worker).is_err() {
653        tracing::error!("no runtime to run a namespace dispatch worker");
654    }
655    queue
656}
657
658/// Dispatch every item of `receiver` in order, releasing each envelope's held capacity once its
659/// dispatch ends.
660async fn drain(receiver: NamespaceReceiver) {
661    while let Some(queued) = receiver.next().await {
662        let dispatched = match queued {
663            Queued::Envelope {
664                route,
665                from,
666                payload,
667                weight,
668            } => {
669                let _permit = EnvelopePermit {
670                    shared: Arc::clone(&receiver.shared),
671                    weight,
672                };
673                route.dispatch(from, payload).await
674            }
675            Queued::Fact { route, fact } => route.observe_link(fact).await,
676        };
677        if let Err(error) = dispatched {
678            tracing::warn!(error = ?error, "protocol dispatch failed");
679        }
680    }
681}
682
683#[cfg(test)]
684mod tests {
685    use super::admits;
686    use super::DispatchDrop;
687    use super::DispatchDropCounters;
688    use super::DispatchDrops;
689    use super::Queue;
690    use super::NAMESPACE_QUEUE_CAPACITY;
691    use super::NAMESPACE_QUEUE_WEIGHT;
692
693    #[test]
694    fn test_each_drop_is_counted_under_its_own_reason() {
695        let drops = DispatchDrops::default();
696        drops.record(DispatchDrop::Undecodable);
697        drops.record(DispatchDrop::QueueFull);
698        drops.record(DispatchDrop::QueueFull);
699        assert_eq!(drops.counters(), DispatchDropCounters {
700            undecodable: 1,
701            unregistered: 0,
702            queue_full: 2,
703            unserved: 0,
704        });
705    }
706
707    /// Law: a queue admits an envelope iff it holds fewer than `NAMESPACE_QUEUE_CAPACITY`
708    /// envelopes within its weight; a release makes room again.
709    #[test]
710    fn test_a_queue_admits_envelopes_up_to_its_capacity() {
711        let mut queue = Queue::default();
712        for _ in 0..NAMESPACE_QUEUE_CAPACITY {
713            assert!(queue.admits_envelope(1));
714            queue.envelopes += 1;
715            queue.weight += 1;
716        }
717        assert!(!queue.admits_envelope(1));
718        queue.release_envelope(1);
719        assert!(queue.admits_envelope(1));
720    }
721
722    #[test]
723    fn test_an_empty_queue_admits_any_envelope() {
724        assert!(admits(0, NAMESPACE_QUEUE_WEIGHT.saturating_mul(4)));
725    }
726
727    #[test]
728    fn test_a_holding_queue_admits_up_to_its_weight_only() {
729        assert!(admits(1, NAMESPACE_QUEUE_WEIGHT - 1));
730        assert!(!admits(1, NAMESPACE_QUEUE_WEIGHT));
731    }
732
733    #[cfg(rings_native)]
734    mod native {
735        use std::sync::Arc;
736        use std::sync::Mutex;
737        use std::time::Duration;
738
739        use async_trait::async_trait;
740        use bytes::Bytes;
741        use rings_core::delegation::DelegateeKey;
742        use rings_core::dht::Did;
743        use rings_core::ecc::SecretKey;
744        use rings_core::lifecycle::StopSource;
745
746        use super::super::channel;
747        use super::super::DispatchDrops;
748        use super::super::FactTransition;
749        use super::super::NamespaceQueues;
750        use super::super::Queued;
751        use super::super::NAMESPACE_PEER_FACT_BOUND;
752        use super::super::NAMESPACE_RUN_FACT_BOUND_PER_PEER;
753        use crate::extension::ext::Ctx;
754        use crate::extension::ext::EffectScope;
755        use crate::extension::ext::Envelope;
756        use crate::extension::ext::Extensions;
757        use crate::extension::ext::Interpret;
758        use crate::extension::ext::LinkFact;
759        use crate::extension::ext::Protocol;
760        use crate::extension::ext::Reject;
761        use crate::extension::ext::Route;
762        use crate::extension::ext::Transition;
763        use crate::extension::ext::Wire;
764        use crate::processor::ProcessorBuilder;
765        use crate::processor::ProcessorConfig;
766
767        #[derive(Clone, Debug, Eq, PartialEq)]
768        enum ObservedItem {
769            Payload(Did, Bytes),
770            Fact(LinkFact),
771        }
772
773        struct TestProtocol {
774            namespace: &'static str,
775        }
776
777        impl Protocol for TestProtocol {
778            type State = ();
779            type Event = ObservedItem;
780            type Effect = ObservedItem;
781
782            fn namespace(&self) -> &str {
783                self.namespace
784            }
785
786            fn init(&self) -> Self::State {}
787
788            fn decode(&self, wire: Wire<'_>) -> std::result::Result<Self::Event, Reject> {
789                Ok(ObservedItem::Payload(
790                    wire.from,
791                    Bytes::copy_from_slice(wire.payload),
792                ))
793            }
794
795            fn step(
796                &self,
797                _ctx: Ctx<'_, Self::State>,
798                event: Self::Event,
799            ) -> Transition<Self::State, Self::Effect> {
800                Transition::with((), vec![event])
801            }
802
803            fn link_fact(&self, fact: LinkFact) -> Option<Self::Event> {
804                Some(ObservedItem::Fact(fact))
805            }
806        }
807
808        struct RecordingInterpreter {
809            observed: Arc<Mutex<Vec<ObservedItem>>>,
810        }
811
812        #[async_trait]
813        impl Interpret for RecordingInterpreter {
814            type Effect = ObservedItem;
815
816            async fn run(
817                &self,
818                _scope: &EffectScope,
819                effect: Self::Effect,
820            ) -> crate::error::Result<Vec<Bytes>> {
821                self.observed.lock().expect("observed log").push(effect);
822                Ok(Vec::new())
823            }
824        }
825
826        fn test_extensions_and_route(namespace: &'static str) -> (Extensions, Route) {
827            let key = DelegateeKey::new_with_seckey(&SecretKey::random()).expect("delegatee key");
828            let config = ProcessorConfig::new(1, String::new(), key, 1);
829            let processor = ProcessorBuilder::from_config(&config)
830                .expect("builder")
831                .advertise_presence(false)
832                .build()
833                .expect("processor");
834            let extensions = Extensions::new(Arc::new(processor));
835            extensions
836                .register(TestProtocol { namespace }, RecordingInterpreter {
837                    observed: Arc::new(Mutex::new(Vec::new())),
838                })
839                .expect("register test protocol");
840            let route = extensions.core().route(namespace).expect("resolved route");
841            (extensions, route)
842        }
843
844        /// Law (#966): at most one `Dropped` fact per peer generation waits in a queue; once the
845        /// worker takes it, a later drop from that peer is told again.
846        #[tokio::test]
847        async fn test_a_drop_is_told_once_while_its_fact_waits() {
848            let (_extensions, route) = test_extensions_and_route("drop-once");
849            let (sender, _receiver) = channel();
850            let peer = Did::from(7_u32);
851
852            assert_eq!(
853                sender.tell(route.clone(), LinkFact::Dropped(peer)),
854                FactTransition::Queued
855            );
856            assert_eq!(
857                sender.tell(route.clone(), LinkFact::Dropped(peer)),
858                FactTransition::Coalesced
859            );
860            assert_eq!(
861                sender.tell(route.clone(), LinkFact::Dropped(Did::from(8_u32))),
862                FactTransition::Queued
863            );
864
865            let taken = sender.shared.lock().take();
866            assert!(matches!(
867                taken,
868                Some(Queued::Fact {
869                    fact: LinkFact::Dropped(actual),
870                    ..
871                }) if actual == peer
872            ));
873            assert_eq!(
874                sender.tell(route, LinkFact::Dropped(peer)),
875                FactTransition::Queued
876            );
877        }
878
879        /// Regression (#1214): 10,000 alternating `Admitted` / `Retired` pairs on an unread
880        /// namespace queue coalesce instead of retaining 20,000 items, while preserving an initial
881        /// `Retired` needed to invalidate already-admitted protocol state.
882        #[tokio::test]
883        async fn test_unread_peer_churn_is_bounded_and_preserves_prior_retirement() {
884            let (_extensions, route) = test_extensions_and_route("churn-bound");
885            let (sender, _receiver) = channel();
886            let peer = Did::from(42_u32);
887
888            // Case 1: peer was not previously admitted; 10,000 unobserved admit+retire pairs
889            // collapse to zero retained items.
890            for _ in 0..10_000 {
891                assert_eq!(
892                    sender.tell(route.clone(), LinkFact::Admitted(peer)),
893                    FactTransition::Queued
894                );
895                assert_eq!(
896                    sender.tell(route.clone(), LinkFact::Dropped(peer)),
897                    FactTransition::Queued
898                );
899                assert_eq!(
900                    sender.tell(route.clone(), LinkFact::Retired(peer)),
901                    FactTransition::WithdrewAdmission
902                );
903            }
904            {
905                let guard = sender.shared.lock();
906                assert_eq!(guard.items.len(), 0);
907                assert!(guard.facts.is_empty());
908                assert_eq!(guard.envelopes, 0);
909                assert_eq!(guard.weight, 0);
910            }
911
912            // Case 2: peer WAS admitted before the worker stalled (worker already consumed
913            // Admitted). Subsequent churn must retain the initial `Retired(peer)` to invalidate
914            // old link state, while drops arriving while retired coalesce into `Retired(peer)`.
915            assert_eq!(
916                sender.tell(route.clone(), LinkFact::Dropped(peer)),
917                FactTransition::Queued
918            );
919            assert_eq!(
920                sender.tell(route.clone(), LinkFact::Retired(peer)),
921                FactTransition::Queued
922            );
923            assert_eq!(
924                sender.tell(route.clone(), LinkFact::Dropped(peer)),
925                FactTransition::Coalesced
926            );
927            for _ in 0..10_000 {
928                assert_eq!(
929                    sender.tell(route.clone(), LinkFact::Admitted(peer)),
930                    FactTransition::Queued
931                );
932                assert_eq!(
933                    sender.tell(route.clone(), LinkFact::Retired(peer)),
934                    FactTransition::WithdrewAdmission
935                );
936            }
937            assert_eq!(
938                sender.tell(route.clone(), LinkFact::Admitted(peer)),
939                FactTransition::Queued
940            );
941            assert_eq!(
942                sender.tell(route, LinkFact::Dropped(peer)),
943                FactTransition::Queued
944            );
945
946            let drained: Vec<LinkFact> = std::iter::from_fn(|| sender.shared.lock().take())
947                .map(|item| match item {
948                    Queued::Fact { fact, .. } => fact,
949                    Queued::Envelope { .. } => panic!("expected only link facts"),
950                })
951                .collect();
952            assert!(drained.len() <= NAMESPACE_RUN_FACT_BOUND_PER_PEER);
953            assert_eq!(drained, vec![
954                LinkFact::Dropped(peer),
955                LinkFact::Retired(peer),
956                LinkFact::Admitted(peer),
957                LinkFact::Dropped(peer),
958            ]);
959        }
960
961        /// Regression (#1214): queued envelopes pin the `Admitted` / `Retired` facts of the link
962        /// generation they arrived in (and per-generation `Dropped` visibility), while unobserved
963        /// churn before, between, and after envelopes coalesces within `NAMESPACE_PEER_FACT_BOUND`.
964        #[tokio::test]
965        async fn test_interleaved_envelopes_preserve_needed_link_facts_and_coalesce_churn() {
966            let (_extensions, route) = test_extensions_and_route("interleaved");
967            let (sender, _receiver) = channel();
968            let peer = Did::from(77_u32);
969
970            // Pre-envelope churn coalesces completely.
971            for _ in 0..100 {
972                sender.tell(route.clone(), LinkFact::Admitted(peer));
973                sender.tell(route.clone(), LinkFact::Retired(peer));
974            }
975
976            // Generation 1 carries envelope `e1` and a drop, then retires.
977            sender.tell(route.clone(), LinkFact::Admitted(peer));
978            sender
979                .submit_envelope(route.clone(), peer, Bytes::from_static(b"e1"), 2)
980                .expect("admit e1");
981            sender.tell(route.clone(), LinkFact::Dropped(peer));
982            sender.tell(route.clone(), LinkFact::Dropped(peer));
983            assert_eq!(
984                sender.tell(route.clone(), LinkFact::Retired(peer)),
985                FactTransition::Queued,
986                "retirement after a queued envelope must be preserved"
987            );
988
989            // 500 unobserved churn cycles between `e1` and `e2` collapse to zero items.
990            for _ in 0..500 {
991                sender.tell(route.clone(), LinkFact::Admitted(peer));
992                sender.tell(route.clone(), LinkFact::Dropped(peer));
993                assert_eq!(
994                    sender.tell(route.clone(), LinkFact::Retired(peer)),
995                    FactTransition::WithdrewAdmission
996                );
997            }
998
999            // Generation 2 carries envelope `e2` and a fresh drop (not suppressed by gen 1's
1000            // drop!).
1001            sender.tell(route.clone(), LinkFact::Admitted(peer));
1002            sender
1003                .submit_envelope(route.clone(), peer, Bytes::from_static(b"e2"), 2)
1004                .expect("admit e2");
1005            assert_eq!(
1006                sender.tell(route.clone(), LinkFact::Dropped(peer)),
1007                FactTransition::Queued
1008            );
1009            assert_eq!(
1010                sender.tell(route.clone(), LinkFact::Retired(peer)),
1011                FactTransition::Queued
1012            );
1013
1014            assert!(sender.shared.lock().items.len() <= NAMESPACE_PEER_FACT_BOUND);
1015
1016            let drained: Vec<ObservedItem> = std::iter::from_fn(|| sender.shared.lock().take())
1017                .map(|item| match item {
1018                    Queued::Envelope { from, payload, .. } => ObservedItem::Payload(from, payload),
1019                    Queued::Fact { fact, .. } => ObservedItem::Fact(fact),
1020                })
1021                .collect();
1022            assert_eq!(drained, vec![
1023                ObservedItem::Fact(LinkFact::Admitted(peer)),
1024                ObservedItem::Payload(peer, Bytes::from_static(b"e1")),
1025                ObservedItem::Fact(LinkFact::Dropped(peer)),
1026                ObservedItem::Fact(LinkFact::Retired(peer)),
1027                ObservedItem::Fact(LinkFact::Admitted(peer)),
1028                ObservedItem::Payload(peer, Bytes::from_static(b"e2")),
1029                ObservedItem::Fact(LinkFact::Dropped(peer)),
1030                ObservedItem::Fact(LinkFact::Retired(peer)),
1031            ]);
1032        }
1033
1034        struct BlockingInterpreter {
1035            entered: Arc<tokio::sync::Notify>,
1036            release: Arc<tokio::sync::Notify>,
1037            block_first: Mutex<bool>,
1038            observed: Arc<Mutex<Vec<ObservedItem>>>,
1039        }
1040
1041        #[async_trait]
1042        impl Interpret for BlockingInterpreter {
1043            type Effect = ObservedItem;
1044
1045            async fn run(
1046                &self,
1047                _scope: &EffectScope,
1048                effect: Self::Effect,
1049            ) -> crate::error::Result<Vec<Bytes>> {
1050                let should_block = {
1051                    let mut first = self.block_first.lock().expect("block_first");
1052                    let was_first = *first;
1053                    *first = false;
1054                    was_first
1055                };
1056                if should_block {
1057                    self.entered.notify_one();
1058                    self.release.notified().await;
1059                }
1060                self.observed.lock().expect("observed").push(effect);
1061                Ok(Vec::new())
1062            }
1063        }
1064
1065        /// Regression (#1214): when one namespace worker blocks inside a callback under sustained
1066        /// single-peer churn and interleaved envelopes, a sibling namespace progresses
1067        /// independently and the stalled namespace remains bounded and delivers coherent state once
1068        /// unblocked.
1069        #[tokio::test]
1070        async fn test_stalled_namespace_bounds_churn_while_sibling_namespace_progresses() {
1071            let key = DelegateeKey::new_with_seckey(&SecretKey::random()).expect("delegatee key");
1072            let config = ProcessorConfig::new(1, String::new(), key, 1);
1073            let processor = ProcessorBuilder::from_config(&config)
1074                .expect("builder")
1075                .advertise_presence(false)
1076                .build()
1077                .expect("processor");
1078            let extensions = Extensions::new(Arc::new(processor));
1079
1080            let stalled_entered = Arc::new(tokio::sync::Notify::new());
1081            let stalled_release = Arc::new(tokio::sync::Notify::new());
1082            let stalled_observed = Arc::new(Mutex::new(Vec::new()));
1083            let fast_observed = Arc::new(Mutex::new(Vec::new()));
1084
1085            extensions
1086                .register(
1087                    TestProtocol {
1088                        namespace: "stalled",
1089                    },
1090                    BlockingInterpreter {
1091                        entered: Arc::clone(&stalled_entered),
1092                        release: Arc::clone(&stalled_release),
1093                        block_first: Mutex::new(true),
1094                        observed: Arc::clone(&stalled_observed),
1095                    },
1096                )
1097                .expect("register stalled");
1098            extensions
1099                .register(TestProtocol { namespace: "fast" }, RecordingInterpreter {
1100                    observed: Arc::clone(&fast_observed),
1101                })
1102                .expect("register fast");
1103
1104            let drops = Arc::new(DispatchDrops::default());
1105            let stop = StopSource::new();
1106            let mut queues =
1107                NamespaceQueues::new(extensions.core(), Arc::clone(&drops), stop.token());
1108            let peer = Did::from(55_u32);
1109
1110            let encode_env = |ns: &str, body: &'static [u8]| -> Bytes {
1111                Bytes::from(
1112                    Envelope::new(ns, Bytes::from_static(body))
1113                        .encode()
1114                        .expect("encode envelope"),
1115                )
1116            };
1117
1118            // Stall `stalled` on its first `Admitted(peer)` callback.
1119            queues.submit_link_fact(LinkFact::Admitted(peer));
1120            tokio::time::timeout(Duration::from_secs(2), stalled_entered.notified())
1121                .await
1122                .expect("stalled worker entered callback");
1123
1124            // Interleave an envelope on the open generation, retire it, then churn 2,000 times
1125            // while also submitting work to `fast`.
1126            queues.submit(peer, &encode_env("stalled", b"gen1-msg"));
1127            queues.submit(peer, &encode_env("fast", b"fast-1"));
1128            queues.submit_link_fact(LinkFact::Retired(peer));
1129            for _ in 0..2_000 {
1130                queues.submit_link_fact(LinkFact::Admitted(peer));
1131                queues.submit_link_fact(LinkFact::Retired(peer));
1132            }
1133            queues.submit_link_fact(LinkFact::Admitted(peer));
1134            queues.submit(peer, &encode_env("fast", b"fast-2"));
1135
1136            // `fast` must progress to completion without waiting on `stalled`!
1137            tokio::time::timeout(Duration::from_secs(2), async {
1138                loop {
1139                    let len = fast_observed.lock().expect("fast_observed").len();
1140                    if fast_observed.lock().expect("fast_observed").last()
1141                        == Some(&ObservedItem::Payload(peer, Bytes::from_static(b"fast-2")))
1142                    {
1143                        assert!(len >= 4);
1144                        break;
1145                    }
1146                    tokio::time::sleep(Duration::from_millis(5)).await;
1147                }
1148            })
1149            .await
1150            .expect("fast namespace progressed independently");
1151
1152            // Meanwhile `stalled` is still blocked on item 0 and its queued tail must be tiny!
1153            {
1154                let stalled_queue = queues.queues.get("stalled").expect("stalled queue");
1155                let guard = stalled_queue.shared.lock();
1156                assert_eq!(
1157                    guard.items.len(),
1158                    3,
1159                    "only [Envelope(gen1-msg), Retired(peer), Admitted(peer)] should remain queued"
1160                );
1161            }
1162
1163            // Release `stalled` and verify exact preserved causal sequence!
1164            stalled_release.notify_waiters();
1165            tokio::time::timeout(Duration::from_secs(2), async {
1166                loop {
1167                    if stalled_observed.lock().expect("stalled_observed").len() == 4 {
1168                        break;
1169                    }
1170                    tokio::time::sleep(Duration::from_millis(5)).await;
1171                }
1172            })
1173            .await
1174            .expect("stalled namespace drained after release");
1175
1176            assert_eq!(*stalled_observed.lock().expect("stalled_observed"), vec![
1177                ObservedItem::Fact(LinkFact::Admitted(peer)),
1178                ObservedItem::Payload(peer, Bytes::from_static(b"gen1-msg")),
1179                ObservedItem::Fact(LinkFact::Retired(peer)),
1180                ObservedItem::Fact(LinkFact::Admitted(peer)),
1181            ]);
1182            stop.request_stop();
1183        }
1184    }
1185}