1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
mod config;
mod decode;
mod encode;
mod inner;
mod open;
mod reader;
mod send;
mod waker;
mod writer;

pub use crate::connection::config::WsConfig;
pub use crate::connection::reader::WsMessageReader;
pub use crate::connection::send::WsSend;
pub use crate::connection::writer::WsMessageWriter;

use crate::connection::inner::WsConnectionInner;
use crate::connection::waker::{new_waker, Wakers};
use crate::frame::{FrameDecodeError, WsDataFrameKind};
use crate::message::WsMessageKind;
use futures::prelude::*;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

pub struct WsConnection<T: AsyncRead + AsyncWrite + Unpin> {
    parent: Arc<Mutex<(WsConnectionInner<T>, Wakers)>>,
}

impl<T: AsyncRead + AsyncWrite + Unpin> WsConnection<T> {
    pub fn with_config(transport: T, config: WsConfig) -> Self {
        Self {
            parent: Arc::new(Mutex::new((
                WsConnectionInner::with_config(transport, config),
                Wakers::default(),
            ))),
        }
    }
    pub fn send(&self, kind: WsMessageKind) -> WsSend<T> {
        WsSend::new(&self.parent, kind)
    }
    pub fn err(&self) -> Option<Arc<WsConnectionError>> {
        self.parent.lock().unwrap().0.err()
    }
}

impl<T: AsyncRead + AsyncWrite + Unpin> Stream for WsConnection<T> {
    type Item = WsMessageReader<T>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let mut guard = self.parent.lock().unwrap();
        let (inner, wakers) = guard.deref_mut();
        wakers.stream_waker = Some(cx.waker().clone());
        let waker = new_waker(Arc::downgrade(&self.parent));
        inner
            .poll_next_reader(&mut Context::from_waker(&waker))
            .map(|o| o.map(|kind| WsMessageReader::new(kind, &self.parent)))
    }
}

#[derive(thiserror::Error, Debug)]
pub enum WsConnectionError {
    #[error("invalid utf8 in text message")]
    InvalidUtf8,
    #[error("incomplete utf8 in text message")]
    IncompleteUtf8,
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("parse error: {0}")]
    FrameDecodeError(#[from] FrameDecodeError),
    #[error("timeout")]
    Timeout,
    #[error("unexpected frame kind {0}")]
    UnexpectedFrameKind(WsDataFrameKind),
}

impl From<WsDataFrameKind> for WsConnectionError {
    fn from(kind: WsDataFrameKind) -> Self {
        WsConnectionError::UnexpectedFrameKind(kind)
    }
}