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
use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::path::Path;
#[cfg(feature = "serde_base64")]
mod base64;
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MiniCdn {
Embedded(EmbeddedMiniCdn),
Filesystem(FilesystemMiniCdn),
}
#[derive(Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EmbeddedMiniCdn {
files: HashMap<Cow<'static, str>, MiniCdnFile>,
}
#[derive(Clone)]
#[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())
}
}
#[cfg(not(feature = "serde_base64"))]
type Bytes = [u8];
#[cfg(feature = "serde_base64")]
type Bytes = base64::Bytes;
#[cfg(not(feature = "serde_base64"))]
type ByteBuf = Vec<u8>;
#[cfg(feature = "serde_base64")]
type ByteBuf = base64::ByteBuf;
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MiniCdnFile {
#[cfg(feature = "etag")]
pub etag: Cow<'static, str>,
#[cfg(feature = "last_modified")]
pub last_modified: Cow<'static, str>,
#[cfg(feature = "mime")]
pub mime: Cow<'static, str>,
pub contents: Cow<'static, Bytes>,
#[cfg(feature = "gzip")]
pub contents_brotli: Option<Cow<'static, Bytes>>,
#[cfg(feature = "brotli")]
pub contents_gzip: Option<Cow<'static, Bytes>>,
#[cfg(feature = "webp")]
pub contents_webp: Option<Cow<'static, Bytes>>,
}
impl EmbeddedMiniCdn {
pub fn new(root_path: &str) -> Self {
FilesystemMiniCdn::new(Cow::Owned(root_path.to_string()))
.borrow()
.into()
}
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_essence = mime(&relative_path);
#[cfg(feature = "etag")]
let etag = etag(&contents);
#[cfg(feature = "webp")]
let contents_webp = webp(&contents, &mime_essence);
#[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: Cow::Owned(etag),
#[cfg(feature = "last_modified")]
last_modified: Cow::Owned(last_modified),
#[cfg(feature = "mime")]
mime: Cow::Owned(mime_essence),
contents: Cow::Owned(into_byte_buf(contents)),
#[cfg(feature = "brotli")]
contents_brotli: contents_brotli.map(into_byte_buf).map(Cow::Owned),
#[cfg(feature = "gzip")]
contents_gzip: contents_gzip.map(into_byte_buf).map(Cow::Owned),
#[cfg(feature = "webp")]
contents_webp: contents_webp.map(into_byte_buf).map(Cow::Owned),
},
)
});
ret
}
pub fn get(&self, path: &str) -> Option<&MiniCdnFile> {
self.files.get(path)
}
pub fn insert(&mut self, path: Cow<'static, str>, file: MiniCdnFile) {
self.files.insert(path, file);
}
pub fn remove(&mut self, path: &str) {
self.files.remove(path);
}
pub fn iter(&self) -> impl Iterator<Item = (&Cow<'_, str>, &MiniCdnFile)> {
self.files.iter()
}
}
impl FilesystemMiniCdn {
pub fn new(root_path: Cow<'static, str>) -> Self {
Self { root_path }
}
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: Cow::Owned(mime(canonical_path)),
#[cfg(feature = "etag")]
etag: Cow::Owned(etag(&contents)),
#[cfg(feature = "last_modified")]
last_modified: Cow::Owned(last_modified(canonical_path)),
contents: Cow::Owned(into_byte_buf(contents)),
#[cfg(feature = "brotli")]
contents_brotli: None,
#[cfg(feature = "gzip")]
contents_gzip: None,
#[cfg(feature = "webp")]
contents_webp: None,
})
}
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 {
pub fn new_embedded_from_path(root_path: &str) -> Self {
Self::Embedded(EmbeddedMiniCdn::new(root_path))
}
pub fn new_compressed_from_path(root_path: &str) -> Self {
Self::Embedded(EmbeddedMiniCdn::new_compressed(root_path))
}
pub fn new_filesystem_from_path(root_path: Cow<'static, str>) -> Self {
Self::Filesystem(FilesystemMiniCdn::new(root_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),
}
}
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);
}
}
}
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
}
}
pub fn into_bytes<'a>(bytes: &'a [u8]) -> &'a Bytes {
#[cfg(feature = "serde_base64")]
return bytes.into();
#[cfg(not(feature = "serde_base64"))]
bytes
}
fn into_byte_buf(vec: Vec<u8>) -> ByteBuf {
#[cfg(feature = "serde_base64")]
return ByteBuf::from(vec);
#[cfg(not(feature = "serde_base64"))]
vec
}
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
}
#[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 {
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.as_ref().len() {
Some(vec)
} else {
None
}
}
#[cfg(feature = "webp")]
fn webp(contents: &[u8], mime_essence: &str) -> Option<Vec<u8>> {
use std::io::Cursor;
let cursor = Cursor::new(contents.as_ref());
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() {
Some(webp_image.as_ref().to_vec())
} else {
None
}
}
Err(_) => None,
}
}