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 hash = bundle.manifest().frames.hash.as_str();
23    let found = match route(request.method(), request.uri().path(), hash) {
24        Route::Frame(path) => bundle.frame_file(&path).map(|body| (body, path)),
25        Route::Pack(place) => bundle
26            .pack_file(&place)
27            .or_else(|| store.file(&place))
28            .map(|body| (body, place.path)),
29        Route::Refused(refusal) => return refused(refusal),
30    };
31    found.map_or_else(
32        || refused(Refusal::NOT_SERVED),
33        |(body, path)| served(&path, body),
34    )
35}
36
37/// `body`, the file at `path`, with its type and the headers.
38fn served(path: &FilePath, body: Vec<u8>) -> Response<Vec<u8>> {
39    with_headers(Response::new(body), served_headers(path.as_str()))
40}
41
42/// A refusal, saying why in plain text, to any origin.
43fn refused(refusal: Refusal) -> Response<Vec<u8>> {
44    let mut response = Response::new(refusal.why.as_bytes().to_vec());
45    *response.status_mut() = refusal.status;
46    with_headers(response, refusal_headers())
47}
48
49/// `response` with `headers`.
50fn with_headers(
51    mut response: Response<Vec<u8>>,
52    headers: impl IntoIterator<Item = (&'static str, &'static str)>,
53) -> Response<Vec<u8>> {
54    for (name, value) in headers {
55        response
56            .headers_mut()
57            .insert(name, HeaderValue::from_static(value));
58    }
59    response
60}
61
62#[cfg(test)]
63mod tests;