use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
use tracing::{debug, info, warn};
use crate::error::{Aria2Error, Result};
use crate::filesystem::control_file::ControlFile;
const MAX_OUTPUT_FILENAME_BYTES: usize = 255;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutputPathPolicy {
pub allow_overwrite: bool,
pub auto_file_renaming: bool,
pub continue_download: bool,
pub check_integrity: bool,
pub total_length: Option<u64>,
}
impl Default for OutputPathPolicy {
fn default() -> Self {
Self {
allow_overwrite: false,
auto_file_renaming: true,
continue_download: false,
check_integrity: false,
total_length: None,
}
}
}
pub struct ActiveOutputRegistry {
inner: Arc<Mutex<HashSet<PathBuf>>>,
}
#[cfg(feature = "bittorrent")]
#[must_use = "dropping the reservation releases its output paths"]
pub(crate) struct OutputPathReservation {
inner: Arc<Mutex<HashSet<PathBuf>>>,
paths: Vec<PathBuf>,
}
#[cfg(feature = "bittorrent")]
impl Drop for OutputPathReservation {
fn drop(&mut self) {
release_paths(&self.inner, &self.paths);
}
}
impl Default for ActiveOutputRegistry {
fn default() -> Self {
Self::new()
}
}
impl ActiveOutputRegistry {
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(HashSet::new())),
}
}
fn lock_paths(&self) -> MutexGuard<'_, HashSet<PathBuf>> {
self.inner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(feature = "bittorrent")]
pub(crate) fn reserve_exact_paths(
&self,
paths: impl IntoIterator<Item = PathBuf>,
) -> std::result::Result<OutputPathReservation, PathBuf> {
let paths = paths
.into_iter()
.filter(|path| !path.as_os_str().is_empty())
.collect::<Vec<_>>();
let mut registry = self.lock_paths();
if let Some(conflict) = paths.iter().find(|path| registry.contains(*path)) {
return Err(conflict.clone());
}
registry.extend(paths.iter().cloned());
Ok(OutputPathReservation {
inner: Arc::clone(&self.inner),
paths,
})
}
pub async fn resolve(&self, desired: &Path) -> PathBuf {
let mut registry = self.lock_paths();
if !registry.contains(desired) {
registry.insert(desired.to_path_buf());
debug!(
"Output path registered (no conflict): {}",
desired.display()
);
return desired.to_path_buf();
}
let (stem, ext) = split_filename_for_aria2(desired);
let parent = desired.parent().unwrap_or_else(|| Path::new("."));
let mut counter: u32 = 1;
loop {
let candidate = parent.join(numbered_filename(&stem, &ext, counter));
if !registry.contains(&candidate) && !candidate.exists() {
registry.insert(candidate.clone());
warn!(
"Filename collision: '{}' is already in use. Resolved to '{}'",
desired.display(),
candidate.display()
);
return candidate;
}
counter += 1;
if counter > 10_000 {
let fallback = parent.join(numbered_filename(&stem, "", counter));
registry.insert(fallback.clone());
warn!(
"Exhausted normal suffix range for '{}', using fallback '{}'",
desired.display(),
fallback.display()
);
return fallback;
}
}
}
pub async fn resolve_with_policy(
&self,
desired: &Path,
policy: OutputPathPolicy,
) -> Result<PathBuf> {
let mut registry = self.lock_paths();
let desired_claimed = registry.contains(desired);
let desired_exists = desired.exists();
let desired_has_control = ControlFile::control_path_for(desired).exists();
let reusable_existing = desired_exists
&& !desired_claimed
&& (policy.allow_overwrite
|| desired_has_control
|| policy.check_integrity
|| (policy.continue_download
&& compatible_existing_length(desired, policy.total_length)));
if !desired_claimed && (!desired_exists || reusable_existing) {
registry.insert(desired.to_path_buf());
debug!(
path = %desired.display(),
reused = desired_exists,
"Output path registered"
);
return Ok(desired.to_path_buf());
}
if !policy.auto_file_renaming {
return Err(Aria2Error::FileAlreadyExists(desired.display().to_string()));
}
let (stem, ext) = split_filename_for_aria2(desired);
let parent = desired.parent().unwrap_or_else(|| Path::new("."));
for counter in 1..10_000u32 {
let candidate = parent.join(numbered_filename(&stem, &ext, counter));
let candidate_has_control = ControlFile::control_path_for(&candidate).exists();
if !registry.contains(&candidate) && (!candidate.exists() || candidate_has_control) {
registry.insert(candidate.clone());
warn!(
original = %desired.display(),
resolved = %candidate.display(),
"Filename collision resolved"
);
return Ok(candidate);
}
}
Err(Aria2Error::FileRenamingFailed(
desired.display().to_string(),
))
}
pub async fn release(&self, path: &Path) {
let mut registry = self.lock_paths();
if registry.remove(path) {
debug!("Output path released: {}", path.display());
}
}
pub async fn len(&self) -> usize {
self.lock_paths().len()
}
pub async fn is_empty(&self) -> bool {
self.lock_paths().is_empty()
}
}
#[cfg(feature = "bittorrent")]
fn release_paths(inner: &Mutex<HashSet<PathBuf>>, paths: &[PathBuf]) {
let mut registry = inner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for path in paths {
registry.remove(path);
}
}
fn compatible_existing_length(path: &Path, total_length: Option<u64>) -> bool {
match total_length {
Some(total_length) => std::fs::metadata(path)
.map(|metadata| metadata.len() <= total_length)
.unwrap_or(false),
None => path.exists(),
}
}
fn split_filename_for_aria2(path: &Path) -> (String, String) {
let file_name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let extension_start = file_name
.rfind('.')
.filter(|index| *index > 0 && *index + 1 < file_name.len());
match extension_start {
Some(index) => (
file_name[..index].to_string(),
file_name[index..].to_string(),
),
None => (file_name, String::new()),
}
}
fn numbered_filename(stem: &str, ext: &str, counter: u32) -> String {
let suffix = format!(".{counter}");
let extension = truncate_utf8(ext, MAX_OUTPUT_FILENAME_BYTES.saturating_sub(suffix.len()));
let stem_limit = MAX_OUTPUT_FILENAME_BYTES
.saturating_sub(suffix.len())
.saturating_sub(extension.len());
let stem = truncate_utf8(stem, stem_limit);
format!("{stem}{suffix}{extension}")
}
fn truncate_utf8(value: &str, max_bytes: usize) -> &str {
let mut end = value.len().min(max_bytes);
while end > 0 && !value.is_char_boundary(end) {
end -= 1;
}
&value[..end]
}
use std::sync::OnceLock;
static GLOBAL_REGISTRY: OnceLock<ActiveOutputRegistry> = OnceLock::new();
pub fn global_registry() -> &'static ActiveOutputRegistry {
GLOBAL_REGISTRY.get_or_init(|| {
info!("Global ActiveOutputRegistry initialized");
ActiveOutputRegistry::new()
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Aria2Error;
use crate::filesystem::control_file::ControlFile;
#[tokio::test]
async fn test_no_collision_when_unique() {
let reg = ActiveOutputRegistry::new();
let p1 = reg.resolve(Path::new("/tmp/file.txt")).await;
assert_eq!(p1, PathBuf::from("/tmp/file.txt"));
assert_eq!(reg.len().await, 1);
}
#[tokio::test]
async fn test_collision_generates_suffix() {
let reg = ActiveOutputRegistry::new();
let p1 = reg.resolve(Path::new("/tmp/file.txt")).await;
let p2 = reg.resolve(Path::new("/tmp/file.txt")).await;
assert_eq!(p1, PathBuf::from("/tmp/file.txt"));
assert_eq!(p2, PathBuf::from("/tmp/file.1.txt"));
assert_eq!(reg.len().await, 2);
}
#[tokio::test]
async fn test_triple_collision() {
let reg = ActiveOutputRegistry::new();
let _p1 = reg.resolve(Path::new("/tmp/data.bin")).await;
let _p2 = reg.resolve(Path::new("/tmp/data.bin")).await;
let p3 = reg.resolve(Path::new("/tmp/data.bin")).await;
assert_eq!(p3, PathBuf::from("/tmp/data.2.bin"));
}
#[tokio::test]
async fn test_release_allows_reuse() {
let reg = ActiveOutputRegistry::new();
let p1 = reg.resolve(Path::new("/tmp/reusable.txt")).await;
reg.release(&p1).await;
assert!(reg.is_empty().await);
let p2 = reg.resolve(Path::new("/tmp/reusable.txt")).await;
assert_eq!(p2, PathBuf::from("/tmp/reusable.txt"));
}
#[tokio::test]
async fn test_no_extension_handling() {
let reg = ActiveOutputRegistry::new();
let p1 = reg.resolve(Path::new("/tmp/Makefile")).await;
let p2 = reg.resolve(Path::new("/tmp/Makefile")).await;
assert_eq!(p1, PathBuf::from("/tmp/Makefile"));
assert_eq!(p2, PathBuf::from("/tmp/Makefile.1"));
}
#[tokio::test]
async fn test_global_singleton() {
let r1 = global_registry();
let r2 = global_registry();
assert!(Arc::ptr_eq(&r1.inner, &r2.inner));
}
#[tokio::test]
async fn existing_file_is_auto_renamed_by_default() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join("download.bin");
tokio::fs::write(&desired, b"existing").await.unwrap();
let registry = ActiveOutputRegistry::new();
let resolved = registry
.resolve_with_policy(&desired, OutputPathPolicy::default())
.await
.unwrap();
assert_eq!(resolved, dir.path().join("download.1.bin"));
assert_eq!(tokio::fs::read(&desired).await.unwrap(), b"existing");
}
#[tokio::test]
async fn policy_rename_keeps_extension_and_portable_length_limit() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join(format!("{}{}", "a".repeat(251), ".bin"));
tokio::fs::write(&desired, b"existing").await.unwrap();
let registry = ActiveOutputRegistry::new();
let resolved = registry
.resolve_with_policy(&desired, OutputPathPolicy::default())
.await
.unwrap();
let expected = format!("{}{}", "a".repeat(249), ".1.bin");
assert_eq!(
resolved.file_name().unwrap().to_str(),
Some(expected.as_str())
);
assert_eq!(resolved.file_name().unwrap().len(), 255);
}
#[tokio::test]
async fn active_collision_keeps_unextended_name_within_limit() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join("a".repeat(255));
let registry = ActiveOutputRegistry::new();
let _first = registry.resolve(&desired).await;
let resolved = registry.resolve(&desired).await;
let expected = format!("{}{}", "a".repeat(253), ".1");
assert_eq!(
resolved.file_name().unwrap().to_str(),
Some(expected.as_str())
);
assert_eq!(resolved.file_name().unwrap().len(), 255);
}
#[tokio::test]
async fn concurrent_policy_reservations_are_unique() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join("shared.bin");
let registry = Arc::new(ActiveOutputRegistry::new());
let mut tasks = Vec::new();
for _ in 0..16 {
let registry = Arc::clone(®istry);
let desired = desired.clone();
tasks.push(tokio::spawn(async move {
registry
.resolve_with_policy(&desired, OutputPathPolicy::default())
.await
.unwrap()
}));
}
let mut resolved = HashSet::new();
for task in tasks {
resolved.insert(task.await.unwrap());
}
assert_eq!(resolved.len(), 16);
assert_eq!(registry.len().await, 16);
}
#[tokio::test]
async fn allow_overwrite_keeps_existing_file() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join("download.bin");
tokio::fs::write(&desired, b"existing").await.unwrap();
let registry = ActiveOutputRegistry::new();
let resolved = registry
.resolve_with_policy(
&desired,
OutputPathPolicy {
allow_overwrite: true,
..OutputPathPolicy::default()
},
)
.await
.unwrap();
assert_eq!(resolved, desired);
}
#[tokio::test]
async fn continue_keeps_partial_file_when_length_is_compatible() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join("download.bin");
tokio::fs::write(&desired, b"partial").await.unwrap();
let registry = ActiveOutputRegistry::new();
let resolved = registry
.resolve_with_policy(
&desired,
OutputPathPolicy {
continue_download: true,
total_length: Some(100),
..OutputPathPolicy::default()
},
)
.await
.unwrap();
assert_eq!(resolved, desired);
}
#[tokio::test]
async fn existing_file_without_auto_rename_returns_file_exists() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join("download.bin");
tokio::fs::write(&desired, b"existing").await.unwrap();
let registry = ActiveOutputRegistry::new();
let error = registry
.resolve_with_policy(
&desired,
OutputPathPolicy {
auto_file_renaming: false,
..OutputPathPolicy::default()
},
)
.await
.expect_err("existing output must not be silently overwritten");
assert!(matches!(error, Aria2Error::FileAlreadyExists(_)));
}
#[tokio::test]
async fn existing_control_file_reuses_output_path() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join("download.bin");
tokio::fs::write(&desired, b"partial").await.unwrap();
let control = ControlFile::control_path_for(&desired);
tokio::fs::write(&control, b"control").await.unwrap();
let registry = ActiveOutputRegistry::new();
let resolved = registry
.resolve_with_policy(&desired, OutputPathPolicy::default())
.await
.unwrap();
assert_eq!(resolved, desired);
}
#[tokio::test]
async fn occupied_output_is_renamed_even_when_overwrite_is_allowed() {
let dir = tempfile::tempdir().unwrap();
let desired = dir.path().join("download.bin");
let registry = ActiveOutputRegistry::new();
let first = registry
.resolve_with_policy(
&desired,
OutputPathPolicy {
allow_overwrite: true,
..OutputPathPolicy::default()
},
)
.await
.unwrap();
let second = registry
.resolve_with_policy(
&desired,
OutputPathPolicy {
allow_overwrite: true,
..OutputPathPolicy::default()
},
)
.await
.unwrap();
assert_eq!(first, desired);
assert_eq!(second, dir.path().join("download.1.bin"));
}
}