snarkos_node_tcp/protocols/
writing.rs

1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::{any::Any, collections::HashMap, io, net::SocketAddr, sync::Arc};
17
18use async_trait::async_trait;
19use futures_util::sink::SinkExt;
20use parking_lot::RwLock;
21use tokio::{
22    io::AsyncWrite,
23    sync::{mpsc, oneshot},
24};
25use tokio_util::codec::{Encoder, FramedWrite};
26use tracing::*;
27
28#[cfg(doc)]
29use crate::{Config, Tcp, protocols::Handshake};
30use crate::{
31    Connection,
32    ConnectionSide,
33    P2P,
34    protocols::{Protocol, ProtocolHandler, ReturnableConnection},
35};
36
37type WritingSenders = Arc<RwLock<HashMap<SocketAddr, mpsc::Sender<WrappedMessage>>>>;
38
39/// Can be used to specify and enable writing, i.e. sending outbound messages. If the [`Handshake`]
40/// protocol is enabled too, it goes into force only after the handshake has been concluded.
41#[async_trait]
42pub trait Writing: P2P
43where
44    Self: Clone + Send + Sync + 'static,
45{
46    /// The depth of per-connection queues used to send outbound messages; the greater it is, the more outbound
47    /// messages the node can enqueue. Setting it to a large value is not recommended, as doing it might
48    /// obscure potential issues with your implementation (like slow serialization) or network.
49    ///
50    /// The default value is 1024.
51    const MESSAGE_QUEUE_DEPTH: usize = 1024;
52
53    /// The type of the outbound messages; unless their serialization is expensive and the message
54    /// is broadcasted (in which case it would get serialized multiple times), serialization should
55    /// be done in the implementation of [`Self::Codec`].
56    type Message: Send;
57
58    /// The user-supplied [`Encoder`] used to write outbound messages to the target stream.
59    type Codec: Encoder<Self::Message, Error = io::Error> + Send;
60
61    /// Prepares the node to send messages.
62    async fn enable_writing(&self) {
63        let (conn_sender, mut conn_receiver) = mpsc::unbounded_channel();
64
65        // the conn_senders are used to send messages from the Tcp to individual connections
66        let conn_senders: WritingSenders = Default::default();
67        // procure a clone to create the WritingHandler with
68        let senders = conn_senders.clone();
69
70        // use a channel to know when the writing task is ready
71        let (tx_writing, rx_writing) = oneshot::channel();
72
73        // the task spawning tasks sending messages to all the streams
74        let self_clone = self.clone();
75        let writing_task = tokio::spawn(async move {
76            trace!(parent: self_clone.tcp().span(), "spawned the Writing handler task");
77            tx_writing.send(()).unwrap(); // safe; the channel was just opened
78
79            // these objects are sent from `Tcp::adapt_stream`
80            while let Some(returnable_conn) = conn_receiver.recv().await {
81                self_clone.handle_new_connection(returnable_conn, &conn_senders).await;
82            }
83        });
84        let _ = rx_writing.await;
85        self.tcp().tasks.lock().push(writing_task);
86
87        // register the WritingHandler with the Tcp
88        let hdl = Box::new(WritingHandler { handler: ProtocolHandler(conn_sender), senders });
89        assert!(self.tcp().protocols.writing.set(hdl).is_ok(), "the Writing protocol was enabled more than once!");
90    }
91
92    /// Creates an [`Encoder`] used to write the outbound messages to the target stream.
93    /// The `side` param indicates the connection side **from the node's perspective**.
94    fn codec(&self, addr: SocketAddr, side: ConnectionSide) -> Self::Codec;
95
96    /// Sends the provided message to the specified [`SocketAddr`]. Returns as soon as the message is queued to
97    /// be sent, without waiting for the actual delivery; instead, the caller is provided with a [`oneshot::Receiver`]
98    /// which can be used to determine when and whether the message has been delivered.
99    ///
100    /// # Errors
101    ///
102    /// The following errors can be returned:
103    /// - [`io::ErrorKind::NotConnected`] if the node is not connected to the provided address
104    /// - [`io::ErrorKind::Other`] if the outbound message queue for this address is full
105    /// - [`io::ErrorKind::Unsupported`] if [`Writing::enable_writing`] hadn't been called yet
106    fn unicast(&self, addr: SocketAddr, message: Self::Message) -> io::Result<oneshot::Receiver<io::Result<()>>> {
107        // access the protocol handler
108        if let Some(handler) = self.tcp().protocols.writing.get() {
109            // find the message sender for the given address
110            if let Some(sender) = handler.senders.read().get(&addr).cloned() {
111                let (msg, delivery) = WrappedMessage::new(Box::new(message));
112                sender
113                    .try_send(msg)
114                    .map_err(|e| {
115                        error!(parent: self.tcp().span(), "can't send a message to {}: {}", addr, e);
116                        self.tcp().stats().register_failure();
117                        io::ErrorKind::Other.into()
118                    })
119                    .map(|_| delivery)
120            } else {
121                Err(io::ErrorKind::NotConnected.into())
122            }
123        } else {
124            Err(io::ErrorKind::Unsupported.into())
125        }
126    }
127
128    /// Broadcasts the provided message to all connected peers. Returns as soon as the message is queued to
129    /// be sent to all the peers, without waiting for the actual delivery. This method doesn't provide the
130    /// means to check when and if the messages actually get delivered; you can achieve that by calling
131    /// [`Writing::unicast`] for each address returned by [`Tcp::connected_addrs`].
132    ///
133    /// # Errors
134    ///
135    /// Returns [`io::ErrorKind::Unsupported`] if [`Writing::enable_writing`] hadn't been called yet.
136    fn broadcast(&self, message: Self::Message) -> io::Result<()>
137    where
138        Self::Message: Clone,
139    {
140        // access the protocol handler
141        if let Some(handler) = self.tcp().protocols.writing.get() {
142            let senders = handler.senders.read().clone();
143            for (addr, message_sender) in senders {
144                let (msg, _delivery) = WrappedMessage::new(Box::new(message.clone()));
145                let _ = message_sender.try_send(msg).map_err(|e| {
146                    error!(parent: self.tcp().span(), "can't send a message to {}: {}", addr, e);
147                    self.tcp().stats().register_failure();
148                });
149            }
150
151            Ok(())
152        } else {
153            Err(io::ErrorKind::Unsupported.into())
154        }
155    }
156}
157
158/// This trait is used to restrict access to methods that would otherwise be public in [`Writing`].
159#[async_trait]
160trait WritingInternal: Writing {
161    /// Writes the given message to the network stream and returns the number of written bytes.
162    async fn write_to_stream<W: AsyncWrite + Unpin + Send>(
163        &self,
164        message: Self::Message,
165        writer: &mut FramedWrite<W, Self::Codec>,
166    ) -> Result<usize, <Self::Codec as Encoder<Self::Message>>::Error>;
167
168    /// Applies the [`Writing`] protocol to a single connection.
169    async fn handle_new_connection(&self, (conn, conn_returner): ReturnableConnection, conn_senders: &WritingSenders);
170}
171
172#[async_trait]
173impl<W: Writing> WritingInternal for W {
174    async fn write_to_stream<A: AsyncWrite + Unpin + Send>(
175        &self,
176        message: Self::Message,
177        writer: &mut FramedWrite<A, Self::Codec>,
178    ) -> Result<usize, <Self::Codec as Encoder<Self::Message>>::Error> {
179        writer.feed(message).await?;
180        let len = writer.write_buffer().len();
181        writer.flush().await?;
182
183        Ok(len)
184    }
185
186    async fn handle_new_connection(
187        &self,
188        (mut conn, conn_returner): ReturnableConnection,
189        conn_senders: &WritingSenders,
190    ) {
191        let addr = conn.addr();
192        let codec = self.codec(addr, !conn.side());
193        let writer = conn.writer.take().expect("missing connection writer!");
194        let mut framed = FramedWrite::new(writer, codec);
195
196        let (outbound_message_sender, mut outbound_message_receiver) = mpsc::channel(Self::MESSAGE_QUEUE_DEPTH);
197
198        // register the connection's message sender with the Writing protocol handler
199        conn_senders.write().insert(addr, outbound_message_sender);
200
201        // this will automatically drop the sender upon a disconnect
202        let auto_cleanup = SenderCleanup { addr, senders: Arc::clone(conn_senders) };
203
204        // use a channel to know when the writer task is ready
205        let (tx_writer, rx_writer) = oneshot::channel();
206
207        // the task for writing outbound messages
208        let self_clone = self.clone();
209        let writer_task = tokio::spawn(async move {
210            let node = self_clone.tcp();
211            trace!(parent: node.span(), "spawned a task for writing messages to {}", addr);
212            tx_writer.send(()).unwrap(); // safe; the channel was just opened
213
214            // move the cleanup into the task that gets aborted on disconnect
215            let _auto_cleanup = auto_cleanup;
216
217            while let Some(wrapped_msg) = outbound_message_receiver.recv().await {
218                let msg = wrapped_msg.msg.downcast().unwrap();
219
220                match self_clone.write_to_stream(*msg, &mut framed).await {
221                    Ok(len) => {
222                        let _ = wrapped_msg.delivery_notification.send(Ok(()));
223                        node.known_peers().register_sent_message(addr.ip(), len);
224                        node.stats().register_sent_message(len);
225                        trace!(parent: node.span(), "sent {}B to {}", len, addr);
226                    }
227                    Err(e) => {
228                        node.known_peers().register_failure(addr.ip());
229                        error!(parent: node.span(), "couldn't send a message to {}: {}", addr, e);
230                        let is_fatal = node.config().fatal_io_errors.contains(&e.kind());
231                        let _ = wrapped_msg.delivery_notification.send(Err(e));
232                        if is_fatal {
233                            break;
234                        }
235                    }
236                }
237            }
238
239            node.disconnect(addr).await;
240        });
241        let _ = rx_writer.await;
242        conn.tasks.push(writer_task);
243
244        // return the Connection to the Tcp, resuming Tcp::adapt_stream
245        if conn_returner.send(Ok(conn)).is_err() {
246            unreachable!("couldn't return a Connection to the Tcp");
247        }
248    }
249}
250
251/// Used to queue messages for delivery.
252struct WrappedMessage {
253    msg: Box<dyn Any + Send>,
254    delivery_notification: oneshot::Sender<io::Result<()>>,
255}
256
257impl WrappedMessage {
258    fn new(msg: Box<dyn Any + Send>) -> (Self, oneshot::Receiver<io::Result<()>>) {
259        let (tx, rx) = oneshot::channel();
260        let wrapped_msg = Self { msg, delivery_notification: tx };
261
262        (wrapped_msg, rx)
263    }
264}
265
266/// The handler object dedicated to the [`Writing`] protocol.
267pub(crate) struct WritingHandler {
268    handler: ProtocolHandler<Connection, io::Result<Connection>>,
269    senders: WritingSenders,
270}
271
272impl Protocol<Connection, io::Result<Connection>> for WritingHandler {
273    fn trigger(&self, item: ReturnableConnection) {
274        self.handler.trigger(item);
275    }
276}
277
278struct SenderCleanup {
279    addr: SocketAddr,
280    senders: WritingSenders,
281}
282
283impl Drop for SenderCleanup {
284    fn drop(&mut self) {
285        self.senders.write().remove(&self.addr);
286    }
287}