|
| 1 | +use crate::{BoxError, Error}; |
| 2 | +use bytes::Bytes; |
| 3 | +use futures_util::stream::{self, Stream, TryStreamExt}; |
| 4 | +use http::HeaderMap; |
| 5 | +use http_body::Body; |
| 6 | +use std::convert::Infallible; |
| 7 | +use std::{ |
| 8 | + fmt, |
| 9 | + pin::Pin, |
| 10 | + task::{Context, Poll}, |
| 11 | +}; |
| 12 | +use sync_wrapper::SyncWrapper; |
| 13 | + |
| 14 | +/// An [`http_body::Body`] created from a [`Stream`]. |
| 15 | +/// |
| 16 | +/// # Example |
| 17 | +/// |
| 18 | +/// ``` |
| 19 | +/// use axum::{ |
| 20 | +/// Router, |
| 21 | +/// handler::get, |
| 22 | +/// body::StreamBody, |
| 23 | +/// }; |
| 24 | +/// use futures::stream; |
| 25 | +/// |
| 26 | +/// async fn handler() -> StreamBody { |
| 27 | +/// let chunks: Vec<Result<_, std::io::Error>> = vec![ |
| 28 | +/// Ok("Hello,"), |
| 29 | +/// Ok(" "), |
| 30 | +/// Ok("world!"), |
| 31 | +/// ]; |
| 32 | +/// let stream = stream::iter(chunks); |
| 33 | +/// StreamBody::new(stream) |
| 34 | +/// } |
| 35 | +/// |
| 36 | +/// let app = Router::new().route("/", get(handler)); |
| 37 | +/// # async { |
| 38 | +/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); |
| 39 | +/// # }; |
| 40 | +/// ``` |
| 41 | +/// |
| 42 | +/// [`Stream`]: futures_util::stream::Stream |
| 43 | +// this should probably be extracted to `http_body`, eventually... |
| 44 | +pub struct StreamBody { |
| 45 | + stream: SyncWrapper<Pin<Box<dyn Stream<Item = Result<Bytes, Error>> + Send>>>, |
| 46 | +} |
| 47 | + |
| 48 | +impl StreamBody { |
| 49 | + /// Create a new `StreamBody` from a [`Stream`]. |
| 50 | + /// |
| 51 | + /// [`Stream`]: futures_util::stream::Stream |
| 52 | + pub fn new<S, T, E>(stream: S) -> Self |
| 53 | + where |
| 54 | + S: Stream<Item = Result<T, E>> + Send + 'static, |
| 55 | + T: Into<Bytes> + 'static, |
| 56 | + E: Into<BoxError> + 'static, |
| 57 | + { |
| 58 | + let stream = stream |
| 59 | + .map_ok(Into::into) |
| 60 | + .map_err(|err| Error::new(err.into())); |
| 61 | + Self { |
| 62 | + stream: SyncWrapper::new(Box::pin(stream)), |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl Default for StreamBody { |
| 68 | + fn default() -> Self { |
| 69 | + Self::new(stream::empty::<Result<Bytes, Infallible>>()) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl fmt::Debug for StreamBody { |
| 74 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 75 | + f.debug_tuple("StreamBody").finish() |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +impl Body for StreamBody { |
| 80 | + type Data = Bytes; |
| 81 | + type Error = Error; |
| 82 | + |
| 83 | + fn poll_data( |
| 84 | + mut self: Pin<&mut Self>, |
| 85 | + cx: &mut Context<'_>, |
| 86 | + ) -> Poll<Option<Result<Self::Data, Self::Error>>> { |
| 87 | + Pin::new(self.stream.get_mut()).poll_next(cx) |
| 88 | + } |
| 89 | + |
| 90 | + fn poll_trailers( |
| 91 | + self: Pin<&mut Self>, |
| 92 | + _cx: &mut Context<'_>, |
| 93 | + ) -> Poll<Result<Option<HeaderMap>, Self::Error>> { |
| 94 | + Poll::Ready(Ok(None)) |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +#[test] |
| 99 | +fn stream_body_traits() { |
| 100 | + crate::tests::assert_send::<StreamBody>(); |
| 101 | + crate::tests::assert_sync::<StreamBody>(); |
| 102 | + crate::tests::assert_unpin::<StreamBody>(); |
| 103 | +} |
0 commit comments