mini-static 0.15.1

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
use std::path::{Path, PathBuf};

use crate::css_bundler;
use crate::minify;
use crate::reload::ChangeType;
use crate::watcher::{Broadcaster, ChangeEvent};

/// Routes source-folder file changes to the pipeline that turns them into served output.
///
/// The watcher layer runs over *source folders only*. The designated output dir is never
/// watched and never a trigger: every pipeline below writes its own output, and a pipeline
/// that listened to its own output would re-trigger itself forever (the feedback-loop bug
/// this design fixes). Instead, after a build finishes, the pipeline broadcasts the reload
/// event for the output it wrote, so the browser still hot-swaps/reloads.
///
/// Dispatch is by the changed file's [`ChangeType`]:
/// - `Css` under a source folder or import root → rebuild the single CSS bundle.
/// - `Script` under a source folder → minify that one file into its mirrored output.
/// - anything else → re-broadcast the change so the client reloads and picks up whatever
///   external builder (e.g. a markdown renderer) wrote to the output.
pub(crate) struct SourcePipeline {
    source_folders: Vec<PathBuf>,
    bundle_roots: Vec<PathBuf>,
    output_dir: PathBuf,
    css_bundle_output: Option<PathBuf>,
    prune_output: bool,
    broadcaster: Broadcaster,
}

impl SourcePipeline {
    pub(crate) fn new(
        source_folders: Vec<PathBuf>,
        bundle_roots: Vec<PathBuf>,
        output_dir: PathBuf,
        css_bundle_output: Option<PathBuf>,
        prune_output: bool,
        broadcaster: Broadcaster,
    ) -> Self {
        SourcePipeline {
            source_folders,
            bundle_roots,
            output_dir,
            css_bundle_output,
            prune_output,
            broadcaster,
        }
    }

    /// Rebuild every enabled output once, then prune stale output if configured.
    ///
    /// Runs at server startup. Never during live-reload — see [`Self::prune_stale_output`].
    pub(crate) async fn full_build(&self) -> Result<(), SourceError> {
        let css_written = self.build_css().await?;

        self.build_all_js().await?;

        if self.prune_output {
            self.prune_stale_output(css_written.as_deref()).await?;
        }

        Ok(())
    }

    /// Handle a single change event for `path` (which must be under a watched source
    /// folder or import root), rebuilding output as needed and broadcasting the reload
    /// event for whatever was written.
    pub(crate) async fn process_change(
        &self,
        path: &Path,
        change_type: &ChangeType,
    ) -> Result<(), SourceError> {
        if self.css_bundle_output.is_some()
            && change_type == &ChangeType::Css
            && self.is_css_input(path)
        {
            if let Some(output) = self.build_css().await? {
                self.broadcast_change(&output);
            }
            return Ok(());
        }

        if change_type == &ChangeType::Script {
            if let Some(output) = self.build_js_file(path).await? {
                self.broadcast_change(&output);
            }
            return Ok(());
        }

        // No pipeline owns this file kind. Re-broadcast only genuine watched-input
        // changes so the client reloads and re-fetches whatever external builder produced
        // the output. The watcher never watches the output dir, so the ONLY paths that
        // reach here without being under a watched root are this pipeline's own broadcast
        // echoes (e.g. a rebuilt bundle) — re-broadcasting those would make the pipeline
        // loop on its own output forever, flooding the SSE stream (the `_mr` cycling bug).
        if self.is_input(path) {
            self.broadcaster.broadcast(ChangeEvent {
                path: path.to_path_buf(),
                change_type: change_type.clone(),
            });
        }
        Ok(())
    }

    /// Rebuild the single CSS bundle from every source folder. Returns the output path it
    /// wrote, or `None` when no CSS sources exist (nothing to produce).
    async fn build_css(&self) -> Result<Option<PathBuf>, SourceError> {
        let Some(output) = &self.css_bundle_output else {
            return Ok(None);
        };

        if !self.has_css_sources() {
            return Ok(None);
        }

        let mut allowed_roots = self.source_folders.clone();
        allowed_roots.extend(self.bundle_roots.iter().cloned());

        css_bundler::bundle_css_sources(&allowed_roots, &self.source_folders, output)
            .await
            .map_err(SourceError::Css)?;

        Ok(Some(output.clone()))
    }

    /// Minify every `.js`/`.mjs` under every source folder into its mirrored output path.
    async fn build_all_js(&self) -> Result<(), SourceError> {
        for folder in &self.source_folders {
            let files = list_files(folder).await.map_err(SourceError::Io)?;
            for file in files {
                if is_script(&file) {
                    let output = self.mirror_output(folder, &file)?;
                    self.write_minified_js(&file, &output).await?;
                }
            }
        }
        Ok(())
    }

