surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! SkillSpector's private uv (M52): when no uv is on `PATH`, "Set up
//! SkillSpector" downloads the pinned uv release ([`super::uv_pin`]) into
//! `<SURJECTION_HOME>/tools/uv/` and runs Prepare with it. Everything that uv
//! writes stays in that folder ([`PrivateUv::env`]), so [`PrivateUv::remove`]
//! undoes it all.
//!
//! ```text
//! tools/uv/
//!   <version>/uv[.exe], uvx[.exe], installed.json
//!   cache/ python/ python-bin/ tool/ tool-bin/ credentials/
//! ```
//!
//! The archive is checked against the compiled size and SHA-256 before it
//! is opened; only the two pinned entries are read from it (anything else
//! is ignored, a link is refused, nothing is written at a path taken from
//! the archive), each is size-capped and checked against its own pinned
//! SHA-256 before it is renamed into place, and `installed.json` is
//! written last. These are real files on purpose (`std::fs`, not
//! [`crate::fs::Fs`]): processes run them.

use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

use serde::{Deserialize, Serialize};

use super::uv_pin::{self, MAX_DOWNLOAD, PinnedFile, PinnedUv};
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::paths::SurjectionHome;
use crate::scan::external::TOOLS_DIR;
use crate::scan::external::download::{
    Download, Hashing, UreqDownload, canceled, copy, finish_file, hash_file, io, make_executable,
};

/// `<SURJECTION_HOME>/<TOOLS_DIR>/<UV_DIR>/`.
pub const UV_DIR: &str = "uv";
/// Written after verification; its absence means "not installed".
const MARKER: &str = "installed.json";

/// One file inside the archive: its path there, SHA-256 and size.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UvFile {
    pub path: String,
    pub sha256: String,
    pub size: u64,
}

impl From<&PinnedFile> for UvFile {
    fn from(pinned: &PinnedFile) -> Self {
        Self {
            path: pinned.path.to_owned(),
            sha256: pinned.sha256.to_owned(),
            size: pinned.size,
        }
    }
}

/// The archive to download and what to take from it ([`super::uv_pin`]'s
/// values, owned, so a test can pin an archive of its own).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UvPin {
    /// The release asset's file name; `.zip`, else a `.tar.gz`.
    pub archive: String,
    pub archive_sha256: String,
    pub archive_size: u64,
    pub uv: UvFile,
    pub uvx: UvFile,
}

impl From<&PinnedUv> for UvPin {
    fn from(pinned: &PinnedUv) -> Self {
        Self {
            archive: pinned.archive.to_owned(),
            archive_sha256: pinned.archive_sha256.to_owned(),
            archive_size: pinned.archive_size,
            uv: UvFile::from(&pinned.uv),
            uvx: UvFile::from(&pinned.uvx),
        }
    }
}

/// What `installed.json` records.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Marker {
    version: String,
    #[serde(flatten)]
    pin: UvPin,
}

/// `<SURJECTION_HOME>/tools/uv`.
pub fn root(home: &SurjectionHome) -> PathBuf {
    home.path.join(TOOLS_DIR).join(UV_DIR)
}

/// The variables that keep a uv started from `root` inside it (see
/// [`PrivateUv::env`]).
pub(super) fn env_in(root: &Path) -> Vec<(String, OsString)> {
    let dir = |name: &str| root.join(name).into_os_string();
    vec![
        ("UV_CACHE_DIR".to_owned(), dir("cache")),
        ("UV_PYTHON_INSTALL_DIR".to_owned(), dir("python")),
        ("UV_PYTHON_BIN_DIR".to_owned(), dir("python-bin")),
        ("UV_PYTHON_INSTALL_BIN".to_owned(), "0".into()),
        ("UV_PYTHON_INSTALL_REGISTRY".to_owned(), "0".into()),
        ("UV_TOOL_DIR".to_owned(), dir("tool")),
        ("UV_TOOL_BIN_DIR".to_owned(), dir("tool-bin")),
        ("UV_CREDENTIALS_DIR".to_owned(), dir("credentials")),
        ("UV_NO_CONFIG".to_owned(), "1".into()),
        ("UV_MANAGED_PYTHON".to_owned(), "1".into()),
    ]
}

/// The private uv of one data folder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrivateUv {
    root: PathBuf,
    version: String,
    pin: UvPin,
}

