aboutsummaryrefslogtreecommitdiffstats
path: root/jabber/src/jabber_stream/bound_stream.rs
blob: 627158a3ef2b30167097fef6c5fa615f162932c2 (plain) (blame)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use std::future::ready;
use std::pin::pin;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Poll;

use futures::ready;
use futures::FutureExt;
use futures::{sink, stream, Sink, Stream};
use peanuts::{Reader, Writer};
use pin_project::pin_project;
use stanza::client::Stanza;
use tokio::io::{AsyncRead, AsyncWrite, ReadHalf, WriteHalf};
use tokio::sync::Mutex;
use tokio::task::JoinHandle;

use crate::Error;

use super::JabberStream;

#[pin_project]
pub struct BoundJabberStream<S>
where
    S: AsyncWrite + AsyncRead + Unpin + Send,
{
    reader: Arc<Mutex<Reader<ReadHalf<S>>>>,
    writer: Arc<Mutex<Writer<WriteHalf<S>>>>,
    write_handle: Option<JoinHandle<Result<(), Error>>>,
    read_handle: Option<JoinHandle<Result<Stanza, Error>>>,
}

impl<S> BoundJabberStream<S>
where
    S: AsyncWrite + AsyncRead + Unpin + Send,
{
    // TODO: look into biased mutex, to close stream ASAP
    // TODO: put into connection
    // pub async fn close_stream(self) -> Result<JabberStream<S>, Error> {
    //     let reader = self.reader.lock().await.into_self();
    //     let writer = self.writer.lock().await.into_self();
    //     // TODO: writer </stream:stream>
    //     return Ok(JabberStream { reader, writer });
    // }
}

pub trait JabberStreamTrait: AsyncWrite + AsyncRead + Unpin + Send {}

impl<S> Sink<Stanza> for BoundJabberStream<S>
where
    S: AsyncWrite + AsyncRead + Unpin + Send + 'static,
{
    type Error = Error;

    fn poll_ready(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.poll_flush(cx)
    }

    fn start_send(self: std::pin::Pin<&mut Self>, item: Stanza) -> Result<(), Self::Error> {
        let this = self.project();
        if let Some(_write_handle) = this.write_handle {
            panic!("start_send called without poll_ready")
        } else {
            // TODO: switch to buffer of one rather than thread spawning and joining
            *this.write_handle = Some(tokio::spawn(write(this.writer.clone(), item)));
            Ok(())
        }
    }

    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        let this = self.project();
        Poll::Ready(if let Some(join_handle) = this.write_handle.as_mut() {
            match ready!(join_handle.poll_unpin(cx)) {
                Ok(state) => {
                    *this.write_handle = None;
                    state
                }
                Err(err) => {
                    *this.write_handle = None;
                    Err(err.into())
                }
            }
        } else {
            Ok(())
        })
    }

    fn poll_close(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.poll_flush(cx)
    }
}

impl<S> Stream for BoundJabberStream<S>
where
    S: AsyncWrite + AsyncRead + Unpin + Send + 'static,
{
    type Item = Result<Stanza, Error>;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        let this = self.project();

        loop {
            if let Some(join_handle) = this.read_handle.as_mut() {
                let stanza = ready!(join_handle.poll_unpin(cx));
                if let Ok(item) = stanza {
                    *this.read_handle = None;
                    return Poll::Ready(Some(item));
                } else if let Err(err) = stanza {
                    return Poll::Ready(Some(Err(err.into())));
                }
            } else {
                *this.read_handle = Some(tokio::spawn(read(this.reader.clone())))
            }
        }
    }
}

impl<S> JabberStream<S>
where
    S: AsyncWrite + AsyncRead + Unpin + Send,
{
    pub fn to_bound_jabber(self) -> BoundJabberStream<S> {
        let reader = Arc::new(Mutex::new(self.reader));
        let writer = Arc::new(Mutex::new(self.writer));
        BoundJabberStream {
            writer,
            reader,
            write_handle: None,
            read_handle: None,
        }
    }
}

pub async fn write<W: AsyncWrite + Unpin + Send>(
    writer: Arc<Mutex<Writer<WriteHalf<W>>>>,
    stanza: Stanza,
) -> Result<(), Error> {
    {
        let mut writer = writer.lock().await;
        writer.write(&stanza).await?;
    }
    Ok(())
}

pub async fn read<R: AsyncRead + Unpin + Send>(
    reader: Arc<Mutex<Reader<ReadHalf<R>>>>,
) -> Result<Stanza, Error> {
    let stanza: Result<Stanza, Error>;
    {
        let mut reader = reader.lock().await;
        stanza = reader.read().await.map_err(|e| e.into());
    }
    stanza
}