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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use std::{
    any::Any,
    borrow::Cow,
    collections::BTreeMap,
    fmt::Debug,
    fs::File,
    io::{BufReader, Read, Seek},
    path::Path,
    sync::Arc,
};

use bytes::{Buf, Bytes};
use shared_buffer::OwnedBuffer;

use crate::{compat::Volume, v1::WebC, Version};

/// A version-agnostic read-only WEBC container.
///
/// A `Container` provides a high-level interface for reading and manipulating
/// WEBC container files. It supports multiple versions of WEBC container
/// formats and abstracts the underlying differences between them.
#[derive(Debug, Clone)]
pub struct Container {
    imp: Arc<dyn AbstractWebc + Send + Sync>,
}

#[allow(clippy::result_large_err)]
impl Container {
    /// Load a [`Container`] from disk.
    ///
    /// Where possible, this will try to use a memory-mapped implementation
    /// to reduce memory usage.
    pub fn from_disk(path: impl AsRef<Path>) -> Result<Self, ContainerError> {
        let path = path.as_ref();

        #[cfg(feature = "package")]
        if path.is_dir() {
            let wasmer_toml = path.join("wasmer.toml");
            let pkg = crate::wasmer_package::Package::from_manifest(wasmer_toml)?;
            return Ok(Container::new(pkg));
        }

        let mut f = File::open(path).map_err(|error| ContainerError::Open {
            error,
            path: path.to_path_buf(),
        })?;

        if is_tarball(&mut f) {
            let pkg = crate::wasmer_package::Package::from_tarball(BufReader::new(f))
                .map_err(ContainerError::WasmerPackage)?;
            return Ok(Container::new(pkg));
        }

        match crate::detect(&mut f) {
            Ok(Version::V1) => {
                // We need to explicitly use WebcMmap to get a memory-mapped
                // parser
                let options = crate::v1::ParseOptions::default();
                let webc = crate::v1::WebCMmap::from_file(f, &options)?;
                Ok(Container::new(webc))
            }
            Ok(Version::V2) => {
                // Note: OwnedReader::from_file() will automatically try to
                // use a memory-mapped file when possible.
                let webc = crate::v2::read::OwnedReader::from_file(f)?;
                Ok(Container::new(webc))
            }
            Ok(other) => {
                // fall back to the allocating generic version
                let mut buffer = Vec::new();
                f.rewind()
                    .and_then(|_| f.read_to_end(&mut buffer))
                    .map_err(|error| ContainerError::Read {
                        path: path.to_path_buf(),
                        error,
                    })?;

                Container::from_bytes_and_version(buffer.into(), other)
            }
            Err(e) => Err(ContainerError::Detect(e)),
        }
    }

    /// Load a [`Container`] from bytes in memory.
    pub fn from_bytes(bytes: impl Into<Bytes>) -> Result<Self, ContainerError> {
        let bytes: Bytes = bytes.into();

        if is_tarball(std::io::Cursor::new(&bytes)) {
            let pkg = crate::wasmer_package::Package::from_tarball(bytes.reader())
                .map_err(ContainerError::WasmerPackage)?;
            return Ok(Container::new(pkg));
        }

        let version = crate::detect(bytes.as_ref())?;
        Container::from_bytes_and_version(bytes, version)
    }

    fn new(repr: impl AbstractWebc + Send + Sync + 'static) -> Self {
        Container {
            imp: Arc::new(repr),
        }
    }

    fn from_bytes_and_version(bytes: Bytes, version: Version) -> Result<Self, ContainerError> {
        match version {
            Version::V1 => {
                let options = crate::v1::ParseOptions::default();
                let webc = crate::v1::WebCOwned::parse(bytes, &options)?;
                Ok(Container::new(webc))
            }
            Version::V2 => {
                let reader = crate::v2::read::OwnedReader::parse(bytes)?;
                Ok(Container::new(reader))
            }
            other => Err(ContainerError::UnsupportedVersion(other)),
        }
    }

    /// Get the [`Container`]'s manifest.
    pub fn manifest(&self) -> &crate::metadata::Manifest {
        self.imp.manifest()
    }

