Skip to main content

ullun/
response.rs

1//! Response types and builders
2
3use crate::cookies::Cookie;
4use crate::error::Error;
5use bytes::Bytes;
6use http::StatusCode;
7use serde::Serialize;
8
9/// HTTP Response wrapper
10pub struct Response {
11    pub status: StatusCode,
12    pub headers: http::HeaderMap,
13    pub body: Bytes,
14    cookies: Vec<Cookie>,
15    stream: Option<tokio::sync::mpsc::Receiver<Bytes>>,
16}
17
18/// Body type of everything sent to hyper: buffered or streamed
19pub(crate) type HyperBody = http_body_util::combinators::BoxBody<Bytes, std::convert::Infallible>;
20
21/// Chunks arriving through a channel, ended when every sender is dropped
22struct ChannelBody {
23    rx: tokio::sync::mpsc::Receiver<Bytes>,
24}
25
26impl hyper::body::Body for ChannelBody {
27    type Data = Bytes;
28    type Error = std::convert::Infallible;
29
30    fn poll_frame(
31        mut self: std::pin::Pin<&mut Self>,
32        cx: &mut std::task::Context<'_>,
33    ) -> std::task::Poll<Option<std::result::Result<hyper::body::Frame<Bytes>, Self::Error>>> {
34        self.rx
35            .poll_recv(cx)
36            .map(|chunk| chunk.map(|b| Ok(hyper::body::Frame::data(b))))
37    }
38}
39
40impl Response {
41    pub fn new(status: StatusCode) -> Self {
42        Self {
43            status,
44            headers: http::HeaderMap::new(),
45            body: Bytes::new(),
46            cookies: Vec::new(),
47            stream: None,
48        }
49    }
50
51    /// A response whose body is produced while it is being sent
52    ///
53    /// Returns the sender for the body chunks and the response; set status and
54    /// headers on the response as usual. The body ends when the last
55    /// [`BodySender`](crate::stream::BodySender) is dropped, and `send` fails
56    /// with [`Disconnected`](crate::stream::Disconnected) once the client is gone.
57    /// Middleware that rewrites `body` (compression, ETags) leaves streams alone.
58    ///
59    /// ```
60    /// use ullun::prelude::*;
61    ///
62    /// async fn countdown(_req: Request) -> Result<Response> {
63    ///     let (tx, res) = Response::stream();
64    ///     tokio::spawn(async move {
65    ///         for n in (1..=3).rev() {
66    ///             if tx.send(format!("{n}\n")).await.is_err() {
67    ///                 return; // client went away
68    ///             }
69    ///         }
70    ///     });
71    ///     Ok(res.with_header("content-type", "text/plain"))
72    /// }
73    /// ```
74    pub fn stream() -> (crate::stream::BodySender, Self) {
75        let (tx, rx) = tokio::sync::mpsc::channel(16);
76        let mut res = Self::ok();
77        res.stream = Some(rx);
78        (crate::stream::BodySender::new(tx), res)
79    }
80
81    /// Whether the body is streamed instead of held in `body`
82    pub fn is_streaming(&self) -> bool {
83        self.stream.is_some()
84    }
85
86    /// Set a cookie
87    pub fn cookie(mut self, cookie: Cookie) -> Self {
88        self.cookies.push(cookie);
89        self
90    }
91
92    pub fn ok() -> Self {
93        Self::new(StatusCode::OK)
94    }
95
96    pub fn with_status(mut self, status: StatusCode) -> Self {
97        self.status = status;
98        self
99    }
100
101    pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
102        self.body = body.into();
103        self
104    }
105
106    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
107        let key = key.into();
108        let value = value.into();
109
110        // Validate and insert header, skip invalid ones
111        if let (Ok(header_name), Ok(header_value)) = (
112            http::HeaderName::from_bytes(key.as_bytes()),
113            http::HeaderValue::from_str(&value),
114        ) {
115            self.headers.insert(header_name, header_value);
116        } else {
117            eprintln!("Warning: Invalid header {}={}", key, value);
118        }
119        self
120    }
121
122    pub fn json<T: Serialize>(data: T) -> Self {
123        match serde_json::to_vec(&data) {
124            Ok(body) => Self::ok()
125                .with_header("content-type", "application/json")
126                .with_body(body),
127            Err(e) => {
128                eprintln!("JSON serialization error: {}", e);
129                Self::new(StatusCode::INTERNAL_SERVER_ERROR)
130                    .with_header("content-type", "application/json")
131                    .with_body("{\"error\":\"Internal serialization error\"}")
132            }
133        }
134    }
135
136    pub fn text(text: impl Into<String>) -> Self {
137        Self::ok()
138            .with_header("content-type", "text/plain")
139            .with_body(text.into())
140    }
141
142    /// `200 OK` with an HTML body
143    pub fn html(html: impl Into<String>) -> Self {
144        Self::ok()
145            .with_header("content-type", "text/html; charset=utf-8")
146            .with_body(html.into())
147    }
148
149    /// `303 See Other`, the right answer after a form POST (Post/Redirect/Get)
150    pub fn redirect(location: impl Into<String>) -> Self {
151        Self::new(StatusCode::SEE_OTHER).with_header("location", location)
152    }
153
154    /// `308 Permanent Redirect`, keeps method and body
155    pub fn redirect_permanent(location: impl Into<String>) -> Self {
156        Self::new(StatusCode::PERMANENT_REDIRECT).with_header("location", location)
157    }
158
159    pub fn from_error(error: Error) -> Self {
160        let status = error.status();
161        let mut body = serde_json::json!({
162            "error": error.message(),
163            "status": error.status_code(),
164        });
165        if let Error::Validation(fields) = &error {
166            // field -> list of messages, in the order they were found
167            let mut by_field = serde_json::Map::new();
168            for f in fields {
169                if let Some(list) = by_field
170                    .entry(f.field.clone())
171                    .or_insert_with(|| serde_json::Value::Array(Vec::new()))
172                    .as_array_mut()
173                {
174                    list.push(serde_json::Value::String(f.message.clone()));
175                }
176            }
177            body["fields"] = serde_json::Value::Object(by_field);
178        }
179        let body_bytes =
180            serde_json::to_vec(&body).unwrap_or_else(|_| b"{\"error\":\"Unknown error\"}".to_vec());
181        Self::new(status)
182            .with_header("content-type", "application/json")
183            .with_body(body_bytes)
184    }
185
186    pub(crate) fn into_hyper(self) -> hyper::Response<HyperBody> {
187        use http_body_util::BodyExt;
188        let mut builder = hyper::Response::builder().status(self.status);
189
190        for (key, value) in self.headers.iter() {
191            builder = builder.header(key, value);
192        }
193
194        // Add Set-Cookie headers
195        for cookie in self.cookies {
196            builder = builder.header("set-cookie", cookie.to_header_value());
197        }
198
199        let body: HyperBody = match self.stream {
200            Some(rx) => ChannelBody { rx }.boxed(),
201            None => http_body_util::Full::new(self.body)
202                .map_err(|never| match never {})
203                .boxed(),
204        };
205        builder.body(body).unwrap_or_else(|e| {
206            eprintln!("Failed to build response: {}", e);
207            hyper::Response::builder()
208                .status(StatusCode::INTERNAL_SERVER_ERROR)
209                .body(
210                    http_body_util::Full::new(Bytes::from("Internal Server Error"))
211                        .map_err(|never| match never {})
212                        .boxed(),
213                )
214                .unwrap()
215        })
216    }
217}
218
219/// JSON response helper
220pub struct Json<T>(pub T);
221
222impl<T: Serialize> From<Json<T>> for Response {
223    fn from(json: Json<T>) -> Self {
224        Response::json(json.0)
225    }
226}