use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;
use futures_core::Stream;
use pin_project_lite::pin_project;
use tokio::time::Sleep;
use tokio_util::sync::CancellationToken;
use tonic::Status;
use crate::load::LoadGuard;
pin_project! {
pub struct GuardedStream<S> {
#[pin]
inner: S,
deadline: Option<Pin<Box<Sleep>>>,
token: CancellationToken,
span: tracing::Span,
_guard: LoadGuard,
finished: bool,
}
}
impl<S> GuardedStream<S> {
pub(crate) fn new(
inner: S,
guard: LoadGuard,
span: tracing::Span,
deadline: Option<Instant>,
token: CancellationToken,
) -> Self {
let deadline = deadline.map(|deadline| {
Box::pin(tokio::time::sleep_until(tokio::time::Instant::from_std(
deadline,
)))
});
Self {
inner,
deadline,
token,
span,
_guard: guard,
finished: false,
}
}
}
impl<S, T> Stream for GuardedStream<S>
where
S: Stream<Item = Result<T, Status>>,
{
type Item = Result<T, Status>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
if *this.finished {
return Poll::Ready(None);
}
let _entered = this.span.enter();
if this.token.is_cancelled() {
*this.finished = true;
return Poll::Ready(Some(Err(Status::cancelled("the call is cancelled"))));
}
if let Some(deadline) = this.deadline.as_mut()
&& deadline.as_mut().poll(cx).is_ready()
{
*this.finished = true;
return Poll::Ready(Some(Err(Status::deadline_exceeded(
"the call deadline is exceeded",
))));
}
match this.inner.as_mut().poll_next(cx) {
Poll::Ready(item) => {
if item.is_none() {
*this.finished = true;
*this.deadline = None;
}
Poll::Ready(item)
}
Poll::Pending => Poll::Pending,
}
}
}