impl PrivateUv {
    /// The pinned release for this platform; `not_supported_on_os` without
    /// one.
    pub fn pinned(home: &SurjectionHome) -> Result<Self, CoreError> {
        let pin = uv_pin::pinned().ok_or_else(|| {
            CoreError::new(
                ErrorCode::NotSupportedOnOs,
                format!(
                    "Surjection cannot set up uv for {} on {}; install uv yourself \
                     (https://docs.astral.sh/uv/getting-started/installation/)",
                    std::env::consts::OS,
                    std::env::consts::ARCH
                ),
            )
        })?;
        Ok(Self::new(home, uv_pin::VERSION, UvPin::from(pin)))
    }

    /// Another version or archive (tests pin an archive of their own).
    pub fn new(home: &SurjectionHome, version: &str, pin: UvPin) -> Self {
        Self {
            root: root(home),
            version: version.to_owned(),
            pin,
        }
    }

    /// [`PrivateUv::pinned`]; in debug builds, the test archive
    /// `SURJECTION_TEST_UV_ARCHIVE` names instead, when set.
    pub fn for_env(env: &Env, home: &SurjectionHome) -> Result<Self, CoreError> {
        #[cfg(debug_assertions)]
        if let Some(archive) = test_archive(env) {
            let sidecar = test_pin_path(&archive);
            let text = std::fs::read_to_string(&sidecar)
                .map_err(|err| io("cannot read the test uv pin", &sidecar, &err))?;
            let pin = serde_json::from_str(&text).map_err(|err| {
                CoreError::new(
                    ErrorCode::IoError,
                    format!("the test uv pin does not parse: {err}"),
                )
                .with_path(&sidecar)
            })?;
            return Ok(Self::new(home, uv_pin::VERSION, pin));
        }
        #[cfg(not(debug_assertions))]
        let _ = env;
        Self::pinned(home)
    }

    pub fn version(&self) -> &str {
        &self.version
    }

    pub fn pin(&self) -> &UvPin {
        &self.pin
    }

    /// `tools/uv`.
    pub fn root(&self) -> PathBuf {
        self.root.clone()
    }

    /// `tools/uv/<version>`.
    pub fn dir(&self) -> PathBuf {
        self.root.join(&self.version)
    }

    pub fn uv(&self) -> PathBuf {
        self.dir()
            .join(format!("uv{}", std::env::consts::EXE_SUFFIX))
    }

    pub fn uvx(&self) -> PathBuf {
        self.dir()
            .join(format!("uvx{}", std::env::consts::EXE_SUFFIX))
    }

    fn marker(&self) -> Marker {
        Marker {
            version: self.version.clone(),
            pin: self.pin.clone(),
        }
    }

    /// Verified and in place: `installed.json` matches this pin, and `uv`
    /// and `uvx` have the pinned sizes.
    pub fn installed(&self) -> bool {
        let Ok(text) = std::fs::read_to_string(self.dir().join(MARKER)) else {
            return false;
        };
        let Ok(marker) = serde_json::from_str::<Marker>(&text) else {
            return false;
        };
        let sized = |path: PathBuf, size: u64| {
            std::fs::metadata(path).is_ok_and(|meta| meta.is_file() && meta.len() == size)
        };
        marker == self.marker()
            && sized(self.uv(), self.pin.uv.size)
            && sized(self.uvx(), self.pin.uvx.size)
    }

    /// Hashes `uv` and `uvx` against the pin. On a confirmed mismatch (size
    /// or SHA-256) deletes `installed.json` (so it reads as not installed,
    /// and [`PrivateUv::install`] repairs it) and says why. A file that
    /// cannot be read (perhaps only for a moment) fails the check too, but
    /// keeps `installed.json`.
    pub fn verify(&self) -> Result<(), String> {
        for (path, pinned) in [(self.uv(), &self.pin.uv), (self.uvx(), &self.pin.uvx)] {
            match hash_file(&path) {
                Ok((size, digest)) if size == pinned.size && digest == pinned.sha256 => {}
                Ok(_) => {
                    let _ = std::fs::remove_file(self.dir().join(MARKER));
                    return Err(format!(
                        "the uv Surjection set up is not the pinned build ({} has another \
                         SHA-256); set it up again (`surject scanner setup`, or Settings > \
                         Security)",
                        path.display()
                    ));
                }
                Err(err) => {
                    return Err(format!(
                        "the uv Surjection set up cannot be read to check its SHA-256 ({}: {})",
                        path.display(),
                        err.kind()
                    ));
                }
            }
        }
        Ok(())
    }

