Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .sampo/changesets/shrewd-dawnrunner-mielikki.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
cargo/maudit-cli: patch
---

Fixed the development server ignoring changes in directories named `dist`, `target` or `.git` anywhere in the project, such as `static/dist`. Only the ones at the root are skipped now.
5 changes: 5 additions & 0 deletions .sampo/changesets/valiant-pathwarden-ahti.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
cargo/maudit-cli: patch
---

Fixed the development server serving stale static files after they change, the browser now revalidates them on every request.
112 changes: 87 additions & 25 deletions crates/maudit-cli/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use notify::{
use notify_debouncer_full::{DebounceEventResult, DebouncedEvent, new_debouncer};
use quanta::Instant;
use server::StatusManager;
use std::{fs, path::Path, path::PathBuf, sync::Arc};
use std::{ffi::OsStr, fs, path::Path, path::PathBuf, sync::Arc};
use tokio::{signal, sync::mpsc::channel, task::JoinHandle};
use tracing::{error, info};

Expand Down Expand Up @@ -40,14 +40,12 @@ pub async fn start_dev_env(
// Set up file watching with debouncer
let (tx, mut rx) = channel::<DebounceEventResult>(1000);

let watch_root = fs::canonicalize(cwd).unwrap_or_else(|_| PathBuf::from(cwd));

let directories = fs::read_dir(cwd)?
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().is_dir())
.filter(|entry| {
let path = entry.path();
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
!matches!(file_name, "target" | ".git" | "dist")
})
.filter(|entry| !entry.path().file_name().is_some_and(is_ignored_root_dir))
.map(|entry| entry.path())
.collect::<Vec<_>>();

Expand Down Expand Up @@ -112,13 +110,13 @@ pub async fn start_dev_env(
// - https://github.com/notify-rs/notify/issues/434
// - https://github.com/notify-rs/notify/issues/412

let should_rebuild = events.iter().any(should_rebuild_for_event);
let should_rebuild = events.iter().any(|event| should_rebuild_for_event(&watch_root, event));

// If new folder are created or removed, add/remove watches as needed
for event in &events {
if let EventKind::Create(CreateKind::Folder) = event.kind {
for path in &event.paths {
if should_watch_path(path) {
if should_watch_path(&watch_root, path) {
if let Err(e) = debouncer.watch(path, RecursiveMode::Recursive) {
error!(name: "watch", "Failed to add watch for new directory {:?}: {}", path, e);
} else {
Expand All @@ -131,7 +129,7 @@ pub async fn start_dev_env(
// TODO: This doesn't seem to always work, sometimes removed folders are considered renames (maybe because of trash?), but it's fine I think
if let EventKind::Remove(RemoveKind::Folder) = event.kind {
for path in &event.paths {
if should_watch_path(path) {
if should_watch_path(&watch_root, path) {
if let Err(e) = debouncer.unwatch(path) {
error!(name: "watch", "Failed to remove watch for directory {:?}: {}", path, e);
} else {
Expand All @@ -147,7 +145,7 @@ pub async fn start_dev_env(
let changed_paths: Vec<PathBuf> = events
.iter()
.flat_map(|e| e.paths.iter().cloned())
.filter(|p| should_watch_path(p))
.filter(|p| should_watch_path(&watch_root, p))
.collect();

if !dev_server_started {
Expand Down Expand Up @@ -252,9 +250,9 @@ pub async fn start_dev_env(
Ok(())
}

fn should_rebuild_for_event(event: &DebouncedEvent) -> bool {
fn should_rebuild_for_event(root: &Path, event: &DebouncedEvent) -> bool {
event.paths.iter().any(|path| {
should_watch_path(path)
should_watch_path(root, path)
&& match event.kind {
// Only rebuild on actual content modifications, not metadata changes
EventKind::Modify(ModifyKind::Data(_)) => true,
Expand All @@ -272,23 +270,25 @@ fn should_rebuild_for_event(event: &DebouncedEvent) -> bool {
})
}

fn should_watch_path(path: &Path) -> bool {
// Skip .DS_Store files
if let Some(file_name) = path.file_name()
&& file_name == ".DS_Store"
{
return false;
}
fn is_ignored_root_dir(name: &OsStr) -> bool {
matches!(name.to_str(), Some("target" | "dist" | ".git"))
}

// Skip dist and target directories, normally ignored by the watcher, but just in case
if path
.ancestors()
.any(|p| p.ends_with("dist") || p.ends_with("target") || p.ends_with(".git"))
{
fn should_watch_path(root: &Path, path: &Path) -> bool {
if path.file_name().is_some_and(|name| name == ".DS_Store") {
return false;
}

true
// Only ignored at the root: a `static/dist` directory is content the user expects to be served
let absolute = root.join(path);
let Ok(relative) = absolute.strip_prefix(root) else {
return true;
};

!relative
.components()
.next()
.is_some_and(|first| is_ignored_root_dir(first.as_os_str()))
}

async fn shutdown_signal() {
Expand All @@ -314,3 +314,65 @@ async fn shutdown_signal() {
_ = terminate => {},
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn ignores_root_output_directories() {
let root = Path::new("/project");

assert!(!should_watch_path(
root,
Path::new("/project/dist/index.html")
));
assert!(!should_watch_path(
root,
Path::new("/project/target/debug/site")
));
assert!(!should_watch_path(root, Path::new("/project/.git/HEAD")));
}

#[test]
fn watches_ignored_names_below_the_root() {
let root = Path::new("/project");

assert!(should_watch_path(
root,
Path::new("/project/static/dist/vendor.js")
));
assert!(should_watch_path(
root,
Path::new("/project/static/target/app.css")
));
}

#[test]
fn watches_relative_paths() {
assert!(should_watch_path(
Path::new("."),
Path::new("./static/dist/vendor.js")
));
assert!(!should_watch_path(
Path::new("."),
Path::new("./dist/index.html")
));
}

#[test]
fn watches_projects_living_under_an_ignored_name() {
assert!(should_watch_path(
Path::new("/dist/project"),
Path::new("/dist/project/static/logo.svg")
));
}

#[test]
fn ignores_ds_store() {
assert!(!should_watch_path(
Path::new("/project"),
Path::new("/project/static/.DS_Store")
));
}
}
49 changes: 47 additions & 2 deletions crates/maudit-cli/src/dev/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,8 +359,8 @@ fn cache_header_by_content(uri: &Uri, content_type: &HeaderValue) -> Option<Head
"public, max-age=31536000, immutable",
))
} else {
// Don't try to cache anything else, the browser will decide based on the last-modified header
None
// Unfingerprinted URLs, so heuristic freshness would hide edits until it expires
Some(HeaderValue::from_static("no-cache"))
}
}

Expand Down Expand Up @@ -448,3 +448,48 @@ async fn shutdown_signal() {
_ = terminate => {},
}
}

#[cfg(test)]
mod tests {
use super::*;

fn cache_header(path: &str, content_type: &str) -> Option<String> {
cache_header_by_content(
&path.parse::<Uri>().unwrap(),
&HeaderValue::from_str(content_type).unwrap(),
)
.map(|value| value.to_str().unwrap().to_string())
}

#[test]
fn html_is_never_cached() {
assert_eq!(
cache_header("/about/", "text/html").as_deref(),
Some("no-cache, no-store, must-revalidate")
);
}

#[test]
fn fingerprinted_assets_are_cached_forever() {
assert_eq!(
cache_header("/_maudit/app-CScY0Smx.js", "text/javascript").as_deref(),
Some("public, max-age=31536000, immutable")
);
}

#[test]
fn static_files_are_revalidated() {
assert_eq!(
cache_header("/style.css", "text/css").as_deref(),
Some("no-cache")
);
assert_eq!(
cache_header("/logo.svg", "image/svg+xml").as_deref(),
Some("no-cache")
);
assert_eq!(
cache_header("/fonts/inter.woff2", "font/woff2").as_deref(),
Some("no-cache")
);
}
}
1 change: 1 addition & 0 deletions e2e/fixtures/hot-reload/static/asset.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Original asset
30 changes: 30 additions & 0 deletions e2e/tests/hot-reload.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,27 +69,32 @@ test.describe("Hot Reload", () => {
const indexPath = resolve(fixturePath, "src", "pages", "index.rs");
const mainPath = resolve(fixturePath, "src", "main.rs");
const dataPath = resolve(fixturePath, "data.txt");
const staticPath = resolve(fixturePath, "static", "asset.txt");
let originalIndexContent: string;
let originalMainContent: string;
let originalDataContent: string;
let originalStaticContent: string;

test.beforeAll(async () => {
// Save original content
originalIndexContent = readFileSync(indexPath, "utf-8");
originalMainContent = readFileSync(mainPath, "utf-8");
originalDataContent = readFileSync(dataPath, "utf-8");
originalStaticContent = readFileSync(staticPath, "utf-8");

// Ensure files are in original state
writeFileSync(indexPath, originalIndexContent, "utf-8");
writeFileSync(mainPath, originalMainContent, "utf-8");
writeFileSync(dataPath, originalDataContent, "utf-8");
writeFileSync(staticPath, originalStaticContent, "utf-8");
});

test.afterEach(async ({ devServer }) => {
// Restore original content after each test
writeFileSync(indexPath, originalIndexContent, "utf-8");
writeFileSync(mainPath, originalMainContent, "utf-8");
writeFileSync(dataPath, originalDataContent, "utf-8");
writeFileSync(staticPath, originalStaticContent, "utf-8");

// Only wait for build if devServer is available (startup might have failed)
if (devServer) {
Expand All @@ -112,6 +117,7 @@ test.describe("Hot Reload", () => {
writeFileSync(indexPath, originalIndexContent, "utf-8");
writeFileSync(mainPath, originalMainContent, "utf-8");
writeFileSync(dataPath, originalDataContent, "utf-8");
writeFileSync(staticPath, originalStaticContent, "utf-8");
});

test("should recompile when Rust code changes (dependencies)", async ({ page, devServer }) => {
Expand Down Expand Up @@ -189,4 +195,28 @@ test.describe("Hot Reload", () => {

await expect(page.locator("#title")).toHaveText("Another Update", { timeout: 15000 });
});

test("should serve updated static files after they change", async ({ request, devServer }) => {
const before = await request.get(`${devServer.url}/asset.txt`);
expect(await before.text()).toContain("Original asset");

devServer.clearLogs();
writeFileSync(staticPath, "Updated asset", "utf-8");

await waitForBuildComplete(devServer, 20000);

const after = await request.get(`${devServer.url}/asset.txt`);
expect(await after.text()).toContain("Updated asset");
});

test("should serve static files with a revalidating cache header", async ({
request,
devServer,
}) => {
const response = await request.get(`${devServer.url}/asset.txt`);
expect(response.headers()["cache-control"]).toBe("no-cache");

const html = await request.get(devServer.url);
expect(html.headers()["cache-control"]).toBe("no-cache, no-store, must-revalidate");
});
});
Loading