-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathmod.rs
More file actions
1723 lines (1489 loc) · 57.9 KB
/
mod.rs
File metadata and controls
1723 lines (1489 loc) · 57.9 KB
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
mod barrier_cell;
mod builder;
mod channel_config;
#[cfg(not(target_arch = "wasm32"))]
mod direct_url_query;
mod error;
#[cfg(feature = "indicatif")]
mod indicatif;
mod local_subdir;
mod query;
mod remote_subdir;
mod repo_data;
mod run_exports_extractor;
mod sharded_subdir;
mod source;
mod subdir;
mod subdir_builder;
use std::{collections::HashSet, sync::Arc};
use crate::{gateway::subdir_builder::SubdirBuilder, Reporter};
pub use barrier_cell::BarrierCell;
pub use builder::{GatewayBuilder, MaxConcurrency};
pub use channel_config::{ChannelConfig, SourceConfig};
use coalesced_map::{CoalescedGetError, CoalescedMap};
pub use error::GatewayError;
#[cfg(feature = "indicatif")]
pub use indicatif::{IndicatifReporter, IndicatifReporterBuilder};
pub use query::{NamesQuery, RepoDataQuery};
#[cfg(not(target_arch = "wasm32"))]
use rattler_cache::package_cache::PackageCache;
use rattler_conda_types::{Channel, MatchSpec, Platform, RepoDataRecord};
use rattler_networking::LazyClient;
pub use repo_data::RepoData;
use run_exports_extractor::{RunExportExtractor, SubdirRunExportsCache};
pub use run_exports_extractor::{RunExportExtractorError, RunExportsReporter};
pub use source::{RepoDataSource, Source};
use subdir::Subdir;
use tracing::{instrument, Level};
use url::Url;
/// Central access point for high level queries about
/// [`rattler_conda_types::RepoDataRecord`]s from different channels.
///
/// The gateway is responsible for fetching and caching repodata. Requests are
/// deduplicated which means that if multiple requests are made for the same
/// repodata only the first request will actually fetch the data. All other
/// requests will wait for the first request to complete and then return the
/// same data.
///
/// The gateway is thread-safe and can be shared between multiple threads. The
/// gateway struct itself uses internal reference counting and is cheaply
/// cloneable. There is no need to wrap the gateway in an `Arc`.
#[derive(Clone)]
pub struct Gateway {
inner: Arc<GatewayInner>,
}
impl Default for Gateway {
fn default() -> Self {
Gateway::new()
}
}
/// A selection of subdirectories.
#[derive(Default, Clone, Debug)]
pub enum SubdirSelection {
/// Select all subdirectories
#[default]
All,
/// Select these specific subdirectories
Some(HashSet<String>),
}
impl SubdirSelection {
/// Returns `true` if the given subdirectory is part of the selection.
pub fn contains(&self, subdir: &str) -> bool {
match self {
SubdirSelection::All => true,
SubdirSelection::Some(subdirs) => subdirs.contains(&subdir.to_string()),
}
}
}
/// Specifies what caches to clear.
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
pub enum CacheClearMode {
/// Only clear in-memory caches.
#[default]
InMemoryOnly,
/// Clear both in-memory and on-disk caches.
InMemoryAndDisk,
}
impl Gateway {
/// Constructs a simple gateway with the default configuration. Use
/// [`Gateway::builder`] if you want more control over how the gateway
/// is constructed.
pub fn new() -> Self {
Gateway::builder().finish()
}
/// Constructs a new gateway with the given client and channel
/// configuration.
pub fn builder() -> GatewayBuilder {
GatewayBuilder::default()
}
/// Constructs a new `GatewayQuery` which can be used to query repodata
/// records.
///
/// # Sources
///
/// The `sources` parameter accepts any type that implements `Into<Source>`.
/// This includes:
/// - `Channel` - traditional conda channels
/// - `Arc<dyn RepoDataSource>` - custom repodata sources
/// - `Source` - the enum itself
///
/// Existing code using channels continues to work unchanged:
///
/// ```ignore
/// gateway.query(
/// vec![channel1, channel2],
/// vec![Platform::Linux64],
/// vec![spec],
/// ).await
/// ```
///
/// You can also mix channels and custom sources:
///
/// ```ignore
/// gateway.query(
/// vec![
/// Source::Channel(channel),
/// Source::Custom(my_custom_source),
/// ],
/// vec![Platform::Linux64],
/// vec![spec],
/// ).await
/// ```
pub fn query<AsSource, SourceIter, PlatformIter, PackageNameIter, IntoMatchSpec>(
&self,
sources: SourceIter,
platforms: PlatformIter,
specs: PackageNameIter,
) -> RepoDataQuery
where
AsSource: Into<Source>,
SourceIter: IntoIterator<Item = AsSource>,
PlatformIter: IntoIterator<Item = Platform>,
<PlatformIter as IntoIterator>::IntoIter: Clone,
PackageNameIter: IntoIterator<Item = IntoMatchSpec>,
IntoMatchSpec: Into<MatchSpec>,
{
RepoDataQuery::new(
self.inner.clone(),
sources.into_iter().map(Into::into).collect(),
platforms.into_iter().collect(),
specs.into_iter().map(Into::into).collect(),
)
}
/// Return all names from repodata
pub fn names<AsChannel, ChannelIter, PlatformIter>(
&self,
channels: ChannelIter,
platforms: PlatformIter,
) -> NamesQuery
where
AsChannel: Into<Channel>,
ChannelIter: IntoIterator<Item = AsChannel>,
PlatformIter: IntoIterator<Item = Platform>,
<PlatformIter as IntoIterator>::IntoIter: Clone,
{
NamesQuery::new(
self.inner.clone(),
channels.into_iter().map(Into::into).collect(),
platforms.into_iter().collect(),
)
}
/// Ensure that given repodata records contain `RunExportsJson`.
pub async fn ensure_run_exports(
&self,
records: impl Iterator<Item = &mut RepoDataRecord>,
// We can avoid Arc by cloning, but this requires helper method in the trait definition.
progress_reporter: Option<Arc<dyn RunExportsReporter>>,
) -> Result<(), RunExportExtractorError> {
let futures = records
.filter_map(|record| {
if record.package_record.run_exports.is_some() {
// If the package already has run exports, we don't need to do anything.
return None;
}
let extractor = RunExportExtractor::default()
.with_opt_max_concurrent_requests(
self.inner.concurrent_requests_semaphore.clone(),
)
.with_client(self.inner.client.clone())
.with_global_run_exports_cache(self.inner.subdir_run_exports_cache.clone());
#[cfg(not(target_arch = "wasm32"))]
let extractor = extractor.with_package_cache(self.inner.package_cache.clone());
let progress_reporter = progress_reporter.clone();
Some(async move {
extractor
.extract(record, progress_reporter)
.await
.map(|rexp| (record, rexp))
})
})
.collect::<Vec<_>>();
let results = futures::future::try_join_all(futures).await?;
for (record, result) in results {
record.package_record.run_exports = result;
}
Ok(())
}
/// Clears any in-memory cache for the given channel.
///
/// Any subsequent query will re-fetch any required data from the source.
///
/// When `mode` is [`CacheClearMode::InMemoryAndDisk`], this method also
/// clears on-disk caches for the specified channel and subdirectories.
pub fn clear_repodata_cache(
&self,
channel: &Channel,
subdirs: SubdirSelection,
mode: CacheClearMode,
) -> Result<(), std::io::Error> {
self.inner.subdirs.retain(|key, _| {
key.0.base_url != channel.base_url || !subdirs.contains(key.1.as_str())
});
#[cfg(not(target_arch = "wasm32"))]
if mode == CacheClearMode::InMemoryAndDisk {
use std::str::FromStr;
let platforms_to_clear: Vec<Platform> = match &subdirs {
SubdirSelection::All => Platform::all().collect(),
SubdirSelection::Some(subdirs) => subdirs
.iter()
.filter_map(|s| Platform::from_str(s).ok())
.collect(),
};
let mut errors = Vec::new();
for platform in platforms_to_clear {
if let Err(e) = remote_subdir::RemoteSubdirClient::clear_cache(
&self.inner.cache,
channel,
platform,
) {
errors.push(e);
}
if let Err(e) =
sharded_subdir::ShardedSubdir::clear_cache(&self.inner.cache, channel, platform)
{
errors.push(e);
}
}
if let Some(first_error) = errors.into_iter().next() {
return Err(first_error);
}
}
#[cfg(target_arch = "wasm32")]
let _ = mode;
Ok(())
}
}
struct GatewayInner {
/// A map of subdirectories for each channel and platform.
subdirs: CoalescedMap<(Channel, Platform), Arc<Subdir>>,
/// The client to use to fetch repodata.
client: LazyClient,
/// The channel configuration
channel_config: ChannelConfig,
/// The directory to store any cache
#[cfg(not(target_arch = "wasm32"))]
cache: std::path::PathBuf,
/// The package cache, stored to reuse memory cache
#[cfg(not(target_arch = "wasm32"))]
package_cache: PackageCache,
/// A cache for global run exports.
subdir_run_exports_cache: Arc<SubdirRunExportsCache>,
/// A semaphore to limit the number of concurrent HTTP requests.
concurrent_requests_semaphore: Option<Arc<tokio::sync::Semaphore>>,
/// A semaphore to limit the number of concurrent IO operations (e.g.
/// reading shard files from the on-disk cache).
io_concurrency_semaphore: Option<Arc<tokio::sync::Semaphore>>,
}
impl GatewayInner {
/// Returns the [`Subdir`] for the given channel and platform. This
/// function will create the [`Subdir`] if it does not exist yet, otherwise
/// it will return the previously created subdir.
///
/// If multiple threads request the same subdir their requests will be
/// coalesced, and they will all receive the same subdir. If an error
/// occurs while creating the subdir all waiting tasks will also return an
/// error.
#[instrument(skip(self, reporter, channel), fields(channel = %channel.base_url), err(level = Level::INFO))]
async fn get_or_create_subdir(
&self,
channel: &Channel,
platform: Platform,
reporter: Option<Arc<dyn Reporter>>,
) -> Result<Arc<Subdir>, GatewayError> {
let key = (channel.clone(), platform);
let channel = channel.clone();
self.subdirs
.get_or_try_init(key, || async move {
let subdir = self.create_subdir(&channel, platform, reporter).await?;
Ok(Arc::new(subdir))
})
.await
.map_err(|e| match e {
CoalescedGetError::Init(gateway_err) => gateway_err,
CoalescedGetError::CoalescedRequestFailed => GatewayError::IoError(
"a coalesced request failed".to_string(),
std::io::ErrorKind::Other.into(),
),
})
}
async fn create_subdir(
&self,
channel: &Channel,
platform: Platform,
reporter: Option<Arc<dyn Reporter>>,
) -> Result<Subdir, GatewayError> {
SubdirBuilder::new(self, channel.clone(), platform, reporter)
.build()
.await
}
}
fn force_sharded_repodata(url: &Url) -> bool {
matches!(url.scheme(), "http" | "https")
&& matches!(url.host_str(), Some("fast.prefiks.dev" | "fast.prefix.dev"))
}
#[cfg(test)]
mod test {
use std::{
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
time::Instant,
};
use assert_matches::assert_matches;
use dashmap::DashSet;
use rattler_cache::{default_cache_dir, package_cache::PackageCache};
use rattler_conda_types::{
Channel, ChannelConfig, MatchSpec, PackageName,
ParseStrictness::{Lenient, Strict},
Platform, RepoDataRecord,
};
use rstest::rstest;
use url::Url;
use crate::{
fetch::CacheAction, gateway::Gateway, utils::simple_channel_server::SimpleChannelServer,
DownloadReporter, GatewayError, RepoData, Reporter, SourceConfig, SubdirSelection,
};
async fn local_conda_forge() -> Channel {
tokio::try_join!(
tools::fetch_test_conda_forge_repodata_async("noarch"),
tools::fetch_test_conda_forge_repodata_async("linux-64")
)
.unwrap();
Channel::from_directory(
&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test-data/channels/conda-forge"),
)
}
async fn remote_conda_forge() -> SimpleChannelServer {
tokio::try_join!(
tools::fetch_test_conda_forge_repodata_async("noarch"),
tools::fetch_test_conda_forge_repodata_async("linux-64")
)
.unwrap();
SimpleChannelServer::new(
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test-data/channels/conda-forge"),
)
.await
}
#[tokio::test]
async fn test_local_gateway() {
let gateway = Gateway::new();
let records = gateway
.query(
vec![local_conda_forge().await],
vec![Platform::Linux64, Platform::NoArch],
vec![PackageName::from_str("rubin-env").unwrap()].into_iter(),
)
.recursive(true)
.await
.unwrap();
let total_records: usize = records.iter().map(RepoData::len).sum();
assert_eq!(total_records, 45060);
}
#[tokio::test]
async fn test_remote_gateway() {
let gateway = Gateway::new();
let index = remote_conda_forge().await;
let records = gateway
.query(
vec![index.channel()],
vec![Platform::Linux64, Platform::Win32, Platform::NoArch],
vec![PackageName::from_str("rubin-env").unwrap()].into_iter(),
)
.recursive(true)
.await
.unwrap();
let total_records: usize = records.iter().map(RepoData::len).sum();
assert_eq!(total_records, 45060);
}
#[tokio::test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_direct_url_spec_from_gateway() {
let gateway = Gateway::builder()
.with_package_cache(PackageCache::new(
default_cache_dir()
.unwrap()
.join(rattler_cache::PACKAGE_CACHE_DIR),
))
.with_cache_dir(
default_cache_dir()
.unwrap()
.join(rattler_cache::REPODATA_CACHE_DIR),
)
.finish();
let index = local_conda_forge().await;
let records = gateway
.query(
vec![index.clone()],
vec![Platform::Win64],
vec![MatchSpec::from_str(
"https://conda.anaconda.org/conda-forge/win-64/openssl-3.3.1-h2466b09_1.conda",
Strict,
)
.unwrap()]
.into_iter(),
)
.recursive(true)
.await
.unwrap();
let non_openssl_direct_records = records
.iter()
.flat_map(RepoData::iter)
.filter(|record| record.package_record.name.as_normalized() != "openssl")
.collect::<Vec<_>>()
.len();
let records = gateway
.query(
vec![index],
vec![Platform::Linux64],
vec![MatchSpec::from_str("openssl ==3.3.1 h2466b09_1", Strict).unwrap()]
.into_iter(),
)
.recursive(true)
.await
.unwrap();
let non_openssl_total_records = records
.iter()
.flat_map(RepoData::iter)
.filter(|record| record.package_record.name.as_normalized() != "openssl")
.collect::<Vec<_>>()
.len();
// The total records without the matchspec should be the same.
assert_eq!(non_openssl_total_records, non_openssl_direct_records);
}
// Make sure that the direct url version of openssl is used instead of the one
// from the normal channel.
#[tokio::test]
async fn test_select_forced_url_instead_of_deps() {
let gateway = Gateway::builder()
.with_package_cache(PackageCache::new(
default_cache_dir()
.unwrap()
.join(rattler_cache::PACKAGE_CACHE_DIR),
))
.with_cache_dir(
default_cache_dir()
.unwrap()
.join(rattler_cache::REPODATA_CACHE_DIR),
)
.finish();
let index = local_conda_forge().await;
let openssl_url =
"https://conda.anaconda.org/conda-forge/win-64/openssl-3.3.1-h2466b09_1.conda";
let records = gateway
.query(
vec![index.clone()],
vec![Platform::Linux64],
vec![
MatchSpec::from_str("mamba ==0.9.2 py39h951de11_0", Strict).unwrap(),
MatchSpec::from_str(openssl_url, Strict).unwrap(),
]
.into_iter(),
)
.recursive(true)
.await
.unwrap();
let total_records_single_openssl: usize = records.iter().map(RepoData::len).sum();
assert_eq!(total_records_single_openssl, 4219);
// There should be only one record for the openssl package.
let openssl_records: Vec<&RepoDataRecord> = records
.iter()
.flat_map(RepoData::iter)
.filter(|record| record.package_record.name.as_normalized() == "openssl")
.collect();
assert_eq!(openssl_records.len(), 1);
// Test if the first repodata subdir contains only the direct url package.
let first_subdir = records.first().unwrap();
assert_eq!(first_subdir.len(), 1);
let openssl_record = first_subdir
.iter()
.find(|record| record.package_record.name.as_normalized() == "openssl")
.unwrap();
assert_eq!(openssl_record.url.as_str(), openssl_url);
// ------------------------------------------------------------
// Now we query for the openssl package without the direct url.
// ------------------------------------------------------------
let gateway = Gateway::new();
let records = gateway
.query(
vec![index.clone()],
vec![Platform::Linux64],
vec![MatchSpec::from_str("mamba ==0.9.2 py39h951de11_0", Strict).unwrap()]
.into_iter(),
)
.recursive(true)
.await
.unwrap();
let total_records: usize = records.iter().map(RepoData::len).sum();
// The total number of records should be greater than the number of records
// fetched when selecting the openssl with a direct url.
assert!(total_records > total_records_single_openssl);
assert_eq!(total_records, 4267);
let openssl_records: Vec<&RepoDataRecord> = records
.iter()
.flat_map(RepoData::iter)
.filter(|record| record.package_record.name.as_normalized() == "openssl")
.collect();
assert!(openssl_records.len() > 1);
}
#[tokio::test]
async fn test_filter_with_specs() {
let gateway = Gateway::new();
let index = local_conda_forge().await;
// Try a complex spec
let matchspec = MatchSpec::from_str("openssl=3.*=*_1", Lenient).unwrap();
let records = gateway
.query(
vec![index.clone()],
vec![Platform::Linux64],
vec![matchspec].into_iter(),
)
.recursive(false)
.await
.unwrap();
let total_records: usize = records.iter().map(RepoData::len).sum();
assert!(total_records == 3);
let _repodata_records = records
.iter()
.flat_map(|r| r.iter().cloned())
.collect::<Vec<_>>();
// Try another spec
let matchspec = MatchSpec::from_str("openssl=3", Lenient).unwrap();
let records = gateway
.query(
vec![index.clone()],
vec![Platform::Linux64],
vec![matchspec].into_iter(),
)
.recursive(false)
.await
.unwrap();
let total_records: usize = records.iter().map(RepoData::len).sum();
assert!(total_records == 9);
// Try with multiple specs
let matchspec1 = MatchSpec::from_str("openssl=3", Lenient).unwrap();
let matchspec2 = MatchSpec::from_str("openssl=1", Lenient).unwrap();
let records = gateway
.query(
vec![index.clone()],
vec![Platform::Linux64],
vec![matchspec1, matchspec2].into_iter(),
)
.recursive(false)
.await
.unwrap();
let total_records: usize = records.iter().map(RepoData::len).sum();
assert!(total_records == 49);
}
#[tokio::test]
async fn test_nameless_matchspec_error() {
let gateway = Gateway::new();
let index = local_conda_forge().await;
let mut matchspec = MatchSpec::from_str(
"https://conda.anaconda.org/conda-forge/linux-64/openssl-3.0.4-h166bdaf_2.tar.bz2",
Strict,
)
.unwrap();
matchspec.name = "*".parse().expect("wildcard always parses");
let gateway_error = gateway
.query(
vec![index.clone()],
vec![Platform::Linux64],
vec![matchspec].into_iter(),
)
.recursive(true)
.await
.unwrap_err();
assert_matches!(gateway_error, GatewayError::MatchSpecWithoutExactName(_));
}
#[rstest]
#[case::named("non-existing-channel")]
#[case::url("https://conda.anaconda.org/does-not-exist")]
#[case::file_url("file:///does/not/exist")]
#[case::win_path("c:/does-not-exist")]
#[case::unix_path("/does-not-exist")]
#[tokio::test]
async fn test_doesnt_exist(#[case] channel: &str) {
let gateway = Gateway::new();
let default_channel_config = ChannelConfig::default_with_root_dir(PathBuf::new());
let err = gateway
.query(
vec![Channel::from_str(channel, &default_channel_config).unwrap()],
vec![Platform::Linux64, Platform::NoArch],
vec![PackageName::from_str("some-package").unwrap()].into_iter(),
)
.await;
assert_matches::assert_matches!(err, Err(GatewayError::SubdirNotFoundError(_)));
}
#[ignore]
#[tokio::test(flavor = "multi_thread")]
async fn test_sharded_gateway() {
let gateway = Gateway::new();
let start = Instant::now();
let records = gateway
.query(
vec![Channel::from_url(
Url::parse("https://conda.anaconda.org/conda-forge").unwrap(),
)],
vec![Platform::Linux64, Platform::NoArch],
vec![
// PackageName::from_str("rubin-env").unwrap(),
// PackageName::from_str("jupyterlab").unwrap(),
// PackageName::from_str("detectron2").unwrap(),
PackageName::from_str("python").unwrap(),
PackageName::from_str("boto3").unwrap(),
PackageName::from_str("requests").unwrap(),
]
.into_iter(),
)
.recursive(true)
.await
.unwrap();
let end = Instant::now();
println!("{} records in {:?}", records.len(), end - start);
let total_records: usize = records.iter().map(RepoData::len).sum();
assert_eq!(total_records, 84242);
}
#[tokio::test]
async fn test_clear_cache() {
#[derive(Default)]
struct Downloads {
urls: DashSet<Url>,
}
impl DownloadReporter for Arc<Downloads> {
fn on_download_complete(&self, url: &Url, _index: usize) {
self.urls.insert(url.clone());
}
}
impl Reporter for Arc<Downloads> {
fn download_reporter(&self) -> Option<&dyn DownloadReporter> {
Some(self)
}
}
let local_channel = remote_conda_forge().await;
// Create a gateway with a custom channel configuration that disables caching.
let gateway = Gateway::builder()
.with_channel_config(super::ChannelConfig {
default: SourceConfig {
cache_action: CacheAction::NoCache,
..Default::default()
},
..Default::default()
})
.finish();
let downloads = Arc::new(Downloads::default());
// Construct a simple query
let query = gateway
.query(
vec![local_channel.channel()],
vec![Platform::Linux64, Platform::NoArch],
vec![PackageName::from_str("python").unwrap()].into_iter(),
)
.with_reporter(downloads.clone());
// Run the query once. We expect some activity.
query.clone().execute().await.unwrap();
assert!(!downloads.urls.is_empty(), "there should be some urls");
downloads.urls.clear();
// Run the query a second time.
query.clone().execute().await.unwrap();
assert!(
downloads.urls.is_empty(),
"there should be NO new url fetches"
);
// Now clear the cache and run the query again.
gateway
.clear_repodata_cache(
&local_channel.channel(),
SubdirSelection::default(),
super::CacheClearMode::InMemoryOnly,
)
.unwrap();
query.clone().execute().await.unwrap();
assert!(
!downloads.urls.is_empty(),
"after clearing the cache there should be new urls fetched"
);
}
#[test]
fn test_clear_disk_cache() {
use crate::gateway::remote_subdir::RemoteSubdirClient;
let cache_dir = tempfile::tempdir().unwrap();
// Create a test channel
let channel_config = ChannelConfig::default_with_root_dir(PathBuf::new());
let channel = Channel::from_str("conda-forge", &channel_config).unwrap();
// Create mock cache files for linux-64 platform
let subdir_url = channel.platform_url(Platform::Linux64);
let cache_key = crate::utils::url_to_cache_filename(
&subdir_url.join("repodata.json").expect("valid filename"),
);
// Create mock cache files
let json_path = cache_dir.path().join(format!("{cache_key}.json"));
let info_path = cache_dir.path().join(format!("{cache_key}.info.json"));
let lock_path = cache_dir.path().join(format!("{cache_key}.lock"));
std::fs::write(&json_path, b"{}").unwrap();
std::fs::write(&info_path, b"{}").unwrap();
std::fs::write(&lock_path, b"").unwrap();
// Verify files exist
assert!(json_path.exists(), "json file should exist before clear");
assert!(info_path.exists(), "info file should exist before clear");
assert!(lock_path.exists(), "lock file should exist before clear");
// Clear the disk cache
RemoteSubdirClient::clear_cache(cache_dir.path(), &channel, Platform::Linux64).unwrap();
// Verify json and info files are removed but lock file remains
assert!(
!json_path.exists(),
"json file should be removed after clear"
);
assert!(
!info_path.exists(),
"info file should be removed after clear"
);
assert!(
lock_path.exists(),
"lock file should remain after clear to avoid ABA problem"
);
}
#[test]
fn test_clear_sharded_disk_cache() {
use crate::gateway::sharded_subdir::{
ShardedSubdir, REPODATA_SHARDS_FILENAME, SHARDS_CACHE_SUFFIX,
};
let cache_dir = tempfile::tempdir().unwrap();
// Create a test channel
let channel_config = ChannelConfig::default_with_root_dir(PathBuf::new());
let channel = Channel::from_str("conda-forge", &channel_config).unwrap();
// Create mock sharded cache file for linux-64 platform
let index_base_url = channel
.base_url
.url()
.join(&format!("{}/", Platform::Linux64.as_str()))
.expect("invalid subdir url");
let canonical_shards_url = index_base_url
.join(REPODATA_SHARDS_FILENAME)
.expect("invalid shard base url");
let cache_path = cache_dir.path().join(format!(
"{}{}",
crate::utils::url_to_cache_filename(&canonical_shards_url),
SHARDS_CACHE_SUFFIX
));
// Create mock cache file
std::fs::write(&cache_path, b"mock shard data").unwrap();
// Verify file exists
assert!(
cache_path.exists(),
"sharded cache file should exist before clear"
);
// Clear the disk cache
ShardedSubdir::clear_cache(cache_dir.path(), &channel, Platform::Linux64).unwrap();
// Verify cache file is removed
assert!(
!cache_path.exists(),
"sharded cache file should be removed after clear"
);
}
#[test]
fn test_clear_disk_cache_no_cache() {
use crate::gateway::remote_subdir::RemoteSubdirClient;
let cache_dir = tempfile::tempdir().unwrap();
// Create a test channel
let channel_config = ChannelConfig::default_with_root_dir(PathBuf::new());
let channel = Channel::from_str("conda-forge", &channel_config).unwrap();
// Clear should succeed even when there's no cache (empty directory)
RemoteSubdirClient::clear_cache(cache_dir.path(), &channel, Platform::Linux64).unwrap();
// Clear should also succeed when the cache directory doesn't exist at all
let non_existent_dir = cache_dir.path().join("does-not-exist");
RemoteSubdirClient::clear_cache(&non_existent_dir, &channel, Platform::Linux64).unwrap();
}
#[test]
fn test_clear_sharded_disk_cache_no_cache() {
use crate::gateway::sharded_subdir::ShardedSubdir;
let cache_dir = tempfile::tempdir().unwrap();
// Create a test channel
let channel_config = ChannelConfig::default_with_root_dir(PathBuf::new());
let channel = Channel::from_str("conda-forge", &channel_config).unwrap();
// Clear should succeed even when there's no cache (empty directory)
ShardedSubdir::clear_cache(cache_dir.path(), &channel, Platform::Linux64).unwrap();
// Clear should also succeed when the cache directory doesn't exist at all
let non_existent_dir = cache_dir.path().join("does-not-exist");
ShardedSubdir::clear_cache(&non_existent_dir, &channel, Platform::Linux64).unwrap();
}
#[test]
fn test_gateway_clear_repodata_cache() {
let cache_dir = tempfile::tempdir().unwrap();
// Create a test channel
let channel_config = ChannelConfig::default_with_root_dir(PathBuf::new());
let channel = Channel::from_str("conda-forge", &channel_config).unwrap();
// Create a gateway with the custom cache directory
let gateway = Gateway::builder()
.with_cache_dir(cache_dir.path().to_path_buf())
.finish();
// Clear should succeed even when there's no cache
gateway
.clear_repodata_cache(
&channel,
SubdirSelection::default(),
super::CacheClearMode::InMemoryAndDisk,
)
.unwrap();
// Clear with specific subdirs should also succeed
gateway
.clear_repodata_cache(
&channel,
SubdirSelection::Some(
["linux-64", "noarch"]
.into_iter()
.map(String::from)
.collect(),
),
super::CacheClearMode::InMemoryAndDisk,
)
.unwrap();
// Clear in-memory only should also succeed
gateway
.clear_repodata_cache(
&channel,
SubdirSelection::default(),
super::CacheClearMode::InMemoryOnly,
)
.unwrap();
}
/// Helper function to generate minimal repodata JSON for a single package.
fn make_repodata(name: &str, version: &str) -> String {
format!(
r#"{{
"packages.conda": {{
"{name}-{version}-0.conda": {{
"build": "0",
"build_number": 0,
"depends": [],
"md5": "00000000000000000000000000000000",
"name": "{name}",
"sha256": "0000000000000000000000000000000000000000000000000000000000000000",
"size": 1000,
"subdir": "linux-64",
"timestamp": 1700000000000,
"version": "{version}"
}}
}}
}}"#
)