cgx-core 0.0.9

Core library for cgx, the Rust equivalent of uvx or npx for running Rust crates quickly and easily
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
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
use crate::{
    Result,
    bin_resolver::ResolvedBinary,
    builder::BuildOptions,
    config::{Config, UsePrebuiltBinaries},
    crate_resolver::{ResolvedCrate, ResolvedSource},
    cratespec::{CrateSpec, Forge, RegistrySource},
    downloader::DownloadedCrate,
    error,
    messages::{BuildCacheMessage, CrateResolutionMessage, PrebuiltBinaryMessage, SourceMessage},
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use snafu::ResultExt;
use std::{
    collections::hash_map::DefaultHasher,
    fs,
    hash::{Hash, Hasher},
    path::PathBuf,
    sync::Arc,
    time::Duration,
};
use tracing::*;

/// A cache entry wrapping a value with timestamp metadata.
///
/// This generic wrapper is used for any cached data that has an expiration policy.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct CacheEntry<T> {
    value: T,
    cached_at: DateTime<Utc>,
}

impl<T> CacheEntry<T> {
    /// Create a new cache entry with the current timestamp.
    fn new(value: T) -> Self {
        Self {
            value,
            cached_at: Utc::now(),
        }
    }

    /// Get the age of this cache entry as a [`Duration`].
    fn age(&self) -> Duration {
        Utc::now()
            .signed_duration_since(self.cached_at)
            .to_std()
            .unwrap_or(Duration::ZERO)
    }

    /// Consume this cache entry and get at the inner value.
    fn into_inner(self) -> T {
        self.value
    }
}

/// A cache entry for a resolved crate specification.
type CrateResolveCacheEntry = CacheEntry<ResolvedCrate>;

/// Manages the various caches that cgx uses to operate.
///
/// The root of the caches is controlled by [`Config::cache_dir`].  Below that are multiple
/// subdirectories for caching various things:
/// - Results of crate spec resolution
/// - Downloaded/extracted crate source code packages
/// - Git database (bare repos)
/// - Git checkouts at specific commits
///
/// More may be added over time.
#[derive(Clone, Debug)]
pub(crate) struct Cache {
    inner: Arc<CacheInner>,
}

impl Cache {
    /// Create a new [`Cache`] with the given configuration and message reporter.
    pub(crate) fn new(config: Config, reporter: crate::messages::MessageReporter) -> Self {
        Self {
            inner: Arc::new(CacheInner { config, reporter }),
        }
    }

    /// Get a cached crate resolution, or resolve it using the provided resolver function.
    ///
    /// This method implements the full caching strategy:
    /// - If a non-expired cache entry exists, return it without calling the resolver
    /// - Call the resolver function to compute a fresh value
    /// - On success, cache the result and return it
    /// - On transient errors (network/IO), fall back to stale cache if available
    /// - On permanent errors, propagate without using stale cache
    pub(crate) fn get_or_resolve_crate<F>(&self, spec: &CrateSpec, resolver: F) -> Result<ResolvedCrate>
    where
        F: FnOnce() -> Result<ResolvedCrate>,
    {
        self.inner
            .reporter
            .report(|| CrateResolutionMessage::cache_lookup(spec));

        let stale_entry = if !self.inner.config.refresh {
            if let Ok(Some(entry)) = self.get_resolved_crate(spec) {
                let age = entry.age();
                let ttl = self.inner.config.resolve_cache_timeout;

                if age < ttl {
                    let cache_path = self.crate_resolve_cache_path(spec).ok();
                    if let Some(path) = &cache_path {
                        self.inner
                            .reporter
                            .report(|| CrateResolutionMessage::cache_hit(path, age, ttl.saturating_sub(age)));
                    }
                    self.inner
                        .reporter
                        .report(|| CrateResolutionMessage::resolved(&entry.value));
                    return Ok(entry.value);
                }

                self.inner
                    .reporter
                    .report(|| CrateResolutionMessage::cache_stale(spec, age));
                Some(entry)
            } else {
                self.inner
                    .reporter
                    .report(|| CrateResolutionMessage::cache_miss(spec));
                None
            }
        } else {
            self.inner
                .reporter
                .report(|| CrateResolutionMessage::cache_miss(spec));
            None
        };

        self.inner
            .reporter
            .report(|| CrateResolutionMessage::resolving(spec));

        match resolver() {
            Ok(resolved) => {
                self.inner
                    .reporter
                    .report(|| CrateResolutionMessage::resolved(&resolved));
                if let Ok(path) = self.crate_resolve_cache_path(spec) {
                    let _ = self.put_resolved_crate(spec, &resolved);
                    self.inner
                        .reporter
                        .report(|| CrateResolutionMessage::cache_stored(&path));
                } else {
                    let _ = self.put_resolved_crate(spec, &resolved);
                }
                Ok(resolved)
            }
            Err(e) if !self.inner.config.refresh && Self::should_use_stale_cache(&e) => {
                // If there was already an entry in the cache, but we didn't use it because it was
                // stale, return it now as a fallback since a stale cache entry is better than
                // failing with this error
                if let Some(entry) = stale_entry {
                    let age = entry.age();
                    let resolved = entry.into_inner();
                    self.inner
                        .reporter
                        .report(|| CrateResolutionMessage::using_stale_fallback(spec, age));
                    self.inner
                        .reporter
                        .report(|| CrateResolutionMessage::resolved(&resolved));
                    Ok(resolved)
                } else {
                    Err(e)
                }
            }
            Err(e) => Err(e),
        }
    }