    /// Downloads the archive to a temp file (size cap, SHA-256 and size
    /// against the pin, else `scanner_verification_failed` and nothing
    /// kept), extracts only the two pinned entries (anything else ignored,
    /// a link refused; each size-capped and checked against its pinned
    /// SHA-256), renames them into `<version>/`, writes `installed.json`
    /// last and removes other versions' folders (never `cache/` or
    /// `python/`). Already installed and verified: nothing is downloaded.
    /// Canceled: `canceled`, partial files removed.
    pub fn install(
        &self,
        download: &dyn Download,
        progress: &mut dyn FnMut(u64, u64),
        cancel: Option<&AtomicBool>,
    ) -> Result<(), CoreError> {
        if self.installed() && self.verify().is_ok() {
            return Ok(());
        }
        for file in [&self.pin.uv, &self.pin.uvx] {
            check_entry_path(&file.path)?;
        }
        if self.pin.uv.path == self.pin.uvx.path {
            return Err(not_pinned("the pin names the same entry for uv and uvx"));
        }
        let dir = self.dir();
        std::fs::create_dir_all(&dir).map_err(|err| io("cannot create folder", &dir, &err))?;
        self.remove_partial_files();
        let archive = crate::apply::temp_path(&dir.join("uv-archive"))?;
        let uv = crate::apply::temp_path(&self.uv())?;
        let uvx = crate::apply::temp_path(&self.uvx())?;
        let mut result = self
            .download_verified(download, &archive, progress, cancel)
            .and_then(|()| self.extract(&archive, &uv, &uvx, cancel));
        if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
            result = Err(canceled());
        }
        let _ = std::fs::remove_file(&archive);
        let placed = result.and_then(|()| {
            make_executable(&uv)?;
            make_executable(&uvx)?;
            let _ = std::fs::remove_file(dir.join(MARKER));
            for (temp, target) in [(&uv, self.uv()), (&uvx, self.uvx())] {
                std::fs::rename(temp, &target)
                    .map_err(|err| io("cannot move uv into place", &target, &err))?;
            }
            Ok(())
        });
        if let Err(err) = placed {
            let _ = std::fs::remove_file(&uv);
            let _ = std::fs::remove_file(&uvx);
            // Folders this install created stay only when something else
            // is in them (`remove_dir` refuses a folder that is not empty).
            let _ = std::fs::remove_dir(&dir);
            let _ = std::fs::remove_dir(&self.root);
            return Err(err);
        }
        let marker = serde_json::to_vec_pretty(&self.marker()).map_err(|err| {
            CoreError::new(ErrorCode::IoError, format!("cannot write {MARKER}: {err}"))
        })?;
        crate::apply::write_atomic(&crate::fs::RealFs, &dir.join(MARKER), &marker)?;
        self.remove_other_versions();
        Ok(())
    }

    fn download_verified(
        &self,
        download: &dyn Download,
        temp: &Path,
        progress: &mut dyn FnMut(u64, u64),
        cancel: Option<&AtomicBool>,
    ) -> Result<(), CoreError> {
        let file =
            std::fs::File::create(temp).map_err(|err| io("cannot create file", temp, &err))?;
        let mut sink = Hashing::new(std::io::BufWriter::new(file));
        let url = uv_pin::download_url(&self.version, &self.pin.archive);
        let size = self.pin.archive_size;
        download.fetch(
            &url,
            &mut sink,
            MAX_DOWNLOAD.max(size),
            &mut |received, total| {
                progress(received, if total == 0 { size } else { total });
            },
            cancel,
        )?;
        let (written, digest) = finish_file(sink, temp)?;
        if written != size || digest != self.pin.archive_sha256 {
            return Err(CoreError::new(
                ErrorCode::ScannerVerificationFailed,
                format!(
                    "the download of uv {} ({}) is not the pinned build (expected {size} bytes \
                     with SHA-256 {}, got {written} bytes with SHA-256 {digest}); nothing was \
                     installed",
                    self.version, self.pin.archive, self.pin.archive_sha256
                ),
            ));
        }
        Ok(())
    }

    /// Writes the pinned `uv` and `uvx` entries of `archive` to `uv` and
    /// `uvx`, each checked against its pin.
    fn extract(
        &self,
        archive: &Path,
        uv: &Path,
        uvx: &Path,
        cancel: Option<&AtomicBool>,
    ) -> Result<(), CoreError> {
        let wanted = [(&self.pin.uv, uv), (&self.pin.uvx, uvx)];
        let mut found = [false; 2];
        let file =
            std::fs::File::open(archive).map_err(|err| io("cannot read file", archive, &err))?;
        let broken = |why: String| {
            not_pinned(&format!(
                "the uv archive {} cannot be read: {why}",
                self.pin.archive
            ))
        };
        if self.pin.archive.ends_with(".zip") {
            let mut zip = zip::ZipArchive::new(std::io::BufReader::new(file))
                .map_err(|err| broken(err.to_string()))?;
            for index in 0..zip.len() {
                let mut entry = zip.by_index(index).map_err(|err| broken(err.to_string()))?;
                let name = entry
                    .name()
                    .map_err(|err| broken(err.to_string()))?
                    .into_owned();
                let Some(at) = wanted.iter().position(|(pin, _)| pin.path == name) else {
                    continue;
                };
                let (pin, target) = wanted[at];
                check_found(&mut found[at], pin, entry.is_file())?;
                extract_entry(&mut entry, pin, target, cancel)?;
            }
        } else {
            let gz = flate2::read::GzDecoder::new(std::io::BufReader::new(file));
            let mut tar = tar::Archive::new(gz);
            let entries = tar.entries().map_err(|err| broken(err.to_string()))?;
            for entry in entries {
                let mut entry = entry.map_err(|err| broken(err.to_string()))?;
                let name = entry.path_bytes().into_owned();
                let Some(at) = wanted
                    .iter()
                    .position(|(pin, _)| pin.path.as_bytes() == name.as_slice())
                else {
                    continue;
                };
                let (pin, target) = wanted[at];
                let regular = matches!(
                    entry.header().entry_type(),
                    tar::EntryType::Regular | tar::EntryType::Continuous
                );
                check_found(&mut found[at], pin, regular)?;
                extract_entry(&mut entry, pin, target, cancel)?;
            }
        }
        for ((pin, _), found) in wanted.iter().zip(found) {
            if !found {
                return Err(not_pinned(&format!(
                    "the uv archive {} has no {}; nothing was installed",
                    self.pin.archive, pin.path
                )));
            }
        }
        Ok(())
    }

    /// Deletes `tools/uv` entirely: both binaries, uv's cache (with
    /// SkillSpector's environment) and the Python it downloaded. `false`
    /// when there was nothing.
    pub fn remove(&self) -> Result<bool, CoreError> {
        remove_root(&self.root)
    }

    /// The variables that keep this uv inside [`PrivateUv::root`], set
    /// after the scanner's passed variables (replacing any `UV_*` the user
    /// set): its cache, Python installs and their links, tools and
    /// credentials in their own folders there, no Windows registry entries,
    /// no user or project `uv.toml`, and only the Python it downloads.
    pub fn env(&self) -> Vec<(String, OsString)> {
        env_in(&self.root)
    }

    /// Deletes partial files (`.*.surjection-*.tmp`) a killed install left in
    /// [`PrivateUv::dir`].
    fn remove_partial_files(&self) {
        let Ok(entries) = std::fs::read_dir(self.dir()) else {
            return;
        };
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            if name.starts_with('.') && name.contains(".surjection-") && name.ends_with(".tmp") {
                let _ = std::fs::remove_file(entry.path());
            }
        }
    }

    /// Other versions' folders (a version starts with a digit): removed
    /// after an install. uv's own folders stay.
    fn remove_other_versions(&self) {
        let Ok(entries) = std::fs::read_dir(&self.root) else {
            return;
        };
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            if name != self.version
                && name.starts_with(|c: char| c.is_ascii_digit())
                && entry.file_type().is_ok_and(|kind| kind.is_dir())
            {
                let _ = std::fs::remove_dir_all(entry.path());
            }
        }
    }
}

