bunsen 0.37.0

bunsen is a batteries included common library for burn
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
//! The pretrained cache: digest-pinned resources under the disk cache.

use std::{
    collections::BTreeMap,
    fmt,
    fs,
    io::Write,
    path::{
        Path,
        PathBuf,
    },
};

use sha2::{
    Digest,
    Sha256,
};

use super::{
    LoadedResources,
    Resource,
    ResourceMap,
    Source,
};
use crate::{
    data::cache::{
        BunsenDiskCache,
        BunsenDiskCacheOptions,
        partial_path,
        verify_sha256,
    },
    errors::{
        BunsenError,
        BunsenResult,
        DigestMismatch,
        DigestOrigin,
        LookupError,
        LookupProblem,
        sys_at,
    },
};
#[cfg(feature = "fetch")]
use crate::{
    data::cache::{
        FetchJob,
        FetchOutcome,
        FetchPolicy,
    },
    errors::Multiple,
};

/// The directory under the cache dir that holds a pretrained's resources:
/// `<cache>/pretrained/<kit>/<namespace>/<sha256>/<file>`.
pub const PRETRAINED_DIR: &str = "pretrained";

/// Options for [`PretrainedCache`], which [`PretrainedCache::new`] opens a
/// cache with.
///
/// The default is online, with the disk cache's default directories and
/// observers, no local-dir overrides, local dirs trusted unhashed, and the
/// default fetch policy.
#[derive(Clone, Debug, Default)]
pub struct PretrainedCacheOptions {
    /// The disk cache underneath: where the cache directory is, and who
    /// watches transfers.
    pub disk: BunsenDiskCacheOptions,

    /// Never reach the network: a resource not already local is an error.
    pub offline: bool,

    /// Overrides for [`Source::LocalDir`] sources, by the source's name:
    /// where another tool's directory is on this machine.
    pub local_dirs: BTreeMap<String, PathBuf>,

    /// Hash a pinned file found in a local-dir source before it is used in
    /// place. Off by default: a local dir is a "trust me" source, and
    /// hashing a 3 GB checkpoint on every run is not trust. A caller that
    /// is not sure has `verify_sha256`.
    pub verify_local_dirs: bool,

    /// How the remote resources of a map are fetched together.
    #[cfg(feature = "fetch")]
    pub fetch: FetchPolicy,
}

impl PretrainedCacheOptions {
    /// Sets the disk cache options.
    pub fn with_disk(
        mut self,
        disk: BunsenDiskCacheOptions,
    ) -> Self {
        self.disk = disk;
        self
    }

    /// Sets whether the network is off limits.
    pub fn with_offline(
        mut self,
        offline: bool,
    ) -> Self {
        self.offline = offline;
        self
    }

    /// Overrides the directory of the local-dir source called `name`.
    pub fn with_local_dir(
        mut self,
        name: impl Into<String>,
        dir: impl Into<PathBuf>,
    ) -> Self {
        self.local_dirs.insert(name.into(), dir.into());
        self
    }

    /// Sets whether a pinned local-dir file is hashed before use.
    pub fn with_verify_local_dirs(
        mut self,
        verify: bool,
    ) -> Self {
        self.verify_local_dirs = verify;
        self
    }

    /// Sets how a map's remote resources are fetched together.
    #[cfg(feature = "fetch")]
    pub fn with_fetch_policy(
        mut self,
        fetch: FetchPolicy,
    ) -> Self {
        self.fetch = fetch;
        self
    }
}

/// Where a resolved file came from, this run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Provenance {
    /// Already in the cache.
    Cached,
    /// Found in another tool's directory, or given as a path, and used in
    /// place.
    LocalDir,
    /// Fetched from a URL, checked, and written to the cache.
    Downloaded,
    /// Linked into the binary, checked, and written to the cache.
    Bundled,
}

impl fmt::Display for Provenance {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        f.write_str(match self {
            Self::Cached => "cached",
            Self::LocalDir => "local dir",
            Self::Downloaded => "downloaded",
            Self::Bundled => "bundled",
        })
    }
}

/// A local file holding a resource.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedResource {
    /// The file.
    pub path: PathBuf,

    /// Where it came from.
    pub provenance: Provenance,
}

/// Where a resource stands before anything is fetched, for a listing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheStatus {
    /// In the cache.
    Cached,
    /// Not in the cache, but another tool's directory has a file of that
    /// name, unchecked.
    LocalDir,
    /// Not in the cache, but linked into the binary.
    Bundled,
    /// Only a URL.
    Remote,
}

impl fmt::Display for CacheStatus {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        f.write_str(match self {
            Self::Cached => "cached",
            Self::LocalDir => "local dir",
            Self::Bundled => "bundled",
            Self::Remote => "remote",
        })
    }
}

/// What a resource's local lookup found.
enum Local {
    /// A file, with where it came from.
    Found(ResolvedResource),

    /// Nothing local: the URLs to try, in order, and where the file lands.
    Remote { dest: PathBuf, urls: Vec<String> },
}

/// A resource a map load has to fetch.
#[cfg_attr(not(feature = "fetch"), allow(dead_code))]
struct RemotePart {
    key: String,
    dest: PathBuf,
    urls: Vec<String>,
    sha256: Option<String>,
}

