fast-down-api 0.1.1

A convenient and easy-to-use FFI wrapper for fast-down
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
use crate::{Config, PartialConfig};
use fast_down::{FileId, ProgressEntry, UrlInfo};
use inherit_config::{ConfigLayer, InheritConfig};
use parking_lot::Mutex;
use path_helper::tokio::safe_replace;
use reqwest::Response;
use std::{
    path::{Path, PathBuf},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};
use tokio::fs;
use url::Url;

/// Errors that can occur when an explicit [`resume`](crate::resume)
/// cannot continue an interrupted download.
///
/// These are surfaced through [`crate::Event::ResumeError`] so the caller is notified
/// instead of silently falling back to a full re-download.
#[derive(Debug, thiserror::Error)]
#[allow(clippy::large_enum_variant)]
pub enum StateError {
    /// Failed to open or read the `.fd` state file from disk.
    ///
    /// This usually means the file is missing or unreadable (permission error,
    /// removed by another process, etc.).
    #[error("failed to open .fd state file: {0}")]
    Open(std::io::Error),
    /// Failed to persist the `.fd` state file to disk.
    ///
    /// The state was computed but could not be written (disk full, permission
    /// error, etc.).
    #[error("failed to save .fd state file: {0}")]
    Save(std::io::Error),
    /// Failed to deserialize the `.fd` state file.
    ///
    /// The file was read but is not valid TOML, or its schema no longer matches
    /// the current [`DownloadStateInner`] definition.
    #[error("failed to decode .fd state file: {0}")]
    Decode(#[from] toml::de::Error),
    /// Failed to serialize the download state into the `.fd` state file.
    ///
    /// The state could not be encoded as TOML (e.g. a field holds a value that
    /// has no valid TOML representation).
    #[error("failed to encode .fd state file: {0}")]
    Encode(#[from] toml::ser::Error),
    /// The remote file changed (size / etag / last-modified mismatch), so resuming would corrupt the output.
    #[error(
        "remote file changed, cannot resume\n  local:  size={local_file_size}, id={local_file_id:?}\n  remote: size={remote_file_size}, id={remote_file_id:?}"
    )]
    FileChanged {
        local_file_id: FileId,
        local_file_size: u64,
        remote_file_id: FileId,
        remote_file_size: u64,
    },
    /// The `.part` file is shorter than the progress recorded in the `.fd`, so
    /// the recorded ranges no longer describe bytes that exist on disk.
    ///
    /// Continuing would let the sink extend the file with zeros across the
    /// missing span and never fetch it, silently corrupting the output.
    #[error(
        "the .part file was truncated: it holds {actual_size} bytes but the .fd state records progress up to {recorded_size}"
    )]
    Truncated {
        actual_size: u64,
        recorded_size: u64,
    },
    /// The server does not support resumable (range) downloads.
    #[error(
        "server does not support resumable download\n  url_info: {:?}\n  url: {}\n  status: {}\n  headers: {:?}",
        .0, .1.url(), .1.status(), .1.headers()
    )]
    NotResumable(UrlInfo, Response),
    /// No URL is available to resume the download.
    ///
    /// `resume` was called with `url = None` and the persisted `.fd` state file
    /// carries no resolvable initial URL (it was missing, or written by an older
    /// build that did not store one). A URL is required to re-resolve the
    /// resource, so the call reports this error instead of silently falling back
    /// to a full re-download.
    #[error(
        "cannot resume without a URL: none was supplied and the .fd state has none (tmp_path = {0})"
    )]
    NoUrl(PathBuf),
    /// `peek_resume` 收到的 `tmp_path` 不是 `.part` 文件。
    ///
    /// `peek_resume` 需要的是 `.part` 临时文件路径,其同名 `.fd` 才是保存的状态;
    /// 传入其他扩展名的路径属于参数错误,而非文件读取失败。
    #[error("peek_resume requires a .part file, got: {0}")]
    NotAPartFile(PathBuf),
}

