capri-voice: add download module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent d0f62b6518
commit 5f71fae89a
1 file changed
+261
+261
View File
@@ -0,0 +1,261 @@
//! Resumable, hash-verified downloads, same rules as Capri's `integrations/model_download.py`.
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result, bail, ensure};
use futures::StreamExt;
use sha2::{Digest, Sha256};
#[derive(Clone, Debug, PartialEq)]
pub struct Pinned {
pub url: String,
pub bytes: u64,
pub sha256: String,
}
impl Pinned {
pub fn new(url: impl Into<String>, bytes: u64, sha256: &str) -> Self {
Self { url: url.into(), bytes, sha256: sha256.into() }
}
}
pub fn http_client() -> reqwest::Client {
reqwest::Client::builder()
.user_agent("Capri-Installer/0.3")
.connect_timeout(Duration::from_secs(30))
.read_timeout(Duration::from_secs(45))
.build()
.expect("HTTP client")
}
pub fn sha256_file(path: &Path) -> Result<String> {
let mut file = std::fs::File::open(path)?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 1 << 20];
loop {
let n = file.read(&mut buf)?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(hex::encode(hasher.finalize()))
}
/// A regular (not symlinked) file with the exact size and hash.
pub fn verified(path: &Path, bytes: u64, sha256: &str) -> bool {
std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file() && m.len() == bytes) && sha256_file(path).is_ok_and(|h| h == sha256)
}
/// Same, by size only (cheap check for UI state; hashes are verified before use).
pub fn present(path: &Path, bytes: u64) -> bool {
std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file() && m.len() == bytes)
}
pub fn free_bytes(path: &Path) -> Option<u64> {
use std::os::unix::ffi::OsStrExt;
let mut dir = path;
while !dir.exists() {
dir = dir.parent()?;
}
let c = std::ffi::CString::new(dir.as_os_str().as_bytes()).ok()?;
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
(unsafe { libc::statvfs(c.as_ptr(), &mut stat) } == 0).then(|| stat.f_bavail as u64 * stat.f_frsize as u64)
}
fn check_url(url: &str) -> Result<reqwest::Url> {
let url = reqwest::Url::parse(url)?;
// Plain HTTP is accepted only for loopback test servers.
ensure!(url.scheme() == "https" || (url.scheme() == "http" && url.host_str() == Some("127.0.0.1")), "Downloads must use HTTPS");
ensure!(url.username().is_empty() && url.password().is_none(), "Download URLs must not carry credentials");
Ok(url)
}
/// Downloads `pin` to `target`: `<target>.partial` is resumed with `Range`, renamed only after size and SHA-256 match.
/// `progress(done, total)` is called as data arrives.
pub async fn download_verified(client: &reqwest::Client, pin: &Pinned, target: &Path, progress: &(dyn Fn(u64, u64) + Send + Sync)) -> Result<()> {
let url = check_url(&pin.url)?;
let host = url.host_str().unwrap_or("?").to_string();
if verified(target, pin.bytes, &pin.sha256) {
progress(pin.bytes, pin.bytes);
return Ok(());
}
let parent = target.parent().context("Download target has no folder")?;
std::fs::create_dir_all(parent)?;
let partial = PathBuf::from(format!("{}.partial", target.display()));
let have = std::fs::metadata(&partial).map_or(0, |m| m.len());
if let Some(free) = free_bytes(parent) {
ensure!(free >= pin.bytes.saturating_sub(have) + (1 << 30), "Not enough free space for {}", target.display());
}
let base = if cfg!(test) { Duration::from_millis(5) } else { Duration::from_secs(1) };
let mut last_error = None;
for attempt in 1..=6u32 {
match fetch(client, &url, pin.bytes, &partial, progress).await {
Ok(()) => {
if sha256_file(&partial)? != pin.sha256 {
let _ = std::fs::remove_file(&partial);
bail!("Checksum mismatch for {}", target.display());
}
std::fs::rename(&partial, target)?;
return Ok(());
}
Err(Retry::Fatal(e)) => return Err(e),
Err(Retry::Later(e, after)) => {
tracing::warn!(host, attempt, error = %e, "download interrupted");
last_error = Some(e);
tokio::time::sleep(after.unwrap_or(base * 2u32.pow(attempt - 1)).min(Duration::from_secs(30))).await;
}
}
}
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("download failed"))).with_context(|| format!("Download from {host} failed"))
}
enum Retry {
Fatal(anyhow::Error),
Later(anyhow::Error, Option<Duration>),
}
async fn fetch(client: &reqwest::Client, url: &reqwest::Url, total: u64, partial: &Path, progress: &(dyn Fn(u64, u64) + Send + Sync)) -> Result<(), Retry> {
let later = |e: anyhow::Error| Retry::Later(e, None);
let mut offset = std::fs::metadata(partial).map_or(0, |m| m.len());
if offset > total {
offset = 0;
}
if offset == total {
return Ok(());
}
let mut request = client.get(url.clone()).header("Accept-Encoding", "identity").header("Cache-Control", "no-cache");
if offset > 0 {
request = request.header("Range", format!("bytes={offset}-"));
}
let response = request.send().await.map_err(|e| later(e.without_url().into()))?;
let status = response.status().as_u16();
if status == 429 || status >= 500 {
let after = response.headers().get("retry-after").and_then(|v| v.to_str().ok()?.parse().ok()).map(Duration::from_secs);
return Err(Retry::Later(anyhow::anyhow!("HTTP {status}"), after));
}
let append = match status {
206 => true,
200 => false, // The server ignored Range: restart cleanly.
416 => {
let _ = std::fs::remove_file(partial);
return Err(later(anyhow::anyhow!("HTTP 416")));
}
_ => return Err(Retry::Fatal(anyhow::anyhow!("HTTP {status}"))),
};
let mut file = std::fs::OpenOptions::new().create(true).write(true).append(append).truncate(!append).open(partial).map_err(|e| Retry::Fatal(e.into()))?;
let mut done = if append { offset } else { 0 };
let mut body = response.bytes_stream();
while let Some(chunk) = body.next().await {
let chunk = chunk.map_err(|e| later(e.without_url().into()))?;
done += chunk.len() as u64;
if done > total {
drop(file);
let _ = std::fs::remove_file(partial);
return Err(Retry::Fatal(anyhow::anyhow!("Download is larger than expected")));
}
file.write_all(&chunk).map_err(|e| Retry::Fatal(e.into()))?;
progress(done, total);
}
file.sync_all().map_err(|e| Retry::Fatal(e.into()))?;
if done != total {
return Err(later(anyhow::anyhow!("Download ended early")));
}
Ok(())
}
/// Extracts the named files found under `prefix` (the folder holding them inside the archive) into `dest`.
/// Names are relative paths; anything else in the archive is ignored. Each file is limited to `max_bytes`.
pub fn extract_named(archive: &Path, prefix: &str, names: &[String], dest: &Path, max_bytes: u64) -> Result<()> {
let mut zip = zip::ZipArchive::new(std::fs::File::open(archive)?)?;
for name in names {
ensure!(!name.split('/').any(|p| p.is_empty() || p == ".." || p == "."), "Invalid archive member {name}");
let full = if prefix.is_empty() { name.clone() } else { format!("{prefix}/{name}") };
let mut entry = zip.by_name(&full).with_context(|| format!("Archive is missing {name}"))?;
ensure!(entry.is_file() && entry.size() <= max_bytes, "Archive member {name} is too large");
let target = dest.join(name);
std::fs::create_dir_all(target.parent().unwrap())?;
let tmp = target.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
let mut out = std::fs::File::create(&tmp)?;
let copied = std::io::copy(&mut (&mut entry).take(max_bytes + 1), &mut out)?;
ensure!(copied <= max_bytes, "Archive member {name} is too large");
out.sync_all()?;
std::fs::rename(&tmp, &target)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn body() -> Vec<u8> {
(0..100_000u32).map(|i| (i * 7 % 251) as u8).collect()
}
fn pin(server: &MockServer, data: &[u8]) -> Pinned {
Pinned::new(format!("{}/model.bin", server.uri()), data.len() as u64, &hex::encode(Sha256::digest(data)))
}
#[tokio::test]
async fn downloads_verifies_and_resumes() {
let server = MockServer::start().await;
let data = body();
Mock::given(method("GET")).and(path("/model.bin")).and(header("range", "bytes=40000-"))
.respond_with(ResponseTemplate::new(206).set_body_bytes(data[40000..].to_vec()))
.expect(1)
.mount(&server)
.await;
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("speech/model.bin");
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
std::fs::write(format!("{}.partial", target.display()), &data[..40000]).unwrap();
let seen = std::sync::atomic::AtomicU64::new(0);
download_verified(&http_client(), &pin(&server, &data), &target, &|d, _| seen.store(d, std::sync::atomic::Ordering::Relaxed)).await.unwrap();
assert_eq!(std::fs::read(&target).unwrap(), data);
assert_eq!(seen.load(std::sync::atomic::Ordering::Relaxed), data.len() as u64);
// Already verified: no request.
download_verified(&http_client(), &pin(&server, &data), &target, &|_, _| {}).await.unwrap();
}
#[tokio::test]
async fn retries_server_errors_and_rejects_bad_hash() {
let server = MockServer::start().await;
let data = body();
Mock::given(method("GET")).respond_with(ResponseTemplate::new(503)).up_to_n_times(2).mount(&server).await;
Mock::given(method("GET")).respond_with(ResponseTemplate::new(200).set_body_bytes(data.clone())).mount(&server).await;
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("model.bin");
download_verified(&http_client(), &pin(&server, &data), &target, &|_, _| {}).await.unwrap();
assert!(verified(&target, data.len() as u64, &pin(&server, &data).sha256));
let mut wrong = pin(&server, &data);
wrong.sha256 = "0".repeat(64);
let other = dir.path().join("other.bin");
let error = download_verified(&http_client(), &wrong, &other, &|_, _| {}).await.unwrap_err();
assert!(error.to_string().contains("Checksum mismatch"));
assert!(!other.exists() && !dir.path().join("other.bin.partial").exists());
assert!(check_url("http://example.com/x").is_err());
}
#[test]
fn extracts_only_named_members() {
let dir = tempfile::tempdir().unwrap();
let archive = dir.path().join("a.zip");
let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive).unwrap());
for (name, data) in [("pack/a.txt", "A"), ("pack/sub/b.wav", "BB"), ("pack/evil.sh", "x")] {
zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(data.as_bytes()).unwrap();
}
zip.finish().unwrap();
let out = dir.path().join("out");
extract_named(&archive, "pack", &["a.txt".into(), "sub/b.wav".into()], &out, 10).unwrap();
assert_eq!(std::fs::read_to_string(out.join("sub/b.wav")).unwrap(), "BB");
assert!(!out.join("evil.sh").exists());
assert!(extract_named(&archive, "pack", &["../x".into()], &out, 10).is_err());
assert!(extract_named(&archive, "pack", &["sub/b.wav".into()], &out, 1).is_err());
}
}