Skip to main content

typeway_server/
body.rs

1//! Shared body type used throughout the server.
2//!
3//! [`BoxBody`] is a type-erased HTTP body that supports both buffered and
4//! streaming responses. Handlers return `Response<BoxBody>`.
5
6use bytes::Bytes;
7use http_body_util::combinators::UnsyncBoxBody;
8use http_body_util::{BodyExt, Empty, Full, StreamBody};
9
10/// The response body type used by typeway handlers.
11///
12/// This is a type-erased body that can wrap buffered data (`Full<Bytes>`),
13/// streaming data, or an empty body. It implements `http_body::Body`.
14///
15/// Uses `UnsyncBoxBody` internally, which only requires `Send` (not `Sync`),
16/// enabling streaming bodies from channels and other async sources.
17pub type BoxBody = UnsyncBoxBody<Bytes, BoxBodyError>;
18
19/// Error type for the boxed body. Infallible for buffered bodies,
20/// but allows streaming bodies to report errors.
21pub type BoxBodyError = Box<dyn std::error::Error + Send + Sync>;
22
23/// Create a `BoxBody` from bytes.
24pub fn body_from_bytes(bytes: Bytes) -> BoxBody {
25    Full::new(bytes).map_err(|e| match e {}).boxed_unsync()
26}
27
28/// Create a `BoxBody` from a string.
29pub fn body_from_string(s: String) -> BoxBody {
30    body_from_bytes(Bytes::from(s))
31}
32
33/// Create an empty `BoxBody`.
34pub fn empty_body() -> BoxBody {
35    Empty::new().map_err(|e| match e {}).boxed_unsync()
36}
37
38/// Create a streaming `BoxBody` from a `Stream` of `Result<Frame<Bytes>, E>`.
39///
40/// Use this for Server-Sent Events, chunked responses, or any streaming body.
41/// The stream only needs to be `Send` — `Sync` is not required.
42///
43/// # Example
44///
45/// ```ignore
46/// use futures::stream;
47/// use http_body::Frame;
48///
49/// let chunks = stream::iter(vec![
50///     Ok(Frame::data(Bytes::from("chunk 1\n"))),
51///     Ok(Frame::data(Bytes::from("chunk 2\n"))),
52/// ]);
53/// let body = body_from_stream(chunks);
54/// ```
55pub fn body_from_stream<S>(stream: S) -> BoxBody
56where
57    S: futures::Stream<Item = Result<http_body::Frame<Bytes>, BoxBodyError>> + Send + 'static,
58{
59    StreamBody::new(stream).boxed_unsync()
60}
61
62/// Create an SSE (Server-Sent Events) body from a stream of event strings.
63///
64/// Each string in the stream is formatted as an SSE event (`data: ...\n\n`).
65/// The stream only needs to be `Send`.
66///
67/// # Example
68///
69/// ```ignore
70/// use futures::stream;
71///
72/// let events = stream::iter(vec!["hello", "world"]);
73/// let body = sse_body(events.map(|s| s.to_string()));
74/// ```
75pub fn sse_body<S>(stream: S) -> BoxBody
76where
77    S: futures::Stream<Item = String> + Send + 'static,
78{
79    use futures::StreamExt;
80    let framed = stream.map(|event| {
81        let data = format!("data: {event}\n\n");
82        Ok(http_body::Frame::data(Bytes::from(data)))
83    });
84    body_from_stream(framed)
85}