//! Repository file and snapshot download builders. //! //! Builders on [`HFRepository`] for fetching file contents: //! //! - [`HFRepository::download_file`] — download one file to the cache or a local directory. //! - [`HFRepository::download_file_stream`] — stream a file (or byte range) without buffering. //! - [`HFRepository::download_file_to_bytes`] — read a file (or byte range) into memory. //! - [`HFRepository::snapshot_download`] — download all files at a revision, optionally filtered by allow/ignore globs //! matched against repo-relative paths. //! //! Range parameters use Rust `std::ops::Range` semantics (start-inclusive, end-exclusive). //! See each builder's docs for the exact path / range / glob format rules. #[cfg(not(target_family = "wasm"))] use std::{ collections::HashMap, io::{Seek, Write}, path::{Path, PathBuf}, }; use bon::bon; #[cfg(not(target_family = "wasm"))] use futures::TryStreamExt; use futures::stream::{Stream, StreamExt}; #[cfg(not(target_family = "wasm"))] use reqwest::header::IF_NONE_MATCH; #[cfg(not(target_family = "wasm"))] use serde::Deserialize; use super::files::{extract_file_size, missing_xet_file_size_error}; #[cfg(not(target_family = "wasm"))] use super::{ FileMetadataInfo, files::{ admit_commit, admit_etag, extract_commit_hash, extract_etag, extract_xet_file_size, extract_xet_hash, matches_any_glob, }, }; use super::{HFRepository, RepoTreeEntry, RepoType}; #[cfg(not(target_family = "wasm"))] use crate::cache::storage as cache; use crate::error::{HFError, HFResult}; use crate::progress::{DownloadEvent, EmitEvent, FileProgress, FileStatus, Progress}; use crate::{constants, retry}; #[cfg(not(target_family = "wasm"))] mod local; #[cfg(not(target_family = "wasm"))] use local::{LocalDownload, ensure_local_repo_path}; /// Boxed byte stream returned by [`HFRepository::download_file_stream`]. /// /// `Send + Unpin` on native targets; on wasm the browser `reqwest` backend /// produces `!Send` streams, so the `Send` bound is dropped. #[cfg(not(target_family = "wasm"))] pub type HFByteStream = Box> + Send + Unpin>; #[cfg(target_family = "wasm")] pub type HFByteStream = Box> + Unpin>; /// Internal options struct used by the file download helpers. #[cfg(not(target_family = "wasm"))] struct DownloadFileParams { filename: String, local_dir: Option, revision: Option, force_download: bool, local_files_only: bool, progress: Option, } /// Internal options struct used by the streaming download helpers. struct DownloadFileStreamParams { filename: String, revision: Option, range: Option>, progress: Option, } #[cfg(not(target_family = "wasm"))] struct CachedFileTarget<'a> { cache_dir: &'a Path, repo_folder: &'a str, revision: &'a str, commit_hash: &'a str, filename: &'a str, etag: &'a str, } #[cfg(not(target_family = "wasm"))] struct CachedFileVersion { commit: String, etag: String, } /// Internal options struct used by `snapshot_download_impl`. #[cfg(not(target_family = "wasm"))] struct SnapshotDownloadParams { revision: Option, allow_patterns: Option>, ignore_patterns: Option>, local_dir: Option, force_download: bool, local_files_only: bool, max_workers: Option, progress: Option, } /// Reject a repo file path that would resolve outside the directory it is joined onto. /// /// Download destinations are built with `dir.join(filename)`, where `dir` is the caller's /// `local_dir` or the cache snapshot folder and `filename` comes from the caller or from the /// repo's file listing. `Path::join` follows `..` and replaces the base entirely when given an /// absolute, root-relative, drive or UNC path. Same rules as the Python client's /// `_validate_relative_filename`, applied under both POSIX and Windows path rules on every /// platform, so a tree written on Linux is still safe to read on Windows. #[cfg(not(target_family = "wasm"))] fn ensure_relative_repo_path(filename: &str) -> Result<(), String> { let normalized = filename.replace('\\', "/"); if normalized.split('/').any(|segment| segment == "..") { return Err(format!( "file path {filename:?} must not contain a '..' segment" )); } let anchored = filename.starts_with(['/', '\\']) || filename .split('/') .any(|part| part.starts_with('\\') || part.chars().nth(1) == Some(':')); if anchored { return Err(format!( "file path {filename:?} must be relative to the repository root (no absolute, drive or UNC path)" )); } if normalized .split('/') .all(|segment| segment.is_empty() || segment == ".") { return Err(format!("file path {filename:?} does not name a file")); } Ok(()) } impl HFRepository { #[cfg(not(target_family = "wasm"))] async fn download_file_impl(&self, params: DownloadFileParams) -> HFResult { let result = self.download_file_inner(¶ms).await; if result.is_ok() { params.progress.emit(DownloadEvent::Complete); } result } #[cfg(not(target_family = "wasm"))] async fn download_file_inner(&self, params: &DownloadFileParams) -> HFResult { ensure_relative_repo_path(¶ms.filename).map_err(HFError::InvalidParameter)?; if let Some(local_dir) = ¶ms.local_dir { ensure_local_repo_path(¶ms.filename).map_err(HFError::InvalidParameter)?; if params.local_files_only { let dest_path = local_dir.join(¶ms.filename); return if dest_path.is_file() { Ok(dest_path) } else { Err(HFError::LocalEntryNotFound { path: params.filename.clone(), }) }; } self.download_file_to_local_dir(params).await } else { if !self.hf_client.cache_enabled() { return Err(HFError::CacheNotEnabled); } self.download_file_to_cache(params).await } } // Determine whether the file is xet-backed and learn its size. // // Native: HEAD the resolve URL and read `X-Xet-Hash` / // `Content-Length` / `X-Linked-Size` from the response headers. Stop at the // first absolute redirect: the Hub sets those headers on the 302 itself and // the CDN response it points at has none of them. // // Wasm: the resolve URL 302-redirects to a CAS blob URL, and the Fetch // spec only surfaces the final response's headers when following // redirects (`redirect: 'manual'` doesn't help — it yields an opaque // response with no readable headers). So on wasm we dispatch via // `paths-info`, a non-redirecting JSON endpoint that returns the same // metadata in the body. #[cfg(not(target_family = "wasm"))] async fn resolve_xet_hash_and_size( &self, revision: &str, filename: &str, ) -> HFResult<(Option, Option)> { let repo_path = self.repo_path(); let url = self.hf_client.download_url( self.repo_type.url_prefix(), &repo_path, revision, filename, )?; let headers = self.hf_client.auth_headers(); let head_response = self .hf_client .head_with_relative_redirects(&url, &headers) .await?; let head_response = if head_response.status().is_redirection() { head_response } else { self.hf_client .check_response( head_response, Some(&repo_path), crate::error::NotFoundContext::Entry { path: filename.to_string(), }, ) .await? }; Ok(( extract_xet_hash(&head_response), extract_file_size(&head_response), )) } #[cfg(target_family = "wasm")] async fn resolve_xet_hash_and_size( &self, revision: &str, filename: &str, ) -> HFResult<(Option, Option)> { let entries = self .get_paths_info() .paths(vec![filename.to_string()]) .revision(revision.to_string()) .send() .await?; let entry = entries .into_iter() .find(|e| matches!(e, RepoTreeEntry::File { path, .. } if path == filename)); match entry { Some(RepoTreeEntry::File { xet_hash, size, .. }) => Ok((xet_hash, Some(size))), _ => Err(HFError::EntryNotFound { path: filename.to_string(), repo_id: self.repo_path(), context: None, }), } } async fn download_file_stream_impl( &self, params: DownloadFileStreamParams, ) -> HFResult<(Option, HFByteStream)> { if let Some(ref range) = params.range && range.start >= range.end { return Err(HFError::InvalidParameter(format!( "range start ({}) must be less than end ({})", range.start, range.end ))); } let revision = params .revision .as_deref() .unwrap_or(constants::DEFAULT_REVISION); let repo_path = self.repo_path(); let url = self.hf_client.download_url( self.repo_type.url_prefix(), &repo_path, revision, ¶ms.filename, )?; let headers = self.hf_client.auth_headers(); let (xet_hash, file_size_hint) = self .resolve_xet_hash_and_size(revision, ¶ms.filename) .await?; if let Some(xet_hash) = xet_hash { let file_size = file_size_hint .ok_or_else(|| missing_xet_file_size_error(¶ms.filename, url.clone()))?; let content_length = params .range .as_ref() .map(|r| r.end.saturating_sub(r.start)) .or(Some(file_size)); let stream = self .xet_download_stream(revision, &xet_hash, file_size, params.range.clone()) .await?; let total_bytes = content_length.unwrap_or(0); params.progress.emit(DownloadEvent::Start { total_files: 1, total_bytes, }); let wrapped = wrap_stream_with_progress( Box::new(Box::pin(stream)), params.progress, params.filename, total_bytes, ); #[cfg(target_family = "wasm")] let wrapped = buffer_wasm_stream(wrapped); return Ok((content_length, wrapped)); } let range_header = params .range .as_ref() .map(|r| format!("bytes={}-{}", r.start, r.end.saturating_sub(1))); let response = retry::retry(self.hf_client.retry_config(), || { let mut req = self .hf_client .http_client() .get(&url) .headers(headers.clone()); if let Some(ref range) = range_header { req = req.header(reqwest::header::RANGE, range); } req.send() }) .await?; let response = self .hf_client .check_response( response, Some(&repo_path), crate::error::NotFoundContext::Entry { path: params.filename.clone(), }, ) .await?; let content_length = extract_file_size(&response); let total_bytes = content_length.unwrap_or(0); let stream = response.bytes_stream().map(|r| r.map_err(HFError::from)); params.progress.emit(DownloadEvent::Start { total_files: 1, total_bytes, }); let wrapped = wrap_stream_with_progress( Box::new(Box::pin(stream)), params.progress, params.filename, total_bytes, ); #[cfg(target_family = "wasm")] let wrapped = buffer_wasm_stream(wrapped); Ok((content_length, wrapped)) } async fn download_file_to_bytes_impl( &self, params: DownloadFileStreamParams, ) -> HFResult { let (_, stream) = self.download_file_stream_impl(params).await?; futures::pin_mut!(stream); let mut buf = bytes::BytesMut::new(); while let Some(chunk) = stream.next().await { buf.extend_from_slice(&chunk?); } Ok(buf.freeze()) } #[cfg(not(target_family = "wasm"))] async fn download_file_to_local_dir(&self, params: &DownloadFileParams) -> HFResult { let revision = params .revision .as_deref() .unwrap_or(constants::DEFAULT_REVISION); let repo_path = self.repo_path(); let url = self.hf_client.download_url( self.repo_type.url_prefix(), &repo_path, revision, ¶ms.filename, )?; let headers = self.hf_client.auth_headers(); let head_response = self .hf_client .head_with_relative_redirects(&url, &headers) .await?; let head_response = if head_response.status().is_redirection() { head_response } else { self.hf_client .check_response( head_response, Some(&repo_path), crate::error::NotFoundContext::Entry { path: params.filename.clone(), }, ) .await? }; let has_xet_hash = head_response .headers() .get(constants::HEADER_X_XET_HASH) .is_some(); let file_size = if has_xet_hash { extract_xet_file_size(&head_response, ¶ms.filename)? } else { extract_file_size(&head_response).unwrap_or(0) }; params.progress.emit(DownloadEvent::Start { total_files: 1, total_bytes: file_size, }); let local_dir = params.local_dir.as_ref().unwrap(); let existing = local_dir.join(¶ms.filename); let file_hash = extract_xet_hash(&head_response); if has_xet_hash && file_hash.is_none() { return Err(HFError::malformed_response("invalid X-Xet-Hash header")); } if !params.force_download && file_size != 0 && existing .metadata() .is_ok_and(|meta| meta.is_file() && meta.len() == file_size) { emit_local_file_complete(params, file_size); return Ok(existing); } let etag = extract_etag(&head_response); let content_id = file_hash.as_deref().or(etag.as_deref()); let local = LocalDownload::prepare( local_dir, ¶ms.filename, &url, content_id.unwrap_or_default(), ) .await?; if let Some(file_hash) = file_hash { self.xet_download_to_path( revision, crate::xet::XetFileTarget { filename: ¶ms.filename, file_hash: &file_hash, file_size, path: &local.staged, force_download: params.force_download, }, ¶ms.progress, ) .await?; return local.publish(&local.staged); } let incomplete_path = cache::incomplete_path(&local.staged); let resume_offset = match cache::partial_download_state( &incomplete_path, file_size, params.force_download || content_id.is_none(), )? { cache::PartialDownloadState::Resume(offset) => offset, // A full-sized incomplete file can remain after a body read fails. cache::PartialDownloadState::Complete | cache::PartialDownloadState::Restart => 0, }; let (response, write_offset) = self .http_download_response( &url, &repo_path, ¶ms.filename, headers, resume_offset, file_size, ) .await?; stream_response_to_file_with_progress( response, &incomplete_path, ¶ms.progress, Some(¶ms.filename), file_size, write_offset, ) .await?; let path = local.publish(&incomplete_path)?; emit_local_file_complete(params, file_size); Ok(path) } /// Resolve a file from the local cache without making network requests. /// Matches Python's `try_to_load_from_cache`: checks the snapshot pointer /// first, then consults `.no_exist` markers for negative cache hits. #[cfg(not(target_family = "wasm"))] fn resolve_from_cache_only( &self, repo_folder: &str, revision: &str, filename: &str, ) -> HFResult { let cache_dir = self.hf_client.cache_dir(); let commit_hash = if cache::is_commit_hash(revision) { Some(revision.to_string()) } else { cache::read_ref_sync(cache_dir, repo_folder, revision)? }; if let Some(ref hash) = commit_hash { let snap = cache::snapshot_path(cache_dir, repo_folder, hash, filename); if snap.exists() { return Ok(snap); } if cache::no_exist_path(cache_dir, repo_folder, hash, filename).exists() { return Err(HFError::EntryNotFound { path: filename.to_string(), repo_id: String::new(), context: None, }); } } Err(HFError::LocalEntryNotFound { path: filename.to_string(), }) } /// Resolve the cached commit and ETag together from the same snapshot. /// If the snapshot is a regular file because symlinks are unavailable, /// `read_link` returns `None` and conditional requests are skipped. #[cfg(not(target_family = "wasm"))] fn find_cached_file_version( &self, repo_folder: &str, revision: &str, filename: &str, ) -> Option { let cache_dir = self.hf_client.cache_dir(); let commit_hash = if cache::is_commit_hash(revision) { Some(revision.to_string()) } else { cache::read_ref_sync(cache_dir, repo_folder, revision) .ok() .flatten() }; let hash = commit_hash?; let snap = cache::snapshot_path(cache_dir, repo_folder, &hash, filename); let target = std::fs::read_link(&snap).ok()?; let etag = target.file_name()?.to_str()?.to_string(); Some(CachedFileVersion { commit: hash, etag }) } #[cfg(not(target_family = "wasm"))] async fn download_file_to_cache(&self, params: &DownloadFileParams) -> HFResult { let revision = params .revision .as_deref() .unwrap_or(constants::DEFAULT_REVISION); let cache_dir = self.hf_client.cache_dir(); let repo_folder = cache::repo_folder_name(&self.repo_path(), self.repo_type.plural()); let force_download = params.force_download; if cache::is_commit_hash(revision) && !force_download { let snap = cache::snapshot_path(cache_dir, &repo_folder, revision, ¶ms.filename); if snap.exists() { return Ok(snap); } } if params.local_files_only { return self.resolve_from_cache_only(&repo_folder, revision, ¶ms.filename); } let result = self .download_file_to_cache_network( params, revision, cache_dir, &repo_folder, force_download, ) .await; match &result { Err(e) if e.is_transient() && !force_download => self .resolve_from_cache_only(&repo_folder, revision, ¶ms.filename) .or(result), _ => result, } } #[cfg(not(target_family = "wasm"))] async fn head_for_cached_download( &self, url: &str, cache_dir: &Path, repo_folder: &str, revision: &str, mut cached_version: Option, ) -> HFResult<(reqwest::Response, Option)> { let mut headers = self.hf_client.auth_headers(); if let Some(version) = &cached_version && let Ok(value) = reqwest::header::HeaderValue::from_str(&format!("\"{}\"", version.etag)) { headers.insert(IF_NONE_MATCH, value); } else { cached_version = None; } let response = self .hf_client .head_with_relative_redirects(url, &headers) .await?; if response.status() == reqwest::StatusCode::NOT_MODIFIED && extract_commit_hash(&response).is_none() && let Some(version) = &cached_version && !cache::is_commit_hash(revision) && cache::read_ref(cache_dir, repo_folder, revision) .await? .as_ref() != Some(&version.commit) { headers.remove(IF_NONE_MATCH); return Ok(( self.hf_client .head_with_relative_redirects(url, &headers) .await?, None, )); } Ok((response, cached_version)) } #[cfg(not(target_family = "wasm"))] async fn download_file_to_cache_network( &self, params: &DownloadFileParams, revision: &str, cache_dir: &Path, repo_folder: &str, force_download: bool, ) -> HFResult { let repo_path = self.repo_path(); let url = self.hf_client.download_url( self.repo_type.url_prefix(), &repo_path, revision, ¶ms.filename, )?; let cached_version = if !force_download { self.find_cached_file_version(repo_folder, revision, ¶ms.filename) } else { None }; let (head_response, cached_version) = self .head_for_cached_download(&url, cache_dir, repo_folder, revision, cached_version) .await?; let status = head_response.status(); if status == reqwest::StatusCode::NOT_FOUND { return Err(mark_no_exist_and_return_error( cache_dir, repo_folder, revision, &head_response, &repo_path, ¶ms.filename, ) .await); } if status == reqwest::StatusCode::NOT_MODIFIED { let version = cached_version.ok_or_else(|| { HFError::malformed_response_at("304 Not Modified without cached ETag", url.clone()) })?; let response_commit = extract_commit_hash(&head_response); let commit_hash = response_commit.as_deref().unwrap_or(&version.commit); // A headerless 304 can reuse the cached snapshot without writing the // ref. Another download may advance the ref after our HEAD finishes. let ref_to_update = if response_commit.is_some() { revision } else { &version.commit }; let etag = admit_etag(&version.etag)?; let commit_hash = admit_commit(commit_hash, revision)?; let lock = cache::acquire_lock(cache_dir, repo_folder, &etag).await?; return finalize_cached_file( &lock, CachedFileTarget { cache_dir, repo_folder, revision: ref_to_update, commit_hash: &commit_hash, filename: ¶ms.filename, etag: &etag, }, false, ) .await; } let etag = extract_etag(&head_response) .ok_or_else(|| HFError::malformed_response_at("missing ETag header", url.clone())); let commit_hash = extract_commit_hash(&head_response); let xet_hash = extract_xet_hash(&head_response); let xet_file_size = xet_hash .as_ref() .map(|_| extract_xet_file_size(&head_response, ¶ms.filename)); let file_size = match &xet_file_size { Some(xet_file_size) => xet_file_size.as_ref().map_or(0, |size| *size), None => extract_file_size(&head_response).unwrap_or_else(|| { tracing::warn!(url = %url, "missing or invalid Content-Length/X-Linked-Size header, defaulting file size to 0"); 0 }), }; if !status.is_success() && !status.is_redirection() { self.hf_client .check_response( head_response, Some(&repo_path), crate::error::NotFoundContext::Entry { path: params.filename.clone(), }, ) .await?; } let etag = admit_etag(&etag?)?; let commit_hash = commit_hash.ok_or_else(|| { HFError::malformed_response_at("missing X-Repo-Commit header", url.clone()) })?; let commit_hash = admit_commit(&commit_hash, revision)?; params.progress.emit(DownloadEvent::Start { total_files: 1, total_bytes: file_size, }); let snapshot_path = cache::snapshot_path(cache_dir, repo_folder, &commit_hash, ¶ms.filename); if snapshot_path.exists() && !force_download { if !cache::is_commit_hash(revision) && let Err(error) = cache::write_ref(cache_dir, repo_folder, revision, &commit_hash).await { tracing::debug!(%error, revision, %commit_hash, "failed to update cache ref for existing snapshot"); } params.progress.emit(DownloadEvent::Progress { files: vec![FileProgress { filename: params.filename.clone(), bytes_completed: file_size, total_bytes: file_size, status: FileStatus::Complete, }], }); return Ok(snapshot_path); } if let Some(xet_file_size) = xet_file_size { let xet_hash = xet_hash.ok_or_else(|| { HFError::malformed_response_at("missing X-Xet-Hash header", url.clone()) })?; let blob = cache::blob_path(cache_dir, repo_folder, &etag); let lock = cache::acquire_lock(cache_dir, repo_folder, &etag).await?; if snapshot_path.exists() && !force_download { if !cache::is_commit_hash(revision) && let Err(error) = cache::write_ref(cache_dir, repo_folder, revision, &commit_hash).await { tracing::debug!(%error, revision, %commit_hash, "failed to update cache ref for existing snapshot"); } params.progress.emit(DownloadEvent::Progress { files: vec![FileProgress { filename: params.filename.clone(), bytes_completed: file_size, total_bytes: file_size, status: FileStatus::Complete, }], }); return Ok(snapshot_path); } let new_blob = !blob.exists(); if new_blob || force_download { if let Some(parent) = blob.parent() { std::fs::create_dir_all(parent)?; } self.xet_download_to_path( revision, crate::xet::XetFileTarget { filename: ¶ms.filename, file_hash: &xet_hash, file_size: xet_file_size?, path: &blob, force_download, }, ¶ms.progress, ) .await?; } return finalize_cached_file( &lock, CachedFileTarget { cache_dir, repo_folder, revision, commit_hash: &commit_hash, filename: ¶ms.filename, etag: &etag, }, new_blob, ) .await; } let blob = cache::blob_path(cache_dir, repo_folder, &etag); let lock = cache::acquire_lock(cache_dir, repo_folder, &etag).await?; if snapshot_path.exists() && !force_download { if !cache::is_commit_hash(revision) && let Err(error) = cache::write_ref(cache_dir, repo_folder, revision, &commit_hash).await { tracing::debug!(%error, revision, %commit_hash, "failed to update cache ref for existing snapshot"); } params.progress.emit(DownloadEvent::Progress { files: vec![FileProgress { filename: params.filename.clone(), bytes_completed: file_size, total_bytes: file_size, status: FileStatus::Complete, }], }); return Ok(snapshot_path); } if blob.exists() && !force_download { params.progress.emit(DownloadEvent::Progress { files: vec![FileProgress { filename: params.filename.clone(), bytes_completed: file_size, total_bytes: file_size, status: FileStatus::Complete, }], }); return finalize_cached_file( &lock, CachedFileTarget { cache_dir, repo_folder, revision, commit_hash: &commit_hash, filename: ¶ms.filename, etag: &etag, }, false, ) .await; } let new_blob = !blob.exists(); let incomplete_path = cache::incomplete_path(&blob); if let Some(parent) = incomplete_path.parent() { std::fs::create_dir_all(parent)?; } let partial = cache::partial_download_state(&incomplete_path, file_size, force_download)?; if partial != cache::PartialDownloadState::Complete { let resume_offset = match partial { cache::PartialDownloadState::Resume(offset) => offset, _ => 0, }; let (response, write_offset) = self .http_download_response( &url, &repo_path, ¶ms.filename, self.hf_client.auth_headers(), resume_offset, file_size, ) .await?; stream_response_to_file_with_progress( response, &incomplete_path, ¶ms.progress, Some(¶ms.filename), file_size, write_offset, ) .await?; } params.progress.emit(DownloadEvent::Progress { files: vec![FileProgress { filename: params.filename.clone(), bytes_completed: file_size, total_bytes: file_size, status: FileStatus::Complete, }], }); std::fs::rename(&incomplete_path, &blob)?; finalize_cached_file( &lock, CachedFileTarget { cache_dir, repo_folder, revision, commit_hash: &commit_hash, filename: ¶ms.filename, etag: &etag, }, new_blob, ) .await } #[cfg(not(target_family = "wasm"))] async fn http_download_response( &self, url: &str, repo_path: &str, filename: &str, headers: reqwest::header::HeaderMap, resume_offset: u64, file_size: u64, ) -> HFResult<(reqwest::Response, u64)> { let response = self .http_download_response_once(url, repo_path, filename, headers.clone(), resume_offset) .await?; if resume_offset == 0 { return Ok((response, 0)); } if response.status() == reqwest::StatusCode::PARTIAL_CONTENT && content_range_matches(response.headers(), resume_offset, file_size) { return Ok((response, resume_offset)); } tracing::warn!( url, resume_offset, "server did not return a valid partial response; restarting download" ); let response = self .http_download_response_once(url, repo_path, filename, headers, 0) .await?; Ok((response, 0)) } #[cfg(not(target_family = "wasm"))] async fn http_download_response_once( &self, url: &str, repo_path: &str, filename: &str, headers: reqwest::header::HeaderMap, resume_offset: u64, ) -> HFResult { let response = retry::retry(self.hf_client.retry_config(), || { let mut request = self .hf_client .http_client() .get(url) .headers(headers.clone()); if resume_offset > 0 { request = request.header(reqwest::header::RANGE, format!("bytes={resume_offset}-")); } request.send() }) .await?; self.hf_client .check_response( response, Some(repo_path), crate::error::NotFoundContext::Entry { path: filename.to_string(), }, ) .await } #[cfg(not(target_family = "wasm"))] async fn resolve_commit_hash(&self, revision: &str) -> HFResult { if cache::is_commit_hash(revision) { return Ok(revision.to_string()); } #[derive(Deserialize)] struct ShaOnly { sha: Option, } let repo_path = self.repo_path(); let info: ShaOnly = self .fetch_repo_info(Some(revision.to_string()), None) .await?; let commit = info.sha.ok_or_else(|| { HFError::malformed_response(format!( "repo info for {}@{} returned no commit sha", repo_path, revision )) })?; admit_commit(&commit, revision) } #[cfg(not(target_family = "wasm"))] async fn list_filtered_files( &self, revision: &str, allow_patterns: Option<&Vec>, ignore_patterns: Option<&Vec>, ) -> HFResult> { let stream = self .list_tree() .revision(revision.to_string()) .recursive(true) .send()?; futures::pin_mut!(stream); let mut filenames: Vec = Vec::new(); while let Some(entry) = stream.next().await { let entry = entry?; if let RepoTreeEntry::File { path, .. } = entry { filenames.push(path); } } if let Some(allow) = allow_patterns { filenames.retain(|f| matches_any_glob(allow, f)); } if let Some(ignore) = ignore_patterns { filenames.retain(|f| !matches_any_glob(ignore, f)); } Ok(filenames) } #[cfg(not(target_family = "wasm"))] async fn snapshot_download_impl(&self, params: SnapshotDownloadParams) -> HFResult { if params.local_dir.is_none() && !self.hf_client.cache_enabled() { return Err(HFError::CacheNotEnabled); } let revision = params .revision .as_deref() .unwrap_or(constants::DEFAULT_REVISION); let max_workers = params.max_workers.unwrap_or(8); let repo_folder = cache::repo_folder_name(&self.repo_path(), self.repo_type.plural()); let cache_dir = self.hf_client.cache_dir(); if params.local_files_only { let commit_hash = if cache::is_commit_hash(revision) { revision.to_string() } else { cache::read_ref(cache_dir, &repo_folder, revision) .await? .ok_or_else(|| HFError::LocalEntryNotFound { path: format!("{}/{}", repo_folder, revision), })? }; let snapshot_dir = cache_dir .join(&repo_folder) .join("snapshots") .join(&commit_hash); if snapshot_dir.exists() { return Ok(snapshot_dir); } return Err(HFError::LocalEntryNotFound { path: format!("{}/{}", repo_folder, commit_hash), }); } let commit_hash = self.resolve_commit_hash(revision).await?; let mut filenames = self .list_filtered_files( &commit_hash, params.allow_patterns.as_ref(), params.ignore_patterns.as_ref(), ) .await?; // The listing comes from the server: a path that would land outside `local_dir` or the // snapshot folder fails the whole snapshot before anything is written. for filename in &filenames { ensure_relative_repo_path(filename).map_err(HFError::malformed_response)?; if params.local_dir.is_some() { ensure_local_repo_path(filename).map_err(HFError::malformed_response)?; } } let total_files = filenames.len(); let force = params.force_download; let mut cached_filenames = Vec::new(); if !force && params.local_dir.is_none() { filenames.retain(|f| { if cache::snapshot_path(cache_dir, &repo_folder, &commit_hash, f).exists() { cached_filenames.push(f.clone()); false } else { true } }); } let repo_path = self.repo_path(); let repo_path_ref = &repo_path; let commit_hash_ref = &commit_hash; let mut head_futs = Vec::with_capacity(filenames.len()); for filename in &filenames { let auth = self.hf_client.auth_headers(); let filename = filename.clone(); let repo_folder_ref = &repo_folder; head_futs.push(async move { let url = self .hf_client .download_url(self.repo_type.url_prefix(), repo_path_ref, commit_hash_ref, &filename)?; let resp = self.hf_client.head_with_relative_redirects(&url, &auth).await?; // Per-file 404 resilience: write a .no_exist marker and skip // the file rather than aborting the entire snapshot download. // This matches the Python huggingface_hub library behavior. // Alternative: since the file list comes from list_repo_tree // on a pinned commit, a 404 here is unexpected and could be // treated as an error instead. if resp.status() == reqwest::StatusCode::NOT_FOUND { if let Some(commit) = extract_commit_hash(&resp) { let commit = admit_commit(&commit, commit_hash_ref)?; let no_exist = cache::no_exist_path(cache_dir, repo_folder_ref, &commit, &filename); if let Some(parent) = no_exist.parent() { let _ = std::fs::create_dir_all(parent); } let _ = std::fs::write(&no_exist, b""); } return Ok::<_, HFError>(None); } else if !resp.status().is_success() && !resp.status().is_redirection() { let context = Box::new(crate::error::HttpErrorContext::from_response(resp).await); return Err(HFError::Http { context }); } let etag = extract_etag(&resp).ok_or_else(|| { HFError::malformed_response_at(format!("missing ETag header for {filename}"), url.clone()) })?; let etag = admit_etag(&etag)?; let commit = extract_commit_hash(&resp).unwrap_or_else(|| commit_hash_ref.clone()); let commit = admit_commit(&commit, commit_hash_ref)?; let xet_hash = extract_xet_hash(&resp); let (file_size, size_error) = if xet_hash.is_some() { match extract_xet_file_size(&resp, &filename) { Ok(size) => (size, None), Err(error) => (0, Some(error)), } } else { let size = extract_file_size(&resp).unwrap_or_else(|| { tracing::warn!(file = %filename, "missing or invalid Content-Length/X-Linked-Size header, defaulting file size to 0"); 0 }); (size, None) }; let location = Some(resp.url().to_string()); let meta = FileMetadataInfo { filename, etag, commit_hash: commit, xet_hash, file_size, location, }; Ok::<_, HFError>(Some((meta, size_error))) }); } let head_results: Vec<(FileMetadataInfo, Option)> = futures::stream::iter(head_futs) .buffer_unordered(max_workers) .try_collect::)>>>() .await? .into_iter() .flatten() .collect(); let mut xet_size_errors: HashMap = HashMap::new(); let mut file_metas = Vec::with_capacity(head_results.len()); for (meta, size_error) in head_results { if let Some(error) = size_error { xet_size_errors.insert(meta.filename.clone(), error); } file_metas.push(meta); } let total_bytes: u64 = file_metas.iter().map(|m| m.file_size).sum(); params.progress.emit(DownloadEvent::Start { total_files, total_bytes, }); if !cached_filenames.is_empty() { params.progress.emit(DownloadEvent::Progress { files: cached_filenames .iter() .map(|f| FileProgress { filename: f.clone(), bytes_completed: 0, total_bytes: 0, status: FileStatus::Complete, }) .collect(), }); } let mut xet_metas = Vec::new(); let mut non_xet_filenames = Vec::new(); if let Some(ref local_dir) = params.local_dir { let mut local_cached = Vec::new(); for meta in file_metas { let dest = local_dir.join(&meta.filename); if dest.exists() && !force { local_cached.push(meta.filename); continue; } if meta.xet_hash.is_some() { xet_metas.push(meta); } else { non_xet_filenames.push(meta.filename); } } if !local_cached.is_empty() { params.progress.emit(DownloadEvent::Progress { files: local_cached .iter() .map(|f| FileProgress { filename: f.clone(), bytes_completed: 0, total_bytes: 0, status: FileStatus::Complete, }) .collect(), }); } let xet_batch_fut = async { if xet_metas.is_empty() { return Ok::<_, HFError>(()); } // Multiple snapshots may share a local directory. Take destination // locks in the same order before starting this batch. xet_metas.sort_unstable_by(|a, b| a.filename.cmp(&b.filename)); let mut batch_files = Vec::with_capacity(xet_metas.len()); let mut downloads = Vec::with_capacity(xet_metas.len()); for m in &xet_metas { if let Some(error) = xet_size_errors.remove(&m.filename) { return Err(error); } let hash = m.xet_hash.as_ref().unwrap(); let url = self.hf_client.download_url( self.repo_type.url_prefix(), &repo_path, &commit_hash, &m.filename, )?; let download = LocalDownload::prepare(local_dir, &m.filename, &url, hash).await?; batch_files.push(crate::xet::XetBatchFile { hash: hash.clone(), file_size: m.file_size, path: download.staged.clone(), filename: m.filename.clone(), }); downloads.push(download); } self.xet_download_batch( &commit_hash, &batch_files, params.force_download, ¶ms.progress, ) .await?; for download in downloads { download.publish(&download.staged)?; } Ok(()) }; let non_xet_dl_params = build_download_params( &repo_path, &non_xet_filenames, &commit_hash, params.force_download, Some(local_dir.clone()), ¶ms.progress, ); let non_xet_fut = async { download_concurrently(self, &non_xet_dl_params, max_workers).await?; Ok::<_, HFError>(()) }; tokio::try_join!(xet_batch_fut, non_xet_fut)?; params.progress.emit(DownloadEvent::Complete); return Ok(local_dir.clone()); } // Cache mode let mut cached_progress: Vec = Vec::new(); for meta in file_metas { let blob = cache::blob_path(cache_dir, &repo_folder, &meta.etag); let pointer = cache::snapshot_path(cache_dir, &repo_folder, &meta.commit_hash, &meta.filename); if pointer.exists() && !force { cached_progress.push(FileProgress { filename: meta.filename.clone(), bytes_completed: meta.file_size, total_bytes: meta.file_size, status: FileStatus::Complete, }); continue; } if blob.exists() && !force { let lock = cache::acquire_lock(cache_dir, &repo_folder, &meta.etag).await?; if pointer.exists() || blob.exists() { if !pointer.exists() { cache::create_pointer_symlink( &lock, cache_dir, &repo_folder, &meta.commit_hash, &meta.filename, &meta.etag, false, ) .await?; } cached_progress.push(FileProgress { filename: meta.filename.clone(), bytes_completed: meta.file_size, total_bytes: meta.file_size, status: FileStatus::Complete, }); continue; } } if meta.xet_hash.is_some() { xet_metas.push(meta); } else { non_xet_filenames.push(meta.filename); } } if !cached_progress.is_empty() { params.progress.emit(DownloadEvent::Progress { files: cached_progress, }); } let xet_batch_fut = async { if xet_metas.is_empty() { return Ok::<_, HFError>(()); } let mut groups: HashMap> = HashMap::new(); for meta in xet_metas { groups.entry(meta.etag.clone()).or_default().push(meta); } let mut etags: Vec = groups.keys().cloned().collect(); etags.sort_unstable(); let mut locks = HashMap::with_capacity(etags.len()); for etag in &etags { locks.insert( etag.clone(), cache::acquire_lock(cache_dir, &repo_folder, etag).await?, ); } let mut batch_files = Vec::new(); let mut pending_groups = Vec::new(); let mut locked_cached_progress = Vec::new(); for etag in etags { let metas = groups.remove(&etag).unwrap_or_default(); let missing_metas: Vec = metas .iter() .filter(|meta| { force || !cache::snapshot_path( cache_dir, &repo_folder, &meta.commit_hash, &meta.filename, ) .exists() }) .cloned() .collect(); if missing_metas.is_empty() { continue; } let blob = cache::blob_path(cache_dir, &repo_folder, &etag); let lock = locks.get(&etag).ok_or_else(|| { HFError::Other(format!("missing cache lock for Xet ETag {etag}")) })?; if blob.exists() && !force { for meta in missing_metas { cache::create_pointer_symlink( lock, cache_dir, &repo_folder, &meta.commit_hash, &meta.filename, &meta.etag, false, ) .await?; locked_cached_progress.push(FileProgress { filename: meta.filename, bytes_completed: meta.file_size, total_bytes: meta.file_size, status: FileStatus::Complete, }); } continue; } let new_blob = !blob.exists(); let representative = select_xet_group_metadata(&metas, &mut xet_size_errors)?; batch_files.push(crate::xet::XetBatchFile { hash: representative.xet_hash.as_ref().unwrap().clone(), file_size: representative.file_size, path: blob, filename: representative.filename.clone(), }); pending_groups.push((etag, new_blob, missing_metas)); } if !locked_cached_progress.is_empty() { params.progress.emit(DownloadEvent::Progress { files: locked_cached_progress, }); } self.xet_download_batch( &commit_hash, &batch_files, params.force_download, ¶ms.progress, ) .await?; for (etag, new_blob, metas) in pending_groups { let lock = locks.get(&etag).ok_or_else(|| { HFError::Other(format!("missing cache lock for Xet ETag {etag}")) })?; let mut blob_must_be_preserved = !new_blob; let last_index = metas.len().saturating_sub(1); for (index, meta) in metas.into_iter().enumerate() { let move_blob = new_blob && !blob_must_be_preserved && index == last_index; let result = cache::create_pointer_symlink( lock, cache_dir, &repo_folder, &meta.commit_hash, &meta.filename, &meta.etag, move_blob, ) .await?; if result.references_blob { blob_must_be_preserved = true; } } } Ok(()) }; let non_xet_dl_params = build_download_params( &repo_path, &non_xet_filenames, &commit_hash, params.force_download, None, ¶ms.progress, ); let non_xet_fut = async { download_concurrently(self, &non_xet_dl_params, max_workers).await?; Ok::<_, HFError>(()) }; tokio::try_join!(xet_batch_fut, non_xet_fut)?; if !cache::is_commit_hash(revision) { cache::write_ref(cache_dir, &repo_folder, revision, &commit_hash).await?; } params.progress.emit(DownloadEvent::Complete); Ok(cache_dir .join(&repo_folder) .join("snapshots") .join(&commit_hash)) } } #[cfg(not(target_family = "wasm"))] fn select_xet_group_metadata<'a>( metas: &'a [FileMetadataInfo], size_errors: &mut HashMap, ) -> HFResult<&'a FileMetadataInfo> { let first = metas .first() .ok_or_else(|| HFError::malformed_response("empty Xet metadata group"))?; let mut representative: Option<&FileMetadataInfo> = None; for meta in metas { if meta.xet_hash != first.xet_hash { return Err(HFError::malformed_response(format!( "conflicting Xet hashes for ETag {}", first.etag ))); } if size_errors.contains_key(&meta.filename) { continue; } if representative.is_some_and(|chosen| chosen.file_size != meta.file_size) { return Err(HFError::malformed_response(format!( "conflicting Xet file sizes for ETag {}", first.etag ))); } representative = Some(meta); } representative.ok_or_else(|| { size_errors.remove(&first.filename).unwrap_or_else(|| { HFError::malformed_response(format!("missing Xet size for ETag {}", first.etag)) }) }) } #[cfg(not(target_family = "wasm"))] fn emit_local_file_complete(params: &DownloadFileParams, file_size: u64) { params.progress.emit(DownloadEvent::Progress { files: vec![FileProgress { filename: params.filename.clone(), bytes_completed: file_size, total_bytes: file_size, status: FileStatus::Complete, }], }); } #[cfg(not(target_family = "wasm"))] async fn mark_no_exist_and_return_error( cache_dir: &Path, repo_folder: &str, revision: &str, response: &reqwest::Response, repo_id: &str, filename: &str, ) -> HFError { if let Some(commit_hash) = extract_commit_hash(response) { let commit_hash = match admit_commit(&commit_hash, revision) { Ok(commit) => commit, Err(error) => return error, }; let no_exist = cache::no_exist_path(cache_dir, repo_folder, &commit_hash, filename); if let Some(parent) = no_exist.parent() { let _ = std::fs::create_dir_all(parent); } let _ = std::fs::write(&no_exist, b""); if !cache::is_commit_hash(revision) { let _ = cache::write_ref(cache_dir, repo_folder, revision, &commit_hash).await; } } HFError::EntryNotFound { path: filename.to_string(), repo_id: repo_id.to_string(), context: None, } } #[cfg(not(target_family = "wasm"))] async fn finalize_cached_file( lock: &cache::CacheLock, target: CachedFileTarget<'_>, new_blob: bool, ) -> HFResult { cache::create_pointer_symlink( lock, target.cache_dir, target.repo_folder, target.commit_hash, target.filename, target.etag, new_blob, ) .await?; if !cache::is_commit_hash(target.revision) { cache::write_ref( target.cache_dir, target.repo_folder, target.revision, target.commit_hash, ) .await?; } Ok(cache::snapshot_path( target.cache_dir, target.repo_folder, target.commit_hash, target.filename, )) } #[cfg(not(target_family = "wasm"))] fn build_download_params( _repo_id: &str, filenames: &[String], commit_hash: &str, force_download: bool, local_dir: Option, progress: &Option, ) -> Vec { filenames .iter() .map(|filename| DownloadFileParams { filename: filename.clone(), local_dir: local_dir.clone(), revision: Some(commit_hash.to_string()), force_download, local_files_only: false, progress: progress.clone(), }) .collect() } #[cfg(not(target_family = "wasm"))] async fn download_concurrently( api: &HFRepository, params: &[DownloadFileParams], max_workers: usize, ) -> HFResult> { let mut download_futs = Vec::with_capacity(params.len()); for file_params in params { download_futs.push(api.download_file_inner(file_params)); } futures::stream::iter(download_futs) .buffer_unordered(max_workers) .try_collect() .await } #[cfg(not(target_family = "wasm"))] async fn stream_response_to_file_with_progress( response: reqwest::Response, dest: &Path, handler: &Option, filename: Option<&str>, total_bytes: u64, initial_bytes: u64, ) -> HFResult<()> { let mut file = if initial_bytes > 0 { let mut file = std::fs::OpenOptions::new() .append(true) .create(true) .open(dest)?; file.seek(std::io::SeekFrom::End(0))?; file } else { std::fs::File::create(dest)? }; let mut stream = response.bytes_stream(); let mut bytes_read = initial_bytes; if let (Some(h), Some(filename)) = (handler, filename) { h.emit(DownloadEvent::Progress { files: vec![FileProgress { filename: filename.to_string(), bytes_completed: initial_bytes, total_bytes, status: FileStatus::Started, }], }); } while let Some(chunk) = stream.next().await { let chunk = chunk?; file.write_all(&chunk)?; bytes_read += chunk.len() as u64; if let (Some(h), Some(filename)) = (handler, filename) { h.emit(DownloadEvent::Progress { files: vec![FileProgress { filename: filename.to_string(), bytes_completed: bytes_read, total_bytes, status: FileStatus::InProgress, }], }); } } file.flush()?; if total_bytes > 0 && bytes_read != total_bytes { return Err(HFError::Other(format!( "downloaded {} bytes but expected {} bytes for {}", bytes_read, total_bytes, filename.unwrap_or("") ))); } Ok(()) } #[cfg(not(target_family = "wasm"))] fn content_range_matches( headers: &reqwest::header::HeaderMap, expected_start: u64, expected_total: u64, ) -> bool { let Some(raw) = headers .get(reqwest::header::CONTENT_RANGE) .and_then(|value| value.to_str().ok()) else { return false; }; let Some(range) = raw.strip_prefix("bytes ") else { return false; }; let Some((bounds, total)) = range.split_once('/') else { return false; }; let Some((start, end)) = bounds.split_once('-') else { return false; }; let Ok(start) = start.parse::() else { return false; }; let Ok(end) = end.parse::() else { return false; }; let total_matches = total == "*" || total .parse::() .is_ok_and(|total| total == expected_total); start == expected_start && end.saturating_add(1) <= expected_total && total_matches } /// Decouple the inner byte stream from the JS-side `ReadableStream` reader cadence on wasm. /// /// `wasm_streams::ReadableStream::from_stream` builds the JS stream with `QueuingStrategy(0.0)` /// (HWM=0) — the underlying Rust stream is only polled when JS calls `reader.read()`. For the xet /// download path, slow JS-side consumption then propagates through hf-xet's term-permit semaphore /// (`AdjustableSemaphore` in `file_reconstructor.rs`) and stalls xorb fetching. Browsers differ in /// how aggressively they schedule the `pull` callback, so the effect is intermittent. /// /// This pump task drains the inner stream into a small bounded channel under `spawn_local`. JS /// `reader.read()` now pulls from the local channel (cheap) instead of gating the live xet /// pipeline; xet keeps making progress as long as the channel has room. The channel depth bounds /// the extra in-flight bytes — at most `depth * max_chunk_size` beyond what xet already buffers. #[cfg(target_family = "wasm")] pub(crate) fn buffer_wasm_stream(inner: HFByteStream) -> HFByteStream { const BUFFER_DEPTH: usize = 2; let (tx, rx) = tokio::sync::mpsc::channel(BUFFER_DEPTH); wasm_bindgen_futures::spawn_local(async move { let mut inner = inner; loop { let item = tokio::select! { biased; _ = tx.closed() => return, item = inner.next() => item, }; let Some(item) = item else { return; }; let is_err = item.is_err(); if tx.send(item).await.is_err() || is_err { return; } } }); Box::new(Box::pin(futures::stream::unfold(rx, |mut rx| async { rx.recv().await.map(|item| (item, rx)) }))) } pub(crate) fn wrap_stream_with_progress( stream: HFByteStream, progress: Option, filename: String, total_bytes: u64, ) -> HFByteStream { if progress.is_none() { return stream; } let wrapped = futures::stream::unfold( (stream, 0u64, false), move |(mut inner, bytes_completed, ended)| { let progress = progress.clone(); let filename = filename.clone(); async move { if ended { return None; } match inner.next().await { Some(Ok(chunk)) => { let bytes_completed = bytes_completed + chunk.len() as u64; progress.emit(DownloadEvent::Progress { files: vec![FileProgress { filename, bytes_completed, total_bytes, status: FileStatus::InProgress, }], }); Some((Ok(chunk), (inner, bytes_completed, false))) } Some(Err(e)) => Some((Err(e), (inner, bytes_completed, true))), None => { progress.emit(DownloadEvent::Complete); None } } } }, ); Box::new(Box::pin(wrapped)) } #[cfg(all(test, not(target_family = "wasm")))] mod tests; #[bon] impl HFRepository { /// Download a single file from a repository. /// /// When `local_dir` is `Some`, the file is downloaded directly to that directory /// (no caching). Partial downloads live under `.cache/huggingface` inside that /// directory, which is reserved for transfer state. When `local_dir` is `None`, /// the HF cache system is used: /// blobs are stored by etag and symlinked from snapshots/{commit}/{filename}. /// /// Returns the local filesystem path of the downloaded or cached file. Use /// [`HFRepository::download_file_stream`] or /// [`HFRepository::download_file_to_bytes`] when you do not want to write to /// disk. /// /// # Offline / cache-only lookups /// /// Set `.local_files_only(true)` to look for a completed file in `local_dir` /// when supplied, or in the Hub cache otherwise, without making a network /// request. A miss returns /// [`HFError::LocalEntryNotFound`], which is distinct from a real failure: /// match it to tell "not cached" apart from a genuinely missing file /// ([`HFError::EntryNotFound`]) or any transport error. /// /// ```no_run /// # #[tokio::main] async fn main() -> hf_hub::HFResult<()> { /// use hf_hub::HFError; /// /// let repo = hf_hub::HFClient::new()?.model("openai-community", "gpt2"); /// match repo.download_file().filename("config.json").local_files_only(true).send().await { /// Ok(path) => println!("cached at {}", path.display()), /// Err(HFError::LocalEntryNotFound { .. }) => println!("not in cache"), /// Err(e) => return Err(e), /// } /// # Ok(()) } /// ``` /// /// Endpoint: `GET {endpoint}/{prefix}{repo_id}/resolve/{revision}/{filename}`. /// /// # Parameters /// /// - `filename` (required): path of the file to download within the repository. /// - `local_dir`: local directory to download the file into. When set, the file is saved with its repo path /// structure. /// - `revision`: Git revision. Defaults to the main branch. /// - `force_download` (default `false`): re-download the file even if a cached copy exists. /// - `local_files_only` (default `false`): only return the file if cached locally; never make a network request. /// - `progress`: optional progress handler. #[cfg(not(target_family = "wasm"))] #[builder(finish_fn = send, derive(Debug, Clone))] pub async fn download_file( &self, /// Path of the file to download within the repository. #[builder(into)] filename: String, /// Local directory to download the file into. When set, the file is saved with its repo path structure. #[builder(into)] local_dir: Option, /// Git revision. Defaults to the main branch. #[builder(into)] revision: Option, /// Re-download the file even if a cached copy exists. #[builder(default)] force_download: bool, /// Only return the file if cached locally; never make a network request. #[builder(default)] local_files_only: bool, /// Progress handler. #[builder(into)] progress: Option, ) -> HFResult { Box::pin(self.download_file_impl(DownloadFileParams { filename, local_dir, revision, force_download, local_files_only, progress, })) .await } /// Download a file and return a byte stream instead of writing to disk. /// /// Returns a `(content_length, stream)` tuple. `content_length` is `Some` /// when the server provides a `Content-Length` header. /// /// When `range` is set, only the specified byte range is fetched. /// /// # Parameters /// /// - `filename` (required): path of the file to stream within the repository. /// - `revision`: Git revision. Defaults to the main branch. /// - `range`: byte range to request, as a Rust `std::ops::Range`. The range follows standard Rust semantics — /// `start` is **inclusive**, `end` is **exclusive** — so `0..1024` fetches the first 1024 bytes (offsets /// `0..=1023`). Internally, this is converted to the HTTP `Range: bytes=-` header. `start` must be /// strictly less than `end`; an empty or inverted range returns [`HFError::InvalidParameter`]. /// - `progress`: optional progress handler. `Start` is emitted before the stream is returned; `Progress` is emitted /// as the caller polls each chunk; `Complete` is emitted when the stream is exhausted. #[builder(finish_fn = send, derive(Debug, Clone))] pub async fn download_file_stream( &self, /// Path of the file to stream within the repository. #[builder(into)] filename: String, /// Git revision. Defaults to the main branch. #[builder(into)] revision: Option, /// Byte range to request, as a Rust `std::ops::Range`. The range follows standard Rust semantics — /// `start` is **inclusive**, `end` is **exclusive** — so `0..1024` fetches the first 1024 bytes (offsets /// `0..=1023`). Internally, this is converted to the HTTP `Range: bytes=-` header. `start` must /// be strictly less than `end`; an empty or inverted range returns [`HFError::InvalidParameter`]. range: Option>, /// Progress handler. `Start` is emitted before the stream is returned; `Progress` is emitted /// as the caller polls each chunk; `Complete` is emitted when the stream is exhausted. #[builder(into)] progress: Option, ) -> HFResult<(Option, HFByteStream)> { Box::pin(self.download_file_stream_impl(DownloadFileStreamParams { filename, revision, range, progress, })) .await } /// Download a file (or byte range) into memory and return the contents as [`bytes::Bytes`]. /// /// This is a convenience wrapper around /// [`download_file_stream`](Self::download_file_stream) that collects the entire stream into /// a single buffer. When `range` is set, only the specified byte range is fetched. /// /// # Parameters /// /// - `filename` (required): path of the file to download within the repository. /// - `revision`: Git revision. Defaults to the main branch. /// - `range`: byte range to request, as a Rust `std::ops::Range`. The range follows standard Rust semantics — /// `start` is **inclusive**, `end` is **exclusive** — so `0..1024` fetches the first 1024 bytes (offsets /// `0..=1023`). Internally, this is converted to the HTTP `Range: bytes=-` header. `start` must be /// strictly less than `end`; an empty or inverted range returns [`HFError::InvalidParameter`]. /// - `progress`: optional progress handler. Emits `Start`/`Progress`/`Complete` as the underlying stream is /// drained, identically to [`download_file_stream`](Self::download_file_stream). #[builder(finish_fn = send, derive(Debug, Clone))] pub async fn download_file_to_bytes( &self, /// Path of the file to download within the repository. #[builder(into)] filename: String, /// Git revision. Defaults to the main branch. #[builder(into)] revision: Option, /// Byte range to request, as a Rust `std::ops::Range`. The range follows standard Rust semantics — /// `start` is **inclusive**, `end` is **exclusive** — so `0..1024` fetches the first 1024 bytes (offsets /// `0..=1023`). Internally, this is converted to the HTTP `Range: bytes=-` header. `start` must /// be strictly less than `end`; an empty or inverted range returns [`HFError::InvalidParameter`]. range: Option>, /// Progress handler. Emits `Start`/`Progress`/`Complete` as the underlying stream is /// drained, identically to [`HFRepository::download_file_stream`]. #[builder(into)] progress: Option, ) -> HFResult { Box::pin(self.download_file_to_bytes_impl(DownloadFileStreamParams { filename, revision, range, progress, })) .await } /// Download all selected files for a resolved revision. /// /// When `local_dir` is `None`, files are stored in the HF cache, and the returned path is the /// cache snapshot directory for the resolved commit. When `local_dir` is `Some`, files are /// written directly under that directory. /// /// `allow_patterns` and `ignore_patterns` use [`globset`](https://docs.rs/globset) syntax /// (`*`, `?`, `**`, character classes, etc.). Both are matched against each candidate file's /// **repository path** — forward-slash-joined and relative to the repo root, e.g., /// `tokenizer.json` or `weights/model-00001-of-00003.safetensors`. /// /// # Parameters /// /// - `revision`: Git revision. Defaults to the main branch. /// - `allow_patterns`: globs selecting which repository files to download. When set, only files whose repo path /// matches at least one pattern are downloaded. /// - `ignore_patterns`: globs of repository files to skip. Matched against the same repo paths as `allow_patterns`. /// - `local_dir`: local directory to download into. /// - `force_download` (default `false`): re-download all files even if cached. /// - `local_files_only` (default `false`): resolve only from the local cache. /// - `max_workers`: maximum concurrent file downloads (default 8). /// - `progress`: optional progress handler. #[cfg(not(target_family = "wasm"))] #[builder(finish_fn = send, derive(Debug, Clone))] pub async fn snapshot_download( &self, /// Git revision. Defaults to the main branch. #[builder(into)] revision: Option, /// Globs selecting which repository files to download. When set, only files whose repo path /// matches at least one pattern are downloaded. allow_patterns: Option>, /// Globs of repository files to skip. Matched against the same repo paths as `allow_patterns`. ignore_patterns: Option>, /// Local directory to download into. #[builder(into)] local_dir: Option, /// Re-download all files even if cached. #[builder(default)] force_download: bool, /// Resolve only from the local cache. #[builder(default)] local_files_only: bool, /// Maximum concurrent file downloads (default 8). max_workers: Option, /// Progress handler. #[builder(into)] progress: Option, ) -> HFResult { Box::pin(self.snapshot_download_impl(SnapshotDownloadParams { revision, allow_patterns, ignore_patterns, local_dir, force_download, local_files_only, max_workers, progress, })) .await } } #[cfg(all(feature = "blocking", not(target_family = "wasm")))] #[bon] impl crate::blocking::HFRepositorySync { /// Blocking counterpart of [`HFRepository::download_file`]. See the async method for /// parameters and behavior. #[builder(finish_fn = send, derive(Debug, Clone))] pub fn download_file( &self, #[builder(into)] filename: String, #[builder(into)] local_dir: Option, #[builder(into)] revision: Option, #[builder(default)] force_download: bool, #[builder(default)] local_files_only: bool, #[builder(into)] progress: Option, ) -> HFResult { self.runtime.block_on( self.inner .download_file() .filename(filename) .maybe_local_dir(local_dir) .maybe_revision(revision) .force_download(force_download) .local_files_only(local_files_only) .maybe_progress(progress) .send(), ) } /// Blocking counterpart of [`HFRepository::download_file_to_bytes`]. See the async method for /// parameters and behavior. #[builder(finish_fn = send, derive(Debug, Clone))] pub fn download_file_to_bytes( &self, #[builder(into)] filename: String, #[builder(into)] revision: Option, range: Option>, #[builder(into)] progress: Option, ) -> HFResult { self.runtime.block_on( self.inner .download_file_to_bytes() .filename(filename) .maybe_revision(revision) .maybe_range(range) .maybe_progress(progress) .send(), ) } /// Blocking counterpart of [`HFRepository::snapshot_download`]. See the async method for /// parameters and behavior. #[builder(finish_fn = send, derive(Debug, Clone))] pub fn snapshot_download( &self, #[builder(into)] revision: Option, allow_patterns: Option>, ignore_patterns: Option>, #[builder(into)] local_dir: Option, #[builder(default)] force_download: bool, #[builder(default)] local_files_only: bool, max_workers: Option, #[builder(into)] progress: Option, ) -> HFResult { self.runtime.block_on( self.inner .snapshot_download() .maybe_revision(revision) .maybe_allow_patterns(allow_patterns) .maybe_ignore_patterns(ignore_patterns) .maybe_local_dir(local_dir) .force_download(force_download) .local_files_only(local_files_only) .maybe_max_workers(max_workers) .maybe_progress(progress) .send(), ) } } #[cfg(all(test, not(target_family = "wasm")))] mod resume_tests;