    /// Minify a single changed `.js`/`.mjs` into its mirrored output path.
    async fn build_js_file(&self, source: &Path) -> Result<Option<PathBuf>, SourceError> {
        let Some(folder) = self.containing_source_folder(source) else {
            return Ok(None);
        };

        if !is_script(source) {
            return Ok(None);
        }

        let output = self.mirror_output(folder, source)?;
        self.write_minified_js(source, &output).await?;
        Ok(Some(output))
    }

    /// The output path for `source`, mirroring its path relative to `folder` under the
    /// output dir.
    fn mirror_output(&self, folder: &Path, source: &Path) -> Result<PathBuf, SourceError> {
        let relative = source
            .strip_prefix(folder)
            .map_err(|_| SourceError::NotUnderSource(source.to_path_buf()))?;
        Ok(self.output_dir.join(relative))
    }

    /// Minify `source` with the JS minifier and write the result to `output`.
    ///
    /// A malformed source degrades to its raw bytes rather than failing the pipeline: the
    /// server must still serve the file and keep the browser in sync (mirrors the
    /// on-the-fly minify path's "serve unminified on failure" contract). The degradation
    /// is logged, not silent.
    async fn write_minified_js(&self, source: &Path, output: &Path) -> Result<(), SourceError> {
        let bytes = tokio::fs::read(source).await.map_err(SourceError::Io)?;
        let output_bytes = match minify::minify(&bytes, ChangeType::Script) {
            Ok(minified) => minified,
            Err(e) => {
                eprintln!(
                    "source pipeline: minify failed for {}, serving raw bytes: {e}",
                    source.display()
                );
                bytes.into()
            }
        };

        if let Some(parent) = output.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(SourceError::Io)?;
        }
        tokio::fs::write(output, &output_bytes)
            .await
            .map_err(SourceError::Io)?;
        Ok(())
    }

    /// Broadcast a reload event for `output`, deriving its change type from the output's
    /// own extension so the browser hot-swaps/reloads exactly as it would for that file.
    fn broadcast_change(&self, output: &Path) {
        self.broadcaster.broadcast(ChangeEvent {
            path: output.to_path_buf(),
            change_type: ChangeType::from_path(output),
        });
    }

    /// True when `path` lives under any watched root (a source folder or a CSS `@import`
    /// root). These are the only paths the watcher emits, so an event whose path fails
    /// this check must be the pipeline's own output echo and must not be re-broadcast.
    fn is_input(&self, path: &Path) -> bool {
        self.source_folders
            .iter()
            .chain(self.bundle_roots.iter())
            .any(|root| path.starts_with(root))
    }

    /// True when `path` lives under a source folder or a CSS `@import` root — i.e. a CSS
    /// change there must trigger a rebundle.
    fn is_css_input(&self, path: &Path) -> bool {
        self.is_input(path)
    }

    /// The source folder containing `path`, if any.
    fn containing_source_folder(&self, path: &Path) -> Option<&PathBuf> {
        self.source_folders
            .iter()
            .find(|folder| path.starts_with(folder))
    }

    /// True when at least one `.css` file exists under the source folders.
    fn has_css_sources(&self) -> bool {
        for folder in &self.source_folders {
            if walk_dir(folder).any(|path| is_css(&path)) {
                return true;
            }
        }
        false
    }

    /// Remove stale output at build time, never during live-reload.
    ///
    /// The only output this server can own *by identity* is the CSS bundle file — a single
    /// exact path that no hand-written file shares. If bundling is enabled but no CSS
    /// sources remain, the leftover bundle is removed. Per-file JS outputs are deliberately
    /// NOT auto-pruned: their mirrored paths can coincide with hand-written files, and
    /// deleting files the server doesn't own is a surprise (A1) the caller can't opt into
    /// by accident.
    async fn prune_stale_output(&self, css_written: Option<&Path>) -> Result<(), SourceError> {
        let Some(bundle) = &self.css_bundle_output else {
            return Ok(());
        };

        let wrote_bundle = css_written.is_some_and(|written| written == bundle);
        if wrote_bundle {
            return Ok(());
        }

        if tokio::fs::metadata(bundle).await.is_err() {
            return Ok(());
        }

        tokio::fs::remove_file(bundle)
            .await
            .map_err(SourceError::Io)?;
        eprintln!("pruned stale css bundle output: {}", bundle.display());
        Ok(())
    }
}

