mini-static 0.14.7

A secure, async static file server with streaming, traversal protection, and connection limits.
Documentation
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

use bytes::Bytes;

use crate::minify::MinifyError;
use crate::reload::ChangeType;
use crate::watcher::Broadcaster;

/// Default cap on the number of distinct paths [`MinifyCache`] holds minified bytes
/// for. An unbounded cache would grow without limit for a server with enough distinct
/// CSS/JS files — this is a stated ceiling (per architecture principle A2), not
/// "as much as fits."
pub(crate) const DEFAULT_MINIFY_CACHE_CAPACITY: usize = 256;

struct CacheEntry {
    /// (path, mtime) pairs for all files this entry's bytes depend on.
    /// For a single-file minify, this is just one entry (the file itself).
    /// For a bundled file, this includes the entry file and all transitively imported files.
    dependencies: Vec<(PathBuf, SystemTime)>,
    bytes: Bytes,
}

/// An in-memory cache of minified (and optionally bundled) file bytes, keyed by path and
/// valid only if all its dependencies match their stored mtimes.
///
/// A cache hit requires both the path to be present *and* every dependency's current mtime
/// to match what's cached — a stale entry (any dependency changed) is treated as a miss
/// and overwritten, not served. Bounded to `capacity` entries: once full, inserting a new
/// path evicts an arbitrary existing entry (not true LRU — see `DEV_PLAN.md`, deferred
/// until a real embedder hits the cap).
///
/// # Bundling and reverse dependencies
///
/// When a CSS file `index.css` imports `base.css`, `index.css`'s cache entry lists both
/// files' mtimes. To detect staleness immediately (not just on the next request for
/// `index.css`), the cache maintains a reverse-dependency index: if `base.css` changes,
/// the watcher broadcasts a `ChangeEvent`, and `MinifyCache::invalidate(&base_path)` looks
/// up which entries import it (via the reverse-dep index) and evicts all of them.
pub(crate) struct MinifyCache {
    entries: Mutex<HashMap<PathBuf, CacheEntry>>,
    /// dependency_path -> set of entry_paths whose cached bytes depend on it.
    /// Lazily pruned: stale rows for already-evicted entries are acceptable and will be
    /// no-ops on next invalidate. This keeps the reverse-index bounded by the same
    /// `capacity × MAX_IMPORTED_FILES` limit as the entries themselves.
    reverse_deps: Mutex<HashMap<PathBuf, HashSet<PathBuf>>>,
    capacity: usize,
}

impl MinifyCache {
    pub(crate) fn new(capacity: usize) -> Self {
        MinifyCache {
            entries: Mutex::new(HashMap::new()),
            reverse_deps: Mutex::new(HashMap::new()),
            capacity,
        }
    }

    /// Return minified bytes for `path`, using `minify_fn` to produce them on a cache
    /// miss or a stale entry (any dependency's mtime doesn't match what's cached).
    ///
    /// `minify_fn` is a parameter (rather than always calling [`crate::minify::minify`]
    /// directly) so tests can wrap it with a call counter and assert the minifier ran
    /// only on genuine misses — the same "inject the thing you want to observe" shape
    /// as `accept_tests`' fake `TcpAccept` listener elsewhere in this crate.
    ///
    /// # Errors
    ///
    /// Returns `Err` if reading `path` fails, or if `minify_fn` rejects the source
    /// bytes as malformed.
    pub(crate) async fn get_or_minify<F>(
        &self,
        path: &Path,
        mtime: SystemTime,
        change_type: ChangeType,
        minify_fn: F,
    ) -> Result<Bytes, MinifyError>
    where
        F: FnOnce(&[u8], ChangeType) -> Result<Bytes, MinifyError>,
    {
        if let Some(bytes) = self.hit(path, &[(path.to_path_buf(), mtime)]) {
            return Ok(bytes);
        }

        let source = tokio::fs::read(path).await.map_err(MinifyError::Io)?;
        let minified = minify_fn(&source, change_type)?;
        self.insert(path.to_path_buf(), vec![(path.to_path_buf(), mtime)], minified.clone());
        Ok(minified)
    }

    /// Drop the cached entry for `path` and every entry that depends on `path`.
    ///
    /// For a non-bundled file, this just removes `path` itself. For a bundled file that
    /// imports other files, a watcher event for one of those imports triggers invalidation
    /// of every bundle entry that (transitively) imports it.
    pub(crate) fn invalidate(&self, path: &Path) {
        let mut entries = self.entries.lock().unwrap();
        let mut reverse_deps = self.reverse_deps.lock().unwrap();

        if let Some(dependent_entries) = reverse_deps.remove(path) {
            for entry_path in dependent_entries {
                entries.remove(&entry_path);
            }
        }

        entries.remove(path);
    }