    /// Get a cached binary resolution result, or resolve it using the provided resolver function.
    ///
    /// Binary resolution results never expire because crates are immutable. Once we determine
    /// whether a binary exists for a specific version on a specific platform, that answer remains
    /// valid forever. We cache both positive (binary found) and negative (no binary) results to
    /// avoid repeatedly checking providers.
    ///
    /// Unlike crate resolution, there is no TTL check - the cache entry is permanent.
    ///
    /// # Arguments
    ///
    /// * `krate` - The resolved crate to find a binary for
    /// * `resolver` - Function that attempts to find and download a pre-built binary
    ///
    /// # Returns
    ///
    /// * `Ok(Some(ResolvedBinary))` - Found a pre-built binary (either cached or freshly resolved)
    /// * `Ok(None)` - No pre-built binary available (either cached negative result or resolver
    ///   returned None)
    /// * `Err(...)` - An error occurred during resolution
    pub(crate) fn get_or_resolve_binary<F>(
        &self,
        krate: &ResolvedCrate,
        resolver: F,
    ) -> Result<Option<ResolvedBinary>>
    where
        F: FnOnce() -> Result<Option<ResolvedBinary>>,
    {
        // Check if prebuilt binaries are disabled entirely (before cache lookup)
        if self.inner.config.prebuilt_binaries.use_prebuilt_binaries == UsePrebuiltBinaries::Never {
            self.inner
                .reporter
                .report(PrebuiltBinaryMessage::prebuilt_binaries_disabled);
            return Ok(None);
        }

        // Check cache unless refresh mode is enabled
        let use_cache = !self.inner.config.refresh;

        if use_cache {
            self.inner
                .reporter
                .report(|| PrebuiltBinaryMessage::cache_lookup(krate));

            if let Ok(Some(entry)) = self.get_cached_binary(krate) {
                match &entry.value {
                    Some(binary) => {
                        self.inner
                            .reporter
                            .report(|| PrebuiltBinaryMessage::cache_hit(&binary.path, binary.provider));
                    }
                    None => {
                        // Negative cache hit - we previously determined no binary was available
                        self.inner.reporter.report(|| {
                            PrebuiltBinaryMessage::no_binary_found(
                                krate,
                                vec!["negative cache hit - no binary available".to_string()],
                            )
                        });
                    }
                }
                // Return the cached result whether it's Some or None
                return Ok(entry.value);
            }

            self.inner
                .reporter
                .report(|| PrebuiltBinaryMessage::cache_miss(krate));
        }

        // Call the resolver to attempt finding a binary
        match resolver() {
            Ok(result) => {
                // Cache the result (whether Some or None)
                let _ = self.put_cached_binary(krate, &result);

                if let Some(ref _binary) = result {
                    if let Ok(cache_path) = self.binary_cache_path(krate) {
                        self.inner
                            .reporter
                            .report(|| PrebuiltBinaryMessage::cache_stored(&cache_path));
                    }
                } else {
                    // Also report when we cache a negative result
                    if let Ok(cache_path) = self.binary_cache_path(krate) {
                        self.inner
                            .reporter
                            .report(|| PrebuiltBinaryMessage::cache_stored(&cache_path));
                    }
                }

                Ok(result)
            }
            Err(e) => Err(e),
        }
    }

    /// Get a cached crate source code package, or download it using the provided downloader
    /// function.
    ///
    /// This method implements transactional caching for source downloads:
    /// 1. If the source is already cached, return it without calling the downloader
    /// 2. Create a temporary directory for the download
    /// 3. Call the downloader function with the temp directory path
    /// 4. On success, atomically rename the temp directory to the cache location
    /// 5. Handle race conditions where multiple processes download simultaneously
    pub(crate) fn get_or_download_crate<F>(
        &self,
        resolved: &ResolvedCrate,
        downloader: F,
    ) -> Result<DownloadedCrate>
    where
        F: FnOnce(&std::path::Path) -> Result<()>,
    {
        self.inner
            .reporter
            .report(|| SourceMessage::cache_lookup(resolved));

        // Compute the target cache path
        let cache_path = self.crate_source_cache_path(resolved)?;

        // Check if already cached
        if !self.inner.config.refresh {
            if let Ok(Some(cached)) = self.get_cached_crate_source(resolved) {
                self.inner
                    .reporter
                    .report(|| SourceMessage::cache_hit(&cached.crate_path));
                return Ok(cached);
            }
        } else {
            // When refresh is enabled, delete any existing cache to ensure a fresh download
            if cache_path.exists() {
                debug!(
                    "Refresh mode: removing existing source cache at {}",
                    cache_path.display()
                );
                let _ = fs::remove_dir_all(&cache_path);
            }
        }

        self.inner.reporter.report(|| SourceMessage::cache_miss(resolved));

        self.inner
            .reporter
            .report(|| SourceMessage::downloading(resolved));

        // Ensure parent directory exists
        let parent = cache_path.parent().expect("BUG: Cache path has no parent");
        fs::create_dir_all(parent).with_context(|_| error::IoSnafu {
            path: parent.to_path_buf(),
        })?;

        // Create a temp directory in the same parent directory for atomic rename
        let temp_dir = tempfile::tempdir_in(parent).with_context(|_| error::TempDirCreationSnafu {
            parent: parent.to_path_buf(),
        })?;

        // Call the downloader with the temp path
        downloader(temp_dir.path())?;
        self.inner
            .reporter
            .report(|| SourceMessage::downloaded(temp_dir.path()));

        // Success! Try to atomically move the temp dir to the cache location
        // Use keep() to prevent temp_dir cleanup
        let temp_path = temp_dir.keep();

        match fs::rename(&temp_path, &cache_path) {
            Ok(()) => {
                self.inner
                    .reporter
                    .report(|| SourceMessage::cache_stored(&cache_path));
                // Successfully moved to cache
                Ok(DownloadedCrate {
                    resolved: resolved.clone(),
                    crate_path: cache_path,
                })
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                // Someone else won the race - that's fine, use their result
                // Clean up our temp dir
                let _ = fs::remove_dir_all(&temp_path);
                Ok(DownloadedCrate {
                    resolved: resolved.clone(),
                    crate_path: cache_path,
                })
            }
            Err(e) => {
                // Some other error during rename - clean up and propagate
                let _ = fs::remove_dir_all(&temp_path);
                Err(e).with_context(|_| error::RenameFileSnafu {
                    src: temp_path.clone(),
                    dst: cache_path.clone(),
                })
            }
        }
    }

    /// Get a cached resolution for the given [`CrateSpec`], if one exists.
    ///
    /// Returns `None` if there is no cached entry or if reading the cache fails.
    fn get_resolved_crate(&self, spec: &CrateSpec) -> Result<Option<CacheEntry<ResolvedCrate>>> {
        let cache_file = self.crate_resolve_cache_path(spec)?;
        if !cache_file.exists() {
            return Ok(None);
        }

        let contents = fs::read_to_string(&cache_file).with_context(|_| error::IoSnafu {
            path: cache_file.clone(),
        })?;
        let entry: CrateResolveCacheEntry = serde_json::from_str(&contents).context(error::JsonSnafu)?;

        Ok(Some(entry))
    }

    /// Store a resolved crate in the cache for the given [`CrateSpec`].
    fn put_resolved_crate(&self, spec: &CrateSpec, resolved: &ResolvedCrate) -> Result<()> {
        let cache_file = self.crate_resolve_cache_path(spec)?;

        if let Some(parent) = cache_file.parent() {
            fs::create_dir_all(parent).with_context(|_| error::IoSnafu {
                path: parent.to_path_buf(),
            })?;
        }

        let entry = CacheEntry::new(resolved.clone());

        let json = serde_json::to_string_pretty(&entry).context(error::JsonSnafu)?;
        fs::write(&cache_file, json).with_context(|_| error::IoSnafu {
            path: cache_file.clone(),
        })?;

        Ok(())
    }

    /// Get a cached binary resolution result for the given [`ResolvedCrate`], if one exists.
    ///
    /// Returns `None` if there is no cached entry or if reading the cache fails.
    /// Note that a cached entry can contain `Some(ResolvedBinary)` or `None` - we cache
    /// both positive and negative results.
    fn get_cached_binary(&self, krate: &ResolvedCrate) -> Result<Option<CacheEntry<Option<ResolvedBinary>>>> {
        let cache_file = self.binary_cache_path(krate)?;
        if !cache_file.exists() {
            return Ok(None);
        }

        let contents = fs::read_to_string(&cache_file).with_context(|_| error::IoSnafu {
            path: cache_file.clone(),
        })?;
        let entry: CacheEntry<Option<ResolvedBinary>> =
            serde_json::from_str(&contents).context(error::JsonSnafu)?;

        Ok(Some(entry))
    }

