1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use crate::{
    error::{BundleError, MrBundleResult},
    location::Location,
    manifest::Manifest,
    resource::ResourceBytes,
};
use holochain_util::ffs;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{
    borrow::Cow,
    collections::{HashMap, HashSet},
    path::{Path, PathBuf},
};

pub type ResourceMap = HashMap<PathBuf, ResourceBytes>;

/// A Manifest bundled together, optionally, with the Resources that it describes.
/// This is meant to be serialized for standalone distribution, and deserialized
/// by the receiver.
///
/// The manifest may describe locations of resources not included in the Bundle.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Bundle<M>
where
    M: Manifest,
{
    /// The manifest describing the resources that compose this bundle.
    #[serde(bound(deserialize = "M: DeserializeOwned"))]
    manifest: M,

    /// The full or partial resource data. Each entry must correspond to one
    /// of the Bundled Locations specified by the Manifest. Bundled Locations
    /// are always relative paths (relative to the root_dir).
    resources: ResourceMap,

    /// Since the Manifest may contain local paths referencing unbundled files,
    /// on the local filesystem, we must have an absolute path at runtime for
    /// normalizing those locations.
    ///
    /// Passing None is a runtime assertion that the manifest contains only
    /// absolute local paths. If this assertion fails,
    /// **resource resolution will panic!**
    //
    // TODO: Represent this with types more solidly, perhaps breaking this
    //       struct into two versions for each case.
    #[serde(skip)]
    root_dir: Option<PathBuf>,
}

