Skip to main content

pbrs_grpc/compat/
mod.rs

1//! Tonic-shaped API shims over the native `pbrs-grpc` transport.
2
3use futures_core::Stream;
4use std::collections::VecDeque;
5use std::future::poll_fn;
6use std::pin::Pin;
7use std::task::{Context, Poll};
8
9#[cfg(unix)]
10pub use crate::UdsConnectInfo;
11pub use crate::{
12    Code, Request, Response, Status, StreamSender, Streaming, TcpConnectInfo, TlsConnectInfo,
13};
14pub use futures_core::Stream as ResponseStream;
15
16/// Convert a value into a tonic-shaped unary request envelope.
17pub trait IntoRequest<T> {
18    /// Convert into a [`Request`].
19    fn into_request(self) -> Request<T>;
20}
21
22impl<T> IntoRequest<T> for T {
23    fn into_request(self) -> Request<T> {
24        Request::new(self)
25    }
26}
27
28impl<T> IntoRequest<T> for Request<T> {
29    fn into_request(self) -> Request<T> {
30        self
31    }
32}
33
34/// Convert a stream into a tonic-shaped streaming request envelope.
35pub trait IntoStreamingRequest<T> {
36    /// Stream type carrying request messages.
37    type Stream: Stream<Item = T> + Send + 'static;
38
39    /// Convert into a [`Request`] around the stream.
40    fn into_streaming_request(self) -> Request<Self::Stream>;
41}
42
43impl<T, S> IntoStreamingRequest<T> for S
44where
45    S: Stream<Item = T> + Send + 'static,
46{
47    type Stream = S;
48
49    fn into_streaming_request(self) -> Request<Self::Stream> {
50        Request::new(self)
51    }
52}
53
54/// A small dependency-free stream for examples and tests.
55pub struct Iter<T> {
56    items: VecDeque<T>,
57}
58
59impl<T> Unpin for Iter<T> {}
60
61impl<T> Stream for Iter<T> {
62    type Item = T;
63
64    fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
65        Poll::Ready(self.items.pop_front())
66    }
67}
68
69/// Build a stream from an iterator without adding `tokio-stream`.
70pub fn iter<T>(items: impl IntoIterator<Item = T>) -> Iter<T> {
71    Iter {
72        items: items.into_iter().collect(),
73    }
74}
75
76/// Forward a client request stream into the native write half.
77pub fn spawn_request_stream<T, S>(stream: S, sender: StreamSender<T>)
78where
79    T: crate::CodecMessage + Send + 'static,
80    S: Stream<Item = T> + Send + 'static,
81{
82    drop(tokio::spawn(async move {
83        let mut stream = Box::pin(stream);
84        loop {
85            let next = poll_fn(|cx| stream.as_mut().poll_next(cx)).await;
86            let Some(message) = next else {
87                break;
88            };
89            if sender.send(message).await.is_err() {
90                return;
91            }
92        }
93        sender.close();
94    }));
95}
96
97/// Convert a tonic-shaped response stream into the native streaming response.
98pub fn response_stream<T, S>(response: Response<S>) -> Response<Streaming<T>>
99where
100    T: crate::CodecMessage + Send + 'static,
101    S: Stream<Item = Result<T, Status>> + Send + 'static,
102{
103    let (stream, parts) = response.into_message_and_parts();
104    let (sender, outbound) = Streaming::channel(crate::DEFAULT_STREAM_BUFFER);
105    drop(tokio::spawn(async move {
106        let mut stream = Box::pin(stream);
107        loop {
108            match poll_fn(|cx| stream.as_mut().poll_next(cx)).await {
109                Some(Ok(message)) => {
110                    if sender.send(message).await.is_err() {
111                        return;
112                    }
113                }
114                Some(Err(status)) => {
115                    sender.fail(status).await;
116                    return;
117                }
118                None => {
119                    sender.close();
120                    return;
121                }
122            }
123        }
124    }));
125    Response::from_message_and_parts(outbound, parts)
126}