Skip to main content

redup_bootstrap_client/
stream.rs

1//! Поток ответов клиента: учёт нагрузки, крайний срок и отмена действуют до его конца.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::task::{Context, Poll};
6use std::time::Instant;
7
8use futures_core::Stream;
9use pin_project_lite::pin_project;
10use tokio::time::Sleep;
11use tokio_util::sync::CancellationToken;
12use tonic::Status;
13
14use crate::load::LoadGuard;
15
16pin_project! {
17    /// Поток ответов с учётом исходящей нагрузки и крайним сроком.
18    pub struct GuardedStream<S> {
19        #[pin]
20        inner: S,
21        deadline: Option<Pin<Box<Sleep>>>,
22        token: CancellationToken,
23        span: tracing::Span,
24        _guard: LoadGuard,
25        finished: bool,
26    }
27}
28
29impl<S> GuardedStream<S> {
30    pub(crate) fn new(
31        inner: S,
32        guard: LoadGuard,
33        span: tracing::Span,
34        deadline: Option<Instant>,
35        token: CancellationToken,
36    ) -> Self {
37        let deadline = deadline.map(|deadline| {
38            Box::pin(tokio::time::sleep_until(tokio::time::Instant::from_std(
39                deadline,
40            )))
41        });
42        Self {
43            inner,
44            deadline,
45            token,
46            span,
47            _guard: guard,
48            finished: false,
49        }
50    }
51}
52
53impl<S, T> Stream for GuardedStream<S>
54where
55    S: Stream<Item = Result<T, Status>>,
56{
57    type Item = Result<T, Status>;
58
59    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
60        let mut this = self.project();
61        if *this.finished {
62            return Poll::Ready(None);
63        }
64        let _entered = this.span.enter();
65        if this.token.is_cancelled() {
66            *this.finished = true;
67            return Poll::Ready(Some(Err(Status::cancelled("the call is cancelled"))));
68        }
69        if let Some(deadline) = this.deadline.as_mut()
70            && deadline.as_mut().poll(cx).is_ready()
71        {
72            *this.finished = true;
73            return Poll::Ready(Some(Err(Status::deadline_exceeded(
74                "the call deadline is exceeded",
75            ))));
76        }
77        match this.inner.as_mut().poll_next(cx) {
78            Poll::Ready(item) => {
79                if item.is_none() {
80                    *this.finished = true;
81                    *this.deadline = None;
82                }
83                Poll::Ready(item)
84            }
85            Poll::Pending => Poll::Pending,
86        }
87    }
88}