pub struct DownloadManager {
AppState: Arc<ApplicationState>,
ActiveDownloads: Arc<RwLock<HashMap<String, DownloadStatus>>>,
DownloadQueue: Arc<RwLock<VecDeque<QueuedDownload>>>,
CacheDirectory: PathBuf,
client: Client,
ChecksumVerifier: Arc<ChecksumVerifier>,
BandwidthLimiter: Arc<Semaphore>,
TokenBucket: Arc<RwLock<TokenBucket>>,
ConcurrentLimiter: Arc<Semaphore>,
statistics: Arc<RwLock<DownloadStatistics>>,
}Expand description
Download manager implementation with full resilience and capabilities
Fields§
§AppState: Arc<ApplicationState>Application state reference
ActiveDownloads: Arc<RwLock<HashMap<String, DownloadStatus>>>Active downloads tracking
DownloadQueue: Arc<RwLock<VecDeque<QueuedDownload>>>Download queue with priority ordering
CacheDirectory: PathBufDownload cache directory
client: ClientHTTP client with connection pooling
ChecksumVerifier: Arc<ChecksumVerifier>Checksum verifier helper
BandwidthLimiter: Arc<Semaphore>Bandwidth limiter for global control
TokenBucket: Arc<RwLock<TokenBucket>>Token bucket for rate limiting
ConcurrentLimiter: Arc<Semaphore>Concurrent download limiter
statistics: Arc<RwLock<DownloadStatistics>>Download statistics
Implementations§
Source§impl DownloadManager
impl DownloadManager
Sourcepub async fn new(AppState: Arc<ApplicationState>) -> Result<Self>
pub async fn new(AppState: Arc<ApplicationState>) -> Result<Self>
Create a new download manager with comprehensive initialization
Sourcepub async fn DownloadFile(
&self,
url: String,
DestinationPath: String,
checksum: String,
) -> Result<DownloadResult>
pub async fn DownloadFile( &self, url: String, DestinationPath: String, checksum: String, ) -> Result<DownloadResult>
Download a file with comprehensive validation and resilience
Sourcepub async fn DownloadFileWithConfig(
&self,
config: DownloadConfig,
) -> Result<DownloadResult>
pub async fn DownloadFileWithConfig( &self, config: DownloadConfig, ) -> Result<DownloadResult>
Download a file with detailed configuration
Sourcefn ValidateAndSanitizeUrl(url: &str) -> Result<String>
fn ValidateAndSanitizeUrl(url: &str) -> Result<String>
Validate and sanitize URL to prevent injection attacks
Sourceasync fn ValidateDiskSpace(
&self,
url: &str,
destination: &Path,
RequiredBytes: u64,
) -> Result<()>
async fn ValidateDiskSpace( &self, url: &str, destination: &Path, RequiredBytes: u64, ) -> Result<()>
Validate available disk space before download
Sourcefn GetDiskStatvfs(&self, path: &Path) -> Result<(u64, u64)>
fn GetDiskStatvfs(&self, path: &Path) -> Result<(u64, u64)>
Get disk statistics using statvfs (Unix)
Sourcefn FindMountPoint(&self, path: &Path) -> Result<PathBuf>
fn FindMountPoint(&self, path: &Path) -> Result<PathBuf>
Find mount point for a given path
Sourceasync fn DownloadWithRetry(
&self,
DownloadId: &str,
url: &str,
destination: &PathBuf,
config: &DownloadConfig,
) -> Result<DownloadResult>
async fn DownloadWithRetry( &self, DownloadId: &str, url: &str, destination: &PathBuf, config: &DownloadConfig, ) -> Result<DownloadResult>
Download with retry logic and circuit breaker
Sourceasync fn PerformDownload(
&self,
DownloadId: &str,
url: &str,
destination: &PathBuf,
config: &DownloadConfig,
) -> Result<DownloadResult>
async fn PerformDownload( &self, DownloadId: &str, url: &str, destination: &PathBuf, config: &DownloadConfig, ) -> Result<DownloadResult>
Perform the actual download with streaming and partial resume support
Sourcepub async fn VerifyChecksum(
&self,
FilePath: &PathBuf,
ExpectedChecksum: &str,
) -> Result<()>
pub async fn VerifyChecksum( &self, FilePath: &PathBuf, ExpectedChecksum: &str, ) -> Result<()>
Verify file checksum using ChecksumVerifier
Sourcepub async fn CalculateChecksum(&self, FilePath: &PathBuf) -> Result<String>
pub async fn CalculateChecksum(&self, FilePath: &PathBuf) -> Result<String>
Calculate file checksum using ChecksumVerifier
Sourceasync fn RegisterDownload(
&self,
DownloadId: &str,
url: &str,
destination: &PathBuf,
ExpectedChecksum: Option<String>,
) -> Result<()>
async fn RegisterDownload( &self, DownloadId: &str, url: &str, destination: &PathBuf, ExpectedChecksum: Option<String>, ) -> Result<()>
Register a new download in the tracking system
Sourceasync fn UpdateDownloadStatus(
&self,
DownloadId: &str,
status: DownloadState,
progress: Option<f32>,
error: Option<String>,
) -> Result<()>
async fn UpdateDownloadStatus( &self, DownloadId: &str, status: DownloadState, progress: Option<f32>, error: Option<String>, ) -> Result<()>
Update download status
Sourceasync fn UpdateDownloadRate(&self, DownloadId: &str, rate: u64)
async fn UpdateDownloadRate(&self, DownloadId: &str, rate: u64)
Update download rate tracking
Sourceasync fn UpdateActualChecksum(&self, DownloadId: &str, checksum: &str)
async fn UpdateActualChecksum(&self, DownloadId: &str, checksum: &str)
Update actual checksum after calculation
Sourceasync fn CalculateDownloadRate(
&self,
DownloadId: &str,
CurrentBytes: u64,
) -> u64
async fn CalculateDownloadRate( &self, DownloadId: &str, CurrentBytes: u64, ) -> u64
Calculate download rate based on progress
Sourceasync fn UpdateStatistics(&self, success: bool, bytes: u64, duration: Duration)
async fn UpdateStatistics(&self, success: bool, bytes: u64, duration: Duration)
Update download statistics
Sourcepub async fn GetDownloadStatus(
&self,
DownloadId: &str,
) -> Option<DownloadStatus>
pub async fn GetDownloadStatus( &self, DownloadId: &str, ) -> Option<DownloadStatus>
Get download status
Sourcepub async fn GetAllDownloads(&self) -> Vec<DownloadStatus>
pub async fn GetAllDownloads(&self) -> Vec<DownloadStatus>
Get all active downloads
Sourcepub async fn CancelDownload(&self, DownloadId: &str) -> Result<()>
pub async fn CancelDownload(&self, DownloadId: &str) -> Result<()>
Cancel a download with proper cleanup
Sourcepub async fn PauseDownload(&self, DownloadId: &str) -> Result<()>
pub async fn PauseDownload(&self, DownloadId: &str) -> Result<()>
Pause a download (supports resume)
Sourcepub async fn ResumeDownload(&self, DownloadId: &str) -> Result<()>
pub async fn ResumeDownload(&self, DownloadId: &str) -> Result<()>
Resume a paused download
Sourcepub async fn GetActiveDownloadCount(&self) -> usize
pub async fn GetActiveDownloadCount(&self) -> usize
Get active download count
Sourcepub async fn GetStatistics(&self) -> DownloadStatistics
pub async fn GetStatistics(&self) -> DownloadStatistics
Get download statistics
Sourcepub async fn QueueDownload(
&self,
url: String,
destination: String,
checksum: String,
priority: DownloadPriority,
) -> Result<String>
pub async fn QueueDownload( &self, url: String, destination: String, checksum: String, priority: DownloadPriority, ) -> Result<String>
Queue a download with priority
Sourcepub async fn ProcessQueue(&self) -> Result<Option<String>>
pub async fn ProcessQueue(&self) -> Result<Option<String>>
Process next download from queue
Sourcepub async fn StartBackgroundTasks(&self) -> Result<JoinHandle<()>>
pub async fn StartBackgroundTasks(&self) -> Result<JoinHandle<()>>
Start background tasks for cleanup and queue processing
Sourceasync fn BackgroundTaskLoop(&self)
async fn BackgroundTaskLoop(&self)
Background task loop for cleanup and queue processing
Sourceasync fn CleanupCompletedDownloads(&self)
async fn CleanupCompletedDownloads(&self)
Clean up completed downloads from active tracking
Sourceasync fn CleanupCache(&self) -> Result<()>
async fn CleanupCache(&self) -> Result<()>
Clean up old cache files with safety checks
Sourcepub async fn StopBackgroundTasks(&self)
pub async fn StopBackgroundTasks(&self)
Stop background tasks and clean up resources
Sourcepub async fn SetBandwidthLimit(&mut self, mb_per_sec: usize)
pub async fn SetBandwidthLimit(&mut self, mb_per_sec: usize)
Set global bandwidth limit (in MB/s)
Updates the token bucket refill rate to enforce the bandwidth limit. The token bucket allows short bursts up to 5x the configured rate.
§Arguments
mb_per_sec- Maximum download speed in megabytes per second (1-1000)
§Example
downloader.SetBandwidthLimit(10).await; // Limit to 10 MB/sSourcepub async fn SetMaxConcurrentDownloads(&mut self, max: usize)
pub async fn SetMaxConcurrentDownloads(&mut self, max: usize)
Set maximum concurrent downloads TODO: Implement per-host concurrent download limits TODO: Add adaptive concurrency based on network conditions
Source§impl DownloadManager
Extension download and validation for Cocoon
impl DownloadManager
Extension download and validation for Cocoon
Cocoon (Extension Host) downloads VSIX files from marketplace APIs:
- Request VSIX download URL from marketplace
- Validate extension manifest metadata
- Download with progress callbacks for UI updates
- Verify SHA-256 checksum of signed .vsix package
- Atomic commit to extension installation directory
- Extract contents and validate before installation
Example Cocoon workflow:
let download_config = DownloadConfig {
url:marketplace_vsix_url,
destination:extension_path,
checksum:expected_sha256,
priority:DownloadPriority::High,
..Default::default()
};
let result = downloader.DownloadFileWithConfig(download_config).await?;
downloader.VerifyChecksum(&PathBuf::from(result.path), &expected_sha256).await?;Package downloads for Mountain (Tauri bundling):
- Build system initiates dependency downloads
- DownloadManager validates package signatures
- Parallel chunk downloads for large packages (>50MB)
- Bandwidth throttling to prevent network saturation
- Atomic staging with final commit to build cache
VSIX download and validation:
- Supports marketplace API authentication tokens
- Validates extension manifest before download
- Verifies package signature after download
- Extracts and validates contents before installation
Sourcepub async fn DownloadFileWithChunks(
&self,
url: String,
destination: String,
checksum: String,
chunk_size_mb: usize,
) -> Result<DownloadResult>
pub async fn DownloadFileWithChunks( &self, url: String, destination: String, checksum: String, chunk_size_mb: usize, ) -> Result<DownloadResult>
Download a large file using parallel chunked downloads
This feature is in progress and will be enhanced with:
- Dynamic chunk size optimization based on bandwidth
- Adaptive chunk count based on file size
- Reassembly with integrity verification TODO: Add adaptive chunk size based on network conditions TODO: Implement parallel download queue management with priority TODO: Add chunk verification and re-download of failed chunks
Sourceasync fn GetRemoteFileSize(&self, url: &str) -> Result<u64>
async fn GetRemoteFileSize(&self, url: &str) -> Result<u64>
Get remote file size using HEAD request
Trait Implementations§
Auto Trait Implementations§
impl Freeze for DownloadManager
impl !RefUnwindSafe for DownloadManager
impl Send for DownloadManager
impl Sync for DownloadManager
impl Unpin for DownloadManager
impl !UnwindSafe for DownloadManager
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].