/// Deletes `root` (`tools/uv`); `false` when it was not there.
pub(super) fn remove_root(root: &Path) -> Result<bool, CoreError> {
    if !root.exists() {
        return Ok(false);
    }
    std::fs::remove_dir_all(root).map_err(|err| io("cannot remove folder", root, &err))?;
    Ok(true)
}

/// `scanner_verification_failed` with `why`.
fn not_pinned(why: &str) -> CoreError {
    CoreError::new(ErrorCode::ScannerVerificationFailed, why.to_owned())
}

/// A pinned entry path is relative, `/`-separated and has no `.` or `..`
/// component (never written as is, but a pin like that is wrong).
pub(super) fn check_entry_path(path: &str) -> Result<(), CoreError> {
    let fine = !path.is_empty()
        && !path.starts_with('/')
        && !path.contains('\\')
        && !path.contains(':')
        && path
            .split('/')
            .all(|part| !part.is_empty() && part != "." && part != "..");
    if fine {
        Ok(())
    } else {
        Err(not_pinned(&format!(
            "the uv pin names an unsafe archive entry ({path})"
        )))
    }
}

/// The second copy of an entry, or one that is a link or a folder, is
/// refused.
fn check_found(found: &mut bool, pin: &UvFile, regular: bool) -> Result<(), CoreError> {
    if *found {
        return Err(not_pinned(&format!(
            "the uv archive holds {} twice; nothing was installed",
            pin.path
        )));
    }
    if !regular {
        return Err(not_pinned(&format!(
            "{} in the uv archive is not a regular file (a link or a folder); nothing was \
             installed",
            pin.path
        )));
    }
    *found = true;
    Ok(())
}