    /// Get all atoms stored in the container as a map.
    pub fn atoms(&self) -> BTreeMap<String, OwnedBuffer> {
        let mut atoms = BTreeMap::new();

        for name in self.imp.atom_names() {
            if let Some(atom) = self.imp.get_atom(&name) {
                atoms.insert(name.into_owned(), atom);
            }
        }

        atoms
    }

    /// Get an atom with the given name.
    ///
    /// Returns `None` if the atom does not exist in the container.
    ///
    /// This operation is pretty cheap, typically just a dictionary lookup
    /// followed by reference count bump and some index math.
    pub fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
        self.imp.get_atom(name)
    }

    /// Get all volumes stored in the container.
    pub fn volumes(&self) -> BTreeMap<String, Volume> {
        let mut volumes = BTreeMap::new();

        for name in self.imp.volume_names() {
            if let Some(atom) = self.imp.get_volume(&name) {
                volumes.insert(name.into_owned(), atom);
            }
        }

        volumes
    }

    /// Get a volume with the given name.
    ///
    /// Returns `None` if the volume does not exist in the container.
    pub fn get_volume(&self, name: &str) -> Option<Volume> {
        self.imp.get_volume(name)
    }

    /// Downcast the [`Container`] a concrete implementation.
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: 'static,
    {
        self.as_any().downcast_ref()
    }

    /// Downcast the [`Container`] a concrete implementation, returning the
    /// original [`Container`] if the cast fails.
    pub fn downcast<T>(self) -> Result<Arc<T>, Self>
    where
        T: 'static,
    {
        if self.as_any().is::<T>() {
            // Safety: We've just checked that the type matches up.
            unsafe { Ok(Arc::from_raw(Arc::into_raw(self.imp).cast())) }
        } else {
            Err(self)
        }
    }
}

trait AbstractWebc: AsAny + Debug {
    fn manifest(&self) -> &crate::metadata::Manifest;

    fn atom_names(&self) -> Vec<Cow<'_, str>>;
    fn get_atom(&self, name: &str) -> Option<OwnedBuffer>;
    fn volume_names(&self) -> Vec<Cow<'_, str>>;
    fn get_volume(&self, name: &str) -> Option<Volume>;
}

impl AbstractWebc for crate::v2::read::OwnedReader {
    fn manifest(&self) -> &crate::metadata::Manifest {
        self.manifest()
    }

    fn atom_names(&self) -> Vec<Cow<'_, str>> {
        self.atom_names().map(Cow::Borrowed).collect()
    }

    fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
        self.get_atom(name).cloned().map(OwnedBuffer::from)
    }

    fn volume_names(&self) -> Vec<Cow<'_, str>> {
        crate::v2::read::OwnedReader::volume_names(self)
            .map(Cow::Borrowed)
            .collect()
    }

    fn get_volume(&self, name: &str) -> Option<Volume> {
        self.get_volume(name).ok().map(Volume::new)
    }
}

impl From<crate::v2::read::OwnedReader> for Container {
    fn from(value: crate::v2::read::OwnedReader) -> Self {
        Container::new(value)
    }
}

impl AbstractWebc for crate::v1::WebCMmap {
    fn manifest(&self) -> &crate::metadata::Manifest {
        &self.manifest
    }

    fn atom_names(&self) -> Vec<Cow<'_, str>> {
        self.get_all_atoms().into_keys().map(Cow::Owned).collect()
    }

    fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
        let atoms = self.get_all_atoms();
        let atom = atoms.get(name)?;
        let range = crate::utils::subslice_offsets(&self.buffer, atom);
        Some(self.buffer.slice(range))
    }

    fn volume_names(&self) -> Vec<Cow<'_, str>> {
        self.volumes
            .keys()
            .map(|s| Cow::Borrowed(s.as_str()))
            .collect()
    }

    fn get_volume(&self, name: &str) -> Option<Volume> {
        let package_name = self.get_package_name();
        let volume = WebC::get_volume(self, &package_name, name)?;
        let buffer = self.buffer.clone();

        Some(Volume::new(crate::volume::VolumeV1 {
            volume: volume.clone(),
            buffer,
        }))
    }
}

impl From<crate::v1::WebCMmap> for Container {
    fn from(value: crate::v1::WebCMmap) -> Self {
        Container::new(value)
    }
}