    /// Store a binary resolution result in the cache for the given [`ResolvedCrate`].
    ///
    /// This stores both positive results (Some(ResolvedBinary)) and negative results (None).
    fn put_cached_binary(&self, krate: &ResolvedCrate, result: &Option<ResolvedBinary>) -> Result<()> {
        let cache_file = self.binary_cache_path(krate)?;

        if let Some(parent) = cache_file.parent() {
            fs::create_dir_all(parent).with_context(|_| error::IoSnafu {
                path: parent.to_path_buf(),
            })?;
        }

        let entry = CacheEntry::new(result.clone());

        let json = serde_json::to_string_pretty(&entry).context(error::JsonSnafu)?;
        fs::write(&cache_file, json).with_context(|_| error::IoSnafu {
            path: cache_file.clone(),
        })?;

        Ok(())
    }

    /// Get the filesystem path for the binary resolution cache file for a given [`ResolvedCrate`].
    ///
    /// The cache key includes the crate identity (name, version, source) and the current platform.
    /// This ensures that binaries are cached per-platform, which is essential since pre-built
    /// binaries are platform-specific.
    fn binary_cache_path(&self, krate: &ResolvedCrate) -> Result<PathBuf> {
        let hash = Self::compute_binary_cache_hash(krate)?;
        Ok(self
            .inner
            .config
            .cache_dir
            .join("binaries")
            .join(format!("{}.json", hash)))
    }

    /// Compute a SHA256 hash for the binary cache key.
    ///
    /// The hash includes:
    /// - Crate name
    /// - Crate version
    /// - Resolved source (crates.io vs git vs forge, etc.)
    /// - Current platform triple
    ///
    /// This ensures that the same crate on different platforms gets different cache entries.
    fn compute_binary_cache_hash(krate: &ResolvedCrate) -> Result<String> {
        #[derive(Serialize)]
        struct BinaryCacheKey<'a> {
            name: &'a str,
            version: &'a semver::Version,
            source: &'a ResolvedSource,
            platform: &'a str,
        }

        let key = BinaryCacheKey {
            name: &krate.name,
            version: &krate.version,
            source: &krate.source,
            platform: build_context::TARGET,
        };

