Skip to main content

compmd_host/
route.rs

1//! Which file a request names, or why it is refused ([hosting], decision 8): the serving contract's decision, apart
2//! from reading the file, so `respond` here and `@compmd/host`'s (this crate as WebAssembly) decide alike.
3//!
4//! [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
5
6use compmd_pack::{FilePath, Place};
7use http::Method;
8
9use crate::refusal::Refusal;
10
11/// What a request asks for: a file of the frames, a pack's file, or nothing the host serves.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub enum Route {
14    /// The frames' file at this path, in the bundle.
15    Frame(FilePath),
16    /// A pack's file, in the bundle or the store.
17    Pack(Place),
18    /// Refused, with why.
19    Refused(Refusal),
20}
21
22/// What a `method` request for `path` asks for, from a bundle whose frames' hash is `hash`.
23///
24/// The paths it answers are `/frames/<hash>/<path>` and `/packs/<place>`, where a path is a [`FilePath`], which can't
25/// leave its folder; another method than `GET` is refused with `405`, anything else with `404`.
26///
27/// ```
28/// use compmd_host::{route, Refusal, Route};
29///
30/// let route = route(&http::Method::GET, "/frames/1df336e75685de8c/strict.html", "1df336e75685de8c");
31/// assert!(matches!(route, Route::Frame(path) if path.as_str() == "strict.html"));
32/// let refused = compmd_host::route(&http::Method::GET, "/frames/1df336e75685de8c/../x", "1df336e75685de8c");
33/// assert_eq!(refused, Route::Refused(Refusal::NOT_SERVED));
34/// ```
35#[must_use]
36pub fn route(method: &Method, path: &str, hash: &str) -> Route {
37    if method != Method::GET {
38        return Route::Refused(Refusal::ONLY_GET);
39    }
40    file_of(path, hash).unwrap_or(Route::Refused(Refusal::NOT_SERVED))
41}
42
43/// The file `path` names, if it names one.
44fn file_of(path: &str, hash: &str) -> Option<Route> {
45    let parts: Vec<&str> = path.strip_prefix('/')?.split('/').collect();
46    match parts.as_slice() {
47        ["frames", given, file @ ..] if *given == hash => {
48            FilePath::new(file.join("/")).ok().map(Route::Frame)
49        }
50        ["packs", place @ ..] => Place::from_parts(place).map(Route::Pack),
51        _ => None,
52    }
53}