Certainly! Below is an enhanced and more sophisticated version of your Rust script. This version incorporates improved error handling, structured logging with colors for better readability, retry mechanisms for robust downloading, and organized code structure for maintainability. The hardcoded values remain intact as per your request.
Enhancements Implemented:
- Structured Logging with Colors: Utilizes the
fern and log crates to provide colored and leveled logging, enhancing readability and debugging.
- Retry Mechanism: Implements retries for failed downloads to increase reliability using the
tokio_retry crate.
- Improved Error Handling: Employs the
thiserror crate to define custom error types for more precise error management.
- Concurrency Control: Maintains and clearly defines concurrency limits for both place IDs and asset downloads.
- Code Organization: Structures the code into modular functions with clear responsibilities and comprehensive documentation.
- Progress Indicators: Integrates progress messages to inform users about the current state of operations.
Dependencies
Make sure to include the following dependencies in your Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.11", features = ["json", "stream"] }
futures = "0.3"
log = "0.4"
fern = "0.6"
chrono = "0.4"
colored = "2.0"
tokio-retry = "0.3"
thiserror = "1.0"
Enhanced Rust Code
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use colored::*;
use futures::stream::{self, StreamExt};
use log::{error, info, warn};
use reqwest::Client;
use tokio::fs::create_dir_all;
use tokio::io::AsyncWriteExt;
use tokio_retry::strategy::{ExponentialBackoff, jitter};
use tokio_retry::Retry;
// Define custom error types for better error handling
use thiserror::Error;
/// Custom error type to encapsulate various errors in the downloader
#[derive(Error, Debug)]
enum DownloadError {
#[error("IO error occurred: {0}")]
Io(#[from] std::io::Error),
#[error("HTTP request failed: {0}")]
Reqwest(#[from] reqwest::Error),
#[error("Failed to parse asset URL: {0}")]
UrlParse(String),
#[error("Unexpected response status: {0}")]
HttpStatus(String),
}
// Entry point of the application with Tokio's asynchronous runtime
#[tokio::main]
async fn main() {
// Initialize the logger with colored output
setup_logger().expect("Failed to initialize logger");
// Base directory where the downloads will be saved
let base_dir = Path::new(r"C:\Users\Lukas\Downloads\lkjhgfd2");
// List of placeIDs
let place_ids = vec![
"10789565990",
"11181971058",
"11181982436",
"11182034319",
"11182037286",
"11263735303",
"11263873956",
"12647442701",
"33564694",
"4568576845",
"4737314314",
"4748963513",
"4956810680",
"4998492434",
"5000291183",
"5063342777",
"5229799451",
"5400427674",
"5465723678",
"5914914682",
"5972110179",
"6087359275",
"6701464352",
"6767882272",
"6768240609",
"6783491168",
"7162161171",
"7730658758",
"9048939285",
];
// Initialize HTTP client with timeout and other configurations
let client = Client::builder()
.timeout(Duration::from_secs(30))
.build()
.expect("Failed to build HTTP client");
// Concurrency settings
let place_concurrency = 5; // Number of placeIDs to process concurrently
let asset_concurrency = 10; // Number of assets to download concurrently per placeID
info!(
"{} Starting the download process.",
"INFO:".green().bold()
);
// Process each placeID concurrently with the defined concurrency limit
stream::iter(place_ids)
.map(|place_id| {
let client = client.clone();
let base_dir = base_dir.to_path_buf();
async move {
if let Err(e) = process_place_id(&client, &base_dir, place_id, asset_concurrency).await {
error!(
"{} Error processing placeID {}: {}",
"ERROR:".red().bold(),
place_id,
e
);
}
}
})
.buffer_unordered(place_concurrency)
.collect::<()>()
.await;
info!(
"{} All downloads completed successfully.",
"INFO:".green().bold()
);
}
/// Sets up the logger with colored output using the fern crate
fn setup_logger() -> Result<(), fern::InitError> {
fern::Dispatch::new()
.format(|out, message, record| {
let level = match record.level() {
log::Level::Error => "ERROR".red().bold(),
log::Level::Warn => "WARN".yellow().bold(),
log::Level::Info => "INFO".green().bold(),
log::Level::Debug => "DEBUG".blue().bold(),
log::Level::Trace => "TRACE".purple().bold(),
};
out.finish(format_args!(
"{} [{}] {}",
chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
level,
message
))
})
.level(log::LevelFilter::Info)
.chain(std::io::stdout())
.apply()?;
Ok(())
}
/// Processes a single placeID:
/// - Reads index.txt
/// - Parses entries
/// - Downloads assets
async fn process_place_id(
client: &Client,
base_dir: &PathBuf,
place_id: &str,
asset_concurrency: usize,
) -> Result<(), DownloadError> {
info!(
"{} Processing placeID: {}",
"INFO:".green().bold(),
place_id
);
// Path to index.txt
let index_path = base_dir.join(place_id).join("index.txt");
// Read index.txt content
let index_content = fs::read_to_string(&index_path).map_err(|e| {
error!(
"{} Failed to read {}: {}",
"ERROR:".red().bold(),
index_path.display(),
e
);
DownloadError::Io(e)
})?;
// Parse index.txt lines
let assets: Vec<(String, String)> = index_content
.lines()
.filter_map(|line| {
let parts: Vec<&str> = line.split('|').map(|s| s.trim()).collect();
if parts.len() == 2 {
Some((parts[0].to_string(), parts[1].to_string()))
} else {
warn!(
"{} Malformed line in {}: {}",
"WARN:".yellow().bold(),
index_path.display(),
line
);
None
}
})
.collect();
info!(
"{} Found {} assets for placeID {}.",
"INFO:".green().bold(),
assets.len(),
place_id
);
// Process asset downloads concurrently with the defined concurrency limit
stream::iter(assets)
.map(|(version, url)| {
let client = client.clone();
let base_dir = base_dir.clone();
let place_id = place_id.to_string();
async move {
if let Err(e) = download_asset(&client, &base_dir, &place_id, &version, &url).await {
error!(
"{} Failed to download asset {} for placeID {}: {}",
"ERROR:".red().bold(),
url,
place_id,
e
);
}
}
})
.buffer_unordered(asset_concurrency)
.collect::<()>()
.await;
info!(
"{} Completed processing placeID: {}",
"INFO:".green().bold(),
place_id
);
Ok(())
}
/// Downloads a single asset and saves it to the designated path with retry logic
async fn download_asset(
client: &Client,
base_dir: &PathBuf,
place_id: &str,
version: &str,
url: &str,
) -> Result<(), DownloadError> {
// Extract asset filename from URL
let asset_filename = url
.split('/')
.last()
.ok_or_else(|| DownloadError::UrlParse(url.to_string()))?;
// Define the target directory and file path
let target_dir = base_dir.join(place_id).join(version);
let target_path = target_dir.join(asset_filename);
// Create directories if they don't exist
create_dir_all(&target_dir).await?;
// Check if the file already exists to avoid re-downloading
if target_path.exists() {
info!(
"{} Asset already exists: {:?}",
"INFO:".green().bold(),
target_path
);
return Ok(());
}
// Define the retry strategy: exponential backoff with jitter, max 3 attempts
let retry_strategy = ExponentialBackoff::from_millis(100).map(jitter).take(3);
// Attempt to download with retries
let response = Retry::spawn(retry_strategy, || async {
let resp = client.get(url).send().await?;
if resp.status().is_success() {
Ok(resp)
} else {
Err(tokio_retry::Error::Retryable(
DownloadError::HttpStatus(format!(
"HTTP {} for URL {}",
resp.status(),
url
)),
))
}
})
.await
.map_err(|e| match e {
tokio_retry::Error::Operation { error, .. } => error,
_ => DownloadError::Reqwest(reqwest::Error::new(
reqwest::StatusCode::INTERNAL_SERVER_ERROR,
e.to_string(),
)),
})?;
// Stream the response bytes to the file
let mut file = tokio::fs::File::create(&target_path).await?;
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let data = chunk?;
file.write_all(&data).await?;
}
info!(
"{} Downloaded: {:?}",
"INFO:".green().bold(),
target_path
);
Ok(())
}
Key Features Explained
-
Structured Logging with Colors:
- The
fern crate is configured in the setup_logger function to format logs with timestamps and colored levels (e.g., INFO in green, ERROR in red).
- Throughout the code,
info!, warn!, and error! macros from the log crate are used to output different levels of logs.
-
Retry Mechanism:
- The
tokio_retry crate is employed to implement a retry strategy for downloading assets. It uses an exponential backoff strategy with jitter and limits retries to three attempts.
- This ensures that transient network issues don't cause the entire download process to fail.
-
Custom Error Handling:
- The
thiserror crate defines a DownloadError enum to categorize different error types, making error management more precise and meaningful.
- Errors are propagated using the
? operator, and detailed error messages are logged.
-
Concurrency Control:
- The concurrency for processing place IDs and downloading assets is managed using the
buffer_unordered combinator from the futures crate.
- This ensures that a controlled number of asynchronous tasks run concurrently, optimizing resource usage without overwhelming the system or network.
-
Code Organization:
- The code is modularized into distinct functions (
main, setup_logger, process_place_id, download_asset) each handling specific responsibilities.
- Comprehensive comments and structured logging statements enhance readability and maintainability.
-
Progress Indicators:
- Informative log messages indicate the start and completion of processing for each place ID and asset, providing clear visibility into the program's progress.
Running the Enhanced Script
-
Setup:
- Ensure you've added the required dependencies to your
Cargo.toml.
- Place the script in your Rust project's
src/main.rs file.
-
Build and Run:
cargo build --release
cargo run --release
-
Observing Logs:
- The console will display colored logs indicating the progress, successful downloads, warnings for malformed lines, and errors if any occur during processing.
Conclusion
This enhanced version provides a robust, maintainable, and user-friendly approach to downloading assets asynchronously in Rust. The incorporation of structured logging, retry mechanisms, and organized code structure ensures that the script is both reliable and easy to debug or extend in the future.