rings_node/extension/mod.rs
1//! This module provide basic mechanism.
2
3mod dispatch;
4pub mod ext;
5pub mod protocols;
6#[cfg(rings_native)]
7pub mod transport;
8use std::sync::Arc;
9
10use bytes::Bytes;
11use futures::FutureExt;
12use rings_core::lifecycle::StopToken;
13use rings_core::message::CustomMessage;
14use rings_core::swarm::application::ApplicationData;
15use rings_core::swarm::application::ApplicationDelivery;
16use rings_core::swarm::application::ApplicationInbox;
17use rings_core::swarm::application::ApplicationMessage;
18
19pub use crate::extension::dispatch::DispatchDropCounters;
20pub(crate) use crate::extension::dispatch::DispatchDrops;
21use crate::extension::ext::Extensions;
22use crate::extension::ext::LinkFact;
23use crate::provider::Provider;
24
25/// Observer of what the [`Backend`] reads from the application inbox but does not act on
26/// itself: the peer facts, and the E2E messages it routes to no protocol.
27///
28/// The backend hands the observer each item in inbox order, before it reads the next. Facts are
29/// the swarm's logical conclusions, never a physical connection state. The observer must not
30/// block: it runs on the inbox's one reader.
31///
32/// A fact reaches the observer as soon as it is read, while the custom messages read before it
33/// may still wait in their namespace's queue: facts keep their order among themselves and with
34/// E2E messages, but may overtake custom messages.
35pub trait BackendObserver: Send + Sync {
36 /// A fact about this node's link to one peer, the same fact every namespace's queue is
37 /// given: [`LinkFact::Admitted`] when the peer's transport is ready and it joined the local
38 /// DHT, [`LinkFact::Retired`] when it left, whichever physical event or local decision caused
39 /// it, and [`LinkFact::Dropped`] when the core's inbox dropped a message from it.
40 fn link_fact(&self, _fact: LinkFact) {}
41
42 /// An E2E message (handshake or stream frame) addressed to this node.
43 fn e2e_message(&self, _message: &ApplicationMessage) {}
44
45 /// An inbound serialized extension [`Envelope`](ext::Envelope) received from `from` before it
46 /// is queued onto its namespace worker.
47 fn custom_envelope(&self, _from: rings_core::dht::Did, _bytes: &[u8]) {}
48}
49
50/// Backend consumes the swarm's application inbox: it routes each inbound custom message,
51/// decoded as an [`Envelope`](ext::Envelope), to its namespace's protocol via the
52/// [`Extensions`] registry, and hands everything else to the optional [`BackendObserver`]. The
53/// registry is shared with the [`Provider`], so protocols registered there are visible to
54/// inbound dispatch here. Each protocol's interpreter does its IO through a namespace-scoped
55/// [`Scope`](ext::Scope).
56///
57/// The swarm never waits on the backend (#935): it reads at its own pace, and a full inbox
58/// drops further live messages. Each registered namespace is dispatched by its own task, in the
59/// order its messages arrived, so a protocol waiting on a slow send holds back neither another
60/// namespace nor the peer facts; a namespace whose queue is full drops further messages,
61/// counted, as the inbox does. Facts and E2E messages go to the observer at once, so a fact can
62/// overtake a custom message still queued for its namespace.
63///
64/// Every message the backend drops is counted in the provider's
65/// [`dispatch_drop_counters`](Provider::dispatch_drop_counters).
66pub struct Backend {
67 extensions: Extensions,
68 drops: Arc<DispatchDrops>,
69 observer: Option<Arc<dyn BackendObserver>>,
70}
71
72impl Backend {
73 /// Create a new backend over a provider, sharing its protocol registry.
74 pub fn new(provider: Arc<Provider>) -> Self {
75 Self {
76 extensions: provider.extensions(),
77 drops: provider.dispatch_drops(),
78 observer: None,
79 }
80 }
81
82 /// Attach the observer that receives peer facts and E2E messages.
83 pub fn observed_by(mut self, observer: Arc<dyn BackendObserver>) -> Self {
84 self.observer = Some(observer);
85 self
86 }
87
88 /// Consume `inbox` until the swarm is gone or `stop` is requested; the namespace workers it
89 /// starts end with it once `stop` is requested.
90 pub async fn serve(self, inbox: ApplicationInbox, stop: StopToken) {
91 let mut namespaces = dispatch::NamespaceQueues::new(
92 self.extensions.core(),
93 Arc::clone(&self.drops),
94 stop.clone(),
95 );
96 loop {
97 let delivery = futures::select_biased! {
98 () = stop.stopped().fuse() => return,
99 delivery = inbox.next().fuse() => delivery,
100 };
101 let Some(delivery) = delivery else {
102 return;
103 };
104 self.route(&mut namespaces, delivery);
105 }
106 }
107
108 /// Route one item of the application inbox: a custom message to its namespace's queue, a
109 /// peer's admission (#843), its retirement (#963) or a drop by the core's inbox (#969), as
110 /// one [`LinkFact`], to every namespace's queue and to the observer. Never waits.
111 fn route(&self, namespaces: &mut dispatch::NamespaceQueues, delivery: ApplicationDelivery) {
112 match delivery {
113 ApplicationDelivery::Message(ApplicationMessage {
114 from,
115 data: ApplicationData::Custom(CustomMessage(bytes)),
116 ..
117 }) => {
118 if let Some(observer) = self.observer.as_deref() {
119 observer.custom_envelope(from, &bytes);
120 }
121 namespaces.submit(from, &Bytes::from(bytes));
122 }
123 ApplicationDelivery::Message(message) => {
124 if let Some(observer) = self.observer.as_deref() {
125 observer.e2e_message(&message);
126 }
127 }
128 ApplicationDelivery::Event(event) => {
129 if let Some(fact) = LinkFact::of(&event) {
130 namespaces.submit_link_fact(fact);
131 if let Some(observer) = self.observer.as_deref() {
132 observer.link_fact(fact);
133 }
134 }
135 }
136 _ => {}
137 }
138 }
139}