xget 0.1.1

xget: fast multi-connection download manager for the terminal: segmented Range downloads, queue, torrents, and curl-like requests.

use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use anyhow::{Context, Result};

use crate::config::{format_bytes, format_duration_precise, format_speed};


#[allow(dead_code)]
pub trait Input: Send + Sync {
    fn label(&self) -> &'static str;
    async fn open(&self) -> Result<()>;
    async fn size(&self) -> Result<Option<u64>>;
    async fn read_range(&self, offset: u64, len: u64) -> Result<Vec<u8>>;
    async fn download(&self, op: &Operation, out: &Output) -> Result<EngineSummary>;
}


#[derive(Debug, Clone, Default)]
pub struct DownloadParams {
    pub connections: usize,
    pub speed_limit_bps: Option<u64>,
    pub retries: u32,
    pub mirrors: Vec<String>,
    pub allow_h3: bool,
    pub auto_mirror: bool,
    pub proxy: Option<String>,
}

#[allow(dead_code)]
#[derive(Debug, Clone, Default)]
pub struct VerifyParams {
    pub expected_total: Option<u64>,
}

#[allow(dead_code)]
#[derive(Debug, Clone, Default)]
pub struct ThrottleParams {
    pub total: u64,
}

#[allow(dead_code)]
#[derive(Debug, Clone, Default)]
pub struct MirrorParams {
    pub candidates: Vec<String>,
    pub total: Option<u64>,
}

#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum Operation {
    Download(DownloadParams),
    Verify(VerifyParams),
    Throttle(ThrottleParams),
    Mirror(MirrorParams),
}

impl Operation {
    #[allow(dead_code)]
    pub fn download(p: DownloadParams) -> Self {
        Self::Download(p)
    }
}


#[derive(Debug, Clone)]
pub enum Output {
    File(PathBuf),
    Dir(PathBuf),
    Stdout,
    Null,
}

impl Output {
    pub fn from_req_output(o: Option<PathBuf>) -> Self {
        match o {
            None => Self::Stdout,
            Some(p) if p.as_os_str() == "/dev/null" => Self::Null,
            Some(p) => Self::File(p),
        }
    }

    #[allow(dead_code)]
    pub fn write_body(&self, bytes: &[u8]) -> Result<()> {
        match self {
            Self::Stdout => {
                use std::io::Write;
                std::io::stdout()
                    .lock()
                    .write_all(bytes)
                    .context("cannot write to stdout")?;
                Ok(())
            }
            Self::Null => Ok(()),
            Self::File(p) => {
                if let Some(parent) = p.parent()
                    && !parent.as_os_str().is_empty()
                {
                    std::fs::create_dir_all(parent)
                        .with_context(|| format!("cannot create {}", parent.display()))?;
                }
                std::fs::write(p, bytes).with_context(|| format!("cannot write {}", p.display()))
            }
            Self::Dir(d) => {
                std::fs::create_dir_all(d)
                    .with_context(|| format!("cannot create {}", d.display()))?;
                Ok(())
            }
        }
    }
}


#[derive(Debug, Clone, Default)]
pub struct EngineSummary {
    pub total_bytes: u64,
    pub elapsed_secs: f64,
    pub avg_bps: f64,
    pub mirrors: Vec<String>,
}

impl EngineSummary {
    #[allow(dead_code)]
    pub fn report(&self) -> String {
        format!(
            "Completed: {} in {} (avg. {})",
            format_bytes(self.total_bytes),
            format_duration_precise(self.elapsed_secs),
            format_speed(self.avg_bps)
        )
    }
}

pub async fn run_input<I: Input>(input: &I, op: &Operation, out: &Output) -> Result<EngineSummary> {
    input.download(op, out).await
}


pub struct Limiter {
    bps: u64,
    start: Instant,
    total: AtomicU64,
}

impl Limiter {
    pub fn new(bps: u64) -> Self {
        Self {
            bps,
            start: Instant::now(),
            total: AtomicU64::new(0),
        }
    }

