Skip to main content

hf_fetch_model/
config.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Configuration for model downloads.
4//!
5//! [`FetchConfig`] controls revision, authentication, file filtering,
6//! concurrency, timeouts, retry behavior, and progress reporting.
7
8use std::path::PathBuf;
9use std::sync::Arc;
10use std::time::Duration;
11
12use globset::{Glob, GlobSet, GlobSetBuilder};
13
14use crate::error::FetchError;
15use crate::progress::ProgressEvent;
16
17// TRAIT_OBJECT: heterogeneous progress handlers from different callers
18pub(crate) type ProgressCallback = Arc<dyn Fn(&ProgressEvent) + Send + Sync>;
19
20/// Configuration for downloading a model repository.
21///
22/// Use [`FetchConfig::builder()`] to construct.
23///
24/// # Example
25///
26/// ```rust
27/// # fn example() -> Result<(), hf_fetch_model::FetchError> {
28/// use hf_fetch_model::FetchConfig;
29///
30/// let config = FetchConfig::builder()
31///     .revision("main")
32///     .filter("*.safetensors")
33///     .concurrency(4)
34///     .build()?;
35/// # Ok(())
36/// # }
37/// ```
38pub struct FetchConfig {
39    /// Git revision (branch, tag, or commit SHA). `None` means `"main"`.
40    pub(crate) revision: Option<String>,
41    /// Authentication token for gated/private repositories.
42    pub(crate) token: Option<String>,
43    /// Compiled include glob patterns. Only matching files are downloaded.
44    pub(crate) include: Option<GlobSet>,
45    /// Compiled exclude glob patterns. Matching files are skipped.
46    pub(crate) exclude: Option<GlobSet>,
47    /// Number of files to download in parallel.
48    pub(crate) concurrency: usize,
49    /// Custom cache directory (overrides the default HF cache).
50    pub(crate) output_dir: Option<PathBuf>,
51    /// Maximum time allowed for a single file download.
52    pub(crate) timeout_per_file: Option<Duration>,
53    /// Maximum total time for the entire download operation.
54    pub(crate) timeout_total: Option<Duration>,
55    /// Maximum retry attempts per file (exponential backoff with jitter).
56    pub(crate) max_retries: u32,
57    /// Whether to verify SHA256 checksums against HF LFS metadata.
58    pub(crate) verify_checksums: bool,
59    /// Minimum file size (bytes) for multi-connection chunked download.
60    pub(crate) chunk_threshold: u64,
61    /// Number of parallel HTTP Range connections per large file.
62    pub(crate) connections_per_file: usize,
63    // TRAIT_OBJECT: heterogeneous progress handlers from different callers
64    /// Progress callback invoked for each download event.
65    pub(crate) on_progress: Option<ProgressCallback>,
66    /// Tracks which performance fields the user explicitly set via the builder.
67    pub(crate) explicit: ExplicitSettings,
68}
69
70/// Tracks which performance fields the user explicitly set via the builder.
71///
72/// Used by the implicit plan retrofit: when a field was not explicitly set,
73/// the plan-based optimizer may override it with a recommended value.
74#[derive(Debug, Clone, Default)]
75pub(crate) struct ExplicitSettings {
76    /// Whether `concurrency` was explicitly set by the caller.
77    pub(crate) concurrency: bool,
78    /// Whether `connections_per_file` was explicitly set by the caller.
79    pub(crate) connections_per_file: bool,
80    /// Whether `chunk_threshold` was explicitly set by the caller.
81    pub(crate) chunk_threshold: bool,
82}
83
84impl std::fmt::Debug for FetchConfig {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.debug_struct("FetchConfig")
87            .field("revision", &self.revision)
88            .field("token", &self.token.as_ref().map(|_| "***"))
89            .field("include", &self.include)
90            .field("exclude", &self.exclude)
91            .field("concurrency", &self.concurrency)
92            .field("output_dir", &self.output_dir)
93            .field("timeout_per_file", &self.timeout_per_file)
94            .field("timeout_total", &self.timeout_total)
95            .field("max_retries", &self.max_retries)
96            .field("verify_checksums", &self.verify_checksums)
97            .field("chunk_threshold", &self.chunk_threshold)
98            .field("connections_per_file", &self.connections_per_file)
99            .field(
100                "on_progress",
101                if self.on_progress.is_some() {
102                    &"Some(<fn>)"
103                } else {
104                    &"None"
105                },
106            )
107            .field("explicit", &self.explicit)
108            .finish()
109    }
110}
111
112impl FetchConfig {
113    /// Creates a new [`FetchConfigBuilder`].
114    #[must_use]
115    pub fn builder() -> FetchConfigBuilder {
116        FetchConfigBuilder::default()
117    }
118
119    /// Returns the configured concurrency level (parallel file downloads).
120    #[must_use]
121    pub const fn concurrency(&self) -> usize {
122        self.concurrency
123    }
124
125    /// Returns the configured number of parallel HTTP connections per file.
126    #[must_use]
127    pub const fn connections_per_file(&self) -> usize {
128        self.connections_per_file
129    }
130
131    /// Returns the chunk threshold in bytes (minimum file size for
132    /// multi-connection chunked downloads).
133    #[must_use]
134    pub const fn chunk_threshold(&self) -> u64 {
135        self.chunk_threshold
136    }
137}
138
139/// Builder for [`FetchConfig`].
140#[derive(Default)]
141pub struct FetchConfigBuilder {
142    revision: Option<String>,
143    token: Option<String>,
144    include_patterns: Vec<String>,
145    exclude_patterns: Vec<String>,
146    concurrency: Option<usize>,
147    output_dir: Option<PathBuf>,
148    timeout_per_file: Option<Duration>,
149    timeout_total: Option<Duration>,
150    max_retries: Option<u32>,
151    verify_checksums: Option<bool>,
152    chunk_threshold: Option<u64>,
153    connections_per_file: Option<usize>,
154    on_progress: Option<ProgressCallback>,
155}
156
157impl FetchConfigBuilder {
158    /// Sets the git revision (branch, tag, or commit SHA) to download.
159    ///
160    /// Defaults to `"main"` if not set.
161    #[must_use]
162    pub fn revision(mut self, revision: &str) -> Self {
163        // BORROW: explicit .to_owned() for &str → owned String
164        self.revision = Some(revision.to_owned());
165        self
166    }
167
168    /// Sets the authentication token.
169    #[must_use]
170    pub fn token(mut self, token: &str) -> Self {
171        // BORROW: explicit .to_owned() for &str → owned String
172        self.token = Some(token.to_owned());
173        self
174    }
175
176    /// Reads the authentication token from the `HF_TOKEN` environment variable.
177    #[must_use]
178    pub fn token_from_env(mut self) -> Self {
179        self.token = std::env::var("HF_TOKEN").ok();
180        self
181    }
182
183    /// Adds an include glob pattern. Only files matching at least one
184    /// include pattern will be downloaded.
185    ///
186    /// Can be called multiple times to add multiple patterns.
187    #[must_use]
188    pub fn filter(mut self, pattern: &str) -> Self {
189        // BORROW: explicit .to_owned() for &str → owned String
190        self.include_patterns.push(pattern.to_owned());
191        self
192    }
193
194    /// Adds an exclude glob pattern. Files matching any exclude pattern
195    /// will be skipped, even if they match an include pattern.
196    ///
197    /// Can be called multiple times to add multiple patterns.
198    #[must_use]
199    pub fn exclude(mut self, pattern: &str) -> Self {
200        // BORROW: explicit .to_owned() for &str → owned String
201        self.exclude_patterns.push(pattern.to_owned());
202        self
203    }
204
205    /// Sets the number of files to download concurrently.
206    ///
207    /// When omitted, the download plan optimizer auto-tunes this value
208    /// based on file count and size distribution. Falls back to 4 if
209    /// no plan recommendation is available.
210    #[must_use]
211    pub fn concurrency(mut self, concurrency: usize) -> Self {
212        self.concurrency = Some(concurrency);
213        self
214    }
215
216    /// Sets a custom output directory for downloaded files.
217    ///
218    /// By default, files are stored in the standard `HuggingFace` cache directory
219    /// (`~/.cache/huggingface/hub/`). When set, the `HuggingFace` cache hierarchy
220    /// is created inside this directory instead.
221    #[must_use]
222    pub fn output_dir(mut self, dir: PathBuf) -> Self {
223        self.output_dir = Some(dir);
224        self
225    }
226
227    /// Sets the maximum time allowed per file download.
228    ///
229    /// If a single file download exceeds this duration, it is aborted
230    /// and may be retried according to the retry policy.
231    #[must_use]
232    pub fn timeout_per_file(mut self, duration: Duration) -> Self {
233        self.timeout_per_file = Some(duration);
234        self
235    }
236
237    /// Sets the maximum total time for the entire download operation.
238    ///
239    /// If the total download time exceeds this duration, remaining files
240    /// are skipped and a [`FetchError::Timeout`] is returned.
241    #[must_use]
242    pub fn timeout_total(mut self, duration: Duration) -> Self {
243        self.timeout_total = Some(duration);
244        self
245    }
246
247    /// Sets the maximum number of retry attempts per file.
248    ///
249    /// Defaults to 3. Set to 0 to disable retries.
250    /// Uses exponential backoff with jitter (base 300ms, cap 10s).
251    #[must_use]
252    pub fn max_retries(mut self, retries: u32) -> Self {
253        self.max_retries = Some(retries);
254        self
255    }
256
257    /// Enables or disables SHA256 checksum verification after download.
258    ///
259    /// When enabled, downloaded files are verified against the SHA256 hash
260    /// from `HuggingFace` LFS metadata. Files without LFS metadata (small
261    /// config files stored directly in git) are skipped.
262    ///
263    /// Defaults to `true`.
264    #[must_use]
265    pub fn verify_checksums(mut self, verify: bool) -> Self {
266        self.verify_checksums = Some(verify);
267        self
268    }
269
270    /// Sets the minimum file size (in bytes) for chunked parallel download.
271    ///
272    /// Files at or above this threshold are downloaded using multiple HTTP
273    /// Range connections in parallel. Files below use the standard single
274    /// connection. Set to `u64::MAX` to disable chunked downloads entirely.
275    ///
276    /// When omitted, the download plan optimizer auto-tunes this value
277    /// based on file size distribution. Falls back to 100 MiB
278    /// (104\_857\_600 bytes) if no plan recommendation is available.
279    #[must_use]
280    pub fn chunk_threshold(mut self, bytes: u64) -> Self {
281        self.chunk_threshold = Some(bytes);
282        self
283    }
284
285    /// Sets the number of parallel HTTP connections per large file.
286    ///
287    /// Only applies to files at or above `chunk_threshold`. When omitted,
288    /// the download plan optimizer auto-tunes this value based on file size
289    /// distribution. Falls back to 8 if no plan recommendation is available.
290    #[must_use]
291    pub fn connections_per_file(mut self, connections: usize) -> Self {
292        self.connections_per_file = Some(connections);
293        self
294    }
295
296    /// Sets a progress callback invoked for each progress event.
297    #[must_use]
298    pub fn on_progress<F>(mut self, callback: F) -> Self
299    where
300        F: Fn(&ProgressEvent) + Send + Sync + 'static,
301    {
302        self.on_progress = Some(Arc::new(callback));
303        self
304    }
305
306    /// Creates a `tokio::sync::watch` channel for async progress consumption.
307    ///
308    /// Returns `(self, receiver)`. The receiver yields the latest [`ProgressEvent`]
309    /// via `.changed().await` + `.borrow()`. Only the most recent event is retained.
310    ///
311    /// The channel is initialized with [`ProgressEvent::default()`] (all zeros,
312    /// empty filename). Use `.changed().await` rather than eager `.borrow()` to
313    /// avoid observing this sentinel value before the first real event.
314    ///
315    /// Composes with [`on_progress()`](Self::on_progress) — if a callback was
316    /// already set, both the callback and the watch channel fire for every event.
317    #[must_use]
318    pub fn progress_channel(mut self) -> (Self, crate::progress::ProgressReceiver) {
319        let (tx, rx) = tokio::sync::watch::channel(ProgressEvent::default());
320        let existing = self.on_progress.take();
321        // TRAIT_OBJECT: heterogeneous progress handlers composed with watch sender
322        self.on_progress = Some(Arc::new(move |event: &ProgressEvent| {
323            if let Some(ref cb) = existing {
324                cb(event);
325            }
326            // Skip clone + send if no receiver is listening.
327            if tx.receiver_count() > 0 {
328                // BORROW: explicit .clone() for owned ProgressEvent sent through watch channel
329                let _ = tx.send(event.clone());
330            }
331        }));
332        (self, rx)
333    }
334
335    /// Builds the [`FetchConfig`].
336    ///
337    /// # Errors
338    ///
339    /// Returns [`FetchError::InvalidPattern`] if any glob pattern is invalid.
340    pub fn build(self) -> Result<FetchConfig, FetchError> {
341        let include = build_globset(&self.include_patterns)?;
342        let exclude = build_globset(&self.exclude_patterns)?;
343
344        Ok(FetchConfig {
345            revision: self.revision,
346            token: self.token,
347            include,
348            exclude,
349            concurrency: self.concurrency.unwrap_or(4),
350            output_dir: self.output_dir,
351            timeout_per_file: self.timeout_per_file,
352            timeout_total: self.timeout_total,
353            max_retries: self.max_retries.unwrap_or(3),
354            verify_checksums: self.verify_checksums.unwrap_or(true),
355            chunk_threshold: self.chunk_threshold.unwrap_or(104_857_600),
356            connections_per_file: self.connections_per_file.unwrap_or(8).max(1),
357            on_progress: self.on_progress,
358            explicit: ExplicitSettings {
359                concurrency: self.concurrency.is_some(),
360                connections_per_file: self.connections_per_file.is_some(),
361                chunk_threshold: self.chunk_threshold.is_some(),
362            },
363        })
364    }
365}
366
367/// Common filter presets for typical download patterns.
368#[non_exhaustive]
369pub struct Filter;
370
371impl Filter {
372    /// Returns a builder pre-configured to download only `*.safetensors` files
373    /// plus common config files.
374    #[must_use]
375    pub fn safetensors() -> FetchConfigBuilder {
376        FetchConfigBuilder::default()
377            .filter("*.safetensors")
378            .filter("*.json")
379            .filter("*.txt")
380    }
381
382    /// Returns a builder pre-configured to download only GGUF files
383    /// plus common config files.
384    #[must_use]
385    pub fn gguf() -> FetchConfigBuilder {
386        FetchConfigBuilder::default()
387            .filter("*.gguf")
388            .filter("*.json")
389            .filter("*.txt")
390    }
391
392    /// Returns a builder pre-configured to download only `.npz` and `.npy`
393    /// files plus common config files. Matches NumPy-based weight repos
394    /// such as Google's `GemmaScope` transcoders (`config.yaml` + many `.npz`).
395    #[must_use]
396    pub fn npz() -> FetchConfigBuilder {
397        FetchConfigBuilder::default()
398            .filter("*.npz")
399            .filter("*.npy")
400            .filter("config.yaml")
401            .filter("*.json")
402            .filter("*.txt")
403    }
404
405    /// Returns a builder pre-configured to download only `pytorch_model*.bin`
406    /// files plus common config files.
407    #[must_use]
408    pub fn pth() -> FetchConfigBuilder {
409        FetchConfigBuilder::default()
410            .filter("pytorch_model*.bin")
411            .filter("*.json")
412            .filter("*.txt")
413    }
414
415    /// Returns a builder pre-configured to download only config files
416    /// (no model weights).
417    #[must_use]
418    pub fn config_only() -> FetchConfigBuilder {
419        FetchConfigBuilder::default()
420            .filter("*.json")
421            .filter("*.txt")
422            .filter("*.md")
423    }
424}
425
426/// Returns whether `filename` passes the given include/exclude glob filters.
427///
428/// A file matches when it is not excluded by any `exclude` pattern **and**
429/// either there are no `include` patterns or it matches at least one.
430#[must_use]
431pub fn file_matches(filename: &str, include: Option<&GlobSet>, exclude: Option<&GlobSet>) -> bool {
432    if let Some(exc) = exclude {
433        if exc.is_match(filename) {
434            return false;
435        }
436    }
437    if let Some(inc) = include {
438        return inc.is_match(filename);
439    }
440    true
441}
442
443fn build_globset(patterns: &[String]) -> Result<Option<GlobSet>, FetchError> {
444    if patterns.is_empty() {
445        return Ok(None);
446    }
447    let mut builder = GlobSetBuilder::new();
448    for pattern in patterns {
449        // BORROW: explicit .as_str() instead of Deref coercion
450        let glob = Glob::new(pattern.as_str()).map_err(|e| FetchError::InvalidPattern {
451            pattern: pattern.clone(),
452            reason: e.to_string(),
453        })?;
454        builder.add(glob);
455    }
456    let set = builder.build().map_err(|e| FetchError::InvalidPattern {
457        pattern: patterns.join(", "),
458        reason: e.to_string(),
459    })?;
460    Ok(Some(set))
461}
462
463/// Builds a compiled [`GlobSet`] from a list of pattern strings.
464///
465/// Returns `None` if the pattern list is empty. This is useful for callers
466/// that need glob filtering outside the download pipeline (e.g., the
467/// `list-files` subcommand).
468///
469/// # Errors
470///
471/// Returns [`FetchError::InvalidPattern`] if any pattern fails to compile.
472pub fn compile_glob_patterns(patterns: &[String]) -> Result<Option<GlobSet>, FetchError> {
473    build_globset(patterns)
474}
475
476/// Returns `true` if `s` contains glob metacharacters (`*`, `?`, `[`, `{`).
477///
478/// Useful for detecting whether a user-supplied filename should be treated
479/// as a glob pattern or an exact match.
480#[must_use]
481pub fn has_glob_chars(s: &str) -> bool {
482    s.bytes().any(|b| matches!(b, b'*' | b'?' | b'[' | b'{'))
483}
484
485#[cfg(test)]
486mod tests {
487    #![allow(clippy::panic, clippy::unwrap_used, clippy::expect_used)]
488
489    use super::*;
490
491    #[test]
492    fn test_file_matches_no_filters() {
493        assert!(file_matches("model.safetensors", None, None));
494    }
495
496    #[test]
497    fn test_file_matches_include() {
498        let include = build_globset(&["*.safetensors".to_owned()]).unwrap();
499        assert!(file_matches("model.safetensors", include.as_ref(), None));
500        assert!(!file_matches("model.bin", include.as_ref(), None));
501    }
502
503    #[test]
504    fn test_file_matches_exclude() {
505        let exclude = build_globset(&["*.bin".to_owned()]).unwrap();
506        assert!(file_matches("model.safetensors", None, exclude.as_ref()));
507        assert!(!file_matches("model.bin", None, exclude.as_ref()));
508    }
509
510    #[test]
511    fn test_exclude_overrides_include() {
512        let include = build_globset(&["*.safetensors".to_owned(), "*.bin".to_owned()]).unwrap();
513        let exclude = build_globset(&["*.bin".to_owned()]).unwrap();
514        assert!(file_matches(
515            "model.safetensors",
516            include.as_ref(),
517            exclude.as_ref()
518        ));
519        assert!(!file_matches(
520            "model.bin",
521            include.as_ref(),
522            exclude.as_ref()
523        ));
524    }
525
526    #[test]
527    fn test_has_glob_chars() {
528        assert!(has_glob_chars("*.safetensors"));
529        assert!(has_glob_chars("model-[0-9].bin"));
530        assert!(has_glob_chars("model?.bin"));
531        assert!(has_glob_chars("{a,b}.bin"));
532        assert!(!has_glob_chars("model.safetensors"));
533        assert!(!has_glob_chars("config.json"));
534        assert!(!has_glob_chars("pytorch_model.bin"));
535    }
536}