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
mod bytes;

pub use crate::bytes::Base64Bytes;
use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::path::Path;

/// A collection of files, either loaded from the compiled binary or the filesystem at runtime.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MiniCdn {
    Embedded(EmbeddedMiniCdn),
    Filesystem(FilesystemMiniCdn),
}

/// A collection of files loaded from the compiled binary.
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EmbeddedMiniCdn {
    files: HashMap<Cow<'static, str>, MiniCdnFile>,
}

/// A collection of files loaded from the filesystem at runtime.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FilesystemMiniCdn {
    root_path: Cow<'static, str>,
}

impl Default for MiniCdn {
    fn default() -> Self {
        Self::Embedded(EmbeddedMiniCdn::default())
    }
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MiniCdnFile {
    /// For ETAG-based caching.
    #[cfg(feature = "etag")]
    pub etag: bytestring::ByteString,
    /// For last modified caching.
    #[cfg(feature = "last_modified")]
    pub last_modified: bytestring::ByteString,
    /// MIME type.
    #[cfg(feature = "mime")]
    pub mime: bytestring::ByteString,
    /// Raw bytes of file.
    pub contents: Base64Bytes,
    /// Contents compressed as Brotli.
    #[cfg(feature = "gzip")]
    pub contents_brotli: Option<Base64Bytes>,
    /// Contents compressed as GZIP.
    #[cfg(feature = "brotli")]
    pub contents_gzip: Option<Base64Bytes>,
    /// Contents compressed as WebP (only applies to images).
    #[cfg(feature = "webp")]
    pub contents_webp: Option<Base64Bytes>,
}

impl EmbeddedMiniCdn {
    /// Embeds the files into the binary at runtime, without compressing. The path is evaluated
    /// at runtime.
    pub fn new(root_path: &str) -> Self {
        FilesystemMiniCdn::new(Cow::Owned(root_path.to_string()))
            .borrow()
            .into()
    }

    /// Embeds the files into the binary at runtime. The path and compression are evaluated at
    /// runtime. This may incur significant runtime latency.
    pub fn new_compressed(root_path: &str) -> Self {
        let mut ret = Self::default();
        get_paths(root_path).for_each(|(absolute_path, relative_path)| {
            #[cfg(feature = "last_modified")]
            let last_modified = last_modified(&absolute_path);
            let contents = std::fs::read(&absolute_path).expect(&relative_path);

            #[cfg(feature = "mime")]
            let mime = mime(&relative_path);
            #[cfg(feature = "etag")]
            let etag = etag(&contents);
            #[cfg(feature = "webp")]
            let contents_webp = webp(&contents, &mime);

            #[cfg(not(feature = "webp"))]
            #[allow(unused)]
            let special = false;

            #[cfg(feature = "webp")]
            #[allow(unused)]
            let special = contents_webp.is_some();

            #[cfg(feature = "gzip")]
            let contents_gzip = if special { None } else { gzip(&contents) };

            #[cfg(feature = "brotli")]
            let contents_brotli = if special { None } else { brotli(&contents) };

            ret.insert(
                Cow::Owned(relative_path),
                MiniCdnFile {
                    #[cfg(feature = "etag")]
                    etag: etag.into(),
                    #[cfg(feature = "last_modified")]
                    last_modified: last_modified.into(),
                    #[cfg(feature = "mime")]
                    mime: mime.into(),
                    contents: contents.into(),
                    #[cfg(feature = "brotli")]
                    contents_brotli: contents_brotli.map(Into::into),
                    #[cfg(feature = "gzip")]
                    contents_gzip: contents_gzip.map(Into::into),
                    #[cfg(feature = "webp")]
                    contents_webp: contents_webp.map(Into::into),
                },
            )
        });
        ret
    }

    /// Gets a previously embedded or inserted file.
    pub fn get(&self, path: &str) -> Option<&MiniCdnFile> {
        self.files.get(path)
    }

