zebra_network/peer/connection/
peer_tx.rs1use futures::{FutureExt, Sink, SinkExt};
4
5use zebra_chain::serialization::SerializationError;
6
7use crate::{constants::REQUEST_TIMEOUT, protocol::external::Message, PeerError};
8
9#[derive(Clone, Debug)]
13pub struct PeerTx<Tx>
14where
15 Tx: Sink<Message, Error = SerializationError> + Unpin,
16{
17 inner: Tx,
21}
22
23impl<Tx> PeerTx<Tx>
24where
25 Tx: Sink<Message, Error = SerializationError> + Unpin,
26{
27 pub async fn send(&mut self, msg: Message) -> Result<(), PeerError> {
29 tokio::time::timeout(REQUEST_TIMEOUT, self.inner.send(msg))
30 .await
31 .map_err(|_| PeerError::ConnectionSendTimeout)?
32 .map_err(Into::into)
33 }
34
35 pub async fn send_authorized(
37 &mut self,
38 msg: Message,
39 mut authorized: impl FnMut() -> Result<(), PeerError>,
40 ) -> Result<(), PeerError> {
41 tokio::time::timeout(REQUEST_TIMEOUT, async {
42 futures::future::poll_fn(|cx| std::pin::Pin::new(&mut self.inner).poll_ready(cx))
43 .await?;
44 authorized()?;
45 std::pin::Pin::new(&mut self.inner).start_send(msg)?;
46 self.inner.flush().await?;
47 Ok(())
48 })
49 .await
50 .map_err(|_| PeerError::ConnectionSendTimeout)?
51 }
52
53 pub async fn close(&mut self) -> Result<(), SerializationError> {
55 self.inner.close().await
56 }
57}
58
59impl<Tx> From<Tx> for PeerTx<Tx>
60where
61 Tx: Sink<Message, Error = SerializationError> + Unpin,
62{
63 fn from(tx: Tx) -> Self {
64 PeerTx { inner: tx }
65 }
66}
67
68impl<Tx> Drop for PeerTx<Tx>
69where
70 Tx: Sink<Message, Error = SerializationError> + Unpin,
71{
72 fn drop(&mut self) {
73 self.close().now_or_never();
75 }
76}