impl<M> Bundle<M>
where
    M: Manifest,
{
    /// Creates a bundle containing a manifest and a collection of resources to
    /// be bundled together with the manifest.
    ///
    /// The paths paired with each resource must correspond to the set of
    /// `Location::Bundle`s specified in the `Manifest::location()`, or else
    /// this is not a valid bundle.
    ///
    /// A base directory must also be supplied so that relative paths can be
    /// resolved into absolute ones.
    pub fn new<R: IntoIterator<Item = (PathBuf, ResourceBytes)>>(
        manifest: M,
        resources: R,
        root_dir: PathBuf,
    ) -> MrBundleResult<Self> {
        Self::from_parts(manifest, resources, Some(root_dir))
    }

    /// Create a bundle, asserting that all paths in the Manifest are absolute.
    pub fn new_unchecked<R: IntoIterator<Item = (PathBuf, ResourceBytes)>>(
        manifest: M,
        resources: R,
    ) -> MrBundleResult<Self> {
        Self::from_parts(manifest, resources, None)
    }

    fn from_parts<R: IntoIterator<Item = (PathBuf, ResourceBytes)>>(
        manifest: M,
        resources: R,
        root_dir: Option<PathBuf>,
    ) -> MrBundleResult<Self> {
        let resources: ResourceMap = resources.into_iter().collect();
        let manifest_paths: HashSet<_> = manifest
            .locations()
            .into_iter()
            .filter_map(|loc| match loc {
                Location::Bundled(path) => Some(path),
                _ => None,
            })
            .collect();

        // Validate that each resource path is contained in the manifest
        for (resource_path, _) in resources.iter() {
            if !manifest_paths.contains(resource_path) {
                return Err(BundleError::BundledPathNotInManifest(resource_path.clone()).into());
            }
        }

        let resources = resources.into_iter().collect();
        Ok(Self {
            manifest,
            resources,
            root_dir,
        })
    }

    /// Accessor for the Manifest
    pub fn manifest(&self) -> &M {
        &self.manifest
    }

    /// Return a new Bundle with an updated manifest, subject to the same
    /// validation constraints as creating a new Bundle from scratch.
    pub fn update_manifest(self, manifest: M) -> MrBundleResult<Self> {
        Self::from_parts(manifest, self.resources, self.root_dir)
    }

    /// Load a Bundle into memory from a file
    pub async fn read_from_file(path: &Path) -> MrBundleResult<Self> {
        Ok(Self::decode(&ffs::read(path).await?)?)
    }

    /// Write a Bundle to a file
    pub async fn write_to_file(&self, path: &Path) -> MrBundleResult<()> {
        Ok(ffs::write(path, &self.encode()?).await?)
    }

    /// Retrieve the bytes for a resource at a Location, downloading it if
    /// necessary
    pub async fn resolve(&self, location: &Location) -> MrBundleResult<Cow<'_, ResourceBytes>> {
        let bytes = match &location.normalize(self.root_dir.as_ref())? {
            Location::Bundled(path) => Cow::Borrowed(
                self.resources
                    .get(path)
                    .ok_or_else(|| BundleError::BundledResourceMissing(path.clone()))?,
            ),
            Location::Path(path) => Cow::Owned(crate::location::resolve_local(path).await?),
            Location::Url(url) => Cow::Owned(crate::location::resolve_remote(url).await?),
        };
        Ok(bytes)
    }

    /// Return the full set of resources specified by this bundle's manifest.
    /// References to bundled resources can be returned directly, while all
    /// others will be fetched from the filesystem or the network.
    pub async fn resolve_all(&self) -> MrBundleResult<HashMap<Location, Cow<'_, ResourceBytes>>> {
        futures::future::join_all(
            self.manifest.locations().into_iter().map(|loc| async move {
                MrBundleResult::Ok((loc.clone(), self.resolve(&loc).await?))
            }),
        )
        .await
        .into_iter()
        .collect::<MrBundleResult<HashMap<Location, Cow<'_, ResourceBytes>>>>()
    }

    /// Resolve all resources, but with fully owned references
    pub async fn resolve_all_cloned(&self) -> MrBundleResult<HashMap<Location, ResourceBytes>> {
        Ok(self
            .resolve_all()
            .await?
            .into_iter()
            .map(|(k, v)| (k, v.into_owned()))
            .collect())
    }

    /// Access the map of resources included in this bundle
    /// Bundled resources are also accessible via `resolve` or `resolve_all`,
    /// but using this method prevents a Clone
    pub fn bundled_resources(&self) -> &ResourceMap {
        &self.resources
    }

    /// An arbitrary and opaque encoding of the bundle data into a byte array
    pub fn encode(&self) -> MrBundleResult<Vec<u8>> {
        crate::encode(self)
    }

    /// Decode bytes produced by [`encode`](Bundle::encode)
    pub fn decode(bytes: &[u8]) -> MrBundleResult<Self> {
        crate::decode(bytes)
    }

    /// Given that the Manifest is located at the given absolute `path`, find
    /// the absolute root directory for the "unpacked" Bundle directory.
    /// Useful when "imploding" a directory into a bundle to determine the
    /// default location of the generated Bundle file.
    ///
    /// This will only be different than the Manifest path itself if the
    /// Manifest::path impl specifies a nested path.
    ///
    /// Will return None if the `path` does not actually end with the
    /// manifest relative path, meaning that either the manifest file is
    /// misplaced within the unpacked directory, or an incorrect path was
    /// supplied.
    #[cfg(feature = "packing")]
    pub fn find_root_dir(&self, path: &Path) -> MrBundleResult<PathBuf> {
        crate::util::prune_path(path.into(), M::path()).map_err(Into::into)
    }
}

#[cfg(test)]
mod tests {
    use crate::error::MrBundleError;

    use super::*;

    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
    struct TestManifest(Vec<Location>);

    impl Manifest for TestManifest {
        fn locations(&self) -> Vec<Location> {
            self.0.clone()
        }

        #[cfg(feature = "packing")]
        fn path() -> PathBuf {
            unimplemented!()
        }

        #[cfg(feature = "packing")]
        fn bundle_extension() -> &'static str {
            unimplemented!()
        }
    }

    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
    struct Thing(u32);

    #[tokio::test]
    async fn bundle_validation() {
        let manifest = TestManifest(vec![
            Location::Bundled("1.thing".into()),
            Location::Bundled("2.thing".into()),
        ]);
        assert!(Bundle::new_unchecked(manifest.clone(), vec![("1.thing".into(), vec![1])]).is_ok());

        matches::assert_matches!(
            Bundle::new_unchecked(manifest, vec![("3.thing".into(), vec![3])]),
            Err(MrBundleError::BundleError(BundleError::BundledPathNotInManifest(path))) if path == PathBuf::from("3.thing")
        );
    }
}