    /// Inserts a file.
    pub fn insert(&mut self, path: Cow<'static, str>, file: MiniCdnFile) {
        self.files.insert(path, file);
    }

    /// Removes a file.
    pub fn remove(&mut self, path: &str) {
        self.files.remove(path);
    }

    /// Iterates the previously embedded or inserted files.
    pub fn iter(&self) -> impl Iterator<Item = (&Cow<'_, str>, &MiniCdnFile)> {
        self.files.iter()
    }
}

impl FilesystemMiniCdn {
    /// References the files. Subsequent accesses will load from the file system relative to
    /// this path.
    pub fn new(root_path: Cow<'static, str>) -> Self {
        Self { root_path }
    }

    /// Loads a file from the corresponding directory.
    pub fn get(&self, path: &str) -> Option<MiniCdnFile> {
        let canonical_path_tmp = Path::new(self.root_path.as_ref())
            .join(path)
            .canonicalize()
            .ok()?;
        let canonical_path = canonical_path_tmp.to_str()?;
        let canonical_root_path_tmp = Path::new(self.root_path.as_ref()).canonicalize().ok()?;
        let canonical_root_path = canonical_root_path_tmp.to_str()?;
        if !canonical_path.starts_with(canonical_root_path) {
            return None;
        }
        let contents = std::fs::read(&canonical_path).ok()?;
        Some(MiniCdnFile {
            #[cfg(feature = "mime")]
            mime: mime(canonical_path).into(),
            #[cfg(feature = "etag")]
            etag: etag(&contents).into(),
            #[cfg(feature = "last_modified")]
            last_modified: last_modified(canonical_path).into(),
            contents: contents.into(),
            #[cfg(feature = "brotli")]
            contents_brotli: None,
            #[cfg(feature = "gzip")]
            contents_gzip: None,
            #[cfg(feature = "webp")]
            contents_webp: None,
        })
    }

    /// Iterate files in the corresponding directory, without compressing.
    pub fn iter(&self) -> impl Iterator<Item = (String, MiniCdnFile)> + '_ {
        get_paths(&self.root_path).filter_map(|(_, relative)| {
            let file = self.get(&relative)?;
            Some((relative, file))
        })
    }
}

impl MiniCdn {
    /// Embeds the files into the binary at runtime, without compressing. The path is evaluated
    /// at runtime.
    pub fn new_embedded_from_path(root_path: &str) -> Self {
        Self::Embedded(EmbeddedMiniCdn::new(root_path))
    }

    /// Embeds the files into the binary at runtime. The path and compression are evaluated at
    /// runtime. This may incur significant runtime latency.
    pub fn new_compressed_from_path(root_path: &str) -> Self {
        Self::Embedded(EmbeddedMiniCdn::new_compressed(root_path))
    }

    /// References the files. Subsequent accesses will load from the file system relative to
    /// this path.
    pub fn new_filesystem_from_path(root_path: Cow<'static, str>) -> Self {
        Self::Filesystem(FilesystemMiniCdn::new(root_path))
    }

    /// Get a file by path.
    pub fn get(&self, path: &str) -> Option<Cow<'_, MiniCdnFile>> {
        match self {
            Self::Embedded(embedded) => embedded.get(path).map(Cow::Borrowed),
            Self::Filesystem(filesystem) => filesystem.get(path).map(Cow::Owned),
        }
    }

    /// Insert a new file. Will convert to embedded mode if needed.
    pub fn insert(&mut self, path: Cow<'static, str>, file: MiniCdnFile) {
        match self {
            Self::Embedded(embedded) => embedded.insert(path, file),
            Self::Filesystem(filesystem) => {
                *self = Self::Embedded((&*filesystem).into());
                self.insert(path, file);
            }
        }
    }

    /// Apply a function to each file.
    pub fn for_each(&self, mut f: impl FnMut(&str, &MiniCdnFile)) {
        match self {
            Self::Embedded(embedded) => embedded.iter().for_each(|(path, file)| f(&path, &file)),
            Self::Filesystem(filesystem) => {
                filesystem.iter().for_each(|(path, file)| f(&path, &file))
            }
        }
    }
}