    /// Spawn a background task that invalidates cache entries as CSS/Script change
    /// events arrive from `broadcaster` — reusing the file watcher already started for
    /// live-reload rather than running a second one. Without this, a changed file's
    /// stale entry would only be noticed reactively, on the next request for it (the
    /// mtime check in [`Self::get_or_minify`] still catches it then — this just makes
    /// the eviction immediate instead of deferred to that next request).
    ///
    /// Runs until `broadcaster`'s sender side is dropped (server shutdown).
    pub(crate) fn subscribe_to_invalidation(self: Arc<Self>, broadcaster: &Broadcaster) {
        let mut events = broadcaster.subscribe();
        tokio::spawn(async move {
            while let Some(event) = events.recv().await {
                if matches!(event.change_type, ChangeType::Css | ChangeType::Script) {
                    self.invalidate(&event.path);
                }
            }
        });
    }

    fn hit(&self, path: &Path, dependencies: &[(PathBuf, SystemTime)]) -> Option<Bytes> {
        let entries = self.entries.lock().unwrap();
        let entry = entries.get(path)?;

        if entry.dependencies.len() != dependencies.len() {
            return None;
        }

        for (stored_path, stored_mtime) in &entry.dependencies {
            let current_mtime = dependencies
                .iter()
                .find(|(p, _)| p == stored_path)
                .map(|(_, m)| m)?;

            if stored_mtime != current_mtime {
                return None;
            }
        }

        Some(entry.bytes.clone())
    }

    fn insert(&self, path: PathBuf, dependencies: Vec<(PathBuf, SystemTime)>, bytes: Bytes) {
        self.remove_entry_and_reverse_deps(&path, &dependencies);

        let mut entries = self.entries.lock().unwrap();
        let mut reverse_deps = self.reverse_deps.lock().unwrap();

        if entries.len() >= self.capacity && !entries.contains_key(&path) {
            if let Some(victim) = entries.keys().next().cloned() {
                if let Some(entry) = entries.remove(&victim) {
                    for (dep_path, _) in &entry.dependencies {
                        if let Some(dependents) = reverse_deps.get_mut(dep_path) {
                            dependents.remove(&victim);
                        }
                    }
                }
            }
        }

        for (dep_path, _) in &dependencies {
            reverse_deps.entry(dep_path.clone()).or_default().insert(path.clone());
        }

        entries.insert(path, CacheEntry { dependencies, bytes });
    }

