use std::path::{Path, PathBuf};
use std::time::SystemTime;
use eyre::Result;
use serde::{Deserialize, Serialize};
use super::DownloadValidator;
use crate::file;
const DEFAULT_MAX_CACHE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
pub(super) fn max_cache_bytes() -> u64 {
let setting = mise_settings::Settings::get();
match setting
.download_cache_max_size
.parse::<bytesize::ByteSize>()
{
Ok(size) if size.as_u64() == 0 => u64::MAX,
Ok(size) => size.as_u64(),
Err(err) => {
debug!(
"invalid download_cache_max_size {:?}: {err}",
setting.download_cache_max_size
);
DEFAULT_MAX_CACHE_BYTES
}
}
}
const IN_USE: std::time::Duration = std::time::Duration::from_secs(10 * 60);
const PIN_ALGOS: &[&str] = &["sha256", "sha384", "sha512", "blake3"];
#[derive(Debug, Clone, Serialize, Deserialize)]
struct UrlEntry {
validator: DownloadValidator,
blake3: String,
effective_filename: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct PinEntry {
blake3: String,
effective_filename: Option<String>,
#[serde(default)]
urls: Vec<String>,
}
#[cfg(test)]
pub(super) static TEST_ROOT: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
fn root() -> Option<PathBuf> {
#[cfg(test)]
{
TEST_ROOT.lock().unwrap().clone()
}
#[cfg(not(test))]
{
Some(crate::dirs::CACHE.join("downloads-cas"))
}
}
fn is_hex(value: &str) -> bool {
!value.is_empty() && value.bytes().all(|b| b.is_ascii_hexdigit())
}
fn blob_dir(root: &Path, blake3: &str) -> PathBuf {
root.join("blobs").join(blake3)
}
fn blob_file(dir: &Path) -> Option<PathBuf> {
std::fs::read_dir(dir)
.ok()?
.flatten()
.map(|entry| entry.path())
.find(|path| path.is_file())
}
pub(super) fn staging_path(request_hash: &str, name: &str) -> Option<PathBuf> {
Some(root()?.join("incoming").join(request_hash).join(name))
}
fn url_path(root: &Path, request_hash: &str) -> PathBuf {
root.join("urls").join(format!("{request_hash}.json"))
}
fn parse_pin(pin: &str) -> Option<(&str, String)> {
let (algo, hex) = pin.split_once(':')?;
(PIN_ALGOS.contains(&algo) && is_hex(hex)).then(|| (algo, hex.to_lowercase()))
}
fn matches_pin(path: &Path, pin: &str) -> bool {
pin.split_once(':')
.is_some_and(|(algo, hex)| crate::hash::ensure_checksum(path, hex, None, algo).is_ok())
}
fn pin_path(root: &Path, algo: &str, hex: &str) -> PathBuf {
root.join("pins").join(algo).join(format!("{hex}.json"))
}
pub(super) struct Hit {
blob: PathBuf,
pub(super) effective_filename: Option<String>,
entry: PathBuf,
verify: Verify,
}
enum Verify {
Blake3 { name: String, pin: Option<String> },
Pin { algo: String, hex: String },
}
pub(super) struct Cached {
pub(super) validator: DownloadValidator,
hit: Hit,
}
impl Cached {
pub(super) fn into_hit(self) -> Hit {
self.hit
}
pub(super) fn effective_filename(&self) -> Option<String> {
self.hit.effective_filename.clone()
}
}
pub(super) fn lookup_url(request_hash: &str, pin: Option<&str>) -> Option<Cached> {
let root = root()?;
let entry = url_path(&root, request_hash);
let url: UrlEntry = serde_json::from_slice(&std::fs::read(&entry).ok()?).ok()?;
if !url.validator.is_valid() || !is_hex(&url.blake3) {
return None;
}
let blob = blob_file(&blob_dir(&root, &url.blake3))?;
Some(Cached {
validator: url.validator,
hit: Hit {
blob,
effective_filename: url.effective_filename,
entry,
verify: Verify::Blake3 {
name: url.blake3,
pin: pin.map(str::to_string),
},
},
})
}
pub(super) fn lookup_pin(pin: &str, url: &str) -> Option<Hit> {
let root = root()?;
let (algo, hex) = parse_pin(pin)?;
let entry = pin_path(&root, algo, &hex);
let pinned: PinEntry = serde_json::from_slice(&std::fs::read(&entry).ok()?).ok()?;
if !is_hex(&pinned.blake3) || !pinned.urls.iter().any(|kept| kept == url) {
return None;
}
let blob = blob_file(&blob_dir(&root, &pinned.blake3))?;
Some(Hit {
blob,
effective_filename: pinned.effective_filename,
entry,
verify: Verify::Pin {
algo: algo.to_string(),
hex,
},
})
}
impl Hit {
pub(super) fn verified(&self) -> Option<PathBuf> {
let intact = match &self.verify {
Verify::Blake3 { name, pin } => {
crate::hash::file_hash_blake3(&self.blob, None).is_ok_and(|hash| hash == *name)
&& pin
.as_deref()
.is_none_or(|pin| matches_pin(&self.blob, pin))
}
Verify::Pin { algo, hex } => {
crate::hash::ensure_checksum(&self.blob, hex, None, algo).is_ok()
}
};
if !intact {
let _ = file::remove_file(&self.entry);
if let Some(dir) = self.blob.parent() {
let name = dir.file_name().map(|n| n.to_string_lossy().to_string());
let damaged = crate::hash::file_hash_blake3(&self.blob, None)
.is_ok_and(|hash| Some(hash) != name);
if damaged {
let _ = file::remove_all(dir);
}
}
return None;
}
if let Ok(f) = std::fs::File::options().write(true).open(&self.blob) {
let _ = f.set_modified(SystemTime::now());
}
Some(self.blob.clone())
}
}
pub(super) fn place(blob: &Path, dest: &Path, link: bool) -> Result<()> {
let parent = dest.parent().unwrap_or(Path::new("."));
file::create_dir_all(parent)?;
let scratch = tempfile::Builder::new()
.prefix(".mise-place-")
.tempdir_in(parent)
.map_err(|err| placing(err, dest))?;
let staged = scratch.path().join("file");
if link {
file::hard_link_or_copy(blob, &staged)?;
} else {
file::copy(blob, &staged)?;
}
tempfile::TempPath::try_from_path(&staged)
.map_err(|err| placing(err, dest))?
.persist(dest)
.map_err(|err| placing(err.error, dest))?;
Ok(())
}
fn placing(err: std::io::Error, dest: &Path) -> eyre::Report {
let msg = file::with_io_hint(
format!(
"failed to move the downloaded file into place: {}",
file::display_path(dest)
),
dest,
&err,
);
eyre::Report::new(err).wrap_err(msg)
}
fn write_atomic(path: &Path, contents: &[u8]) -> Result<()> {
let parent = path.parent().expect("index paths have a parent");
file::create_dir_all(parent)?;
let tmp = tempfile::NamedTempFile::new_in(parent)?.into_temp_path();
file::write(&tmp, contents)?;
tmp.persist(path).map_err(|err| err.error)?;
Ok(())
}
pub(super) struct Keep<'a> {
pub(super) request_hash: &'a str,
pub(super) url: &'a str,
pub(super) pin: Option<&'a str>,
pub(super) validator: Option<&'a DownloadValidator>,
pub(super) effective_filename: Option<String>,
}
pub(super) fn store(path: &Path, keep: Keep<'_>) -> Result<Option<PathBuf>> {
keep_file(path, keep, false)
}
pub(super) fn ingest(path: &Path, keep: Keep<'_>) -> Result<Option<PathBuf>> {
keep_file(path, keep, true)
}
fn keep_file(path: &Path, keep: Keep<'_>, move_in: bool) -> Result<Option<PathBuf>> {
let Some(root) = root() else {
return Ok(None);
};
if keep.pin.is_some_and(|pin| !matches_pin(path, pin)) {
debug!("not keeping a download that doesn't match its pin");
return Ok(None);
}
let pin = keep.pin.and_then(parse_pin);
if keep.validator.is_none() && pin.is_none() {
return Ok(None);
}
let name = path.file_name().expect("downloads have a file name");
let blake3 = crate::hash::file_hash_blake3(path, None)?;
let dir = blob_dir(&root, &blake3);
let existing = blob_file(&dir).filter(|existing| {
let intact = crate::hash::file_hash_blake3(existing, None).is_ok_and(|h| h == blake3);
if !intact {
let _ = file::remove_all(&dir);
}
intact
});
let blob = match existing {
Some(blob) => {
if move_in {
let _ = file::remove_file(path);
}
blob
}
None => {
let blob = dir.join(name);
let blobs = root.join("blobs");
file::create_dir_all(&blobs)?;
let building = tempfile::Builder::new()
.prefix(".building-")
.tempdir_in(&blobs)?;
let staged = building.path().join(name);
if move_in {
file::rename(path, &staged)?;
} else {
file::copy(path, &staged)?;
}
let building = building.keep();
if let Err(err) = std::fs::rename(&building, &dir) {
let _ = file::remove_all(&building);
if blob_file(&dir).is_none() {
return Err(err.into());
}
}
blob_file(&dir).unwrap_or(blob)
}
};
if let Some(validator) = keep.validator {
let entry = UrlEntry {
validator: validator.clone(),
blake3: blake3.clone(),
effective_filename: keep.effective_filename.clone(),
};
write_atomic(
&url_path(&root, keep.request_hash),
&serde_json::to_vec(&entry)?,
)?;
}
if let Some((algo, hex)) = pin
&& let Err(err) = record_pin(&root, algo, &hex, blake3, &keep)
{
debug!("not recording the pin of a kept download: {err:#}");
}
evict(&root, blob.parent());
Ok(Some(blob))
}
const PIN_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
#[cfg(test)]
pub(super) static TEST_PIN_LOCK_WAIT: std::sync::Mutex<Option<std::time::Duration>> =
std::sync::Mutex::new(None);
fn pin_lock_wait() -> std::time::Duration {
#[cfg(test)]
if let Some(wait) = *TEST_PIN_LOCK_WAIT.lock().unwrap() {
return wait;
}
PIN_LOCK_WAIT
}
fn record_pin(root: &Path, algo: &str, hex: &str, blake3: String, keep: &Keep<'_>) -> Result<()> {
let lock_path = root.join("pins.lock");
let started = std::time::Instant::now();
let wait = pin_lock_wait();
let _lock = loop {
if let Some(lock) = crate::lock_file::LockFile::at(&lock_path).try_lock()? {
break lock;
}
eyre::ensure!(
started.elapsed() < wait,
"the pin index stayed locked for {wait:?}"
);
std::thread::sleep(std::time::Duration::from_millis(10));
};
let path = pin_path(root, algo, hex);
let mut urls = std::fs::read(&path)
.ok()
.and_then(|bytes| serde_json::from_slice::<PinEntry>(&bytes).ok())
.filter(|existing| existing.blake3 == blake3)
.map(|existing| existing.urls)
.unwrap_or_default();
if !urls.iter().any(|kept| kept == keep.url) {
urls.push(keep.url.to_string());
}
let entry = PinEntry {
blake3,
effective_filename: keep.effective_filename.clone(),
urls,
};
write_atomic(&path, &serde_json::to_vec(&entry)?)
}
fn evict(root: &Path, keep: Option<&Path>) {
let week = std::time::Duration::from_secs(7 * 24 * 60 * 60);
if let Ok(read) = std::fs::read_dir(root.join("incoming")) {
for entry in read.flatten() {
let stale = entry
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|modified| modified.elapsed().ok())
.is_some_and(|age| age > week);
if stale {
let _ = file::remove_all(entry.path());
}
}
}
let Ok(read) = std::fs::read_dir(root.join("blobs")) else {
return;
};
let mut entries = Vec::new();
let mut total = 0u64;
for entry in read.flatten() {
let dir = entry.path();
if entry.file_name().to_string_lossy().starts_with('.')
|| !dir.is_dir()
|| keep == Some(dir.as_path())
{
continue;
}
let (mut size, mut used) = (0, SystemTime::UNIX_EPOCH);
for file in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
if let Ok(meta) = file.metadata() {
size = size.max(meta.len());
used = used.max(meta.modified().unwrap_or(SystemTime::UNIX_EPOCH));
}
}
total += size;
if used.elapsed().is_ok_and(|age| age < IN_USE) {
continue;
}
entries.push((used, size, dir));
}
entries.sort();
let limit = max_cache_bytes();
for (_, size, dir) in entries {
if total <= limit {
break;
}
if file::remove_all(&dir).is_ok() {
total -= size;
}
}
}