        let json = serde_json::to_string(&key).context(error::JsonSnafu)?;
        Ok(Self::compute_hash(json.as_bytes()))
    }

    /// Get the filesystem path for the resolve cache file for a given [`CrateSpec`].
    fn crate_resolve_cache_path(&self, spec: &CrateSpec) -> Result<PathBuf> {
        let hash = Self::compute_spec_hash(spec)?;
        Ok(self
            .inner
            .config
            .cache_dir
            .join("resolve")
            .join(format!("{}.json", hash)))
    }

    /// Compute a SHA256 hash of the serialized [`CrateSpec`] to use as a cache key.
    fn compute_spec_hash(spec: &CrateSpec) -> Result<String> {
        let json = serde_json::to_string(spec).context(error::JsonSnafu)?;
        Ok(Self::compute_hash(json.as_bytes()))
    }

    /// Compute a SHA256 hash of the given data.
    fn compute_hash(data: &[u8]) -> String {
        let mut hasher = Sha256::new();
        hasher.update(data);
        format!("{:x}", hasher.finalize())
    }

    /// Determine if an error should trigger fallback to stale cache.
    ///
    /// Network and I/O errors are considered transient and should use stale cache if available.
    /// Other errors (like version mismatches) are permanent and should not use stale cache.
    fn should_use_stale_cache(error: &error::Error) -> bool {
        matches!(
            error,
            error::Error::Registry { .. } | error::Error::Git { .. } | error::Error::Io { .. }
        )
    }

    /// Check if a resolved crate's source code package is already in the cache.
    fn get_cached_crate_source(&self, resolved: &ResolvedCrate) -> Result<Option<DownloadedCrate>> {
        let cache_path = self.crate_source_cache_path(resolved)?;

        if cache_path.exists() {
            Ok(Some(DownloadedCrate {
                resolved: resolved.clone(),
                crate_path: cache_path,
            }))
        } else {
            Ok(None)
        }
    }

    /// Get the cache directory path for a resolved crate's source code package.
    fn crate_source_cache_path(&self, resolved: &ResolvedCrate) -> Result<PathBuf> {
        let base = self.inner.config.cache_dir.join("sources");

        let path = match &resolved.source {
            ResolvedSource::CratesIo => base
                .join("crates-io")
                .join(&resolved.name)
                .join(resolved.version.to_string()),

            ResolvedSource::Registry { source } => match source {
                RegistrySource::Named(name) => base
                    .join("registry")
                    .join(name)
                    .join(&resolved.name)
                    .join(resolved.version.to_string()),

                RegistrySource::IndexUrl(url) => {
                    let url_hash = Self::compute_hash(url.as_str().as_bytes());
                    base.join("registry-index")
                        .join(url_hash)
                        .join(&resolved.name)
                        .join(resolved.version.to_string())
                }
            },

            ResolvedSource::Git { repo, commit } => {
                let repo_hash = Self::compute_hash(repo.as_bytes());
                base.join("git").join(repo_hash).join(commit)
            }

            ResolvedSource::Forge { forge, commit } => match forge {
                Forge::GitHub { owner, repo, .. } => base.join("github").join(owner).join(repo).join(commit),
                Forge::GitLab { owner, repo, .. } => base.join("gitlab").join(owner).join(repo).join(commit),
            },

            ResolvedSource::LocalDir { .. } => {
                unreachable!("LocalDir sources should not be passed to source_cache_path")
            }
        };

        Ok(path)
    }

    /// Get the cache path for a git database (bare repo) for a URL.
    pub(crate) fn git_db_path(&self, url: &str) -> PathBuf {
        let ident = Self::compute_git_ident(url);
        self.inner.config.cache_dir.join("git-db").join(ident)
    }

    /// Get the cache path for a git checkout at a specific commit.
    pub(crate) fn git_checkout_path(&self, url: &str, commit: &str) -> PathBuf {
        let ident = Self::compute_git_ident(url);
        self.inner
            .config
            .cache_dir
            .join("git-checkouts")
            .join(ident)
            .join(commit)
    }

    /// Compute stable identifier for git URL (like cargo's ident).
    ///
    /// Format: `{repo-name}-{short-hash}`
    /// Example: `tokio-a1b2c3d4` for `https://github.com/tokio-rs/tokio`
    fn compute_git_ident(url: &str) -> String {
        // Extract repo name from URL (last path component)
        let name = url
            .trim_end_matches('/')
            .trim_end_matches(".git")
            .rsplit('/')
            .next()
            .unwrap_or("repo");

        // Short hash of full URL for uniqueness
        let hash = &Self::compute_hash(url.as_bytes())[..8];

        format!("{}-{}", name, hash)
    }

    /// Test helper to manually insert a stale resolve cache entry.
    ///
    /// This allows tests to populate the cache with entries of a specific age,
    /// useful for testing stale cache behavior and offline mode.
    #[cfg(test)]
    pub(crate) fn insert_stale_resolve_entry(
        &self,
        spec: &CrateSpec,
        resolved: &ResolvedCrate,
        age: Duration,
    ) -> Result<()> {
        let cache_file = self.crate_resolve_cache_path(spec)?;

        if let Some(parent) = cache_file.parent() {
            fs::create_dir_all(parent).with_context(|_| error::IoSnafu {
                path: parent.to_path_buf(),
            })?;
        }

        let cached_at = Utc::now() - chrono::Duration::from_std(age).unwrap();
        let entry = CacheEntry {
            value: resolved.clone(),
            cached_at,
        };

        let json = serde_json::to_string_pretty(&entry).context(error::JsonSnafu)?;
        fs::write(&cache_file, json).with_context(|_| error::IoSnafu {
            path: cache_file.clone(),
        })?;

        Ok(())
    }

    /// Get a cached binary or build it if not present.
    ///
    /// This method implements binary caching with a cache key computed from both the
    /// crate identity and the build options. Local directory sources are never cached,
    /// as their source code can change arbitrarily.
    ///
    /// An SBOM (Software Bill of Materials) is stored alongside the binary
    /// for all cached sources, describing the dependencies and build configuration.
    ///
    /// # Arguments
    ///
    /// * `krate` - The resolved crate to build
    /// * `options` - Build options that affect the output binary
    /// * `build_fn` - Closure that builds the binary and returns both the binary path and the
    ///   generated SBOM
    ///
    /// # Returns
    ///
    /// The path to the binary, either from cache or freshly built.
    pub(crate) fn get_or_build_binary<F>(
        &self,
        krate: &ResolvedCrate,
        options: &BuildOptions,
        build_fn: F,
    ) -> Result<PathBuf>
    where
        F: FnOnce() -> Result<(PathBuf, crate::sbom::CycloneDx)>,
    {
        // Don't cache local directories - their source can change
        if matches!(krate.source, ResolvedSource::LocalDir { .. }) {
            self.inner
                .reporter
                .report(BuildCacheMessage::skipping_cache_local_dir);
            let (binary_path, _sbom) = build_fn()?;
            return Ok(binary_path);
        }

        self.inner
            .reporter
            .report(|| BuildCacheMessage::cache_lookup(krate, options));

        let source_hash = Self::compute_source_hash(&krate.source);
        let build_hash = Self::compute_build_hash(options);
        let binary_name = Self::expected_binary_name(&krate.name, &options.build_target);

        let cache_dir = self
            .inner
            .config
            .bin_dir
            .join(format!("{}-{}", krate.name, krate.version))
            .join(source_hash)
            .join(build_hash);

        let cache_path = cache_dir.join(&binary_name);
        let sbom_path = cache_dir.join("sbom.cyclonedx.json");

        // Return cached binary if it exists (SBOM is presumed to also exist in this case)
        if cache_path.exists() {
            if !self.inner.config.refresh {
                self.inner
                    .reporter
                    .report(|| BuildCacheMessage::cache_hit(&cache_path, &sbom_path));
                return Ok(cache_path);
            } else {
                debug!(
                    cache_dir = %cache_dir.display(),
                    "Refresh mode: removing existing binary cache",
                );
                let _ = fs::remove_dir_all(&cache_dir);
            }
        }

        self.inner
            .reporter
            .report(|| BuildCacheMessage::cache_miss(krate));

        // Build the binary and get the SBOM
        let (built_binary, sbom) = build_fn()?;

        // Create cache directory
        fs::create_dir_all(&cache_dir).with_context(|_| error::IoSnafu {
            path: cache_dir.clone(),
        })?;

        // Copy binary to cache
        fs::copy(&built_binary, &cache_path).with_context(|_| error::CopyBinarySnafu {
            src: built_binary.clone(),
            dst: cache_path.clone(),
        })?;

        // Serialize and write SBOM to cache
        let sbom_json = serde_json::to_string_pretty(&sbom).context(error::JsonSnafu)?;
        fs::write(&sbom_path, sbom_json).with_context(|_| error::IoSnafu {
            path: sbom_path.clone(),
        })?;

        self.inner
            .reporter
            .report(|| BuildCacheMessage::cache_stored(&cache_path, &sbom_path));

        Ok(cache_path)
    }

    /// Compute a hash of the resolved source to distinguish different crate origins.
    ///
    /// Different sources (crates.io vs git vs forge) will produce different hashes
    /// even for the same crate name and version.
    fn compute_source_hash(source: &ResolvedSource) -> String {
        let mut hasher = DefaultHasher::new();
        match source {
            ResolvedSource::CratesIo => {
                "crates-io".hash(&mut hasher);
            }
            ResolvedSource::Registry { source: registry } => {
                "registry".hash(&mut hasher);
                match registry {
                    RegistrySource::Named(name) => name.hash(&mut hasher),
                    RegistrySource::IndexUrl(url) => url.as_str().hash(&mut hasher),
                }
            }
            ResolvedSource::Git { repo, commit } => {
                "git".hash(&mut hasher);
                repo.hash(&mut hasher);
                commit.hash(&mut hasher);
            }
            ResolvedSource::Forge { forge, commit } => {
                "forge".hash(&mut hasher);
                // Format Debug output of forge for hashing
                format!("{:?}", forge).hash(&mut hasher);
                commit.hash(&mut hasher);
            }
            ResolvedSource::LocalDir { .. } => {
                panic!("Should not compute hash for LocalDir sources");
            }
        }
        format!("{:016x}", hasher.finish())
    }

    /// Compute a hash of build options that affect the output binary.
    ///
    /// Only options that actually change the binary output are included.
    /// Options like `offline`, `jobs`, and `ignore_rust_version` affect build
    /// behavior but not the resulting binary, so they're excluded.
    ///
    /// The `locked` flag DOES affect the binary because it affects dependency
    /// resolution - different dependency versions produce different binaries.
    ///
    /// Features are sorted before hashing to ensure consistent cache keys
    /// regardless of the order they're specified.
    fn compute_build_hash(options: &BuildOptions) -> String {
        let mut hasher = DefaultHasher::new();

        // Sort features for consistency - order shouldn't matter for cache key
        let mut features = options.features.clone();
        features.sort();
        features.hash(&mut hasher);

        options.all_features.hash(&mut hasher);
        options.no_default_features.hash(&mut hasher);
        options.profile.hash(&mut hasher);
        options.target.hash(&mut hasher);
        options.build_target.hash(&mut hasher);
        options.toolchain.hash(&mut hasher);

        // locked affects dependency resolution, which affects the binary
        options.locked.hash(&mut hasher);

        // Explicitly NOT hashing these fields as they don't affect the binary output:
        // - offline: affects network access, not binary
        // - jobs: affects build parallelism, not binary
        // - ignore_rust_version: affects cargo checks, not binary

        format!("{:016x}", hasher.finish())
    }

    /// Compute the expected binary name based on the build target.
    ///
    /// The binary name is deterministic based on the crate name and build target,
    /// with platform-specific extensions added automatically.
    fn expected_binary_name(crate_name: &str, build_target: &crate::builder::BuildTarget) -> String {
        use crate::builder::BuildTarget;

        let base_name = match build_target {
            BuildTarget::DefaultBin => crate_name,
            BuildTarget::Bin(name) | BuildTarget::Example(name) => name.as_str(),
        };

        #[cfg(windows)]
        return format!("{}.exe", base_name);

        #[cfg(not(windows))]
        return base_name.to_string();
    }
}