    fn remove_entry_and_reverse_deps(&self, path: &PathBuf, _dependencies: &[(PathBuf, SystemTime)]) {
        let mut entries = self.entries.lock().unwrap();
        let mut reverse_deps = self.reverse_deps.lock().unwrap();

        if let Some(entry) = entries.remove(path) {
            for (dep_path, _) in &entry.dependencies {
                if let Some(dependents) = reverse_deps.get_mut(dep_path) {
                    dependents.remove(path);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn counting_minify(counter: &AtomicUsize) -> impl Fn(&[u8], ChangeType) -> Result<Bytes, MinifyError> + '_ {
        move |bytes, change_type| {
            counter.fetch_add(1, Ordering::SeqCst);
            crate::minify::minify(bytes, change_type)
        }
    }

    #[tokio::test]
    async fn minifies_once_per_mtime_then_serves_from_cache() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("app.css");
        std::fs::write(&path, "body {  color: red;  }").unwrap();
        let mtime = std::fs::metadata(&path).unwrap().modified().unwrap();

        let cache = MinifyCache::new(DEFAULT_MINIFY_CACHE_CAPACITY);
        let calls = AtomicUsize::new(0);

        let first = cache
            .get_or_minify(&path, mtime, ChangeType::Css, counting_minify(&calls))
            .await
            .unwrap();
        let second = cache
            .get_or_minify(&path, mtime, ChangeType::Css, counting_minify(&calls))
            .await
            .unwrap();

        assert_eq!(calls.load(Ordering::SeqCst), 1, "second request with the same mtime should hit the cache");
        assert_eq!(first, second);

        // Touch the file (new mtime) and request again: must re-minify.
        std::thread::sleep(std::time::Duration::from_millis(10));
        std::fs::write(&path, "body {  color: blue;  }").unwrap();
        let new_mtime = std::fs::metadata(&path).unwrap().modified().unwrap();
        assert_ne!(mtime, new_mtime, "test fixture must actually produce a new mtime");

        let third = cache
            .get_or_minify(&path, new_mtime, ChangeType::Css, counting_minify(&calls))
            .await
            .unwrap();

        assert_eq!(calls.load(Ordering::SeqCst), 2, "a changed mtime must be treated as a miss");
        assert_ne!(first, third, "content changed, so minified bytes must differ");
    }

    #[tokio::test]
    async fn invalidate_forces_a_reminify_even_with_an_unchanged_mtime() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("app.css");
        std::fs::write(&path, "body { color: red; }").unwrap();
        let mtime = std::fs::metadata(&path).unwrap().modified().unwrap();

        let cache = MinifyCache::new(DEFAULT_MINIFY_CACHE_CAPACITY);
        let calls = AtomicUsize::new(0);

        cache
            .get_or_minify(&path, mtime, ChangeType::Css, counting_minify(&calls))
            .await
            .unwrap();
        cache.invalidate(&path);
        cache
            .get_or_minify(&path, mtime, ChangeType::Css, counting_minify(&calls))
            .await
            .unwrap();

        assert_eq!(calls.load(Ordering::SeqCst), 2, "invalidate() must force a re-minify on the next request");
    }

    #[tokio::test]
    async fn capacity_is_enforced() {
        let dir = tempfile::TempDir::new().unwrap();
        let cache = MinifyCache::new(2);
        let calls = AtomicUsize::new(0);

        for i in 0..5 {
            let path = dir.path().join(format!("f{i}.css"));
            std::fs::write(&path, format!("body {{ color: red{i}; }}")).unwrap();
            let mtime = std::fs::metadata(&path).unwrap().modified().unwrap();
            cache
                .get_or_minify(&path, mtime, ChangeType::Css, counting_minify(&calls))
                .await
                .unwrap();
        }

        assert!(
            cache.entries.lock().unwrap().len() <= 2,
            "cache must never exceed its stated capacity"
        );
    }

    #[tokio::test]
    async fn broadcaster_change_event_invalidates_before_the_next_request() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("app.css");
        std::fs::write(&path, "body { color: red; }").unwrap();
        let mtime = std::fs::metadata(&path).unwrap().modified().unwrap();

        let cache = Arc::new(MinifyCache::new(DEFAULT_MINIFY_CACHE_CAPACITY));
        let calls = AtomicUsize::new(0);

        // Populate the cache.
        cache
            .get_or_minify(&path, mtime, ChangeType::Css, counting_minify(&calls))
            .await
            .unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 1);

        // Reuse the same broadcaster live-reload's watcher already runs — not a
        // second watcher — and subscribe the cache to it.
        let broadcaster = Broadcaster::new();
        Arc::clone(&cache).subscribe_to_invalidation(&broadcaster);

        broadcaster.broadcast(crate::watcher::ChangeEvent {
            path: path.clone(),
            change_type: ChangeType::Css,
        });