impl AbstractWebc for crate::v1::WebCOwned {
    fn manifest(&self) -> &crate::metadata::Manifest {
        &self.manifest
    }

    fn atom_names(&self) -> Vec<Cow<'_, str>> {
        self.get_all_atoms().into_keys().map(Cow::Owned).collect()
    }

    fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
        let atoms = self.get_all_atoms();
        let atom = atoms.get(name)?;
        let range = crate::utils::subslice_offsets(&self.backing_data, atom);
        Some(self.backing_data.slice(range).into())
    }

    fn volume_names(&self) -> Vec<Cow<'_, str>> {
        self.volumes
            .keys()
            .map(|s| Cow::Borrowed(s.as_str()))
            .collect()
    }

    fn get_volume(&self, name: &str) -> Option<Volume> {
        let package_name = self.get_package_name();
        let volume = WebC::get_volume(self, &package_name, name)?.clone();
        let buffer = self.backing_data.clone().into();

        Some(Volume::new(crate::volume::VolumeV1 { buffer, volume }))
    }
}

impl From<crate::v1::WebCOwned> for Container {
    fn from(value: crate::v1::WebCOwned) -> Self {
        Container::new(value)
    }
}

impl AbstractWebc for crate::wasmer_package::Package {
    fn manifest(&self) -> &crate::metadata::Manifest {
        self.manifest()
    }

    fn atom_names(&self) -> Vec<Cow<'_, str>> {
        self.atoms()
            .keys()
            .map(|s| Cow::Borrowed(s.as_str()))
            .collect()
    }

    fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
        self.atoms().get(name).cloned()
    }

    fn volume_names(&self) -> Vec<Cow<'_, str>> {
        self.volume_names()
    }

    fn get_volume(&self, name: &str) -> Option<Volume> {
        self.get_volume(name).map(Volume::new)
    }
}

impl From<crate::wasmer_package::Package> for Container {
    fn from(value: crate::wasmer_package::Package) -> Self {
        Container::new(value)
    }
}

trait AsAny {
    fn as_any(&self) -> &(dyn Any + 'static);
}

impl<T> AsAny for T
where
    T: Any,
{
    fn as_any(&self) -> &(dyn Any + 'static) {
        self
    }
}

/// Various errors that may occur during [`Container`] operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ContainerError {
    /// Unable to detect the WEBC version.
    #[error("Unable to detect the WEBC version")]
    Detect(#[from] crate::DetectError),
    /// An unsupported WEBC version was found.
    #[error("Unsupported WEBC version, {_0}")]
    UnsupportedVersion(crate::Version),
    /// An error occurred while parsing a v1 WEBC file.
    #[error(transparent)]
    V1(#[from] crate::v1::Error),
    /// An error occurred while parsing a v2 WEBC file.
    #[error(transparent)]
    V2Owned(#[from] crate::v2::read::OwnedReaderError),
    /// an error occurred while loading a Wasmer package from disk.
    #[error(transparent)]
    WasmerPackage(#[from] crate::wasmer_package::WasmerPackageError),
    /// Unable to open a file.
    #[error("Unable to open \"{}\"", path.display())]
    Open {
        /// The file's path.
        path: std::path::PathBuf,
        /// The underlying error.
        #[source]
        error: std::io::Error,
    },
    /// Unable to read a file's contents into memory.
    #[error("Unable to read \"{}\"", path.display())]
    Read {
        /// The file's path.
        path: std::path::PathBuf,
        /// The underlying error.
        #[source]
        error: std::io::Error,
    },
}

/// Check if something looks like a `*.tar.gz` file.
fn is_tarball(mut file: impl Read + Seek) -> bool {
    /// Magic bytes for a `*.tar.gz` file according to
    /// [Wikipedia](https://en.wikipedia.org/wiki/List_of_file_signatures).
    const TAR_GZ_MAGIC_BYTES: [u8; 2] = [0x1F, 0x8B];

    let mut buffer = [0_u8; 2];
    let result = match file.read_exact(&mut buffer) {
        Ok(_) => buffer == TAR_GZ_MAGIC_BYTES,
        Err(_) => false,
    };

    let _ = file.rewind();

    result
}