ctb_formats_internetarchive/
internetarchive.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Internet Archive file format, item metadata, and checksum parsing utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29pub mod cli;
30
31use anyhow::{Context, Result, anyhow, bail};
32use md5::{Digest as _, Md5};
33use serde::{Deserialize, Serialize};
34use sha1::Sha1;
35use std::collections::{BTreeMap, BTreeSet};
36use std::fs::{self, File, OpenOptions};
37use std::io::{BufReader, Read, Seek, SeekFrom, Write};
38use std::path::{Component, Path, PathBuf};
39use xml::reader::{EventReader, XmlEvent};
40
41const PART_FILE_SUFFIX: &str = ".part";
42const FILES_XML_SUFFIX: &str = "_files.xml";
43const META_XML_SUFFIX: &str = "_meta.xml";
44const META_SQLITE_SUFFIX: &str = "_meta.sqlite";
45const ARCHIVE_TORRENT_SUFFIX: &str = "_archive.torrent";
46const KNOWN_IDENTIFIER_SUFFIXES: [&str; 4] = [
47    FILES_XML_SUFFIX,
48    META_XML_SUFFIX,
49    META_SQLITE_SUFFIX,
50    ARCHIVE_TORRENT_SUFFIX,
51];
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54struct ArchiveTarget {
55    identifier: String,
56    archive_path: Option<String>,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60struct ManifestEntry {
61    name: String,
62    source: Option<String>,
63    md5: Option<String>,
64    sha1: Option<String>,
65    size: Option<u64>,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
69struct FilesManifest {
70    identifier: String,
71    entries: BTreeMap<String, ManifestEntry>,
72}
73
74#[derive(Debug, Clone, Deserialize, Serialize)]
75struct MetadataResponse {
76    #[serde(default)]
77    files: Vec<MetadataFile>,
78
79    #[serde(flatten)]
80    extra: BTreeMap<String, serde_json::Value>,
81}
82
83#[derive(Debug, Clone, Deserialize, Serialize)]
84struct MetadataFile {
85    name: String,
86    #[serde(default)]
87    source: Option<String>,
88    #[serde(default)]
89    md5: Option<String>,
90    #[serde(default)]
91    sha1: Option<String>,
92    #[serde(default)]
93    size: Option<String>,
94}
95
96#[derive(Debug, Serialize, PartialEq, Eq)]
97struct VerificationMismatch {
98    name: String,
99    #[serde(skip_serializing_if = "Option::is_none")]
100    expected_sha1: Option<String>,
101    #[serde(skip_serializing_if = "Option::is_none")]
102    actual_sha1: Option<String>,
103    #[serde(skip_serializing_if = "Option::is_none")]
104    expected_md5: Option<String>,
105    #[serde(skip_serializing_if = "Option::is_none")]
106    actual_md5: Option<String>,
107    #[serde(skip_serializing_if = "Option::is_none")]
108    expected_size: Option<u64>,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    actual_size: Option<u64>,
111}
112
113#[derive(Debug, Serialize, PartialEq, Eq)]
114struct VerificationResult {
115    valid: bool,
116    identifier: String,
117    checked_files: Vec<String>,
118    missing_files: Vec<String>,
119    mismatched_files: Vec<VerificationMismatch>,
120    unexpected_files: Vec<String>,
121}
122
123#[derive(Debug, Serialize, PartialEq, Eq)]
124struct DownloadResult {
125    identifier: String,
126    output_directory: String,
127    downloaded_files: Vec<String>,
128}
129
130#[derive(Debug, Serialize, PartialEq, Eq)]
131struct DownloadHereResult {
132    identifier: String,
133    output_path: String,
134}
135
136trait ArchiveClient {
137    fn fetch_metadata(&self, identifier: &str) -> Result<MetadataResponse>;
138    fn fetch_files_xml_bytes(&self, identifier: &str) -> Result<Vec<u8>>;
139    fn fetch_meta_xml_bytes(&self, identifier: &str) -> Result<Vec<u8>>;
140    fn fetch_download_bytes(
141        &self,
142        identifier: &str,
143        file_name: &str,
144    ) -> Result<Vec<u8>>;
145    fn download_file(
146        &self,
147        identifier: &str,
148        file_name: &str,
149        destination: &Path,
150        expected_size: Option<u64>,
151        file_progress: Option<&FileItemProgress>,
152    ) -> Result<u64> {
153        let bytes = self.fetch_download_bytes(identifier, file_name)?;
154        let len_u64 = u64::try_from(bytes.len()).map_err(|e| {
155            anyhow!("Failed to convert byte length to u64: {e}")
156        })?;
157        if let Some(expected) = expected_size {
158            anyhow::ensure!(
159                len_u64 == expected,
160                "Downloaded size {len_u64} did not match expected size {expected} for {file_name}"
161            );
162        }
163        if let Some(fp) = file_progress {
164            fp.set_total_bytes(len_u64);
165            fp.set_bytes_done(len_u64);
166        }
167        // Reason for fallback: If destination has no parent path (bare filename), stage .part file in current directory.
168        let parent = destination.parent().unwrap_or_else(|| Path::new("."));
169        fs::create_dir_all(parent).with_context(|| {
170            format!("Failed to create parent directory {}", parent.display())
171        })?;
172        let part_path = part_path_for_destination(destination);
173        let mut part_file = OpenOptions::new()
174            .create(true)
175            .read(true)
176            .write(true)
177            .open(&part_path)
178            .with_context(|| {
179                format!(
180                    "Failed to open partial download file {}",
181                    part_path.display()
182                )
183            })?;
184        let existing_len = part_file
185            .metadata()
186            .with_context(|| {
187                format!("Failed to read metadata for {}", part_path.display())
188            })?
189            .len();
190        let existing_usize = usize::try_from(existing_len).ok();
191        let can_append = existing_usize.is_some_and(|existing| {
192            existing <= bytes.len()
193                && bytes.get(..existing).is_some_and(|prefix| {
194                    let mut current = vec![0_u8; existing];
195                    part_file
196                        .read_exact(&mut current)
197                        .is_ok_and(|()| current.as_slice() == prefix)
198                })
199        });
200        if let Some(existing) = existing_usize.filter(|_| can_append) {
201            part_file.seek(SeekFrom::End(0)).with_context(|| {
202                format!("Failed to seek to end of {}", part_path.display())
203            })?;
204            if let Some(tail) = bytes.get(existing..) {
205                part_file.write_all(tail).with_context(|| {
206                    format!("Failed to append to {}", part_path.display())
207                })?;
208            }
209        } else {
210            part_file.set_len(0).with_context(|| {
211                format!("Failed to truncate {}", part_path.display())
212            })?;
213            part_file.seek(SeekFrom::Start(0)).with_context(|| {
214                format!("Failed to seek to start of {}", part_path.display())
215            })?;
216            part_file.write_all(&bytes).with_context(|| {
217                format!("Failed to write {}", part_path.display())
218            })?;
219        }
220        part_file.sync_all().with_context(|| {
221            format!("Failed to sync {}", part_path.display())
222        })?;
223        drop(part_file);
224        commit_atomic_file(&part_path, destination)?;
225        Ok(len_u64)
226    }
227}
228
229struct LiveArchiveClient;
230
231impl ArchiveClient for LiveArchiveClient {
232    fn fetch_metadata(&self, identifier: &str) -> Result<MetadataResponse> {
233        fetch_live_metadata(identifier)
234    }
235
236    fn fetch_files_xml_bytes(&self, identifier: &str) -> Result<Vec<u8>> {
237        fetch_live_files_xml_bytes(identifier)
238    }
239
240    fn fetch_meta_xml_bytes(&self, identifier: &str) -> Result<Vec<u8>> {
241        fetch_live_meta_xml_bytes(identifier)
242    }
243
244    fn fetch_download_bytes(
245        &self,
246        identifier: &str,
247        file_name: &str,
248    ) -> Result<Vec<u8>> {
249        fetch_download_bytes(identifier, file_name)
250    }
251
252    fn download_file(
253        &self,
254        identifier: &str,
255        file_name: &str,
256        destination: &Path,
257        expected_size: Option<u64>,
258        file_progress: Option<&FileItemProgress>,
259    ) -> Result<u64> {
260        download_live_file_chunked_range(
261            identifier,
262            file_name,
263            destination,
264            expected_size,
265            file_progress,
266        )
267    }
268}
269
270#[derive(Debug, Clone, PartialEq, Eq)]
271struct VerificationOptions {
272    files_xml_live_sha1: Option<String>,
273}
274
275pub fn guess_identifier_from_path(path: &Path) -> Option<String> {
276    guess_identifer_from_path(path)
277}
278
279/// Look for `ident_files.xml`, `ident_meta.xml`, `ident_archive.torrent`,
280/// and/or `ident_meta.sqlite`; fall back to a plausible identifier-shaped
281/// directory name; otherwise return `None`.
282pub fn guess_identifer_from_path(path: &Path) -> Option<String> {
283    if let Some(file_name) = path.file_name().and_then(std::ffi::OsStr::to_str)
284    {
285        if let Some(identifier) = identifier_from_metadata_name(file_name) {
286            return Some(identifier);
287        }
288    }
289
290    if path.is_dir() {
291        if let Ok(entries) = fs::read_dir(path) {
292            for entry in entries.flatten() {
293                let name = entry.file_name();
294                if let Some(identifier) =
295                    name.to_str().and_then(identifier_from_metadata_name)
296                {
297                    return Some(identifier);
298                }
299            }
300        }
301    }
302
303    if let Some(parent_name) = path
304        .parent()
305        .and_then(Path::file_name)
306        .and_then(std::ffi::OsStr::to_str)
307        .filter(|name| is_probable_identifier(name))
308    {
309        return Some(parent_name.to_string());
310    }
311
312    path.file_name()
313        .and_then(std::ffi::OsStr::to_str)
314        .filter(|name| is_probable_identifier(name))
315        .map(std::string::ToString::to_string)
316}
317
318/// If `check_live` is true, fetch the live files XML and verify the local item
319/// against that manifest instead of a local `*_files.xml`.
320/// If `original` is true, only verify files with source="original".
321pub fn verify(
322    item_path: &Path,
323    identifier: Option<&str>,
324    check_live: bool,
325    original: bool,
326) -> Result<Vec<u8>> {
327    let root = normalize_item_root(item_path);
328    let identifier = resolve_identifier(item_path, identifier)?;
329    let (manifest, files_xml_live_sha1) = if check_live {
330        let live_files_xml_bytes = fetch_live_files_xml_bytes(&identifier)?;
331        let manifest =
332            parse_files_manifest(&identifier, &live_files_xml_bytes)?;
333        let sha1 = Some(sha1_hex_for_bytes(&live_files_xml_bytes));
334        (manifest, sha1)
335    } else {
336        let manifest = load_local_files_manifest(&root, &identifier)?;
337        (manifest, None)
338    };
339    let selected_files = if original {
340        Some(
341            manifest
342                .entries
343                .values()
344                .filter(|entry| entry.source.as_deref() == Some("original"))
345                .map(|entry| entry.name.clone())
346                .collect::<BTreeSet<_>>(),
347        )
348    } else {
349        None
350    };
351    let verification = verify_against_manifest(
352        &root,
353        &identifier,
354        &manifest,
355        selected_files.as_ref(),
356        true,
357        &VerificationOptions {
358            files_xml_live_sha1,
359        },
360        None,
361    )?;
362    pretty_json_bytes(&verification)
363}
364
365pub fn iasha1(
366    target: &str,
367    identifier: Option<&str>,
368    check_live: bool,
369) -> Result<Vec<u8>> {
370    let resolved_target = resolve_hash_target(target, identifier)?;
371    let manifest = if check_live {
372        fetch_live_files_manifest(&resolved_target.identifier)?
373    } else {
374        load_manifest_for_hash_target(&resolved_target)?
375    };
376    let sha1 =
377        sha1_for_manifest_entry(&resolved_target, &manifest, check_live)?;
378    let mut output = sha1.into_bytes();
379    output.push(b'\n');
380    Ok(output)
381}
382
383pub fn iamd5(
384    target: &str,
385    identifier: Option<&str>,
386    check_live: bool,
387) -> Result<Vec<u8>> {
388    let resolved_target = resolve_hash_target(target, identifier)?;
389    let manifest = if check_live {
390        fetch_live_files_manifest(&resolved_target.identifier)?
391    } else {
392        load_manifest_for_hash_target(&resolved_target)?
393    };
394    let md5 = md5_for_manifest_entry(&resolved_target, &manifest, check_live)?;
395    let mut output = md5.into_bytes();
396    output.push(b'\n');
397    Ok(output)
398}
399
400pub fn contains(target: &str, desired_file: &str) -> Result<Vec<u8>> {
401    contains_with_client(&LiveArchiveClient, target, desired_file)
402}
403
404pub fn listplain(target: &str) -> Result<Vec<u8>> {
405    listplain_with_client(&LiveArchiveClient, target)
406}
407
408pub fn metadata(target: &str) -> Result<Vec<u8>> {
409    metadata_with_client(&LiveArchiveClient, target)
410}
411
412pub fn filesxml(target: &str) -> Result<Vec<u8>> {
413    filesxml_with_client(&LiveArchiveClient, target)
414}
415
416pub fn metaxml(target: &str) -> Result<Vec<u8>> {
417    metaxml_with_client(&LiveArchiveClient, target)
418}
419
420pub fn download(
421    target: &str,
422    output_dir: Option<&Path>,
423    original: bool,
424    progress: Progress,
425) -> Result<Vec<u8>> {
426    download_with_client(
427        &LiveArchiveClient,
428        target,
429        output_dir,
430        original,
431        progress,
432    )
433}
434
435pub fn download_as_stream(target: &str) -> Result<Vec<u8>> {
436    download_as_stream_with_client(&LiveArchiveClient, target)
437}
438
439pub fn download_here(
440    target: &str,
441    output_dir: Option<&Path>,
442    progress: Progress,
443) -> Result<Vec<u8>> {
444    download_here_with_client(&LiveArchiveClient, target, output_dir, progress)
445}
446
447fn resolve_download_file_specs(
448    client: &dyn ArchiveClient,
449    archive_target: &ArchiveTarget,
450    original: bool,
451    manifest: Option<&FilesManifest>,
452) -> Result<Vec<(String, Option<u64>)>> {
453    if original {
454        let metadata_files =
455            client.fetch_metadata(&archive_target.identifier)?.files;
456        let original_files: Vec<(String, Option<u64>)> = metadata_files
457            .into_iter()
458            .filter(|file| file.source.as_deref() == Some("original"))
459            .map(|file| {
460                let size =
461                    file.size.as_deref().and_then(|s| s.parse().ok()).or_else(
462                        || {
463                            manifest
464                                .and_then(|m| m.entries.get(&file.name))
465                                .and_then(|e| e.size)
466                        },
467                    );
468                (file.name, size)
469            })
470            .collect();
471        if let Some(file_name) = &archive_target.archive_path {
472            Ok(original_files
473                .into_iter()
474                .filter(|(name, _)| name == file_name)
475                .collect())
476        } else {
477            Ok(original_files)
478        }
479    } else if let Some(file_name) = &archive_target.archive_path {
480        let known_size = manifest
481            .and_then(|m| m.entries.get(file_name))
482            .and_then(|e| e.size);
483        Ok(vec![(file_name.clone(), known_size)])
484    } else {
485        Ok(client
486            .fetch_metadata(&archive_target.identifier)?
487            .files
488            .into_iter()
489            .map(|file| {
490                let size =
491                    file.size.as_deref().and_then(|s| s.parse().ok()).or_else(
492                        || {
493                            manifest
494                                .and_then(|m| m.entries.get(&file.name))
495                                .and_then(|e| e.size)
496                        },
497                    );
498                (file.name, size)
499            })
500            .collect())
501    }
502}
503
504fn start_download_batch(
505    progress: &Progress,
506    identifier: &str,
507    file_specs: &[(String, Option<u64>)],
508) -> Result<FileBatchProgress> {
509    let total_files_u64 = u64::try_from(file_specs.len())
510        .map_err(|e| anyhow!("Failed to convert file count to u64: {e}"))?;
511    let initial_known_bytes: u64 = file_specs
512        .iter()
513        .filter_map(|(_, sz)| *sz)
514        .fold(0_u64, u64::saturating_add);
515    let any_known_size = file_specs.iter().any(|(_, sz)| sz.is_some());
516    Ok(progress.start_file_batch(
517        &format!("Overall ({identifier})"),
518        Some(total_files_u64),
519        any_known_size.then_some(initial_known_bytes),
520    ))
521}
522
523fn download_with_client(
524    client: &dyn ArchiveClient,
525    target: &str,
526    output_dir: Option<&Path>,
527    original: bool,
528    progress: Progress,
529) -> Result<Vec<u8>> {
530    let archive_target = parse_archive_target(target)?;
531    let base_output_dir = resolve_output_dir(output_dir)?;
532    let item_directory = base_output_dir.join(&archive_target.identifier);
533    fs::create_dir_all(&item_directory).with_context(|| {
534        format!("Failed to create {}", item_directory.display())
535    })?;
536
537    progress.message(&format!(
538        "Downloading item '{}' to {}",
539        archive_target.identifier,
540        item_directory.display()
541    ));
542
543    let file_specs =
544        resolve_download_file_specs(client, &archive_target, original, None)?;
545    let batch = start_download_batch(
546        &progress,
547        &archive_target.identifier,
548        &file_specs,
549    )?;
550
551    let mut downloaded_files = Vec::new();
552
553    for (file_name, known_size) in &file_specs {
554        let destination = item_directory.join(Path::new(file_name));
555        if let Some(parent) = destination.parent() {
556            fs::create_dir_all(parent).with_context(|| {
557                format!(
558                    "Failed to create parent directory {}",
559                    parent.display()
560                )
561            })?;
562        }
563        let part_path = part_path_for_destination(&destination);
564        if let Some(expected_sz) = *known_size
565            && destination.is_file()
566            && !part_path.exists()
567            && fs::metadata(&destination).is_ok_and(|m| m.len() == expected_sz)
568        {
569            let fp =
570                batch.start_transient_file("Existing", file_name, *known_size);
571            fp.finish(expected_sz);
572            downloaded_files.push(file_name.clone());
573            continue;
574        }
575        let file_progress = batch.start_file(file_name, *known_size);
576        let bytes_written = client.download_file(
577            &archive_target.identifier,
578            file_name,
579            &destination,
580            *known_size,
581            Some(&file_progress),
582        )?;
583        file_progress.finish(bytes_written);
584        downloaded_files.push(file_name.clone());
585    }
586
587    batch.finish();
588
589    let result = DownloadResult {
590        identifier: archive_target.identifier,
591        output_directory: item_directory.display().to_string(),
592        downloaded_files,
593    };
594    pretty_json_bytes(&result)
595}
596
597pub fn checkeddl(
598    target: &str,
599    output_dir: Option<&Path>,
600    original: bool,
601    progress: Progress,
602) -> Result<Vec<u8>> {
603    checkeddl_with_client(
604        &LiveArchiveClient,
605        target,
606        output_dir,
607        original,
608        progress,
609    )
610}
611
612#[expect(
613    clippy::too_many_arguments,
614    reason = "Internal per-file resume and manifest verification helper"
615)]
616fn checkeddl_download_or_resume_file(
617    client: &dyn ArchiveClient,
618    item_directory: &Path,
619    identifier: &str,
620    file_name: &str,
621    known_size: Option<u64>,
622    manifest: &FilesManifest,
623    verify_options: &VerificationOptions,
624    batch: &FileBatchProgress,
625    progress: &Progress,
626    pre_verified_ok: &mut BTreeSet<String>,
627) -> Result<()> {
628    let destination = item_directory.join(Path::new(file_name));
629    if let Some(parent) = destination.parent() {
630        fs::create_dir_all(parent).with_context(|| {
631            format!("Failed to create parent directory {}", parent.display())
632        })?;
633    }
634    let part_path = part_path_for_destination(&destination);
635    let entry_opt = manifest.entries.get(file_name);
636
637    if destination.is_file()
638        && let Some(entry) = entry_opt
639    {
640        let check_fp =
641            batch.start_transient_file("Check", file_name, known_size);
642        let (mismatch_opt, hashed_len) = verify_local_file(
643            item_directory,
644            identifier,
645            &destination,
646            entry,
647            verify_options,
648            Some(&check_fp),
649        )?;
650        if mismatch_opt.is_none() {
651            if part_path.is_file() {
652                drop(fs::remove_file(&part_path));
653            }
654            check_fp.finish(hashed_len);
655            pre_verified_ok.insert(file_name.to_string());
656            return Ok(());
657        }
658        drop(check_fp);
659        if !part_path.is_file() {
660            drop(fs::remove_file(&destination));
661        }
662    }
663
664    let had_existing_part = part_path.is_file();
665    let file_progress = batch.start_file(file_name, known_size);
666    let bytes_written = client.download_file(
667        identifier,
668        file_name,
669        &destination,
670        known_size,
671        Some(&file_progress),
672    )?;
673    file_progress.finish(bytes_written);
674
675    if had_existing_part && let Some(entry) = entry_opt {
676        let (mismatch_opt, _) = verify_local_file(
677            item_directory,
678            identifier,
679            &destination,
680            entry,
681            verify_options,
682            None,
683        )?;
684        if mismatch_opt.is_none() {
685            pre_verified_ok.insert(file_name.to_string());
686        } else {
687            progress.message(&format!(
688                "Resumed partial download for '{file_name}' did not match manifest checksum; re-downloading cleanly..."
689            ));
690            drop(fs::remove_file(&destination));
691            if part_path.is_file() {
692                drop(fs::remove_file(&part_path));
693            }
694            let retry_fp =
695                batch.start_transient_file("Retry", file_name, known_size);
696            let retried_bytes = client.download_file(
697                identifier,
698                file_name,
699                &destination,
700                known_size,
701                Some(&retry_fp),
702            )?;
703            retry_fp.finish(retried_bytes);
704        }
705    }
706    Ok(())
707}
708
709fn checkeddl_with_client(
710    client: &dyn ArchiveClient,
711    target: &str,
712    output_dir: Option<&Path>,
713    original: bool,
714    progress: Progress,
715) -> Result<Vec<u8>> {
716    let archive_target = parse_archive_target(target)?;
717    let base_output_dir = resolve_output_dir(output_dir)?;
718    let item_directory = base_output_dir.join(&archive_target.identifier);
719    fs::create_dir_all(&item_directory).with_context(|| {
720        format!("Failed to create {}", item_directory.display())
721    })?;
722
723    progress.message(&format!(
724        "Downloading item '{}' to {}",
725        archive_target.identifier,
726        item_directory.display()
727    ));
728
729    let live_files_xml_bytes =
730        client.fetch_files_xml_bytes(&archive_target.identifier)?;
731    let manifest = parse_files_manifest(
732        &archive_target.identifier,
733        &live_files_xml_bytes,
734    )?;
735    let verify_options = VerificationOptions {
736        files_xml_live_sha1: Some(sha1_hex_for_bytes(&live_files_xml_bytes)),
737    };
738    let files_xml_name =
739        format!("{}{FILES_XML_SUFFIX}", archive_target.identifier);
740    let files_xml_path = item_directory.join(&files_xml_name);
741
742    let file_specs = resolve_download_file_specs(
743        client,
744        &archive_target,
745        original,
746        Some(&manifest),
747    )?;
748    let batch = start_download_batch(
749        &progress,
750        &archive_target.identifier,
751        &file_specs,
752    )?;
753    let mut pre_verified_ok = BTreeSet::new();
754
755    for (file_name, known_size) in &file_specs {
756        if file_name == &files_xml_name {
757            write_atomic_bytes(&files_xml_path, &live_files_xml_bytes)?;
758            let xml_len = u64::try_from(live_files_xml_bytes.len())
759                .map_err(|e| anyhow!("Invalid files.xml length: {e}"))?;
760            let fp = batch.start_file(file_name, Some(xml_len));
761            fp.finish(xml_len);
762            pre_verified_ok.insert(file_name.clone());
763            continue;
764        }
765        checkeddl_download_or_resume_file(
766            client,
767            &item_directory,
768            &archive_target.identifier,
769            file_name,
770            *known_size,
771            &manifest,
772            &verify_options,
773            &batch,
774            &progress,
775            &mut pre_verified_ok,
776        )?;
777    }
778
779    batch.finish();
780
781    if !files_xml_path.exists() || archive_target.archive_path.is_none() {
782        write_atomic_bytes(&files_xml_path, &live_files_xml_bytes)?;
783    }
784
785    progress.message("Verifying downloaded files...");
786    let selected_files =
787        if let Some(file_name) = archive_target.archive_path.clone() {
788            let mut files = BTreeSet::new();
789            if !original
790                || manifest
791                    .entries
792                    .get(&file_name)
793                    .and_then(|entry| entry.source.as_deref())
794                    == Some("original")
795            {
796                files.insert(file_name);
797            }
798            Some(files)
799        } else if original {
800            Some(
801                manifest
802                    .entries
803                    .values()
804                    .filter(|entry| entry.source.as_deref() == Some("original"))
805                    .map(|entry| entry.name.clone())
806                    .collect(),
807            )
808        } else {
809            None
810        };
811    let verification = verify_against_manifest_with_preverified(
812        &item_directory,
813        &archive_target.identifier,
814        &manifest,
815        selected_files.as_ref(),
816        archive_target.archive_path.is_none(),
817        &verify_options,
818        &pre_verified_ok,
819        Some(&progress),
820    )?;
821    progress.message("Verification complete.");
822    pretty_json_bytes(&verification)
823}
824
825fn download_as_stream_with_client(
826    client: &dyn ArchiveClient,
827    target: &str,
828) -> Result<Vec<u8>> {
829    let archive_target = parse_archive_target(target)?;
830    let Some(file_name) = archive_target.archive_path else {
831        bail!("downloadAsStream requires an item file path or download URL");
832    };
833    client.fetch_download_bytes(&archive_target.identifier, &file_name)
834}
835
836fn download_here_with_client(
837    client: &dyn ArchiveClient,
838    target: &str,
839    output_dir: Option<&Path>,
840    progress: Progress,
841) -> Result<Vec<u8>> {
842    let archive_target = parse_archive_target(target)?;
843    let Some(file_name) = archive_target.archive_path.clone() else {
844        bail!("downloadHere requires an item file path or download URL");
845    };
846    let base_output_dir = resolve_output_dir(output_dir)?;
847    let leaf_name = Path::new(&file_name)
848        .file_name()
849        .and_then(std::ffi::OsStr::to_str)
850        .ok_or_else(|| {
851            anyhow!("Could not determine local file name for {file_name}")
852        })?;
853    let output_path = base_output_dir.join(leaf_name);
854    let batch = progress.start_file_batch(
855        &format!("Overall ({})", archive_target.identifier),
856        Some(1),
857        None,
858    );
859    let file_progress = batch.start_file(&file_name, None);
860    let bytes_written = client.download_file(
861        &archive_target.identifier,
862        &file_name,
863        &output_path,
864        None,
865        Some(&file_progress),
866    )?;
867    file_progress.finish(bytes_written);
868    batch.finish();
869    let result = DownloadHereResult {
870        identifier: archive_target.identifier,
871        output_path: output_path.display().to_string(),
872    };
873    pretty_json_bytes(&result)
874}
875
876fn normalize_item_root(item_path: &Path) -> PathBuf {
877    if item_path.is_file() {
878        item_path
879            .parent()
880            // Reason for fallback: when item_path is a root file without a parent directory, falling back to item_path itself maintains a valid PathBuf root.
881            .map_or_else(|| item_path.to_path_buf(), Path::to_path_buf)
882    } else {
883        item_path.to_path_buf()
884    }
885}
886
887fn resolve_identifier(
888    item_path: &Path,
889    identifier: Option<&str>,
890) -> Result<String> {
891    if let Some(identifier) = identifier {
892        let archive_target = parse_archive_target(identifier)?;
893        return Ok(archive_target.identifier);
894    }
895    guess_identifer_from_path(item_path).ok_or_else(|| {
896        anyhow!("Could not determine Internet Archive identifier")
897    })
898}
899
900fn resolve_output_dir(output_dir: Option<&Path>) -> Result<PathBuf> {
901    if let Some(output_dir) = output_dir {
902        return Ok(output_dir.to_path_buf());
903    }
904    std::env::current_dir().context("Failed to determine current directory")
905}
906
907fn resolve_hash_target(
908    target: &str,
909    identifier: Option<&str>,
910) -> Result<HashTarget> {
911    let target_path = Path::new(target);
912    if target_path.exists() {
913        let root = normalize_item_root(target_path);
914        let identifier = resolve_identifier(target_path, identifier)?;
915        let file_name = if target_path.is_file() {
916            relative_archive_name(&root, target_path)?
917        } else {
918            bail!("A file path is required when hashing a local target");
919        };
920        return Ok(HashTarget {
921            identifier,
922            file_name,
923            local_root: Some(root),
924            local_file_path: Some(target_path.to_path_buf()),
925        });
926    }
927
928    let archive_target = parse_archive_target(target)?;
929    let Some(file_name) = archive_target.archive_path else {
930        bail!("A file path inside the item is required");
931    };
932    Ok(HashTarget {
933        identifier: archive_target.identifier,
934        file_name,
935        local_root: None,
936        local_file_path: None,
937    })
938}
939
940#[derive(Debug, Clone, PartialEq, Eq)]
941struct HashTarget {
942    identifier: String,
943    file_name: String,
944    local_root: Option<PathBuf>,
945    local_file_path: Option<PathBuf>,
946}
947
948fn sha1_for_manifest_entry(
949    target: &HashTarget,
950    manifest: &FilesManifest,
951    check_live: bool,
952) -> Result<String> {
953    if target.file_name == format!("{}{FILES_XML_SUFFIX}", target.identifier) {
954        if check_live {
955            let xml_bytes = fetch_live_files_xml_bytes(&target.identifier)?;
956            return Ok(sha1_hex_for_bytes(&xml_bytes));
957        }
958
959        let local_file_path =
960            if let Some(local_file_path) = &target.local_file_path {
961                local_file_path.clone()
962            } else if let Some(local_root) = &target.local_root {
963                local_root.join(&target.file_name)
964            } else {
965                bail!(
966                    "A local files XML copy is required to hash {0}",
967                    target.file_name
968                );
969            };
970        return sha1_hex_for_file(&local_file_path);
971    }
972
973    if let Some(entry) = manifest.entries.get(&target.file_name) {
974        if let Some(sha1) = &entry.sha1 {
975            return Ok(sha1.clone());
976        }
977    }
978
979    if let Some(local_file_path) = &target.local_file_path {
980        return sha1_hex_for_file(local_file_path);
981    }
982
983    bail!(
984        "No sha1 value is available for {} in item {}",
985        target.file_name,
986        target.identifier
987    )
988}
989
990fn md5_for_manifest_entry(
991    target: &HashTarget,
992    manifest: &FilesManifest,
993    check_live: bool,
994) -> Result<String> {
995    if target.file_name == format!("{}{FILES_XML_SUFFIX}", target.identifier) {
996        if check_live {
997            let xml_bytes = fetch_live_files_xml_bytes(&target.identifier)?;
998            return Ok(md5_hex_for_bytes(&xml_bytes));
999        }
1000
1001        let local_file_path =
1002            if let Some(local_file_path) = &target.local_file_path {
1003                local_file_path.clone()
1004            } else if let Some(local_root) = &target.local_root {
1005                local_root.join(&target.file_name)
1006            } else {
1007                bail!(
1008                    "A local files XML copy is required to hash {0}",
1009                    target.file_name
1010                );
1011            };
1012        return md5_hex_for_file(&local_file_path);
1013    }
1014
1015    if let Some(entry) = manifest.entries.get(&target.file_name) {
1016        if let Some(md5) = &entry.md5 {
1017            return Ok(md5.clone());
1018        }
1019    }
1020
1021    if let Some(local_file_path) = &target.local_file_path {
1022        return md5_hex_for_file(local_file_path);
1023    }
1024
1025    bail!(
1026        "No md5 value is available for {} in item {}",
1027        target.file_name,
1028        target.identifier
1029    )
1030}
1031
1032fn load_manifest_for_hash_target(target: &HashTarget) -> Result<FilesManifest> {
1033    if let Some(local_root) = &target.local_root {
1034        return load_local_files_manifest(local_root, &target.identifier);
1035    }
1036    fetch_live_files_manifest(&target.identifier)
1037}
1038
1039fn verify_against_manifest(
1040    item_root: &Path,
1041    identifier: &str,
1042    manifest: &FilesManifest,
1043    selected_files: Option<&BTreeSet<String>>,
1044    include_unexpected: bool,
1045    options: &VerificationOptions,
1046    progress: Option<&Progress>,
1047) -> Result<VerificationResult> {
1048    let empty_preverified = BTreeSet::new();
1049    verify_against_manifest_with_preverified(
1050        item_root,
1051        identifier,
1052        manifest,
1053        selected_files,
1054        include_unexpected,
1055        options,
1056        &empty_preverified,
1057        progress,
1058    )
1059}
1060
1061#[expect(
1062    clippy::too_many_arguments,
1063    reason = "Internal manifest verifier accepting optional pre-verified set from resumed checkeddl"
1064)]
1065fn verify_against_manifest_with_preverified(
1066    item_root: &Path,
1067    identifier: &str,
1068    manifest: &FilesManifest,
1069    selected_files: Option<&BTreeSet<String>>,
1070    include_unexpected: bool,
1071    options: &VerificationOptions,
1072    pre_verified_ok: &BTreeSet<String>,
1073    progress: Option<&Progress>,
1074) -> Result<VerificationResult> {
1075    let selected_names: BTreeSet<String> =
1076        if let Some(selected_files) = selected_files {
1077            selected_files.clone()
1078        } else {
1079            manifest.entries.keys().cloned().collect()
1080        };
1081
1082    let total_files = selected_names.len();
1083    let total_files_u64 = u64::try_from(total_files)
1084        .map_err(|e| anyhow!("Failed to convert verify count to u64: {e}"))?;
1085    let known_verify_bytes: u64 = selected_names
1086        .iter()
1087        .filter_map(|name| manifest.entries.get(name).and_then(|e| e.size))
1088        .fold(0_u64, u64::saturating_add);
1089    let any_known_size = selected_names
1090        .iter()
1091        .any(|name| manifest.entries.get(name).and_then(|e| e.size).is_some());
1092
1093    let verify_batch = progress.map(|prog| {
1094        prog.start_file_batch(
1095            &format!("Verifying ({identifier})"),
1096            Some(total_files_u64),
1097            any_known_size.then_some(known_verify_bytes),
1098        )
1099    });
1100
1101    let mut checked_files = Vec::new();
1102    let mut missing_files = Vec::new();
1103    let mut mismatched_files = Vec::new();
1104
1105    for file_name in &selected_names {
1106        let Some(entry) = manifest.entries.get(file_name) else {
1107            missing_files.push(file_name.clone());
1108            if let Some(ref batch) = verify_batch {
1109                batch.record_skipped_file();
1110            }
1111            continue;
1112        };
1113        let local_path = item_root.join(Path::new(file_name));
1114        if !local_path.is_file() {
1115            missing_files.push(file_name.clone());
1116            if let Some(ref batch) = verify_batch {
1117                batch.record_skipped_file();
1118            }
1119            continue;
1120        };
1121
1122        if pre_verified_ok.contains(file_name)
1123            && let Ok(meta) = fs::metadata(&local_path)
1124            && entry.size.is_none_or(|sz| sz == meta.len())
1125        {
1126            if let Some(ref batch) = verify_batch {
1127                let fp = batch.start_transient_file(
1128                    "Verify",
1129                    file_name,
1130                    Some(meta.len()),
1131                );
1132                fp.finish(meta.len());
1133            }
1134            checked_files.push(file_name.clone());
1135            continue;
1136        }
1137
1138        let file_progress = verify_batch.as_ref().map(|batch| {
1139            batch.start_transient_file("Verify", file_name, entry.size)
1140        });
1141
1142        let (mismatch_opt, file_size_hashed) = verify_local_file(
1143            item_root,
1144            identifier,
1145            &local_path,
1146            entry,
1147            options,
1148            file_progress.as_ref(),
1149        )?;
1150
1151        if let Some(fp) = file_progress {
1152            fp.finish(file_size_hashed);
1153        }
1154
1155        if let Some(mismatch) = mismatch_opt {
1156            mismatched_files.push(mismatch);
1157        } else {
1158            checked_files.push(file_name.clone());
1159        }
1160    }
1161
1162    if let Some(batch) = verify_batch {
1163        batch.finish();
1164    }
1165
1166    let unexpected_files = if include_unexpected {
1167        let local_files = collect_local_files(item_root)?;
1168        let expected_names: BTreeSet<String> =
1169            manifest.entries.keys().cloned().collect();
1170        local_files
1171            .into_iter()
1172            .filter(|local_name| !expected_names.contains(local_name))
1173            .collect()
1174    } else {
1175        Vec::new()
1176    };
1177
1178    checked_files.sort();
1179    missing_files.sort();
1180    mismatched_files.sort_by(|left, right| left.name.cmp(&right.name));
1181
1182    Ok(VerificationResult {
1183        valid: missing_files.is_empty()
1184            && mismatched_files.is_empty()
1185            && unexpected_files.is_empty(),
1186        identifier: identifier.to_string(),
1187        checked_files,
1188        missing_files,
1189        mismatched_files,
1190        unexpected_files,
1191    })
1192}
1193
1194fn verify_local_file(
1195    item_root: &Path,
1196    identifier: &str,
1197    local_path: &Path,
1198    entry: &ManifestEntry,
1199    options: &VerificationOptions,
1200    file_progress: Option<&FileItemProgress>,
1201) -> Result<(Option<VerificationMismatch>, u64)> {
1202    let actual_size = fs::metadata(local_path)
1203        .with_context(|| {
1204            format!("Failed to read metadata for {}", local_path.display())
1205        })?
1206        .len();
1207    if let Some(fp) = file_progress {
1208        fp.set_total_bytes(actual_size);
1209    }
1210    let relative_name = relative_archive_name(item_root, local_path)?;
1211    let files_xml_name = format!("{identifier}{FILES_XML_SUFFIX}");
1212    let is_files_xml = relative_name == files_xml_name;
1213    if is_files_xml && options.files_xml_live_sha1.is_none() {
1214        return Ok((None, actual_size));
1215    }
1216
1217    let mut mismatch = VerificationMismatch {
1218        name: entry.name.clone(),
1219        expected_sha1: if is_files_xml {
1220            options.files_xml_live_sha1.clone()
1221        } else {
1222            entry.sha1.clone()
1223        },
1224        actual_sha1: None,
1225        expected_md5: if is_files_xml {
1226            None
1227        } else {
1228            entry.md5.clone()
1229        },
1230        actual_md5: None,
1231        expected_size: entry.size,
1232        actual_size: Some(actual_size),
1233    };
1234    let mut has_mismatch = false;
1235
1236    if let Some(expected_size) = entry.size
1237        && expected_size != actual_size
1238    {
1239        has_mismatch = true;
1240    }
1241    match (&mismatch.expected_sha1, &mismatch.expected_md5) {
1242        (Some(expected_sha1), Some(expected_md5)) => {
1243            let (actual_sha1, actual_md5) =
1244                sha1_and_md5_hex_for_file(local_path, file_progress)?;
1245            if &actual_sha1 != expected_sha1 {
1246                mismatch.actual_sha1 = Some(actual_sha1);
1247                has_mismatch = true;
1248            }
1249            if &actual_md5 != expected_md5 {
1250                mismatch.actual_md5 = Some(actual_md5);
1251                has_mismatch = true;
1252            }
1253        }
1254        (Some(expected_sha1), None) => {
1255            let actual_sha1 =
1256                sha1_hex_for_file_with_progress(local_path, file_progress)?;
1257            if &actual_sha1 != expected_sha1 {
1258                mismatch.actual_sha1 = Some(actual_sha1);
1259                has_mismatch = true;
1260            }
1261        }
1262        (None, Some(expected_md5)) => {
1263            let actual_md5 =
1264                md5_hex_for_file_with_progress(local_path, file_progress)?;
1265            if &actual_md5 != expected_md5 {
1266                mismatch.actual_md5 = Some(actual_md5);
1267                has_mismatch = true;
1268            }
1269        }
1270        (None, None) => {}
1271    }
1272
1273    if has_mismatch {
1274        Ok((Some(mismatch), actual_size))
1275    } else {
1276        Ok((None, actual_size))
1277    }
1278}
1279
1280fn collect_local_files(item_root: &Path) -> Result<Vec<String>> {
1281    let mut local_files = Vec::new();
1282    collect_local_files_inner(item_root, item_root, &mut local_files)?;
1283    local_files.sort();
1284    Ok(local_files)
1285}
1286
1287fn collect_local_files_inner(
1288    root: &Path,
1289    current: &Path,
1290    local_files: &mut Vec<String>,
1291) -> Result<()> {
1292    for entry in fs::read_dir(current)
1293        .with_context(|| format!("Failed to list {}", current.display()))?
1294    {
1295        let entry = entry
1296            .with_context(|| format!("Failed to read {}", current.display()))?;
1297        let path = entry.path();
1298        if path.is_dir() {
1299            collect_local_files_inner(root, &path, local_files)?;
1300        } else if path.is_file() {
1301            local_files.push(relative_archive_name(root, &path)?);
1302        }
1303    }
1304    Ok(())
1305}
1306
1307fn relative_archive_name(root: &Path, path: &Path) -> Result<String> {
1308    let relative_path = path.strip_prefix(root).with_context(|| {
1309        format!("{} is not within {}", path.display(), root.display())
1310    })?;
1311    let mut parts = Vec::new();
1312    for component in relative_path.components() {
1313        if let Component::Normal(part) = component {
1314            parts.push(part.to_string_lossy().into_owned());
1315        }
1316    }
1317    Ok(parts.join("/"))
1318}
1319
1320fn load_local_files_manifest(
1321    item_root: &Path,
1322    identifier: &str,
1323) -> Result<FilesManifest> {
1324    let files_xml_path =
1325        item_root.join(format!("{identifier}{FILES_XML_SUFFIX}"));
1326    let bytes = fs::read(&files_xml_path).with_context(|| {
1327        format!("Failed to read {}", files_xml_path.display())
1328    })?;
1329    parse_files_manifest(identifier, &bytes)
1330}
1331
1332const CHUNK_RETRY_BASE_DELAY_MS: u64 = 500;
1333
1334fn fetch_live_files_manifest(identifier: &str) -> Result<FilesManifest> {
1335    let bytes = fetch_live_files_xml_bytes(identifier)?;
1336    parse_files_manifest(identifier, &bytes)
1337}
1338
1339fn fetch_live_files_xml_bytes(identifier: &str) -> Result<Vec<u8>> {
1340    let response = perform_get(&format!(
1341        "https://archive.org/download/{identifier}/{identifier}{FILES_XML_SUFFIX}"
1342    ))?;
1343    response.bytes().context("Failed to read files XML body")
1344}
1345
1346fn fetch_live_meta_xml_bytes(identifier: &str) -> Result<Vec<u8>> {
1347    let response = perform_get(&format!(
1348        "https://archive.org/download/{identifier}/{identifier}{META_XML_SUFFIX}"
1349    ))?;
1350    response.bytes().context("Failed to read meta XML body")
1351}
1352
1353fn fetch_live_metadata(identifier: &str) -> Result<MetadataResponse> {
1354    let response =
1355        perform_get(&format!("https://archive.org/metadata/{identifier}"))?;
1356    let body = response.text().context("Failed to read metadata body")?;
1357    serde_json::from_str(&body)
1358        .context("Failed to parse Internet Archive metadata JSON")
1359}
1360
1361const DOWNLOAD_CHUNK_SIZE: u64 = 8_388_608; // 8 MiB
1362
1363trait RangeHttpResponse: Read {
1364    fn status(&self) -> reqwest::StatusCode;
1365    fn headers(&self) -> &reqwest::header::HeaderMap;
1366    fn content_length(&self) -> Option<u64>;
1367}
1368
1369impl RangeHttpResponse for https::BlockingResponse {
1370    fn status(&self) -> reqwest::StatusCode {
1371        https::BlockingResponse::status(self)
1372    }
1373
1374    fn headers(&self) -> &reqwest::header::HeaderMap {
1375        https::BlockingResponse::headers(self)
1376    }
1377
1378    fn content_length(&self) -> Option<u64> {
1379        https::BlockingResponse::content_length(self)
1380    }
1381}
1382
1383trait RangeHttpClient {
1384    fn get_with_headers(
1385        &self,
1386        url: &str,
1387        headers: Option<reqwest::header::HeaderMap>,
1388    ) -> Result<Box<dyn RangeHttpResponse>>;
1389}
1390
1391struct PooledRangeHttpClient;
1392
1393impl RangeHttpClient for PooledRangeHttpClient {
1394    fn get_with_headers(
1395        &self,
1396        url: &str,
1397        headers: Option<reqwest::header::HeaderMap>,
1398    ) -> Result<Box<dyn RangeHttpResponse>> {
1399        let resp = https::blocking_get_response_with_headers(url, headers)?;
1400        Ok(Box::new(resp))
1401    }
1402}
1403
1404fn parse_content_range(val: &str) -> Option<(u64, u64, Option<u64>)> {
1405    let s = val.trim();
1406    let s = s.strip_prefix("bytes ")?;
1407    let (range_part, total_part) = s.split_once('/')?;
1408    let (start_str, end_str) = range_part.split_once('-')?;
1409    let start: u64 = start_str.trim().parse().ok()?;
1410    let end: u64 = end_str.trim().parse().ok()?;
1411    let total = if total_part.trim() == "*" {
1412        None
1413    } else {
1414        total_part.trim().parse().ok()
1415    };
1416    Some((start, end, total))
1417}
1418
1419fn parse_unsatisfied_content_range_total(val: &str) -> Option<u64> {
1420    let s = val.trim().strip_prefix("bytes ")?;
1421    let (range_part, total_part) = s.split_once('/')?;
1422    if range_part.trim() != "*" {
1423        return None;
1424    }
1425    total_part.trim().parse().ok()
1426}
1427
1428fn part_path_for_destination(destination: &Path) -> PathBuf {
1429    let mut os_str = destination.as_os_str().to_os_string();
1430    os_str.push(PART_FILE_SUFFIX);
1431    PathBuf::from(os_str)
1432}
1433
1434fn create_temp_path(parent_dir: &Path, file_name: &str) -> PathBuf {
1435    static ATOMIC_SEQ: std::sync::atomic::AtomicU64 =
1436        std::sync::atomic::AtomicU64::new(0);
1437    let pid = std::process::id();
1438    let nanos = match std::time::SystemTime::now()
1439        .duration_since(std::time::UNIX_EPOCH)
1440    {
1441        Ok(dur) => dur.subsec_nanos(),
1442        Err(_) => 0,
1443    };
1444    let seq = ATOMIC_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1445    // Reason for fallback: If file_name has no valid leaf or non-utf8 path, use generic prefix for temporary file.
1446    let leaf_name = Path::new(file_name)
1447        .file_name()
1448        .and_then(std::ffi::OsStr::to_str)
1449        .unwrap_or("file");
1450    let temp_name = format!(".{leaf_name}.ia-tmp.{pid}.{nanos}.{seq}");
1451    parent_dir.join(temp_name)
1452}
1453
1454struct TempFileCleanupGuard {
1455    temp_path: PathBuf,
1456    active: bool,
1457}
1458
1459impl Drop for TempFileCleanupGuard {
1460    fn drop(&mut self) {
1461        if self.active {
1462            drop(fs::remove_file(&self.temp_path));
1463        }
1464    }
1465}
1466
1467fn commit_atomic_file(temp_path: &Path, destination: &Path) -> Result<()> {
1468    #[cfg(windows)]
1469    if destination.exists() {
1470        drop(fs::remove_file(destination));
1471    }
1472    fs::rename(temp_path, destination).with_context(|| {
1473        format!(
1474            "Failed to atomically rename {} to {}",
1475            temp_path.display(),
1476            destination.display()
1477        )
1478    })
1479}
1480
1481fn write_atomic_bytes(destination: &Path, bytes: &[u8]) -> Result<()> {
1482    // Reason for fallback: If destination is a bare filename without a parent directory, stage in current directory.
1483    let parent = destination.parent().unwrap_or_else(|| Path::new("."));
1484    fs::create_dir_all(parent).with_context(|| {
1485        format!("Failed to create parent directory {}", parent.display())
1486    })?;
1487    // Reason for fallback: Non-UTF-8 leaf names use a generic prefix for the transient atomic staging file.
1488    let name_str = destination
1489        .file_name()
1490        .and_then(std::ffi::OsStr::to_str)
1491        .unwrap_or("file");
1492    let temp_path = create_temp_path(parent, name_str);
1493    let mut guard = TempFileCleanupGuard {
1494        temp_path: temp_path.clone(),
1495        active: true,
1496    };
1497    fs::write(&temp_path, bytes).with_context(|| {
1498        format!("Failed to write temporary file {}", temp_path.display())
1499    })?;
1500    commit_atomic_file(&temp_path, destination)?;
1501    guard.active = false;
1502    Ok(())
1503}
1504
1505fn fetch_download_bytes(identifier: &str, file_name: &str) -> Result<Vec<u8>> {
1506    let url = download_url(identifier, file_name)?;
1507    let mut buffer = Vec::new();
1508    download_to_writer_chunked_range_with_http(
1509        &PooledRangeHttpClient,
1510        url.as_str(),
1511        &mut buffer,
1512        None,
1513        DOWNLOAD_CHUNK_SIZE,
1514        CHUNK_RETRY_BASE_DELAY_MS,
1515    )?;
1516    Ok(buffer)
1517}
1518
1519fn download_live_file_chunked_range(
1520    identifier: &str,
1521    file_name: &str,
1522    destination: &Path,
1523    expected_size: Option<u64>,
1524    file_progress: Option<&FileItemProgress>,
1525) -> Result<u64> {
1526    let url = download_url(identifier, file_name)?;
1527    download_to_part_file_chunked_range_with_http(
1528        &PooledRangeHttpClient,
1529        url.as_str(),
1530        destination,
1531        expected_size,
1532        file_progress,
1533        DOWNLOAD_CHUNK_SIZE,
1534        CHUNK_RETRY_BASE_DELAY_MS,
1535    )
1536}
1537
1538enum InitialChunkOutcome {
1539    FullStream(Box<dyn RangeHttpResponse>),
1540    EmptyFile,
1541    Partial {
1542        bytes: Vec<u8>,
1543        total_size: Option<u64>,
1544    },
1545}
1546
1547enum ResumeChunkOutcome {
1548    AlreadyComplete(u64),
1549    RestartFromZero,
1550    FullStreamFromZero(Box<dyn RangeHttpResponse>),
1551    Partial {
1552        bytes: Vec<u8>,
1553        total_size: Option<u64>,
1554    },
1555}
1556
1557fn sleep_chunk_retry(attempt: usize, backoff_base_ms: u64) {
1558    if backoff_base_ms == 0 {
1559        return;
1560    }
1561    // Reason for fallback: If attempt count cannot convert to u32, cap exponent to bound exponential backoff.
1562    let exponent = u32::try_from(attempt).unwrap_or(4).min(4);
1563    // Reason for fallback: power computation overflow safely caps multiplier
1564    let multiplier = 2u64.checked_pow(exponent).unwrap_or(16);
1565    let delay_ms = backoff_base_ms.saturating_mul(multiplier);
1566    std::thread::sleep(std::time::Duration::from_millis(delay_ms));
1567}
1568
1569fn read_response_to_vec_with_progress(
1570    response: &mut dyn RangeHttpResponse,
1571    base_offset: u64,
1572    file_progress: Option<&FileItemProgress>,
1573) -> Result<Vec<u8>> {
1574    let mut out = Vec::new();
1575    let mut buf = [0_u8; 64 * 1024];
1576    loop {
1577        let n = response
1578            .read(&mut buf)
1579            .context("Failed to read chunk response body")?;
1580        if n == 0 {
1581            break;
1582        }
1583        let slice = buf.get(..n).context("Buffer slice index out of bounds")?;
1584        out.extend_from_slice(slice);
1585        if let Some(fp) = file_progress
1586            && let Ok(cur_u64) = u64::try_from(out.len())
1587        {
1588            fp.set_bytes_done(base_offset.saturating_add(cur_u64));
1589        }
1590    }
1591    Ok(out)
1592}
1593
1594fn fetch_initial_chunk_with_retry(
1595    http: &dyn RangeHttpClient,
1596    url: &str,
1597    chunk_size: u64,
1598    retry_limit: usize,
1599    backoff_base_ms: u64,
1600    file_progress: Option<&FileItemProgress>,
1601) -> Result<InitialChunkOutcome> {
1602    let first_end = chunk_size.saturating_sub(1);
1603    let range_str = format!("bytes=0-{first_end}");
1604    let mut attempt = 0;
1605
1606    loop {
1607        let mut headers = reqwest::header::HeaderMap::new();
1608        headers.insert(
1609            reqwest::header::RANGE,
1610            reqwest::header::HeaderValue::from_str(&range_str)
1611                .context("Failed to format initial Range header")?,
1612        );
1613
1614        let attempt_res: Result<InitialChunkOutcome> = (|| {
1615            let mut response = http
1616                .get_with_headers(url, Some(headers))
1617                .with_context(|| format!("Failed to connect to {url}"))?;
1618            let status = response.status();
1619            if status == reqwest::StatusCode::OK {
1620                return Ok(InitialChunkOutcome::FullStream(response));
1621            }
1622            if status == reqwest::StatusCode::RANGE_NOT_SATISFIABLE {
1623                let unsatisfied_total = response
1624                    .headers()
1625                    .get(reqwest::header::CONTENT_RANGE)
1626                    .and_then(|v| v.to_str().ok())
1627                    .and_then(parse_unsatisfied_content_range_total);
1628                if unsatisfied_total == Some(0) {
1629                    return Ok(InitialChunkOutcome::EmptyFile);
1630                }
1631                let fallback = http
1632                    .get_with_headers(url, None)
1633                    .with_context(|| format!("Failed to GET {url}"))?;
1634                if fallback.status() == reqwest::StatusCode::OK {
1635                    return Ok(InitialChunkOutcome::FullStream(fallback));
1636                }
1637                bail!(
1638                    "Unexpected HTTP response status {} after 416 fallback for {url}",
1639                    fallback.status()
1640                );
1641            }
1642            if status != reqwest::StatusCode::PARTIAL_CONTENT {
1643                bail!("Unexpected HTTP response status {status} for {url}");
1644            }
1645
1646            let parsed_range = response
1647                .headers()
1648                .get(reqwest::header::CONTENT_RANGE)
1649                .and_then(|v| v.to_str().ok())
1650                .and_then(parse_content_range);
1651            if let Some((range_start, _, _)) = parsed_range {
1652                anyhow::ensure!(
1653                    range_start == 0,
1654                    "Unexpected Content-Range start {range_start} for initial chunk of {url}"
1655                );
1656            }
1657            let mut total_size = parsed_range.and_then(|(_, _, total)| total);
1658            if total_size.is_none()
1659                && let Some(content_len) = response.content_length()
1660                && content_len < chunk_size
1661            {
1662                total_size = Some(content_len);
1663            }
1664            if let (Some(fp), Some(total)) = (file_progress, total_size) {
1665                fp.set_total_bytes(total);
1666            }
1667
1668            let chunk_buf = read_response_to_vec_with_progress(
1669                response.as_mut(),
1670                0,
1671                file_progress,
1672            )
1673            .context("Failed to read first chunk body")?;
1674            if chunk_buf.is_empty() && total_size != Some(0) {
1675                bail!(
1676                    "Received empty body for initial byte range 0-{first_end}"
1677                );
1678            }
1679            Ok(InitialChunkOutcome::Partial {
1680                bytes: chunk_buf,
1681                total_size,
1682            })
1683        })();
1684
1685        match attempt_res {
1686            Ok(outcome) => return Ok(outcome),
1687            Err(err) => {
1688                if attempt < retry_limit {
1689                    attempt = attempt.saturating_add(1);
1690                    warn_fmt!(
1691                        "Retrying initial chunk 0-{first_end} for {url} (attempt {attempt}/{retry_limit}): {err}"
1692                    );
1693                    sleep_chunk_retry(attempt, backoff_base_ms);
1694                    continue;
1695                }
1696                return Err(err);
1697            }
1698        }
1699    }
1700}
1701
1702fn stream_full_response_to_writer(
1703    mut response: Box<dyn RangeHttpResponse>,
1704    url: &str,
1705    writer: &mut dyn Write,
1706    file_progress: Option<&FileItemProgress>,
1707) -> Result<u64> {
1708    let expected_len = response.content_length();
1709    if let (Some(fp), Some(expected)) = (file_progress, expected_len) {
1710        fp.set_total_bytes(expected);
1711    }
1712    let mut total_copied = 0_u64;
1713    let mut buf = [0_u8; 64 * 1024];
1714    loop {
1715        let n = response
1716            .read(&mut buf)
1717            .context("Failed to read HTTP response body")?;
1718        if n == 0 {
1719            break;
1720        }
1721        let n_u64 = u64::try_from(n).map_err(|e| {
1722            anyhow!("Failed to convert read buffer length: {e}")
1723        })?;
1724        let slice = buf.get(..n).context("Buffer slice index out of bounds")?;
1725        writer
1726            .write_all(slice)
1727            .context("Failed to write downloaded bytes to stream")?;
1728        total_copied = total_copied.saturating_add(n_u64);
1729        if let Some(fp) = file_progress {
1730            fp.set_bytes_done(total_copied);
1731        }
1732    }
1733    if let Some(expected) = expected_len {
1734        anyhow::ensure!(
1735            total_copied == expected,
1736            "Incomplete download for {url}: received {total_copied} of {expected} bytes"
1737        );
1738    }
1739    Ok(total_copied)
1740}
1741
1742#[expect(
1743    clippy::too_many_arguments,
1744    reason = "Internal HTTP range resumption helper with explicit retry and progress parameters"
1745)]
1746fn fetch_resume_chunk_with_retry(
1747    http: &dyn RangeHttpClient,
1748    url: &str,
1749    resume_offset: u64,
1750    resume_end: u64,
1751    expected_size: Option<u64>,
1752    retry_limit: usize,
1753    backoff_base_ms: u64,
1754    file_progress: Option<&FileItemProgress>,
1755) -> Result<ResumeChunkOutcome> {
1756    let range_str = format!("bytes={resume_offset}-{resume_end}");
1757    let mut attempt = 0;
1758
1759    loop {
1760        let mut headers = reqwest::header::HeaderMap::new();
1761        headers.insert(
1762            reqwest::header::RANGE,
1763            reqwest::header::HeaderValue::from_str(&range_str)
1764                .context("Failed to format resume Range header")?,
1765        );
1766
1767        let attempt_res: Result<ResumeChunkOutcome> = (|| {
1768            let mut response = http
1769                .get_with_headers(url, Some(headers))
1770                .with_context(|| format!("Failed to connect to {url}"))?;
1771            let status = response.status();
1772            if status == reqwest::StatusCode::OK {
1773                return Ok(ResumeChunkOutcome::FullStreamFromZero(response));
1774            }
1775            if status == reqwest::StatusCode::RANGE_NOT_SATISFIABLE {
1776                let unsatisfied_total = response
1777                    .headers()
1778                    .get(reqwest::header::CONTENT_RANGE)
1779                    .and_then(|v| v.to_str().ok())
1780                    .and_then(parse_unsatisfied_content_range_total);
1781                if unsatisfied_total == Some(resume_offset) {
1782                    return Ok(ResumeChunkOutcome::AlreadyComplete(
1783                        resume_offset,
1784                    ));
1785                }
1786                return Ok(ResumeChunkOutcome::RestartFromZero);
1787            }
1788            if status != reqwest::StatusCode::PARTIAL_CONTENT {
1789                bail!(
1790                    "Unexpected HTTP response status {status} while resuming {url}"
1791                );
1792            }
1793
1794            let parsed_range = response
1795                .headers()
1796                .get(reqwest::header::CONTENT_RANGE)
1797                .and_then(|v| v.to_str().ok())
1798                .and_then(parse_content_range);
1799            if let Some((range_start, _, _)) = parsed_range {
1800                anyhow::ensure!(
1801                    range_start == resume_offset,
1802                    "Unexpected Content-Range start {range_start} (expected {resume_offset}) while resuming {url}"
1803                );
1804            }
1805            let total_size = parsed_range
1806                .and_then(|(_, _, total)| total)
1807                .or(expected_size);
1808            if let Some(total) = total_size
1809                && resume_offset > total
1810            {
1811                return Ok(ResumeChunkOutcome::RestartFromZero);
1812            }
1813            if let (Some(fp), Some(total)) = (file_progress, total_size) {
1814                fp.set_total_bytes(total);
1815            }
1816
1817            let chunk_buf = read_response_to_vec_with_progress(
1818                response.as_mut(),
1819                resume_offset,
1820                file_progress,
1821            )
1822            .context("Failed to read resumed chunk body")?;
1823            if chunk_buf.is_empty() && total_size != Some(resume_offset) {
1824                bail!(
1825                    "Received empty body for resumed byte range {resume_offset}-{resume_end}"
1826                );
1827            }
1828            Ok(ResumeChunkOutcome::Partial {
1829                bytes: chunk_buf,
1830                total_size,
1831            })
1832        })();
1833
1834        match attempt_res {
1835            Ok(outcome) => return Ok(outcome),
1836            Err(err) => {
1837                if attempt < retry_limit {
1838                    attempt = attempt.saturating_add(1);
1839                    warn_fmt!(
1840                        "Retrying resumed chunk {resume_offset}-{resume_end} for {url} (attempt {attempt}/{retry_limit}): {err}"
1841                    );
1842                    sleep_chunk_retry(attempt, backoff_base_ms);
1843                    continue;
1844                }
1845                return Err(err);
1846            }
1847        }
1848    }
1849}
1850
1851#[expect(
1852    clippy::too_many_arguments,
1853    reason = "Shared chunked HTTP Range download loop across file and stream writers"
1854)]
1855fn continue_chunked_range_loop(
1856    http: &dyn RangeHttpClient,
1857    url: &str,
1858    writer: &mut dyn Write,
1859    initial_offset: u64,
1860    initial_chunk_len: u64,
1861    total_size: Option<u64>,
1862    chunk_size: u64,
1863    retry_limit: usize,
1864    backoff_base_ms: u64,
1865    file_progress: Option<&FileItemProgress>,
1866) -> Result<u64> {
1867    let mut current_offset = initial_offset;
1868    if let Some(fp) = file_progress {
1869        fp.set_bytes_done(current_offset);
1870    }
1871
1872    if let Some(total) = total_size {
1873        if current_offset >= total {
1874            anyhow::ensure!(
1875                current_offset == total,
1876                "Received {current_offset} bytes exceeding expected size {total} for {url}"
1877            );
1878            return Ok(current_offset);
1879        }
1880    } else if initial_chunk_len < chunk_size {
1881        if let Some(fp) = file_progress {
1882            fp.set_total_bytes(current_offset);
1883        }
1884        return Ok(current_offset);
1885    }
1886
1887    loop {
1888        if let Some(total) = total_size
1889            && current_offset >= total
1890        {
1891            break;
1892        }
1893
1894        let next_end = if let Some(total) = total_size {
1895            std::cmp::min(
1896                current_offset.saturating_add(chunk_size).saturating_sub(1),
1897                total.saturating_sub(1),
1898            )
1899        } else {
1900            current_offset.saturating_add(chunk_size).saturating_sub(1)
1901        };
1902
1903        if next_end < current_offset {
1904            break;
1905        }
1906
1907        let chunk_bytes_opt = fetch_chunk_with_retry(
1908            http,
1909            url,
1910            current_offset,
1911            next_end,
1912            total_size,
1913            retry_limit,
1914            backoff_base_ms,
1915            file_progress,
1916        )?;
1917
1918        let Some(chunk_bytes) = chunk_bytes_opt else {
1919            break;
1920        };
1921
1922        let chunk_len = u64::try_from(chunk_bytes.len()).map_err(|e| {
1923            anyhow!("Failed to convert chunk bytes length to u64: {e}")
1924        })?;
1925
1926        writer
1927            .write_all(&chunk_bytes)
1928            .context("Failed to write chunk bytes to destination")?;
1929        writer
1930            .flush()
1931            .context("Failed to flush chunk bytes to destination")?;
1932
1933        current_offset = current_offset.saturating_add(chunk_len);
1934        if let Some(fp) = file_progress {
1935            fp.set_bytes_done(current_offset);
1936        }
1937
1938        if chunk_len < chunk_size && total_size.is_none() {
1939            break;
1940        }
1941    }
1942
1943    if let Some(total) = total_size {
1944        anyhow::ensure!(
1945            current_offset == total,
1946            "Incomplete download for {url}: received {current_offset} of {total} bytes"
1947        );
1948    } else if let Some(fp) = file_progress {
1949        fp.set_total_bytes(current_offset);
1950    }
1951
1952    Ok(current_offset)
1953}
1954
1955fn download_to_writer_chunked_range_with_http(
1956    http: &dyn RangeHttpClient,
1957    url: &str,
1958    writer: &mut dyn Write,
1959    file_progress: Option<&FileItemProgress>,
1960    chunk_size: u64,
1961    backoff_base_ms: u64,
1962) -> Result<u64> {
1963    anyhow::ensure!(chunk_size > 0, "Download chunk size must be non-zero");
1964    let retry_limit = invocation_settings::get_settings()
1965        .retry_on_host_error
1966        .max(3);
1967
1968    let (first_chunk, total_size) = match fetch_initial_chunk_with_retry(
1969        http,
1970        url,
1971        chunk_size,
1972        retry_limit,
1973        backoff_base_ms,
1974        file_progress,
1975    )? {
1976        InitialChunkOutcome::EmptyFile => {
1977            if let Some(fp) = file_progress {
1978                fp.set_total_bytes(0);
1979                fp.set_bytes_done(0);
1980            }
1981            return Ok(0);
1982        }
1983        InitialChunkOutcome::FullStream(response) => {
1984            return stream_full_response_to_writer(
1985                response,
1986                url,
1987                writer,
1988                file_progress,
1989            );
1990        }
1991        InitialChunkOutcome::Partial { bytes, total_size } => {
1992            (bytes, total_size)
1993        }
1994    };
1995
1996    let first_chunk_len = u64::try_from(first_chunk.len())
1997        .map_err(|e| anyhow!("Failed to convert chunk size to u64: {e}"))?;
1998    writer
1999        .write_all(&first_chunk)
2000        .context("Failed to write first chunk to destination")?;
2001    writer
2002        .flush()
2003        .context("Failed to flush first chunk to destination")?;
2004
2005    continue_chunked_range_loop(
2006        http,
2007        url,
2008        writer,
2009        first_chunk_len,
2010        first_chunk_len,
2011        total_size,
2012        chunk_size,
2013        retry_limit,
2014        backoff_base_ms,
2015        file_progress,
2016    )
2017}
2018
2019fn finalize_part_file(
2020    mut part_file: File,
2021    part_path: &Path,
2022    destination: &Path,
2023    total_bytes: u64,
2024) -> Result<u64> {
2025    part_file.sync_all().with_context(|| {
2026        format!(
2027            "Failed to sync partial download file {}",
2028            part_path.display()
2029        )
2030    })?;
2031    drop(part_file);
2032    commit_atomic_file(part_path, destination)?;
2033    Ok(total_bytes)
2034}
2035
2036fn reset_part_file_to_zero(
2037    part_file: &mut File,
2038    part_path: &Path,
2039) -> Result<()> {
2040    part_file.set_len(0).with_context(|| {
2041        format!("Failed to truncate {}", part_path.display())
2042    })?;
2043    let _ = part_file.seek(SeekFrom::Start(0)).with_context(|| {
2044        format!("Failed to seek to start of {}", part_path.display())
2045    })?;
2046    Ok(())
2047}
2048
2049#[expect(
2050    clippy::too_many_arguments,
2051    reason = "Internal .part resumption helper taking explicit file handle, destination paths, and range parameters"
2052)]
2053fn resume_existing_part_file(
2054    http: &dyn RangeHttpClient,
2055    url: &str,
2056    mut part_file: File,
2057    part_path: &Path,
2058    destination: &Path,
2059    existing_len: u64,
2060    expected_size: Option<u64>,
2061    file_progress: Option<&FileItemProgress>,
2062    chunk_size: u64,
2063    retry_limit: usize,
2064    backoff_base_ms: u64,
2065) -> Result<u64> {
2066    part_file.seek(SeekFrom::End(0)).with_context(|| {
2067        format!("Failed to seek to end of {}", part_path.display())
2068    })?;
2069    if let Some(fp) = file_progress {
2070        if let Some(expected) = expected_size {
2071            fp.set_total_bytes(expected);
2072        }
2073        fp.set_bytes_done(existing_len);
2074    }
2075    let resume_end = if let Some(expected) = expected_size {
2076        std::cmp::min(
2077            existing_len.saturating_add(chunk_size).saturating_sub(1),
2078            expected.saturating_sub(1),
2079        )
2080    } else {
2081        existing_len.saturating_add(chunk_size).saturating_sub(1)
2082    };
2083    match fetch_resume_chunk_with_retry(
2084        http,
2085        url,
2086        existing_len,
2087        resume_end,
2088        expected_size,
2089        retry_limit,
2090        backoff_base_ms,
2091        file_progress,
2092    )? {
2093        ResumeChunkOutcome::AlreadyComplete(total) => {
2094            if let Some(fp) = file_progress {
2095                fp.set_total_bytes(total);
2096                fp.set_bytes_done(total);
2097            }
2098            finalize_part_file(part_file, part_path, destination, total)
2099        }
2100        ResumeChunkOutcome::FullStreamFromZero(response) => {
2101            reset_part_file_to_zero(&mut part_file, part_path)?;
2102            let written = stream_full_response_to_writer(
2103                response,
2104                url,
2105                &mut part_file,
2106                file_progress,
2107            )?;
2108            finalize_part_file(part_file, part_path, destination, written)
2109        }
2110        ResumeChunkOutcome::RestartFromZero => {
2111            reset_part_file_to_zero(&mut part_file, part_path)?;
2112            let written = download_to_writer_chunked_range_with_http(
2113                http,
2114                url,
2115                &mut part_file,
2116                file_progress,
2117                chunk_size,
2118                backoff_base_ms,
2119            )?;
2120            finalize_part_file(part_file, part_path, destination, written)
2121        }
2122        ResumeChunkOutcome::Partial { bytes, total_size } => {
2123            let chunk_len = u64::try_from(bytes.len()).map_err(|e| {
2124                anyhow!("Failed to convert chunk size to u64: {e}")
2125            })?;
2126            part_file.write_all(&bytes).with_context(|| {
2127                format!("Failed to append to {}", part_path.display())
2128            })?;
2129            part_file.flush().with_context(|| {
2130                format!("Failed to flush {}", part_path.display())
2131            })?;
2132            let new_offset = existing_len.saturating_add(chunk_len);
2133            let total_written = continue_chunked_range_loop(
2134                http,
2135                url,
2136                &mut part_file,
2137                new_offset,
2138                chunk_len,
2139                total_size,
2140                chunk_size,
2141                retry_limit,
2142                backoff_base_ms,
2143                file_progress,
2144            )?;
2145            finalize_part_file(part_file, part_path, destination, total_written)
2146        }
2147    }
2148}
2149
2150fn download_to_part_file_chunked_range_with_http(
2151    http: &dyn RangeHttpClient,
2152    url: &str,
2153    destination: &Path,
2154    expected_size: Option<u64>,
2155    file_progress: Option<&FileItemProgress>,
2156    chunk_size: u64,
2157    backoff_base_ms: u64,
2158) -> Result<u64> {
2159    anyhow::ensure!(chunk_size > 0, "Download chunk size must be non-zero");
2160    // Reason for fallback: If destination is a relative file path without an explicit parent directory, use current directory.
2161    let parent = destination.parent().unwrap_or_else(|| Path::new("."));
2162    fs::create_dir_all(parent).with_context(|| {
2163        format!("Failed to create parent directory {}", parent.display())
2164    })?;
2165
2166    let part_path = part_path_for_destination(destination);
2167    let mut part_file = OpenOptions::new()
2168        .create(true)
2169        .read(true)
2170        .write(true)
2171        .open(&part_path)
2172        .with_context(|| {
2173            format!(
2174                "Failed to open partial download file {}",
2175                part_path.display()
2176            )
2177        })?;
2178    let mut existing_len = part_file
2179        .metadata()
2180        .with_context(|| {
2181            format!("Failed to read metadata for {}", part_path.display())
2182        })?
2183        .len();
2184
2185    if let Some(expected) = expected_size {
2186        if existing_len > expected {
2187            reset_part_file_to_zero(&mut part_file, &part_path)?;
2188            existing_len = 0;
2189        } else if existing_len == expected && expected > 0 {
2190            if let Some(fp) = file_progress {
2191                fp.set_total_bytes(expected);
2192                fp.set_bytes_done(expected);
2193            }
2194            return finalize_part_file(
2195                part_file,
2196                &part_path,
2197                destination,
2198                expected,
2199            );
2200        }
2201    }
2202
2203    let retry_limit = invocation_settings::get_settings()
2204        .retry_on_host_error
2205        .max(3);
2206
2207    if existing_len > 0 {
2208        return resume_existing_part_file(
2209            http,
2210            url,
2211            part_file,
2212            &part_path,
2213            destination,
2214            existing_len,
2215            expected_size,
2216            file_progress,
2217            chunk_size,
2218            retry_limit,
2219            backoff_base_ms,
2220        );
2221    }
2222
2223    let total_written = download_to_writer_chunked_range_with_http(
2224        http,
2225        url,
2226        &mut part_file,
2227        file_progress,
2228        chunk_size,
2229        backoff_base_ms,
2230    )?;
2231    finalize_part_file(part_file, &part_path, destination, total_written)
2232}
2233
2234fn fetch_chunk_with_retry(
2235    http: &dyn RangeHttpClient,
2236    url: &str,
2237    start: u64,
2238    end: u64,
2239    expected_total: Option<u64>,
2240    retry_limit: usize,
2241    backoff_base_ms: u64,
2242    file_progress: Option<&FileItemProgress>,
2243) -> Result<Option<Vec<u8>>> {
2244    let range_val = format!("bytes={start}-{end}");
2245    let mut attempt = 0;
2246    loop {
2247        let mut chunk_headers = reqwest::header::HeaderMap::new();
2248        chunk_headers.insert(
2249            reqwest::header::RANGE,
2250            reqwest::header::HeaderValue::from_str(&range_val)
2251                .context("Invalid Range header value")?,
2252        );
2253
2254        let chunk_read_res: Result<Option<Vec<u8>>> = (|| {
2255            let mut chunk_resp =
2256                http.get_with_headers(url, Some(chunk_headers))?;
2257            let status = chunk_resp.status();
2258            if status == reqwest::StatusCode::RANGE_NOT_SATISFIABLE {
2259                if expected_total.is_none() {
2260                    return Ok(None);
2261                }
2262                bail!(
2263                    "Unexpected HTTP 416 Range Not Satisfiable for chunk {start}-{end}"
2264                );
2265            }
2266            if status != reqwest::StatusCode::PARTIAL_CONTENT {
2267                bail!(
2268                    "Unexpected HTTP status {status} for chunk {start}-{end}"
2269                );
2270            }
2271
2272            if let Some((range_start, _, range_total)) = chunk_resp
2273                .headers()
2274                .get(reqwest::header::CONTENT_RANGE)
2275                .and_then(|v| v.to_str().ok())
2276                .and_then(parse_content_range)
2277            {
2278                anyhow::ensure!(
2279                    range_start == start,
2280                    "Unexpected Content-Range start {range_start} (expected {start}) for {url}"
2281                );
2282                if let (Some(expected), Some(actual)) =
2283                    (expected_total, range_total)
2284                {
2285                    anyhow::ensure!(
2286                        actual == expected,
2287                        "Remote file size changed during download of {url}: expected {expected}, got {actual}"
2288                    );
2289                }
2290            }
2291
2292            let buf = read_response_to_vec_with_progress(
2293                chunk_resp.as_mut(),
2294                start,
2295                file_progress,
2296            )
2297            .context("Failed to read chunk response body")?;
2298            if buf.is_empty() {
2299                bail!("Received empty body for chunk {start}-{end}");
2300            }
2301            Ok(Some(buf))
2302        })();
2303
2304        match chunk_read_res {
2305            Ok(data) => return Ok(data),
2306            Err(err) => {
2307                if attempt < retry_limit {
2308                    attempt = attempt.saturating_add(1);
2309                    warn_fmt!(
2310                        "Retrying chunk {start}-{end} for {url} (attempt {attempt}/{retry_limit}): {err}"
2311                    );
2312                    sleep_chunk_retry(attempt, backoff_base_ms);
2313                    continue;
2314                }
2315                return Err(err.context(format!(
2316                    "Failed to download chunk {start}-{end} from {url}"
2317                )));
2318            }
2319        }
2320    }
2321}
2322
2323fn perform_get(url: &str) -> Result<https::BlockingResponse> {
2324    let response = https::blocking_get_response_with_backoff(url, 3)
2325        .with_context(|| format!("Failed to GET {url}"))?;
2326    if !response.is_success() {
2327        bail!(
2328            "Unexpected response status {} for {url}",
2329            response.status_code()
2330        );
2331    }
2332    Ok(response)
2333}
2334
2335fn contains_with_client(
2336    client: &dyn ArchiveClient,
2337    target: &str,
2338    desired_file: &str,
2339) -> Result<Vec<u8>> {
2340    let archive_target = parse_archive_target(target)?;
2341    let metadata = client.fetch_metadata(&archive_target.identifier)?;
2342    let result = metadata.files.iter().any(|file| file.name == desired_file);
2343    let mut output = if result {
2344        b"true".to_vec()
2345    } else {
2346        b"false".to_vec()
2347    };
2348    output.push(b'\n');
2349    Ok(output)
2350}
2351
2352fn listplain_with_client(
2353    client: &dyn ArchiveClient,
2354    target: &str,
2355) -> Result<Vec<u8>> {
2356    let archive_target = parse_archive_target(target)?;
2357    let metadata = client.fetch_metadata(&archive_target.identifier)?;
2358    let mut names: Vec<String> =
2359        metadata.files.into_iter().map(|file| file.name).collect();
2360    names.sort();
2361    let mut output = names.join("\n").into_bytes();
2362    if !output.is_empty() {
2363        output.push(b'\n');
2364    }
2365    Ok(output)
2366}
2367
2368fn metadata_with_client(
2369    client: &dyn ArchiveClient,
2370    target: &str,
2371) -> Result<Vec<u8>> {
2372    let archive_target = parse_archive_target(target)?;
2373    let metadata = client.fetch_metadata(&archive_target.identifier)?;
2374    pretty_json_bytes(&metadata)
2375}
2376
2377fn filesxml_with_client(
2378    client: &dyn ArchiveClient,
2379    target: &str,
2380) -> Result<Vec<u8>> {
2381    let archive_target = parse_archive_target(target)?;
2382    client.fetch_files_xml_bytes(&archive_target.identifier)
2383}
2384
2385fn metaxml_with_client(
2386    client: &dyn ArchiveClient,
2387    target: &str,
2388) -> Result<Vec<u8>> {
2389    let archive_target = parse_archive_target(target)?;
2390    client.fetch_meta_xml_bytes(&archive_target.identifier)
2391}
2392
2393fn download_url(identifier: &str, file_name: &str) -> Result<reqwest::Url> {
2394    let mut url = reqwest::Url::parse("https://archive.org/download/")
2395        .context("Failed to construct download URL")?;
2396    {
2397        let mut segments = url
2398            .path_segments_mut()
2399            .map_err(|()| anyhow!("Failed to modify download URL segments"))?;
2400        segments.push(identifier);
2401        for segment in file_name.split('/') {
2402            segments.push(segment);
2403        }
2404    }
2405    Ok(url)
2406}
2407
2408fn parse_files_manifest(
2409    identifier: &str,
2410    bytes: &[u8],
2411) -> Result<FilesManifest> {
2412    let cursor = std::io::Cursor::new(bytes);
2413    let parser = EventReader::new(BufReader::new(cursor));
2414    let mut entries = BTreeMap::new();
2415    let mut current_entry: Option<ManifestEntry> = None;
2416    let mut current_tag: Option<String> = None;
2417    let mut current_text = String::new();
2418
2419    for event in parser {
2420        match event.context("Failed to parse files XML")? {
2421            XmlEvent::StartElement {
2422                name, attributes, ..
2423            } => {
2424                if name.local_name == "file" {
2425                    let file_name = attributes
2426                        .iter()
2427                        .find(|attribute| attribute.name.local_name == "name")
2428                        .map(|attribute| attribute.value.clone())
2429                        .ok_or_else(|| {
2430                            anyhow!(
2431                                "Encountered <file> without a name attribute"
2432                            )
2433                        })?;
2434                    let source = attributes
2435                        .iter()
2436                        .find(|attribute| attribute.name.local_name == "source")
2437                        .map(|attribute| attribute.value.clone());
2438                    current_entry = Some(ManifestEntry {
2439                        name: file_name,
2440                        source,
2441                        md5: None,
2442                        sha1: None,
2443                        size: None,
2444                    });
2445                    current_tag = None;
2446                    current_text.clear();
2447                } else if current_entry.is_some() {
2448                    current_tag = Some(name.local_name);
2449                    current_text.clear();
2450                }
2451            }
2452            XmlEvent::Characters(text) | XmlEvent::CData(text) => {
2453                if current_entry.is_some() && current_tag.is_some() {
2454                    current_text.push_str(&text);
2455                }
2456            }
2457            XmlEvent::EndElement { name } => {
2458                if name.local_name == "file" {
2459                    if let Some(entry) = current_entry.take() {
2460                        entries.insert(entry.name.clone(), entry);
2461                    }
2462                    current_tag = None;
2463                    current_text.clear();
2464                    continue;
2465                }
2466
2467                if let Some(entry) = current_entry.as_mut() {
2468                    if let Some(tag) = &current_tag {
2469                        let value = current_text.trim();
2470                        match tag.as_str() {
2471                            "md5" if !value.is_empty() => {
2472                                entry.md5 = Some(value.to_string());
2473                            }
2474                            "sha1" if !value.is_empty() => {
2475                                entry.sha1 = Some(value.to_string());
2476                            }
2477                            "size" if !value.is_empty() => {
2478                                entry.size = value.parse::<u64>().ok();
2479                            }
2480                            _ => {}
2481                        }
2482                    }
2483                }
2484
2485                current_tag = None;
2486                current_text.clear();
2487            }
2488            XmlEvent::EndDocument => break,
2489            _ => {}
2490        }
2491    }
2492
2493    Ok(FilesManifest {
2494        identifier: identifier.to_string(),
2495        entries,
2496    })
2497}
2498
2499fn is_archive_org_host(host: &str) -> bool {
2500    // Reason for fallback: if host has no colon separator, use host as-is.
2501    let host_no_port = host.split(':').next().unwrap_or(host);
2502    // Reason for fallback: if host has no trailing dot, use host_no_port as-is.
2503    let host_clean = host_no_port.strip_suffix('.').unwrap_or(host_no_port);
2504    host_clean.eq_ignore_ascii_case("archive.org")
2505        || host_clean.to_ascii_lowercase().ends_with(".archive.org")
2506}
2507
2508fn is_wayback_host(host: &str) -> bool {
2509    // Reason for fallback: if host has no colon separator, use host as-is.
2510    let host_no_port = host.split(':').next().unwrap_or(host);
2511    // Reason for fallback: if host has no trailing dot, use host_no_port as-is.
2512    let host_clean = host_no_port.strip_suffix('.').unwrap_or(host_no_port);
2513    host_clean.eq_ignore_ascii_case("web.archive.org")
2514}
2515
2516fn parse_archive_target(target: &str) -> Result<ArchiveTarget> {
2517    let trimmed = target.trim();
2518    if trimmed.is_empty() {
2519        bail!("An Internet Archive identifier is required");
2520    }
2521
2522    let url_candidate =
2523        if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
2524            Some(trimmed.to_string())
2525        } else if let Some((host_candidate, _)) = trimmed.split_once('/') {
2526            if is_archive_org_host(host_candidate) {
2527                Some(format!("https://{trimmed}"))
2528            } else {
2529                None
2530            }
2531        } else {
2532            None
2533        };
2534
2535    if is_archive_org_host(trimmed) {
2536        bail!("An Internet Archive identifier is required");
2537    }
2538
2539    if let Some(url_str) = url_candidate {
2540        let url = reqwest::Url::parse(&url_str)
2541            .map_err(|e| anyhow!("Failed to parse URL '{url_str}': {e}"))?;
2542        let Some(host) = url.host_str() else {
2543            bail!("URL has no host: {url_str}");
2544        };
2545        if is_wayback_host(host) {
2546            bail!(
2547                "Wayback Machine URLs (web.archive.org) are not supported as item targets"
2548            );
2549        }
2550        if !is_archive_org_host(host) {
2551            bail!("'{host}' is not an Internet Archive host");
2552        }
2553
2554        let segments: Vec<&str> = url
2555            .path_segments()
2556            // Reason for fallback: URL without a path produces empty segments; empty list safely avoids panic.
2557            .map(|segs| segs.filter(|segment| !segment.is_empty()).collect())
2558            .unwrap_or_default();
2559
2560        let keyword_pos = segments.iter().position(|segment| {
2561            matches!(
2562                *segment,
2563                "details"
2564                    | "download"
2565                    | "metadata"
2566                    | "stream"
2567                    | "embed"
2568                    | "items"
2569            )
2570        });
2571
2572        let (ident_segment, path_slice) = if let Some(idx) = keyword_pos {
2573            let Some(ident_raw) = segments.get(idx.saturating_add(1)) else {
2574                bail!("An Internet Archive identifier is required");
2575            };
2576            let path_slice = match segments.get(idx.saturating_add(2)..) {
2577                Some(slice) => slice,
2578                None => &[],
2579            };
2580            (*ident_raw, path_slice)
2581        } else {
2582            let Some(first) = segments.first() else {
2583                bail!("An Internet Archive identifier is required");
2584            };
2585            let path_slice = match segments.get(1..) {
2586                Some(slice) => slice,
2587                None => &[],
2588            };
2589            (*first, path_slice)
2590        };
2591
2592        let ident = percent_encoding::percent_decode_str(ident_segment)
2593            .decode_utf8()
2594            .context("Invalid UTF-8 in identifier")?;
2595        if !is_probable_identifier(&ident) {
2596            bail!("{ident} is not a plausible Internet Archive identifier");
2597        }
2598
2599        let archive_path = if path_slice.is_empty() {
2600            None
2601        } else {
2602            let mut parts = Vec::new();
2603            for part in path_slice {
2604                let decoded = percent_encoding::percent_decode_str(part)
2605                    .decode_utf8()
2606                    .context("Invalid UTF-8 in archive path")?;
2607                parts.push(decoded.into_owned());
2608            }
2609            let path_str = parts.join("/");
2610            if path_str.is_empty() {
2611                None
2612            } else {
2613                Some(path_str)
2614            }
2615        };
2616
2617        return Ok(ArchiveTarget {
2618            identifier: ident.into_owned(),
2619            archive_path,
2620        });
2621    }
2622
2623    parse_archive_target_path(trimmed)
2624}
2625
2626fn parse_archive_target_path(target: &str) -> Result<ArchiveTarget> {
2627    let trimmed = target.trim_matches('/');
2628    if trimmed.is_empty() {
2629        bail!("An Internet Archive identifier is required");
2630    }
2631    let mut parts = trimmed.splitn(2, '/');
2632    // Reason for fallback: non-empty check on line 1069 guarantees splitn iterator yields at least one item; empty string fallback safely avoids panic.
2633    let identifier = parts.next().unwrap_or_default();
2634    if !is_probable_identifier(identifier) {
2635        bail!("{identifier} is not a plausible Internet Archive identifier");
2636    }
2637    let archive_path = parts
2638        .next()
2639        .filter(|path| !path.is_empty())
2640        .map(std::string::ToString::to_string);
2641    Ok(ArchiveTarget {
2642        identifier: identifier.to_string(),
2643        archive_path,
2644    })
2645}
2646
2647fn identifier_from_metadata_name(name: &str) -> Option<String> {
2648    for suffix in KNOWN_IDENTIFIER_SUFFIXES {
2649        if let Some(identifier) = name.strip_suffix(suffix)
2650            && is_probable_identifier(identifier)
2651        {
2652            return Some(identifier.to_string());
2653        }
2654    }
2655    None
2656}
2657
2658fn is_probable_identifier(candidate: &str) -> bool {
2659    !candidate.is_empty()
2660        && candidate.chars().all(|character| {
2661            character.is_ascii_alphanumeric()
2662                || matches!(character, '-' | '_' | '.')
2663        })
2664}
2665
2666const FILE_HASH_BUFFER_SIZE: usize = 65536;
2667
2668fn sha1_and_md5_hex_for_file(
2669    path: &Path,
2670    file_progress: Option<&FileItemProgress>,
2671) -> Result<(String, String)> {
2672    let mut file = File::open(path)
2673        .with_context(|| format!("Failed to open {}", path.display()))?;
2674    let mut sha1_hasher = Sha1::new();
2675    let mut md5_hasher = Md5::new();
2676    let mut buffer = [0_u8; FILE_HASH_BUFFER_SIZE];
2677    let mut total_read = 0_u64;
2678    loop {
2679        let bytes_read = file
2680            .read(&mut buffer)
2681            .with_context(|| format!("Failed to read {}", path.display()))?;
2682        if bytes_read == 0 {
2683            break;
2684        }
2685        let slice = buffer
2686            .get(..bytes_read)
2687            .context("Invalid bytes read length")?;
2688        sha1_hasher.update(slice);
2689        md5_hasher.update(slice);
2690        if let Ok(n_u64) = u64::try_from(bytes_read) {
2691            total_read = total_read.saturating_add(n_u64);
2692            if let Some(fp) = file_progress {
2693                fp.set_bytes_done(total_read);
2694            }
2695        }
2696    }
2697    Ok((
2698        format!("{:x}", sha1_hasher.finalize()),
2699        format!("{:x}", md5_hasher.finalize()),
2700    ))
2701}
2702
2703fn sha1_hex_for_file(path: &Path) -> Result<String> {
2704    sha1_hex_for_file_with_progress(path, None)
2705}
2706
2707fn sha1_hex_for_file_with_progress(
2708    path: &Path,
2709    file_progress: Option<&FileItemProgress>,
2710) -> Result<String> {
2711    let mut file = File::open(path)
2712        .with_context(|| format!("Failed to open {}", path.display()))?;
2713    let mut hasher = Sha1::new();
2714    let mut buffer = [0_u8; FILE_HASH_BUFFER_SIZE];
2715    let mut total_read = 0_u64;
2716    loop {
2717        let bytes_read = file
2718            .read(&mut buffer)
2719            .with_context(|| format!("Failed to read {}", path.display()))?;
2720        if bytes_read == 0 {
2721            break;
2722        }
2723        hasher.update(
2724            buffer
2725                .get(..bytes_read)
2726                .context("Invalid bytes read length")?,
2727        );
2728        if let Ok(n_u64) = u64::try_from(bytes_read) {
2729            total_read = total_read.saturating_add(n_u64);
2730            if let Some(fp) = file_progress {
2731                fp.set_bytes_done(total_read);
2732            }
2733        }
2734    }
2735    Ok(format!("{:x}", hasher.finalize()))
2736}
2737
2738fn md5_hex_for_file(path: &Path) -> Result<String> {
2739    md5_hex_for_file_with_progress(path, None)
2740}
2741
2742fn md5_hex_for_file_with_progress(
2743    path: &Path,
2744    file_progress: Option<&FileItemProgress>,
2745) -> Result<String> {
2746    let mut file = File::open(path)
2747        .with_context(|| format!("Failed to open {}", path.display()))?;
2748    let mut hasher = Md5::new();
2749    let mut buffer = [0_u8; FILE_HASH_BUFFER_SIZE];
2750    let mut total_read = 0_u64;
2751    loop {
2752        let bytes_read = file
2753            .read(&mut buffer)
2754            .with_context(|| format!("Failed to read {}", path.display()))?;
2755        if bytes_read == 0 {
2756            break;
2757        }
2758        hasher.update(
2759            buffer
2760                .get(..bytes_read)
2761                .context("Invalid bytes read length")?,
2762        );
2763        if let Ok(n_u64) = u64::try_from(bytes_read) {
2764            total_read = total_read.saturating_add(n_u64);
2765            if let Some(fp) = file_progress {
2766                fp.set_bytes_done(total_read);
2767            }
2768        }
2769    }
2770    Ok(format!("{:x}", hasher.finalize()))
2771}
2772
2773fn sha1_hex_for_bytes(bytes: &[u8]) -> String {
2774    let mut hasher = Sha1::new();
2775    hasher.update(bytes);
2776    format!("{:x}", hasher.finalize())
2777}
2778
2779fn md5_hex_for_bytes(bytes: &[u8]) -> String {
2780    let mut hasher = Md5::new();
2781    hasher.update(bytes);
2782    format!("{:x}", hasher.finalize())
2783}
2784
2785fn pretty_json_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> {
2786    let compact =
2787        serde_json::to_string(value).context("Failed to serialize JSON")?;
2788    let formatted = json::jq_formatted(".", &compact)
2789        .context("Failed to format Internet Archive JSON output")?;
2790    Ok(formatted.into_bytes())
2791}
2792
2793#[cfg(test)]
2794#[allow(
2795    clippy::panic,
2796    clippy::expect_used,
2797    clippy::unwrap_used,
2798    clippy::unwrap_in_result,
2799    clippy::panic_in_result_fn,
2800    clippy::indexing_slicing,
2801    clippy::arithmetic_side_effects,
2802    reason = "Standard repository test boilerplate"
2803)]
2804mod tests {
2805    use super::*;
2806    use std::fs;
2807
2808    const TEST_IDENTIFIER: &str = "1234-some-test-item-identifier";
2809    const AUDIO_FILE_NAME: &str = "01 Track 01.m4a";
2810    const IMAGE_FILE_NAME: &str = "01 Track 01.png";
2811    const META_XML: &str = "<metadata><title>Some Test Item</title></metadata>";
2812
2813    #[derive(Default)]
2814    struct FixtureArchiveClient {
2815        metadata: Option<MetadataResponse>,
2816        files_xml_bytes: Option<Vec<u8>>,
2817        meta_xml_bytes: Option<Vec<u8>>,
2818        download_bytes: BTreeMap<String, Vec<u8>>,
2819    }
2820
2821    impl ArchiveClient for FixtureArchiveClient {
2822        fn fetch_metadata(
2823            &self,
2824            _identifier: &str,
2825        ) -> Result<MetadataResponse> {
2826            self.metadata
2827                .clone()
2828                .ok_or_else(|| anyhow!("missing fixture metadata"))
2829        }
2830
2831        fn fetch_files_xml_bytes(&self, _identifier: &str) -> Result<Vec<u8>> {
2832            self.files_xml_bytes
2833                .clone()
2834                .ok_or_else(|| anyhow!("missing fixture files xml"))
2835        }
2836
2837        fn fetch_meta_xml_bytes(&self, _identifier: &str) -> Result<Vec<u8>> {
2838            self.meta_xml_bytes
2839                .clone()
2840                .ok_or_else(|| anyhow!("missing fixture meta xml"))
2841        }
2842
2843        fn fetch_download_bytes(
2844            &self,
2845            _identifier: &str,
2846            file_name: &str,
2847        ) -> Result<Vec<u8>> {
2848            self.download_bytes.get(file_name).cloned().ok_or_else(|| {
2849                anyhow!("missing fixture download bytes for {file_name}")
2850            })
2851        }
2852    }
2853
2854    fn fixture_metadata() -> MetadataResponse {
2855        MetadataResponse {
2856            files: vec![
2857                MetadataFile {
2858                    name: AUDIO_FILE_NAME.to_string(),
2859                    source: Some("original".to_string()),
2860                    md5: Some("5d41402abc4b2a76b9719d911017c592".to_string()),
2861                    sha1: Some(
2862                        "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d".to_string(),
2863                    ),
2864                    size: Some("5".to_string()),
2865                },
2866                MetadataFile {
2867                    name: IMAGE_FILE_NAME.to_string(),
2868                    source: Some("derivative".to_string()),
2869                    md5: Some("7d793037a0760186574b0282f2f435e7".to_string()),
2870                    sha1: Some(
2871                        "7c211433f02071597741e6ff5a8ea34789abbf43".to_string(),
2872                    ),
2873                    size: Some("5".to_string()),
2874                },
2875            ],
2876            extra: BTreeMap::from([(
2877                "metadata".to_string(),
2878                serde_json::json!({"identifier": TEST_IDENTIFIER}),
2879            )]),
2880        }
2881    }
2882
2883    fn fixture_client() -> FixtureArchiveClient {
2884        FixtureArchiveClient {
2885            metadata: Some(fixture_metadata()),
2886            files_xml_bytes: Some(fixture_xml().into_bytes()),
2887            meta_xml_bytes: Some(META_XML.as_bytes().to_vec()),
2888            download_bytes: BTreeMap::from([
2889                (AUDIO_FILE_NAME.to_string(), b"hello".to_vec()),
2890                (IMAGE_FILE_NAME.to_string(), b"world".to_vec()),
2891            ]),
2892        }
2893    }
2894
2895    fn fixture_xml() -> String {
2896        format!(
2897            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
2898<files>\
2899<file name=\"{AUDIO_FILE_NAME}\" source=\"original\">\
2900<size>5</size>\
2901<md5>5d41402abc4b2a76b9719d911017c592</md5>\
2902<sha1>aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d</sha1>\
2903</file>\
2904<file name=\"{IMAGE_FILE_NAME}\" source=\"derivative\">\
2905<size>5</size>\
2906<md5>7d793037a0760186574b0282f2f435e7</md5>\
2907<sha1>7c211433f02071597741e6ff5a8ea34789abbf43</sha1>\
2908</file>\
2909<file name=\"{TEST_IDENTIFIER}_files.xml\" source=\"original\">\
2910<md5>placeholder</md5>\
2911</file>\
2912</files>"
2913        )
2914    }
2915
2916    fn write_basic_item(temp_dir: &tempfile::TempDir) -> PathBuf {
2917        let item_path = temp_dir.path().join(TEST_IDENTIFIER);
2918        fs::create_dir_all(&item_path).unwrap();
2919        fs::write(item_path.join(AUDIO_FILE_NAME), b"hello").unwrap();
2920        fs::write(item_path.join(IMAGE_FILE_NAME), b"world").unwrap();
2921        fs::write(
2922            item_path.join(format!("{TEST_IDENTIFIER}{FILES_XML_SUFFIX}")),
2923            fixture_xml(),
2924        )
2925        .unwrap();
2926        item_path
2927    }
2928
2929    #[crate::ctb_test]
2930    fn test_verify() {
2931        let temp_dir = tempfile::tempdir().unwrap();
2932        let item_path = write_basic_item(&temp_dir);
2933        let result = verify(&item_path, None, false, false).unwrap();
2934        let result_str = String::from_utf8(result).unwrap();
2935        assert!(result_str.starts_with("{\n"));
2936        let result_json: serde_json::Value =
2937            serde_json::from_str(&result_str).unwrap();
2938        assert_eq!(result_json["valid"], true);
2939        assert_eq!(result_json["identifier"], TEST_IDENTIFIER);
2940        assert_eq!(result_json["missing_files"], serde_json::json!([]));
2941        assert_eq!(result_json["unexpected_files"], serde_json::json!([]));
2942    }
2943
2944    #[crate::ctb_test]
2945    fn test_verify_original() {
2946        let temp_dir = tempfile::tempdir().unwrap();
2947        let item_path = temp_dir.path().join(TEST_IDENTIFIER);
2948        fs::create_dir_all(&item_path).unwrap();
2949        fs::write(item_path.join(AUDIO_FILE_NAME), b"hello").unwrap();
2950        fs::write(
2951            item_path.join(format!("{TEST_IDENTIFIER}{FILES_XML_SUFFIX}")),
2952            fixture_xml(),
2953        )
2954        .unwrap();
2955
2956        let result = verify(&item_path, None, false, true).unwrap();
2957        let result_json: serde_json::Value =
2958            serde_json::from_slice(&result).unwrap();
2959        assert_eq!(result_json["valid"], true);
2960        assert_eq!(result_json["missing_files"], serde_json::json!([]));
2961    }
2962
2963    #[crate::ctb_test]
2964    fn test_verify_reports_mismatch() {
2965        let temp_dir = tempfile::tempdir().unwrap();
2966        let item_path = write_basic_item(&temp_dir);
2967        fs::write(item_path.join(AUDIO_FILE_NAME), b"HELLO").unwrap();
2968
2969        let result = verify(&item_path, None, false, false).unwrap();
2970        let result_json: serde_json::Value =
2971            serde_json::from_slice(&result).unwrap();
2972
2973        assert_eq!(result_json["valid"], false);
2974        assert_eq!(
2975            result_json["mismatched_files"].as_array().unwrap().len(),
2976            1
2977        );
2978        assert_eq!(
2979            result_json["mismatched_files"][0]["name"],
2980            serde_json::json!(AUDIO_FILE_NAME)
2981        );
2982    }
2983
2984    #[crate::ctb_test]
2985    fn test_guess_identifier_from_metadata_path() {
2986        let path = Path::new("/tmp/1234-some-test-item-identifier_meta.sqlite");
2987        assert_eq!(
2988            guess_identifer_from_path(path),
2989            Some(TEST_IDENTIFIER.to_string())
2990        );
2991    }
2992
2993    #[crate::ctb_test]
2994    fn test_guess_identifier_from_item_directory() {
2995        let temp_dir = tempfile::tempdir().unwrap();
2996        let item_path = write_basic_item(&temp_dir);
2997
2998        assert_eq!(
2999            guess_identifier_from_path(&item_path),
3000            Some(TEST_IDENTIFIER.to_string())
3001        );
3002    }
3003
3004    #[crate::ctb_test]
3005    fn test_iasha1_hashes_local_files_xml_when_manifest_has_no_sha1() {
3006        let temp_dir = tempfile::tempdir().unwrap();
3007        let item_path = write_basic_item(&temp_dir);
3008        let files_xml_path =
3009            item_path.join(format!("{TEST_IDENTIFIER}{FILES_XML_SUFFIX}"));
3010
3011        let expected_sha1 = sha1_hex_for_file(&files_xml_path).unwrap();
3012        let actual_sha1 = String::from_utf8(
3013            iasha1(files_xml_path.to_string_lossy().as_ref(), None, false)
3014                .unwrap(),
3015        )
3016        .unwrap();
3017
3018        assert_eq!(actual_sha1.trim(), expected_sha1);
3019    }
3020
3021    #[crate::ctb_test]
3022    fn test_iamd5_hashes_local_files_xml_when_manifest_has_no_md5() {
3023        let temp_dir = tempfile::tempdir().unwrap();
3024        let item_path = write_basic_item(&temp_dir);
3025        let files_xml_path =
3026            item_path.join(format!("{TEST_IDENTIFIER}{FILES_XML_SUFFIX}"));
3027
3028        let expected_md5 = md5_hex_for_file(&files_xml_path).unwrap();
3029        let actual_md5 = String::from_utf8(
3030            iamd5(files_xml_path.to_string_lossy().as_ref(), None, false)
3031                .unwrap(),
3032        )
3033        .unwrap();
3034
3035        assert_eq!(actual_md5.trim(), expected_md5);
3036    }
3037
3038    #[crate::ctb_test]
3039    fn test_verify_ignores_local_files_xml_checksum_mismatch() {
3040        let temp_dir = tempfile::tempdir().unwrap();
3041        let item_path = write_basic_item(&temp_dir);
3042
3043        let result = verify(&item_path, None, false, false).unwrap();
3044        let result_json: serde_json::Value =
3045            serde_json::from_slice(&result).unwrap();
3046
3047        assert_eq!(result_json["valid"], true);
3048        assert_eq!(result_json["mismatched_files"], serde_json::json!([]));
3049    }
3050
3051    #[crate::ctb_test]
3052    fn test_verify_live_detects_files_xml_checksum_mismatch() {
3053        let temp_dir = tempfile::tempdir().unwrap();
3054        let item_path = write_basic_item(&temp_dir);
3055        let local_manifest =
3056            load_local_files_manifest(&item_path, TEST_IDENTIFIER).unwrap();
3057        let live_files_xml_bytes = b"<files></files>".to_vec();
3058        let verification = verify_against_manifest(
3059            &item_path,
3060            TEST_IDENTIFIER,
3061            &local_manifest,
3062            None,
3063            true,
3064            &VerificationOptions {
3065                files_xml_live_sha1: Some(sha1_hex_for_bytes(
3066                    &live_files_xml_bytes,
3067                )),
3068            },
3069            None,
3070        )
3071        .unwrap();
3072
3073        assert!(!verification.valid);
3074        assert_eq!(verification.mismatched_files.len(), 1);
3075        assert_eq!(
3076            verification.mismatched_files[0].name,
3077            format!("{TEST_IDENTIFIER}{FILES_XML_SUFFIX}")
3078        );
3079    }
3080
3081    #[crate::ctb_test]
3082    fn test_metadata_with_client_is_pretty_printed() {
3083        let result =
3084            metadata_with_client(&fixture_client(), TEST_IDENTIFIER).unwrap();
3085        let result_str = String::from_utf8(result).unwrap();
3086
3087        assert!(result_str.starts_with("{\n"));
3088        assert!(result_str.contains("\n  \"files\":"));
3089    }
3090
3091    #[crate::ctb_test]
3092    fn test_listplain_with_client() {
3093        let result = String::from_utf8(
3094            listplain_with_client(&fixture_client(), TEST_IDENTIFIER).unwrap(),
3095        )
3096        .unwrap();
3097
3098        assert_eq!(result, format!("{AUDIO_FILE_NAME}\n{IMAGE_FILE_NAME}\n"));
3099    }
3100
3101    #[crate::ctb_test]
3102    fn test_contains_with_client() {
3103        let result = String::from_utf8(
3104            contains_with_client(
3105                &fixture_client(),
3106                TEST_IDENTIFIER,
3107                IMAGE_FILE_NAME,
3108            )
3109            .unwrap(),
3110        )
3111        .unwrap();
3112
3113        assert_eq!(result, "true\n");
3114    }
3115
3116    #[crate::ctb_test]
3117    fn test_filesxml_with_client() {
3118        let result = String::from_utf8(
3119            filesxml_with_client(&fixture_client(), TEST_IDENTIFIER).unwrap(),
3120        )
3121        .unwrap();
3122
3123        assert_eq!(result, fixture_xml());
3124    }
3125
3126    #[crate::ctb_test]
3127    fn test_metaxml_with_client() {
3128        let result = String::from_utf8(
3129            metaxml_with_client(&fixture_client(), TEST_IDENTIFIER).unwrap(),
3130        )
3131        .unwrap();
3132
3133        assert_eq!(result, META_XML);
3134    }
3135
3136    #[crate::ctb_test]
3137    fn test_download_as_stream_with_client() {
3138        let result = String::from_utf8(
3139            download_as_stream_with_client(
3140                &fixture_client(),
3141                &format!("{TEST_IDENTIFIER}/{AUDIO_FILE_NAME}"),
3142            )
3143            .unwrap(),
3144        )
3145        .unwrap();
3146
3147        assert_eq!(result, "hello");
3148    }
3149
3150    #[crate::ctb_test]
3151    fn test_download_here_with_client() {
3152        let temp_dir = tempfile::tempdir().unwrap();
3153        let result = download_here_with_client(
3154            &fixture_client(),
3155            &format!("{TEST_IDENTIFIER}/{AUDIO_FILE_NAME}"),
3156            Some(temp_dir.path()),
3157            Progress::new(false),
3158        )
3159        .unwrap();
3160        let result_json: serde_json::Value =
3161            serde_json::from_slice(&result).unwrap();
3162        let written =
3163            fs::read_to_string(temp_dir.path().join(AUDIO_FILE_NAME)).unwrap();
3164
3165        assert_eq!(written, "hello");
3166        assert_eq!(result_json["identifier"], TEST_IDENTIFIER);
3167    }
3168
3169    #[crate::ctb_test]
3170    fn test_download_with_client() {
3171        let temp_dir = tempfile::tempdir().unwrap();
3172        let result = download_with_client(
3173            &fixture_client(),
3174            TEST_IDENTIFIER,
3175            Some(temp_dir.path()),
3176            false,
3177            Progress::new(false),
3178        )
3179        .unwrap();
3180        let result_json: serde_json::Value =
3181            serde_json::from_slice(&result).unwrap();
3182
3183        assert_eq!(
3184            fs::read_to_string(
3185                temp_dir.path().join(TEST_IDENTIFIER).join(AUDIO_FILE_NAME)
3186            )
3187            .unwrap(),
3188            "hello"
3189        );
3190        assert_eq!(
3191            result_json["downloaded_files"].as_array().unwrap().len(),
3192            2
3193        );
3194    }
3195
3196    #[crate::ctb_test]
3197    fn test_download_with_client_original() {
3198        let temp_dir = tempfile::tempdir().unwrap();
3199        let result = download_with_client(
3200            &fixture_client(),
3201            TEST_IDENTIFIER,
3202            Some(temp_dir.path()),
3203            true,
3204            Progress::new(false),
3205        )
3206        .unwrap();
3207        let result_json: serde_json::Value =
3208            serde_json::from_slice(&result).unwrap();
3209
3210        assert_eq!(
3211            fs::read_to_string(
3212                temp_dir.path().join(TEST_IDENTIFIER).join(AUDIO_FILE_NAME)
3213            )
3214            .unwrap(),
3215            "hello"
3216        );
3217        let downloaded = result_json["downloaded_files"].as_array().unwrap();
3218        assert_eq!(downloaded.len(), 1);
3219        assert_eq!(downloaded[0], AUDIO_FILE_NAME);
3220    }
3221
3222    #[crate::ctb_test]
3223    fn test_checkeddl_with_client() {
3224        let temp_dir = tempfile::tempdir().unwrap();
3225        let result = checkeddl_with_client(
3226            &fixture_client(),
3227            &format!("{TEST_IDENTIFIER}/{AUDIO_FILE_NAME}"),
3228            Some(temp_dir.path()),
3229            false,
3230            Progress::new(false),
3231        )
3232        .unwrap();
3233        let result_json: serde_json::Value =
3234            serde_json::from_slice(&result).unwrap();
3235
3236        assert_eq!(result_json["valid"], true);
3237        assert_eq!(
3238            result_json["checked_files"],
3239            serde_json::json!([AUDIO_FILE_NAME])
3240        );
3241    }
3242
3243    #[crate::ctb_test]
3244    fn test_checkeddl_with_client_data_node_url() {
3245        let temp_dir = tempfile::tempdir().unwrap();
3246        let data_node_url = format!(
3247            "https://dn711000.ca.archive.org/0/items/{TEST_IDENTIFIER}/{AUDIO_FILE_NAME}"
3248        );
3249        let result = checkeddl_with_client(
3250            &fixture_client(),
3251            &data_node_url,
3252            Some(temp_dir.path()),
3253            false,
3254            Progress::new(false),
3255        )
3256        .unwrap();
3257        let result_json: serde_json::Value =
3258            serde_json::from_slice(&result).unwrap();
3259
3260        assert_eq!(result_json["valid"], true);
3261        assert_eq!(
3262            result_json["checked_files"],
3263            serde_json::json!([AUDIO_FILE_NAME])
3264        );
3265    }
3266
3267    #[crate::ctb_test]
3268    fn test_checkeddl_with_client_original() {
3269        let temp_dir = tempfile::tempdir().unwrap();
3270        let result = checkeddl_with_client(
3271            &fixture_client(),
3272            TEST_IDENTIFIER,
3273            Some(temp_dir.path()),
3274            true,
3275            Progress::new(false),
3276        )
3277        .unwrap();
3278        let result_json: serde_json::Value =
3279            serde_json::from_slice(&result).unwrap();
3280
3281        assert_eq!(result_json["valid"], true);
3282        let checked = result_json["checked_files"].as_array().unwrap();
3283        assert_eq!(checked.len(), 2);
3284        assert!(checked.contains(&serde_json::json!(AUDIO_FILE_NAME)));
3285        assert!(checked.contains(&serde_json::json!(format!(
3286            "{TEST_IDENTIFIER}{FILES_XML_SUFFIX}"
3287        ))));
3288    }
3289
3290    #[crate::ctb_test]
3291    fn test_parse_archive_target_urls() {
3292        let details_url =
3293            "https://archive.org/details/populationschedu1331unix";
3294        let target = parse_archive_target(details_url).unwrap();
3295        assert_eq!(target.identifier, "populationschedu1331unix");
3296        assert_eq!(target.archive_path, None);
3297
3298        let details_slash =
3299            "https://archive.org/details/populationschedu1331unix/";
3300        let target = parse_archive_target(details_slash).unwrap();
3301        assert_eq!(target.identifier, "populationschedu1331unix");
3302        assert_eq!(target.archive_path, None);
3303
3304        let details_with_file =
3305            "https://archive.org/details/populationschedu1331unix/sub/file.pdf";
3306        let target = parse_archive_target(details_with_file).unwrap();
3307        assert_eq!(target.identifier, "populationschedu1331unix");
3308        assert_eq!(target.archive_path, Some("sub/file.pdf".to_string()));
3309
3310        let download_url = "https://archive.org/download/populationschedu1331unix/01%20Track%2001.m4a";
3311        let target = parse_archive_target(download_url).unwrap();
3312        assert_eq!(target.identifier, "populationschedu1331unix");
3313        assert_eq!(target.archive_path, Some("01 Track 01.m4a".to_string()));
3314
3315        let metadata_url =
3316            "https://archive.org/metadata/populationschedu1331unix";
3317        let target = parse_archive_target(metadata_url).unwrap();
3318        assert_eq!(target.identifier, "populationschedu1331unix");
3319        assert_eq!(target.archive_path, None);
3320
3321        let stream_url = "https://archive.org/stream/populationschedu1331unix";
3322        let target = parse_archive_target(stream_url).unwrap();
3323        assert_eq!(target.identifier, "populationschedu1331unix");
3324        assert_eq!(target.archive_path, None);
3325
3326        let embed_url = "https://archive.org/embed/populationschedu1331unix";
3327        let target = parse_archive_target(embed_url).unwrap();
3328        assert_eq!(target.identifier, "populationschedu1331unix");
3329        assert_eq!(target.archive_path, None);
3330
3331        let items_url = "https://archive.org/items/populationschedu1331unix";
3332        let target = parse_archive_target(items_url).unwrap();
3333        assert_eq!(target.identifier, "populationschedu1331unix");
3334        assert_eq!(target.archive_path, None);
3335
3336        let www_http_query = "http://www.archive.org/details/populationschedu1331unix?query=1#frag";
3337        let target = parse_archive_target(www_http_query).unwrap();
3338        assert_eq!(target.identifier, "populationschedu1331unix");
3339        assert_eq!(target.archive_path, None);
3340
3341        let no_scheme = "archive.org/details/populationschedu1331unix";
3342        let target = parse_archive_target(no_scheme).unwrap();
3343        assert_eq!(target.identifier, "populationschedu1331unix");
3344        assert_eq!(target.archive_path, None);
3345
3346        let plain_ident = "populationschedu1331unix";
3347        let target = parse_archive_target(plain_ident).unwrap();
3348        assert_eq!(target.identifier, "populationschedu1331unix");
3349        assert_eq!(target.archive_path, None);
3350
3351        let plain_with_path = "populationschedu1331unix/01 Track 01.m4a";
3352        let target = parse_archive_target(plain_with_path).unwrap();
3353        assert_eq!(target.identifier, "populationschedu1331unix");
3354        assert_eq!(target.archive_path, Some("01 Track 01.m4a".to_string()));
3355
3356        let data_node_url = "https://dn711000.ca.archive.org/0/items/prideandprejudice_1005_librivox/prideandprejudice_01_austen.ogg";
3357        let target = parse_archive_target(data_node_url).unwrap();
3358        assert_eq!(target.identifier, "prideandprejudice_1005_librivox");
3359        assert_eq!(
3360            target.archive_path,
3361            Some("prideandprejudice_01_austen.ogg".to_string())
3362        );
3363
3364        let data_node_no_scheme = "dn711000.ca.archive.org/0/items/prideandprejudice_1005_librivox/prideandprejudice_01_austen.ogg";
3365        let target = parse_archive_target(data_node_no_scheme).unwrap();
3366        assert_eq!(target.identifier, "prideandprejudice_1005_librivox");
3367        assert_eq!(
3368            target.archive_path,
3369            Some("prideandprejudice_01_austen.ogg".to_string())
3370        );
3371
3372        let us_node_url = "https://ia800100.us.archive.org/3/items/prideandprejudice_1005_librivox/prideandprejudice_01_austen.ogg";
3373        let target = parse_archive_target(us_node_url).unwrap();
3374        assert_eq!(target.identifier, "prideandprejudice_1005_librivox");
3375        assert_eq!(
3376            target.archive_path,
3377            Some("prideandprejudice_01_austen.ogg".to_string())
3378        );
3379
3380        let node_no_disk_url = "https://ia600201.us.archive.org/items/prideandprejudice_1005_librivox/prideandprejudice_01_austen.ogg";
3381        let target = parse_archive_target(node_no_disk_url).unwrap();
3382        assert_eq!(target.identifier, "prideandprejudice_1005_librivox");
3383        assert_eq!(
3384            target.archive_path,
3385            Some("prideandprejudice_01_austen.ogg".to_string())
3386        );
3387
3388        let node_item_only = "https://dn711000.ca.archive.org/0/items/prideandprejudice_1005_librivox";
3389        let target = parse_archive_target(node_item_only).unwrap();
3390        assert_eq!(target.identifier, "prideandprejudice_1005_librivox");
3391        assert_eq!(target.archive_path, None);
3392
3393        parse_archive_target("").unwrap_err();
3394        parse_archive_target("https://archive.org/details/").unwrap_err();
3395        parse_archive_target("https://archive.org/").unwrap_err();
3396        parse_archive_target("https://dn711000.ca.archive.org/0/items/")
3397            .unwrap_err();
3398        parse_archive_target("https://dn711000.ca.archive.org/").unwrap_err();
3399        parse_archive_target(
3400            "https://web.archive.org/web/20261018/https://example.com",
3401        )
3402        .unwrap_err();
3403        parse_archive_target("https://example.com/items/test/file.ogg")
3404            .unwrap_err();
3405    }
3406
3407    #[crate::ctb_test]
3408    fn test_parse_content_range() {
3409        assert_eq!(
3410            parse_content_range("bytes 0-8388607/52428800"),
3411            Some((0, 8388607, Some(52428800)))
3412        );
3413        assert_eq!(
3414            parse_content_range("bytes 100-200/*"),
3415            Some((100, 200, None))
3416        );
3417        assert_eq!(parse_content_range("bytes 0-0/1"), Some((0, 0, Some(1))));
3418        assert_eq!(parse_content_range("invalid"), None);
3419        assert_eq!(parse_content_range("items 0-10/20"), None);
3420    }
3421
3422    #[crate::ctb_test]
3423    fn test_create_temp_path_and_atomic_commit() {
3424        let temp_dir = tempfile::tempdir().unwrap();
3425        let dest = temp_dir.path().join("final_file.bin");
3426        let temp_path = create_temp_path(temp_dir.path(), "final_file.bin");
3427        assert!(temp_path.starts_with(temp_dir.path()));
3428        assert_ne!(temp_path, dest);
3429
3430        let mut guard = TempFileCleanupGuard {
3431            temp_path: temp_path.clone(),
3432            active: true,
3433        };
3434        fs::write(&temp_path, b"atomic test payload").unwrap();
3435        assert!(temp_path.exists());
3436
3437        commit_atomic_file(&temp_path, &dest).unwrap();
3438        guard.active = false;
3439
3440        assert!(!temp_path.exists());
3441        assert!(dest.exists());
3442        assert_eq!(fs::read(&dest).unwrap(), b"atomic test payload");
3443    }
3444
3445    #[crate::ctb_test]
3446    fn test_temp_file_cleanup_guard_removes_file() {
3447        let temp_dir = tempfile::tempdir().unwrap();
3448        let temp_path = temp_dir.path().join(".test_cleanup_temp");
3449        fs::write(&temp_path, b"uncommitted partial data").unwrap();
3450        assert!(temp_path.exists());
3451
3452        {
3453            let _guard = TempFileCleanupGuard {
3454                temp_path: temp_path.clone(),
3455                active: true,
3456            };
3457        }
3458
3459        assert!(!temp_path.exists());
3460    }
3461
3462    struct MockRangeResponse {
3463        status: reqwest::StatusCode,
3464        headers: reqwest::header::HeaderMap,
3465        content_length: Option<u64>,
3466        body: std::io::Cursor<Vec<u8>>,
3467        fail_after_bytes: Option<usize>,
3468        read_so_far: usize,
3469    }
3470
3471    impl Read for MockRangeResponse {
3472        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
3473            if let Some(limit) = self.fail_after_bytes
3474                && self.read_so_far >= limit
3475            {
3476                return Err(std::io::Error::new(
3477                    std::io::ErrorKind::TimedOut,
3478                    "simulated stalled range stream",
3479                ));
3480            }
3481            let max_len = if let Some(limit) = self.fail_after_bytes {
3482                buf.len().min(limit - self.read_so_far)
3483            } else {
3484                buf.len()
3485            };
3486            let n = self.body.read(&mut buf[..max_len])?;
3487            self.read_so_far += n;
3488            Ok(n)
3489        }
3490    }
3491
3492    impl RangeHttpResponse for MockRangeResponse {
3493        fn status(&self) -> reqwest::StatusCode {
3494            self.status
3495        }
3496
3497        fn headers(&self) -> &reqwest::header::HeaderMap {
3498            &self.headers
3499        }
3500
3501        fn content_length(&self) -> Option<u64> {
3502            self.content_length
3503        }
3504    }
3505
3506    struct MockRangeClient<F> {
3507        handler: F,
3508    }
3509
3510    impl<F> MockRangeClient<F>
3511    where
3512        F: Fn(
3513            &str,
3514            Option<&reqwest::header::HeaderMap>,
3515        ) -> Result<MockRangeResponse>,
3516    {
3517        fn new(handler: F) -> Self {
3518            Self { handler }
3519        }
3520    }
3521
3522    impl<F> RangeHttpClient for MockRangeClient<F>
3523    where
3524        F: Fn(
3525            &str,
3526            Option<&reqwest::header::HeaderMap>,
3527        ) -> Result<MockRangeResponse>,
3528    {
3529        fn get_with_headers(
3530            &self,
3531            url: &str,
3532            headers: Option<reqwest::header::HeaderMap>,
3533        ) -> Result<Box<dyn RangeHttpResponse>> {
3534            Ok(Box::new((self.handler)(url, headers.as_ref())?))
3535        }
3536    }
3537
3538    #[crate::ctb_test]
3539    fn test_chunked_range_download_many_chunks_and_retries() {
3540        let payload: Vec<u8> = (0..2500_u32)
3541            .map(|i| u8::try_from(i % 251).unwrap())
3542            .collect();
3543        let total_len = u64::try_from(payload.len()).unwrap();
3544        let attempts = std::sync::atomic::AtomicUsize::new(0);
3545
3546        let client = MockRangeClient::new(|_url, headers| {
3547            let call_idx =
3548                attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3549            let range_str = headers
3550                .unwrap()
3551                .get(reqwest::header::RANGE)
3552                .unwrap()
3553                .to_str()
3554                .unwrap();
3555            let (start_s, end_s) = range_str
3556                .strip_prefix("bytes=")
3557                .unwrap()
3558                .split_once('-')
3559                .unwrap();
3560            let start: usize = start_s.parse().unwrap();
3561            let end: usize =
3562                end_s.parse::<usize>().unwrap().min(payload.len() - 1);
3563
3564            // Inject transient connection failure on chunk 0 and mid-read
3565            // timeout on a later chunk to test retry recovery.
3566            if call_idx == 0 {
3567                bail!("simulated transient connection reset on chunk 0");
3568            }
3569
3570            let mut resp_headers = reqwest::header::HeaderMap::new();
3571            resp_headers.insert(
3572                reqwest::header::CONTENT_RANGE,
3573                reqwest::header::HeaderValue::from_str(&format!(
3574                    "bytes {start}-{end}/{total_len}"
3575                ))
3576                .unwrap(),
3577            );
3578            let slice = payload[start..=end].to_vec();
3579            let slice_len = u64::try_from(slice.len()).unwrap();
3580            Ok(MockRangeResponse {
3581                status: reqwest::StatusCode::PARTIAL_CONTENT,
3582                headers: resp_headers,
3583                content_length: Some(slice_len),
3584                body: std::io::Cursor::new(slice),
3585                fail_after_bytes: if call_idx == 70 { Some(4) } else { None },
3586                read_so_far: 0,
3587            })
3588        });
3589
3590        let progress = Progress::new(false);
3591        let batch = progress.start_file_batch("Overall", Some(1), None);
3592        let fp = batch.start_file("big.bin", None);
3593        let mut out = Vec::new();
3594        let written = download_to_writer_chunked_range_with_http(
3595            &client,
3596            "https://archive.org/download/test/big.bin",
3597            &mut out,
3598            Some(&fp),
3599            16,
3600            0,
3601        )
3602        .unwrap();
3603        fp.finish(written);
3604        batch.finish();
3605
3606        assert_eq!(written, total_len);
3607        assert_eq!(out, payload);
3608        // 2500 / 16 = 157 chunks + 2 retried attempts = 159 requests
3609        assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 159);
3610    }
3611
3612    #[crate::ctb_test]
3613    fn test_chunked_range_download_rejects_200_ok_on_nonzero_offset() {
3614        let client = MockRangeClient::new(|_url, headers| {
3615            let range_str = headers
3616                .unwrap()
3617                .get(reqwest::header::RANGE)
3618                .unwrap()
3619                .to_str()
3620                .unwrap();
3621            if range_str.starts_with("bytes=0-") {
3622                let mut resp_headers = reqwest::header::HeaderMap::new();
3623                resp_headers.insert(
3624                    reqwest::header::CONTENT_RANGE,
3625                    reqwest::header::HeaderValue::from_static("bytes 0-3/8"),
3626                );
3627                Ok(MockRangeResponse {
3628                    status: reqwest::StatusCode::PARTIAL_CONTENT,
3629                    headers: resp_headers,
3630                    content_length: Some(4),
3631                    body: std::io::Cursor::new(b"abcd".to_vec()),
3632                    fail_after_bytes: None,
3633                    read_so_far: 0,
3634                })
3635            } else {
3636                // Misbehaving server ignores Range on second chunk and returns 200 OK
3637                Ok(MockRangeResponse {
3638                    status: reqwest::StatusCode::OK,
3639                    headers: reqwest::header::HeaderMap::new(),
3640                    content_length: Some(8),
3641                    body: std::io::Cursor::new(b"abcdefgh".to_vec()),
3642                    fail_after_bytes: None,
3643                    read_so_far: 0,
3644                })
3645            }
3646        });
3647
3648        let mut out = Vec::new();
3649        let err = download_to_writer_chunked_range_with_http(
3650            &client,
3651            "https://archive.org/download/test/broken.bin",
3652            &mut out,
3653            None,
3654            4,
3655            0,
3656        )
3657        .unwrap_err();
3658        assert!(format!("{err:#}").contains("Unexpected HTTP status 200"));
3659    }
3660
3661    #[crate::ctb_test]
3662    fn test_chunked_range_download_empty_file_416_and_truncated_error() {
3663        let empty_client = MockRangeClient::new(|_url, _headers| {
3664            let mut resp_headers = reqwest::header::HeaderMap::new();
3665            resp_headers.insert(
3666                reqwest::header::CONTENT_RANGE,
3667                reqwest::header::HeaderValue::from_static("bytes */0"),
3668            );
3669            Ok(MockRangeResponse {
3670                status: reqwest::StatusCode::RANGE_NOT_SATISFIABLE,
3671                headers: resp_headers,
3672                content_length: Some(0),
3673                body: std::io::Cursor::new(Vec::new()),
3674                fail_after_bytes: None,
3675                read_so_far: 0,
3676            })
3677        });
3678        let mut empty_out = Vec::new();
3679        let written = download_to_writer_chunked_range_with_http(
3680            &empty_client,
3681            "https://archive.org/download/test/empty.bin",
3682            &mut empty_out,
3683            None,
3684            16,
3685            0,
3686        )
3687        .unwrap();
3688        assert_eq!(written, 0);
3689        assert!(empty_out.is_empty());
3690
3691        let truncated_client = MockRangeClient::new(|_url, headers| {
3692            let range_str = headers
3693                .unwrap()
3694                .get(reqwest::header::RANGE)
3695                .unwrap()
3696                .to_str()
3697                .unwrap();
3698            if range_str.starts_with("bytes=0-") {
3699                let mut resp_headers = reqwest::header::HeaderMap::new();
3700                resp_headers.insert(
3701                    reqwest::header::CONTENT_RANGE,
3702                    reqwest::header::HeaderValue::from_static("bytes 0-3/8"),
3703                );
3704                Ok(MockRangeResponse {
3705                    status: reqwest::StatusCode::PARTIAL_CONTENT,
3706                    headers: resp_headers,
3707                    content_length: Some(4),
3708                    body: std::io::Cursor::new(b"abcd".to_vec()),
3709                    fail_after_bytes: None,
3710                    read_so_far: 0,
3711                })
3712            } else {
3713                Ok(MockRangeResponse {
3714                    status: reqwest::StatusCode::RANGE_NOT_SATISFIABLE,
3715                    headers: reqwest::header::HeaderMap::new(),
3716                    content_length: Some(0),
3717                    body: std::io::Cursor::new(Vec::new()),
3718                    fail_after_bytes: None,
3719                    read_so_far: 0,
3720                })
3721            }
3722        });
3723        let mut trunc_out = Vec::new();
3724        let err = download_to_writer_chunked_range_with_http(
3725            &truncated_client,
3726            "https://archive.org/download/test/trunc.bin",
3727            &mut trunc_out,
3728            None,
3729            4,
3730            0,
3731        )
3732        .unwrap_err();
3733        assert!(format!("{err:#}").contains("416"));
3734    }
3735
3736    #[crate::ctb_test]
3737    fn test_part_file_interrupted_download_resumes_from_exact_offset() {
3738        let temp_dir = tempfile::tempdir().unwrap();
3739        let dest = temp_dir.path().join("movie.iso");
3740        let part = part_path_for_destination(&dest);
3741        assert_eq!(part, temp_dir.path().join("movie.iso.part"));
3742
3743        let payload: Vec<u8> = (0..120_u32)
3744            .map(|i| u8::try_from(i % 251).unwrap())
3745            .collect();
3746        let total_len = u64::try_from(payload.len()).unwrap();
3747
3748        // Run 1: fail persistently once offset reaches 48 (3 chunks of 16 bytes),
3749        // simulating an interrupted download leaving 48 bytes in movie.iso.part.
3750        let run1_client = MockRangeClient::new(|_url, headers| {
3751            let range_str = headers
3752                .unwrap()
3753                .get(reqwest::header::RANGE)
3754                .unwrap()
3755                .to_str()
3756                .unwrap();
3757            let (start_s, end_s) = range_str
3758                .strip_prefix("bytes=")
3759                .unwrap()
3760                .split_once('-')
3761                .unwrap();
3762            let start: usize = start_s.parse().unwrap();
3763            let end: usize =
3764                end_s.parse::<usize>().unwrap().min(payload.len() - 1);
3765            if start >= 48 {
3766                bail!("simulated interruption at byte 48");
3767            }
3768            let mut resp_headers = reqwest::header::HeaderMap::new();
3769            resp_headers.insert(
3770                reqwest::header::CONTENT_RANGE,
3771                reqwest::header::HeaderValue::from_str(&format!(
3772                    "bytes {start}-{end}/{total_len}"
3773                ))
3774                .unwrap(),
3775            );
3776            let slice = payload[start..=end].to_vec();
3777            let slice_len = u64::try_from(slice.len()).unwrap();
3778            Ok(MockRangeResponse {
3779                status: reqwest::StatusCode::PARTIAL_CONTENT,
3780                headers: resp_headers,
3781                content_length: Some(slice_len),
3782                body: std::io::Cursor::new(slice),
3783                fail_after_bytes: None,
3784                read_so_far: 0,
3785            })
3786        });
3787
3788        download_to_part_file_chunked_range_with_http(
3789            &run1_client,
3790            "https://archive.org/download/test/movie.iso",
3791            &dest,
3792            Some(total_len),
3793            None,
3794            16,
3795            0,
3796        )
3797        .unwrap_err();
3798
3799        assert!(!dest.exists());
3800        assert!(part.is_file());
3801        assert_eq!(fs::read(&part).unwrap(), &payload[..48]);
3802
3803        // Run 2: resume from movie.iso.part; assert NO request starts below byte 48!
3804        let requested_starts = std::sync::Mutex::new(Vec::new());
3805        let run2_client = MockRangeClient::new(|_url, headers| {
3806            let range_str = headers
3807                .unwrap()
3808                .get(reqwest::header::RANGE)
3809                .unwrap()
3810                .to_str()
3811                .unwrap();
3812            let (start_s, end_s) = range_str
3813                .strip_prefix("bytes=")
3814                .unwrap()
3815                .split_once('-')
3816                .unwrap();
3817            let start: usize = start_s.parse().unwrap();
3818            let end: usize =
3819                end_s.parse::<usize>().unwrap().min(payload.len() - 1);
3820            requested_starts.lock().unwrap().push(start);
3821
3822            let mut resp_headers = reqwest::header::HeaderMap::new();
3823            resp_headers.insert(
3824                reqwest::header::CONTENT_RANGE,
3825                reqwest::header::HeaderValue::from_str(&format!(
3826                    "bytes {start}-{end}/{total_len}"
3827                ))
3828                .unwrap(),
3829            );
3830            let slice = payload[start..=end].to_vec();
3831            let slice_len = u64::try_from(slice.len()).unwrap();
3832            Ok(MockRangeResponse {
3833                status: reqwest::StatusCode::PARTIAL_CONTENT,
3834                headers: resp_headers,
3835                content_length: Some(slice_len),
3836                body: std::io::Cursor::new(slice),
3837                fail_after_bytes: None,
3838                read_so_far: 0,
3839            })
3840        });
3841
3842        let final_len = download_to_part_file_chunked_range_with_http(
3843            &run2_client,
3844            "https://archive.org/download/test/movie.iso",
3845            &dest,
3846            Some(total_len),
3847            None,
3848            16,
3849            0,
3850        )
3851        .unwrap();
3852
3853        assert_eq!(final_len, total_len);
3854        assert!(!part.exists());
3855        assert_eq!(fs::read(&dest).unwrap(), payload);
3856        let starts = requested_starts.lock().unwrap().clone();
3857        assert_eq!(starts, vec![48, 64, 80, 96, 112]);
3858    }
3859
3860    #[crate::ctb_test]
3861    fn test_part_file_handles_already_complete_416_and_200_ok_fallback() {
3862        let temp_dir = tempfile::tempdir().unwrap();
3863
3864        // Case A: .part already has full 32 bytes, expected_size is None, server returns 416 bytes */32
3865        let dest_a = temp_dir.path().join("complete.bin");
3866        let part_a = part_path_for_destination(&dest_a);
3867        let payload_a = b"0123456789abcdef0123456789abcdef".to_vec();
3868        fs::write(&part_a, &payload_a).unwrap();
3869
3870        let client_416 = MockRangeClient::new(|_url, _headers| {
3871            let mut resp_headers = reqwest::header::HeaderMap::new();
3872            resp_headers.insert(
3873                reqwest::header::CONTENT_RANGE,
3874                reqwest::header::HeaderValue::from_static("bytes */32"),
3875            );
3876            Ok(MockRangeResponse {
3877                status: reqwest::StatusCode::RANGE_NOT_SATISFIABLE,
3878                headers: resp_headers,
3879                content_length: Some(0),
3880                body: std::io::Cursor::new(Vec::new()),
3881                fail_after_bytes: None,
3882                read_so_far: 0,
3883            })
3884        });
3885        let written_a = download_to_part_file_chunked_range_with_http(
3886            &client_416,
3887            "https://archive.org/download/test/complete.bin",
3888            &dest_a,
3889            None,
3890            None,
3891            16,
3892            0,
3893        )
3894        .unwrap();
3895        assert_eq!(written_a, 32);
3896        assert!(!part_a.exists());
3897        assert_eq!(fs::read(&dest_a).unwrap(), payload_a);
3898
3899        // Case B: .part has 10 bytes, server ignores Range and responds 200 OK with full stream
3900        let dest_b = temp_dir.path().join("fallback200.bin");
3901        let part_b = part_path_for_destination(&dest_b);
3902        fs::write(&part_b, b"0123456789").unwrap();
3903        let payload_b = b"0123456789ABCDEFGHIJKLMNOPQRSTUV".to_vec();
3904        let payload_b_clone = payload_b.clone();
3905
3906        let client_200 = MockRangeClient::new(move |_url, _headers| {
3907            Ok(MockRangeResponse {
3908                status: reqwest::StatusCode::OK,
3909                headers: reqwest::header::HeaderMap::new(),
3910                content_length: Some(32),
3911                body: std::io::Cursor::new(payload_b_clone.clone()),
3912                fail_after_bytes: None,
3913                read_so_far: 0,
3914            })
3915        });
3916        let written_b = download_to_part_file_chunked_range_with_http(
3917            &client_200,
3918            "https://archive.org/download/test/fallback200.bin",
3919            &dest_b,
3920            Some(32),
3921            None,
3922            16,
3923            0,
3924        )
3925        .unwrap();
3926        assert_eq!(written_b, 32);
3927        assert!(!part_b.exists());
3928        assert_eq!(fs::read(&dest_b).unwrap(), payload_b);
3929    }
3930
3931    #[crate::ctb_test]
3932    fn test_checkeddl_resumes_interrupted_batch_skipping_verified_and_healing_corrupt_part()
3933     {
3934        struct RangeBackedArchiveClient<'a> {
3935            metadata: MetadataResponse,
3936            files_xml: Vec<u8>,
3937            files: BTreeMap<String, Vec<u8>>,
3938            range_log: &'a std::sync::Mutex<Vec<(String, usize)>>,
3939        }
3940
3941        impl ArchiveClient for RangeBackedArchiveClient<'_> {
3942            fn fetch_metadata(
3943                &self,
3944                _identifier: &str,
3945            ) -> Result<MetadataResponse> {
3946                Ok(self.metadata.clone())
3947            }
3948
3949            fn fetch_files_xml_bytes(
3950                &self,
3951                _identifier: &str,
3952            ) -> Result<Vec<u8>> {
3953                Ok(self.files_xml.clone())
3954            }
3955
3956            fn fetch_meta_xml_bytes(
3957                &self,
3958                _identifier: &str,
3959            ) -> Result<Vec<u8>> {
3960                Ok(META_XML.as_bytes().to_vec())
3961            }
3962
3963            fn fetch_download_bytes(
3964                &self,
3965                _identifier: &str,
3966                file_name: &str,
3967            ) -> Result<Vec<u8>> {
3968                self.files
3969                    .get(file_name)
3970                    .cloned()
3971                    .ok_or_else(|| anyhow!("missing {file_name}"))
3972            }
3973
3974            fn download_file(
3975                &self,
3976                identifier: &str,
3977                file_name: &str,
3978                destination: &Path,
3979                expected_size: Option<u64>,
3980                file_progress: Option<&FileItemProgress>,
3981            ) -> Result<u64> {
3982                let data = self
3983                    .files
3984                    .get(file_name)
3985                    .cloned()
3986                    .ok_or_else(|| anyhow!("missing {file_name}"))?;
3987                let total = u64::try_from(data.len()).unwrap();
3988                let fname = file_name.to_string();
3989                let log_ref = self.range_log;
3990                let mock_http = MockRangeClient::new(move |_url, headers| {
3991                    let range_str = headers
3992                        .unwrap()
3993                        .get(reqwest::header::RANGE)
3994                        .unwrap()
3995                        .to_str()
3996                        .unwrap();
3997                    let (start_s, end_s) = range_str
3998                        .strip_prefix("bytes=")
3999                        .unwrap()
4000                        .split_once('-')
4001                        .unwrap();
4002                    let start: usize = start_s.parse().unwrap();
4003                    let end: usize =
4004                        end_s.parse::<usize>().unwrap().min(data.len() - 1);
4005                    log_ref.lock().unwrap().push((fname.clone(), start));
4006                    let mut resp_headers = reqwest::header::HeaderMap::new();
4007                    resp_headers.insert(
4008                        reqwest::header::CONTENT_RANGE,
4009                        reqwest::header::HeaderValue::from_str(&format!(
4010                            "bytes {start}-{end}/{total}"
4011                        ))
4012                        .unwrap(),
4013                    );
4014                    let slice = data[start..=end].to_vec();
4015                    let slice_len = u64::try_from(slice.len()).unwrap();
4016                    Ok(MockRangeResponse {
4017                        status: reqwest::StatusCode::PARTIAL_CONTENT,
4018                        headers: resp_headers,
4019                        content_length: Some(slice_len),
4020                        body: std::io::Cursor::new(slice),
4021                        fail_after_bytes: None,
4022                        read_so_far: 0,
4023                    })
4024                });
4025                let url = download_url(identifier, file_name)?;
4026                download_to_part_file_chunked_range_with_http(
4027                    &mock_http,
4028                    url.as_str(),
4029                    destination,
4030                    expected_size,
4031                    file_progress,
4032                    16,
4033                    0,
4034                )
4035            }
4036        }
4037
4038        let file_a = b"file-a-already-complete-and-verified-bytes!".to_vec();
4039        let file_b =
4040            b"file-b-resumable-payload-across-several-16-byte-chunks!!"
4041                .to_vec();
4042        let file_c =
4043            b"file-c-clean-remote-contents-after-corrupt-part".to_vec();
4044
4045        let files_map = BTreeMap::from([
4046            ("a.bin".to_string(), file_a.clone()),
4047            ("b.bin".to_string(), file_b.clone()),
4048            ("c.bin".to_string(), file_c.clone()),
4049        ]);
4050
4051        let mut xml =
4052            String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?><files>");
4053        let mut meta_files = Vec::new();
4054        for (name, bytes) in &files_map {
4055            let md5 = md5_hex_for_bytes(bytes);
4056            let sha1 = sha1_hex_for_bytes(bytes);
4057            let sz = bytes.len().to_string();
4058            xml.push_str(&format!(
4059                "<file name=\"{name}\" source=\"original\"><size>{sz}</size><md5>{md5}</md5><sha1>{sha1}</sha1></file>"
4060            ));
4061            meta_files.push(MetadataFile {
4062                name: name.clone(),
4063                source: Some("original".to_string()),
4064                md5: Some(md5),
4065                sha1: Some(sha1),
4066                size: Some(sz),
4067            });
4068        }
4069        xml.push_str(&format!(
4070            "<file name=\"{TEST_IDENTIFIER}{FILES_XML_SUFFIX}\" source=\"original\"><md5>placeholder</md5></file></files>"
4071        ));
4072
4073        let temp_dir = tempfile::tempdir().unwrap();
4074        let item_dir = temp_dir.path().join(TEST_IDENTIFIER);
4075        fs::create_dir_all(&item_dir).unwrap();
4076
4077        // Seed interrupted state on disk:
4078        // 1) a.bin is complete & valid (plus a stale a.bin.part that should be cleaned up)
4079        fs::write(item_dir.join("a.bin"), &file_a).unwrap();
4080        fs::write(item_dir.join("a.bin.part"), b"stale").unwrap();
4081        // 2) b.bin was interrupted after 24 bytes -> b.bin.part exists
4082        fs::write(item_dir.join("b.bin.part"), &file_b[..24]).unwrap();
4083        // 3) c.bin.part has 16 corrupted bytes -> must detect mismatch after resume and re-download cleanly
4084        fs::write(item_dir.join("c.bin.part"), b"CORRUPTED_PREFIX").unwrap();
4085
4086        let range_log = std::sync::Mutex::new(Vec::new());
4087        let client = RangeBackedArchiveClient {
4088            metadata: MetadataResponse {
4089                files: meta_files,
4090                extra: BTreeMap::new(),
4091            },
4092            files_xml: xml.into_bytes(),
4093            files: files_map,
4094            range_log: &range_log,
4095        };
4096
4097        let out = checkeddl_with_client(
4098            &client,
4099            TEST_IDENTIFIER,
4100            Some(temp_dir.path()),
4101            false,
4102            Progress::new(false),
4103        )
4104        .unwrap();
4105        let json_res: serde_json::Value = serde_json::from_slice(&out).unwrap();
4106        assert_eq!(json_res["valid"], true, "{json_res:#}");
4107        assert_eq!(json_res["mismatched_files"], serde_json::json!([]));
4108        assert_eq!(json_res["unexpected_files"], serde_json::json!([]));
4109
4110        assert_eq!(fs::read(item_dir.join("a.bin")).unwrap(), file_a);
4111        assert_eq!(fs::read(item_dir.join("b.bin")).unwrap(), file_b);
4112        assert_eq!(fs::read(item_dir.join("c.bin")).unwrap(), file_c);
4113        assert!(!item_dir.join("a.bin.part").exists());
4114        assert!(!item_dir.join("b.bin.part").exists());
4115        assert!(!item_dir.join("c.bin.part").exists());
4116
4117        let logged = range_log.lock().unwrap().clone();
4118        // a.bin must NOT be downloaded at all (0 HTTP requests)!
4119        assert!(!logged.iter().any(|(f, _)| f == "a.bin"), "{logged:?}");
4120        // b.bin must ONLY be requested starting at offset 24 (24, 40)!
4121        let b_starts: Vec<usize> = logged
4122            .iter()
4123            .filter(|(f, _)| f == "b.bin")
4124            .map(|(_, s)| *s)
4125            .collect();
4126        assert_eq!(b_starts, vec![24, 40]);
4127        // c.bin resumed at 16 first, failed SHA1/MD5 check, then re-downloaded cleanly from 0!
4128        let c_starts: Vec<usize> = logged
4129            .iter()
4130            .filter(|(f, _)| f == "c.bin")
4131            .map(|(_, s)| *s)
4132            .collect();
4133        assert_eq!(c_starts.first().copied(), Some(16));
4134        assert!(c_starts.contains(&0), "{c_starts:?}");
4135    }
4136}