tonic/codec/
decode.rs

1use super::compression::{decompress, CompressionEncoding, CompressionSettings};
2use super::{BufferSettings, DecodeBuf, Decoder, DEFAULT_MAX_RECV_MESSAGE_SIZE, HEADER_SIZE};
3use crate::{body::Body, metadata::MetadataMap, Code, Status};
4use bytes::{Buf, BufMut, BytesMut};
5use http::{HeaderMap, StatusCode};
6use http_body::Body as HttpBody;
7use http_body_util::BodyExt;
8use std::{
9    fmt, future,
10    pin::Pin,
11    task::ready,
12    task::{Context, Poll},
13};
14use sync_wrapper::SyncWrapper;
15use tokio_stream::Stream;
16use tracing::{debug, trace};
17
18/// Streaming requests and responses.
19///
20/// This will wrap some inner [`Body`] and [`Decoder`] and provide an interface
21/// to fetch the message stream and trailing metadata
22pub struct Streaming<T> {
23    decoder: SyncWrapper<Box<dyn Decoder<Item = T, Error = Status> + Send + 'static>>,
24    inner: StreamingInner,
25}
26
27struct StreamingInner {
28    body: SyncWrapper<Body>,
29    state: State,
30    direction: Direction,
31    buf: BytesMut,
32    trailers: Option<HeaderMap>,
33    decompress_buf: BytesMut,
34    encoding: Option<CompressionEncoding>,
35    max_message_size: Option<usize>,
36}
37
38impl<T> Unpin for Streaming<T> {}
39
40#[derive(Debug, Clone)]
41enum State {
42    ReadHeader,
43    ReadBody {
44        compression: Option<CompressionEncoding>,
45        len: usize,
46    },
47    Error(Option<Status>),
48}
49
50#[derive(Debug, PartialEq, Eq)]
51enum Direction {
52    Request,
53    Response(StatusCode),
54    EmptyResponse,
55}
56
57impl<T> Streaming<T> {
58    /// Create a new streaming response in the grpc response format for decoding a response [Body]
59    /// into message of type T
60    pub fn new_response<B, D>(
61        decoder: D,
62        body: B,
63        status_code: StatusCode,
64        encoding: Option<CompressionEncoding>,
65        max_message_size: Option<usize>,
66    ) -> Self
67    where
68        B: HttpBody + Send + 'static,
69        B::Error: Into<crate::BoxError>,
70        D: Decoder<Item = T, Error = Status> + Send + 'static,
71    {
72        Self::new(
73            decoder,
74            body,
75            Direction::Response(status_code),
76            encoding,
77            max_message_size,
78        )
79    }
80
81    /// Create empty response. For creating responses that have no content (headers + trailers only)
82    pub fn new_empty<B, D>(decoder: D, body: B) -> Self
83    where
84        B: HttpBody + Send + 'static,
85        B::Error: Into<crate::BoxError>,
86        D: Decoder<Item = T, Error = Status> + Send + 'static,
87    {
88        Self::new(decoder, body, Direction::EmptyResponse, None, None)
89    }
90
91    /// Create a new streaming request in the grpc response format for decoding a request [Body]
92    /// into message of type T
93    pub fn new_request<B, D>(
94        decoder: D,
95        body: B,
96        encoding: Option<CompressionEncoding>,
97        max_message_size: Option<usize>,
98    ) -> Self
99    where
100        B: HttpBody + Send + 'static,
101        B::Error: Into<crate::BoxError>,
102        D: Decoder<Item = T, Error = Status> + Send + 'static,
103    {
104        Self::new(
105            decoder,
106            body,
107            Direction::Request,
108            encoding,
109            max_message_size,
110        )
111    }
112
113    fn new<B, D>(
114        decoder: D,
115        body: B,
116        direction: Direction,
117        encoding: Option<CompressionEncoding>,
118        max_message_size: Option<usize>,
119    ) -> Self
120    where
121        B: HttpBody + Send + 'static,
122        B::Error: Into<crate::BoxError>,
123        D: Decoder<Item = T, Error = Status> + Send + 'static,
124    {
125        let buffer_size = decoder.buffer_settings().buffer_size;
126        Self {
127            decoder: SyncWrapper::new(Box::new(decoder)),
128            inner: StreamingInner {
129                body: SyncWrapper::new(Body::new(
130                    body.map_frame(|frame| {
131                        frame.map_data(|mut buf| buf.copy_to_bytes(buf.remaining()))
132                    })
133                    .map_err(|err| Status::map_error(err.into())),
134                )),
135                state: State::ReadHeader,
136                direction,
137                buf: BytesMut::with_capacity(buffer_size),
138                trailers: None,
139                decompress_buf: BytesMut::new(),
140                encoding,
141                max_message_size,
142            },
143        }
144    }
145}
146
147impl StreamingInner {
148    fn decode_chunk(
149        &mut self,
150        buffer_settings: BufferSettings,
151    ) -> Result<Option<DecodeBuf<'_>>, Status> {
152        if let State::ReadHeader = self.state {
153            if self.buf.remaining() < HEADER_SIZE {
154                return Ok(None);
155            }
156
157            let compression_encoding = match self.buf.get_u8() {
158                0 => None,
159                1 => {
160                    {
161                        if self.encoding.is_some() {
162                            self.encoding
163                        } else {
164                            // https://grpc.github.io/grpc/core/md_doc_compression.html
165                            // An ill-constructed message with its Compressed-Flag bit set but lacking a grpc-encoding
166                            // entry different from identity in its metadata MUST fail with INTERNAL status,
167                            // its associated description indicating the invalid Compressed-Flag condition.
168                            return Err(Status::internal( "protocol error: received message with compressed-flag but no grpc-encoding was specified"));
169                        }
170                    }
171                }
172                f => {
173                    trace!("unexpected compression flag");
174                    let message = if let Direction::Response(status) = self.direction {
175                        format!(
176                            "protocol error: received message with invalid compression flag: {f} (valid flags are 0 and 1) while receiving response with status: {status}"
177                        )
178                    } else {
179                        format!("protocol error: received message with invalid compression flag: {f} (valid flags are 0 and 1), while sending request")
180                    };
181                    return Err(Status::internal(message));
182                }
183            };
184
185            let len = self.buf.get_u32() as usize;
186            let limit = self
187                .max_message_size
188                .unwrap_or(DEFAULT_MAX_RECV_MESSAGE_SIZE);
189            if len > limit {
190                return Err(Status::out_of_range(
191                    format!(
192                        "Error, decoded message length too large: found {len} bytes, the limit is: {limit} bytes"
193                    ),
194                ));
195            }
196
197            self.buf.reserve(len);
198
199            self.state = State::ReadBody {
200                compression: compression_encoding,
201                len,
202            }
203        }
204
205        if let State::ReadBody { len, compression } = self.state {
206            // if we haven't read enough of the message then return and keep
207            // reading
208            if self.buf.remaining() < len || self.buf.len() < len {
209                return Ok(None);
210            }
211
212            let decode_buf = if let Some(encoding) = compression {
213                self.decompress_buf.clear();
214                let limit = self
215                    .max_message_size
216                    .unwrap_or(DEFAULT_MAX_RECV_MESSAGE_SIZE);
217                let limited_out_buf = (&mut self.decompress_buf).limit(limit);
218
219                if let Err(err) = decompress(
220                    CompressionSettings {
221                        encoding,
222                        buffer_growth_interval: buffer_settings.buffer_size,
223                    },
224                    &mut self.buf,
225                    limited_out_buf,
226                    len,
227                ) {
228                    if matches!(err.kind(), std::io::ErrorKind::WriteZero) {
229                        return Err(Status::resource_exhausted(format!(
230                            "Error decompressing: size limit, of {limit} bytes, exceeded while decompressing message"
231                        )));
232                    }
233                    let message = if let Direction::Response(status) = self.direction {
234                        format!(
235                            "Error decompressing: {err}, while receiving response with status: {status}"
236                        )
237                    } else {
238                        format!("Error decompressing: {err}, while sending request")
239                    };
240                    return Err(Status::internal(message));
241                }
242                let decompressed_len = self.decompress_buf.len();
243                DecodeBuf::new(&mut self.decompress_buf, decompressed_len)
244            } else {
245                DecodeBuf::new(&mut self.buf, len)
246            };
247
248            return Ok(Some(decode_buf));
249        }
250
251        Ok(None)
252    }
253
254    // Returns Some(()) if data was found or None if the loop in `poll_next` should break
255    fn poll_frame(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<()>, Status>> {
256        let frame = match ready!(Pin::new(self.body.get_mut()).poll_frame(cx)) {
257            Some(Ok(frame)) => frame,
258            Some(Err(status)) => {
259                if self.direction == Direction::Request && status.code() == Code::Cancelled {
260                    return Poll::Ready(Ok(None));
261                }
262
263                let _ = std::mem::replace(&mut self.state, State::Error(Some(status.clone())));
264                debug!("decoder inner stream error: {:?}", status);
265                return Poll::Ready(Err(status));
266            }
267            None => {
268                // FIXME: improve buf usage.
269                return Poll::Ready(if self.buf.has_remaining() {
270                    trace!("unexpected EOF decoding stream, state: {:?}", self.state);
271                    Err(Status::internal("Unexpected EOF decoding stream."))
272                } else {
273                    Ok(None)
274                });
275            }
276        };
277
278        Poll::Ready(if frame.is_data() {
279            self.buf.put(frame.into_data().unwrap());
280            Ok(Some(()))
281        } else if frame.is_trailers() {
282            if let Some(trailers) = &mut self.trailers {
283                trailers.extend(frame.into_trailers().unwrap());
284            } else {
285                self.trailers = Some(frame.into_trailers().unwrap());
286            }
287
288            Ok(None)
289        } else {
290            panic!("unexpected frame: {frame:?}");
291        })
292    }
293
294    fn response(&mut self) -> Result<(), Status> {
295        if let Direction::Response(status) = self.direction {
296            if let Err(Some(e)) = crate::status::infer_grpc_status(self.trailers.as_ref(), status) {
297                // If the trailers contain a grpc-status, then we should return that as the error
298                // and otherwise stop the stream (by taking the error state)
299                self.trailers.take();
300                return Err(e);
301            }
302        }
303        Ok(())
304    }
305}
306
307impl<T> Streaming<T> {
308    /// Fetch the next message from this stream.
309    ///
310    /// # Return value
311    ///
312    /// - `Result::Err(val)` means a gRPC error was sent by the sender instead
313    ///   of a valid response message. Refer to [`Status::code`] and
314    ///   [`Status::message`] to examine possible error causes.
315    ///
316    /// - `Result::Ok(None)` means the stream was closed by the sender and no
317    ///   more messages will be delivered. Further attempts to call
318    ///   [`Streaming::message`] will result in the same return value.
319    ///
320    /// - `Result::Ok(Some(val))` means the sender streamed a valid response
321    ///   message `val`.
322    ///
323    /// ```rust
324    /// # use tonic::{Streaming, Status, codec::Decoder};
325    /// # use std::fmt::Debug;
326    /// # async fn next_message_ex<T, D>(mut request: Streaming<T>) -> Result<(), Status>
327    /// # where T: Debug,
328    /// # D: Decoder<Item = T, Error = Status> + Send  + 'static,
329    /// # {
330    /// if let Some(next_message) = request.message().await? {
331    ///     println!("{:?}", next_message);
332    /// }
333    /// # Ok(())
334    /// # }
335    /// ```
336    pub async fn message(&mut self) -> Result<Option<T>, Status> {
337        match future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await {
338            Some(Ok(m)) => Ok(Some(m)),
339            Some(Err(e)) => Err(e),
340            None => Ok(None),
341        }
342    }
343
344    /// Fetch the trailing metadata.
345    ///
346    /// This will drain the stream of all its messages to receive the trailing
347    /// metadata. If [`Streaming::message`] returns `None` then this function
348    /// will not need to poll for trailers since the body was totally consumed.
349    ///
350    /// ```rust
351    /// # use tonic::{Streaming, Status};
352    /// # async fn trailers_ex<T>(mut request: Streaming<T>) -> Result<(), Status> {
353    /// if let Some(metadata) = request.trailers().await? {
354    ///     println!("{:?}", metadata);
355    /// }
356    /// # Ok(())
357    /// # }
358    /// ```
359    pub async fn trailers(&mut self) -> Result<Option<MetadataMap>, Status> {
360        // Shortcut to see if we already pulled the trailers in the stream step
361        // we need to do that so that the stream can error on trailing grpc-status
362        if let Some(trailers) = self.inner.trailers.take() {
363            return Ok(Some(MetadataMap::from_headers(trailers)));
364        }
365
366        // To fetch the trailers we must clear the body and drop it.
367        while self.message().await?.is_some() {}
368
369        // Since we call poll_trailers internally on poll_next we need to
370        // check if it got cached again.
371        if let Some(trailers) = self.inner.trailers.take() {
372            return Ok(Some(MetadataMap::from_headers(trailers)));
373        }
374
375        // We've polled through all the frames, and still no trailers, return None
376        Ok(None)
377    }
378
379    fn decode_chunk(&mut self) -> Result<Option<T>, Status> {
380        match self
381            .inner
382            .decode_chunk(self.decoder.get_mut().buffer_settings())?
383        {
384            Some(mut decode_buf) => match self.decoder.get_mut().decode(&mut decode_buf)? {
385                Some(msg) => {
386                    self.inner.state = State::ReadHeader;
387                    Ok(Some(msg))
388                }
389                None => Ok(None),
390            },
391            None => Ok(None),
392        }
393    }
394}
395
396impl<T> Stream for Streaming<T> {
397    type Item = Result<T, Status>;
398
399    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
400        loop {
401            // When the stream encounters an error yield that error once and then on subsequent
402            // calls to poll_next return Poll::Ready(None) indicating that the stream has been
403            // fully exhausted.
404            if let State::Error(status) = &mut self.inner.state {
405                return Poll::Ready(status.take().map(Err));
406            }
407
408            if let Some(item) = self.decode_chunk()? {
409                return Poll::Ready(Some(Ok(item)));
410            }
411
412            if ready!(self.inner.poll_frame(cx))?.is_none() {
413                match self.inner.response() {
414                    Ok(()) => return Poll::Ready(None),
415                    Err(err) => self.inner.state = State::Error(Some(err)),
416                }
417            }
418        }
419    }
420}
421
422impl<T> fmt::Debug for Streaming<T> {
423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424        f.debug_struct("Streaming").finish()
425    }
426}
427
428#[cfg(test)]
429static_assertions::assert_impl_all!(Streaming<()>: Send, Sync);