terraphim_update 1.16.34

Shared auto-update functionality for Terraphim AI binaries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Download functionality with retry logic and exponential backoff
//!
//! This module provides robust download capabilities for update files,
//! including:
//! - Exponential backoff retry strategy
//! - Graceful network error handling
//! - Progress tracking
//! - Timeout handling

use anyhow::{Result, anyhow};
use std::io::{self, Write};
use std::time::{Duration, Instant};
use tracing::{debug, error, info, warn};

/// Default maximum number of retry attempts
pub const DEFAULT_MAX_RETRIES: u32 = 3;

/// Default initial delay between retries (in milliseconds)
pub const DEFAULT_INITIAL_DELAY_MS: u64 = 1000;

/// Default multiplier for exponential backoff
pub const DEFAULT_BACKOFF_MULTIPLIER: f64 = 2.0;

/// Maximum delay between retries (in milliseconds)
pub const MAX_DELAY_MS: u64 = 30000;

/// Configuration for download retry behavior
#[derive(Debug, Clone)]
pub struct DownloadConfig {
    /// Maximum number of retry attempts
    pub max_retries: u32,

    /// Initial delay between retries in milliseconds
    pub initial_delay_ms: u64,

    /// Multiplier for exponential backoff
    pub backoff_multiplier: f64,

    /// Request timeout
    pub timeout: Duration,

    /// Whether to show download progress
    pub show_progress: bool,
}

impl Default for DownloadConfig {
    fn default() -> Self {
        Self {
            max_retries: DEFAULT_MAX_RETRIES,
            initial_delay_ms: DEFAULT_INITIAL_DELAY_MS,
            backoff_multiplier: DEFAULT_BACKOFF_MULTIPLIER,
            timeout: Duration::from_secs(30),
            show_progress: false,
        }
    }
}

impl DownloadConfig {
    /// Create a new download config with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the maximum number of retries
    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// Set the initial delay in milliseconds
    pub fn with_initial_delay_ms(mut self, delay_ms: u64) -> Self {
        self.initial_delay_ms = delay_ms;
        self
    }

    /// Set the backoff multiplier
    pub fn with_backoff_multiplier(mut self, multiplier: f64) -> Self {
        self.backoff_multiplier = multiplier;
        self
    }

    /// Set the timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Enable or disable progress display
    pub fn with_progress(mut self, show: bool) -> Self {
        self.show_progress = show;
        self
    }
}

/// Result of a download operation
#[derive(Debug, Clone)]
pub struct DownloadResult {
    /// Whether the download was successful
    pub success: bool,

    /// Number of attempts made
    pub attempts: u32,

    /// Total duration of all attempts
    pub total_duration: Duration,

    /// Size of the downloaded file in bytes
    pub bytes_downloaded: u64,
}

/// Download a file with retry logic and exponential backoff
///
/// # Arguments
/// * `url` - URL to download from
/// * `output_path` - Path where to save the downloaded file
/// * `config` - Download configuration (optional, uses defaults if not provided)
///
/// # Returns
/// * `Ok(DownloadResult)` - Information about the download
/// * `Err(anyhow::Error)` - Error if download fails after all retries
///
/// # Example
/// ```no_run
/// use terraphim_update::downloader::download_with_retry;
/// use std::path::PathBuf;
///
/// let result = download_with_retry(
///     "https://example.com/binary.tar.gz",
///     &PathBuf::from("/tmp/binary.tar.gz"),
///     None
/// ).unwrap();
/// ```
pub fn download_with_retry(
    url: &str,
    output_path: &std::path::Path,
    config: Option<DownloadConfig>,
) -> Result<DownloadResult> {
    let config = config.unwrap_or_default();
    let start_time = Instant::now();
    let mut attempts = 0;
    let mut last_error: Option<String> = None;

    info!("Starting download from {}", url);

    for attempt in 1..=config.max_retries {
        attempts = attempt;

        let attempt_start = Instant::now();

        match perform_download(url, output_path, &config) {
            Ok(bytes) => {
                let duration = attempt_start.elapsed();

                info!(
                    "Download successful after {} attempt(s) ({:.2}s, {} bytes)",
                    attempt,
                    duration.as_secs_f64(),
                    bytes
                );

                return Ok(DownloadResult {
                    success: true,
                    attempts,
                    total_duration: start_time.elapsed(),
                    bytes_downloaded: bytes,
                });
            }
            Err(e) => {
                last_error = Some(e.to_string());
                let duration = attempt_start.elapsed();

                warn!(
                    "Download attempt {} failed after {:.2}s: {}",
                    attempt,
                    duration.as_secs_f64(),
                    e
                );

                if attempt < config.max_retries {
                    let delay = calculate_backoff_delay(attempt, &config);
                    info!("Waiting {:.2}s before retry...", delay.as_secs_f64());
                    std::thread::sleep(delay);
                }
            }
        }
    }

    let total_duration = start_time.elapsed();

    error!(
        "Download failed after {} attempt(s) ({:.2}s total)",
        attempts,
        total_duration.as_secs_f64()
    );

    Err(anyhow!(
        last_error.unwrap_or_else(|| "Download failed".to_string())
    ))
}

