1use std::{
4 pin::Pin,
5 task::{Context, Poll},
6};
7#[cfg(not(wasm_browser))]
8use std::{
9 sync::Arc,
10 task::{Wake, Waker},
11};
12
13use bytes::Bytes;
14use n0_error::AnyError;
15#[cfg(not(wasm_browser))]
16use n0_error::anyerr;
17use n0_future::{Sink, Stream, ready};
18#[cfg(not(wasm_browser))]
19use tokio::io::{AsyncRead, AsyncWrite};
20use tracing::warn;
21
22use crate::ExportKeyingMaterial;
23
24#[cfg(not(wasm_browser))]
25#[derive(derive_more::Debug)]
26pub(crate) struct WsBytesFramed<T> {
27 #[debug("WebSocketStream<T>")]
28 pub(crate) io: tokio_websockets::WebSocketStream<T>,
29 has_queued_pong: bool,
30 stream_waker: Option<Waker>,
31 sink_waker: Option<Waker>,
32}
33
34#[cfg(not(wasm_browser))]
35impl<T> WsBytesFramed<T> {
36 pub(crate) fn new(io: tokio_websockets::WebSocketStream<T>) -> Self {
37 Self {
38 io,
39 has_queued_pong: false,
40 stream_waker: None,
41 sink_waker: None,
42 }
43 }
44}
45
46#[cfg(not(wasm_browser))]
48fn register_write(own: &mut Option<Waker>, other: Option<&Waker>, cx: &Context<'_>) -> Waker {
49 *own = Some(cx.waker().clone());
50 match other {
51 Some(other) if !other.will_wake(cx.waker()) => {
52 Waker::from(Arc::new(TwoWakers(cx.waker().clone(), other.clone())))
53 }
54 _ => cx.waker().clone(),
55 }
56}
57
58#[cfg(not(wasm_browser))]
59struct TwoWakers(Waker, Waker);
60
61#[cfg(not(wasm_browser))]
62impl Wake for TwoWakers {
63 fn wake(self: Arc<Self>) {
64 self.0.wake_by_ref();
65 self.1.wake_by_ref();
66 }
67}
68
69#[cfg(wasm_browser)]
70#[derive(derive_more::Debug)]
71pub(crate) struct WsBytesFramed {
72 #[debug("WebSocketStream")]
73 pub(crate) io: ws_stream_wasm::WsStream,
74}
75
76#[cfg(wasm_browser)]
77impl WsBytesFramed {
78 pub(crate) fn new(io: ws_stream_wasm::WsStream) -> Self {
79 Self { io }
80 }
81}
82
83pub type StreamError = AnyError;
93
94pub trait BytesStreamSink:
96 Stream<Item = Result<Bytes, StreamError>> + Sink<Bytes, Error = StreamError> + Unpin
97{
98}
99
100impl<T> BytesStreamSink for T where
101 T: Stream<Item = Result<Bytes, StreamError>> + Sink<Bytes, Error = StreamError> + Unpin
102{
103}
104
105#[cfg(not(wasm_browser))]
106impl<IO: ExportKeyingMaterial + AsyncRead + AsyncWrite + Unpin> ExportKeyingMaterial
107 for WsBytesFramed<IO>
108{
109 fn export_keying_material<T: AsMut<[u8]>>(
110 &self,
111 output: T,
112 label: &[u8],
113 context: Option<&[u8]>,
114 ) -> Option<T> {
115 self.io
116 .get_ref()
117 .export_keying_material(output, label, context)
118 }
119}
120
121#[cfg(wasm_browser)]
122impl ExportKeyingMaterial for WsBytesFramed {
123 fn export_keying_material<T: AsMut<[u8]>>(
124 &self,
125 _output: T,
126 _label: &[u8],
127 _context: Option<&[u8]>,
128 ) -> Option<T> {
129 None
130 }
131}
132
133#[cfg(not(wasm_browser))]
134impl<T: AsyncRead + AsyncWrite + Unpin> Stream for WsBytesFramed<T> {
135 type Item = Result<Bytes, StreamError>;
136
137 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
138 loop {
139 if self.has_queued_pong {
142 let this = &mut *self;
143 let waker = register_write(&mut this.stream_waker, this.sink_waker.as_ref(), cx);
144 let res = Pin::new(&mut this.io).poll_flush(&mut Context::from_waker(&waker));
145 let res = ready!(res);
146 self.has_queued_pong = false;
147 if let Err(e) = res {
148 return Poll::Ready(Some(Err(anyerr!(e))));
149 }
150 }
151 match ready!(Pin::new(&mut self.io).poll_next(cx)) {
152 None => return Poll::Ready(None),
153 Some(Err(e)) => return Poll::Ready(Some(Err(anyerr!(e)))),
154 Some(Ok(msg)) => {
155 if msg.is_close() {
156 return Poll::Ready(None);
159 }
160 if msg.is_ping() || msg.is_pong() {
161 self.has_queued_pong |= msg.is_ping();
162 continue; }
164 if !msg.is_binary() {
165 warn!(?msg, "Got websocket message of unsupported type, skipping.");
166 continue;
167 }
168 return Poll::Ready(Some(Ok(msg.into_payload().into())));
169 }
170 }
171 }
172 }
173}
174
175#[cfg(wasm_browser)]
176impl Stream for WsBytesFramed {
177 type Item = Result<Bytes, StreamError>;
178
179 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
180 loop {
181 match ready!(Pin::new(&mut self.io).poll_next(cx)) {
182 None => return Poll::Ready(None),
183 Some(ws_stream_wasm::WsMessage::Binary(msg)) => {
184 return Poll::Ready(Some(Ok(msg.into())));
185 }
186 Some(msg) => {
187 warn!(?msg, "Got websocket message of unsupported type, skipping.");
188 continue;
189 }
190 }
191 }
192 }
193}
194
195#[cfg(not(wasm_browser))]
196impl<T: AsyncRead + AsyncWrite + Unpin> Sink<Bytes> for WsBytesFramed<T> {
197 type Error = StreamError;
198
199 fn start_send(mut self: Pin<&mut Self>, bytes: Bytes) -> Result<(), Self::Error> {
200 let msg = tokio_websockets::Message::binary(tokio_websockets::Payload::from(bytes));
201 Pin::new(&mut self.io)
202 .start_send(msg)
203 .map_err(AnyError::from_std)
204 }
205
206 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
207 let this = &mut *self;
208 let waker = register_write(&mut this.sink_waker, this.stream_waker.as_ref(), cx);
209 Pin::new(&mut this.io)
210 .poll_ready(&mut Context::from_waker(&waker))
211 .map_err(AnyError::from_std)
212 }
213
214 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
215 let this = &mut *self;
216 let waker = register_write(&mut this.sink_waker, this.stream_waker.as_ref(), cx);
217 Pin::new(&mut this.io)
218 .poll_flush(&mut Context::from_waker(&waker))
219 .map_err(AnyError::from_std)
220 }
221
222 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
223 let this = &mut *self;
224 let waker = register_write(&mut this.sink_waker, this.stream_waker.as_ref(), cx);
225 Pin::new(&mut this.io)
226 .poll_close(&mut Context::from_waker(&waker))
227 .map_err(AnyError::from_std)
228 }
229}
230
231#[cfg(wasm_browser)]
232impl Sink<Bytes> for WsBytesFramed {
233 type Error = StreamError;
234
235 fn start_send(mut self: Pin<&mut Self>, bytes: Bytes) -> Result<(), Self::Error> {
236 let msg = ws_stream_wasm::WsMessage::Binary(Vec::from(bytes));
237 Pin::new(&mut self.io)
238 .start_send(msg)
239 .map_err(AnyError::from_std)
240 }
241
242 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
243 Pin::new(&mut self.io)
244 .poll_ready(cx)
245 .map_err(AnyError::from_std)
246 }
247
248 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
249 Pin::new(&mut self.io)
250 .poll_flush(cx)
251 .map_err(AnyError::from_std)
252 }
253
254 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
255 Pin::new(&mut self.io)
256 .poll_close(cx)
257 .map_err(AnyError::from_std)
258 }
259}
260
261#[cfg(all(test, not(wasm_browser)))]
262mod tests {
263 use std::time::Duration;
264
265 use bytes::Bytes;
266 use n0_future::{SinkExt, StreamExt, split::split, task::AbortOnDropHandle};
267 use tokio::{
268 io::AsyncWriteExt,
269 time::{sleep, timeout},
270 };
271
272 use super::WsBytesFramed;
273
274 #[tokio::test(start_paused = true)]
275 async fn split_halves_are_both_woken_after_ping_sink() {
276 split_halves_are_woken(true).await;
277 }
278
279 #[tokio::test(start_paused = true)]
280 async fn split_halves_are_both_woken_after_ping_stream() {
281 split_halves_are_woken(false).await;
282 }
283
284 async fn split_halves_are_woken(sink_first: bool) {
285 let (local, mut remote) = tokio::io::duplex(64);
286 let local = WsBytesFramed::new(tokio_websockets::ClientBuilder::new().take_over(local));
287 let (mut sink, mut stream) = split(local);
288
289 let mut frames = [0x89, 0].repeat(20);
290 frames.extend([0x82, 0]);
291 remote.write_all(&frames).await.unwrap();
292
293 let send = async move { sink.send(Bytes::from(vec![0; 1024])).await };
294 let recv = async move { stream.next().await };
295
296 let (send, recv) = if sink_first {
297 let send = AbortOnDropHandle::new(tokio::spawn(send));
298 sleep(Duration::from_secs(1)).await;
299 (send, AbortOnDropHandle::new(tokio::spawn(recv)))
300 } else {
301 let recv = AbortOnDropHandle::new(tokio::spawn(recv));
302 sleep(Duration::from_secs(1)).await;
303 (AbortOnDropHandle::new(tokio::spawn(send)), recv)
304 };
305
306 sleep(Duration::from_secs(1)).await;
307 assert!(!send.is_finished() && !recv.is_finished());
308
309 let _reader = AbortOnDropHandle::new(tokio::spawn(async move {
310 tokio::io::copy(&mut remote, &mut tokio::io::sink()).await
311 }));
312 let both = async { (send.await.unwrap(), recv.await.unwrap()) };
313 let (sent, received) = timeout(Duration::from_secs(60), both)
314 .await
315 .expect("a half was not woken");
316 sent.unwrap();
317 assert_eq!(received.unwrap().unwrap(), Bytes::new());
318 }
319
320 #[tokio::test]
321 async fn failed_pong_flush_ends_the_stream() {
322 let (local, mut remote) = tokio::io::duplex(64);
323 let mut local = WsBytesFramed::new(tokio_websockets::ClientBuilder::new().take_over(local));
324 remote.write_all(&[0x89, 0]).await.unwrap();
325 drop(remote);
326
327 assert!(matches!(local.next().await, Some(Err(_))));
328 assert!(local.next().await.is_none());
329 }
330}