/// Full (resolved) download state that is serialized into the `.fd` file.
///
/// `DownloadStateInner` is the non-partial form of the persisted state: every
/// field is present. It is encoded to TOML by [`DownloadState::store`] and read
/// back as the generated partial [`PartialDownloadStateInner`] on resume. The
/// `size` field is recorded for resume validation; older `.fd` files omit it and
/// read back as `None` in the partial form.
#[derive(Debug, Clone, InheritConfig)]
pub struct DownloadStateInner {
    #[config(default = Url::parse("about:blank").unwrap())]
    pub url: Url,
    pub etag: Option<Arc<str>>,
    pub last_modified: Option<Arc<str>>,
    #[config(nest)]
    pub config: Config,
    /// Total file size recorded at save time, compared against the server
    /// `UrlInfo.size` during resume validation.
    ///
    /// An older `.fd` written without this field reads back as `None`, which
    /// makes `validate` fail and safely fall back to a full re-download.
    pub size: u64,
    /// Total active download time accumulated across all resume runs.
    ///
    /// Persisted as a human-readable string (e.g. `"1h 30m 2s"`) via
    /// `humantime_serde`, so the `.fd` file stays easy to inspect and edit by
    /// hand. A zero elapsed is omitted from the file, and a missing `elapsed`
    /// field on load is tolerated (treated as zero). A resumed download
    /// continues this clock instead of restarting it from zero; the progress
    /// reporter folds it into its average-speed calculation, giving a speed that
    /// spans the whole download session rather than only the current run.
    #[config(default = Duration::ZERO)]
    #[config(partial_attr(serde(with = "humantime_serde::option")))]
    #[config(partial_attr(serde(default)))]
    pub elapsed: Duration,
}

/// On-disk state for an in-progress download, backing resume support.
///
/// `DownloadState` pairs a [`PartialDownloadStateInner`] (the persisted config,
/// whose fields may be absent if the `.fd` file predates them) with the path of
/// the `.fd` file and a dirty flag. It is the bridge between a saved `.fd` file
/// and a fresh [`crate::PartialConfig`] handed to
/// [`crate::resume`]: [`DownloadState::merge_config`] folds the
/// loaded progress into the new request so a resumed download continues from the
/// correct byte offset instead of restarting from zero.
///
/// `DownloadState` derefs to [`PartialDownloadStateInner`], so the saved `url`,
/// `etag`, `last_modified`, `config` and `size` are reachable directly.
///
/// The inner state is wrapped in an `Arc<Mutex<PartialDownloadStateInner>>` to
/// provide a single source of truth shared between the engine loop, the
/// internal progress reporter, and any other readers/writers.
///
/// `DownloadState` is cheaply `Clone`able: the clone shares the same inner state
/// and the same dirty flag (both behind `Arc`), so a download driver can hand a
/// clone to a background task that performs the periodic disk persist without
/// blocking the engine event loop.
#[derive(Debug, Clone)]
pub struct DownloadState {
    inner: Arc<Mutex<PartialDownloadStateInner>>,
    is_dirty: Arc<AtomicBool>,
    pub config_path: PathBuf,
}

/// 已保存、可续传下载的只读快照,由 [`DownloadState::snapshot`] 产出。
///
/// 与引擎内部的 `DownloadState`(持有 `Mutex` 与脏标记、可持久化)不同,这是一个纯数据视图,
/// 供 UI 等只读消费者在不持有内部 `MutexGuard` 的情况下读取进度元数据。
#[derive(Debug, Clone)]
pub struct ResumeInfo {
    /// 持久化的初始 URL;旧 `.fd` 可能缺失,故为 `Option`。
    pub url: Option<Url>,
    /// 保存时记录的总大小;缺失时回退为 `0`。
    pub size: u64,
    /// 已写入 `.part` 的字节区间(续传进度的唯一真相)。
    pub progress: Vec<ProgressEntry>,
    /// 跨所有续传累计的活跃下载时长。
    pub elapsed: Duration,
}

