1use 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
16pub 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
39fn served(path: &FilePath, body: Vec<u8>) -> Response<Vec<u8>> {
41 with_headers(Response::new(body), served_headers(path.as_str()))
42}
43
44#[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
60fn 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;