]> git.lizzy.rs Git - connect-rs.git/blob - src/writer.rs
refactor read/write for correctness and ordering of messages
[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::task::{Context, Poll};
5 use futures::{AsyncWrite, Sink};
6 use log::*;
7 use std::error::Error;
8
9 pub use futures::SinkExt;
10 pub use futures::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<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                     trace!("sending pending bytes to network stream");
106                     match stream.poll_write(cx, self.pending_writes.as_slice()) {
107                         Poll::Pending => Poll::Pending,
108
109                         Poll::Ready(Ok(bytes_written)) => {
110                             trace!("wrote {} bytes to network stream", bytes_written);
111                             self.pending_writes.clear();
112                             Poll::Ready(Ok(()))
113                         }
114
115                         Poll::Ready(Err(err)) => {
116                             error!("Encountered error when writing to network stream");
117                             Poll::Ready(Err(ConnectionWriteError::IoError(err)))
118                         }
119                     }
120                 }
121
122                 Poll::Ready(Err(err)) => {
123                     error!("Encountered error when flushing network stream");
124                     Poll::Ready(Err(ConnectionWriteError::IoError(err)))
125                 }
126             }
127         } else {
128             Poll::Ready(Ok(()))
129         }
130     }
131 }
132
133 impl Sink<ConnectDatagram> for ConnectionWriter {
134     type Error = ConnectionWriteError;
135
136     fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
137         if self.is_closed() {
138             trace!("connection is closed, cannot send message");
139             Poll::Ready(Err(ConnectionWriteError::ConnectionClosed))
140         } else {
141             trace!("connection ready to send message");
142             Poll::Ready(Ok(()))
143         }
144     }
145
146     fn start_send(mut self: Pin<&mut Self>, item: ConnectDatagram) -> Result<(), Self::Error> {
147         trace!("preparing datagram to be queued for sending");
148
149         let buffer = item.encode();
150         let msg_size = buffer.len();
151         trace!("serialized pending message into {} bytes", msg_size);
152
153         self.pending_writes.extend(buffer);
154
155         Ok(())
156     }
157
158     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
159         self.write_pending_bytes(cx)
160     }
161
162     fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
163         self.closed = true;
164
165         match self.write_pending_bytes(cx) {
166             Poll::Pending => Poll::Pending,
167
168             Poll::Ready(Ok(_)) => {
169                 let stream = self.write_stream.as_mut();
170
171                 match stream.poll_close(cx) {
172                     Poll::Pending => Poll::Pending,
173
174                     Poll::Ready(Ok(_)) => Poll::Ready(Ok(())),
175
176                     Poll::Ready(Err(err)) => Poll::Ready(Err(ConnectionWriteError::IoError(err))),
177                 }
178             }
179
180             err => err,
181         }
182     }
183 }