Skip to main content

CdnClient

Struct CdnClient 

Source
pub struct CdnClient { /* private fields */ }
Expand description

CDN client for downloading content with automatic fallback

Implementations§

Source§

impl CdnClient

Source

pub fn new() -> Result<Self>

Create a new CDN client with default configuration

Source

pub fn with_client(client: Client) -> Self

Create a new CDN client with custom HTTP client

Source

pub fn builder() -> CdnClientBuilder

Create a builder for configuring the CDN client

Source

pub fn add_primary_host(&self, host: impl Into<String>)

Add a primary CDN host

Primary hosts are tried before fallback hosts

Source

pub fn add_primary_hosts( &self, hosts: impl IntoIterator<Item = impl Into<String>>, )

Add multiple primary CDN hosts

Source

pub fn set_primary_hosts( &self, hosts: impl IntoIterator<Item = impl Into<String>>, )

Set primary CDN hosts, replacing any existing ones

Source

pub fn add_fallback_host(&self, host: impl Into<String>)

Add a fallback CDN host

Source

pub fn add_fallback_hosts( &self, hosts: impl IntoIterator<Item = impl Into<String>>, )

Add multiple fallback CDN hosts

Source

pub fn clear_primary_hosts(&self)

Clear all primary hosts

Source

pub fn clear_fallback_hosts(&self)

Clear all fallback hosts

Source

pub fn disable_fallbacks(&self)

Disable fallback hosts (only use primary)

Source

pub fn get_all_hosts(&self) -> Vec<String>

Get all configured hosts (primary first, then fallback)

Source

pub fn with_max_retries(self, max_retries: u32) -> Self

Set the maximum number of retries

Source

pub fn with_initial_backoff_ms(self, initial_backoff_ms: u64) -> Self

Set the initial backoff duration in milliseconds

Source

pub fn with_max_backoff_ms(self, max_backoff_ms: u64) -> Self

Set the maximum backoff duration in milliseconds

Source

pub fn with_backoff_multiplier(self, backoff_multiplier: f64) -> Self

Set the backoff multiplier

Source

pub fn with_jitter_factor(self, jitter_factor: f64) -> Self

Set the jitter factor (0.0 to 1.0)

Source

pub fn with_user_agent(self, user_agent: impl Into<String>) -> Self

Set a custom user agent string

Source

pub fn calculate_backoff(&self, attempt: u32) -> Duration

Calculate backoff duration with exponential backoff and jitter

Source

pub async fn request(&self, url: &str) -> Result<Response>

Make a basic request to a CDN URL

Source

pub fn build_url(cdn_host: &str, path: &str, hash: &str) -> Result<String>

Build a CDN URL for a content hash

CDN URLs follow the pattern: http://{cdn_host}/{path}/{hash[0:2]}/{hash[2:4]}/{hash}

Source

pub async fn check_exists( &self, cdn_host: &str, path: &str, hash: &str, ) -> Result<bool>

Check if content exists on CDN using HEAD request

Source

pub async fn download( &self, cdn_host: &str, path: &str, hash: &str, ) -> Result<Response>

Download content from CDN by hash with automatic fallback

Source

pub async fn download_build_config( &self, cdn_host: &str, path: &str, hash: &str, ) -> Result<Response>

Download BuildConfig from CDN

BuildConfig files are stored at {path}/config/{hash}

Source

pub async fn download_cdn_config( &self, cdn_host: &str, path: &str, hash: &str, ) -> Result<Response>

Download CDNConfig from CDN

CDNConfig files are stored at {path}/config/{hash}

Source

pub async fn download_product_config( &self, cdn_host: &str, config_path: &str, hash: &str, ) -> Result<Response>

Download ProductConfig from CDN

ProductConfig files are stored at {config_path}/{hash} Note: This uses the config_path from CDN response, not the regular path

Source

pub async fn download_key_ring( &self, cdn_host: &str, path: &str, hash: &str, ) -> Result<Response>

Download KeyRing from CDN

KeyRing files are stored at {path}/config/{hash}

Source

pub async fn download_data( &self, cdn_host: &str, path: &str, hash: &str, ) -> Result<Response>

Download data file from CDN

Data files are stored at {path}/data/{hash}

Source

pub async fn download_patch( &self, cdn_host: &str, path: &str, hash: &str, ) -> Result<Response>

