quic_rpc/pattern/
server_streaming.rsuse std::{
error,
fmt::{self, Debug},
result,
};
use futures_lite::{Stream, StreamExt};
use futures_util::{FutureExt, SinkExt, TryFutureExt};
use crate::{
client::{BoxStreamSync, DeferDrop},
message::{InteractionPattern, Msg},
server::{race2, RpcChannel, RpcServerError},
transport::{ConnectionErrors, Connector, StreamTypes},
RpcClient, Service,
};
#[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: Connector> fmt::Display for Error<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl<S: Connector> 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> RpcClient<S, C>
where
C: crate::Connector<S>,
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 = msg.into();
let (mut send, recv) = self.source.open().await.map_err(Error::Open)?;
send.send(msg).map_err(Error::<C>::Send).await?;
let recv = recv.map(move |x| match x {
Ok(msg) => M::Response::try_from(msg).map_err(|_| ItemError::DowncastError),
Err(e) => Err(ItemError::RecvError(e)),
});
let recv = Box::pin(DeferDrop(recv, send));
Ok(recv)
}
}
impl<S, C> RpcChannel<S, C>
where
S: Service,
C: StreamTypes<In = S::Req, Out = S::Res>,
{
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 = response.into();
send.send(response)
.await
.map_err(RpcServerError::SendError)?;
}
Ok(())
})
.await
}
}