]> git.lizzy.rs Git - connect-rs.git/blob - src/writer.rs
improve documentation and logging
[connect-rs.git] / src / writer.rs
1 use crate::protocol::ConnectDatagram;
2 use async_std::net::SocketAddr;
3 use async_std::pin::Pin;
4 use futures::io::IoSlice;
5 use futures::task::{Context, Poll};
6 use futures::{AsyncWrite, Sink};
7 use log::*;
8 use std::error::Error;
9
10 pub use futures::{SinkExt, StreamExt};
11 use std::fmt::Debug;
12
13 /// Encountered when there is an issue with writing messages on the network stream.
14 ///
15 #[derive(Debug)]
16 pub enum ConnectionWriteError {
17     /// Encountered when trying to send a message while the connection is closed.
18     ConnectionClosed,
19
20     /// Encountered when there is an IO-level error with the connection.
21     IoError(std::io::Error),
22 }
23
24 impl Error for ConnectionWriteError {}
25
26 impl std::fmt::Display for ConnectionWriteError {
27     fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
28         match self {
29             ConnectionWriteError::ConnectionClosed => {
30                 formatter.write_str("cannot send message when connection is closed")
31             }
32             ConnectionWriteError::IoError(err) => std::fmt::Display::fmt(&err, formatter),
33         }
34     }
35 }
36
37 /// An interface to write messages to the network connection.
38 ///
39 /// Implements the `Sink` trait to asynchronously write messages to the network connection.
40 ///
41 /// # Example
42 ///
43 /// Basic usage:
44 ///
45 /// ```ignore
46 /// writer.send(msg).await?;
47 /// ```
48 ///
49 /// Please see the [tcp-client](https://github.com/sachanganesh/connect-rs/blob/main/examples/tcp-client/)
50 /// example program or other client example programs for a more thorough showcase.
51 ///
52 pub struct ConnectionWriter {
53     local_addr: SocketAddr,
54     peer_addr: SocketAddr,
55     write_stream: Pin<Box<dyn AsyncWrite + Send + Sync>>,
56     pending_writes: Vec<Vec<u8>>,
57     closed: bool,
58 }
59
60 impl ConnectionWriter {
61     /// Creates a new [`ConnectionWriter`] from an [`AsyncWrite`] trait object and the local and peer
62     /// socket metadata.
63     pub fn new(
64         local_addr: SocketAddr,
65         peer_addr: SocketAddr,
66         write_stream: Pin<Box<dyn AsyncWrite + Send + Sync>>,
67     ) -> Self {
68         Self {
69             local_addr,
70             peer_addr,
71             write_stream,
72             pending_writes: Vec::new(),
73             closed: false,
74         }
75     }
76
77     /// Get the local IP address and port.
78     pub fn local_addr(&self) -> SocketAddr {
79         self.local_addr.clone()
80     }
81
82     /// Get the peer IP address and port.
83     pub fn peer_addr(&self) -> SocketAddr {
84         self.peer_addr.clone()
85     }
86
87     /// Check if the `Sink` of messages to the network is closed.
88     pub fn is_closed(&self) -> bool {
89         self.closed
90     }
91
92     pub(crate) fn write_pending_bytes(
93         &mut self,
94         cx: &mut Context<'_>,
95     ) -> Poll<Result<(), ConnectionWriteError>> {
96         if self.pending_writes.len() > 0 {
97             let stream = self.write_stream.as_mut();
98
99             match stream.poll_flush(cx) {
100                 Poll::Pending => Poll::Pending,
101
102                 Poll::Ready(Ok(_)) => {
103                     let stream = self.write_stream.as_mut();
104
105                     let pending = self.pending_writes.split_off(0);
106                     let writeable_vec: Vec<IoSlice> =
107                         pending.iter().map(|p| IoSlice::new(p)).collect();
108
109                     trace!("sending pending bytes to network stream");
110                     match stream.poll_write_vectored(cx, writeable_vec.as_slice()) {
111                         Poll::Pending => Poll::Pending,
112
113                         Poll::Ready(Ok(bytes_written)) => {
114                             trace!("wrote {} bytes to network stream", bytes_written);
115                             self.pending_writes.clear();
116                             Poll::Ready(Ok(()))
117                         }
118
119                         Poll::Ready(Err(err)) => {
120                             error!("Encountered error when writing to network stream");
121                             Poll::Ready(Err(ConnectionWriteError::IoError(err)))
122                         }
123                     }
124                 }
125
126                 Poll::Ready(Err(err)) => {
127                     error!("Encountered error when flushing network stream");
128                     Poll::Ready(Err(ConnectionWriteError::IoError(err)))
129                 }
130             }
131         } else {
132             Poll::Ready(Ok(()))
133         }
134     }
135 }
136
137 impl Sink<ConnectDatagram> for ConnectionWriter {
138     type Error = ConnectionWriteError;
139
140     fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
141         if self.is_closed() {
142             trace!("connection is closed, cannot send message");
143             Poll::Ready(Err(ConnectionWriteError::ConnectionClosed))
144         } else {
145             trace!("connection ready to send message");
146             Poll::Ready(Ok(()))
147         }
148     }
149
150     fn start_send(mut self: Pin<&mut Self>, item: ConnectDatagram) -> Result<(), Self::Error> {
151         trace!("preparing datagram to be queued for sending");
152
153         let buffer = item.encode();
154         let msg_size = buffer.len();
155         trace!("serialized pending message into {} bytes", msg_size);
156
157         self.pending_writes.push(buffer);
158
159         Ok(())
160     }
161
162     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
163         self.write_pending_bytes(cx)
164     }
165
166     fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
167         self.closed = true;
168         debug!("Closing the sink for connection with {}", self.peer_addr);
169
170         match self.write_pending_bytes(cx) {
171             Poll::Pending => Poll::Pending,
172
173             Poll::Ready(Ok(_)) => {
174                 let stream = self.write_stream.as_mut();
175
176                 match stream.poll_close(cx) {
177                     Poll::Pending => Poll::Pending,
178
179                     Poll::Ready(Ok(_)) => Poll::Ready(Ok(())),
180
181                     Poll::Ready(Err(err)) => Poll::Ready(Err(ConnectionWriteError::IoError(err))),
182                 }
183             }
184
185             err => err,
186         }
187     }
188 }