use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::tools::shell::ProgramOutcome;
use crate::util::http::{DownloadSizeCheck, build_download_client, download_verified};
const LAST_KNOWN_GOOD: &str = "https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json";
const VERSION_TIMEOUT: Duration = Duration::from_secs(60);
static INSTALLING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static IN_USE: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
const UNPROVEN: &str = ".unproven";
const DOES_NOT_RUN: &str = "the browser build does not run on this machine";
pub(super) struct Shell {
pub(super) binary: PathBuf,
_held: tokio::sync::RwLockReadGuard<'static, ()>,
}
#[derive(Debug)]
pub(super) enum Unavailable {
Missing(String),
Unchecked(String),
}
enum Unproven {
Stopped(String),
DoesNotRun,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct ChromeVersion([u64; 4]);
impl ChromeVersion {
fn parse(text: &str) -> Option<Self> {
let mut parts = text.trim().split('.');
let mut numbers = [0_u64; 4];
for number in &mut numbers {
*number = parts.next()?.parse().ok()?;
}
if parts.next().is_some() {
return None;
}
Some(Self(numbers))
}
fn spelling(self) -> String {
format!("{}.{}.{}.{}", self.0[0], self.0[1], self.0[2], self.0[3])
}
}
#[must_use]
fn platform_for(os: &str, arch: &str) -> Option<&'static str> {
Some(match (os, arch) {
("macos", "x86_64") => "mac-x64",
("macos", "aarch64") => "mac-arm64",
("linux", "x86_64") => "linux64",
("linux", "aarch64") => "linux-arm64",
("windows", "x86_64" | "aarch64") => "win64",
_ => return None,
})
}
#[must_use]
fn platform() -> Option<&'static str> {
let (os, arch) = crate::util::managed_bin::host_os_arch().ok()?;
platform_for(os, arch)
}
const fn binary_name() -> &'static str {
if cfg!(target_os = "windows") {
"chrome-headless-shell.exe"
} else {
"chrome-headless-shell"
}
}
fn root() -> Result<PathBuf, String> {
let root = crate::config::default_config_dir()
.map(|dir| dir.join("chrome-headless-shell"))
.map_err(|_| "the product's configuration directory is unavailable".to_string())?;
fs::create_dir_all(&root).map_err(|e| {
format!(
"the product's browser directory could not be created ({})",
e.kind()
)
})?;
Ok(root)
}
fn cached(root: &Path, platform: &str) -> Vec<(ChromeVersion, PathBuf)> {
let folder = format!("chrome-headless-shell-{platform}");
let mut copies = Vec::new();
for entry in fs::read_dir(root).into_iter().flatten().flatten() {
let Ok(name) = entry.file_name().into_string() else {
continue;
};
let Some(version) = ChromeVersion::parse(&name) else {
continue;
};
let binary = entry.path().join(&folder).join(binary_name());
if crate::util::is_executable(&binary) {
copies.push((version, binary));
}
}
copies.sort_by_key(|(version, _)| std::cmp::Reverse(*version));
copies
}
async fn usable(root: &Path, platform: &str) -> Result<Option<PathBuf>, Unavailable> {
let mut stopped = None;
for (version, binary) in cached(root, platform) {
if recorded_unproven(root, version).is_some() {
continue;
}
match prove_it_runs(&binary, root).await {
Ok(()) => return Ok(Some(binary)),
Err(Unproven::DoesNotRun) => record_unproven(root, version, DOES_NOT_RUN),
Err(Unproven::Stopped(reason)) => {
stopped.get_or_insert(reason);
}
}
}
match stopped {
Some(reason) => Err(Unavailable::Unchecked(reason)),
None => Ok(None),
}
}
async fn shell_in_use(root: &Path, platform: &str) -> Result<Option<Shell>, Unavailable> {
let held = IN_USE.read().await;
Ok(usable(root, platform).await?.map(|binary| Shell {
binary,
_held: held,
}))
}
fn prune(root: &Path, keep: ChromeVersion) {
let kept = keep.spelling();
for entry in fs::read_dir(root).into_iter().flatten().flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if name != kept && name != UNPROVEN && !name.starts_with(".install-") {
crate::util::managed_bin::remove_any(&entry.path());
}
}
}
fn unproven_record(root: &Path) -> Option<(ChromeVersion, String)> {
let body = fs::read_to_string(root.join(UNPROVEN)).ok()?;
let (failed, reason) = body.split_once('\n')?;
Some((
ChromeVersion::parse(failed.trim())?,
reason.trim().to_string(),
))
}
fn recorded_unproven(root: &Path, version: ChromeVersion) -> Option<String> {
unproven_record(root)
.filter(|(recorded, _)| *recorded == version)
.map(|(_, reason)| reason)
}
fn record_unproven(root: &Path, version: ChromeVersion, reason: &str) {
let _ = fs::write(
root.join(UNPROVEN),
format!("{}\n{reason}", version.spelling()),
);
}
fn drop_unproven(root: &Path) {
if let Some((version, _)) = unproven_record(root) {
let _ = fs::remove_dir_all(root.join(version.spelling()));
}
}
pub(super) async fn ensure_shell() -> Result<Shell, Unavailable> {
let platform = platform()
.ok_or_else(|| Unavailable::Missing("this platform is not supported".to_string()))?;
let root = root().map_err(Unavailable::Missing)?;
super::reclaim_scratch(&root);
if let Ok(_swap) = IN_USE.try_write() {
super::reclaim_aside(&root);
drop_unproven(&root);
}
if let Some(shell) = shell_in_use(&root, platform).await? {
return Ok(shell);
}
let _queue = INSTALLING.lock().await;
if let Some(shell) = shell_in_use(&root, platform).await? {
return Ok(shell);
}
let client = build_download_client(super::DOWNLOAD_TIMEOUT)
.map_err(|_| Unavailable::Missing("the download client could not be built".to_string()))?;
let (version, url) = stable_build(&client, platform)
.await
.map_err(Unavailable::Missing)?;
if let Some(reason) = recorded_unproven(&root, version) {
return Err(Unavailable::Missing(reason));
}
let binary = install_build(&client, &root, platform, version, &url).await?;
Ok(Shell {
binary,
_held: IN_USE.read().await,
})
}
async fn stable_build(
client: &reqwest::Client,
platform: &str,
) -> Result<(ChromeVersion, String), String> {
use crate::util::managed_bin::request_reason;
let response = client.get(LAST_KNOWN_GOOD).send().await.map_err(|e| {
format!(
"the browser build list request failed: {}",
request_reason(&e)
)
})?;
if !response.status().is_success() {
return Err(format!(
"the browser build list got HTTP {}",
response.status()
));
}
let body = response.text().await.map_err(|e| {
format!(
"the browser build list could not be read: {}",
request_reason(&e)
)
})?;
let listing = serde_json::from_str::<serde_json::Value>(&body)
.map_err(|_| "the browser build list was not the expected document".to_string())?;
let stable = listing
.pointer("/channels/Stable")
.ok_or_else(|| "the browser build list carries no stable channel".to_string())?;
let version = stable
.get("version")
.and_then(|v| v.as_str())
.and_then(ChromeVersion::parse)
.ok_or_else(|| "the stable channel's answer carries no version".to_string())?;
let url = stable
.get("downloads")
.and_then(|downloads| downloads.get("chrome-headless-shell"))
.and_then(|builds| builds.as_array())
.and_then(|builds| {
builds
.iter()
.find(|build| build.get("platform").and_then(|p| p.as_str()) == Some(platform))
})
.and_then(|build| build.get("url"))
.and_then(|url| url.as_str())
.ok_or_else(|| "the browser build list carries no build for this platform".to_string())?;
Ok((version, url.to_string()))
}
async fn install_build(
client: &reqwest::Client,
root: &Path,
platform: &str,
version: ChromeVersion,
url: &str,
) -> Result<PathBuf, Unavailable> {
let work = super::scratch(root).map_err(Unavailable::Missing)?;
let archive = work.path().join("chrome-headless-shell.zip");
download_verified(
client,
url,
&archive,
"",
None,
DownloadSizeCheck::None,
|_, _| {},
)
.await
.map_err(|e| {
Unavailable::Missing(format!(
"the browser build could not be downloaded: {}",
crate::util::managed_bin::download_reason(&e)
))
})?;
let extracted = work.path().join("extracted");
fs::create_dir_all(&extracted).map_err(|e| {
Unavailable::Missing(format!(
"the browser build could not be unpacked ({})",
e.kind()
))
})?;
crate::util::managed_bin::extract_tree_zip(&archive, &extracted).map_err(|reason| {
Unavailable::Missing(format!("the browser build could not be unpacked: {reason}"))
})?;
let folder = format!("chrome-headless-shell-{platform}");
let binary = extracted.join(&folder).join(binary_name());
if !binary.is_file() {
return Err(Unavailable::Missing(
"the browser archive carries no binary".to_string(),
));
}
crate::util::managed_bin::set_executable(&binary).map_err(Unavailable::Missing)?;
if let Err(unproven) = prove_it_runs(&binary, work.path()).await {
return Err(refused(root, version, &folder, &extracted, unproven).await);
}
let placed = place(root, version, &folder, &extracted).await?;
let _ = fs::remove_file(root.join(UNPROVEN));
Ok(placed)
}
async fn refused(
root: &Path,
version: ChromeVersion,
folder: &str,
tree: &Path,
unproven: Unproven,
) -> Unavailable {
match unproven {
Unproven::DoesNotRun => {
record_unproven(root, version, DOES_NOT_RUN);
Unavailable::Missing(DOES_NOT_RUN.to_string())
}
Unproven::Stopped(reason) => {
let _ = place(root, version, folder, tree).await;
Unavailable::Unchecked(reason)
}
}
}
async fn place(
root: &Path,
version: ChromeVersion,
folder: &str,
tree: &Path,
) -> Result<PathBuf, Unavailable> {
let placed = root.join(version.spelling());
let _swap = IN_USE.write().await;
crate::util::managed_bin::place_staged_tree(tree, &placed).map_err(Unavailable::Missing)?;
prune(root, version);
Ok(placed.join(folder).join(binary_name()))
}
async fn prove_it_runs(binary: &Path, cwd: &Path) -> Result<(), Unproven> {
let args = vec!["--version".to_string()];
let outcome = crate::tools::shell::run_internal_program_outcome(
cwd,
binary,
&args,
&[],
Some(VERSION_TIMEOUT),
)
.await;
proof_verdict(&outcome)
}
fn proof_verdict(outcome: &ProgramOutcome) -> Result<(), Unproven> {
if outcome.stopped() {
return Err(Unproven::Stopped(outcome.detail.clone()));
}
if !outcome.success
|| !outcome
.output
.trim_start()
.starts_with("Google Chrome for Testing")
{
return Err(Unproven::DoesNotRun);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn platform_for_maps_each_published_platform() {
assert_eq!(platform_for("macos", "x86_64"), Some("mac-x64"));
assert_eq!(platform_for("macos", "aarch64"), Some("mac-arm64"));
assert_eq!(platform_for("linux", "x86_64"), Some("linux64"));
assert_eq!(platform_for("linux", "aarch64"), Some("linux-arm64"));
assert_eq!(platform_for("windows", "x86_64"), Some("win64"));
assert_eq!(platform_for("windows", "aarch64"), Some("win64"));
assert_eq!(platform_for("linux", "armv7l"), None);
assert_eq!(platform_for("windows", "arm64ec"), None);
assert_eq!(platform_for("freebsd", "x86_64"), None);
}
#[test]
fn chrome_version_orders_four_numeric_components() {
let older = ChromeVersion::parse("141.0.7390.54").expect("a version");
let newer = ChromeVersion::parse("142.0.7444.175").expect("a version");
assert!(older < newer);
assert_eq!(newer.spelling(), "142.0.7444.175");
assert_eq!(ChromeVersion::parse("142.0.7444"), None);
assert_eq!(ChromeVersion::parse("142.0.7444.175.1"), None);
assert_eq!(ChromeVersion::parse("stable"), None);
}
#[test]
fn a_swap_keeps_the_new_build_and_drops_the_rest() {
let root = tempfile::tempdir().unwrap();
for name in ["150.0.1.0", "151.0.1.0", "150.0.1.0.old"] {
fs::create_dir_all(root.path().join(name)).unwrap();
}
fs::write(root.path().join(UNPROVEN), "150.0.1.0\n").unwrap();
prune(root.path(), ChromeVersion::parse("151.0.1.0").unwrap());
assert!(
root.path().join("151.0.1.0").exists(),
"the new build stays"
);
for gone in ["150.0.1.0", "150.0.1.0.old"] {
assert!(!root.path().join(gone).exists(), "{gone} goes");
}
assert!(
root.path().join(UNPROVEN).exists(),
"the record is not a build and is not swept"
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_cached_copy_is_proved_at_use() {
use std::os::unix::fs::PermissionsExt as _;
let root = tempfile::tempdir().unwrap();
let platform = "linux64";
let write = |version: &str, body: &str| {
let dir = root
.path()
.join(version)
.join(format!("chrome-headless-shell-{platform}"));
fs::create_dir_all(&dir).unwrap();
let binary = dir.join(binary_name());
fs::write(&binary, body).unwrap();
fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)).unwrap();
};
write("150.0.1.0", "#!/bin/sh\nexit 1\n");
assert!(
usable(root.path(), platform).await.ok().flatten().is_none(),
"a copy that does not answer is not used"
);
let dead = ChromeVersion::parse("150.0.1.0").expect("a version");
assert!(
recorded_unproven(root.path(), dead).is_some(),
"a copy that does not run is remembered, so it is never spawned again"
);
assert!(
root.path().join("150.0.1.0").exists(),
"the proof itself deletes nothing: no relocation happens where a render may be launching"
);
drop_unproven(root.path());
assert!(
!root.path().join("150.0.1.0").exists(),
"a copy that does not run is not kept either"
);
write(
"151.0.1.0",
"#!/bin/sh\necho 'Google Chrome for Testing 151.0.1.0'\n",
);
let binary = usable(root.path(), platform)
.await
.expect("the proof completes")
.expect("the copy that answers is used");
assert!(
binary.ends_with("chrome-headless-shell"),
"got: {}",
binary.display()
);
write("152.0.1.0", "#!/bin/sh\nexit 1\n");
let binary = usable(root.path(), platform)
.await
.expect("the proof completes")
.expect("the older copy that answers is still used");
assert!(
binary.starts_with(root.path().join("151.0.1.0")),
"got: {}",
binary.display()
);
}
#[test]
fn a_stop_is_never_the_builds_verdict() {
let run =
|success: bool, output: &str, stop: Option<crate::tools::shell::Stop>| ProgramOutcome {
success,
detail: "the machine's own reason".to_string(),
output: output.to_string(),
has_output: !output.is_empty(),
stop,
};
assert!(proof_verdict(&run(true, "Google Chrome for Testing 151.0.1.0\n", None)).is_ok());
assert!(matches!(
proof_verdict(&run(true, "Chrome 1.0\n", None)),
Err(Unproven::DoesNotRun)
));
assert!(matches!(
proof_verdict(&run(false, "", None)),
Err(Unproven::DoesNotRun)
));
for stop in [
crate::tools::shell::Stop::Spawn,
crate::tools::shell::Stop::Memory,
] {
let Err(Unproven::Stopped(reason)) = proof_verdict(&run(false, "", Some(stop))) else {
panic!("{stop:?} is a stop, not the build's verdict");
};
assert_eq!(reason, "the machine's own reason");
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_cached_copy_the_product_could_not_start_is_passed_over() {
let root = tempfile::tempdir().unwrap();
let platform = "linux64";
let write = |version: &str, body: &str| {
let dir = root
.path()
.join(version)
.join(format!("chrome-headless-shell-{platform}"));
fs::create_dir_all(&dir).unwrap();
let binary = dir.join(binary_name());
fs::write(&binary, body).unwrap();
crate::util::managed_bin::set_executable(&binary).unwrap();
};
write("153.0.1.0", "#!/nonexistent/hyperframes-test\n");
write(
"152.0.1.0",
"#!/bin/sh\necho 'Google Chrome for Testing 152.0.1.0'\n",
);
let binary = usable(root.path(), platform)
.await
.expect("the proof completes")
.expect("the older copy that answers is used");
assert!(
binary.starts_with(root.path().join("152.0.1.0")),
"got: {}",
binary.display()
);
assert!(
recorded_unproven(root.path(), ChromeVersion::parse("153.0.1.0").unwrap()).is_none(),
"a build we could not start is not a build that does not run"
);
assert!(
root.path().join("153.0.1.0").exists(),
"the copy is kept for the next attempt"
);
}
#[tokio::test]
async fn a_stopped_proof_keeps_the_build_and_a_wrong_one_is_remembered() {
let root = tempfile::tempdir().unwrap();
let platform = "linux64";
let folder = format!("chrome-headless-shell-{platform}");
let version = ChromeVersion::parse("151.0.1.0").expect("a version");
let unpack = |name: &str| {
let tree = root.path().join(name);
let dir = tree.join(&folder);
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join(binary_name()), "a build").unwrap();
tree
};
let answer = refused(
root.path(),
version,
&folder,
&unpack("first"),
Unproven::Stopped("terminated: exceeded memory limit (used ~2 GiB)".to_string()),
)
.await;
assert!(matches!(answer, Unavailable::Unchecked(_)));
assert!(
root.path()
.join(version.spelling())
.join(&folder)
.join(binary_name())
.is_file(),
"the build stays in the cache"
);
assert!(
recorded_unproven(root.path(), version).is_none(),
"a stop is the product's verdict, never the build's"
);
let answer = refused(
root.path(),
version,
&folder,
&unpack("second"),
Unproven::DoesNotRun,
)
.await;
assert!(matches!(answer, Unavailable::Missing(_)));
assert_eq!(
recorded_unproven(root.path(), version).as_deref(),
Some(DOES_NOT_RUN)
);
let newer = ChromeVersion::parse("152.0.1.0").expect("a version");
assert_eq!(
recorded_unproven(root.path(), newer),
None,
"a build that did not run is remembered for that build only"
);
}
}