/// Streams one entry into `target`, at most its pinned size, and checks
/// its size and SHA-256.
fn extract_entry(
    reader: &mut dyn Read,
    pin: &UvFile,
    target: &Path,
    cancel: Option<&AtomicBool>,
) -> Result<(), CoreError> {
    let file =
        std::fs::File::create(target).map_err(|err| io("cannot create file", target, &err))?;
    let mut sink = Hashing::new(std::io::BufWriter::new(file));
    // The pinned size is the cap (the pin test keeps real pins under
    // `uv_pin::MAX_FILE`); a test pin of a debug stub can be larger.
    let max = pin.size;
    copy(reader, &mut sink, max, pin.size, &mut |_, _| {}, cancel).map_err(|err| {
        if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
            canceled()
        } else if err.kind() == std::io::ErrorKind::FileTooLarge {
            not_pinned(&format!(
                "{} in the uv archive is larger than the pinned build; nothing was installed",
                pin.path
            ))
        } else {
            not_pinned(&format!(
                "{} in the uv archive cannot be read: {err}",
                pin.path
            ))
        }
    })?;
    let (written, digest) = finish_file(sink, target)?;
    if written != pin.size || digest != pin.sha256 {
        return Err(not_pinned(&format!(
            "{} in the uv archive is not the pinned build (expected {} bytes with SHA-256 {}, \
             got {written} bytes with SHA-256 {digest}); nothing was installed",
            pin.path, pin.size, pin.sha256
        )));
    }
    Ok(())
}

/// The test archive `SURJECTION_TEST_UV_ARCHIVE` names (absolute), in debug
/// builds.
#[cfg(debug_assertions)]
fn test_archive(env: &Env) -> Option<PathBuf> {
    env.var(crate::brand::TEST_UV_ARCHIVE_ENV_VAR)
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
}

/// `<archive>.pin.json`: the [`UvPin`] of a test archive.
pub fn test_pin_path(archive: &Path) -> PathBuf {
    let mut name = archive.file_name().unwrap_or_default().to_owned();
    name.push(".pin.json");
    archive.with_file_name(name)
}

/// The [`Download`] the private uv is fetched with: [`UreqDownload`] over
/// the injected [`Env`]'s proxy. In debug builds with
/// `SURJECTION_TEST_UV_ARCHIVE` set, the test archive served from disk.
pub fn uv_download(env: &Env) -> Box<dyn Download> {
    #[cfg(debug_assertions)]
    if let Some(archive) = test_archive(env) {
        return Box::new(TestArchive(archive));
    }
    Box::new(UreqDownload::new(env))
}

/// Serves a test archive from disk for its own file name (debug builds).
#[cfg(debug_assertions)]
#[derive(Debug)]
struct TestArchive(PathBuf);

#[cfg(debug_assertions)]
impl Download for TestArchive {
    fn fetch(
        &self,
        url: &str,
        out: &mut dyn std::io::Write,
        max: u64,
        progress: &mut dyn FnMut(u64, u64),
        cancel: Option<&AtomicBool>,
    ) -> Result<u64, CoreError> {
        let failed = |why: String| CoreError::new(ErrorCode::ScannerDownloadFailed, why);
        let name = self.0.file_name().unwrap_or_default().to_string_lossy();
        if !url.ends_with(&format!("/{name}")) {
            return Err(failed(format!("the test archive is not {url}")));
        }
        let mut file = std::fs::File::open(&self.0)
            .map_err(|err| failed(format!("cannot read the test archive: {err}")))?;
        let total = file.metadata().map(|meta| meta.len()).unwrap_or(0);
        copy(&mut file, out, max, total, progress, cancel).map_err(|err| {
            if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
                canceled()
            } else {
                failed(err.to_string())
            }
        })
    }
}