use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use semver::Version;
use crate::util::UnwrapPoison;
use crate::util::managed_bin;
const TAG_PREFIX: &str = "ffmpeg-v";
const REVISION_MARKER: &str = "-mahbot.";
pub(super) const RELEASES_URL_ENV: &str = "MAHBOT_FFMPEG_RELEASES_URL";
const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
const LISTING_SUBJECT: &str = "the ffmpeg release listing";
const LICENCE_AND_SOURCE: [&str; 2] = ["LICENCE.txt", "SOURCE.txt"];
const COMPONENT_NOTICES: &str = "LICENCES.txt";
const fn ffmpeg_file() -> &'static str {
if cfg!(windows) {
"ffmpeg.exe"
} else {
"ffmpeg"
}
}
const fn ffprobe_file() -> &'static str {
if cfg!(windows) {
"ffprobe.exe"
} else {
"ffprobe"
}
}
#[must_use]
fn parse_tag(name: &str) -> Option<(semver::Version, u32)> {
let rest = name.strip_prefix(TAG_PREFIX)?;
let (upstream, revision) = rest.split_once(REVISION_MARKER)?;
Some((
managed_bin::parse_short_version(upstream)?,
revision.parse().ok()?,
))
}
struct Build {
tag: String,
upstream: Version,
}
#[must_use]
fn asset_name(tag: &str, os: &str, arch: &str) -> String {
let stem = tag.strip_prefix(TAG_PREFIX).unwrap_or(tag);
let extension = if os == "windows" { "zip" } else { "tar.gz" };
format!("ffmpeg-{stem}-{os}-{arch}.{extension}")
}
#[derive(Debug)]
pub(crate) struct Binaries {
pub(crate) ffmpeg: PathBuf,
pub(crate) ffprobe: PathBuf,
}
#[cfg(test)]
pub(crate) const ROOT_ENV: &str = "MAHBOT_FFMPEG_ROOT";
#[cfg_attr(
test,
expect(clippy::unnecessary_wraps, reason = "the test root always resolves")
)]
fn root() -> Result<PathBuf, String> {
#[cfg(test)]
let dir = std::env::var_os(ROOT_ENV).map_or_else(
|| crate::util::test::test_root().join("ffmpeg"),
PathBuf::from,
);
#[cfg(not(test))]
let dir = crate::config::default_config_dir()
.map_err(|_| "the product's configuration directory is unavailable".to_string())?
.join("ffmpeg");
Ok(dir)
}
fn chosen(root: &Path) -> Option<(Build, Binaries)> {
fs::read_dir(root)
.ok()?
.flatten()
.filter_map(|entry| {
let tag = entry.file_name().into_string().ok()?;
let rank = parse_tag(&tag)?;
let binaries = binaries_at(&entry.path())?;
Some((rank, tag, binaries))
})
.max_by(|(left, _, _), (right, _, _)| left.cmp(right))
.map(|((upstream, _), tag, binaries)| (Build { tag, upstream }, binaries))
}
fn binaries_in(dir: &Path) -> Binaries {
let bin = dir.join("bin");
Binaries {
ffmpeg: bin.join(ffmpeg_file()),
ffprobe: bin.join(ffprobe_file()),
}
}
fn binaries_at(dir: &Path) -> Option<Binaries> {
let binaries = binaries_in(dir);
(crate::util::is_executable(&binaries.ffmpeg) && crate::util::is_executable(&binaries.ffprobe))
.then_some(binaries)
}
pub(crate) fn installed() -> Option<Binaries> {
chosen(&root().ok()?).map(|(_, binaries)| binaries)
}
static INSTALLING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static ATTEMPT_FAILURE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
async fn installing<T, E>(attempt: impl AsyncFnOnce() -> Result<T, E>) -> Result<T, E> {
let _queue = INSTALLING.lock().await;
attempt().await
}
pub(super) async fn ensure_installed() -> Result<Binaries, String> {
let root = root()?;
if let Some((_, binaries)) = chosen(&root) {
return Ok(binaries);
}
let tag = installing(async || {
if let Some((build, _)) = chosen(&root) {
return Ok(build.tag);
}
if let Some(reason) = ATTEMPT_FAILURE.lock().unwrap_poison().clone() {
return Err(reason);
}
let build = newest().await.map_err(recorded)?;
install(&root, &build).await.map_err(recorded)?;
Ok(build.tag)
})
.await?;
Ok(binaries_in(&root.join(tag)))
}
#[derive(Debug)]
enum Standing {
Working(String),
Damaged(String),
Missing,
}
#[derive(Debug)]
struct Failure {
reason: String,
standing: Standing,
}
pub async fn install_on_start() {
match update().await {
Ok(None) => tracing::debug!("ffmpeg needs nothing at this start"),
Ok(Some(tag)) => tracing::info!("ffmpeg {tag} installed"),
Err(failure) => report_failure(&failure),
}
}
fn report_failure(failure: &Failure) {
let reason = &failure.reason;
match &failure.standing {
Standing::Damaged(tag) => tracing::warn!(
"ffmpeg {tag} is damaged and could not be replaced (retried on the next \
start): {reason}"
),
Standing::Working(tag) => tracing::warn!(
"ffmpeg is running {tag}; the newest build is not installed (retried on the \
next start): {reason}"
),
Standing::Missing => {
tracing::warn!("ffmpeg is not installed (retried on the next start): {reason}");
}
}
}
async fn standing(root: &Path) -> Standing {
match chosen(root) {
Some((in_use, binaries)) if proves_itself(&binaries, &in_use.upstream).await => {
Standing::Working(in_use.tag)
}
Some((in_use, _)) => Standing::Damaged(in_use.tag),
None => Standing::Missing,
}
}
async fn update() -> Result<Option<String>, Failure> {
let root = root().map_err(|reason| Failure {
reason,
standing: Standing::Missing,
})?;
installing(async || {
let current = standing(&root).await;
let build = match newest().await {
Ok(build) => build,
Err(reason) => {
return match current {
Standing::Working(tag) => {
tracing::debug!("keeping ffmpeg {tag}: {reason}");
Ok(None)
}
other => Err(Failure {
reason: recorded(reason),
standing: other,
}),
};
}
};
if let Standing::Working(tag) = ¤t
&& tag == &build.tag
{
return Ok(None);
}
install(&root, &build).await.map_err(|reason| Failure {
reason: recorded(reason),
standing: current,
})?;
Ok(Some(build.tag))
})
.await
}
async fn proves_itself(binaries: &Binaries, upstream: &Version) -> bool {
reports_upstream(&binaries.ffmpeg, upstream).await
&& reports_upstream(&binaries.ffprobe, upstream).await
}
fn recorded(reason: String) -> String {
*ATTEMPT_FAILURE.lock().unwrap_poison() = Some(reason.clone());
reason
}
#[cfg(test)]
pub(super) fn forget_failed_attempt() {
*ATTEMPT_FAILURE.lock().unwrap_poison() = None;
}
async fn newest() -> Result<Build, String> {
let (os, arch) = managed_bin::host_os_arch()?;
let base = stream_url("https://api.github.com/repos", "releases");
let mut newest: Option<((Version, u32), String)> = None;
for page in 1..=managed_bin::LISTING_PAGES {
let releases = managed_bin::release_page(&base, page, LISTING_SUBJECT)
.await?
.ok_or_else(|| {
format!("{LISTING_SUBJECT} could not be read: it is not a JSON array")
})?;
for release in &releases {
let Some(tag) = release["tag_name"].as_str() else {
continue;
};
let Some(rank) = parse_tag(tag) else {
continue;
};
let asset = asset_name(tag, os, arch);
let carries_ours = release["assets"]
.as_array()
.is_some_and(|assets| assets.iter().any(|a| a["name"].as_str() == Some(&asset)));
if !carries_ours || newest.as_ref().is_some_and(|(best, _)| best >= &rank) {
continue;
}
newest = Some((rank, tag.to_string()));
}
if releases.len() < managed_bin::LISTING_PAGE_SIZE {
break;
}
}
let ((upstream, _), tag) =
newest.ok_or_else(|| format!("no ffmpeg build is published for {os}-{arch}"))?;
Ok(Build { tag, upstream })
}
async fn install(root: &Path, build: &Build) -> Result<(), String> {
use crate::util::http::{DownloadSizeCheck, download_verified};
let (os, arch) = managed_bin::host_os_arch()?;
let tag = &build.tag;
let asset = asset_name(tag, os, arch);
let base = stream_url("https://github.com", "releases/download");
let sums = managed_bin::fetch_sha256_sums(
&format!("{base}/{tag}/SHA256SUMS"),
"the release's checksum file",
)
.await?;
let digest = managed_bin::sha256_for(&sums, &asset)
.ok_or_else(|| "the release carries no checksum for this platform's archive".to_string())?;
let downloads = root.join("downloads");
let _ = fs::remove_dir_all(&downloads);
fs::create_dir_all(&downloads)
.map_err(|e| format!("the download directory could not be created ({})", e.kind()))?;
let archive = downloads.join(&asset);
download_verified(
managed_bin::download_client()?,
&format!("{base}/{tag}/{asset}"),
&archive,
&digest,
None,
DownloadSizeCheck::Exact,
|_, _| {},
)
.await
.map_err(|e| {
format!(
"the ffmpeg release could not be downloaded: {}",
managed_bin::download_reason(&e)
)
})?;
let staging = tempfile::Builder::new()
.prefix(".staging-")
.tempdir_in(root)
.map_err(|e| format!("the staging directory could not be created ({})", e.kind()))?;
extract_into(&archive, staging.path())?;
let _ = fs::remove_dir_all(&downloads);
for (name, tool) in [("ffmpeg", ffmpeg_file()), ("ffprobe", ffprobe_file())] {
if !reports_upstream(&staging.path().join("bin").join(tool), &build.upstream).await {
return Err(format!(
"the downloaded {name} could not run, or does not report ffmpeg {}",
build.upstream
));
}
}
managed_bin::place_staged_tree(staging.path(), &root.join(tag))?;
prune(root, tag);
Ok(())
}
#[cfg_attr(
test,
expect(unused_variables, reason = "the test default names no host or path")
)]
fn stream_url(host: &str, path: &str) -> String {
#[cfg(not(test))]
let default = format!("{host}/{}/{path}", managed_bin::release_repo());
#[cfg(test)]
let default = "http://127.0.0.1:1".to_string();
std::env::var(RELEASES_URL_ENV).map_or(default, |base| base.trim_end_matches('/').to_string())
}
fn extract_into(archive: &Path, staging: &Path) -> Result<(), String> {
let bin_dir = staging.join("bin");
fs::create_dir_all(&bin_dir).map_err(|e| {
format!(
"the staged copy's directory could not be created ({})",
e.kind()
)
})?;
let tools = [ffmpeg_file(), ffprobe_file()];
let required = tools
.iter()
.copied()
.chain(LICENCE_AND_SOURCE)
.collect::<Vec<_>>();
let paths = extract(archive, staging, &required, &[COMPONENT_NOTICES])?;
for (name, path) in tools.into_iter().zip(&paths) {
managed_bin::set_executable(path)?;
fs::rename(path, bin_dir.join(name))
.map_err(|e| format!("the staged copy could not be arranged ({})", e.kind()))?;
}
Ok(())
}
fn extract(
archive: &Path,
dir: &Path,
required: &[&str],
optional: &[&str],
) -> Result<Vec<PathBuf>, String> {
if archive.extension().and_then(OsStr::to_str) == Some("zip") {
managed_bin::extract_named_files_zip(archive, dir, required, optional)
} else {
managed_bin::extract_named_files_tar_gz(archive, dir, required, optional)
}
}
fn banner_version(stdout: &[u8]) -> Option<Version> {
let text = String::from_utf8_lossy(stdout);
let line = text.lines().next()?;
let token = line
.split_whitespace()
.skip_while(|word| *word != "version")
.nth(1)?;
managed_bin::parse_short_version(token.split_once('-').map_or(token, |(head, _)| head))
}
async fn reports_upstream(bin: &Path, upstream: &Version) -> bool {
let Ok(output) = super::run_tool(bin, &["-version".into()], VERSION_TIMEOUT).await else {
return false;
};
output.success && banner_version(&output.stdout).as_ref() == Some(upstream)
}
fn prune(root: &Path, tag: &str) {
let Ok(entries) = fs::read_dir(root) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
if name == OsStr::new(tag) {
continue;
}
let path = entry.path();
if path.is_dir() {
let _ = fs::remove_dir_all(&path);
} else {
let _ = fs::remove_file(&path);
}
}
}
#[cfg(test)]
mod tests {
use std::io::Write as _;
#[cfg(unix)]
use std::{
collections::HashMap,
io::Read as _,
net::{TcpListener, TcpStream},
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
};
use super::*;
#[cfg(unix)]
use crate::ffmpeg::ReleasesHook;
#[cfg(unix)]
#[must_use]
struct EnvHeld {
_lock: std::sync::MutexGuard<'static, ()>,
}
#[cfg(unix)]
fn env_held() -> EnvHeld {
EnvHeld {
_lock: crate::util::test::env_lock().lock().unwrap_poison(),
}
}
fn install_fake(root: &Path, tag: &str) -> PathBuf {
let bin = root.join(tag).join("bin");
fs::create_dir_all(&bin).expect("create tag directory");
for tool in [ffmpeg_file(), ffprobe_file()] {
let path = bin.join(tool);
fs::write(&path, b"BIN").expect("write binary");
managed_bin::set_executable(&path).expect("make executable");
}
root.join(tag)
}
fn build(tag: &str) -> Build {
let (upstream, _) = parse_tag(tag).expect("a parsable tag");
Build {
tag: tag.to_string(),
upstream,
}
}
#[test]
fn every_platform_gets_its_own_archive() {
let tag = "ffmpeg-v7.1-mahbot.2";
assert_eq!(
asset_name(tag, "macos", "aarch64"),
"ffmpeg-7.1-mahbot.2-macos-aarch64.tar.gz"
);
assert_eq!(
asset_name(tag, "macos", "x86_64"),
"ffmpeg-7.1-mahbot.2-macos-x86_64.tar.gz"
);
assert_eq!(
asset_name(tag, "linux", "aarch64"),
"ffmpeg-7.1-mahbot.2-linux-aarch64.tar.gz"
);
assert_eq!(
asset_name(tag, "linux", "x86_64"),
"ffmpeg-7.1-mahbot.2-linux-x86_64.tar.gz"
);
assert_eq!(
asset_name(tag, "windows", "x86_64"),
"ffmpeg-7.1-mahbot.2-windows-x86_64.zip"
);
assert_eq!(
asset_name(tag, "windows", "aarch64"),
"ffmpeg-7.1-mahbot.2-windows-aarch64.zip"
);
}
#[test]
fn the_newest_copy_on_disk_is_the_one_in_use() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
install_fake(root, "ffmpeg-v6.0-mahbot.1");
install_fake(root, "ffmpeg-v7.1-mahbot.0");
install_fake(root, "ffmpeg-v7.2-mahbot.1");
fs::create_dir_all(root.join(".staging-Kd7x2p")).expect("create staging");
fs::create_dir(root.join("not-a-tag")).expect("create junk directory");
let (build, binaries) = chosen(root).expect("a copy is in use");
assert_eq!(build.tag, "ffmpeg-v7.2-mahbot.1");
assert_eq!(
binaries.ffmpeg,
root.join("ffmpeg-v7.2-mahbot.1")
.join("bin")
.join(ffmpeg_file())
);
install_fake(root, "ffmpeg-v7.2-mahbot.2");
assert_eq!(
chosen(root).expect("a copy is in use").0.tag,
"ffmpeg-v7.2-mahbot.2"
);
let broken = root.join("ffmpeg-v7.2-mahbot.2");
fs::remove_file(broken.join("bin").join(ffprobe_file())).expect("remove ffprobe");
assert_eq!(
chosen(root).expect("a copy is in use").0.tag,
"ffmpeg-v7.2-mahbot.1"
);
fs::remove_dir_all(root.join("ffmpeg-v7.2-mahbot.1")).expect("remove the newer build");
assert_eq!(
chosen(root).expect("a copy is in use").0.tag,
"ffmpeg-v7.1-mahbot.0"
);
}
#[test]
fn pruning_leaves_only_the_copy_just_installed() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
for tag in [
"ffmpeg-v6.0-mahbot.1",
"ffmpeg-v7.1-mahbot.0",
"ffmpeg-v7.1-mahbot.2",
] {
install_fake(root, tag);
}
fs::create_dir_all(root.join(".staging-Kd7x2p")).expect("create staging");
fs::create_dir_all(root.join("downloads")).expect("create downloads");
prune(root, "ffmpeg-v7.1-mahbot.0");
assert!(
root.join("ffmpeg-v7.1-mahbot.0").exists(),
"the installed copy stays"
);
for gone in [
"ffmpeg-v6.0-mahbot.1",
"ffmpeg-v7.1-mahbot.2",
".staging-Kd7x2p",
"downloads",
] {
assert!(!root.join(gone).exists(), "{gone} is gone");
}
}
#[test]
fn the_banner_names_the_upstream_version() {
let tagged = build("ffmpeg-v7.1.3-mahbot.2");
assert_eq!(
tagged.upstream,
Version::new(7, 1, 3),
"the tag names the version every banner is compared against"
);
assert_eq!(
banner_version(b"ffmpeg version 7.1.3 Copyright (c) 2000-2024 the FFmpeg developers\n"),
Some(tagged.upstream.clone())
);
assert_eq!(
banner_version(b"ffprobe version 7.1.3-static Copyright (c) 2000-2024\n"),
Some(tagged.upstream)
);
assert_eq!(
banner_version(b"ffmpeg version 7.1 Copyright\n"),
Some(Version::new(7, 1, 0))
);
assert_eq!(banner_version(b"nothing to see\n"), None);
assert_eq!(banner_version(b""), None);
}
fn release_entries(tag: &str) -> Vec<(String, Vec<u8>)> {
let upstream = parse_tag(tag).expect("a parsable tag").0;
let script =
format!("#!/bin/sh\necho 'ffmpeg version {upstream} stand-in build'\n").into_bytes();
vec![
(format!("pkg/bin/{}", ffmpeg_file()), script.clone()),
(format!("pkg/bin/{}", ffprobe_file()), script),
("LICENCE.txt".to_string(), b"GPLv3".to_vec()),
(
"LICENCES.txt".to_string(),
b"x264: GPL-2.0-or-later\n".to_vec(),
),
("SOURCE.txt".to_string(), b"upstream source".to_vec()),
]
}
fn write_tar_gz(path: &Path, entries: &[(String, Vec<u8>)]) {
let encoder = flate2::write::GzEncoder::new(
fs::File::create(path).expect("create archive"),
flate2::Compression::default(),
);
let mut builder = tar::Builder::new(encoder);
for (name, contents) in entries {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(0o644);
header.set_entry_type(tar::EntryType::Regular);
builder
.append_data(&mut header, name.as_str(), contents.as_slice())
.expect("append entry");
}
builder
.into_inner()
.expect("finish archive")
.finish()
.expect("finish gzip");
}
fn write_zip(path: &Path, entries: &[(String, Vec<u8>)]) {
let mut writer = zip::ZipWriter::new(fs::File::create(path).expect("create archive"));
let options = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated);
for (name, contents) in entries {
writer
.start_file(name.as_str(), options)
.expect("start entry");
writer.write_all(contents).expect("write entry");
}
writer.finish().expect("finish zip");
}
fn assert_staged(archive: &Path, staging: &Path) {
extract_into(archive, staging).expect("extract the release archive");
for tool in [ffmpeg_file(), ffprobe_file()] {
let path = staging.join("bin").join(tool);
assert!(crate::util::is_executable(&path), "{tool} is executable");
}
for licence in LICENCE_AND_SOURCE.into_iter().chain([COMPONENT_NOTICES]) {
assert!(
staging.join(licence).is_file(),
"{licence} is at the archive's root"
);
}
assert_eq!(
fs::read(staging.join("LICENCE.txt")).expect("read the licence"),
b"GPLv3" as &[u8]
);
assert_eq!(
fs::read(staging.join("SOURCE.txt")).expect("read the source note"),
b"upstream source" as &[u8]
);
}
#[test]
fn a_release_lands_in_the_staging_layout() {
let entries = release_entries("ffmpeg-v7.1-mahbot.2");
let dir = tempfile::tempdir().expect("tempdir");
let tarball = dir.path().join("pkg.tar.gz");
write_tar_gz(&tarball, &entries);
assert_staged(&tarball, &dir.path().join("staging-tar"));
let archive = dir.path().join("pkg.zip");
write_zip(&archive, &entries);
assert_staged(&archive, &dir.path().join("staging-zip"));
}
#[test]
fn licence_material_rules() {
let dir = tempfile::tempdir().expect("tempdir");
let archive = dir.path().join("no-licence.tar.gz");
let entries: Vec<(String, Vec<u8>)> = release_entries("ffmpeg-v7.1-mahbot.2")
.into_iter()
.filter(|(name, _)| !name.starts_with("LICENCE"))
.collect();
write_tar_gz(&archive, &entries);
let reason = extract_into(&archive, &dir.path().join("refused-staging"))
.expect_err("a release without its licence text is refused");
assert!(reason.contains("LICENCE.txt"), "{reason}");
let archive = dir.path().join("no-notices.tar.gz");
let entries: Vec<(String, Vec<u8>)> = release_entries("ffmpeg-v7.1-mahbot.2")
.into_iter()
.filter(|(name, _)| name != COMPONENT_NOTICES)
.collect();
write_tar_gz(&archive, &entries);
let staging = dir.path().join("staging");
extract_into(&archive, &staging).expect("a build from before the notices installs");
for licence in LICENCE_AND_SOURCE {
assert!(staging.join(licence).is_file(), "{licence} is there");
}
assert!(
!staging.join(COMPONENT_NOTICES).exists(),
"no notices to copy"
);
assert!(
crate::util::is_executable(&staging.join("bin").join(ffmpeg_file())),
"the pair is staged regardless"
);
}
#[test]
fn the_floors_are_the_product_own() {
let workflow = fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR")).join(".github/workflows/ffmpeg-release.yml"),
)
.expect("the workflow that builds the archives");
let (macos, glibc) = (
crate::self_update::MACOS_FLOOR,
crate::self_update::GLIBC_FLOOR,
);
assert!(
workflow.contains(&format!("-mmacosx-version-min={}.{}", macos.0, macos.1)),
"the macOS archives must be built against {}.{}",
macos.0,
macos.1
);
assert!(
workflow.contains(&format!("GLIBC_FLOOR: \"{}.{}\"", glibc.0, glibc.1)),
"the Linux archives must be built against glibc {}.{}",
glibc.0,
glibc.1
);
assert!(
workflow.contains("getconf GNU_LIBC_VERSION"),
"the Linux legs must refuse a base newer than the floor"
);
}
#[cfg(unix)]
fn host_asset(tag: &str) -> String {
let (os, arch) =
managed_bin::host_os_arch().expect("this host is one the product builds for");
asset_name(tag, os, arch)
}
#[cfg(unix)]
fn archive_bytes(dir: &Path, tag: &str) -> Vec<u8> {
let archive = dir.join(host_asset(tag));
write_tar_gz(&archive, &release_entries(tag));
fs::read(&archive).expect("read the stand-in archive")
}
#[cfg(unix)]
fn checksum_line(digest: &str, name: &str) -> String {
format!("{digest} {name}\n")
}
#[cfg(unix)]
fn sha256_hex(bytes: &[u8]) -> String {
use sha2::Digest as _;
crate::util::hex_string(&sha2::Sha256::digest(bytes))
}
#[cfg(unix)]
fn staging_dirs(root: &Path) -> Vec<String> {
entries(root)
.into_iter()
.filter(|name| name.starts_with(".staging-"))
.collect()
}
#[cfg(unix)]
fn entries(root: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(root)
.map(|entries| {
entries
.flatten()
.filter_map(|entry| entry.file_name().into_string().ok())
.collect()
})
.unwrap_or_default();
names.sort();
names
}
#[cfg(unix)]
type Offered = Arc<Mutex<Vec<(String, Vec<String>)>>>;
#[cfg(unix)]
struct FakeRelease {
base: String,
offered: Offered,
served: Arc<Mutex<HashMap<String, Vec<u8>>>>,
asked: Arc<Mutex<Vec<String>>>,
listing: Arc<Mutex<Option<Vec<u8>>>>,
stop: Arc<AtomicBool>,
accept: Option<std::thread::JoinHandle<()>>,
}
#[cfg(unix)]
impl FakeRelease {
fn start() -> Self {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind the stand-in host");
listener
.set_nonblocking(true)
.expect("the stand-in host accepts without blocking");
let port = listener.local_addr().expect("stand-in host address").port();
let offered = Arc::new(Mutex::new(Vec::new()));
let served = Arc::new(Mutex::new(HashMap::new()));
let asked = Arc::new(Mutex::new(Vec::new()));
let listing = Arc::new(Mutex::new(None));
let stop = Arc::new(AtomicBool::new(false));
let accept = std::thread::spawn({
let offered = Arc::clone(&offered);
let served = Arc::clone(&served);
let asked = Arc::clone(&asked);
let listing = Arc::clone(&listing);
let stop = Arc::clone(&stop);
move || {
while !stop.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, _)) => {
let _ = stream.set_nonblocking(false);
let offered = Arc::clone(&offered);
let served = Arc::clone(&served);
let asked = Arc::clone(&asked);
let listing = Arc::clone(&listing);
std::thread::spawn(move || {
serve(stream, &offered, &served, &asked, &listing);
});
}
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(2));
}
Err(_) => {}
}
}
}
});
Self {
base: format!("http://127.0.0.1:{port}"),
offered,
served,
asked,
listing,
stop,
accept: Some(accept),
}
}
fn offer(&self, tag: &str, asset: &str, sums: &str, archive: &[u8]) {
let mut offered = self.offered.lock().expect("fake listing");
if !offered.iter().any(|(name, _)| name == tag) {
offered.push((tag.to_string(), vec![asset.to_string()]));
}
drop(offered);
self.served.lock().expect("fake release files").extend([
(format!("/{tag}/SHA256SUMS"), sums.as_bytes().to_vec()),
(format!("/{tag}/{asset}"), archive.to_vec()),
]);
}
fn base(&self) -> &str {
&self.base
}
fn asked(&self) -> Vec<String> {
self.asked.lock().expect("fake release log").clone()
}
fn listing_is(&self, body: &[u8]) {
*self.listing.lock().expect("fake listing override") = Some(body.to_vec());
}
}
#[cfg(unix)]
impl Drop for FakeRelease {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(accept) = self.accept.take() {
let _ = accept.join();
}
}
}
#[cfg(unix)]
fn serve(
mut stream: TcpStream,
offered: &Mutex<Vec<(String, Vec<String>)>>,
served: &Mutex<HashMap<String, Vec<u8>>>,
asked: &Mutex<Vec<String>>,
listing: &Mutex<Option<Vec<u8>>>,
) {
let Some(path) = request_path(&mut stream) else {
return;
};
asked.lock().expect("fake release log").push(path.clone());
let override_body = listing.lock().expect("fake listing override").clone();
let body = match path.strip_prefix("/?") {
Some(_) if override_body.is_some() => override_body,
Some(query) if query.contains("page=1") => Some(listing_body(offered)),
Some(_) => Some(b"[]".to_vec()),
None => served
.lock()
.expect("fake release files")
.get(&path)
.cloned(),
};
let head = match &body {
Some(bytes) => format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n\
Content-Length: {}\r\nConnection: close\r\n\r\n",
bytes.len()
),
None => "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
.to_string(),
};
let _ = stream.write_all(head.as_bytes());
if let Some(bytes) = body {
let _ = stream.write_all(&bytes);
}
}
#[cfg(unix)]
fn listing_body(offered: &Mutex<Vec<(String, Vec<String>)>>) -> Vec<u8> {
let releases: Vec<serde_json::Value> = offered
.lock()
.expect("fake listing")
.iter()
.map(|(tag, assets)| {
serde_json::json!({
"tag_name": tag,
"assets": assets
.iter()
.map(|name| serde_json::json!({ "name": name }))
.collect::<Vec<_>>(),
})
})
.collect();
serde_json::Value::Array(releases).to_string().into_bytes()
}
#[cfg(unix)]
fn request_path(stream: &mut TcpStream) -> Option<String> {
let mut buffer = Vec::new();
let mut chunk = [0u8; 1024];
loop {
let read = stream.read(&mut chunk).ok()?;
if read == 0 {
return None;
}
buffer.extend_from_slice(&chunk[..read]);
if buffer.windows(4).any(|window| window == b"\r\n\r\n") {
break;
}
}
let head = String::from_utf8_lossy(&buffer);
Some(head.lines().next()?.split_whitespace().nth(1)?.to_string())
}
#[cfg(unix)]
fn temp_root() -> (tempfile::TempDir, crate::util::test::EnvVarGuard, PathBuf) {
let dir = tempfile::tempdir().expect("temp install root");
let guard = crate::util::test::set_env_var(ROOT_ENV, dir.path().to_str());
let root = root().expect("the install root resolves under the temp root");
(dir, guard, root)
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial(ffmpeg_releases)]
async fn the_boot_installs_the_newest_build_the_stream_offers() {
let files = tempfile::tempdir().expect("stand-in release files");
let (_home, _lock, root) = temp_root();
let host = FakeRelease::start();
for tag in [
"ffmpeg-v7.1-mahbot.2",
"ffmpeg-v7.0-mahbot.9",
"ffmpeg-v7.1-mahbot.1",
] {
let asset = host_asset(tag);
let archive = archive_bytes(files.path(), tag);
let sums = checksum_line(&sha256_hex(&archive), &asset);
host.offer(tag, &asset, &sums, &archive);
}
host.offer(
"ffmpeg-v9.0-mahbot.1",
&asset_name("ffmpeg-v9.0-mahbot.1", "windows", "aarch64"),
"",
b"",
);
let _hook = ReleasesHook::at(host.base());
assert_eq!(
update()
.await
.expect("the newest build installs")
.as_deref(),
Some("ffmpeg-v7.1-mahbot.2")
);
assert_eq!(
chosen(&root).expect("a copy is in use").0.tag,
"ffmpeg-v7.1-mahbot.2",
"the newest build the stream carries for this host is the one in use"
);
assert_eq!(
entries(&root),
["ffmpeg-v7.1-mahbot.2"],
"one copy: nothing older, no download and no staging left"
);
for licence in LICENCE_AND_SOURCE.into_iter().chain([COMPONENT_NOTICES]) {
assert!(
root.join("ffmpeg-v7.1-mahbot.2").join(licence).is_file(),
"{licence} travelled with the pair"
);
}
assert_eq!(
host.asked().first().map(String::as_str),
Some("/?per_page=100&page=1"),
"the listing is what the boot starts from"
);
let asked = host.asked().len();
assert_eq!(update().await.expect("nothing to do"), None);
assert_eq!(
host.asked().len(),
asked + 1,
"only the listing is read again"
);
let newer = "ffmpeg-v7.1-mahbot.3";
let asset = host_asset(newer);
let archive = archive_bytes(files.path(), newer);
let sums = checksum_line(&sha256_hex(&archive), &asset);
host.offer(newer, &asset, &sums, &archive);
assert_eq!(
update().await.expect("the newer build installs").as_deref(),
Some(newer)
);
assert_eq!(entries(&root), [newer], "the build it replaced is gone");
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial(ffmpeg_releases)]
async fn an_unkept_copy_is_replaced_once() {
{
let files = tempfile::tempdir().expect("stand-in release files");
let (_home, _lock, root) = temp_root();
let host = FakeRelease::start();
let tag = "ffmpeg-v7.1-mahbot.2";
let asset = host_asset(tag);
let archive = archive_bytes(files.path(), tag);
let sums = checksum_line(&sha256_hex(&archive), &asset);
host.offer(tag, &asset, &sums, &archive);
let _hook = ReleasesHook::at(host.base());
update().await.expect("the build installs");
let damaged = root.join(tag).join("bin").join(ffmpeg_file());
fs::write(
&damaged,
b"#!/bin/sh\necho 'ffmpeg version 0.0.0 damaged'\n",
)
.expect("damage the copy");
managed_bin::set_executable(&damaged).expect("keep it executable");
assert_eq!(
update()
.await
.expect("the damaged copy is replaced")
.as_deref(),
Some(tag),
"the same build is installed again"
);
assert_eq!(
update().await.expect("nothing to do").as_deref(),
None,
"the replacement proves itself"
);
}
{
let files = tempfile::tempdir().expect("stand-in release files");
let (_home, _lock, root) = temp_root();
let host = FakeRelease::start();
let tag = "ffmpeg-v7.1-mahbot.2";
let asset = host_asset(tag);
let archive = archive_bytes(files.path(), tag);
let sums = checksum_line(&sha256_hex(&archive), &asset);
host.offer(tag, &asset, &sums, &archive);
let _hook = ReleasesHook::at(host.base());
install_fake(&root, "ffmpeg-v7.1-mahbot.9");
assert_eq!(
update()
.await
.expect("the build the stream offers installs")
.as_deref(),
Some(tag)
);
assert_eq!(
entries(&root),
[tag],
"the copy the stream no longer offers is gone"
);
let asked = host.asked().len();
assert_eq!(
update().await.expect("nothing to do"),
None,
"the following start converges on the one copy"
);
assert_eq!(
host.asked().len(),
asked + 1,
"only the listing is read again"
);
}
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial(ffmpeg_releases)]
async fn an_unreadable_stream_leaves_a_proven_copy_alone() {
let files = tempfile::tempdir().expect("stand-in release files");
let (_home, _lock, root) = temp_root();
let host = FakeRelease::start();
let tag = "ffmpeg-v7.1-mahbot.2";
let asset = host_asset(tag);
let archive = archive_bytes(files.path(), tag);
let sums = checksum_line(&sha256_hex(&archive), &asset);
host.offer(tag, &asset, &sums, &archive);
{
let _hook = ReleasesHook::at(host.base());
update().await.expect("the build installs");
}
let _hook = ReleasesHook::at("http://127.0.0.1:1");
assert_eq!(
update()
.await
.expect("a copy that proves itself needs no listing"),
None
);
assert_eq!(entries(&root), [tag], "the copy stays in use");
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial(ffmpeg_releases)]
async fn a_copy_in_place_is_used_without_asking_the_stream() {
let (_home, _lock, root) = temp_root();
install_fake(&root, "ffmpeg-v7.1-mahbot.1");
let _hook = ReleasesHook::at("http://127.0.0.1:1");
let binaries = ensure_installed().await.expect("the copy in place is used");
assert_eq!(
binaries.ffmpeg,
root.join("ffmpeg-v7.1-mahbot.1")
.join("bin")
.join(ffmpeg_file())
);
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial(ffmpeg_releases)]
async fn newest_names_why_it_cannot_pick_a_build() {
let host = FakeRelease::start();
host.offer(
"ffmpeg-v7.1-mahbot.2",
&asset_name("ffmpeg-v7.1-mahbot.2", "windows", "aarch64"),
"",
b"",
);
{
let _lock = env_held();
let _hook = ReleasesHook::at(host.base());
let Err(reason) = newest().await else {
panic!("this host has no build in the stream");
};
let (os, arch) = managed_bin::host_os_arch().expect("a supported host");
assert!(
reason.contains(&format!("no ffmpeg build is published for {os}-{arch}")),
"{reason}"
);
}
host.listing_is(br#"{"message":"API rate limit exceeded"}"#);
let _lock = env_held();
let _hook = ReleasesHook::at(host.base());
let Err(reason) = newest().await else {
panic!("a body that is not a release array names no build");
};
assert!(
reason.contains("could not be read: it is not a JSON array"),
"{reason}"
);
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial(ffmpeg_releases)]
async fn the_install_checks_the_release_against_its_own_checksums() {
let dir = tempfile::tempdir().expect("install root");
let root = dir.path();
let files = tempfile::tempdir().expect("stand-in release files");
let tag = "ffmpeg-v7.1-mahbot.2";
let asset = host_asset(tag);
let archive = archive_bytes(files.path(), tag);
let sums = checksum_line(&sha256_hex(&archive), &asset);
let host = FakeRelease::start();
host.offer(tag, &asset, &sums, &archive);
let _lock = env_held();
let _hook = ReleasesHook::at(host.base());
install(root, &build(tag))
.await
.expect("the release installs");
assert_eq!(
host.asked(),
[format!("/{tag}/SHA256SUMS"), format!("/{tag}/{asset}")],
"the checksum file and this platform's archive, both under the tag"
);
assert_eq!(
chosen(root).expect("a copy is in use").0.tag,
tag,
"the copy in use is the one installed"
);
for tool in [ffmpeg_file(), ffprobe_file()] {
assert!(
crate::util::is_executable(&root.join(tag).join("bin").join(tool)),
"{tool} is installed executable"
);
}
assert_eq!(
entries(root),
[tag.to_string()],
"the whole install is one directory: no download and no staging left"
);
let elsewhere = checksum_line(
&sha256_hex(&archive),
&asset_name(tag, "windows", "aarch64"),
);
host.offer(tag, &asset, &elsewhere, &archive);
let reason = install(root, &build(tag))
.await
.expect_err("a release without this platform's archive is refused");
assert!(reason.contains("no checksum for this platform"), "{reason}");
assert_eq!(
chosen(root).expect("the installed copy survives").0.tag,
tag,
"the copy in use is untouched"
);
assert!(
!root.join("downloads").exists(),
"nothing was downloaded for a release without this archive"
);
assert!(
staging_dirs(root).is_empty(),
"nothing was staged for a release without this archive"
);
let mut altered = archive.clone();
*altered.last_mut().expect("the archive has bytes") ^= 0xff;
host.offer(tag, &asset, &sums, &altered);
let reason = install(root, &build(tag))
.await
.expect_err("an archive that does not match its digest is refused");
assert!(reason.contains("does not match the checksum"), "{reason}");
assert_eq!(
chosen(root).expect("the installed copy survives").0.tag,
tag,
"the copy in use is untouched"
);
assert!(
!root.join("downloads").join(&asset).exists(),
"the refused archive is not kept"
);
assert!(
staging_dirs(root).is_empty(),
"nothing was staged for a rejected download"
);
host.offer(tag, &asset, &sums, &archive);
fs::remove_file(root.join(tag).join("bin").join(ffprobe_file()))
.expect("break the installed copy");
assert!(
chosen(root).is_none(),
"a copy that lost a binary is not a copy"
);
install(root, &build(tag))
.await
.expect("the release replaces the broken copy");
for tool in [ffmpeg_file(), ffprobe_file()] {
assert!(
crate::util::is_executable(&root.join(tag).join("bin").join(tool)),
"{tool} is back after the swap"
);
}
for licence in LICENCE_AND_SOURCE {
assert!(
root.join(tag).join(licence).is_file(),
"{licence} survives the swap"
);
}
}
}