DownloadManager

Struct DownloadManager 

Source
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: PathBuf

Download cache directory

§client: Client

HTTP 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

Source

pub async fn new(AppState: Arc<ApplicationState>) -> Result<Self>

Create a new download manager with comprehensive initialization

Source

pub async fn DownloadFile( &self, url: String, DestinationPath: String, checksum: String, ) -> Result<DownloadResult>

Download a file with comprehensive validation and resilience

Source

pub async fn DownloadFileWithConfig( &self, config: DownloadConfig, ) -> Result<DownloadResult>

Download a file with detailed configuration

Source

fn ValidateAndSanitizeUrl(url: &str) -> Result<String>

Validate and sanitize URL to prevent injection attacks

Source

async fn ValidateDiskSpace( &self, url: &str, destination: &Path, RequiredBytes: u64, ) -> Result<()>

Validate available disk space before download

Source

fn GetDiskStatvfs(&self, path: &Path) -> Result<(u64, u64)>

Get disk statistics using statvfs (Unix)

Source

fn FindMountPoint(&self, path: &Path) -> Result<PathBuf>

Find mount point for a given path

Source

async fn DownloadWithRetry( &self, DownloadId: &str, url: &str, destination: &PathBuf, config: &DownloadConfig, ) -> Result<DownloadResult>

Download with retry logic and circuit breaker

Source

async fn PerformDownload( &self, DownloadId: &str, url: &str, destination: &PathBuf, config: &DownloadConfig, ) -> Result<DownloadResult>

Perform the actual download with streaming and partial resume support

Source

pub async fn VerifyChecksum( &self, FilePath: &PathBuf, ExpectedChecksum: &str, ) -> Result<()>

Verify file checksum using ChecksumVerifier

Source

pub async fn CalculateChecksum(&self, FilePath: &PathBuf) -> Result<String>

Calculate file checksum using ChecksumVerifier

Source

async fn RegisterDownload( &self, DownloadId: &str, url: &str, destination: &PathBuf, ExpectedChecksum: Option<String>, ) -> Result<()>

Register a new download in the tracking system

Source

async fn UpdateDownloadStatus( &self, DownloadId: &str, status: DownloadState, progress: Option<f32>, error: Option<String>, ) -> Result<()>

Update download status

Source

async fn UpdateDownloadRate(&self, DownloadId: &str, rate: u64)

Update download rate tracking

Source

async fn UpdateActualChecksum(&self, DownloadId: &str, checksum: &str)

Update actual checksum after calculation

Source

async fn CalculateDownloadRate( &self, DownloadId: &str, CurrentBytes: u64, ) -> u64

Calculate download rate based on progress

Source

async fn UpdateStatistics(&self, success: bool, bytes: u64, duration: Duration)

Update download statistics

Source

pub async fn GetDownloadStatus( &self, DownloadId: &str, ) -> Option<DownloadStatus>

Get download status

Source

pub async fn GetAllDownloads(&self) -> Vec<DownloadStatus>

Get all active downloads

Source

pub async fn CancelDownload(&self, DownloadId: &str) -> Result<()>

Cancel a download with proper cleanup

Source

pub async fn PauseDownload(&self, DownloadId: &str) -> Result<()>

Pause a download (supports resume)

Source

pub async fn ResumeDownload(&self, DownloadId: &str) -> Result<()>

Resume a paused download

Source

pub async fn GetActiveDownloadCount(&self) -> usize

Get active download count

Source

pub async fn GetStatistics(&self) -> DownloadStatistics

Get download statistics

Source

pub async fn QueueDownload( &self, url: String, destination: String, checksum: String, priority: DownloadPriority, ) -> Result<String>

Queue a download with priority

Source

pub async fn ProcessQueue(&self) -> Result<Option<String>>

Process next download from queue

Source

pub async fn StartBackgroundTasks(&self) -> Result<JoinHandle<()>>

Start background tasks for cleanup and queue processing

Source

async fn BackgroundTaskLoop(&self)

Background task loop for cleanup and queue processing

Source

async fn CleanupCompletedDownloads(&self)

Clean up completed downloads from active tracking

Source

async fn CleanupCache(&self) -> Result<()>

Clean up old cache files with safety checks

Source

pub async fn StopBackgroundTasks(&self)

Stop background tasks and clean up resources

Source

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/s
Source

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

Cocoon (Extension Host) downloads VSIX files from marketplace APIs:

  1. Request VSIX download URL from marketplace
  2. Validate extension manifest metadata
  3. Download with progress callbacks for UI updates
  4. Verify SHA-256 checksum of signed .vsix package
  5. Atomic commit to extension installation directory
  6. 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):

  1. Build system initiates dependency downloads
  2. DownloadManager validates package signatures
  3. Parallel chunk downloads for large packages (>50MB)
  4. Bandwidth throttling to prevent network saturation
  5. 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
Source

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
Source

async fn GetRemoteFileSize(&self, url: &str) -> Result<u64>

Get remote file size using HEAD request

Source

async fn DownloadChunk( &self, url: &str, chunk: &ChunkInfo, chunk_index: usize, ) -> Result<()>

Download a single chunk using HTTP Range request

Source

async fn ReassembleChunks( &self, chunks: &[ChunkInfo], destination: &Path, ) -> Result<()>

Reassemble downloaded chunks into final file

Trait Implementations§

Source§

impl Clone for DownloadManager

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more