use futures::FutureExt;
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use std::{io, result};
use tokio::sync::{mpsc, oneshot};
use tokio::time::{sleep, Sleep};
const RESPONSE_TIMEOUT: Duration = Duration::from_secs(60);
pub type Result<T> = result::Result<T, io::Error>;
#[derive(Debug)]
pub struct ChannelSender<T> {
inner: InnerSenderChannel<T>,
}
impl<T> ChannelSender<T> {
pub fn is_closed(&self) -> bool {
self.inner.0.is_closed()
}
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub async fn send<M, R, E, S>(&self, message: M) -> Response<R, E>
where
M: FnOnce(Reply<S>) -> T,
Response<R, E>: From<oneshot::Receiver<S>>,
{
let (tx, rx) = oneshot::channel::<S>();
match self.inner.send(message(Reply::new(tx))).await {
Ok(()) => Response::from(rx),
Err(_) => Response::closed(),
}
}
#[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
pub async fn fire_and_forget(&self, message: T) {
let _ = self.inner.send(message).await;
}
pub fn try_fire_and_forget(&self, message: T) -> bool {
self.inner.0.try_send(message).is_ok()
}
}
impl<T> Clone for ChannelSender<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
#[derive(Debug)]
pub struct ChannelReceiver<T> {
inner: InnerReceiverChannel<T>,
}
#[allow(dead_code)]
impl<T> ChannelReceiver<T> {
pub async fn recv(&mut self) -> Option<T> {
self.inner.recv().await
}
pub fn try_recv(&mut self) -> Option<T> {
self.inner.recv().now_or_never().flatten()
}
}
#[derive(Debug)]
pub struct Response<T, E> {
inner: InnerResponse<T, E>,
timeout: Duration,
timeout_timer: Option<Pin<Box<Sleep>>>,
}
impl<T, E> Response<T, E> {
pub fn err(e: E) -> Self {
Self {
inner: InnerResponse::Err(Some(e)),
timeout: RESPONSE_TIMEOUT,
timeout_timer: Default::default(),
}
}
pub fn with_timeout(mut self, limit: Duration) -> Self {
self.timeout = limit;
self.timeout_timer = None;
self
}
pub fn closed() -> Self {
Self {
inner: InnerResponse::Closed,
timeout: RESPONSE_TIMEOUT,
timeout_timer: Default::default(),
}
}
}
impl<T, E> Future for Response<T, E>
where
E: Unpin,
io::Error: Into<E>,
{
type Output = result::Result<T, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
if let Poll::Ready(result) = Pin::new(&mut this.inner).poll(cx) {
return Poll::Ready(result);
}
let timeout = this.timeout;
let timer = this
.timeout_timer
.get_or_insert_with(|| Box::pin(sleep(timeout)));
if timer.as_mut().poll(cx).is_ready() {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::TimedOut,
format!("channel response timed out after {}ms", timeout.as_millis()),
)
.into()));
}
Poll::Pending
}
}
impl<T> From<oneshot::Receiver<T>> for Response<T, io::Error> {
fn from(rx: oneshot::Receiver<T>) -> Self {
Self {
inner: InnerResponse::PendingMapper(rx),
timeout: RESPONSE_TIMEOUT,
timeout_timer: Default::default(),
}
}
}
impl<T, E> From<oneshot::Receiver<result::Result<T, E>>> for Response<T, E> {
fn from(rx: oneshot::Receiver<result::Result<T, E>>) -> Self {
Self {
inner: InnerResponse::Pending(rx),
timeout: RESPONSE_TIMEOUT,
timeout_timer: Default::default(),
}
}
}
enum InnerResponse<T, E> {
Pending(oneshot::Receiver<result::Result<T, E>>),
PendingMapper(oneshot::Receiver<T>),
Err(Option<E>),
Closed,
}
impl<T, E> InnerResponse<T, E> {
fn closed() -> io::Error {
io::Error::new(io::ErrorKind::Interrupted, "channel closed")
}
}
impl<T, E> Future for InnerResponse<T, E>
where
E: Unpin,
io::Error: Into<E>,
{
type Output = result::Result<T, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
match this {
InnerResponse::Pending(rx) => Pin::new(rx)
.poll(cx)
.map(|res| res.unwrap_or_else(|_| Err(Self::closed().into()))),
InnerResponse::PendingMapper(rx) => Pin::new(rx).poll(cx).map(|res| match res {
Ok(v) => Ok(v),
Err(_) => Err(Self::closed().into()),
}),
InnerResponse::Err(e) => {
let err = e.take().unwrap_or_else(|| Self::closed().into());
*this = InnerResponse::Closed;
Poll::Ready(Err(err))
}
InnerResponse::Closed => Poll::Ready(Err(Self::closed().into())),
}
}
}
impl<T, E> Debug for InnerResponse<T, E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Pending(_) => write!(f, "Pending"),
Self::PendingMapper(_) => write!(f, "PendingMapper"),
Self::Err(_) => write!(f, "Err"),
Self::Closed => write!(f, "Closed"),
}
}
}
#[derive(Debug)]
pub struct Reply<T> {
inner: InnerReply<T>,
}
impl<T> Reply<T> {
fn new(inner: oneshot::Sender<T>) -> Self {
Self {
inner: InnerReply::Sender(inner),
}
}
pub fn empty() -> Self {
Self {
inner: InnerReply::Empty,
}
}
pub fn send(self, value: T) {
match self.inner {
InnerReply::Sender(inner) => {
let _ = inner.send(value);
}
InnerReply::Empty => {}
}
}
pub(crate) fn take(self) -> oneshot::Sender<T> {
match self.inner {
InnerReply::Sender(e) => e,
InnerReply::Empty => oneshot::channel().0,
}
}
}
#[derive(Debug)]
enum InnerReply<T> {
Sender(oneshot::Sender<T>),
Empty,
}
#[derive(Debug)]
struct InnerSenderChannel<T>(mpsc::Sender<T>);
impl<T> InnerSenderChannel<T> {
async fn send(&self, value: T) -> Result<()> {
self.0.send(value).await.map_err(|_| Self::closed())
}
fn closed() -> io::Error {
io::Error::new(io::ErrorKind::Interrupted, "channel closed")
}
}
impl<T> Clone for InnerSenderChannel<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
#[derive(Debug)]
struct InnerReceiverChannel<T>(mpsc::Receiver<T>);
impl<T> InnerReceiverChannel<T> {
async fn recv(&mut self) -> Option<T> {
self.0.recv().await
}
}
pub fn channel<T>(limit: usize) -> (ChannelSender<T>, ChannelReceiver<T>) {
let (sender, receiver) = mpsc::channel(limit);
(
ChannelSender {
inner: InnerSenderChannel(sender),
},
ChannelReceiver {
inner: InnerReceiverChannel(receiver),
},
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
use tokio::{select, time};
#[derive(Debug)]
enum TestCommand {
RequestWithArgAndResponse { arg: u32, response: Reply<bool> },
FireAndForget { tx: oneshot::Sender<()> },
None,
}
mod bounded {
use super::*;
#[tokio::test]
async fn test_send_and_receive() {
let arg = 42;
let (sender, receiver) = channel!(2);
let response = sender
.send(|tx| TestCommand::RequestWithArgAndResponse { arg, response: tx })
.await;
validate_response(arg, response, receiver).await;
}
#[tokio::test]
async fn test_fire_and_forget() {
let (sender, receiver) = channel!(2);
let (tx, rx) = oneshot::channel();
start_receiver_processor(receiver);
sender
.fire_and_forget(TestCommand::FireAndForget { tx })
.await;
select! {
_ = time::sleep(Duration::from_millis(250)) => assert!(false, "expected the fire and forget to have been processed"),
_ = rx => {},
}
}
#[tokio::test]
async fn test_try_fire_and_forget() {
let (sender, _receiver) = channel!(1);
assert_eq!(true, sender.try_fire_and_forget(TestCommand::None));
assert_eq!(
false,
sender.try_fire_and_forget(TestCommand::None),
"expected the full channel to reject the message"
);
}
#[tokio::test]
async fn test_backpressure() {
let (sender, mut receiver) = channel!(1);
sender.fire_and_forget(TestCommand::None).await;
let future = sender.fire_and_forget(TestCommand::None);
tokio::pin!(future);
select! {
_ = time::sleep(Duration::from_millis(50)) => {},
_ = &mut future => assert!(false, "expected the second message to be blocked"),
}
receiver
.recv()
.await
.expect("expected to receive the first message");
select! {
_ = time::sleep(Duration::from_millis(100)) => assert!(false, "expected the second message to be processed"),
_ = &mut future => {},
}
}
}
mod response {
use super::*;
#[tokio::test]
async fn test_ready_reply_wins_over_elapsed_timeout() {
let (tx, rx) = oneshot::channel::<u32>();
let response =
Response::<u32, io::Error>::from(rx).with_timeout(Duration::from_millis(20));
tokio::pin!(response);
assert!(futures::poll!(&mut response).is_pending());
tx.send(42).unwrap();
time::sleep(Duration::from_millis(60)).await;
assert_eq!(42, response.await.expect("expected a reply"));
}
#[tokio::test]
async fn test_times_out_without_reply() {
let (_tx, rx) = oneshot::channel::<u32>();
let response =
Response::<u32, io::Error>::from(rx).with_timeout(Duration::from_millis(20));
let err = response.await.expect_err("expected a timeout");
assert_eq!(io::ErrorKind::TimedOut, err.kind());
}
#[tokio::test]
async fn test_from_receiver_uses_default_timeout() {
let (_tx, rx) = oneshot::channel::<u32>();
let response = Response::<u32, io::Error>::from(rx);
assert_eq!(RESPONSE_TIMEOUT, response.timeout);
}
}
mod reply {
use super::*;
#[tokio::test]
async fn test_send_sender() {
let expected_result = 42;
let (tx, mut rx) = oneshot::channel();
let reply = Reply::new(tx);
reply.send(expected_result);
let result = timeout!(Duration::from_millis(100), &mut rx).expect("expected a reply");
assert_eq!(expected_result, result);
}
#[tokio::test]
async fn test_send_empty() {
let reply = Reply::empty();
reply.send(66);
}
#[tokio::test]
async fn test_take_empty() {
let reply = Reply::<u32>::empty();
assert_eq!(true, reply.take().is_closed());
}
}
fn start_receiver_processor(mut receiver: ChannelReceiver<TestCommand>) {
tokio::spawn(async move {
while let Some(command) = receiver.recv().await {
match command {
TestCommand::FireAndForget { tx } => tx.send(()).unwrap(),
_ => {}
}
}
});
}
async fn validate_response<E: Debug + From<io::Error> + Unpin>(
expected_arg_value: u32,
response: Response<bool, E>,
mut receiver: ChannelReceiver<TestCommand>,
) {
let result = receiver.recv().await;
if let Some(TestCommand::RequestWithArgAndResponse {
arg: received_arg,
response,
}) = result
{
assert_eq!(
received_arg, expected_arg_value,
"expected the message argument to match"
);
response.send(true);
} else {
assert!(false, "expected TestCommand::Lorem, but got {:?}", result);
}
let result = response.await.expect("expected a response");
assert_eq!(true, result, "expected the response to be true");
}
}