#[derive(Debug)]
struct CacheInner {
    config: Config,
    reporter: crate::messages::MessageReporter,
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;
    use semver::Version;
    use snafu::IntoError;
    use std::{cell::RefCell, rc::Rc, time::Duration};
    use tempfile::TempDir;

    fn test_cache() -> (Cache, TempDir) {
        test_cache_with_timeout(Duration::from_secs(3600))
    }

    fn test_cache_with_timeout(timeout: Duration) -> (Cache, TempDir) {
        crate::logging::init_test_logging();

        let (temp_dir, mut config) = crate::config::create_test_env();
        config.resolve_cache_timeout = timeout;
        (
            Cache::new(config, crate::messages::MessageReporter::null()),
            temp_dir,
        )
    }

    fn test_cache_with_refresh() -> (Cache, TempDir) {
        crate::logging::init_test_logging();

        let (temp_dir, mut config) = crate::config::create_test_env();
        config.refresh = true;
        (
            Cache::new(config, crate::messages::MessageReporter::null()),
            temp_dir,
        )
    }

    fn test_spec() -> CrateSpec {
        CrateSpec::CratesIo {
            name: "serde".to_string(),
            version: None,
        }
    }

    fn test_spec_alt() -> CrateSpec {
        CrateSpec::CratesIo {
            name: "tokio".to_string(),
            version: None,
        }
    }

    fn test_resolved() -> ResolvedCrate {
        ResolvedCrate {
            name: "serde".to_string(),
            version: Version::parse("1.0.0").unwrap(),
            source: ResolvedSource::CratesIo,
        }
    }

    fn test_resolved_alt() -> ResolvedCrate {
        ResolvedCrate {
            name: "serde".to_string(),
            version: Version::parse("1.0.1").unwrap(),
            source: ResolvedSource::CratesIo,
        }
    }

    mod get_or_resolve {
        use super::*;

        #[test]
        fn cache_miss_calls_closure() {
            let (cache, _temp) = test_cache();
            let spec = test_spec();
            let resolved = test_resolved();

            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();
            let resolved_clone = resolved.clone();

            let result = cache.get_or_resolve_crate(&spec, || {
                *call_count_clone.borrow_mut() += 1;
                Ok(resolved_clone.clone())
            });

            assert!(result.is_ok());
            assert_eq!(result.unwrap(), resolved);
            assert_eq!(*call_count.borrow(), 1);

            let cached = cache.get_resolved_crate(&spec).unwrap();
            assert_eq!(cached.map(|e| e.value), Some(resolved));
        }

        #[test]
        fn cache_hit_valid_skips_closure() {
            let (cache, _temp) = test_cache();
            let spec = test_spec();
            let resolved = test_resolved();

            cache.put_resolved_crate(&spec, &resolved).unwrap();

            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();

            let result = cache.get_or_resolve_crate(&spec, || {
                *call_count_clone.borrow_mut() += 1;
                Ok(test_resolved_alt())
            });

            assert!(result.is_ok());
            assert_eq!(result.unwrap(), resolved);
            assert_eq!(*call_count.borrow(), 0);
        }

        #[test]
        fn cache_hit_expired_calls_closure() {
            let (cache, _temp) = test_cache_with_timeout(Duration::from_secs(0));
            let spec = test_spec();
            let old_resolved = test_resolved();
            let new_resolved = test_resolved_alt();

            cache.put_resolved_crate(&spec, &old_resolved).unwrap();
            std::thread::sleep(Duration::from_secs(1));

            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();
            let new_resolved_clone = new_resolved.clone();

            let result = cache.get_or_resolve_crate(&spec, || {
                *call_count_clone.borrow_mut() += 1;
                Ok(new_resolved_clone.clone())
            });

            assert!(result.is_ok());
            assert_eq!(result.unwrap(), new_resolved);
            assert_eq!(*call_count.borrow(), 1);
        }

        #[test]
        fn network_error_with_stale_returns_stale() {
            let (cache, _temp) = test_cache_with_timeout(Duration::from_secs(0));
            let spec = test_spec();
            let resolved = test_resolved();

            cache.put_resolved_crate(&spec, &resolved).unwrap();
            std::thread::sleep(Duration::from_secs(1));

            let result = cache.get_or_resolve_crate(&spec, || {
                Err(
                    error::RegistrySnafu.into_error(tame_index::Error::Io(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        "network error",
                    ))),
                )
            });

            assert!(result.is_ok());
            assert_eq!(result.unwrap(), resolved);
        }

        #[test]
        fn network_error_without_stale_propagates() {
            let (cache, _temp) = test_cache();
            let spec = test_spec();

            let result = cache.get_or_resolve_crate(&spec, || {
                Err(
                    error::RegistrySnafu.into_error(tame_index::Error::Io(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        "network error",
                    ))),
                )
            });

