|
1 | 1 | use anyhow::{Context, Result}; |
2 | 2 | use chromiumoxide::{Browser, BrowserConfig, BrowserFetcher, BrowserFetcherOptions, Page}; |
3 | 3 | use futures::StreamExt; |
4 | | -use std::path::PathBuf; |
| 4 | +use std::path::{Path, PathBuf}; |
| 5 | +use std::time::{SystemTime, UNIX_EPOCH}; |
5 | 6 | use tokio::task::JoinHandle; |
6 | 7 |
|
7 | 8 | /// Downloads a Chrome-for-Testing build into ~/.cache/formwatch/chrome. Only |
8 | 9 | /// runs when no system Chrome/Chromium can be auto-detected, so a plain |
9 | 10 | /// `cargo install formwatch` still works with no root/apt step. |
10 | 11 | /// |
11 | | -/// ponytail: not safe for concurrent callers racing to populate a cold |
12 | | -/// cache (two formwatch processes started at once on a machine with no |
13 | | -/// Chrome yet, or — the way this was actually found — `cargo test`'s |
14 | | -/// default test parallelism on a machine without system Chrome) can |
15 | | -/// corrupt each other's extraction. Normal usage launches the browser |
16 | | -/// once per process, so this doesn't bite real `formwatch test`/`monitor` |
17 | | -/// runs; if it needs to be made safe, the fix is downloading into a |
18 | | -/// per-process temp dir and atomically renaming into place. Contributors |
19 | | -/// without system Chrome: run something that warms the cache once (e.g. |
20 | | -/// `cargo run -- test file://...`) before `cargo test`. |
| 12 | +/// Safe for concurrent callers racing to populate a cold cache (two |
| 13 | +/// formwatch processes started at once on a machine with no Chrome yet, or |
| 14 | +/// `cargo test`'s default test parallelism on a machine without system |
| 15 | +/// Chrome): each downloads into its own private temp directory, then |
| 16 | +/// atomically renames it into place. Whichever caller's `fs::rename` lands |
| 17 | +/// first wins; every other caller's rename fails (the destination now |
| 18 | +/// exists and is non-empty), which is exactly the signal to discard its |
| 19 | +/// own copy and defer to the winner. No lock file needed — the |
| 20 | +/// atomicity of a same-filesystem rename provides the race-safety. |
21 | 21 | async fn fetch_chrome() -> Result<PathBuf> { |
22 | 22 | let home = std::env::var("HOME").context("HOME is not set")?; |
23 | 23 | let cache_dir = PathBuf::from(home).join(".cache/formwatch/chrome"); |
24 | | - std::fs::create_dir_all(&cache_dir).context("creating chrome cache dir")?; |
25 | | - let already_cached = cache_dir |
26 | | - .read_dir() |
27 | | - .map(|mut d| d.next().is_some()) |
28 | | - .unwrap_or(false); |
29 | | - if !already_cached { |
| 24 | + |
| 25 | + if !already_downloaded(&cache_dir) { |
30 | 26 | eprintln!( |
31 | 27 | "No Chrome/Chromium found — downloading one to {} (first run only)...", |
32 | 28 | cache_dir.display() |
33 | 29 | ); |
| 30 | + download_into(&cache_dir).await?; |
34 | 31 | } |
| 32 | + |
| 33 | + // Whether we just won the race, lost it, or the cache was already warm, |
| 34 | + // BrowserFetcher::fetch() against the now-populated cache_dir is a |
| 35 | + // local-only existence check (no network) that resolves the final |
| 36 | + // executable path — see chromiumoxide_fetcher's BrowserFetcher::local(). |
| 37 | + fetch_at(&cache_dir).await |
| 38 | +} |
| 39 | + |
| 40 | +fn already_downloaded(cache_dir: &Path) -> bool { |
| 41 | + cache_dir |
| 42 | + .read_dir() |
| 43 | + .map(|mut d| d.next().is_some()) |
| 44 | + .unwrap_or(false) |
| 45 | +} |
| 46 | + |
| 47 | +async fn fetch_at(path: &Path) -> Result<PathBuf> { |
35 | 48 | let opts = BrowserFetcherOptions::builder() |
36 | | - .with_path(&cache_dir) |
| 49 | + .with_path(path) |
37 | 50 | .build() |
38 | 51 | .map_err(|e| anyhow::anyhow!(e))?; |
39 | | - let fetcher = BrowserFetcher::new(opts); |
40 | | - let info = fetcher.fetch().await.context("failed to download Chrome")?; |
| 52 | + let info = BrowserFetcher::new(opts) |
| 53 | + .fetch() |
| 54 | + .await |
| 55 | + .context("failed to download Chrome")?; |
41 | 56 | Ok(info.executable_path) |
42 | 57 | } |
43 | 58 |
|
| 59 | +/// Downloads into a private, unique directory next to `cache_dir`, then |
| 60 | +/// hands it to [`install_or_discard`] to atomically become `cache_dir` — |
| 61 | +/// or to be thrown away if a racing caller already got there first. |
| 62 | +async fn download_into(cache_dir: &Path) -> Result<()> { |
| 63 | + let parent = cache_dir |
| 64 | + .parent() |
| 65 | + .context("chrome cache dir has no parent")?; |
| 66 | + std::fs::create_dir_all(parent).context("creating chrome cache dir's parent")?; |
| 67 | + |
| 68 | + let nanos = SystemTime::now() |
| 69 | + .duration_since(UNIX_EPOCH) |
| 70 | + .map(|d| d.as_nanos()) |
| 71 | + .unwrap_or(0); |
| 72 | + let tmp = parent.join(format!(".chrome-download-{}-{nanos}", std::process::id())); |
| 73 | + let _ = std::fs::remove_dir_all(&tmp); // stale leftover from a crashed prior run, if any |
| 74 | + |
| 75 | + fetch_at(&tmp).await?; |
| 76 | + install_or_discard(&tmp, cache_dir); |
| 77 | + Ok(()) |
| 78 | +} |
| 79 | + |
| 80 | +/// Moves a completed download from `tmp` into `dest`. If `dest` already |
| 81 | +/// exists (a racing caller's download won first), the rename fails — |
| 82 | +/// that failure is the race signal, not a real error — so `tmp` is |
| 83 | +/// discarded instead, leaving the winner's `dest` untouched. |
| 84 | +fn install_or_discard(tmp: &Path, dest: &Path) { |
| 85 | + if std::fs::rename(tmp, dest).is_err() { |
| 86 | + let _ = std::fs::remove_dir_all(tmp); |
| 87 | + } |
| 88 | +} |
| 89 | + |
44 | 90 | async fn build_config(headful: bool) -> Result<BrowserConfig> { |
45 | 91 | let mut builder = BrowserConfig::builder(); |
46 | 92 | if headful { |
@@ -98,3 +144,58 @@ pub async fn open(browser: &Browser, url: &str) -> Result<Page> { |
98 | 144 | } |
99 | 145 | Ok(page) |
100 | 146 | } |
| 147 | + |
| 148 | +#[cfg(test)] |
| 149 | +mod tests { |
| 150 | + use super::*; |
| 151 | + |
| 152 | + #[test] |
| 153 | + fn install_or_discard_moves_tmp_into_place_when_nothing_won_the_race() { |
| 154 | + let base = std::env::temp_dir().join("formwatch-test-install-or-discard-clean"); |
| 155 | + let _ = std::fs::remove_dir_all(&base); |
| 156 | + let tmp = base.join("tmp"); |
| 157 | + let dest = base.join("dest"); |
| 158 | + std::fs::create_dir_all(&tmp).expect("create tmp"); |
| 159 | + std::fs::write(tmp.join("chrome"), b"the download").expect("write marker file"); |
| 160 | + |
| 161 | + install_or_discard(&tmp, &dest); |
| 162 | + |
| 163 | + assert!(!tmp.exists(), "tmp should have been moved, not left behind"); |
| 164 | + assert_eq!( |
| 165 | + std::fs::read(dest.join("chrome")).expect("dest should contain the download"), |
| 166 | + b"the download" |
| 167 | + ); |
| 168 | + |
| 169 | + let _ = std::fs::remove_dir_all(&base); |
| 170 | + } |
| 171 | + |
| 172 | + #[test] |
| 173 | + fn install_or_discard_defers_to_a_dest_that_already_won_the_race() { |
| 174 | + // Simulates losing the race: `dest` was already populated (by |
| 175 | + // another caller's `install_or_discard`) by the time this one |
| 176 | + // runs. The loser's `tmp` must be discarded, and the winner's |
| 177 | + // `dest` must survive untouched — not merged, not corrupted. |
| 178 | + let base = std::env::temp_dir().join("formwatch-test-install-or-discard-race"); |
| 179 | + let _ = std::fs::remove_dir_all(&base); |
| 180 | + let tmp = base.join("tmp"); |
| 181 | + let dest = base.join("dest"); |
| 182 | + std::fs::create_dir_all(&tmp).expect("create tmp"); |
| 183 | + std::fs::write(tmp.join("chrome"), b"the loser's download").expect("write marker file"); |
| 184 | + std::fs::create_dir_all(&dest).expect("create dest"); |
| 185 | + std::fs::write(dest.join("chrome"), b"the winner's download").expect("write marker file"); |
| 186 | + |
| 187 | + install_or_discard(&tmp, &dest); |
| 188 | + |
| 189 | + assert!( |
| 190 | + !tmp.exists(), |
| 191 | + "the losing tmp dir should be discarded, not left behind" |
| 192 | + ); |
| 193 | + assert_eq!( |
| 194 | + std::fs::read(dest.join("chrome")).expect("dest should be untouched"), |
| 195 | + b"the winner's download", |
| 196 | + "the winner's already-installed download must survive unchanged" |
| 197 | + ); |
| 198 | + |
| 199 | + let _ = std::fs::remove_dir_all(&base); |
| 200 | + } |
| 201 | +} |
0 commit comments