rings_core/swarm/application/mod.rs
1#![deny(missing_docs)]
2
3//! The boundary between core and the application (#935).
4//!
5//! Core defines, handles and judges every protocol message itself. The application sees only
6//! what core hands it through this boundary:
7//!
8//! ```text
9//! core inbound lanes ──deliver (queued, or dropped)──┐
10//! relay-inbox drain ──try_reserve ▸ fill───────────┤
11//! connection lifecycle ──announce───────────────────┼──▶ ApplicationInbox::next ──▶ app
12//! successor lookups ──answer──▶ SuccessorReport ─────┘ (a handle the app awaited itself)
13//! delegated namespaces ◀── registered in advance by the app, read by core as data
14//! ```
15//!
16//! Laws:
17//! - **Core never waits on the application.** Core never calls, awaits or waits for
18//! application code. Application delivery is lossy by design: a full inbox drops further live
19//! application data, counted ([`ApplicationInbox::dropped`]) and logged at `warn`, as a
20//! best-effort network drops it, and no lane and no lifecycle transition ever waits for the
21//! application to read. A protocol that needs a reliable stream detects loss end to end, as
22//! the E2E stream decryptor's stall deadline does (#939). Stored relay mail is offered only
23//! when it fits, and is retired once the application took it from the inbox; what the
24//! application does with it afterwards is the application's.
25//! - Only [`ApplicationData`] crosses the boundary, in both directions: no control message has
26//! a representation here. Inbound, the projection `ApplicationData::project` is total over
27//! [`Message`] variants, so a new variant fails to compile until it is classified; outbound,
28//! the application sends only `ApplicationData`, injected into [`Message`] by `From`.
29//! - Events are the logical facts [`SwarmEvent::PeerAdmitted`] and [`SwarmEvent::PeerRetired`],
30//! never a physical connection state.
31
32mod delegation;
33mod inbox;
34mod lookup;
35mod relay;
36
37use std::sync::Arc;
38
39use delegation::DelegatedNamespaces;
40use futures::lock::Mutex as FuturesMutex;
41pub use inbox::ApplicationInbox;
42use inbox::ApplicationOutlet;
43pub(crate) use inbox::Delivered;
44pub use inbox::APPLICATION_INBOX_WEIGHT;
45use lookup::ApplicationLookups;
46pub use lookup::SuccessorReport;
47pub(crate) use relay::RelayConsumption;
48use relay::RelayInFlight;
49pub(crate) use relay::RelayTransactionId;
50
51use crate::dht::Did;
52use crate::message::e2e::E2eHandshakeRequest;
53use crate::message::e2e::E2eHandshakeResponse;
54use crate::message::e2e::E2eStreamFrame;
55use crate::message::CustomMessage;
56use crate::message::Message;
57use crate::message::MessagePayload;
58use crate::message::MessageVerificationExt;
59
60/// Core's side of the boundary, held by the transport: everything core hands the application,
61/// and the one piece of application configuration core reads.
62pub(crate) struct ApplicationPort {
63 /// The inbox core writes.
64 pub(crate) outlet: ApplicationOutlet,
65 /// The application's outstanding successor lookups.
66 pub(crate) lookups: Arc<ApplicationLookups>,
67 /// The namespaces whose admission the application delegated.
68 pub(crate) delegations: DelegatedNamespaces,
69 /// The namespaces whose replay the application delegated (#1081).
70 pub(crate) replay_delegations: DelegatedNamespaces,
71 /// Relay mail handed to the inbox and not yet retired from storage.
72 pub(crate) relay_in_flight: RelayInFlight,
73 /// Held by the pass over this node's relay inbox: a pass, from local storage or from a fetch,
74 /// that finds another running leaves the elements to the next one.
75 pub(crate) relay_drain: FuturesMutex<()>,
76}
77
78impl ApplicationPort {
79 /// A port with an unclaimed inbox, no lookups and no delegation.
80 pub(crate) fn new() -> Self {
81 Self {
82 outlet: ApplicationOutlet::new(),
83 lookups: Arc::new(ApplicationLookups::default()),
84 delegations: DelegatedNamespaces::default(),
85 replay_delegations: DelegatedNamespaces::default(),
86 relay_in_flight: RelayInFlight::default(),
87 relay_drain: FuturesMutex::new(()),
88 }
89 }
90}
91
92/// The body of a message core hands to the application: the message classes that carry
93/// application data. Every other class is core's own.
94#[derive(Clone, Debug, PartialEq, Eq)]
95#[non_exhaustive]
96pub enum ApplicationData {
97 /// An application message (`CustomMessage`).
98 Custom(CustomMessage),
99 /// A request to negotiate E2E encryption.
100 E2eHandshakeRequest(E2eHandshakeRequest),
101 /// An acceptance of E2E encryption.
102 E2eHandshakeResponse(E2eHandshakeResponse),
103 /// One encrypted E2E stream frame.
104 E2eStreamFrame(E2eStreamFrame),
105}
106
107impl ApplicationData {
108 /// The application data `message` carries, if it carries any.
109 ///
110 /// Laws (with [`From`] as the injection into [`Message`]):
111 /// - total and exhaustive over [`Message`]: `project(m) = Some(_)` exactly for the
112 /// `Application` and `E2e` classes other than a chunk, which core reassembles first;
113 /// - `project(Message::from(d)) = Some(d)`.
114 pub(crate) fn project(message: Message) -> Option<Self> {
115 match message {
116 Message::CustomMessage(message) => Some(Self::Custom(message)),
117 Message::E2eHandshakeRequest(request) => Some(Self::E2eHandshakeRequest(request)),
118 Message::E2eHandshakeResponse(response) => Some(Self::E2eHandshakeResponse(response)),
119 Message::E2eStreamFrame(frame) => Some(Self::E2eStreamFrame(frame)),
120 Message::ConnectNodeSend(_)
121 | Message::ConnectNodeReport(_)
122 | Message::FindSuccessorSend(_)
123 | Message::FindSuccessorReport(_)
124 | Message::NotifyPredecessorSend(_)
125 | Message::ProbeRequest(_)
126 | Message::ProbeOffer(_)
127 | Message::SearchEntry(_)
128 | Message::FoundEntry(_)
129 | Message::OperateEntry(_)
130 | Message::SyncEntriesWithSuccessor(_)
131 | Message::SyncEntriesWithSuccessorReport(_)
132 | Message::QueryForTopoInfoSend(_)
133 | Message::QueryForTopoInfoReport(_)
134 | Message::Chunk(_)
135 | Message::ProbeAcknowledgement(_)
136 | Message::AnnounceRelayHolder(_)
137 | Message::FetchRelayInbox(_)
138 | Message::RelayInboxReport(_)
139 | Message::RelayCarrierRefused(_)
140 | Message::RelayCarrierHeld(_)
141 | Message::FindRelayHolder(_)
142 | Message::RelayHolderFound(_)
143 | Message::ReplicateRelayHold(_)
144 | Message::DeclareRelayCustody(_)
145 | Message::RelayCarrierDigests(_)
146 | Message::RelayCarriersWanted(_)
147 | Message::EntryStoreReport(_)
148 | Message::Leave(_) => None,
149 }
150 }
151
152 /// An application message carrying `bytes`, as an application sends one.
153 pub fn custom(bytes: &[u8]) -> Self {
154 Self::Custom(CustomMessage(bytes.to_vec()))
155 }
156
157 /// The bytes of data this body carries beyond its own size, part of the measure of
158 /// [`APPLICATION_INBOX_WEIGHT`]. One rule for every variant: the byte length of the data,
159 /// not its allocation, so a message weighs the same however it was built.
160 fn data_len(&self) -> usize {
161 match self {
162 Self::Custom(CustomMessage(bytes)) => bytes.len(),
163 Self::E2eHandshakeRequest(_) | Self::E2eHandshakeResponse(_) => 0,
164 Self::E2eStreamFrame(frame) => frame.ciphertext.len(),
165 }
166 }
167}
168
169/// The injection of application data into the messages core sends: a section of
170/// `ApplicationData::project`: `project ∘ from = Some`.
171impl From<ApplicationData> for Message {
172 fn from(data: ApplicationData) -> Self {
173 match data {
174 ApplicationData::Custom(message) => Message::CustomMessage(message),
175 ApplicationData::E2eHandshakeRequest(request) => Message::E2eHandshakeRequest(request),
176 ApplicationData::E2eHandshakeResponse(response) => {
177 Message::E2eHandshakeResponse(response)
178 }
179 ApplicationData::E2eStreamFrame(frame) => Message::E2eStreamFrame(frame),
180 }
181 }
182}
183
184/// One application message addressed to this node, as core admitted and handled it.
185#[derive(Clone, Debug, PartialEq, Eq)]
186pub struct ApplicationMessage {
187 /// The transaction the message arrived under.
188 pub tx_id: uuid::Uuid,
189 /// The authenticated signer of the message.
190 pub from: Did,
191 /// The application data.
192 pub data: ApplicationData,
193}
194
195impl ApplicationMessage {
196 /// The application message `payload` carries for this node, if its body is application
197 /// data. `message` is the body already decoded from `payload`.
198 pub(crate) fn project(payload: &MessagePayload, message: Message) -> Option<Self> {
199 ApplicationData::project(message).map(|data| Self {
200 tx_id: payload.transaction.tx_id,
201 from: payload.transaction.signer(),
202 data,
203 })
204 }
205
206 /// The bytes this message retains while it waits in the inbox: its own size and the length
207 /// of its data in bytes, so an empty message still counts.
208 fn weight(&self) -> usize {
209 std::mem::size_of::<Self>().saturating_add(self.data.data_len())
210 }
211}
212
213/// A logical fact about a peer, as core concluded it.
214///
215/// Law: per peer, the inbox yields `PeerAdmitted` and `PeerRetired` alternately, starting with
216/// `PeerAdmitted`, in the order core decided them; every `MessageDropped` lies between an
217/// admission and the retirement after it. An admission retired before the application read it is
218/// withdrawn together with its retirement and the drops after it, so an application never reads a
219/// fact about an admission it did not read.
220#[derive(Clone, Copy, Debug, Eq, PartialEq)]
221#[non_exhaustive]
222pub enum SwarmEvent {
223 /// `peer`'s data channel is open and it joined the local DHT.
224 PeerAdmitted {
225 /// The admitted peer.
226 peer: Did,
227 },
228 /// `peer`'s admitted connection record was retired: it left the local DHT, whatever
229 /// physical event or local decision caused it.
230 PeerRetired {
231 /// The retired peer.
232 peer: Did,
233 },
234 /// A live application message from `peer`, an admitted peer, was dropped here because the
235 /// inbox was full (#969). The link stays up, but a message `peer` sent was lost; several drops
236 /// before the application reads the fact are told once.
237 MessageDropped {
238 /// The admitted peer the dropped message came from.
239 peer: Did,
240 },
241}
242
243impl SwarmEvent {
244 /// The peer this fact is about.
245 pub fn peer(&self) -> Did {
246 match *self {
247 Self::PeerAdmitted { peer }
248 | Self::PeerRetired { peer }
249 | Self::MessageDropped { peer } => peer,
250 }
251 }
252}
253
254/// One item of the application inbox.
255#[derive(Clone, Debug, PartialEq, Eq)]
256#[non_exhaustive]
257pub enum ApplicationDelivery {
258 /// Application data addressed to this node.
259 Message(ApplicationMessage),
260 /// A logical fact about a peer.
261 Event(SwarmEvent),
262}
263
264#[cfg(test)]
265mod tests {
266 use super::ApplicationData;
267 use crate::dht::Did;
268 use crate::ecc::SecretKey;
269 use crate::message::e2e::E2eHandshakeRequest;
270 use crate::message::FindSuccessorReportHandler;
271 use crate::message::FindSuccessorSend;
272 use crate::message::FindSuccessorThen;
273 use crate::message::Message;
274
275 /// The injection is a section of the projection: `project(Message::from(d)) = Some(d)`.
276 #[test]
277 fn test_projecting_injected_application_data_gives_it_back() {
278 let key = SecretKey::random();
279 for data in [
280 ApplicationData::custom(b"application"),
281 ApplicationData::E2eHandshakeRequest(E2eHandshakeRequest::new(key.pubkey())),
282 ] {
283 assert_eq!(
284 ApplicationData::project(Message::from(data.clone())),
285 Some(data)
286 );
287 }
288 }
289
290 /// A body that is core's own projects to nothing.
291 #[test]
292 fn test_a_core_message_carries_no_application_data() {
293 let did: Did = SecretKey::random().address().into();
294 let core = Message::FindSuccessorSend(FindSuccessorSend {
295 did,
296 strict: false,
297 then: FindSuccessorThen::Report(FindSuccessorReportHandler::None),
298 });
299 assert_eq!(ApplicationData::project(core), None);
300 }
301}