fn remote_keys(remote: &[RemotePart]) -> String {
    remote
        .iter()
        .map(|r| r.key.as_str())
        .collect::<Vec<_>>()
        .join(", ")
}

/// Digest-pinned resources under the disk cache's cache directory: where a
/// [`ResourceMap`]'s files are brought local.
///
/// [`BunsenDiskCache`] decides *where* the cache directory is; this decides
/// *what is trusted there*. A caller opens one from
/// [`PretrainedCacheOptions`] (offline or not, local-dir overrides and
/// verification, and with `fetch` the batch policy) and passes it to every
/// load. [`Deferred::load`](super::Deferred::load) calls
/// [`load`](Self::load) between the kit hook's
/// [`plan`](super::Construct::plan) and
/// [`construct`](super::Construct::construct), and the
/// [`LoadedResources`] it returns are what the hook builds from. A
/// [`PretrainedFactory`](super::PretrainedFactory) hands the cache to its
/// providers too, so that a hub ([`HfProvider`](super::HfProvider)) can
/// keep what it asked for. [`status`](Self::status) and
/// [`map_status`](Self::map_status) answer a listing without touching any
/// bytes.
///
/// # Cache layout
///
/// ```text
/// <cache>/pretrained/<kit>/<namespace>/<sha256>/<file>
/// ```
///
/// `<kit>` is the hook's [`KIT`](super::Construct::KIT), `<namespace>` the
/// resource's (who published it), and `<file>` its file name. An unpinned
/// resource sits under a cache key in place of `<sha256>`: one derived from
/// its first URL ([`url_to_cache_key`](super::url_to_cache_key)), or its
/// file name when it has no URL. [`resource_path`](Self::resource_path)
/// names the path, present or not.
///
/// # Trust model
///
/// The digest in the path is the pin. A file at that path was verified when
/// it was written, so it is trusted on later runs without re-hashing 3 GB,
/// and a re-pinned model cannot collide with a stale one. The cache's own
/// writes go to a `.partial` beside the path and are renamed into place
/// once checked, so a write cut short leaves nothing there to trust. The
/// cache trusts the path whoever wrote it: a download, bundled bytes, or a
/// build script or a deployment that laid the directory out ahead of time.
/// That is what makes a populated cache directory a bundle.
///
/// A local-dir source is a "trust me" source: its file is used in place,
/// and hashed first only when
/// [`verify_local_dirs`](PretrainedCacheOptions::verify_local_dirs) asks.
/// An unpinned file is trusted by its name alone.
///
/// # Source order
///
/// [`resolve`](Self::resolve), for one resource, and [`load`](Self::load),
/// for a map, look in the same order:
///
/// 1. the cache path: a file there is [`Provenance::Cached`];
/// 2. the resource's local sources, in the order listed: a [`Source::LocalDir`]
///    that has the file is used in place, and [`Source::Bundled`] bytes are
///    checked against the digest, written to a `.partial`, and renamed into
///    place;
/// 3. only then its [`Source::Url`]s, in the order listed: streamed to a
///    `.partial`, checked against the digest when pinned and against the length
///    the server sent, and renamed into place. [`load`](Self::load) fetches
///    every remote resource of a map together, under the options' fetch policy.
///
/// Nothing is linked or copied into the cache: only a download, or bundled
/// bytes, write there. Every transfer reports to the disk cache's observer
/// stack. A resource that only a URL can supply is a
/// [`Policy`](crate::errors::BunsenErrorKind::Policy) error on an offline
/// cache, and [`Unsupported`](crate::errors::BunsenErrorKind::Unsupported)
/// without the `fetch` feature, which step 3 needs.
pub struct PretrainedCache {
    disk: BunsenDiskCache,
    offline: bool,
    local_dirs: BTreeMap<String, PathBuf>,
    verify_local_dirs: bool,
    #[cfg(feature = "fetch")]
    fetch: FetchPolicy,
}

impl PretrainedCache {
    /// Opens the cache.
    ///
    /// # Errors
    /// As [`BunsenDiskCache::new`].
    pub fn new(options: PretrainedCacheOptions) -> BunsenResult<Self> {
        Ok(Self {
            disk: BunsenDiskCache::new(options.disk)?,
            offline: options.offline,
            local_dirs: options.local_dirs,
            verify_local_dirs: options.verify_local_dirs,
            #[cfg(feature = "fetch")]
            fetch: options.fetch,
        })
    }

    /// The disk cache underneath.
    pub fn disk(&self) -> &BunsenDiskCache {
        &self.disk
    }

    /// The cache directory.
    pub fn cache_dir(&self) -> &Path {
        self.disk.cache_dir()
    }

    /// Whether the network is off limits.
    pub fn offline(&self) -> bool {
        self.offline
    }

    /// Whether a pinned local-dir file is hashed before use.
    pub fn verify_local_dirs(&self) -> bool {
        self.verify_local_dirs
    }

    /// The local-dir overrides, by source name.
    pub fn local_dirs(&self) -> &BTreeMap<String, PathBuf> {
        &self.local_dirs
    }

    /// The directory a local-dir source resolves to: the override for its
    /// name, else the directory the source carries.
    pub fn local_dir(
        &self,
        source: &Source,
    ) -> Option<PathBuf> {
        match source {
            Source::LocalDir { name, dir } => {
                self.local_dirs.get(name).cloned().or_else(|| dir.clone())
            }
            Source::Url(_) | Source::Bundled(_) => None,
        }
    }