        // Give the spawned subscriber task a moment to process the event before the
        // "next request" arrives — matching the DEV_PLAN spec: the entry must be gone
        // *before* that next request, not just eventually consistent by the one after.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // Same mtime as before: if the entry were still cached, this would be a hit
        // and the minifier would NOT run again. A second call proves invalidation.
        cache
            .get_or_minify(&path, mtime, ChangeType::Css, counting_minify(&calls))
            .await
            .unwrap();
        assert_eq!(
            calls.load(Ordering::SeqCst),
            2,
            "the broadcaster's change event must have evicted the entry before this request"
        );
    }

    #[tokio::test]
    async fn bundle_cache_hit_requires_every_dependency_mtime_unchanged() {
        let dir = tempfile::TempDir::new().unwrap();
        let base_path = dir.path().join("base.css");
        let entry_path = dir.path().join("entry.css");

        std::fs::write(&base_path, "body { margin: 0; }").unwrap();
        std::fs::write(&entry_path, "@import \"base.css\";").unwrap();

        let base_mtime = std::fs::metadata(&base_path).unwrap().modified().unwrap();
        let entry_mtime = std::fs::metadata(&entry_path).unwrap().modified().unwrap();

        let cache = MinifyCache::new(DEFAULT_MINIFY_CACHE_CAPACITY);
        let deps = vec![(base_path.clone(), base_mtime), (entry_path.clone(), entry_mtime)];

        // Simulate a bundled entry: entry depends on both itself and base.css
        cache.insert(entry_path.clone(), deps.clone(), Bytes::from("body{margin:0}"));

        // Hit with unchanged mtimes.
        assert!(cache.hit(&entry_path, &deps).is_some());

        // Touch base.css (mtime changes).
        std::thread::sleep(std::time::Duration::from_millis(10));
        std::fs::write(&base_path, "body { margin: 1px; }").unwrap();
        let new_base_mtime = std::fs::metadata(&base_path).unwrap().modified().unwrap();
        assert_ne!(base_mtime, new_base_mtime);

        let stale_deps = vec![(base_path.clone(), new_base_mtime), (entry_path.clone(), entry_mtime)];
        // Miss because base.css's mtime changed.
        assert!(cache.hit(&entry_path, &stale_deps).is_none());
    }

    #[tokio::test]
    async fn changed_leaf_dependency_invalidates_all_bundles_that_import_it() {
        let dir = tempfile::TempDir::new().unwrap();
        let shared_path = dir.path().join("shared.css");
        let entry1_path = dir.path().join("entry1.css");
        let entry2_path = dir.path().join("entry2.css");

        std::fs::write(&shared_path, "body { padding: 0; }").unwrap();
        std::fs::write(&entry1_path, "@import \"shared.css\";").unwrap();
        std::fs::write(&entry2_path, "@import \"shared.css\";").unwrap();

        let shared_mtime = std::fs::metadata(&shared_path).unwrap().modified().unwrap();
        let entry1_mtime = std::fs::metadata(&entry1_path).unwrap().modified().unwrap();
        let entry2_mtime = std::fs::metadata(&entry2_path).unwrap().modified().unwrap();

        let cache = Arc::new(MinifyCache::new(DEFAULT_MINIFY_CACHE_CAPACITY));

        // Both entries depend on shared.css.
        cache.insert(
            entry1_path.clone(),
            vec![(shared_path.clone(), shared_mtime), (entry1_path.clone(), entry1_mtime)],
            Bytes::from("entry1"),
        );
        cache.insert(
            entry2_path.clone(),
            vec![(shared_path.clone(), shared_mtime), (entry2_path.clone(), entry2_mtime)],
            Bytes::from("entry2"),
        );

        assert!(cache.entries.lock().unwrap().contains_key(&entry1_path));
        assert!(cache.entries.lock().unwrap().contains_key(&entry2_path));

        // Invalidate the shared dependency.
        Arc::clone(&cache).invalidate(&shared_path);

        // Both entries should be gone.
        assert!(!cache.entries.lock().unwrap().contains_key(&entry1_path));
        assert!(!cache.entries.lock().unwrap().contains_key(&entry2_path));
    }

    #[tokio::test]
    async fn eviction_cleans_up_reverse_dep_index() {
        let dir = tempfile::TempDir::new().unwrap();
        let dep_path = dir.path().join("dep.css");
        let entry_path = dir.path().join("entry.css");

        std::fs::write(&dep_path, "body { }").unwrap();
        std::fs::write(&entry_path, "@import \"dep.css\";").unwrap();

        let dep_mtime = std::fs::metadata(&dep_path).unwrap().modified().unwrap();
        let entry_mtime = std::fs::metadata(&entry_path).unwrap().modified().unwrap();

        let cache = MinifyCache::new(1);

        cache.insert(
            entry_path.clone(),
            vec![(dep_path.clone(), dep_mtime), (entry_path.clone(), entry_mtime)],
            Bytes::from("bundled"),
        );

        {
            let reverse_deps = cache.reverse_deps.lock().unwrap();
            assert!(reverse_deps.get(&dep_path).is_some());
            assert!(reverse_deps[&dep_path].contains(&entry_path));
        }

        // Insert another entry to trigger eviction of the first.
        let other_dep = dir.path().join("other.css");
        let other_entry = dir.path().join("other.css");
        std::fs::write(&other_dep, "").unwrap();
        cache.insert(
            other_entry.clone(),
            vec![(other_dep.clone(), dep_mtime)],
            Bytes::from("other"),
        );

        // First entry should be evicted.
        assert!(!cache.entries.lock().unwrap().contains_key(&entry_path));

        // Reverse-dep for the evicted entry's dependency should be cleaned up.
        {
            let reverse_deps = cache.reverse_deps.lock().unwrap();
            let dependents = reverse_deps.get(&dep_path);
            assert!(dependents.is_none() || !dependents.unwrap().contains(&entry_path));
        }
    }
}