reading.rs
1 // Copyright (c) 2025 ADnet Contributors 2 // This file is part of the adnet-core library. 3 // Derived from snarkOS, originally by Provable Inc. 4 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at: 8 9 // http://www.apache.org/licenses/LICENSE-2.0 10 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 #[cfg(doc)] 18 use crate::{Config, protocols::Handshake}; 19 use crate::{ 20 ConnectionSide, P2P, Tcp, 21 protocols::{ProtocolHandler, ReturnableConnection}, 22 }; 23 24 use async_trait::async_trait; 25 use bytes::BytesMut; 26 use futures_util::StreamExt; 27 use std::{io, net::SocketAddr}; 28 use tokio::{ 29 io::AsyncRead, 30 sync::{mpsc, oneshot}, 31 }; 32 use tokio_util::codec::{Decoder, FramedRead}; 33 use tracing::*; 34 35 /// Can be used to specify and enable reading, i.e. receiving inbound messages. If the [`Handshake`] 36 /// protocol is enabled too, it goes into force only after the handshake has been concluded. 37 /// 38 /// Each inbound message is isolated by the user-supplied [`Reading::Codec`], creating a [`Reading::Message`], 39 /// which is immediately queued (with a [`Reading::MESSAGE_QUEUE_DEPTH`] limit) to be processed by 40 /// [`Reading::process_message`]. The configured fatal IO errors result in an immediate disconnect 41 /// (in order to e.g. avoid accidentally reading "borked" messages). 42 #[async_trait] 43 pub trait Reading: P2P 44 where 45 Self: Clone + Send + Sync + 'static, 46 { 47 /// The depth of per-connection queues used to process inbound messages; the greater it is, the more inbound 48 /// messages the node can enqueue, but setting it to a large value can make the node more susceptible to DoS 49 /// attacks. 50 /// 51 /// The default value is 1024. 52 fn message_queue_depth(&self) -> usize { 53 1024 54 } 55 56 /// The initial size of a per-connection buffer for reading inbound messages. Can be set to the maximum expected size 57 /// of the inbound message in order to only allocate it once. 58 /// 59 /// The default value is 1024KiB. 60 const INITIAL_BUFFER_SIZE: usize = 1024 * 1024; 61 62 /// The final (deserialized) type of inbound messages. 63 type Message: Send; 64 65 /// The user-supplied [`Decoder`] used to interpret inbound messages. 66 type Codec: Decoder<Item = Self::Message, Error = io::Error> + Send; 67 68 /// Prepares the node to receive messages. 69 async fn enable_reading(&self) { 70 let (conn_sender, mut conn_receiver) = mpsc::unbounded_channel(); 71 72 // use a channel to know when the reading task is ready 73 let (tx_reading, rx_reading) = oneshot::channel(); 74 75 // the main task spawning per-connection tasks reading messages from their streams 76 let self_clone = self.clone(); 77 let reading_task = tokio::spawn(async move { 78 trace!(parent: self_clone.tcp().span(), "spawned the Reading handler task"); 79 tx_reading.send(()).unwrap(); // safe; the channel was just opened 80 81 // these objects are sent from `Tcp::adapt_stream` 82 while let Some(returnable_conn) = conn_receiver.recv().await { 83 self_clone.handle_new_connection(returnable_conn).await; 84 } 85 }); 86 let _ = rx_reading.await; 87 self.tcp().tasks.lock().push(reading_task); 88 89 // register the Reading handler with the Tcp 90 let hdl = Box::new(ProtocolHandler(conn_sender)); 91 assert!( 92 self.tcp().protocols.reading.set(hdl).is_ok(), 93 "the Reading protocol was enabled more than once!" 94 ); 95 } 96 97 /// Creates a [`Decoder`] used to interpret messages from the network. 98 /// The `side` param indicates the connection side **from the node's perspective**. 99 fn codec(&self, addr: SocketAddr, side: ConnectionSide) -> Self::Codec; 100 101 /// Processes an inbound message. Can be used to update state, send replies etc. 102 async fn process_message(&self, source: SocketAddr, message: Self::Message) -> io::Result<()>; 103 } 104 105 /// This trait is used to restrict access to methods that would otherwise be public in [`Reading`]. 106 #[async_trait] 107 trait ReadingInternal: Reading { 108 /// Applies the [`Reading`] protocol to a single connection. 109 async fn handle_new_connection(&self, (conn, conn_returner): ReturnableConnection); 110 111 /// Wraps the user-supplied [`Decoder`] ([`Reading::Codec`]) in another one used for message accounting. 112 fn map_codec<T: AsyncRead>( 113 &self, 114 framed: FramedRead<T, Self::Codec>, 115 addr: SocketAddr, 116 ) -> FramedRead<T, CountingCodec<Self::Codec>>; 117 } 118 119 #[async_trait] 120 impl<R: Reading> ReadingInternal for R { 121 async fn handle_new_connection(&self, (mut conn, conn_returner): ReturnableConnection) { 122 let addr = conn.addr(); 123 let codec = self.codec(addr, !conn.side()); 124 let reader = conn.reader.take().expect("missing connection reader!"); 125 let framed = FramedRead::new(reader, codec); 126 let mut framed = self.map_codec(framed, addr); 127 128 // the connection will notify the reading task once it's fully ready 129 let (tx_conn_ready, rx_conn_ready) = oneshot::channel(); 130 conn.readiness_notifier = Some(tx_conn_ready); 131 132 if Self::INITIAL_BUFFER_SIZE != 0 { 133 framed.read_buffer_mut().reserve(Self::INITIAL_BUFFER_SIZE); 134 } 135 136 let (inbound_message_sender, mut inbound_message_receiver) = 137 mpsc::channel(self.message_queue_depth()); 138 139 // use a channel to know when the processing task is ready 140 let (tx_processing, rx_processing) = oneshot::channel::<()>(); 141 142 // the task for processing parsed messages 143 let self_clone = self.clone(); 144 let inbound_processing_task = tokio::spawn(Box::pin(async move { 145 let node = self_clone.tcp(); 146 trace!(parent: node.span(), "spawned a task for processing messages from {addr}"); 147 tx_processing.send(()).unwrap(); // safe; the channel was just opened 148 149 while let Some(msg) = inbound_message_receiver.recv().await { 150 if let Err(e) = self_clone.process_message(addr, msg).await { 151 error!(parent: node.span(), "can't process a message from {addr}: {e}"); 152 node.known_peers().register_failure(addr.ip()); 153 } 154 #[cfg(feature = "metrics")] 155 metrics::decrement_gauge(metrics::tcp::TCP_TASKS, 1f64); 156 } 157 })); 158 let _ = rx_processing.await; 159 conn.tasks.push(inbound_processing_task); 160 161 // use a channel to know when the reader task is ready 162 let (tx_reader, rx_reader) = oneshot::channel::<()>(); 163 164 // the task for reading messages from a stream 165 let node = self.tcp().clone(); 166 let reader_task = tokio::spawn(Box::pin(async move { 167 trace!(parent: node.span(), "spawned a task for reading messages from {addr}"); 168 tx_reader.send(()).unwrap(); // safe; the channel was just opened 169 170 // postpone reads until the connection is fully established; if the process fails, 171 // this task gets aborted, so there is no need for a dedicated timeout 172 let _ = rx_conn_ready.await; 173 174 while let Some(bytes) = framed.next().await { 175 match bytes { 176 Ok(msg) => { 177 // send the message for further processing 178 if let Err(e) = inbound_message_sender.try_send(msg) { 179 error!(parent: node.span(), "can't process a message from {addr}: {e}"); 180 node.stats().register_failure(); 181 if matches!(e, mpsc::error::TrySendError::Closed(_)) { 182 break; 183 } 184 } 185 #[cfg(feature = "metrics")] 186 metrics::increment_gauge(metrics::tcp::TCP_TASKS, 1f64); 187 } 188 Err(e) => { 189 error!(parent: node.span(), "can't read from {addr}: {e}"); 190 node.known_peers().register_failure(addr.ip()); 191 if node.config().fatal_io_errors.contains(&e.kind()) { 192 break; 193 } 194 } 195 } 196 } 197 198 let _ = node.disconnect(addr).await; 199 })); 200 let _ = rx_reader.await; 201 conn.tasks.push(reader_task); 202 203 // return the Connection to the Tcp, resuming Tcp::adapt_stream 204 if conn_returner.send(Ok(conn)).is_err() { 205 unreachable!("couldn't return a Connection to the Tcp"); 206 } 207 } 208 209 fn map_codec<T: AsyncRead>( 210 &self, 211 framed: FramedRead<T, Self::Codec>, 212 addr: SocketAddr, 213 ) -> FramedRead<T, CountingCodec<Self::Codec>> { 214 framed.map_decoder(|codec| CountingCodec { 215 codec, 216 node: self.tcp().clone(), 217 addr, 218 acc: 0, 219 }) 220 } 221 } 222 223 /// A wrapper [`Decoder`] that also counts the inbound messages. 224 struct CountingCodec<D: Decoder> { 225 codec: D, 226 node: Tcp, 227 addr: SocketAddr, 228 acc: usize, 229 } 230 231 impl<D: Decoder> Decoder for CountingCodec<D> { 232 type Error = D::Error; 233 type Item = D::Item; 234 235 fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { 236 let initial_buf_len = src.len(); 237 let ret = self.codec.decode(src)?; 238 let final_buf_len = src.len(); 239 let read_len = initial_buf_len - final_buf_len + self.acc; 240 241 if read_len != 0 { 242 trace!(parent: self.node.span(), "read {}B from {}", read_len, self.addr); 243 244 if ret.is_some() { 245 self.acc = 0; 246 self.node 247 .known_peers() 248 .register_received_message(self.addr.ip(), read_len); 249 self.node.stats().register_received_message(read_len); 250 } else { 251 self.acc = read_len; 252 } 253 } 254 255 Ok(ret) 256 } 257 }