/// Why [`SourcePipeline`] could not produce output for a change or build.
#[derive(Debug)]
pub(crate) enum SourceError {
    /// The CSS bundle step failed.
    Css(css_bundler::CssBundlerError),
    /// A filesystem operation failed.
    Io(std::io::Error),
    /// A changed path was not under the source folder claimed to contain it.
    NotUnderSource(PathBuf),
}

impl std::fmt::Display for SourceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SourceError::Css(e) => write!(f, "css bundle failed: {e}"),
            SourceError::Io(e) => write!(f, "io error: {e}"),
            SourceError::NotUnderSource(p) => {
                write!(f, "path not under any source folder: {}", p.display())
            }
        }
    }
}

impl std::error::Error for SourceError {}

/// True if `path` names a CSS file (by extension).
fn is_css(path: &Path) -> bool {
    path.extension().and_then(|e| e.to_str()) == Some("css")
}

/// True if `path` names a script the minifier accepts (`js`/`mjs`).
fn is_script(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some("js" | "mjs")
    )
}

/// Recursively list every file under `dir`.
///
/// Bounded by the filesystem: `walk_dir` pushes directories onto a stack and terminates
/// when none remain — a directory tree is finite, so this loop always ends.
async fn list_files(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    let mut dirs = vec![dir.to_path_buf()];

    while let Some(current) = dirs.pop() {
        let mut entries = tokio::fs::read_dir(&current).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if entry.file_type().await?.is_dir() {
                dirs.push(path);
            } else {
                files.push(path);
            }
        }
    }

    Ok(files)
}

/// Synchronously walk `dir` and yield every file path. Used by the cheap existence check
/// in [`SourcePipeline::has_css_sources`] (runs at build boundaries, not per request).
fn walk_dir(dir: &Path) -> impl Iterator<Item = PathBuf> {
    let mut dirs = vec![dir.to_path_buf()];
    std::iter::from_fn(move || {
        while let Some(current) = dirs.pop() {
            let Ok(entries) = std::fs::read_dir(&current) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if entry.file_type().is_ok_and(|t| t.is_dir()) {
                    dirs.push(path);
                } else {
                    return Some(path);
                }
            }
        }
        None
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::time::Duration;
    use tempfile::TempDir;

    /// Regression: the pipeline must not loop on its own output. The pipeline subscribes
    /// to the same broadcaster it broadcasts into. After rebuilding the CSS bundle it
    /// broadcasts a `css` event for the output path — that echo must NOT be re-broadcast,
    /// or the pipeline loops forever and floods the SSE stream (the bug where the browser
    /// kept cycling fresh `_mr` values). Here one source change must produce exactly two
    /// events (the source change itself plus the bundle broadcast), then stop.
    #[tokio::test]
    async fn pipeline_does_not_rebroadcast_its_own_output_echo() {
        let src = TempDir::new().unwrap();
        let out = TempDir::new().unwrap();
        tokio::fs::write(src.path().join("style.css"), "body { margin: 0; }")
            .await
            .unwrap();

        let broadcaster = Broadcaster::new();
        let pipeline = Arc::new(SourcePipeline::new(
            vec![src.path().to_path_buf()],
            Vec::new(),
            out.path().to_path_buf(),
            Some(out.path().join("styles.css")),
            false,
            broadcaster.clone(),
        ));

        // The pipeline consumes the same broadcaster it writes to, exactly as in `run_on`.
        // Subscribe both receivers here so they are registered before the broadcast (the
        // spawned task alone could miss it while still scheduling on the test runtime).
        let mut pipeline_rx = broadcaster.subscribe();
        let mut observer = broadcaster.subscribe();
        let pipeline_task = tokio::spawn(async move {
            while let Some(event) = pipeline_rx.recv().await {
                if let Err(e) = pipeline
                    .process_change(&event.path, &event.change_type)
                    .await
                {
                    eprintln!("source pipeline error: {e}");
                }
            }
        });

        broadcaster.broadcast(ChangeEvent {
            path: src.path().join("style.css"),
            change_type: ChangeType::Css,
        });

        // Collect every event the SSE clients would see during a bounded window.
        let mut count = 0usize;
        let window = Duration::from_millis(400);
        let deadline = tokio::time::Instant::now() + window;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                break;
            }
            match tokio::time::timeout(remaining, observer.recv()).await {
                Ok(Some(_)) => count += 1,
                Ok(None) | Err(_) => break,
            }
        }

        pipeline_task.abort();

        assert_eq!(
            count, 2,
            "a single source css change must emit exactly the source event + the bundle \
             broadcast, and then stop — not feed back forever (got {count})"
        );
    }
}