    /// Where a resource's file lives in the cache, present or not:
    /// `pretrained/<kit>/<namespace>/<sha256>/<file>` when it is pinned,
    /// and `pretrained/<kit>/<namespace>/<cache key>/<file>` when not.
    pub fn resource_path(
        &self,
        kit: &str,
        res: &Resource,
    ) -> PathBuf {
        let pin = match &res.sha256 {
            Some(sha256) => sha256.clone(),
            None => res.cache_key(),
        };
        self.disk.cache_path(
            &[PRETRAINED_DIR, kit, res.namespace.as_str(), pin.as_str()],
            &res.file,
        )
    }

    /// Where a resource stands, without fetching or hashing anything.
    pub fn status(
        &self,
        kit: &str,
        res: &Resource,
    ) -> CacheStatus {
        if self.resource_path(kit, res).is_file() {
            return CacheStatus::Cached;
        }
        for source in &res.sources {
            match source {
                Source::LocalDir { .. } => {
                    if let Some(dir) = self.local_dir(source)
                        && dir.join(&res.file).is_file()
                    {
                        return CacheStatus::LocalDir;
                    }
                }
                Source::Bundled(_) => return CacheStatus::Bundled,
                Source::Url(_) => {}
            }
        }
        CacheStatus::Remote
    }

    /// Where every resource of `map` stands, by key.
    pub fn map_status(
        &self,
        kit: &str,
        map: &ResourceMap,
    ) -> BTreeMap<String, CacheStatus> {
        map.resources
            .iter()
            .map(|(key, res)| (key.clone(), self.status(kit, res)))
            .collect()
    }

    /// Brings a resource local, and says where it came from.
    ///
    /// The cache is consulted first; then each source in the resource's
    /// order: a file in another tool's directory is used in place, hashed
    /// first only when the options ask; bytes linked into the binary are
    /// checked and written into the cache; the URLs are fetched in order,
    /// a mirror that is down retried as the options' fetch policy says,
    /// checked, and written into the cache. Nothing is linked or copied
    /// in.
    ///
    /// # Errors
    /// When nothing local matches:
    /// [`Policy`](crate::errors::BunsenErrorKind::Policy) if the cache is
    /// offline; [`Unsupported`](crate::errors::BunsenErrorKind::Unsupported)
    /// if the `fetch` feature is off;
    /// [`Lookup`](crate::errors::BunsenErrorKind::Lookup), with a
    /// [`LookupError`] for the path a local source names, if the resource has
    /// no URL (a given path that is not there).
    /// [`InvalidResource`](crate::errors::BunsenErrorKind::InvalidResource),
    /// with a [`DigestMismatch`], if a download's or bundled bytes' digest
    /// does not match, or a local-dir file's when the options verify them.
    /// [`Illegal`](crate::errors::BunsenErrorKind::Illegal), with a
    /// [`ConstraintError`](crate::errors::ConstraintError), for a bundled
    /// source without a digest, as [`Resource::validate`]. A transfer
    /// failure is sorted by the disk cache's fetch (a missing or refused URL
    /// is a `Lookup`, an unreachable one
    /// [`Unavailable`](crate::errors::BunsenErrorKind::Unavailable)), and a
    /// file-system failure by [`sys_at`].
    pub fn resolve(
        &self,
        kit: &str,
        res: &Resource,
    ) -> BunsenResult<ResolvedResource> {
        match self.resolve_local(kit, res)? {
            Local::Found(found) => Ok(found),
            Local::Remote { dest, urls } => {
                if self.offline {
                    return Err(BunsenError::policy(format!(
                        "not in the cache ({}), and the cache is offline",
                        dest.display()
                    ))
                    .context(&res.key));
                }
                let urls: Vec<&str> = urls.iter().map(String::as_str).collect();
                self.download(dest, &urls, res.sha256.as_deref())
            }
        }
    }

    /// Every resource of `map` local, under `kit`, all or nothing.
    ///
    /// Each resource is looked for locally as [`resolve`](Self::resolve)
    /// does; the ones only a URL can supply are then fetched together,
    /// under the options' fetch policy, into the cache. A resource that
    /// cannot be had fails the load with its key named; the files that did
    /// land stay.
    ///
    /// # Errors
    /// As [`resolve`](Self::resolve) for a resource looked for locally.
    /// Under a frame naming the map:
    /// [`Policy`](crate::errors::BunsenErrorKind::Policy) naming the remote
    /// keys when the cache is offline, and
    /// [`Unsupported`](crate::errors::BunsenErrorKind::Unsupported) when the
    /// `fetch` feature is off; when some remote resources did not land, a
    /// [`Multiple`](crate::errors::Multiple) of each one's error, labelled by
    /// its key, whose kind comes from them.
    pub fn load(
        &self,
        kit: &str,
        map: &ResourceMap,
    ) -> BunsenResult<LoadedResources> {
        let mut parts = BTreeMap::new();
        let mut remote = Vec::new();
        for (key, res) in &map.resources {
            match self.resolve_local(kit, res)? {
                Local::Found(found) => {
                    parts.insert(key.clone(), found);
                }
                Local::Remote { dest, urls } => remote.push(RemotePart {
                    key: key.clone(),
                    dest,
                    urls,
                    sha256: res.sha256.clone(),
                }),
            }
        }
        if !remote.is_empty() {
            if self.offline {
                return Err(BunsenError::policy(format!(
                    "not in the cache, and the cache is offline: {}",
                    remote_keys(&remote)
                ))
                .context(&map.name));
            }
            self.fetch_remote(&map.name, remote, &mut parts)?;
        }
        Ok(LoadedResources {
            map: map.clone(),
            parts,
        })
    }

