Skip to main content

bindings_generat/llm/
network.rs

1use anyhow::{Context, Result};
2use indicatif::{ProgressBar, ProgressStyle};
3use sha2::{Digest, Sha256};
4use std::path::Path;
5use std::thread;
6use std::time::Duration;
7use tracing::{debug, warn};
8
9/// Maximum number of retry attempts for downloads
10const MAX_RETRIES: u32 = 3;
11
12/// Initial delay in milliseconds for exponential backoff
13const INITIAL_BACKOFF_MS: u64 = 1000;
14
15/// Configuration for downloading files with retry and verification
16#[derive(Debug, Clone)]
17pub struct DownloadConfig {
18    /// URL to download from
19    pub url: String,
20    /// Destination file path
21    pub dest: std::path::PathBuf,
22    /// Optional SHA-256 checksum to verify (hex string)
23    pub checksum: Option<String>,
24    /// Expected size in bytes (for progress bar)
25    pub expected_size: Option<u64>,
26    /// Description for progress messages
27    pub description: String,
28}
29
30impl DownloadConfig {
31    /// Create a new download configuration
32    pub fn new(url: impl Into<String>, dest: impl AsRef<Path>) -> Self {
33        Self {
34            url: url.into(),
35            dest: dest.as_ref().to_path_buf(),
36            checksum: None,
37            expected_size: None,
38            description: "Downloading".to_string(),
39        }
40    }
41
42    /// Set the expected checksum for verification
43    pub fn with_checksum(mut self, checksum: impl Into<String>) -> Self {
44        self.checksum = Some(checksum.into());
45        self
46    }
47
48    /// Set the expected file size
49    pub fn with_expected_size(mut self, size: u64) -> Self {
50        self.expected_size = Some(size);
51        self
52    }
53
54    /// Set the description for progress messages
55    pub fn with_description(mut self, description: impl Into<String>) -> Self {
56        self.description = description.into();
57        self
58    }
59}
60
61/// Download a file with retry logic and optional checksum verification
62pub fn download_with_retry(config: &DownloadConfig) -> Result<()> {
63    let mut attempt = 0;
64
65    loop {
66        attempt += 1;
67
68        match try_download(config, attempt) {
69            Ok(()) => {
70                // Verify checksum if provided
71                if let Some(expected_checksum) = &config.checksum {
72                    debug!("Verifying checksum for {}", config.dest.display());
73                    verify_checksum(&config.dest, expected_checksum)?;
74                }
75                return Ok(());
76            }
77            Err(e) if attempt >= MAX_RETRIES => {
78                anyhow::bail!(
79                    "Failed to download {} after {} attempts: {}",
80                    config.url,
81                    MAX_RETRIES,
82                    e
83                );
84            }
85            Err(e) => {
86                let backoff_ms = INITIAL_BACKOFF_MS * 2u64.pow(attempt - 1);
87                warn!(
88                    "Download attempt {}/{} failed: {}. Retrying in {}ms...",
89                    attempt, MAX_RETRIES, e, backoff_ms
90                );
91                thread::sleep(Duration::from_millis(backoff_ms));
92            }
93        }
94    }
95}
96
97/// Attempt to download a file once
98fn try_download(config: &DownloadConfig, attempt: u32) -> Result<()> {
99    let attempt_msg = if attempt > 1 {
100        format!(" (attempt {}/{})", attempt, MAX_RETRIES)
101    } else {
102        String::new()
103    };
104
105    debug!("Downloading from {}{}", config.url, attempt_msg);
106
107    // Create progress bar
108    let pb = ProgressBar::new(config.expected_size.unwrap_or(0));
109    pb.set_style(
110        ProgressStyle::default_bar()
111            .template(&format!(
112                "    [{{bar:40.cyan/blue}}] {{bytes}}/{{total_bytes}} ({{eta}}) {}{}",
113                config.description, attempt_msg
114            ))
115            .unwrap()
116            .progress_chars("#>-"),
117    );
118
119    // Create HTTP client with timeout
120    let client = reqwest::blocking::Client::builder()
121        .timeout(Duration::from_secs(300)) // 5 minutes
122        .build()
123        .context("Failed to create HTTP client")?;
124
125    // Send request
126    let mut response = client
127        .get(&config.url)
128        .send()
129        .context("Failed to send HTTP request")?;
130
131    if !response.status().is_success() {
132        anyhow::bail!("HTTP error: {}", response.status());
133    }
134
135    // Update progress bar with actual content length
136    if let Some(len) = response.content_length() {
137        pb.set_length(len);
138    }
139
140    // Create destination file
141    let file = std::fs::File::create(&config.dest)
142        .with_context(|| format!("Failed to create file: {}", config.dest.display()))?;
143    let mut file = pb.wrap_write(file);
144
145    // Copy response to file with progress
146    std::io::copy(&mut response, &mut file)
147        .with_context(|| format!("Failed to write to file: {}", config.dest.display()))?;
148
149    let finish_msg = format!("✓ {}", config.description);
150    pb.finish_with_message(finish_msg);
151
152    Ok(())
153}
154
155/// Verify SHA-256 checksum of a file
156fn verify_checksum(path: &Path, expected_hex: &str) -> Result<()> {
157    let mut file =
158        std::fs::File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
159
160    let mut hasher = Sha256::new();
161    std::io::copy(&mut file, &mut hasher)
162        .with_context(|| format!("Failed to read {}", path.display()))?;
163
164    let hash_bytes = hasher.finalize();
165    let actual_hex = format!("{:x}", hash_bytes);
166
167    if actual_hex.eq_ignore_ascii_case(expected_hex) {
168        debug!("Checksum verified for {}", path.display());
169        Ok(())
170    } else {
171        anyhow::bail!(
172            "Checksum mismatch for {}\n  Expected: {}\n  Got:      {}",
173            path.display(),
174            expected_hex,
175            actual_hex
176        );
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn test_download_config_builder() {
186        let config = DownloadConfig::new("https://example.com/file.tar.gz", "/tmp/file.tar.gz")
187            .with_checksum("abc123")
188            .with_expected_size(1024)
189            .with_description("Test file");
190
191        assert_eq!(config.url, "https://example.com/file.tar.gz");
192        assert_eq!(config.dest, Path::new("/tmp/file.tar.gz"));
193        assert_eq!(config.checksum, Some("abc123".to_string()));
194        assert_eq!(config.expected_size, Some(1024));
195        assert_eq!(config.description, "Test file");
196    }
197
198    #[test]
199    fn test_verify_checksum_empty_file() {
200        // Empty file has known SHA-256 hash
201        let temp_dir = tempfile::tempdir().unwrap();
202        let file_path = temp_dir.path().join("empty.txt");
203        std::fs::write(&file_path, b"").unwrap();
204
205        let expected_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
206        verify_checksum(&file_path, expected_hash).unwrap();
207    }
208
209    #[test]
210    fn test_verify_checksum_mismatch() {
211        let temp_dir = tempfile::tempdir().unwrap();
212        let file_path = temp_dir.path().join("test.txt");
213        std::fs::write(&file_path, b"hello").unwrap();
214
215        let wrong_hash = "0000000000000000000000000000000000000000000000000000000000000000";
216        let result = verify_checksum(&file_path, wrong_hash);
217        assert!(result.is_err());
218        assert!(
219            result
220                .unwrap_err()
221                .to_string()
222                .contains("Checksum mismatch")
223        );
224    }
225}