ash_jsonapi/response.rs
1//! Turning documents and errors into HTTP responses.
2//!
3//! A handler returns [`Created`], [`Ok`] or a [`JsonApiError`] and gets the
4//! right status, the JSON:API media type, and a correctly shaped body. None
5//! of that is assembled at a call site.
6
7use axum::http::{StatusCode, header};
8use axum::response::{IntoResponse, Response};
9
10use std::collections::BTreeMap;
11
12use crate::document::{Document, Links, MEDIA_TYPE, ResourceObject};
13use crate::error::JsonApiError;
14
15/// `200 OK` with a document.
16///
17/// Named `Fetched` rather than `Ok`: a handler returns
18/// `Result<Fetched, Errors>`, and a type called `Ok` in that position
19/// shadows `Result::Ok` at every call site.
20pub struct Fetched(pub Document);
21
22impl Fetched {
23 /// One resource.
24 pub fn one(resource: ResourceObject) -> Self {
25 Self(Document::single(resource))
26 }
27
28 /// A collection.
29 pub fn many(resources: Vec<ResourceObject>) -> Self {
30 Self(Document::collection(resources))
31 }
32
33 /// One page of a collection, with its pagination links.
34 ///
35 /// Built by the generated `LIST` handler from what
36 /// [`List::list`](crate::crud::List::list) returned. `total` becomes
37 /// `meta.total` when storage counted the collection, so a client can size
38 /// a pager without walking it.
39 pub fn page(resources: Vec<ResourceObject>, links: Links, total: Option<usize>) -> Self {
40 let mut document = Document::collection(resources).with_links(links);
41
42 if let Some(total) = total {
43 document.meta = Some(BTreeMap::from([(
44 "total".to_string(),
45 serde_json::Value::from(total),
46 )]));
47 }
48
49 Self(document)
50 }
51
52 /// Record the negotiated locale on the document's top-level `meta`.
53 ///
54 /// A no-op when the request sent no `Accept-Language` this crate could
55 /// parse, so a response carries `lang` only when there was one to carry.
56 /// The rest of `meta` is left alone — a paged listing keeps its `total`.
57 ///
58 /// Applied by the generated handlers; call it on a hand-written one to
59 /// get the same behaviour.
60 #[must_use]
61 pub fn in_context(self, ctx: &crate::Context) -> Self {
62 match ctx.locale() {
63 Some(locale) => Self(self.0.with_meta("lang", locale.as_str())),
64 None => self,
65 }
66 }
67}
68
69/// `201 Created` with the resource and its `Location` header.
70///
71/// The location is the resource's own `self` link, so it is never spelled
72/// separately.
73pub struct Created(pub ResourceObject);
74
75/// A JSONL body, written one line at a time.
76///
77/// Built by the generated `LIST` handler when the client sends
78/// `Accept: application/jsonl` and the resource routes
79/// [`STREAM`](crate::api!). Each row is serialized, written, and dropped, so
80/// the response holds one row rather than the collection — see
81/// [`jsonl`](crate::jsonl) for the trade this makes against a document.
82#[cfg(feature = "streaming")]
83#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
84pub struct Streamed(
85 Box<dyn futures_core::Stream<Item = Result<Vec<u8>, std::convert::Infallible>> + Send + Unpin>,
86);
87
88#[cfg(feature = "streaming")]
89impl Streamed {
90 /// Build a JSONL body from a stream of already-rendered lines.
91 ///
92 /// Each item is one complete line, newline included. The error type is
93 /// [`Infallible`](std::convert::Infallible) deliberately: a failure has
94 /// to become a *line* rather than a transport error, because the status
95 /// was already sent — see [`ERROR_LINE`](crate::jsonl::ERROR_LINE).
96 pub fn new(
97 lines: impl futures_core::Stream<Item = Result<Vec<u8>, std::convert::Infallible>>
98 + Send
99 + Unpin
100 + 'static,
101 ) -> Self {
102 Self(Box::new(lines))
103 }
104
105 /// Render one resource object as a JSONL line.
106 ///
107 /// Serialization cannot fail for a `ResourceObject`, but if it somehow
108 /// did, an error line is emitted rather than a truncated stream — a
109 /// client must never mistake a partial export for a whole one.
110 pub fn line(resource: &crate::document::ResourceObject) -> Vec<u8> {
111 match serde_json::to_vec(resource) {
112 Ok(mut line) => {
113 line.push(b'\n');
114 line
115 }
116 Err(_) => Self::error_line(&JsonApiError::new(crate::ErrorCode::Internal)),
117 }
118 }
119
120 /// Render one created resource as an ingest result line.
121 ///
122 /// A *document* per line — `{"data":{…}}` — where [`line`](Self::line)
123 /// writes a bare resource object. The difference is deliberate: an
124 /// export is a row stream, but an ingest result line sits next to error
125 /// lines that are themselves documents, so a client parses every line
126 /// the same way and looks for `data` or `errors`.
127 pub fn result_line(resource: &crate::document::ResourceObject) -> Vec<u8> {
128 match serde_json::to_vec(&Document::single(resource.clone())) {
129 Ok(mut line) => {
130 line.push(b'\n');
131 line
132 }
133 Err(_) => Self::error_line(&JsonApiError::new(crate::ErrorCode::Internal)),
134 }
135 }
136
137 /// Render an error as one line's result, stamped with its line number.
138 ///
139 /// The line number is what makes a per-line failure actionable: a client
140 /// that sent a hundred thousand rows needs to know *which* ones did not
141 /// land, so it can retry exactly those. See
142 /// [`LINE_MEMBER`](crate::jsonl::LINE_MEMBER).
143 pub fn error_line_at(error: &JsonApiError, line: usize) -> Vec<u8> {
144 let mut object = error.to_object();
145
146 let meta = object.meta.get_or_insert_with(Default::default);
147 meta.insert(
148 crate::jsonl::LINE_MEMBER.to_string(),
149 serde_json::Value::from(line),
150 );
151
152 let document = Document::errors(vec![object]);
153 let mut rendered = serde_json::to_vec(&document).unwrap_or_else(|_| {
154 br#"{"errors":[{"status":"500","code":"internal","title":"Internal server error"}]}"#
155 .to_vec()
156 });
157 rendered.push(b'\n');
158 rendered
159 }
160
161 /// Render an error as the stream's final line.
162 ///
163 /// Shaped like a JSON:API error document so a client parsing lines as
164 /// JSON finds the same `errors` member it would in a normal response.
165 pub fn error_line(error: &JsonApiError) -> Vec<u8> {
166 let document = Document::errors(vec![error.to_object()]);
167 let mut line = serde_json::to_vec(&document).unwrap_or_else(|_| {
168 br#"{"errors":[{"status":"500","code":"internal","title":"Internal server error"}]}"#
169 .to_vec()
170 });
171 line.push(b'\n');
172 line
173 }
174}
175
176#[cfg(feature = "streaming")]
177impl IntoResponse for Streamed {
178 fn into_response(self) -> Response {
179 let body = axum::body::Body::from_stream(self.0);
180
181 (
182 StatusCode::OK,
183 [
184 (header::CONTENT_TYPE, crate::jsonl::MEDIA_TYPE),
185 // Two representations live at this URL, so a cache must key
186 // on which one was asked for.
187 (header::VARY, "Accept"),
188 ],
189 body,
190 )
191 .into_response()
192 }
193}
194
195/// Raw bytes, with their own media type — a file, not a document.
196///
197/// The one response in this crate that is deliberately *not*
198/// `application/vnd.api+json`. A resource's bytes are not a JSON:API
199/// document and wrapping them in one would mean base64 in an attribute,
200/// which doubles the transfer and cannot be streamed or ranged.
201///
202/// The conventional shape, and the one [`CONTENT`](crate::api!) routes: the
203/// resource stays a JSON document carrying metadata at `/docs/{id}`, and its
204/// bytes live beside it at `/docs/{id}/content`.
205///
206/// ```
207/// use ash_jsonapi::response::Download;
208///
209/// let file = Download::new(vec![0x89, b'P', b'N', b'G'], "image/png")
210/// .filename("diagram.png");
211/// # let _ = file;
212/// ```
213pub struct Download {
214 bytes: Vec<u8>,
215 content_type: String,
216 filename: Option<String>,
217 inline: bool,
218}
219
220impl Download {
221 /// Bytes, and the media type to serve them as.
222 ///
223 /// The media type is the caller's: this crate does not sniff content,
224 /// because guessing a type from bytes is how an uploaded HTML file comes
225 /// back as `text/html` and runs as the origin.
226 pub fn new(bytes: impl Into<Vec<u8>>, content_type: impl Into<String>) -> Self {
227 Self {
228 bytes: bytes.into(),
229 content_type: content_type.into(),
230 filename: None,
231 inline: false,
232 }
233 }
234
235 /// Suggest a filename, and ask the browser to save rather than render.
236 ///
237 /// Sets `Content-Disposition: attachment`. The name is escaped — see
238 /// [`disposition`].
239 #[must_use]
240 pub fn filename(mut self, filename: impl Into<String>) -> Self {
241 self.filename = Some(filename.into());
242 self
243 }
244
245 /// Render in the browser rather than downloading, keeping any filename.
246 ///
247 /// `Content-Disposition: inline` — for an image or a PDF a user expects
248 /// to see rather than save. Off by default: `attachment` is the safer
249 /// choice, since it does not invite the browser to interpret the bytes.
250 #[must_use]
251 pub fn inline(mut self) -> Self {
252 self.inline = true;
253 self
254 }
255}
256
257impl IntoResponse for Download {
258 fn into_response(self) -> Response {
259 let mut headers = axum::http::HeaderMap::new();
260
261 // A media type that will not parse as a header is the caller's bug,
262 // not the client's; fall back to the neutral type rather than
263 // sending a malformed header or panicking in a handler.
264 let content_type = self
265 .content_type
266 .parse()
267 .unwrap_or_else(|_| axum::http::HeaderValue::from_static("application/octet-stream"));
268 headers.insert(header::CONTENT_TYPE, content_type);
269
270 // Always sent, filename or not: it is what stops a browser from
271 // interpreting an uploaded file as active content in the origin.
272 if let std::result::Result::Ok(value) =
273 disposition(self.inline, self.filename.as_deref()).parse()
274 {
275 headers.insert(header::CONTENT_DISPOSITION, value);
276 }
277
278 // Uploaded bytes are attacker-controlled, so the declared type must
279 // be the only one considered — without this a browser may sniff an
280 // `image/png` that is really HTML and run it.
281 headers.insert(
282 header::X_CONTENT_TYPE_OPTIONS,
283 axum::http::HeaderValue::from_static("nosniff"),
284 );
285
286 (StatusCode::OK, headers, self.bytes).into_response()
287 }
288}
289
290/// Build a `Content-Disposition` value, safely.
291///
292/// A filename reaches this from an upload, so it is attacker-controlled and
293/// cannot be interpolated as-is: a quote or a newline would end the header
294/// value and start another. Two defences, per [RFC 6266]:
295///
296/// - the quoted form carries an ASCII-only fallback, with `"` and `\`
297/// escaped and control characters dropped;
298/// - `filename*` carries the real name, percent-encoded as UTF-8, which is
299/// what a modern browser reads.
300///
301/// [RFC 6266]: https://www.rfc-editor.org/rfc/rfc6266#section-4.3
302pub fn disposition(inline: bool, filename: Option<&str>) -> String {
303 let kind = if inline { "inline" } else { "attachment" };
304
305 let Some(name) = filename else {
306 return kind.to_string();
307 };
308
309 // The ASCII fallback: printable ASCII only, quotes and backslashes
310 // escaped. Anything else becomes `_` rather than being dropped, so the
311 // name keeps its shape.
312 let mut ascii = String::with_capacity(name.len());
313 for ch in name.chars() {
314 match ch {
315 '"' | '\\' => {
316 ascii.push('\\');
317 ascii.push(ch);
318 }
319 c if c.is_ascii_graphic() || c == ' ' => ascii.push(c),
320 _ => ascii.push('_'),
321 }
322 }
323
324 // `filename*` in RFC 5987 form: UTF-8, percent-encoded, attribute
325 // characters passed through.
326 let mut encoded = String::with_capacity(name.len());
327 for byte in name.as_bytes() {
328 match byte {
329 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
330 encoded.push(*byte as char);
331 }
332 other => encoded.push_str(&format!("%{other:02X}")),
333 }
334 }
335
336 format!("{kind}; filename=\"{ascii}\"; filename*=UTF-8''{encoded}")
337}
338
339/// `204 No Content` — a successful delete.
340pub struct NoContent;
341
342impl IntoResponse for Fetched {
343 fn into_response(self) -> Response {
344 json_api(StatusCode::OK, &self.0, None)
345 }
346}
347
348impl IntoResponse for Created {
349 fn into_response(self) -> Response {
350 let location = self.0.links.as_ref().and_then(|l| l.this.clone());
351
352 json_api(StatusCode::CREATED, &Document::single(self.0), location)
353 }
354}
355
356impl IntoResponse for NoContent {
357 fn into_response(self) -> Response {
358 (StatusCode::NO_CONTENT, [(header::CONTENT_TYPE, MEDIA_TYPE)]).into_response()
359 }
360}
361
362/// Several errors in one response.
363///
364/// JSON:API allows a document to carry more than one error, and a validation
365/// run usually produces several — a client fixing a form wants the whole list,
366/// not the first problem. The status is the most severe of them.
367///
368/// `Debug` so a test can `.unwrap()` a `Result<_, Errors>`; the derive is on
369/// [`JsonApiError`] already, and a handler's error type being un-debuggable
370/// makes every test of one awkward for no benefit.
371#[derive(Debug)]
372pub struct Errors(pub Vec<JsonApiError>);
373
374impl From<Vec<JsonApiError>> for Errors {
375 fn from(errors: Vec<JsonApiError>) -> Self {
376 Self(errors)
377 }
378}
379
380impl From<JsonApiError> for Errors {
381 fn from(error: JsonApiError) -> Self {
382 Self(vec![error])
383 }
384}
385
386impl IntoResponse for Errors {
387 fn into_response(self) -> Response {
388 // The most severe status wins: a 500 among 422s is still a 500.
389 let status = self
390 .0
391 .iter()
392 .map(|error| error.status())
393 .max()
394 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
395
396 let objects = self.0.iter().map(JsonApiError::to_object).collect();
397
398 // Every error in the batch came from the same request, so the first
399 // one's locale is the request's.
400 let document = with_lang(Document::errors(objects), self.0.first());
401 json_api(status, &document, None)
402 }
403}
404
405/// An error is a response: `return err.into()` from any handler.
406impl IntoResponse for JsonApiError {
407 fn into_response(self) -> Response {
408 let status = self.status();
409 let document = with_lang(Document::errors(vec![self.to_object()]), Some(&self));
410 json_api(status, &document, None)
411 }
412}
413
414/// Record the request's locale on an error document, when it had one.
415fn with_lang(document: Document, error: Option<&JsonApiError>) -> Document {
416 match error.and_then(JsonApiError::locale) {
417 Some(locale) => document.with_meta("lang", locale.as_str()),
418 None => document,
419 }
420}
421
422fn json_api(status: StatusCode, doc: &Document, location: Option<String>) -> Response {
423 let body = serde_json::to_string(doc).unwrap_or_else(|_| {
424 // A Document is always serializable; this keeps the signature
425 // infallible rather than panicking in a handler.
426 r#"{"errors":[{"status":"500","code":"internal","title":"Internal server error"}]}"#
427 .to_string()
428 });
429
430 let mut response = (status, [(header::CONTENT_TYPE, MEDIA_TYPE)], body).into_response();
431 if let Some(location) = location
432 && let std::result::Result::Ok(value) = location.parse()
433 {
434 response.headers_mut().insert(header::LOCATION, value);
435 }
436 response
437}