#![allow(clippy::missing_panics_doc, clippy::must_use_candidate)]
use std::path::{Path, PathBuf};
use std::time::Duration;
use futures_lite::io::AsyncReadExt;
use heel::HeelBinary;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use zenwave::Client as _;
#[derive(Debug, Deserialize)]
struct Pin {
tool: String,
target: PinTarget,
url: String,
size: u64,
executable_sha256: String,
}
#[derive(Debug, Deserialize)]
struct PinTarget {
os: String,
arch: String,
}
#[derive(Debug, Deserialize)]
struct Manifest {
host_programs: Vec<Pin>,
}
const ATTEMPTS: u32 = 4;
const ATTEMPT_TIMEOUT: Duration = Duration::from_secs(60);
pub async fn binary() -> anyhow::Result<HeelBinary> {
if std::env::var_os("HEEL_BIN").is_some() {
return Ok(blocking::unblock(HeelBinary::locate).await?);
}
let path = pinned().await?;
Ok(blocking::unblock(move || HeelBinary::verify(path)).await?)
}
fn target_dir() -> PathBuf {
std::env::var_os("CARGO_TARGET_DIR").map_or_else(
|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target"),
PathBuf::from,
)
}
fn pin() -> anyhow::Result<Pin> {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("test-heel.json");
let manifest: Manifest = serde_json::from_slice(&std::fs::read(path)?)?;
let (os, arch) = (std::env::consts::OS, std::env::consts::ARCH);
let mut pins = manifest
.host_programs
.into_iter()
.filter(|pin| pin.tool == "heel" && pin.target.os == os && pin.target.arch == arch);
let pin = pins
.next()
.ok_or_else(|| anyhow::anyhow!("no heel is pinned for {os} {arch}"))?;
anyhow::ensure!(
pins.next().is_none(),
"heel is pinned twice for {os} {arch}"
);
Ok(pin)
}
async fn pinned() -> anyhow::Result<PathBuf> {
let pin = pin()?;
let name = if cfg!(windows) { "heel.exe" } else { "heel" };
let directory = target_dir()
.join("aither-test-tools/bin")
.join(&pin.executable_sha256);
let path = directory.join(name);
if path.is_file() {
return Ok(path);
}
let bytes = download(&pin).await?;
anyhow::ensure!(
hex::encode(Sha256::digest(&bytes)) == pin.executable_sha256,
"the downloaded heel does not match its pinned digest"
);
blocking::unblock(move || store(&directory, &path, &bytes)).await
}
fn holds(path: &Path, bytes: &[u8]) -> bool {
std::fs::read(path).is_ok_and(|have| have == bytes)
}
fn store(directory: &Path, path: &Path, bytes: &[u8]) -> anyhow::Result<PathBuf> {
std::fs::create_dir_all(directory)?;
if holds(path, bytes) {
return Ok(path.to_path_buf());
}
let partial = directory.join(format!("partial-{}", std::process::id()));
std::fs::write(&partial, bytes)?;
#[cfg(unix)]
std::fs::set_permissions(
&partial,
std::os::unix::fs::PermissionsExt::from_mode(0o755),
)?;
let renamed = std::fs::rename(&partial, path);
if let Err(error) = renamed {
let identical = holds(path, bytes);
std::fs::remove_file(&partial)?;
anyhow::ensure!(
identical,
"cannot place the pinned heel at {}: {error}",
path.display()
);
}
Ok(path.to_path_buf())
}
async fn download(pin: &Pin) -> anyhow::Result<Vec<u8>> {
let mut backoff = Duration::from_secs(1);
let mut attempt = 1;
loop {
match download_once(pin).await {
Err(error) if attempt < ATTEMPTS => {
tracing::warn!(%error, attempt, "heel download failed; retrying");
async_io::Timer::after(backoff).await;
backoff *= 2;
attempt += 1;
}
result => return result,
}
}
}
async fn download_once(pin: &Pin) -> anyhow::Result<Vec<u8>> {
futures_lite::future::or(
async {
let response = zenwave::client().get(pin.url.as_str())?.await?;
anyhow::ensure!(
response.status().is_success(),
"{} answered {}",
pin.url,
response.status()
);
let mut bytes = Vec::new();
response
.into_body()
.into_reader()
.take(pin.size.saturating_add(1))
.read_to_end(&mut bytes)
.await?;
anyhow::ensure!(
bytes.len() as u64 == pin.size,
"the downloaded heel is {} bytes, pinned at {}",
bytes.len(),
pin.size
);
Ok(bytes)
},
async {
async_io::Timer::after(ATTEMPT_TIMEOUT).await;
anyhow::bail!("downloading {} timed out", pin.url)
},
)
.await
}