Skip to main content

compmd_host/
bundle.rs

1//! A bundle: its manifest and its files ([hosting], decision 3).
2//!
3//! [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
4
5use std::collections::BTreeMap;
6use std::path::Path;
7
8use compmd_pack::{FilePath, Place};
9
10use crate::bundle_error::BundleError;
11use crate::files::Files;
12use crate::manifest::Manifest;
13use crate::store::Store;
14
15/// The manifest's path in a bundle.
16pub const MANIFEST: &str = "manifest.json";
17
18/// A bundle the host serves.
19#[derive(Clone, Debug, PartialEq)]
20pub struct Bundle {
21    manifest: Manifest,
22    files: Files,
23}
24
25impl Bundle {
26    /// The bundle embedded in a binary: its files by path, sorted, `manifest.json` among them.
27    ///
28    /// # Errors
29    ///
30    /// [`BundleError`] when it has no manifest, or one that can't be used.
31    pub fn embedded(files: &'static [(&'static str, &'static [u8])]) -> Result<Self, BundleError> {
32        Self::with(Files::Embedded(files))
33    }
34
35    /// The bundle in `folder`.
36    ///
37    /// # Errors
38    ///
39    /// [`BundleError`] when it has no manifest, or one that can't be used.
40    pub fn read(folder: &Path) -> Result<Self, BundleError> {
41        Self::with(Files::Folder(folder.to_path_buf()))
42    }
43
44    /// A bundle of `files`, by path, `manifest.json` among them: for a host's tests.
45    ///
46    /// # Errors
47    ///
48    /// [`BundleError`] when it has no manifest, or one that can't be used.
49    pub fn from_files<P: Into<String>>(
50        files: impl IntoIterator<Item = (P, Vec<u8>)>,
51    ) -> Result<Self, BundleError> {
52        let files: BTreeMap<String, Vec<u8>> = files
53            .into_iter()
54            .map(|(path, bytes)| (path.into(), bytes))
55            .collect();
56        Self::with(Files::Owned(files))
57    }
58
59    fn with(files: Files) -> Result<Self, BundleError> {
60        let text = files.read(MANIFEST).ok_or(BundleError::NoManifest)?;
61        let manifest = Manifest::parse(&String::from_utf8_lossy(&text))?;
62        Ok(Self { manifest, files })
63    }
64
65    /// Its manifest.
66    #[must_use]
67    pub const fn manifest(&self) -> &Manifest {
68        &self.manifest
69    }
70
71    /// The bytes of the frames' file at `path`, inside `frames/<hash>/`.
72    #[must_use]
73    pub fn frame_file(&self, path: &FilePath) -> Option<Vec<u8>> {
74        self.files
75            .read(&format!("frames/{}/{path}", self.manifest.frames.hash))
76    }
77
78    /// The bytes of the pack file at `place`, `packs/<place>`, when the bundle holds that release.
79    #[must_use]
80    pub fn pack_file(&self, place: &Place) -> Option<Vec<u8>> {
81        self.manifest.pack(&place.release)?;
82        self.files.read(&format!("packs/{place}"))
83    }
84
85    /// The bytes of the pack file at `place`: the bundle's, then `store`'s for a release the bundle doesn't hold, as
86    /// the serving contract and the processor's packs both read them.
87    #[must_use]
88    pub fn pack_file_or(&self, store: &dyn Store, place: &Place) -> Option<Vec<u8>> {
89        self.pack_file(place).or_else(|| store.file(place))
90    }
91
92    /// The frames' `base` on `origin` (`compmd://localhost`, `https://frames.example`), as `@compmd/sandbox` takes it.
93    #[must_use]
94    pub fn frames_base(&self, origin: &str) -> String {
95        format!(
96            "{}/frames/{}/",
97            origin.trim_end_matches('/'),
98            self.manifest.frames.hash
99        )
100    }
101}
102
103#[cfg(test)]
104pub(crate) mod tests;