1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use crate::error::Error;
use crate::grpc::convert::{error_into_grpc, IntoProtobuf};
use futures::prelude::*;
use pin_project::pin_project;
use tonic::Status;

use std::pin::Pin;
use std::task::{Context, Poll};

#[must_use = "streams do nothing unless polled"]
#[pin_project]
pub struct OutboundStream<S> {
    #[pin]
    inner: S,
}

impl<S> OutboundStream<S> {
    pub(crate) fn new(inner: S) -> Self {
        OutboundStream { inner }
    }
}

impl<S> Stream for OutboundStream<S>
where
    S: Stream,
    S::Item: IntoProtobuf,
{
    type Item = <S::Item as IntoProtobuf>::Message;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.project();
        this.inner
            .poll_next(cx)
            .map(|maybe_item| maybe_item.map(|item| item.into_message()))
    }
}

#[must_use = "streams do nothing unless polled"]
#[pin_project]
pub struct OutboundTryStream<S> {
    #[pin]
    inner: S,
}

impl<S> OutboundTryStream<S> {
    pub(crate) fn new(inner: S) -> Self {
        OutboundTryStream { inner }
    }
}

impl<S> Stream for OutboundTryStream<S>
where
    S: TryStream<Error = Error>,
    S::Ok: IntoProtobuf,
{
    type Item = Result<<S::Ok as IntoProtobuf>::Message, Status>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.project();
        this.inner.try_poll_next(cx).map(|maybe_item| {
            maybe_item.map(|item| match item {
                Ok(data) => Ok(data.into_message()),
                Err(e) => Err(error_into_grpc(e)),
            })
        })
    }
}