impl From<&FilesystemMiniCdn> for EmbeddedMiniCdn {
    fn from(filesystem: &FilesystemMiniCdn) -> Self {
        let mut ret = EmbeddedMiniCdn::default();
        for (existing_path, existing_file) in filesystem.iter() {
            ret.insert(Cow::Owned(existing_path), existing_file);
        }
        ret
    }
}

fn get_paths(root_path: &str) -> impl Iterator<Item = (String, String)> + '_ {
    walkdir::WalkDir::new(&root_path)
        .follow_links(true)
        .sort_by_file_name()
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .map(move |e| {
            let relative_path = e
                .path()
                .strip_prefix(&root_path)
                .unwrap()
                .to_str()
                .expect("relative path error");
            let absolute_path_raw =
                std::fs::canonicalize(e.path()).expect("absolute path raw error");
            let absolute_path = absolute_path_raw.to_str().expect("absolute path error");

            let relative_path = if std::path::MAIN_SEPARATOR == '\\' {
                relative_path.replace('\\', "/")
            } else {
                relative_path.to_string()
            };

            (absolute_path.to_string(), relative_path)
        })
}

#[cfg(feature = "mime")]
fn mime(path: &str) -> String {
    mime_guess::from_path(&path)
        .first_or_octet_stream()
        .to_string()
}

#[cfg(feature = "last_modified")]
fn last_modified(absolute_path: &str) -> String {
    use std::time::SystemTime;
    std::fs::metadata(absolute_path)
        .expect(&format!("could not get metadata for {}", absolute_path))
        .modified()
        .ok()
        .map(|last_modified| {
            last_modified
                .duration_since(SystemTime::UNIX_EPOCH)
                .expect("invalid UNIX time")
                .as_secs()
        })
        .unwrap_or(
            SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        )
        .to_string()
}

#[cfg(feature = "etag")]
fn etag(contents: &[u8]) -> String {
    let mut etag = sha256::digest_bytes(contents);
    etag.truncate(32);
    //etag.shrink_to_fit();
    etag
}

#[cfg(feature = "brotli")]
fn brotli(contents: &[u8]) -> Option<Vec<u8>> {
    use std::io::Write;
    let mut output = Vec::new();
    let mut writer = brotli::CompressorWriter::new(&mut output, 4096, 9, 20);
    writer.write_all(contents).unwrap();
    drop(writer);
    if output.len() * 10 / 9 < contents.len() {
        Some(output)
    } else {
        // Compression is counterproductive.
        None
    }
}

#[cfg(feature = "gzip")]
fn gzip(contents: &[u8]) -> Option<Vec<u8>> {
    use flate2::write::GzEncoder;
    use flate2::Compression;
    use std::io::Write;
    let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
    encoder.write_all(contents.as_ref()).unwrap();
    let vec = encoder.finish().unwrap();
    if vec.len() * 10 / 9 < contents.len() {
        Some(vec)
    } else {
        // Compression is counterproductive.
        None
    }
}

#[cfg(feature = "webp")]
fn webp(contents: &[u8], mime_essence: &str) -> Option<Vec<u8>> {
    use std::io::Cursor;
    let cursor = Cursor::new(contents);
    let mut reader = image::io::Reader::new(cursor);
    use image::ImageFormat;
    reader.set_format(match mime_essence {
        "image/png" => ImageFormat::Png,
        "image/jpeg" => ImageFormat::Jpeg,
        _ => return None,
    });
    match reader.decode() {
        Ok(image) => {
            let webp_image =
                webp::Encoder::from_rgba(image.as_bytes(), image.width(), image.height())
                    .encode(90.0);

            if webp_image.len() * 10 / 9 < contents.len() {
                // Compression is counterproductive.
                use std::ops::Deref;
                Some(webp_image.deref().to_vec())
            } else {
                None
            }
        }
        Err(_) => None,
    }
}