    /// The cache, then the local sources in order; the URLs otherwise.
    fn resolve_local(
        &self,
        kit: &str,
        res: &Resource,
    ) -> BunsenResult<Local> {
        let dest = self.resource_path(kit, res);
        if dest.is_file() {
            return Ok(Local::Found(ResolvedResource {
                path: dest,
                provenance: Provenance::Cached,
            }));
        }

        let mut urls = Vec::new();
        let mut tried = Vec::new();
        for source in &res.sources {
            match source {
                Source::LocalDir { .. } => {
                    let Some(dir) = self.local_dir(source) else {
                        continue;
                    };
                    let path = dir.join(&res.file);
                    if !path.is_file() {
                        tried.push(path);
                        continue;
                    }
                    if self.verify_local_dirs
                        && let Some(sha256) = &res.sha256
                    {
                        verify_sha256(&path, sha256)?;
                    }
                    return Ok(Local::Found(ResolvedResource {
                        path,
                        provenance: Provenance::LocalDir,
                    }));
                }
                Source::Bundled(bytes) => {
                    return Ok(Local::Found(self.write_bundled(res, &dest, bytes.0)?));
                }
                Source::Url(url) => urls.push(url.clone()),
            }
        }

        if urls.is_empty() {
            // Nothing to fetch: the file is missing where a local source
            // says it is, a given path say.
            let missing = tried
                .first()
                .cloned()
                .unwrap_or_else(|| PathBuf::from(&res.file));
            let looked_in = tried
                .iter()
                .map(|p| format!("\n  {}", p.display()))
                .collect::<String>();
            return Err(
                BunsenError::lookup(LookupError::path(missing, LookupProblem::Missing))
                    .with_details(format!("no URL to fetch it from; looked in:{looked_in}"))
                    .context(&res.key),
            );
        }
        Ok(Local::Remote { dest, urls })
    }