Download patch file from CDN

Patch files are stored at {path}/patch/{hash}

Source

pub async fn download_parallel( &self, cdn_host: &str, path: &str, hashes: &[String], max_concurrent: Option<usize>, ) -> Vec<Result<Vec<u8>>>

Download multiple files in parallel

Returns a vector of results in the same order as the input hashes. Failed downloads will be represented as Err values in the vector.

§Arguments
  • cdn_host - CDN host to download from
  • path - Base path on the CDN
  • hashes - List of content hashes to download
  • max_concurrent - Maximum number of concurrent downloads (None = unlimited)
Source

pub async fn download_batched( &self, cdn_host: &str, path: &str, hashes: &[String], ) -> Vec<Result<Vec<u8>>>

Download multiple files using HTTP/2 request batching for optimal performance

This method uses HTTP/2 multiplexing to batch requests efficiently, providing significant performance improvements over traditional parallel downloads.

§Arguments
  • cdn_host - CDN host to download from
  • path - Base path on the CDN
  • hashes - List of content hashes to download
§Returns

Vector of results in the same order as input hashes, containing downloaded data or errors.

§Performance

HTTP/2 multiplexing allows multiple requests over a single connection, reducing:

  • Connection overhead
  • Network latency
  • Server connection pressure

Expected improvement: 2-5x faster than traditional parallel downloads for batches >10 files.

Source

pub async fn download_parallel_with_progress<F>( &self, cdn_host: &str, path: &str, hashes: &[String], max_concurrent: Option<usize>, progress: F, ) -> Vec<Result<Vec<u8>>>
where F: FnMut(usize, usize),

Download multiple files in parallel with progress tracking

Returns a vector of results in the same order as the input hashes. The progress callback is called after each successful download.

§Arguments
  • cdn_host - CDN host to download from
  • path - Base path on the CDN
  • hashes - List of content hashes to download
  • max_concurrent - Maximum number of concurrent downloads (None = unlimited)
  • progress - Callback function called with (completed_count, total_count) after each download
Source

pub async fn download_data_parallel( &self, cdn_host: &str, path: &str, hashes: &[String], max_concurrent: Option<usize>, ) -> Vec<Result<Vec<u8>>>

Download multiple data files in parallel

Source

pub async fn download_config_parallel( &self, cdn_host: &str, path: &str, hashes: &[String], max_concurrent: Option<usize>, ) -> Vec<Result<Vec<u8>>>

Download multiple config files in parallel

Source

pub async fn download_patch_parallel( &self, cdn_host: &str, path: &str, hashes: &[String], max_concurrent: Option<usize>, ) -> Vec<Result<Vec<u8>>>

Download multiple patch files in parallel

Source

pub async fn download_data_batched( &self, cdn_host: &str, path: &str, hashes: &[String], ) -> Vec<Result<Vec<u8>>>

Download multiple data files using HTTP/2 request batching (optimized)

This method provides superior performance for downloading multiple data files by leveraging HTTP/2 multiplexing to reduce connection overhead and latency.

Source

pub async fn download_config_batched( &self, cdn_host: &str, path: &str, hashes: &[String], ) -> Vec<Result<Vec<u8>>>

Download multiple config files using HTTP/2 request batching (optimized)

This method provides superior performance for downloading multiple config files by leveraging HTTP/2 multiplexing to reduce connection overhead and latency.

Source

pub async fn download_patch_batched( &self, cdn_host: &str, path: &str, hashes: &[String], ) -> Vec<Result<Vec<u8>>>

Download multiple patch files using HTTP/2 request batching (optimized)

This method provides superior performance for downloading multiple patch files by leveraging HTTP/2 multiplexing to reduce connection overhead and latency.

Source

pub async fn get_batch_stats(&self) -> Option<BatchStats>

Get statistics for request batching performance

Returns detailed metrics about HTTP/2 batching performance including batch sizes, timing, and HTTP/2 connection usage.

Source

pub async fn download_parallel_to_writers<W>( &self, cdn_host: &str, path: &str, hashes: &[String], writers: Vec<W>, max_concurrent: Option<usize>, ) -> Vec<Result<u64>>
where W: AsyncWrite + Unpin + Send + 'static,

Download multiple files in parallel with streaming to writers (memory-efficient)