impl DownloadState {
    /// Returns a reference to the shared inner state, locked for reading.
    /// Prefer this over the previous `Deref`-based field access.
    pub fn lock_inner(&self) -> parking_lot::MutexGuard<'_, PartialDownloadStateInner> {
        self.inner.lock()
    }

    /// Returns a clone of the shared `Arc<Mutex<PartialDownloadStateInner>>`,
    /// for sharing the authoritative state with other tasks
    /// (e.g. the internal progress reporter).
    #[must_use]
    pub fn share_inner(&self) -> Arc<Mutex<PartialDownloadStateInner>> {
        self.inner.clone()
    }

    /// Build a fresh, dirty download state from the initial prefetch metadata.
    ///
    /// `url` and `url_info` come from the prefetch step, `config` is the
    /// caller-provided [`PartialConfig`], and `config_path` is where the `.fd`
    /// file will be written. The returned state is marked dirty so the first
    /// [`DownloadState::store`] persists it.
    #[must_use]
    pub fn new(url: &Url, url_info: &UrlInfo, config: &PartialConfig, config_path: &Path) -> Self {
        Self {
            inner: Arc::new(Mutex::new(PartialDownloadStateInner {
                url: Some(url.clone()),
                etag: Some(url_info.file_id.etag.clone()),
                last_modified: Some(url_info.file_id.last_modified.clone()),
                config: Some(config.clone()),
                size: Some(url_info.size),
                elapsed: Some(Duration::ZERO),
            })),
            is_dirty: Arc::new(AtomicBool::new(true)),
            config_path: config_path.to_path_buf(),
        }
    }

    /// Load a download state from disk.
    ///
    /// # Errors
    /// Returns an error if the file cannot be read or deserialized.
    #[allow(clippy::result_large_err)]
    pub async fn load(config_path: &Path) -> Result<Self, StateError> {
        let inner = fs::read(&config_path).await.map_err(StateError::Open)?;
        let inner: PartialDownloadStateInner = toml::from_slice(&inner)?;
        Ok(Self {
            inner: Arc::new(Mutex::new(inner)),
            is_dirty: Arc::new(AtomicBool::new(false)),
            config_path: config_path.to_path_buf(),
        })
    }

    /// Persist the download state to disk.
    ///
    /// This serializes a snapshot of the shared inner state and atomically
    /// replaces the `.fd` file. It does **not** consult or clear the dirty flag;
    /// callers decide *when* to persist (typically via [`DownloadState::take_dirty`]
    /// on a fixed cadence, off the engine event loop). Safe to call from a
    /// background task because the heavy `safe_replace` (disk write + fsync) runs
    /// after the inner lock is released.
    ///
    /// # Errors
    /// Returns an error if serializing or writing the state fails.
    #[allow(clippy::result_large_err)]
    pub async fn store(&self) -> Result<(), StateError> {
        let serialized = {
            let mut guard = self.inner.lock();
            guard.simplify_from(&PartialDownloadStateInner::default());
            toml::to_string_pretty(&*guard)?
        };
        safe_replace(&self.config_path, serialized.as_bytes())
            .await
            .map_err(StateError::Save)?;
        Ok(())
    }

    /// Consume the dirty flag (swap to clean) and report whether it was dirty.
    ///
    /// Used by the engine loop on a fixed cadence: a `true` return means "a
    /// persist is due, hand the work to a background task". Because the flag is
    /// an `Arc<AtomicBool>` shared with any clones, the background task and the
    /// loop observe the same flag.
    #[must_use]
    pub fn take_dirty(&self) -> bool {
        self.is_dirty.swap(false, Ordering::SeqCst)
    }

    /// Mark the state dirty so the next persist cycle rewrites the `.fd`.
    ///
    /// Call this when a mutation lands (e.g. progress or identity changed) and
    /// when a background [`DownloadState::store`] fails and should be retried.
    pub fn mark_dirty(&self) {
        self.is_dirty.store(true, Ordering::SeqCst);
    }

    /// Apply a mutation to the inner partial state and mark it dirty.
    ///
    /// Any change made through `cb` (e.g. updating `etag`/`last_modified` or the
    /// nested `config`) schedules the next [`DownloadState::store`].
    pub fn update<F: FnOnce(&mut PartialDownloadStateInner) -> R, R>(&self, cb: F) -> R {
        let res = cb(&mut self.inner.lock());
        self.mark_dirty();
        res
    }

    /// Check whether the server-side file is still the same one this state was
    /// saved for, so a resumed download continues from the correct offset.
    ///
    /// The comparison requires the recorded `size` to match and (unless both
    /// sides are missing identity headers) the `FileId` (`etag` +
    /// `last_modified`) to be equal. Resumable downloads also require the
    /// server to support range requests.
    ///
    /// # Errors
    #[allow(clippy::result_large_err)]
    pub fn validate(&self, info: &UrlInfo) -> Result<(), StateError> {
        let inner = self.inner.lock();
        let local_file_id = FileId {
            etag: inner.etag.clone().flatten(),
            last_modified: inner.last_modified.clone().flatten(),
        };
        let local_file_size = inner.size.unwrap_or(0);
        drop(inner);
        let is_same = local_file_size == info.size && local_file_id == info.file_id;
        if is_same {
            Ok(())
        } else {
            Err(StateError::FileChanged {
                local_file_id,
                local_file_size,
                remote_file_id: info.file_id.clone(),
                remote_file_size: info.size,
            })
        }
    }

    /// Return the list of byte ranges already written to the `.part` file.
    ///
    /// This is the authoritative on-disk progress. It is empty for a brand new
    /// download and grows as [`DownloadState::merge_progress`] is called.
    #[must_use]
    pub fn get_progress(&self) -> Vec<ProgressEntry> {
        self.inner
            .lock()
            .config
            .as_ref()
            .and_then(|c| c.downloaded_chunk.clone())
            .unwrap_or_default()
    }

    /// Total active download time accumulated so far, across all prior resume
    /// runs. `Duration::ZERO` when nothing has been recorded yet.
    #[must_use]
    pub fn get_elapsed(&self) -> Duration {
        self.inner.lock().elapsed.unwrap_or(Duration::ZERO)
    }

    /// 产出一份只读快照,供 UI 等只读消费者读取进度元数据,而无需持有内部 `MutexGuard`。
    ///
    /// 与 [`DownloadState::lock_inner`] 不同,这里返回的是拥有所有权的 [`ResumeInfo`],
    /// 调用方可以随意读取 `url` / `size` / `progress` / `elapsed`,不会触及引擎内部的并发原语。
    #[must_use]
    pub fn snapshot(&self) -> ResumeInfo {
        let guard = self.inner.lock();
        ResumeInfo {
            url: guard.url.clone(),
            size: guard.size.unwrap_or(0),
            progress: guard
                .config
                .as_ref()
                .and_then(|c| c.downloaded_chunk.clone())
                .unwrap_or_default(),
            elapsed: guard.elapsed.unwrap_or(Duration::ZERO),
        }
    }

    /// Set the total accumulated active download time (absolute, not additive).
    ///
    /// Called by the download driver as time accrues, so the value persisted on
    /// the next [`DownloadState::store`] reflects the full session. Marks the
    /// state dirty.
    pub fn set_elapsed(&self, elapsed: Duration) {
        self.update(|inner| inner.elapsed = Some(elapsed));
    }

    /// Merge a freshly-written byte range into the recorded progress.
    ///
    /// The progress list is the authoritative set of on-disk ranges; new ranges
    /// are merged, de-duplicated and normalized. Marks the state dirty.
    pub fn merge_progress(&self, range: ProgressEntry) {
        self.update(|inner| inner.config.get_or_insert_default().merge_progress(range));
    }

    /// Fold a freshly-built [`PartialConfig`] into this loaded state for resume.
    ///
    /// This is the key bridge that preserves download progress across a resume:
    /// the ranges already recorded in `self.config.downloaded_chunk` are merged
    /// into `partial_config` first, so that even if `partial_config` starts from
    /// an empty progress list the resumed download keeps the already-downloaded
    /// bytes. `partial_config` is then layered on top via
    /// `inherit_from`, and the merged result replaces the stored
    /// config. Marks the state dirty.
    pub fn merge_config(&self, partial_config: &PartialConfig) {
        self.update(|inner| {
            let mut pc = partial_config.clone();
            if let Some(config) = &inner.config {
                if let Some(downloaded_chunk) = &config.downloaded_chunk {
                    for i in downloaded_chunk {
                        pc.merge_progress(i.clone());
                    }
                }
                pc.inherit_from(config);
            }
            inner.config = Some(pc);
        });
    }

    /// Refresh the recorded state for a new download session.
    ///
    /// Two fields are refreshed on every (re)start of a download:
    ///
    /// 1. **The durable initial URL.** The URL stored in the `.fd` is the
    ///    caller's *initial* URL — the one passed to `download`/`resume`. When the
    ///    caller supplies a new URL (the `Some` case) it takes priority and
    ///    replaces any previously recorded URL, so a later `resume(None)` still
    ///    re-resolves the resource the caller actually wants. When the URL is
    ///    itself read back from the `.fd` (a `resume(None)`), this assignment is a
    ///    no-op.
    /// 2. **The content identity headers** (etag/last-modified/size), refreshed to
    ///    the fresh server values from the current prefetch.
    ///
    /// The redirect target (`info.final_url`) is deliberately **never** persisted:
    /// such links are usually temporary signed/CDN URLs that expire, so writing one
    /// into the `.fd` would poison the next resume. The download part targets
    /// `info.final_url` directly for range requests, which also avoids a redirect
    /// round-trip on every range request.
    pub fn refresh_identity(&self, url: &Url, info: &UrlInfo) {
        self.update(|inner| {
            inner.url = Some(url.clone());
            inner.etag = Some(info.file_id.etag.clone());
            inner.last_modified = Some(info.file_id.last_modified.clone());
            inner.size = Some(info.size);
        });
    }

    /// Reconstruct the identity of the file this state was saved for.
    ///
    /// Returns a [`FileId`] from the stored `etag` / `last_modified`. Missing
    /// headers collapse to `None`, which makes [`DownloadState::validate`] treat
    /// "no identity on either side" as a match.
    #[must_use]
    pub fn file_id(&self) -> FileId {
        let inner = self.inner.lock();
        FileId {
            etag: inner.etag.clone().flatten(),
            last_modified: inner.last_modified.clone().flatten(),
        }
    }

    /// Path of the partial (`.part`) output file paired with this state.
    ///
    /// Derived from `config_path` by swapping the extension to `.part`.
    #[must_use]
    pub fn tmp_path(&self) -> PathBuf {
        self.config_path.with_extension("part")
    }

    /// Measure `tmp_path` against the progress recorded in this state.
    ///
    /// Returns `Some((actual_size, recorded_size))` when the file is shorter
    /// than the highest recorded offset — the state claims bytes that are not
    /// on disk, so resuming from it would leave that span filled with zeros
    /// that are never fetched.
    ///
    /// Returns `None` when the file is long enough, is not a regular file, or
    /// cannot be inspected; those cases surface later when the sink is built.
    pub async fn part_shortfall(&self, tmp_path: &Path) -> Option<(u64, u64)> {
        let metadata = fs::metadata(tmp_path).await.ok()?;
        if !metadata.is_file() {
            return None;
        }
        let actual_size = metadata.len();
        // `downloaded_chunk` is normalized to ascending `start` order when the
        // `.fd` is loaded, so the last entry's `end` is the highest recorded
        // offset — the frontier a resume would continue from.
        let recorded_size = self.get_progress().last().map_or(0, |r| r.end);
        (actual_size < recorded_size).then_some((actual_size, recorded_size))
    }
}

