use compmd_pack::FilePath;
use http::header::HeaderValue;
use http::{Request, Response};
use crate::bundle::Bundle;
use crate::headers::{refusal_headers, served_headers};
use crate::refusal::Refusal;
use crate::route::{Route, route};
use crate::store::Store;
pub fn respond<B>(bundle: &Bundle, store: &dyn Store, request: &Request<B>) -> Response<Vec<u8>> {
let _span = tracing::debug_span!("compmd_host::respond", path = request.uri().path()).entered();
let hash = bundle.manifest().frames.hash.as_str();
let found = match route(request.method(), request.uri().path(), hash) {
Route::Frame(path) => bundle.frame_file(&path).map(|body| (body, path)),
Route::Pack(place) => bundle
.pack_file_or(store, &place)
.map(|body| (body, place.path)),
Route::Refused(refusal) => return refused(refusal),
};
let response = found.map_or_else(
|| refused(Refusal::NOT_SERVED),
|(body, path)| served(&path, body),
);
tracing::debug!(status = response.status().as_u16(), "answered");
response
}
fn served(path: &FilePath, body: Vec<u8>) -> Response<Vec<u8>> {
with_headers(Response::new(body), served_headers(path.as_str()))
}
#[must_use]
pub fn refused(refusal: Refusal) -> Response<Vec<u8>> {
let mut response = Response::new(refusal.why.as_bytes().to_vec());
*response.status_mut() = refusal.status;
with_headers(response, refusal_headers())
}
fn with_headers(
mut response: Response<Vec<u8>>,
headers: impl IntoIterator<Item = (&'static str, &'static str)>,
) -> Response<Vec<u8>> {
for (name, value) in headers {
response
.headers_mut()
.insert(name, HeaderValue::from_static(value));
}
response
}
#[cfg(test)]
mod tests;