/// Perform a single download attempt
fn perform_download(
    url: &str,
    output_path: &std::path::Path,
    config: &DownloadConfig,
) -> Result<u64> {
    let response = ureq::get(url)
        .timeout(config.timeout)
        .call()
        .map_err(|e| anyhow!("HTTP request failed: {}", e))?;

    if response.status() != 200 {
        return Err(anyhow!(
            "HTTP error: {} {}",
            response.status(),
            response.status_text()
        ));
    }

    let content_length = response
        .header("Content-Length")
        .and_then(|h| h.parse::<u64>().ok());

    let mut reader = response.into_reader();

    let mut file = std::fs::File::create(output_path)?;
    let mut total_bytes = 0u64;
    let mut buffer = [0u8; 8192];

    loop {
        let bytes_read = reader.read(&mut buffer)?;

        if bytes_read == 0 {
            break;
        }

        file.write_all(&buffer[..bytes_read])?;
        total_bytes += bytes_read as u64;

        if config.show_progress {
            if let Some(total) = content_length {
                let percent = (total_bytes as f64 / total as f64) * 100.0;
                print!(
                    "\rProgress: {:.0}% ({}/{} bytes)",
                    percent, total_bytes, total
                );
                io::stdout().flush()?;
            } else {
                print!("\rDownloaded: {} bytes", total_bytes);
                io::stdout().flush()?;
            }
        }
    }

    if config.show_progress {
        println!();
    }

    debug!("Downloaded {} bytes to {:?}", total_bytes, output_path);

    Ok(total_bytes)
}

/// Calculate the delay for exponential backoff
fn calculate_backoff_delay(attempt: u32, config: &DownloadConfig) -> Duration {
    let delay_ms =
        (config.initial_delay_ms as f64) * config.backoff_multiplier.powi(attempt as i32 - 1);

    let delay_ms = delay_ms.min(MAX_DELAY_MS as f64) as u64;

    Duration::from_millis(delay_ms)
}