This method downloads multiple files concurrently while streaming each file directly to its corresponding writer. This prevents loading all downloads into memory simultaneously, making it suitable for large file batches.

§Arguments
  • cdn_host - CDN host to download from
  • path - Base path for downloads
  • hashes - Vector of file hashes to download
  • writers - Vector of writers (must match hashes length)
  • max_concurrent - Maximum number of concurrent downloads
§Returns

Vector of results with bytes written for each file

Source

pub async fn download_streaming<W>( &self, cdn_host: &str, path: &str, hash: &str, writer: W, ) -> Result<u64>
where W: AsyncWrite + Unpin,

Download content and stream it to a writer

This is useful for large files to avoid loading them entirely into memory.

Source

pub async fn download_chunked<F>( &self, cdn_host: &str, path: &str, hash: &str, callback: F, ) -> Result<u64>
where F: FnMut(&[u8]) -> Result<()>,

Download content and process it in chunks

This allows processing large files without loading them entirely into memory. The callback is called for each chunk received.

Source

pub fn create_resumable_download( &mut self, cdn_host: &str, path: &str, hash: &str, output_file: &Path, ) -> Result<ResumableDownload>

Create a resumable download for a data file

This creates a resumable download that can be paused and resumed from interruption. Progress is saved to disk and the download can survive application crashes.

§Arguments
  • cdn_host - CDN server hostname
  • path - Base path on the CDN (e.g., “tpr/wow”)
  • hash - Content hash to download
  • output_file - Local file path where content should be saved
§Returns

Returns a ResumableDownload instance that can be used to start, pause, and resume the download.

§Example
use ngdp_cdn::CdnClient;
use std::path::PathBuf;

let mut client = CdnClient::new()?;
let mut resumable = client.create_resumable_download(
    "blzddist1-a.akamaihd.net",
    "tpr/wow",
    "2e9c1e3b5f5a0c9d9e8f1234567890ab",
    &PathBuf::from("game_file.bin")
)?;

// Start or resume the download
resumable.start_or_resume().await?;

// Clean up progress file when complete
resumable.cleanup_completed().await?;
Source

pub async fn resume_download( &mut self, progress_file: &Path, ) -> Result<ResumableDownload>

Resume an existing download from a progress file

This method loads an existing progress file and creates a ResumableDownload instance that can continue from where the previous download left off.

§Arguments
  • progress_file - Path to the .download progress file
§Returns

Returns a ResumableDownload instance ready to resume the download.

§Example
use ngdp_cdn::CdnClient;
use std::path::PathBuf;

let mut client = CdnClient::new()?;

// Resume from existing progress file
let mut resumable = client.resume_download(&PathBuf::from("file.bin.download")).await?;
resumable.start_or_resume().await?;
resumable.cleanup_completed().await?;
Source

pub async fn find_resumable_downloads( &self, directory: &Path, ) -> Result<Vec<DownloadProgress>>

Find all resumable downloads in a directory

This is a convenience method that scans a directory for .download progress files and returns information about incomplete downloads.

§Arguments
  • directory - Directory to scan for progress files
§Returns

Returns a vector of DownloadProgress instances for incomplete downloads.

§Example
use ngdp_cdn::CdnClient;
use std::path::PathBuf;

let client = CdnClient::new()?;

// Find all resumable downloads in Downloads folder
let downloads = client.find_resumable_downloads(&PathBuf::from("Downloads")).await?;

for download in downloads {
    println!("Found: {} - {}", download.file_hash, download.progress_string());
}
Source

pub async fn cleanup_old_progress_files( &self, directory: &Path, max_age_hours: u64, ) -> Result<usize>

Clean up old completed progress files in a directory

This method scans for .download progress files that are marked as completed and are older than the specified age, then removes them to free up disk space.

§Arguments
  • directory - Directory to scan and clean up
  • max_age_hours - Maximum age in hours for completed progress files
§Returns

Returns the number of files that were cleaned up.

§Example
use ngdp_cdn::CdnClient;
use std::path::PathBuf;

let client = CdnClient::new()?;

// Clean up progress files older than 24 hours
let cleaned = client.cleanup_old_progress_files(&PathBuf::from("Downloads"), 24).await?;
println!("Cleaned up {} old progress files", cleaned);

Trait Implementations§

Source§

impl Debug for CdnClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. 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> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

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

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

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.

Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + 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, 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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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