    /// Bytes linked into the binary, checked against the resource's digest,
    /// written beside `dest`, the resource's cache path, and renamed into
    /// place: `dest` holds the whole checked file or nothing, as after a
    /// download.
    fn write_bundled(
        &self,
        res: &Resource,
        dest: &Path,
        bytes: &[u8],
    ) -> BunsenResult<ResolvedResource> {
        let Some(sha256) = res.sha256.as_deref() else {
            return Err(BunsenError::from(Resource::bundled_without_digest()).context(&res.key));
        };
        let found = Sha256::digest(bytes)
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect::<String>();
        if found != sha256 {
            return Err(DigestMismatch::new(&res.key, DigestOrigin::Bundled, sha256, found).into());
        }
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent).map_err(sys_at("create", parent))?;
        }
        let partial = partial_path(dest);
        let written = (|| -> std::io::Result<()> {
            let mut file = fs::File::create(&partial)?;
            file.write_all(bytes)?;
            file.sync_all()?;
            fs::rename(&partial, dest)
        })();
        if let Err(e) = written {
            let _ = fs::remove_file(&partial);
            return Err(sys_at("write", dest)(e));
        }
        Ok(ResolvedResource {
            path: dest.to_path_buf(),
            provenance: Provenance::Bundled,
        })
    }

    /// The URLs, in order, through the disk cache's fetch, retrying a mirror
    /// that is down as the options' fetch policy says.
    #[cfg(feature = "fetch")]
    fn download(
        &self,
        dest: PathBuf,
        urls: &[&str],
        sha256: Option<&str>,
    ) -> BunsenResult<ResolvedResource> {
        self.disk
            .fetch_from_urls_retrying(urls, &dest, sha256, self.fetch.retries)?;
        Ok(ResolvedResource {
            path: dest,
            provenance: Provenance::Downloaded,
        })
    }

    /// Without the `fetch` feature there is no network: not local is
    /// unsupported.
    #[cfg(not(feature = "fetch"))]
    fn download(
        &self,
        dest: PathBuf,
        _urls: &[&str],
        _sha256: Option<&str>,
    ) -> BunsenResult<ResolvedResource> {
        Err(BunsenError::unsupported(format!(
            "{}: not local, and fetching needs the `fetch` feature",
            dest.display()
        )))
    }

    /// The remote parts, together, under the fetch policy.
    #[cfg(feature = "fetch")]
    fn fetch_remote(
        &self,
        name: &str,
        remote: Vec<RemotePart>,
        parts: &mut BTreeMap<String, ResolvedResource>,
    ) -> BunsenResult<()> {
        let jobs: Vec<FetchJob> = remote
            .iter()
            .map(|r| {
                let mut job = FetchJob::new(r.urls.clone(), r.dest.clone());
                job.sha256 = r.sha256.clone();
                job
            })
            .collect();
        let report = self.disk.fetch_many(&jobs, &self.fetch);

        let mut failed = Vec::new();
        let mut skipped = Vec::new();
        for (outcome, part) in report.outcomes.into_iter().zip(remote) {
            let provenance = match outcome {
                FetchOutcome::Cached(_) => Provenance::Cached,
                FetchOutcome::Fetched(_) => Provenance::Downloaded,
                FetchOutcome::Failed { error, .. } => {
                    failed.push((part.key, error));
                    continue;
                }
                FetchOutcome::Skipped { .. } => {
                    skipped.push(part.key);
                    continue;
                }
            };
            parts.insert(
                part.key,
                ResolvedResource {
                    path: part.dest,
                    provenance,
                },
            );
        }
        if failed.is_empty() && skipped.is_empty() {
            return Ok(());
        }
        let mut summary = format!(
            "{} of {} resources did not land",
            failed.len() + skipped.len(),
            jobs.len()
        );
        if !skipped.is_empty() {
            summary.push_str(&format!(
                "; skipped after a failure: {}",
                skipped.join(", ")
            ));
        }
        Err(BunsenError::from(Multiple::new(summary, failed)).context(name))
    }

    /// Without the `fetch` feature there is no network: not local is
    /// unsupported.
    #[cfg(not(feature = "fetch"))]
    fn fetch_remote(
        &self,
        name: &str,
        remote: Vec<RemotePart>,
        _parts: &mut BTreeMap<String, ResolvedResource>,
    ) -> BunsenResult<()> {
        Err(BunsenError::unsupported(format!(
            "not local, and fetching needs the `fetch` feature: {}",
            remote_keys(&remote)
        ))
        .context(name))
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;
    use crate::{
        data::cache::testing::ABC_SHA256,
        errors::{
            BunsenErrorKind,
            ConstraintError,
            testing::{
                ErrorMatcher,
                predicate,
                text,
            },
        },
    };
    #[cfg(feature = "fetch")]
    use crate::{
        data::cache::{
            OnFailure,
            testing::{
                refused_url,
                serve_once,
            },
        },
        errors::testing::not,
    };

    fn cache_in(
        dir: &Path,
        offline: bool,
    ) -> PretrainedCache {
        PretrainedCache::new(
            PretrainedCacheOptions::default()
                .with_disk(
                    BunsenDiskCacheOptions::default()
                        .with_cache_dir(Some(dir.join("cache")))
                        .without_transfer_observers(),
                )
                .with_offline(offline),
        )
        .unwrap()
    }

    use crate::data::pretrained::BundledBytes;

    fn url(u: &str) -> Source {
        Source::Url(u.to_string())
    }

    /// `<key>.bin`, three bytes when pinned to `abc`, from `sources`.
    fn res(
        key: &str,
        sha256: Option<&str>,
        sources: Vec<Source>,
    ) -> Resource {
        Resource {
            key: key.to_string(),
            file: format!("{key}.bin"),
            sha256: sha256.map(str::to_string),
            kind: None,
            namespace: "prov".to_string(),
            sources,
        }
    }

    fn local_dir(dir: &Path) -> Source {
        Source::LocalDir {
            name: "up".to_string(),
            dir: Some(dir.to_path_buf()),
        }
    }

    /// Bundled bytes land in the cache under the resource's digest on
    /// first use and are `Cached` after; wrong bytes are refused and
    /// nothing is written.
    #[test]
    fn test_a_bundled_source_lands_under_its_digest() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path(), true);

        let bundled = res(
            "abc",
            Some(ABC_SHA256),
            vec![Source::Bundled(BundledBytes(b"abc"))],
        );
        bundled.validate().unwrap();
        assert_eq!(cache.status("kit", &bundled), CacheStatus::Bundled);
        let resolved = cache.resolve("kit", &bundled).unwrap();
        assert_eq!(resolved.provenance, Provenance::Bundled);
        assert_eq!(resolved.path, cache.resource_path("kit", &bundled));
        assert_eq!(std::fs::read(&resolved.path).unwrap(), b"abc");
        assert_eq!(cache.status("kit", &bundled), CacheStatus::Cached);
        assert_eq!(
            cache.resolve("kit", &bundled).unwrap().provenance,
            Provenance::Cached
        );

        let wrong = res(
            "abd",
            Some(ABC_SHA256),
            vec![Source::Bundled(BundledBytes(b"abd"))],
        );
        ErrorMatcher::kind(BunsenErrorKind::InvalidResource)
            .message_contains("not the pinned")
            .cause(predicate("a bundled mismatch", |c: &DigestMismatch| {
                c.origin == DigestOrigin::Bundled && c.subject == "abd" && c.expected == ABC_SHA256
            }))
            .assert_err(&cache.resolve("kit", &wrong));
        assert!(!cache.resource_path("kit", &wrong).exists());

        // The cache checks the rule `validate` does, with the same error.
        let unpinned = res("abe", None, vec![Source::Bundled(BundledBytes(b"abe"))]);
        let unpinned_err = |e: &BunsenError| {
            ErrorMatcher::kind(BunsenErrorKind::Illegal)
                .display(text::eq(
                    "abe: Resource.sha256: a bundled source needs a digest to be cached under",
                ))
                .has_cause::<ConstraintError>()
                .assert(e);
        };
        unpinned_err(&unpinned.validate().unwrap_err());
        unpinned_err(&cache.resolve("kit", &unpinned).unwrap_err());

        // The local dir comes first when it has the file; the bundle is
        // next; a URL after a bundle is never needed.
        let up = dir.path().join("up");
        std::fs::create_dir_all(&up).unwrap();
        std::fs::write(up.join("abf.bin"), b"abc").unwrap();
        let ordered = res(
            "abf",
            Some(ABC_SHA256),
            vec![
                local_dir(&up),
                Source::Bundled(BundledBytes(b"abc")),
                url("https://a.example/abf.bin"),
            ],
        );
        assert_eq!(cache.status("kit", &ordered), CacheStatus::LocalDir);
        assert_eq!(
            cache.resolve("kit", &ordered).unwrap().provenance,
            Provenance::LocalDir
        );
        let map = ResourceMap::new("m").with_resource(bundled.clone());
        let loaded = cache.load("kit", &map).unwrap();
        assert_eq!(loaded.get("abc").unwrap().provenance, Provenance::Cached);
    }

    /// Bundled bytes are written beside the cache path and renamed into
    /// place, as a download is, so the path holds the whole checked file or
    /// nothing. What a write cut short at the path would leave is trusted
    /// on the next run; a link at the path, which a write in place follows
    /// out of the cache, shows where the bytes go.
    #[cfg(unix)]
    #[test]
    fn test_a_bundled_write_is_renamed_into_place() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path(), true);
        let bundled = res(
            "abc",
            Some(ABC_SHA256),
            vec![Source::Bundled(BundledBytes(b"abc"))],
        );
        let dest = cache.resource_path("kit", &bundled);
        fs::create_dir_all(dest.parent().unwrap()).unwrap();

        // A truncated file at the path is the pin's: trusted, not re-hashed.
        fs::write(&dest, b"ab").unwrap();
        assert_eq!(
            cache.resolve("kit", &bundled).unwrap().provenance,
            Provenance::Cached
        );
        fs::remove_file(&dest).unwrap();

        let outside = dir.path().join("outside.bin");
        std::os::unix::fs::symlink(&outside, &dest).unwrap();
        assert_eq!(
            cache.resolve("kit", &bundled).unwrap().provenance,
            Provenance::Bundled
        );
        assert!(
            !outside.exists(),
            "the bytes were written through the cache path"
        );
        assert!(fs::symlink_metadata(&dest).unwrap().file_type().is_file());
        assert_eq!(fs::read(&dest).unwrap(), b"abc");
        assert!(!partial_path(&dest).exists());
    }

    #[test]
    fn test_resource_paths_by_pin() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path(), true);
        let root = dir.path().join("cache").join("pretrained");

        let pinned = res(
            "abc",
            Some(ABC_SHA256),
            vec![url("https://a.example/abc.bin")],
        );
        assert_eq!(
            cache.resource_path("kit", &pinned),
            root.join("kit")
                .join("prov")
                .join(ABC_SHA256)
                .join("abc.bin")
        );

        let unpinned = res("abc", None, vec![url("https://a.example/abc.bin")]);
        assert_eq!(
            cache.resource_path("kit", &unpinned),
            root.join("kit")
                .join("prov")
                .join(unpinned.cache_key())
                .join("abc.bin"),
            "unpinned is keyed by its first URL"
        );
        assert_eq!(cache.cache_dir(), dir.path().join("cache"));
        assert!(cache.offline());
        assert!(!cache.verify_local_dirs());
        assert!(cache.local_dirs().is_empty());
    }

    /// Whatever is at the pinned path is taken as verified-when-written.
    #[test]
    fn test_a_cached_resource_is_trusted_in_place() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path(), true);
        let r = res(
            "abc",
            Some(ABC_SHA256),
            vec![url("https://a.example/abc.bin")],
        );

        assert_eq!(cache.status("kit", &r), CacheStatus::Remote);
        let dest = cache.resource_path("kit", &r);
        fs::create_dir_all(dest.parent().unwrap()).unwrap();
        fs::write(&dest, b"not really abc").unwrap();

        assert_eq!(cache.status("kit", &r), CacheStatus::Cached);
        assert_eq!(
            cache.resolve("kit", &r).unwrap(),
            ResolvedResource {
                path: dest,
                provenance: Provenance::Cached,
            }
        );
    }

    /// A file in a local dir is used where it is, and the cache stays
    /// empty. It is not hashed unless the options ask, and then a wrong
    /// file is an error rather than passed over. An override by name wins
    /// over the directory the source carries.
    #[test]
    fn test_local_dir_is_used_in_place_and_trusted_unless_asked() {
        let dir = tempfile::tempdir().unwrap();
        let upstream = dir.path().join("upstream");
        fs::create_dir_all(&upstream).unwrap();
        let r = res(
            "abc",
            Some(ABC_SHA256),
            vec![local_dir(&upstream), url("https://a.example/abc.bin")],
        );
        fs::write(upstream.join("abc.bin"), b"a partial download").unwrap();

        let trusting = cache_in(dir.path(), true);
        assert_eq!(trusting.status("kit", &r), CacheStatus::LocalDir);
        let resolved = trusting.resolve("kit", &r).unwrap();
        assert_eq!(resolved.provenance, Provenance::LocalDir);
        assert_eq!(resolved.path, upstream.join("abc.bin"));
        assert!(!dir.path().join("cache").join("pretrained").exists());

        let verifying = PretrainedCache::new(
            PretrainedCacheOptions::default()
                .with_disk(
                    BunsenDiskCacheOptions::default()
                        .with_cache_dir(Some(dir.path().join("cache")))
                        .without_transfer_observers(),
                )
                .with_offline(true)
                .with_verify_local_dirs(true),
        )
        .unwrap();
        assert!(verifying.verify_local_dirs());
        ErrorMatcher::kind(BunsenErrorKind::InvalidResource)
            .assert_err(&verifying.resolve("kit", &r));
        fs::write(upstream.join("abc.bin"), b"abc").unwrap();
        assert_eq!(
            verifying.resolve("kit", &r).unwrap().provenance,
            Provenance::LocalDir
        );
        assert!(!dir.path().join("cache").join("pretrained").exists());

        let elsewhere = dir.path().join("elsewhere");
        fs::create_dir_all(&elsewhere).unwrap();
        fs::write(elsewhere.join("abc.bin"), b"abc").unwrap();
        let overridden = PretrainedCache::new(
            PretrainedCacheOptions::default()
                .with_disk(
                    BunsenDiskCacheOptions::default()
                        .with_cache_dir(Some(dir.path().join("cache")))
                        .without_transfer_observers(),
                )
                .with_offline(true)
                .with_local_dir("up", elsewhere.clone()),
        )
        .unwrap();
        assert_eq!(overridden.local_dir(&r.sources[0]), Some(elsewhere.clone()));
        assert_eq!(overridden.local_dir(&r.sources[1]), None);
        assert_eq!(
            overridden.resolve("kit", &r).unwrap().path,
            elsewhere.join("abc.bin")
        );
    }

    /// A path on the command line resolves to itself.
    #[test]
    fn test_a_given_resource_resolves_in_place() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("mine.pt");
        fs::write(&file, b"x").unwrap();
        let cache = cache_in(dir.path(), true);
        let r = Resource::given("checkpoint", &file);

        assert_eq!(cache.status("kit", &r), CacheStatus::LocalDir);
        assert_eq!(
            cache.resolve("kit", &r).unwrap(),
            ResolvedResource {
                path: file,
                provenance: Provenance::LocalDir,
            }
        );
    }

    /// Offline, a resource only a URL can supply is refused by the
    /// settings; a resource with no URL that is not where its local source
    /// says is a lookup of that path.
    #[test]
    fn test_resource_offline_or_without_a_url() {
        let dir = tempfile::tempdir().unwrap();
        let offline = cache_in(dir.path(), true);
        let remote = res(
            "abc",
            Some(ABC_SHA256),
            vec![url("https://a.example/abc.bin")],
        );
        ErrorMatcher::kind(BunsenErrorKind::Policy)
            .message_contains("the cache is offline")
            .frame_contains("abc")
            .assert_err(&offline.resolve("kit", &remote));

        let no_url = res("abc", Some(ABC_SHA256), vec![]);
        ErrorMatcher::kind(BunsenErrorKind::Lookup)
            .details_contains("no URL")
            .assert_err(&cache_in(dir.path(), false).resolve("kit", &no_url));

        let absent = dir.path().join("absent.pt");
        let given = Resource::given("checkpoint", &absent);
        ErrorMatcher::kind(BunsenErrorKind::Lookup)
            .frame_contains("checkpoint")
            .cause(predicate("a missing path", move |c: &LookupError| {
                c.problem == LookupProblem::Missing && c.key == absent.display().to_string()
            }))
            .assert_err(&offline.resolve("kit", &given));
    }

    /// A URL is fetched, checked and written under `pretrained/`; the next
    /// resolve is cached. The wrong bytes under another pin are refused
    /// and leave nothing.
    #[cfg(feature = "fetch")]
    #[test]
    fn test_a_resource_url_is_fetched_then_cached() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path(), false);
        let live = serve_once("abc.bin", b"abc");
        let r = res("abc", Some(ABC_SHA256), vec![url(&live)]);

        let resolved = cache.resolve("kit", &r).unwrap();
        assert_eq!(resolved.provenance, Provenance::Downloaded);
        assert_eq!(resolved.path, cache.resource_path("kit", &r));
        assert_eq!(fs::read(&resolved.path).unwrap(), b"abc");
        assert_eq!(
            cache.resolve("kit", &r).unwrap().provenance,
            Provenance::Cached
        );

        let wrong = serve_once("abd.bin", b"abd");
        let r = res("abd", Some(ABC_SHA256), vec![url(&wrong)]);
        ErrorMatcher::kind(BunsenErrorKind::InvalidResource).assert_err(&cache.resolve("kit", &r));
        assert!(!cache.resource_path("kit", &r).exists());
    }

    /// A map loads with one provenance per resource: the cached one is
    /// trusted, the local-dir one used in place, the remote one fetched.
    #[cfg(feature = "fetch")]
    #[test]
    fn test_load_mixes_provenances() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path(), false);
        let upstream = dir.path().join("upstream");
        fs::create_dir_all(&upstream).unwrap();
        fs::write(upstream.join("local.bin"), b"abc").unwrap();
        let live = serve_once("remote.bin", b"abc");

        let cached = res(
            "cached",
            Some(ABC_SHA256),
            vec![url("https://a.example/cached.bin")],
        );
        let dest = cache.resource_path("kit", &cached);
        fs::create_dir_all(dest.parent().unwrap()).unwrap();
        fs::write(&dest, b"abc").unwrap();
        let local = res(
            "local",
            Some(ABC_SHA256),
            vec![local_dir(&upstream), url("https://a.example/local.bin")],
        );
        let remote = res("remote", Some(ABC_SHA256), vec![url(&live)]);
        let map = ResourceMap::new("m")
            .with_resource(cached)
            .with_resource(local.clone())
            .with_resource(remote.clone());

        let status = cache.map_status("kit", &map);
        assert_eq!(status["cached"], CacheStatus::Cached);
        assert_eq!(status["local"], CacheStatus::LocalDir);
        assert_eq!(status["remote"], CacheStatus::Remote);

        let loaded = cache.load("kit", &map).unwrap();
        assert_eq!(loaded.map, map);
        assert_eq!(loaded.keys(), ["cached", "local", "remote"]);
        assert_eq!(loaded.get("cached").unwrap().provenance, Provenance::Cached);
        assert_eq!(
            loaded.get("local").unwrap().provenance,
            Provenance::LocalDir
        );
        assert_eq!(
            loaded.get("local").unwrap().path,
            upstream.join("local.bin")
        );
        assert_eq!(
            loaded.get("remote").unwrap().provenance,
            Provenance::Downloaded
        );
        assert_eq!(
            loaded.expect("remote").unwrap(),
            cache.resource_path("kit", &remote)
        );
        assert!(!cache.resource_path("kit", &local).exists());
        assert_eq!(cache.map_status("kit", &map)["remote"], CacheStatus::Cached);
    }

    /// One remote that cannot be had fails the load and is named by key;
    /// the one that could be had is on disk.
    #[cfg(feature = "fetch")]
    #[test]
    fn test_load_names_the_key_that_did_not_land() {
        let dir = tempfile::tempdir().unwrap();
        let cache = PretrainedCache::new(
            PretrainedCacheOptions::default()
                .with_disk(
                    BunsenDiskCacheOptions::default()
                        .with_cache_dir(Some(dir.path().join("cache")))
                        .without_transfer_observers(),
                )
                .with_fetch_policy(FetchPolicy::default().with_on_failure(OnFailure::Continue)),
        )
        .unwrap();
        let live = res(
            "live",
            Some(ABC_SHA256),
            vec![url(&serve_once("live.bin", b"abc"))],
        );
        let dead = res(
            "dead",
            Some(ABC_SHA256),
            vec![url(&refused_url("dead.bin"))],
        );
        let map = ResourceMap::new("m")
            .with_resource(live.clone())
            .with_resource(dead);

        let err = cache.load("kit", &map).unwrap_err();
        ErrorMatcher::new()
            .display(text::eq("m: 1 of 2 resources did not land"))
            .details_contains("dead: ")
            .details(not(text::contains("live:")))
            .cause(predicate("one member, dead", |c: &Multiple| {
                c.members.len() == 1 && c.members[0].0 == "dead"
            }))
            .assert(&err);
        assert!(cache.resource_path("kit", &live).is_file());
    }

    /// Offline, a map with a remote resource is not found, and the error
    /// names the remote keys; a map of local resources loads.
    #[test]
    fn test_load_offline_names_the_remote_keys() {
        let dir = tempfile::tempdir().unwrap();
        let cache = cache_in(dir.path(), true);
        let cached = res(
            "cached",
            Some(ABC_SHA256),
            vec![url("https://a.example/cached.bin")],
        );
        let dest = cache.resource_path("kit", &cached);
        fs::create_dir_all(dest.parent().unwrap()).unwrap();
        fs::write(&dest, b"abc").unwrap();
        let remote = res(
            "remote",
            Some(ABC_SHA256),
            vec![url("https://a.example/remote.bin")],
        );
        let map = ResourceMap::new("m")
            .with_resource(cached)
            .with_resource(remote);

        ErrorMatcher::kind(BunsenErrorKind::Policy)
            .message(text::ends_with("offline: remote"))
            .frame_contains("m")
            .assert_err(&cache.load("kit", &map));

        let local_only = ResourceMap::new("m").with_resource(res(
            "cached",
            Some(ABC_SHA256),
            vec![url("https://a.example/cached.bin")],
        ));
        let loaded = cache.load("kit", &local_only).unwrap();
        assert_eq!(loaded.get("cached").unwrap().provenance, Provenance::Cached);
    }

    #[test]
    fn test_display() {
        assert_eq!(Provenance::Cached.to_string(), "cached");
        assert_eq!(Provenance::LocalDir.to_string(), "local dir");
        assert_eq!(Provenance::Downloaded.to_string(), "downloaded");
        assert_eq!(CacheStatus::Cached.to_string(), "cached");
        assert_eq!(CacheStatus::LocalDir.to_string(), "local dir");
        assert_eq!(CacheStatus::Remote.to_string(), "remote");
    }
}