Skip to main content

compmd_host/
respond.rs

1//! The serving contract ([hosting], decision 8): a bundle's frames and the packs the bundle or the store holds, with
2//! the headers that sandbox them, and a refusal, saying why, for anything else.
3//!
4//! [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
5
6use compmd_pack::FilePath;
7use http::header::HeaderValue;
8use http::{Request, Response};
9
10use crate::bundle::Bundle;
11use crate::headers::{refusal_headers, served_headers};
12use crate::refusal::Refusal;
13use crate::route::{Route, route};
14use crate::store::Store;
15
16/// The answer to `request`: the frames' file or pack file it names, from the bundle or, for a pack the bundle doesn't
17/// hold, from `store`; a `405` for another method than `GET`; a `404` for anything else. Each refusal says why.
18///
19/// The paths it answers are `/frames/<hash>/<path>`, with the bundle's hash, and `/packs/<place>`, where a path is a
20/// [`FilePath`], which can't leave its folder ([`route`]).
21pub fn respond<B>(bundle: &Bundle, store: &dyn Store, request: &Request<B>) -> Response<Vec<u8>> {
22    let _span = tracing::debug_span!("compmd_host::respond", path = request.uri().path()).entered();
23    let hash = bundle.manifest().frames.hash.as_str();
24    let found = match route(request.method(), request.uri().path(), hash) {
25        Route::Frame(path) => bundle.frame_file(&path).map(|body| (body, path)),
26        Route::Pack(place) => bundle
27            .pack_file_or(store, &place)
28            .map(|body| (body, place.path)),
29        Route::Refused(refusal) => return refused(refusal),
30    };
31    let response = found.map_or_else(
32        || refused(Refusal::NOT_SERVED),
33        |(body, path)| served(&path, body),
34    );
35    tracing::debug!(status = response.status().as_u16(), "answered");
36    response
37}
38
39/// `body`, the file at `path`, with its type and the headers.
40fn served(path: &FilePath, body: Vec<u8>) -> Response<Vec<u8>> {
41    with_headers(Response::new(body), served_headers(path.as_str()))
42}
43
44/// The answer refusing a request for `refusal`'s reason: its status, why in plain text, and the contract's headers, so
45/// any origin reads it. An adapter's own refusal, such as having no bundle, is answered with it too.
46///
47/// ```
48/// use compmd_host::{Refusal, refused};
49///
50/// let response = refused(Refusal { status: http::StatusCode::NOT_FOUND, why: "this app has no bundle" });
51/// assert_eq!(response.headers()["access-control-allow-origin"], "*");
52/// ```
53#[must_use]
54pub fn refused(refusal: Refusal) -> Response<Vec<u8>> {
55    let mut response = Response::new(refusal.why.as_bytes().to_vec());
56    *response.status_mut() = refusal.status;
57    with_headers(response, refusal_headers())
58}
59
60/// `response` with `headers`.
61fn with_headers(
62    mut response: Response<Vec<u8>>,
63    headers: impl IntoIterator<Item = (&'static str, &'static str)>,
64) -> Response<Vec<u8>> {
65    for (name, value) in headers {
66        response
67            .headers_mut()
68            .insert(name, HeaderValue::from_static(value));
69    }
70    response
71}
72
73#[cfg(test)]
74mod tests;