    pub async fn consume(&self, n: u64) {
        if self.bps == 0 || n == 0 {
            return;
        }
        let t = self.total.fetch_add(n, Ordering::Relaxed).saturating_add(n);
        let target = Duration::from_secs_f64(t as f64 / self.bps as f64);
        loop {
            let elapsed = self.start.elapsed();
            if target <= elapsed {
                return;
            }
            tokio::time::sleep((target - elapsed).min(Duration::from_millis(500))).await;
        }
    }
}


pub async fn backoff(attempt: u32) {
    let ms = 500u64.saturating_mul(1 << attempt.min(5)) + attempt as u64 * 120;
    tokio::time::sleep(Duration::from_millis(ms.min(15_000))).await;
}


pub fn total_style() -> indicatif::ProgressStyle {
    indicatif::ProgressStyle::with_template(
        "{msg} [{bar:32.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, eta {eta})",
    )
    .unwrap()
    .progress_chars("=>-")
}

pub fn seg_style() -> indicatif::ProgressStyle {
    indicatif::ProgressStyle::with_template(
        "  seg {msg} [{bar:28.green/yellow}] {bytes}/{total_bytes} ({bytes_per_sec})",
    )
    .unwrap()
    .progress_chars("=>-")
}

pub fn spinner_style() -> indicatif::ProgressStyle {
    indicatif::ProgressStyle::with_template("{msg} {spinner} {bytes} ({bytes_per_sec})").unwrap()
}

pub fn short_name(p: &std::path::Path) -> String {
    p.file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| p.to_string_lossy().to_string())
}


pub fn hash_range(path: &std::path::Path, start: u64, len: u64) -> Option<String> {
    use std::io::{Read, Seek};
    let mut f = std::fs::File::open(path).ok()?;
    f.seek(std::io::SeekFrom::Start(start)).ok()?;
    let mut hasher = blake3::Hasher::new();
    let mut left = len;
    let mut buf = [0u8; 64 * 1024];
    while left > 0 {
        let want = (left.min(buf.len() as u64)) as usize;
        let mut got = 0;
        while got < want {
            match f.read(&mut buf[got..want]) {
                Ok(0) => return None,
                Ok(n) => got += n,
                Err(_) => return None,
            }
        }
        hasher.update(&buf[..want]);
        left -= want as u64;
    }
    Some(hasher.finalize().to_hex().to_string())
}


pub fn save_json<T: serde::Serialize>(path: &std::path::Path, v: &T) {
    if let Ok(raw) = serde_json::to_string_pretty(v) {
        let _ = std::fs::write(path, raw);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn output_null_discards() {
        assert!(Output::Null.write_body(b"hello").is_ok());
    }

    #[test]
    fn output_from_req_output() {
        assert!(matches!(Output::from_req_output(None), Output::Stdout));
        assert!(matches!(
            Output::from_req_output(Some(PathBuf::from("/dev/null"))),
            Output::Null
        ));
        assert!(matches!(
            Output::from_req_output(Some(PathBuf::from("/tmp/x"))),
            Output::File(_)
        ));
    }

    #[test]
    fn summary_report_mentions_bytes() {
        let s = EngineSummary {
            total_bytes: 1024,
            elapsed_secs: 1.0,
            avg_bps: 1024.0,
            mirrors: vec![],
        };
        assert!(s.report().contains("Completed"));
    }

    #[test]
    fn hash_range_agrees_with_blake3() {
        let dir = std::env::temp_dir().join("xget-engine-hash-test");
        std::fs::create_dir_all(&dir).unwrap();
        let p = dir.join("b.bin");
        let data: Vec<u8> = (0..50_000u32).map(|i| (i % 251) as u8).collect();
        std::fs::write(&p, &data).unwrap();
        let want = blake3::hash(&data[100..20_000]).to_hex().to_string();
        assert_eq!(hash_range(&p, 100, 19_900), Some(want));
        let _ = std::fs::remove_dir_all(&dir);
    }
}