iroh_relay/client/
conn.rs1use std::{
6 pin::Pin,
7 task::{Context, Poll, ready},
8};
9
10use iroh_base::SecretKey;
11use n0_error::{AnyError, anyerr, ensure, stack_error};
12use n0_future::{Sink, Stream};
13use tracing::trace;
14
15use super::KeyCache;
16#[cfg(not(wasm_browser))]
17use crate::client::streams::{MaybeTlsStream, ProxyStream};
18use crate::{
19 MAX_PACKET_SIZE,
20 http::ProtocolVersion,
21 protos::{
22 handshake,
23 relay::{ClientToRelayMsg, Error as ProtoError, RelayToClientMsg},
24 streams::WsBytesFramed,
25 },
26};
27
28#[stack_error(derive, add_meta, from_sources, std_sources)]
30#[allow(missing_docs)]
31#[non_exhaustive]
32pub enum SendError {
33 #[error("Stream error")]
40 StreamError { source: AnyError },
41 #[error("Exceeds max packet size ({MAX_PACKET_SIZE}): {size}")]
42 ExceedsMaxPacketSize { size: usize },
43 #[error("Attempted to send empty packet")]
45 EmptyPacket {},
46}
47
48#[stack_error(derive, add_meta, from_sources, std_sources)]
50#[allow(missing_docs)]
51#[non_exhaustive]
52pub enum RecvError {
53 #[error(transparent)]
54 Protocol { source: ProtoError },
55 #[error("Stream error")]
62 StreamError { source: AnyError },
63}
64
65#[derive(derive_more::Debug)]
72pub(crate) struct Conn {
73 #[cfg(not(wasm_browser))]
74 #[debug("tokio_websockets::WebSocketStream")]
75 pub(crate) conn: WsBytesFramed<MaybeTlsStream<ProxyStream>>,
76 #[cfg(wasm_browser)]
77 #[debug("ws_stream_wasm::WsStream")]
78 pub(crate) conn: WsBytesFramed,
79 pub(crate) key_cache: KeyCache,
80 pub(crate) protocol_version: ProtocolVersion,
81}
82
83impl Conn {
84 pub(crate) async fn new(
86 #[cfg(not(wasm_browser))] io: tokio_websockets::WebSocketStream<
87 MaybeTlsStream<ProxyStream>,
88 >,
89 #[cfg(wasm_browser)] io: ws_stream_wasm::WsStream,
90 key_cache: KeyCache,
91 secret_key: &SecretKey,
92 protocol_version: ProtocolVersion,
93 ) -> Result<Self, handshake::Error> {
94 let mut conn = WsBytesFramed::new(io);
95
96 trace!("server_handshake: started");
98 handshake::clientside(&mut conn, secret_key).await?;
99 trace!("server_handshake: done");
100
101 Ok(Self {
102 conn,
103 key_cache,
104 protocol_version,
105 })
106 }
107
108 #[cfg(all(test, feature = "server"))]
109 pub(crate) fn test(io: tokio::io::DuplexStream, protocol_version: ProtocolVersion) -> Self {
110 use crate::protos::relay::MAX_FRAME_SIZE;
111 Self {
112 conn: WsBytesFramed::new(
113 tokio_websockets::ClientBuilder::new()
114 .limits(
115 tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE)),
116 )
117 .take_over(MaybeTlsStream::Test(io)),
118 ),
119 key_cache: KeyCache::test(),
120 protocol_version,
121 }
122 }
123}
124
125impl Stream for Conn {
126 type Item = Result<RelayToClientMsg, RecvError>;
127
128 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
129 match ready!(Pin::new(&mut self.conn).poll_next(cx)) {
130 Some(Ok(msg)) => {
131 let message =
132 RelayToClientMsg::from_bytes(msg, &self.key_cache, self.protocol_version);
133 Poll::Ready(Some(message.map_err(Into::into)))
134 }
135 Some(Err(e)) => Poll::Ready(Some(Err(anyerr!(e).into()))),
136 None => Poll::Ready(None),
137 }
138 }
139}
140
141impl Sink<ClientToRelayMsg> for Conn {
142 type Error = SendError;
143
144 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
145 Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into)
146 }
147
148 fn start_send(mut self: Pin<&mut Self>, frame: ClientToRelayMsg) -> Result<(), Self::Error> {
149 let size = frame.encoded_len();
150 ensure!(
151 size <= MAX_PACKET_SIZE,
152 SendError::ExceedsMaxPacketSize { size }
153 );
154
155 Pin::new(&mut self.conn)
156 .start_send(frame.to_bytes().freeze())
157 .map_err(Into::into)
158 }
159
160 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
161 Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into)
162 }
163
164 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
165 Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into)
166 }
167}