#[cfg(test)]
mod tests {
    use super::{DownloadState, PartialConfig, StateError};
    use fast_down::{FileId, UrlInfo};
    use std::path::Path;
    use std::time::Duration;
    use url::Url;

    fn make_state(path: &Path) -> DownloadState {
        let url = Url::parse("https://example.com/file.bin").unwrap();
        let url_info = UrlInfo {
            size: 1024,
            raw_name: "file.bin".to_string(),
            supports_range: true,
            fast_download: true,
            final_url: url.clone(),
            file_id: FileId::new(Some("etag-1"), None),
            content_type: Some("application/octet-stream".to_string()),
        };
        DownloadState::new(&url, &url_info, &PartialConfig::default(), path)
    }

    #[tokio::test]
    async fn part_shortfall_reports_short_file_against_recorded_frontier() {
        let dir = std::env::temp_dir().join(format!("fd_ps_short_{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let part = dir.join("a.part");
        let state = make_state(Path::new("dummy.fd"));
        state.merge_progress(0u64..600);
        std::fs::write(&part, vec![0u8; 500]).unwrap();
        assert_eq!(state.part_shortfall(&part).await, Some((500, 600)));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn part_shortfall_is_none_when_file_covers_frontier() {
        let dir = std::env::temp_dir().join(format!("fd_ps_ok_{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let part = dir.join("a.part");
        let state = make_state(Path::new("dummy.fd"));
        state.merge_progress(0u64..600);
        std::fs::write(&part, vec![0u8; 700]).unwrap();
        assert_eq!(state.part_shortfall(&part).await, None);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn elapsed_stored_as_human_readable_string_and_round_trips() {
        let path = std::env::temp_dir().join(format!(
            "fd_elapsed_test_{}.fd",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let state = make_state(&path);
        let value = Duration::from_secs(3661); // 1h 1m 1s
        state.set_elapsed(value);
        state.store().await.unwrap();

        let content = tokio::fs::read_to_string(&path).await.unwrap();
        // Human-readable: a quoted string carrying h/m/s, not raw nanoseconds.
        assert!(
            content.contains("elapsed = \"")
                && content.contains('h')
                && content.contains('m')
                && content.contains('s'),
            "elapsed should be stored as a human-readable string, got:\n{content}"
        );
        assert!(
            !content.contains("3661000000000"),
            "elapsed must not be stored as raw nanoseconds, got:\n{content}"
        );

        let loaded = DownloadState::load(&path).await.unwrap();
        assert_eq!(loaded.get_elapsed(), value);

        let _ = std::fs::remove_file(&path);
    }

    #[tokio::test]
    async fn elapsed_zero_is_not_persisted() {
        let path = std::env::temp_dir().join(format!(
            "fd_elapsed_zero_{}.fd",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let state = make_state(&path); // fresh state => elapsed is ZERO
        state.store().await.unwrap();

        let content = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(
            !content.contains("elapsed"),
            "a zero elapsed should be omitted from the .fd file, got:\n{content}"
        );

        let loaded = DownloadState::load(&path).await.unwrap();
        assert_eq!(loaded.get_elapsed(), Duration::ZERO);

        let _ = std::fs::remove_file(&path);
    }

    #[tokio::test]
    async fn merge_config_adopts_fresh_config_when_loaded_state_has_none() {
        // Regression guard for the bug where a resumed `.fd` that deserializes with
        // `inner.config = None` (which is reachable: `store` omits an all-default
        // `[config]` table via `skip_serializing_if`) made `merge_config` a silent
        // no-op — it marked the state dirty but never adopted the fresh request's
        // config, so the user's resume settings were dropped. The fix makes the
        // `None` arm adopt the fresh config (a real mutation), so the dirty flag is
        // always earned. This test pins that behavior.
        let path = std::env::temp_dir().join(format!(
            "fd_merge_none_{}.fd",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        // A `.fd` with NO `[config]` section: only the fields a valid state needs.
        tokio::fs::write(
            &path,
            "url = \"https://example.com/file.bin\"\nsize = 1024\n",
        )
        .await
        .unwrap();

        let state = DownloadState::load(&path).await.unwrap();
        assert!(
            state.lock_inner().config.is_none(),
            "precondition: a .fd without [config] must load with inner.config = None"
        );

        let fresh = PartialConfig {
            min_chunk_size: Some(1234),
            ..Default::default()
        };
        state.merge_config(&fresh);

        assert!(
            state.lock_inner().config.is_some(),
            "merge_config must adopt the fresh config even when the loaded state had none \
             (regression: it used to be a silent no-op that dropped the resume request)"
        );

        let _ = std::fs::remove_file(&path);
    }

    #[tokio::test]
    #[allow(clippy::single_range_in_vec_init)]
    async fn merge_config_preserves_loaded_progress_into_fresh() {
        // Regression guard for the `Some(downloaded_chunk)` arm of
        // `merge_config` (state.rs lines 313-317): when the loaded `.fd` already
        // records progress, that progress must be folded into the fresh request so a
        // resumed download keeps the already-downloaded bytes, and the fresh
        // request's own overrides (here `min_chunk_size`) must still apply.
        let path = std::env::temp_dir().join(format!(
            "fd_merge_progress_{}.fd",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let state = make_state(&path);
        // Simulate a loaded state that already recorded two contiguous ranges.
        state.inner.lock().config = Some(PartialConfig {
            downloaded_chunk: Some(vec![0u64..10, 10..20]),
            ..Default::default()
        });

        let fresh = PartialConfig {
            min_chunk_size: Some(2048),
            ..Default::default()
        };
        state.merge_config(&fresh);

        let merged = state.inner.lock().config.clone().unwrap();
        assert_eq!(
            merged.downloaded_chunk,
            Some(vec![0u64..20]),
            "loaded progress must be preserved and merged into the fresh config"
        );
        assert_eq!(
            merged.min_chunk_size,
            Some(2048),
            "fresh request overrides must still be applied via inherit_from"
        );

        let _ = std::fs::remove_file(&path);
    }

    fn info_with(etag: Option<&str>, size: u64) -> UrlInfo {
        UrlInfo {
            size,
            raw_name: "file.bin".to_string(),
            supports_range: true,
            fast_download: true,
            final_url: Url::parse("https://example.com/file.bin").unwrap(),
            file_id: FileId::new(etag, None),
            content_type: Some("application/octet-stream".to_string()),
        }
    }

    fn fd_path(name: &str) -> std::path::PathBuf {
        std::env::temp_dir().join(format!(
            "fd_validate_{name}_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ))
    }

    #[test]
    fn validate_ok_when_size_and_file_id_match() {
        // validate (state.rs lines 247-261): identical size + etag must pass.
        let state = make_state(&fd_path("ok"));
        assert!(
            state.validate(&info_with(Some("etag-1"), 1024)).is_ok(),
            "matching size + etag must validate"
        );
    }

    #[test]
    fn validate_rejects_size_mismatch() {
        // Same etag, different size => the remote file changed => FileChanged.
        let state = make_state(&fd_path("size"));
        assert!(matches!(
            state.validate(&info_with(Some("etag-1"), 2048)),
            Err(StateError::FileChanged { .. })
        ));
    }

    #[test]
    fn validate_rejects_etag_mismatch() {
        // Same size, different etag => identity mismatch => FileChanged.
        let state = make_state(&fd_path("etag"));
        assert!(matches!(
            state.validate(&info_with(Some("etag-2"), 1024)),
            Err(StateError::FileChanged { .. })
        ));
    }

    #[test]
    fn refresh_identity_updates_url_to_caller_initial_url_not_final_url() {
        // refresh_identity (state.rs): when a resumed download is called with a
        // URL, that URL must be persisted as the `.fd`'s durable initial URL so a
        // later `resume(None)` re-resolves the caller's resource. It must NOT
        // persist the transient `info.final_url` (signed/CDN links expire). The
        // content identity (etag/last-modified/size) is refreshed to the fresh
        // prefetch values.
        let path = fd_path("refresh_identity");
        let state = make_state(&path); // url = https://example.com/file.bin, etag-1, size 1024
        assert_eq!(
            state.lock_inner().url.as_ref().unwrap().as_str(),
            "https://example.com/file.bin",
            "precondition: fresh state records the initial caller URL"
        );

        // A new caller URL (e.g. a rotated signed URL) and a fresh prefetch whose
        // final_url is a different, transient redirect target.
        let new_initial_url =
            Url::parse("https://example.com/v2/signed-token-xyz/file.bin").unwrap();
        let new_info = UrlInfo {
            size: 2048,
            raw_name: "file.bin".to_string(),
            supports_range: true,
            fast_download: true,
            final_url: Url::parse("https://cdn.example.com/signed/token-abc/file.bin").unwrap(),
            file_id: FileId::new(Some("etag-2"), Some("Mon, 02 Aug 2026 00:00:00 GMT")),
            content_type: Some("application/octet-stream".to_string()),
        };

        // Caller passes the new initial URL: it must take priority over the stored one.
        state.refresh_identity(&new_initial_url, &new_info);
        let inner = state.lock_inner();
        assert_eq!(
            inner.url.as_ref().unwrap().as_str(),
            "https://example.com/v2/signed-token-xyz/file.bin",
            "refresh must update the .fd URL to the caller-supplied initial URL (priority)"
        );
        assert_ne!(
            inner.url.as_ref().unwrap().as_str(),
            "https://cdn.example.com/signed/token-abc/file.bin",
            "refresh must NEVER store the transient final_url in the .fd"
        );
        assert_eq!(
            inner.etag.as_ref().unwrap().as_deref(),
            Some("etag-2"),
            "refresh must update the etag"
        );
        assert_eq!(
            inner.last_modified.as_ref().unwrap().as_deref(),
            Some("Mon, 02 Aug 2026 00:00:00 GMT"),
            "refresh must update last-modified"
        );
        assert_eq!(inner.size, Some(2048), "refresh must update size");
    }
}