quic_rpc/pattern/
server_streaming.rsuse futures_lite::{Stream, StreamExt};
use futures_util::{FutureExt, SinkExt, TryFutureExt};
use crate::{
client::{BoxStreamSync, DeferDrop},
message::{InteractionPattern, Msg},
server::{race2, RpcChannel, RpcServerError},
transport::ConnectionErrors,
RpcClient, Service, ServiceConnection, ServiceEndpoint,
};
use std::{
error,
fmt::{self, Debug},
result,
sync::Arc,
};
#[derive(Debug, Clone, Copy)]
pub struct ServerStreaming;
impl InteractionPattern for ServerStreaming {}
pub trait ServerStreamingMsg<S: Service>: Msg<S, Pattern = ServerStreaming> {
type Response: Into<S::Res> + TryFrom<S::Res> + Send + 'static;
}
#[derive(Debug)]
pub enum Error<C: ConnectionErrors> {
Open(C::OpenError),
Send(C::SendError),
}
impl<S: ConnectionErrors> fmt::Display for Error<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl<S: ConnectionErrors> error::Error for Error<S> {}
#[derive(Debug)]
pub enum ItemError<S: ConnectionErrors> {
RecvError(S::RecvError),
DowncastError,
}
impl<S: ConnectionErrors> fmt::Display for ItemError<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl<S: ConnectionErrors> error::Error for ItemError<S> {}
impl<S, C, SC> RpcClient<S, C, SC>
where
SC: Service,
C: ServiceConnection<SC>,
S: Service,
{
pub async fn server_streaming<M>(
&self,
msg: M,
) -> result::Result<BoxStreamSync<'static, result::Result<M::Response, ItemError<C>>>, Error<C>>
where
M: ServerStreamingMsg<S>,
{
let msg = self.map.req_into_outer(msg.into());
let (mut send, recv) = self.source.open().await.map_err(Error::Open)?;
send.send(msg).map_err(Error::<C>::Send).await?;
let map = Arc::clone(&self.map);
let recv = recv.map(move |x| match x {
Ok(x) => {
let x = map
.res_try_into_inner(x)
.map_err(|_| ItemError::DowncastError)?;
M::Response::try_from(x).map_err(|_| ItemError::DowncastError)
}
Err(e) => Err(ItemError::RecvError(e)),
});
let recv = Box::pin(DeferDrop(recv, send));
Ok(recv)
}
}
impl<S, C, SC> RpcChannel<S, C, SC>
where
S: Service,
SC: Service,
C: ServiceEndpoint<SC>,
{
pub async fn server_streaming<M, F, Str, T>(
self,
req: M,
target: T,
f: F,
) -> result::Result<(), RpcServerError<C>>
where
M: ServerStreamingMsg<S>,
F: FnOnce(T, M) -> Str + Send + 'static,
Str: Stream<Item = M::Response> + Send + 'static,
T: Send + 'static,
{
let Self {
mut send, mut recv, ..
} = self;
let cancel = recv
.next()
.map(|_| RpcServerError::UnexpectedUpdateMessage::<C>);
race2(cancel.map(Err), async move {
let responses = f(target, req);
tokio::pin!(responses);
while let Some(response) = responses.next().await {
let response = self.map.res_into_outer(response.into());
send.send(response)
.await
.map_err(RpcServerError::SendError)?;
}
Ok(())
})
.await
}
}