            assert_matches!(result.unwrap_err(), error::Error::Registry { .. });
        }

        #[test]
        fn io_error_with_stale_returns_stale() {
            let (cache, _temp) = test_cache_with_timeout(Duration::from_secs(0));
            let spec = test_spec();
            let resolved = test_resolved();

            cache.put_resolved_crate(&spec, &resolved).unwrap();
            std::thread::sleep(Duration::from_secs(1));

            let result = cache.get_or_resolve_crate(&spec, || {
                Err(error::IoSnafu {
                    path: PathBuf::from("/fake/test/path"),
                }
                .into_error(std::io::Error::new(std::io::ErrorKind::Other, "io error")))
            });

            assert!(result.is_ok());
            assert_eq!(result.unwrap(), resolved);
        }

        #[test]
        fn other_error_never_uses_stale() {
            let (cache, _temp) = test_cache_with_timeout(Duration::from_secs(0));
            let spec = test_spec();
            let resolved = test_resolved();

            cache.put_resolved_crate(&spec, &resolved).unwrap();
            std::thread::sleep(Duration::from_secs(1));

            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();

            let result = cache.get_or_resolve_crate(&spec, || {
                *call_count_clone.borrow_mut() += 1;
                error::VersionMismatchSnafu {
                    requirement: "2.0.0".to_string(),
                    found: Version::parse("1.0.0").unwrap(),
                }
                .fail()
            });

            assert_eq!(*call_count.borrow(), 1, "Closure should have been called");
            assert_matches!(result.unwrap_err(), error::Error::VersionMismatch { .. });
        }

        #[test]
        fn successful_resolve_updates_cache() {
            let (cache, _temp) = test_cache_with_timeout(Duration::from_secs(0));
            let spec = test_spec();
            let old_resolved = test_resolved();
            let new_resolved = test_resolved_alt();

            cache.put_resolved_crate(&spec, &old_resolved).unwrap();
            std::thread::sleep(Duration::from_secs(1));

            let result = cache.get_or_resolve_crate(&spec, || Ok(new_resolved.clone()));

            assert!(result.is_ok());
            assert_eq!(result.unwrap(), new_resolved);

            let cached = cache.get_resolved_crate(&spec).unwrap();
            assert_eq!(cached.map(|e| e.value), Some(new_resolved));
        }

        #[test]
        fn refresh_bypasses_valid_cache() {
            let (cache, _temp) = test_cache_with_refresh();
            let spec = test_spec();
            let cached_resolved = test_resolved();
            let new_resolved = test_resolved_alt();

            cache.put_resolved_crate(&spec, &cached_resolved).unwrap();

            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();
            let new_resolved_clone = new_resolved.clone();

            let resolved_crate = cache
                .get_or_resolve_crate(&spec, || {
                    *call_count_clone.borrow_mut() += 1;
                    Ok(new_resolved_clone.clone())
                })
                .unwrap();

            assert_eq!(resolved_crate, new_resolved);
            assert_eq!(
                *call_count.borrow(),
                1,
                "Resolver should be called even with valid cache"
            );
        }

        #[test]
        fn refresh_disables_stale_cache_fallback() {
            let (cache, _temp) = test_cache_with_refresh();
            let spec = test_spec();
            let stale_resolved = test_resolved();

            cache
                .insert_stale_resolve_entry(&spec, &stale_resolved, Duration::from_secs(9999))
                .unwrap();

            let result = cache.get_or_resolve_crate(&spec, || {
                Err(
                    error::RegistrySnafu.into_error(tame_index::Error::Io(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        "network error",
                    ))),
                )
            });

            assert_matches!(result, Err(error::Error::Registry { .. }));
        }
    }

    mod get_or_download {
        use super::*;

        #[test]
        fn source_cache_hit_skips_downloader() {
            let (cache, _temp) = test_cache();
            let resolved = test_resolved();

            let cache_path = cache.crate_source_cache_path(&resolved).unwrap();
            fs::create_dir_all(&cache_path).unwrap();

            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();

            let result = cache.get_or_download_crate(&resolved, |_download_path| {
                *call_count_clone.borrow_mut() += 1;
                Err(error::IoSnafu {
                    path: PathBuf::from("/fake/test/path"),
                }
                .into_error(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "should not be called",
                )))
            });

            assert!(result.is_ok());
            assert_eq!(result.unwrap().crate_path, cache_path);
            assert_eq!(*call_count.borrow(), 0);
        }

        #[test]
        fn source_cache_miss_calls_downloader() {
            let (cache, _temp) = test_cache();
            let resolved = test_resolved();
            let cache_path = cache.crate_source_cache_path(&resolved).unwrap();

            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();

            let result = cache.get_or_download_crate(&resolved, |download_path| {
                *call_count_clone.borrow_mut() += 1;
                // Create a test file to simulate successful download
                fs::create_dir_all(download_path).unwrap();
                fs::write(download_path.join("test.txt"), b"test content").unwrap();
                Ok(())
            });

            assert!(result.is_ok());
            assert_eq!(result.unwrap().crate_path, cache_path);
            assert_eq!(*call_count.borrow(), 1);

            // Verify the downloaded file is in the cache
            assert!(cache_path.join("test.txt").exists());
        }

        #[test]
        fn download_error_without_cache() {
            let (cache, _temp) = test_cache();
            let resolved = test_resolved();

            let result = cache.get_or_download_crate(&resolved, |_download_path| {
                Err(error::IoSnafu {
                    path: PathBuf::from("/fake/test/path"),
                }
                .into_error(std::io::Error::new(std::io::ErrorKind::Other, "download failed")))
            });

            assert_matches!(result.unwrap_err(), error::Error::Io { .. });
        }

        #[test]
        fn successful_download_creates_cache_entry() {
            let (cache, _temp) = test_cache();
            let resolved = test_resolved();
            let cache_path = cache.crate_source_cache_path(&resolved).unwrap();

            // Verify cache doesn't exist initially
            assert!(!cache_path.exists());

            let result = cache.get_or_download_crate(&resolved, |download_path| {
                // Create multiple files to simulate real download
                fs::create_dir_all(download_path).unwrap();
                fs::write(download_path.join("Cargo.toml"), b"[package]\nname = \"test\"").unwrap();
                fs::write(download_path.join("lib.rs"), b"pub fn test() {}").unwrap();
                Ok(())
            });

            assert!(result.is_ok());
            let cached = result.unwrap();
            assert_eq!(cached.crate_path, cache_path);

            // Verify files are in the cache location, not temp
            assert!(cache_path.join("Cargo.toml").exists());
            assert!(cache_path.join("lib.rs").exists());
        }

        #[test]
        fn failed_download_does_not_create_cache_entry() {
            let (cache, _temp) = test_cache();
            let resolved = test_resolved();
            let cache_path = cache.crate_source_cache_path(&resolved).unwrap();

            let result = cache.get_or_download_crate(&resolved, |download_path| {
                // Create some files but then fail
                fs::create_dir_all(download_path).unwrap();
                fs::write(download_path.join("partial.txt"), b"partial data").unwrap();
                Err(error::IoSnafu {
                    path: PathBuf::from("/fake/test/path"),
                }
                .into_error(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "simulated failure",
                )))
            });

            assert_matches!(result.unwrap_err(), error::Error::Io { .. });

            // Verify cache path doesn't exist (no partial download)
            assert!(!cache_path.exists());

            // Verify no temp directories were left behind in the parent
            let cache_parent = cache_path.parent().unwrap();
            if cache_parent.exists() {
                let entries: Vec<_> = fs::read_dir(cache_parent)
                    .unwrap()
                    .filter_map(|e| e.ok())
                    .collect();
                // Should be empty or not contain our cache entry
                assert!(entries.is_empty() || !entries.iter().any(|e| e.path() == cache_path));
            }
        }

        #[test]
        fn race_condition_both_downloads_succeed() {
            let (cache, _temp) = test_cache();
            let resolved = test_resolved();
            let cache_path = cache.crate_source_cache_path(&resolved).unwrap();

            // Simulate first download
            let result1 = cache.get_or_download_crate(&resolved, |download_path| {
                fs::create_dir_all(download_path).unwrap();
                fs::write(download_path.join("version.txt"), b"download1").unwrap();
                Ok(())
            });

            assert!(result1.is_ok());
            let cached1 = result1.unwrap();
            assert_eq!(cached1.crate_path, cache_path);

            // Simulate second download (race condition - someone already downloaded)
            // This should return the existing cache without calling the downloader
            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();

            let result2 = cache.get_or_download_crate(&resolved, |download_path| {
                *call_count_clone.borrow_mut() += 1;
                fs::create_dir_all(download_path).unwrap();
                fs::write(download_path.join("version.txt"), b"download2").unwrap();
                Ok(())
            });

            assert!(result2.is_ok());
            let cached2 = result2.unwrap();
            assert_eq!(cached2.crate_path, cache_path);

            // Second downloader should not have been called
            assert_eq!(*call_count.borrow(), 0);

            // Verify first download's content is preserved
            let content = fs::read_to_string(cache_path.join("version.txt")).unwrap();
            assert_eq!(content, "download1");
        }

        #[test]
        fn refresh_bypasses_source_cache() {
            let (cache, _temp) = test_cache_with_refresh();
            let resolved = test_resolved();
            let cache_path = cache.crate_source_cache_path(&resolved).unwrap();

            fs::create_dir_all(&cache_path).unwrap();
            fs::write(cache_path.join("cached.txt"), b"cached content").unwrap();

            let call_count = Rc::new(RefCell::new(0));
            let call_count_clone = call_count.clone();

            let result = cache.get_or_download_crate(&resolved, |download_path| {
                *call_count_clone.borrow_mut() += 1;
                fs::create_dir_all(download_path).unwrap();
                fs::write(download_path.join("fresh.txt"), b"fresh content").unwrap();
                Ok(())
            });

            result.unwrap();
            assert_eq!(
                *call_count.borrow(),
                1,
                "Downloader should be called even with cached source"
            );
        }
    }

    mod binary_cache_hash {
        use super::*;
        use crate::builder::{BuildOptions, BuildTarget};

        #[test]
        fn same_inputs_produce_same_hash() {
            let options = BuildOptions {
                features: vec!["foo".to_string(), "bar".to_string()],
                profile: Some("release".to_string()),
                ..Default::default()
            };

            let hash1 = Cache::compute_build_hash(&options);
            let hash2 = Cache::compute_build_hash(&options);

            assert_eq!(hash1, hash2);
        }

        #[test]
        fn feature_order_doesnt_matter() {
            let options1 = BuildOptions {
                features: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
                ..Default::default()
            };
            let options2 = BuildOptions {
                features: vec!["baz".to_string(), "foo".to_string(), "bar".to_string()],
                ..Default::default()
            };

            assert_eq!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2),
                "Same features in different order should produce same hash"
            );
        }

        #[test]
        fn different_features_produce_different_hash() {
            let options1 = BuildOptions {
                features: vec!["foo".to_string()],
                ..Default::default()
            };
            let options2 = BuildOptions {
                features: vec!["bar".to_string()],
                ..Default::default()
            };

            assert_ne!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2)
            );
        }

        #[test]
        fn different_profile_produces_different_hash() {
            let options1 = BuildOptions {
                profile: Some("dev".to_string()),
                ..Default::default()
            };
            let options2 = BuildOptions {
                profile: Some("release".to_string()),
                ..Default::default()
            };

            assert_ne!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2)
            );
        }

        #[test]
        fn different_target_produces_different_hash() {
            let options1 = BuildOptions {
                target: Some("x86_64-unknown-linux-gnu".to_string()),
                ..Default::default()
            };
            let options2 = BuildOptions {
                target: Some("aarch64-unknown-linux-gnu".to_string()),
                ..Default::default()
            };

            assert_ne!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2)
            );
        }

        #[test]
        fn different_toolchain_produces_different_hash() {
            let options1 = BuildOptions {
                toolchain: Some("stable".to_string()),
                ..Default::default()
            };
            let options2 = BuildOptions {
                toolchain: Some("nightly".to_string()),
                ..Default::default()
            };

            assert_ne!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2)
            );
        }

        #[test]
        fn different_build_target_produces_different_hash() {
            let options1 = BuildOptions {
                build_target: BuildTarget::DefaultBin,
                ..Default::default()
            };
            let options2 = BuildOptions {
                build_target: BuildTarget::Bin("foo".to_string()),
                ..Default::default()
            };

            assert_ne!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2)
            );
        }

        #[test]
        fn all_features_affects_hash() {
            let options1 = BuildOptions {
                all_features: false,
                ..Default::default()
            };
            let options2 = BuildOptions {
                all_features: true,
                ..Default::default()
            };

            assert_ne!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2)
            );
        }

        #[test]
        fn no_default_features_affects_hash() {
            let options1 = BuildOptions {
                no_default_features: false,
                ..Default::default()
            };
            let options2 = BuildOptions {
                no_default_features: true,
                ..Default::default()
            };

            assert_ne!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2)
            );
        }

        #[test]
        fn locked_flag_affects_hash() {
            let options1 = BuildOptions {
                locked: true,
                ..Default::default()
            };
            let options2 = BuildOptions {
                locked: false,
                ..Default::default()
            };

            assert_ne!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2),
                "locked flag affects dependency resolution, so it must affect hash"
            );
        }

        #[test]
        fn offline_flag_does_not_affect_hash() {
            let options1 = BuildOptions {
                offline: true,
                ..Default::default()
            };
            let options2 = BuildOptions {
                offline: false,
                ..Default::default()
            };

            assert_eq!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2),
                "offline flag should not affect hash"
            );
        }

        #[test]
        fn jobs_does_not_affect_hash() {
            let options1 = BuildOptions {
                jobs: Some(1),
                ..Default::default()
            };
            let options2 = BuildOptions {
                jobs: Some(8),
                ..Default::default()
            };

            assert_eq!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2),
                "jobs setting should not affect hash"
            );
        }

        #[test]
        fn ignore_rust_version_does_not_affect_hash() {
            let options1 = BuildOptions {
                ignore_rust_version: true,
                ..Default::default()
            };
            let options2 = BuildOptions {
                ignore_rust_version: false,
                ..Default::default()
            };

            assert_eq!(
                Cache::compute_build_hash(&options1),
                Cache::compute_build_hash(&options2),
                "ignore_rust_version should not affect hash"
            );
        }

        #[test]
        fn source_hash_distinguishes_crates_io() {
            let hash = Cache::compute_source_hash(&ResolvedSource::CratesIo);
            assert_eq!(hash.len(), 16, "Hash should be 16 hex chars");
        }

        #[test]
        fn source_hash_distinguishes_git() {
            let hash1 = Cache::compute_source_hash(&ResolvedSource::Git {
                repo: "https://github.com/rust-lang/cargo".to_string(),
                commit: "abc123".to_string(),
            });
            let hash2 = Cache::compute_source_hash(&ResolvedSource::Git {
                repo: "https://github.com/rust-lang/cargo".to_string(),
                commit: "def456".to_string(),
            });

            assert_ne!(hash1, hash2, "Different commits should produce different hashes");
        }

        #[test]
        fn source_hash_distinguishes_forge() {
            let hash1 = Cache::compute_source_hash(&ResolvedSource::Forge {
                forge: Forge::GitHub {
                    custom_url: None,
                    owner: "rust-lang".to_string(),
                    repo: "cargo".to_string(),
                },
                commit: "abc123".to_string(),
            });
            let hash2 = Cache::compute_source_hash(&ResolvedSource::Forge {
                forge: Forge::GitHub {
                    custom_url: None,
                    owner: "rust-lang".to_string(),
                    repo: "cargo".to_string(),
                },
                commit: "def456".to_string(),
            });

            assert_ne!(hash1, hash2, "Different commits should produce different hashes");
        }

        #[test]
        fn source_hash_distinguishes_registry() {
            let hash1 = Cache::compute_source_hash(&ResolvedSource::Registry {
                source: RegistrySource::Named("my-registry".to_string()),
            });
            let hash2 = Cache::compute_source_hash(&ResolvedSource::Registry {
                source: RegistrySource::Named("other-registry".to_string()),
            });

            assert_ne!(
                hash1, hash2,
                "Different registries should produce different hashes"
            );
        }

        #[test]
        fn expected_binary_name_default_bin() {
            let name = Cache::expected_binary_name("my-crate", &BuildTarget::DefaultBin);
            #[cfg(windows)]
            assert_eq!(name, "my-crate.exe");
            #[cfg(not(windows))]
            assert_eq!(name, "my-crate");
        }

        #[test]
        fn expected_binary_name_specific_bin() {
            let name = Cache::expected_binary_name("my-crate", &BuildTarget::Bin("foo".to_string()));
            #[cfg(windows)]
            assert_eq!(name, "foo.exe");
            #[cfg(not(windows))]
            assert_eq!(name, "foo");
        }

        #[test]
        fn expected_binary_name_example() {
            let name = Cache::expected_binary_name("my-crate", &BuildTarget::Example("bar".to_string()));
            #[cfg(windows)]
            assert_eq!(name, "bar.exe");
            #[cfg(not(windows))]
            assert_eq!(name, "bar");
        }
    }

    mod utility {
        use super::*;

        #[test]
        fn hash_stability() {
            let spec = test_spec();

            let hash1 = Cache::compute_spec_hash(&spec).unwrap();
            let hash2 = Cache::compute_spec_hash(&spec).unwrap();

            assert_eq!(hash1, hash2);
        }

        #[test]
        fn hash_uniqueness() {
            let spec1 = test_spec();
            let spec2 = test_spec_alt();

            let hash1 = Cache::compute_spec_hash(&spec1).unwrap();
            let hash2 = Cache::compute_spec_hash(&spec2).unwrap();

            assert_ne!(hash1, hash2);
        }

        #[test]
        fn cache_path_format_crates_io() {
            let (cache, _temp) = test_cache();
            let resolved = test_resolved();

            let path = cache.crate_source_cache_path(&resolved).unwrap();
            let path_str = path.to_string_lossy();

            assert!(path_str.contains("sources"));
            assert!(path_str.contains("crates-io"));
            assert!(path_str.contains("serde"));
            assert!(path_str.contains("1.0.0"));
        }

        #[test]
        fn cache_path_format_git() {
            let (cache, _temp) = test_cache();
            let resolved = ResolvedCrate {
                name: "test".to_string(),
                version: Version::parse("1.0.0").unwrap(),
                source: ResolvedSource::Git {
                    repo: "https://github.com/test/test.git".to_string(),
                    commit: "abc123".to_string(),
                },
            };

            let path = cache.crate_source_cache_path(&resolved).unwrap();
            let path_str = path.to_string_lossy();

            assert!(path_str.contains("sources"));
            assert!(path_str.contains("git"));
            assert!(path_str.contains("abc123"));
        }

        #[test]
        fn cache_path_format_github() {
            let (cache, _temp) = test_cache();
            let resolved = ResolvedCrate {
                name: "test".to_string(),
                version: Version::parse("1.0.0").unwrap(),
                source: ResolvedSource::Forge {
                    forge: Forge::GitHub {
                        custom_url: None,
                        owner: "owner".to_string(),
                        repo: "repo".to_string(),
                    },
                    commit: "abc123".to_string(),
                },
            };

            let path = cache.crate_source_cache_path(&resolved).unwrap();
            let path_str = path.to_string_lossy();

            assert!(path_str.contains("sources"));
            assert!(path_str.contains("github"));
            assert!(path_str.contains("owner"));
            assert!(path_str.contains("repo"));
            assert!(path_str.contains("abc123"));
        }

        #[test]
        fn cache_path_format_gitlab() {
            let (cache, _temp) = test_cache();
            let resolved = ResolvedCrate {
                name: "test".to_string(),
                version: Version::parse("1.0.0").unwrap(),
                source: ResolvedSource::Forge {
                    forge: Forge::GitLab {
                        custom_url: None,
                        owner: "owner".to_string(),
                        repo: "repo".to_string(),
                    },
                    commit: "def456".to_string(),
                },
            };

            let path = cache.crate_source_cache_path(&resolved).unwrap();
            let path_str = path.to_string_lossy();

            assert!(path_str.contains("sources"));
            assert!(path_str.contains("gitlab"));
            assert!(path_str.contains("owner"));
            assert!(path_str.contains("repo"));
            assert!(path_str.contains("def456"));
        }

        #[test]
        fn cache_path_format_registry_named() {
            let (cache, _temp) = test_cache();
            let resolved = ResolvedCrate {
                name: "test".to_string(),
                version: Version::parse("1.0.0").unwrap(),
                source: ResolvedSource::Registry {
                    source: RegistrySource::Named("my-registry".to_string()),
                },
            };

            let path = cache.crate_source_cache_path(&resolved).unwrap();
            let path_str = path.to_string_lossy();

            assert!(path_str.contains("sources"));
            assert!(path_str.contains("registry"));
            assert!(path_str.contains("my-registry"));
            assert!(path_str.contains("test"));
            assert!(path_str.contains("1.0.0"));
        }

        #[test]
        fn cache_path_format_registry_index_url() {
            let (cache, _temp) = test_cache();
            let index_url = url::Url::parse("https://example.com/index").unwrap();
            let resolved = ResolvedCrate {
                name: "test".to_string(),
                version: Version::parse("1.0.0").unwrap(),
                source: ResolvedSource::Registry {
                    source: RegistrySource::IndexUrl(index_url),
                },
            };

            let path = cache.crate_source_cache_path(&resolved).unwrap();
            let path_str = path.to_string_lossy();

            assert!(path_str.contains("sources"));
            assert!(path_str.contains("registry-index"));
            assert!(path_str.contains("test"));
            assert!(path_str.contains("1.0.0"));
        }
    }
}