/// Download a file silently (no retries, fail fast)
///
/// # Arguments
/// * `url` - URL to download from
/// * `output_path` - Path where to save the downloaded file
///
/// # Returns
/// * `Ok(())` - Success
/// * `Err(anyhow::Error)` - Error if download fails
///
/// # Example
/// ```no_run
/// use terraphim_update::downloader::download_silent;
/// use std::path::PathBuf;
///
/// download_silent(
///     "https://example.com/binary.tar.gz",
///     &PathBuf::from("/tmp/binary.tar.gz")
/// ).unwrap();
/// ```
pub fn download_silent(url: &str, output_path: &std::path::Path) -> Result<()> {
    let config = DownloadConfig {
        max_retries: 1,
        show_progress: false,
        ..Default::default()
    };

    download_with_retry(url, output_path, Some(config))?;
    Ok(())
}

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

    fn can_connect(host: &str, port: u16) -> bool {
        let addr = (host, port)
            .to_socket_addrs()
            .ok()
            .and_then(|mut addrs| addrs.next());
        let Some(addr) = addr else {
            return false;
        };
        std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok()
    }

    #[test]
    fn test_download_config_default() {
        let config = DownloadConfig::default();

        assert_eq!(config.max_retries, DEFAULT_MAX_RETRIES);
        assert_eq!(config.initial_delay_ms, DEFAULT_INITIAL_DELAY_MS);
        assert_eq!(config.backoff_multiplier, DEFAULT_BACKOFF_MULTIPLIER);
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert!(!config.show_progress);
    }

    #[test]
    fn test_download_config_builder() {
        let config = DownloadConfig::new()
            .with_max_retries(5)
            .with_initial_delay_ms(2000)
            .with_backoff_multiplier(3.0)
            .with_timeout(Duration::from_secs(60))
            .with_progress(true);

        assert_eq!(config.max_retries, 5);
        assert_eq!(config.initial_delay_ms, 2000);
        assert_eq!(config.backoff_multiplier, 3.0);
        assert_eq!(config.timeout, Duration::from_secs(60));
        assert!(config.show_progress);
    }

    #[test]
    fn test_calculate_backoff_delay() {
        let config = DownloadConfig::default();

        let delay1 = calculate_backoff_delay(1, &config);
        assert_eq!(delay1, Duration::from_millis(1000));

        let delay2 = calculate_backoff_delay(2, &config);
        assert_eq!(delay2, Duration::from_millis(2000));

        let delay3 = calculate_backoff_delay(3, &config);
        assert_eq!(delay3, Duration::from_millis(4000));

        let delay4 = calculate_backoff_delay(4, &config);
        assert_eq!(delay4, Duration::from_millis(8000));
    }

    #[test]
    fn test_calculate_backoff_delay_with_custom_multiplier() {
        let config = DownloadConfig {
            initial_delay_ms: 500,
            backoff_multiplier: 3.0,
            ..Default::default()
        };

        let delay1 = calculate_backoff_delay(1, &config);
        assert_eq!(delay1, Duration::from_millis(500));

        let delay2 = calculate_backoff_delay(2, &config);
        assert_eq!(delay2, Duration::from_millis(1500));

        let delay3 = calculate_backoff_delay(3, &config);
        assert_eq!(delay3, Duration::from_millis(4500));
    }

    #[test]
    fn test_calculate_backoff_delay_max_limit() {
        let config = DownloadConfig {
            initial_delay_ms: 10000,
            backoff_multiplier: 10.0,
            ..Default::default()
        };

        let delay = calculate_backoff_delay(5, &config);

        assert_eq!(delay, Duration::from_millis(MAX_DELAY_MS));
    }

    #[test]
    fn test_download_invalid_url() {
        let temp_dir = tempfile::tempdir().unwrap();
        let output_file = temp_dir.path().join("output.txt");

        let result = download_with_retry(
            "http://localhost:9999/nonexistent",
            &output_file,
            Some(DownloadConfig {
                max_retries: 2,
                ..Default::default()
            }),
        );

        assert!(result.is_err());
        assert!(!output_file.exists());
    }

    #[test]
    fn test_download_with_timeout() {
        // Test timeout behavior against localhost with connection refusal
        // This is reliable and doesn't depend on external network availability
        // The test verifies timeout config is applied correctly, not network latency
        let temp_dir = tempfile::tempdir().unwrap();
        let output_file = temp_dir.path().join("output.txt");

        let start = std::time::Instant::now();

        // Use localhost:9999 which typically refuses connections, causing immediate failure
        // This tests the retry/timeout logic without network flakiness
        let result = download_with_retry(
            "http://localhost:9999/nonexistent",
            &output_file,
            Some(DownloadConfig {
                max_retries: 2,
                timeout: Duration::from_millis(100),
                initial_delay_ms: 50,
                ..Default::default()
            }),
        );

        let elapsed = start.elapsed();

        // Should fail quickly with connection refused
        assert!(result.is_err());
        // Verify the file wasn't created
        assert!(!output_file.exists());
        // With 2 retries and 50ms initial delay, should complete quickly
        assert!(
            elapsed < Duration::from_secs(5),
            "Timeout took too long: {:?}",
            elapsed
        );
    }

    #[test]
    fn test_download_max_retries() {
        let temp_dir = tempfile::tempdir().unwrap();
        let output_file = temp_dir.path().join("output.txt");

        let start = std::time::Instant::now();

        let result = download_with_retry(
            "http://localhost:9999/nonexistent",
            &output_file,
            Some(DownloadConfig {
                max_retries: 3,
                initial_delay_ms: 100,
                ..Default::default()
            }),
        );

        let elapsed = start.elapsed();

        assert!(result.is_err());

        let expected_min_delay = Duration::from_millis(100 + 200);
        assert!(elapsed >= expected_min_delay);
    }

    #[test]
    fn test_download_creates_output_file() {
        // Try Gitea first (managed infrastructure), fallback to localhost test
        let test_url = if can_connect("git.terraphim.cloud", 443) {
            "https://git.terraphim.cloud/api/v1/version"
        } else if can_connect("localhost", 3000) {
            "http://localhost:3000/api/v1/version"
        } else {
            eprintln!("Skipping network test: no available endpoint");
            return;
        };

        let temp_dir = tempfile::tempdir().unwrap();
        let output_file = temp_dir.path().join("output.txt");

        let result = download_with_retry(test_url, &output_file, None);

        assert!(result.is_ok(), "Download should succeed");
        assert!(output_file.exists(), "Output file should be created");
    }

    #[test]
    fn test_download_result_success() {
        // Try Gitea first (managed infrastructure), fallback to localhost test
        let test_url = if can_connect("git.terraphim.cloud", 443) {
            "https://git.terraphim.cloud/api/v1/version"
        } else if can_connect("localhost", 3000) {
            "http://localhost:3000/api/v1/version"
        } else {
            eprintln!("Skipping network test: no available endpoint");
            return;
        };

        let temp_dir = tempfile::tempdir().unwrap();
        let output_file = temp_dir.path().join("output.txt");

        let result = download_with_retry(test_url, &output_file, None).unwrap();

        assert!(result.success, "Download should report success");
        assert!(result.attempts >= 1, "Should have at least one attempt");
        assert!(
            result.total_duration.as_millis() > 0,
            "Duration should be recorded"
        );
    }

    #[test]
    fn test_download_silent_local_file() {
        // Try Gitea first (managed infrastructure), fallback to localhost test
        let test_url = if can_connect("git.terraphim.cloud", 443) {
            "https://git.terraphim.cloud/api/v1/version"
        } else if can_connect("localhost", 3000) {
            "http://localhost:3000/api/v1/version"
        } else {
            eprintln!("Skipping network test: no available endpoint");
            return;
        };

        let temp_dir = tempfile::tempdir().unwrap();
        let output_file = temp_dir.path().join("output.txt");

        let result = download_silent(test_url, &output_file);

        assert!(result.is_ok(), "Silent download should succeed");
        assert!(output_file.exists(), "Output file should be created");
    }
}