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    /// The response a `HEAD` request gets: same status and headers, no body.
82    /// `content-length` is set from the buffered body unless already present.
83    pub(crate) fn into_head(mut self) -> Self {
84        let bodiless = self.status.is_informational()
85            || self.status == StatusCode::NO_CONTENT
86            || self.status == StatusCode::NOT_MODIFIED;
87        if self.stream.is_none()
88            && !bodiless
89            && !self.headers.contains_key(http::header::CONTENT_LENGTH)
90        {
91            if let Ok(len) = http::HeaderValue::from_str(&self.body.len().to_string()) {
92                self.headers.insert(http::header::CONTENT_LENGTH, len);
93            }
94        }
95        self.body = Bytes::new();
96        self.stream = None;
97        self
98    }
99
100    /// Whether the body is streamed instead of held in `body`
101    pub fn is_streaming(&self) -> bool {
102        self.stream.is_some()
103    }
104
105    /// Set a cookie
106    pub fn cookie(mut self, cookie: Cookie) -> Self {
107        self.cookies.push(cookie);
108        self
109    }
110
111    pub fn ok() -> Self {
112        Self::new(StatusCode::OK)
113    }
114
115    pub fn with_status(mut self, status: StatusCode) -> Self {
116        self.status = status;
117        self
118    }
119
120    pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
121        self.body = body.into();
122        self
123    }
124
125    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
126        let key = key.into();
127        let value = value.into();
128
129        // Validate and insert header, skip invalid ones
130        if let (Ok(header_name), Ok(header_value)) = (
131            http::HeaderName::from_bytes(key.as_bytes()),
132            http::HeaderValue::from_str(&value),
133        ) {
134            self.headers.insert(header_name, header_value);
135        } else {
136            eprintln!("Warning: Invalid header {}={}", key, value);
137        }
138        self
139    }
140
141    pub fn json<T: Serialize>(data: T) -> Self {
142        match serde_json::to_vec(&data) {
143            Ok(body) => Self::ok()
144                .with_header("content-type", "application/json")
145                .with_body(body),
146            Err(e) => {
147                eprintln!("JSON serialization error: {}", e);
148                Self::new(StatusCode::INTERNAL_SERVER_ERROR)
149                    .with_header("content-type", "application/json")
150                    .with_body("{\"error\":\"Internal serialization error\"}")
151            }
152        }
153    }
154
155    pub fn text(text: impl Into<String>) -> Self {
156        Self::ok()
157            .with_header("content-type", "text/plain")
158            .with_body(text.into())
159    }
160
161    /// `200 OK` with an HTML body
162    pub fn html(html: impl Into<String>) -> Self {
163        Self::ok()
164            .with_header("content-type", "text/html; charset=utf-8")
165            .with_body(html.into())
166    }
167
168    /// `303 See Other`, the right answer after a form POST (Post/Redirect/Get)
169    pub fn redirect(location: impl Into<String>) -> Self {
170        Self::new(StatusCode::SEE_OTHER).with_header("location", location)
171    }
172
173    /// `308 Permanent Redirect`, keeps method and body
174    pub fn redirect_permanent(location: impl Into<String>) -> Self {
175        Self::new(StatusCode::PERMANENT_REDIRECT).with_header("location", location)
176    }
177
178    pub fn from_error(error: Error) -> Self {
179        let status = error.status();
180        let mut body = serde_json::json!({
181            "error": error.message(),
182            "status": error.status_code(),
183        });
184        if let Error::Validation(fields) = &error {
185            // field -> list of messages, in the order they were found
186            let mut by_field = serde_json::Map::new();
187            for f in fields {
188                if let Some(list) = by_field
189                    .entry(f.field.clone())
190                    .or_insert_with(|| serde_json::Value::Array(Vec::new()))
191                    .as_array_mut()
192                {
193                    list.push(serde_json::Value::String(f.message.clone()));
194                }
195            }
196            body["fields"] = serde_json::Value::Object(by_field);
197        }
198        let body_bytes =
199            serde_json::to_vec(&body).unwrap_or_else(|_| b"{\"error\":\"Unknown error\"}".to_vec());
200        Self::new(status)
201            .with_header("content-type", "application/json")
202            .with_body(body_bytes)
203    }
204
205    pub(crate) fn into_hyper(self) -> hyper::Response<HyperBody> {
206        use http_body_util::BodyExt;
207        let mut builder = hyper::Response::builder().status(self.status);
208
209        for (key, value) in self.headers.iter() {
210            builder = builder.header(key, value);
211        }
212
213        // Add Set-Cookie headers
214        for cookie in self.cookies {
215            builder = builder.header("set-cookie", cookie.to_header_value());
216        }
217
218        let body: HyperBody = match self.stream {
219            Some(rx) => ChannelBody { rx }.boxed(),
220            None => http_body_util::Full::new(self.body)
221                .map_err(|never| match never {})
222                .boxed(),
223        };
224        builder.body(body).unwrap_or_else(|e| {
225            eprintln!("Failed to build response: {}", e);
226            hyper::Response::builder()
227                .status(StatusCode::INTERNAL_SERVER_ERROR)
228                .body(
229                    http_body_util::Full::new(Bytes::from("Internal Server Error"))
230                        .map_err(|never| match never {})
231                        .boxed(),
232                )
233                .unwrap()
234        })
235    }
236}
237
238/// JSON response helper
239pub struct Json<T>(pub T);
240
241impl<T: Serialize> From<Json<T>> for Response {
242    fn from(json: Json<T>) -> Self {
243        Response::json(json.0)
244    }
245}