use crate::http_poll::{Foldable, ResponseFramer, ResultCallback, Writer, WriterError};
use futures::{Future, Sink, SinkExt, Stream};
use pin_project_lite::pin_project;
use std::pin::Pin;
use std::{
task::{ready, Poll},
time::Duration,
};
use tokio::sync::{mpsc, oneshot};
use tokio_stream::wrappers::ReceiverStream;
pub type SessionError = WriterError;
#[derive(Copy, Clone)]
pub struct Config {
pub message_max_size: usize,
pub request_capactiy: usize,
pub poll_timeout: Duration,
}
impl Default for Config {
fn default() -> Self {
Self {
message_max_size: 1 << 20,
request_capactiy: 16,
poll_timeout: Duration::from_secs(30),
}
}
}
pin_project! {
pub struct Session<T> where T:Foldable {
#[pin]
read: ReceiverStream<Result<T,()>>,
#[pin]
write: ResponseFramer<Writer<ReceiverStream<ResultCallback<T::Start>>>,T>,
}
}
impl<T> Session<T>
where
T: Foldable,
{
fn new(
read: ReceiverStream<Result<T, ()>>,
write: ReceiverStream<ResultCallback<T::Start>>,
max_size: usize,
poll_timeout: Duration,
) -> Self {
Self {
read,
write: ResponseFramer::new(max_size, Writer::new(write)),
}
}
pub async fn close_session(mut self: Pin<&mut Self>) -> Result<(), SessionError> {
self.as_mut().project().read.close();
self.project().write.close().await
}
}
impl<T> Stream for Session<T>
where
T: Foldable,
{
type Item = T;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
if let Poll::Ready(result) = self.as_mut().project().write.poll(cx) {
self.as_mut().project().read.close();
}
match ready!(self.as_mut().project().read.poll_next(cx)) {
Some(Err(_)) => {
self.project().read.close();
Poll::Ready(None)
}
other => Poll::Ready(other.map(|r| r.unwrap())),
}
}
}
impl<T> Sink<T> for Session<T>
where
T: Foldable,
{
type Error = WriterError;
fn poll_ready(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.project().write.poll_ready(cx)
}
fn start_send(mut self: std::pin::Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
self.project().write.start_send(item)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.project().write.poll_flush(cx)
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.project().write.poll_close(cx)
}
}
impl<T> Session<T>
where
T: Foldable,
{
pub fn connect(config: Config) -> (SessionHandle<T>, Session<T>) {
let (p_tx, p_rx) = mpsc::channel(config.request_capactiy);
let (m_tx, m_rx) = mpsc::channel(config.request_capactiy);
(
SessionHandle {
msg: m_tx,
poll: p_tx,
},
Session::new(
ReceiverStream::new(m_rx),
ReceiverStream::new(p_rx),
config.message_max_size,
config.poll_timeout,
),
)
}
}
#[derive(Debug)]
pub struct SessionHandle<T>
where
T: Foldable,
{
msg: mpsc::Sender<Result<T, ()>>,
poll: mpsc::Sender<ResultCallback<T::Start>>,
}
impl<T> Clone for SessionHandle<T>
where
T: Foldable,
{
fn clone(&self) -> Self {
Self {
msg: self.msg.clone(),
poll: self.poll.clone(),
}
}
}
impl<T> SessionHandle<T>
where
T: Foldable,
{
pub async fn close(&mut self) -> Result<(), SessionError> {
self.msg
.send(Err(()))
.await
.map_err(|_| SessionError::Closed)?;
Ok(())
}
pub async fn msg(&mut self, item: T) -> Result<(), SessionError> {
self.msg
.send(Ok(item))
.await
.map_err(|_| SessionError::Closed)
}
pub async fn poll(&mut self) -> Result<T::Start, SessionError> {
let (tx, rx) = oneshot::channel();
self.poll.send(tx).await.map_err(|_| SessionError::Closed)?;
rx.await.map_err(|_| SessionError::Closed)?
}
}