Skip to main content

http_longpoll/
session.rs

1use crate::http_poll::{Foldable, ResponseFramer, ResultCallback, Writer, WriterError};
2use futures::{Future, Sink, SinkExt, Stream};
3use pin_project_lite::pin_project;
4use std::pin::Pin;
5use std::{
6    task::{ready, Poll},
7    time::Duration,
8};
9use tokio::sync::{mpsc, oneshot};
10use tokio_stream::wrappers::ReceiverStream;
11
12pub type SessionError = WriterError;
13
14#[derive(Copy, Clone)]
15pub struct Config {
16    pub message_max_size: usize,
17    pub request_capactiy: usize,
18    pub poll_timeout: Duration,
19}
20
21impl Default for Config {
22    fn default() -> Self {
23        Self {
24            message_max_size: 1 << 20,
25            request_capactiy: 16,
26            poll_timeout: Duration::from_secs(30),
27        }
28    }
29}
30
31pin_project! {
32    pub struct Session<T> where T:Foldable {
33        #[pin]
34        read: ReceiverStream<Result<T,()>>,
35        #[pin]
36        write: ResponseFramer<Writer<ReceiverStream<ResultCallback<T::Start>>>,T>,
37    }
38}
39
40impl<T> Session<T>
41where
42    T: Foldable,
43{
44    fn new(
45        read: ReceiverStream<Result<T, ()>>,
46        write: ReceiverStream<ResultCallback<T::Start>>,
47        max_size: usize,
48        poll_timeout: Duration,
49    ) -> Self {
50        Self {
51            read,
52            write: ResponseFramer::new(max_size, Writer::new(write)),
53        }
54    }
55
56    pub async fn close_session(mut self: Pin<&mut Self>) -> Result<(), SessionError> {
57        // Close read, and then poll write for flush + close
58        // calling code should drain session stream as well
59        self.as_mut().project().read.close();
60        self.project().write.close().await
61    }
62}
63
64// PROXY STREAM AND SINK
65//
66
67impl<T> Stream for Session<T>
68where
69    T: Foldable,
70{
71    type Item = T;
72    fn poll_next(
73        mut self: std::pin::Pin<&mut Self>,
74        cx: &mut std::task::Context<'_>,
75    ) -> std::task::Poll<Option<Self::Item>> {
76        //
77        // Close reader stream so eventually stream finishes
78        if let Poll::Ready(result) = self.as_mut().project().write.poll(cx) {
79            // what todo about error ?
80            self.as_mut().project().read.close();
81        }
82
83        match ready!(self.as_mut().project().read.poll_next(cx)) {
84            Some(Err(_)) => {
85                self.project().read.close();
86                Poll::Ready(None)
87                // TODO: fuse it ?
88            }
89            other => Poll::Ready(other.map(|r| r.unwrap())),
90        }
91    }
92}
93
94impl<T> Sink<T> for Session<T>
95where
96    T: Foldable,
97{
98    type Error = WriterError;
99
100    fn poll_ready(
101        self: std::pin::Pin<&mut Self>,
102        cx: &mut std::task::Context<'_>,
103    ) -> std::task::Poll<Result<(), Self::Error>> {
104        self.project().write.poll_ready(cx)
105    }
106
107    fn start_send(mut self: std::pin::Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
108        self.project().write.start_send(item)
109    }
110
111    fn poll_flush(
112        self: std::pin::Pin<&mut Self>,
113        cx: &mut std::task::Context<'_>,
114    ) -> std::task::Poll<Result<(), Self::Error>> {
115        self.project().write.poll_flush(cx)
116    }
117
118    fn poll_close(
119        self: std::pin::Pin<&mut Self>,
120        cx: &mut std::task::Context<'_>,
121    ) -> std::task::Poll<Result<(), Self::Error>> {
122        self.project().write.poll_close(cx)
123    }
124}
125
126impl<T> Session<T>
127where
128    T: Foldable,
129{
130    pub fn connect(config: Config) -> (SessionHandle<T>, Session<T>) {
131        let (p_tx, p_rx) = mpsc::channel(config.request_capactiy);
132        let (m_tx, m_rx) = mpsc::channel(config.request_capactiy);
133        (
134            SessionHandle {
135                msg: m_tx,
136                poll: p_tx,
137            },
138            Session::new(
139                ReceiverStream::new(m_rx),
140                ReceiverStream::new(p_rx),
141                config.message_max_size,
142                config.poll_timeout,
143            ),
144        )
145    }
146}
147
148#[derive(Debug)]
149pub struct SessionHandle<T>
150where
151    T: Foldable,
152{
153    msg: mpsc::Sender<Result<T, ()>>,
154    poll: mpsc::Sender<ResultCallback<T::Start>>,
155}
156
157// Implement Clone manually to avoid B affecting derive
158impl<T> Clone for SessionHandle<T>
159where
160    T: Foldable,
161{
162    fn clone(&self) -> Self {
163        Self {
164            msg: self.msg.clone(),
165            poll: self.poll.clone(),
166        }
167    }
168}
169
170impl<T> SessionHandle<T>
171where
172    T: Foldable,
173{
174    pub async fn close(&mut self) -> Result<(), SessionError> {
175        // We send a ERR down to session (client code might need to timeout this op ?)
176        // Client can choose to drain remaining message or DROP handle
177        self.msg
178            .send(Err(()))
179            .await
180            .map_err(|_| SessionError::Closed)?;
181        Ok(())
182    }
183
184    pub async fn msg(&mut self, item: T) -> Result<(), SessionError> {
185        self.msg
186            .send(Ok(item))
187            .await
188            .map_err(|_| SessionError::Closed)
189    }
190
191    pub async fn poll(&mut self) -> Result<T::Start, SessionError> {
192        let (tx, rx) = oneshot::channel();
193        self.poll.send(tx).await.map_err(|_| SessionError::Closed)?;
194
195        rx.await.map_err(|_| SessionError::Closed)?
196    }
197}