kget/optimization.rs
1//! Download optimization through compression and caching.
2//!
3//! This module provides the [`Optimizer`] struct for configuring and applying
4//! optimizations to downloads:
5//!
6//! - **Compression**: Automatic compression/decompression using Gzip, LZ4, or Brotli
7//! - **Caching**: Store downloaded files locally to avoid redundant downloads
8//! - **Speed limiting**: Control bandwidth usage
9//!
10//! # Example
11//!
12//! ```rust
13//! use kget::Optimizer;
14//!
15//! // Create with default settings
16//! let optimizer = Optimizer::new();
17//!
18//! // Check if compression is enabled
19//! if optimizer.is_compression_enabled() {
20//! println!("Compression active");
21//! }
22//! ```
23
24use crate::config::OptimizationConfig;
25use flate2::write::{GzDecoder, GzEncoder};
26use lz4::block::{CompressionMode, compress};
27use std::error::Error;
28use std::fs::{self, File};
29use std::io::{Read, Write};
30use std::path::PathBuf;
31
32/// Download optimizer for compression, caching, and speed limiting.
33///
34/// The `Optimizer` manages download performance features:
35///
36/// - **Compression**: Reduces storage size using configurable algorithms
37/// - **Caching**: Stores files locally to avoid re-downloading
38/// - **Speed limits**: Controls maximum download speed
39///
40/// # Compression Levels
41///
42/// | Level | Algorithm | Speed | Ratio |
43/// |-------|-----------|----------|----------|
44/// | 1-3 | Gzip | Fast | Moderate |
45/// | 4-6 | LZ4 | Balanced | Good |
46/// | 7-9 | Brotli | Slow | Best |
47///
48/// # Example
49///
50/// ```rust
51/// use kget::{Optimizer, Config};
52///
53/// // From config
54/// let config = Config::default();
55/// let optimizer = Optimizer::from_config(config.optimization);
56///
57/// // Or with defaults
58/// let optimizer = Optimizer::new();
59/// ```
60#[derive(Clone)]
61pub struct Optimizer {
62 config: OptimizationConfig,
63 /// Speed limit in bytes per second (None = unlimited)
64 pub speed_limit: Option<u64>,
65}
66
67impl Optimizer {
68 /// Create a new `Optimizer` with the provided configuration.
69 ///
70 /// # Arguments
71 ///
72 /// * `config` - Optimization configuration settings
73 ///
74 /// # Example
75 ///
76 /// ```rust
77 /// use kget::{Optimizer, Config};
78 ///
79 /// let config = Config::default();
80 /// let optimizer = Optimizer::from_config(config.optimization);
81 /// ```
82 pub fn from_config(config: OptimizationConfig) -> Self {
83 let speed_limit = config.speed_limit;
84 Self {
85 config,
86 speed_limit,
87 }
88 }
89
90 /// Compress data using the configured algorithm.
91 ///
92 /// The algorithm is selected based on `compression_level`:
93 /// - Levels 1-3: Gzip (fast)
94 /// - Levels 4-6: LZ4 (balanced)
95 /// - Levels 7-9: Brotli (high compression)
96 ///
97 /// Returns the original data unchanged if compression is disabled.
98 pub fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> {
99 if !self.config.compression {
100 return Ok(data.to_vec());
101 }
102 let compressed = match self.config.compression_level {
103 1..=3 => {
104 let mut encoder = GzEncoder::new(Vec::new(), flate2::Compression::fast());
105 encoder.write_all(data)?;
106 encoder.finish()?
107 }
108 4..=6 => compress(data, Some(CompressionMode::FAST(0)), true)?,
109 7..=9 => {
110 let mut encoder = brotli::CompressorWriter::new(
111 Vec::new(),
112 self.config.compression_level as usize,
113 4096,
114 22,
115 );
116 encoder.write_all(data)?;
117 encoder.into_inner()
118 }
119 _ => return Ok(data.to_vec()),
120 };
121 Ok(compressed)
122 }
123
124 /// Decompress data using the appropriate algorithm based on the file header
125 ///
126 /// Supports Gzip, Brotli, and LZ4
127 pub fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> {
128 if !self.config.compression {
129 return Ok(data.to_vec());
130 }
131 let mut decompressed = Vec::new();
132 if data.starts_with(&[0x1f, 0x8b]) {
133 let mut decoder = GzDecoder::new(Vec::new());
134 decoder.write_all(data)?;
135 decompressed = decoder.finish()?;
136 } else if data.starts_with(&[0x28, 0xb5, 0x2f, 0xfd]) {
137 let mut decoder = brotli::Decompressor::new(data, 4096);
138 decoder.read_to_end(&mut decompressed)?;
139 } else {
140 let mut decoder = lz4::Decoder::new(data)?;
141 decoder.read_to_end(&mut decompressed)?;
142 }
143 Ok(decompressed)
144 }
145
146 /// Retrieve a file from the cache if it exists.
147 ///
148 /// # Arguments
149 ///
150 /// * `url` - The URL that was used to download the file
151 ///
152 /// # Returns
153 ///
154 /// - `Ok(Some(data))` if the file exists in cache
155 /// - `Ok(None)` if caching is disabled or file doesn't exist
156 /// - `Err` on I/O errors
157 pub fn get_cached_file(&self, url: &str) -> Result<Option<Vec<u8>>, Box<dyn Error>> {
158 if !self.config.cache_enabled {
159 return Ok(None);
160 }
161
162 let _cache_dir = self.config.cache_dir.as_str();
163 let cache_path = self.get_cache_path(url)?;
164 if cache_path.exists() {
165 let mut file = File::open(cache_path)?;
166 let mut contents = Vec::new();
167 file.read_to_end(&mut contents)?;
168 return Ok(Some(contents));
169 }
170 Ok(None)
171 }
172
173 /// Store a file in the cache.
174 ///
175 /// Does nothing if caching is disabled.
176 pub fn cache_file(&self, url: &str, data: &[u8]) -> Result<(), Box<dyn Error>> {
177 if !self.config.cache_enabled {
178 return Ok(());
179 }
180 let cache_path = self.get_cache_path(url)?;
181 if let Some(parent) = cache_path.parent() {
182 fs::create_dir_all(parent)?;
183 }
184 let mut file = File::create(cache_path)?;
185 file.write_all(data)?;
186 Ok(())
187 }
188
189 /// Generate the cache file path for a URL using a simple hash.
190 fn get_cache_path(&self, url: &str) -> Result<PathBuf, Box<dyn Error>> {
191 let mut cache_dir = PathBuf::from(if self.config.cache_dir.is_empty() {
192 "~/.cache/kget".to_string()
193 } else {
194 self.config.cache_dir.clone()
195 });
196
197 if cache_dir.starts_with("~") {
198 if let Some(home) = dirs::home_dir() {
199 cache_dir = home.join(cache_dir.strip_prefix("~").unwrap());
200 }
201 }
202
203 // Simple hash function to generate a unique filename
204 let mut hash = 0u64;
205 for byte in url.bytes() {
206 hash = hash.wrapping_mul(31).wrapping_add(byte as u64);
207 }
208
209 cache_dir.push(format!("{:x}", hash));
210 Ok(cache_dir)
211 }
212
213 /// Get the peer connection limit for torrent downloads.
214 pub fn get_peer_limit(&self) -> usize {
215 50
216 }
217
218 /// Maximum parallel HTTP connections to use for advanced downloads.
219 pub fn max_connections(&self) -> usize {
220 self.config.max_connections.clamp(1, 32)
221 }
222
223 /// Check if compression is enabled.
224 pub fn is_compression_enabled(&self) -> bool {
225 self.config.compression
226 }
227
228 /// Create a new `Optimizer` with default settings.
229 ///
230 /// Equivalent to `Optimizer::default()`.
231 pub fn new() -> Self {
232 Self::default()
233 }
234
235 /// Deprecated alias for `from_config`. Use `Optimizer::from_config()` instead.
236 #[doc(hidden)]
237 pub fn with_config(config: OptimizationConfig) -> Self {
238 Self::from_config(config)
239 }
240}
241
242impl Default for Optimizer {
243 /// Create an `Optimizer` with sensible defaults:
244 /// - Compression enabled at level 6 (LZ4)
245 /// - Caching enabled in ~/.cache/kget
246 /// - No speed limit
247 /// - 4 max connections
248 fn default() -> Self {
249 Self {
250 config: OptimizationConfig {
251 compression: true,
252 compression_level: 6,
253 cache_enabled: true,
254 cache_dir: "~/.cache/kget".to_string(),
255 speed_limit: None,
256 max_connections: 4,
257 },
258 speed_limit: None,
259 }
260 }
261}