1#![deny(missing_docs)]
12
13use crate::error::{Error, Result};
14use crate::models::{Package, PackageIndex, SerializedPackageIndex};
15use crate::progress::{NoopProgress, ProgressReporter};
16use crate::retry::{RetryPolicy, retry_http};
17use crate::util::{SizeCap, io_context};
18
19use chrono::prelude::*;
20use futures::stream::StreamExt;
21use reqwest::Client;
22use reqwest::header;
23use std::collections::HashMap;
24use std::io::Read;
25use std::path::{Path, PathBuf};
26use std::sync::Arc;
27use std::sync::atomic::{AtomicU64, Ordering};
28use std::time::Duration;
29use tokio::fs;
30use tokio::io::{AsyncReadExt, AsyncWriteExt};
31
32const DEFAULT_BASE_URL: &str = "https://thunderstore.io";
34const LAST_MODIFIED_FILENAME: &str = "last_modified";
35const API_MANIFEST_FILENAME: &str = "api_manifest.bin.zst";
36
37const INDEX_CACHE_SUBDIR: &str = "index";
44
45const DEFAULT_MAX_DOWNLOAD_BYTES: u64 = 2 * 1024 * 1024 * 1024;
50
51const DEFAULT_MAX_MANIFEST_BYTES: u64 = 512 * 1024 * 1024;
58
59const DEFAULT_MAX_MANIFEST_DECOMPRESSED_BYTES: usize = 512 * 1024 * 1024;
75
76const MAX_DECODE_ALLOC: usize = 1024 * 1024 * 1024;
85
86const MAX_LAST_MODIFIED_BYTES: u64 = 4096;
90
91const PROFILE_API_PATH: &str = "api/experimental/legacyprofile";
94
95const MAX_PROFILE_CODE_BYTES: u64 = 64 * 1024 * 1024;
99
100const PACKAGE_API_PATH: &str = "api/experimental/package";
103
104const MAX_README_BYTES: u64 = 16 * 1024 * 1024;
107
108#[derive(Debug, Clone)]
110#[expect(
111 clippy::large_enum_variant,
112 reason = "returned once per refresh and matched at once, like Result<PackageIndex>"
113)]
114pub enum Refreshed {
115 Unchanged,
117 Updated(PackageIndex),
119}
120
121pub struct ThunderstoreClient {
125 http: Client,
126 package_index_url: String,
127 base_url: String,
128 cache_dir: PathBuf,
129 index_cache_key: String,
130 progress: Arc<dyn ProgressReporter>,
131 download_concurrency: usize,
132 max_download_bytes: Option<u64>,
133 max_manifest_bytes: Option<u64>,
134 max_manifest_decompressed_bytes: usize,
135 retry: RetryPolicy,
136}
137
138impl ThunderstoreClient {
139 pub fn builder() -> ThunderstoreClientBuilder {
165 ThunderstoreClientBuilder::default()
166 }
167
168 pub fn package_index_url(&self) -> &str {
170 &self.package_index_url
171 }
172
173 pub fn base_url(&self) -> &str {
175 &self.base_url
176 }
177
178 pub fn cache_dir(&self) -> &Path {
180 &self.cache_dir
181 }
182
183 fn index_cache_dir(&self) -> PathBuf {
190 self
191 .cache_dir
192 .join(INDEX_CACHE_SUBDIR)
193 .join(&self.index_cache_key)
194 }
195
196 pub async fn get_manifest(&self) -> Result<PackageIndex> {
217 let index_dir = self.index_cache_dir();
218 let last_modified = local_last_modified(&index_dir).await?;
219 tracing::info!("Manifest last modified: {}", last_modified);
220
221 if api_manifest_file_exists(&index_dir) {
222 match network_last_modified(&self.http, &self.package_index_url).await {
223 Ok(network) if is_fresh(network, last_modified) => {
224 tracing::info!("Loading manifest from cache");
225
226 if let Some(manifest) =
227 load_cached_index(&index_dir, self.max_manifest_decompressed_bytes).await
228 {
229 return Ok(manifest);
230 }
231 }
232 Ok(_) => tracing::info!("Cache is stale; downloading new manifest"),
233 Err(err) => {
234 tracing::warn!("Freshness check failed ({}); serving cached manifest", err);
235
236 if let Some(manifest) =
237 load_cached_index(&index_dir, self.max_manifest_decompressed_bytes).await
238 {
239 return Ok(manifest);
240 }
241 }
242 }
243 }
244
245 tracing::info!("Downloading new manifest");
246
247 get_manifest_from_network_and_cache(
248 &index_dir,
249 &self.http,
250 &self.package_index_url,
251 self.max_manifest_bytes,
252 &self.retry,
253 self.progress.as_ref(),
254 )
255 .await
256 }
257
258 pub async fn cached_index(&self) -> Result<Option<PackageIndex>> {
274 let path = api_manifest_path(&self.index_cache_dir());
275 let limit = self.max_manifest_decompressed_bytes;
276
277 let decoded = tokio::task::spawn_blocking(move || decode_cached_manifest(&path, limit))
280 .await
281 .map_err(|e| Error::Cache(format!("cache decode task panicked: {}", e)))?;
282
283 match decoded {
284 Ok(index) => Ok(Some(index)),
285 Err(Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
286 Err(err) => Err(err),
287 }
288 }
289
290 pub async fn refresh_if_stale(&self) -> Result<Refreshed> {
312 let index_dir = self.index_cache_dir();
313
314 if api_manifest_file_exists(&index_dir) {
315 let local = local_last_modified(&index_dir).await?;
316 let network = network_last_modified(&self.http, &self.package_index_url).await?;
317
318 if is_fresh(network, local) {
319 return Ok(Refreshed::Unchanged);
320 }
321 }
322
323 self.refresh_index().await.map(Refreshed::Updated)
324 }
325
326 pub async fn refresh_index(&self) -> Result<PackageIndex> {
334 get_manifest_from_network_and_cache(
335 &self.index_cache_dir(),
336 &self.http,
337 &self.package_index_url,
338 self.max_manifest_bytes,
339 &self.retry,
340 self.progress.as_ref(),
341 )
342 .await
343 }
344
345 pub async fn download_files(&self, urls: HashMap<String, String>) -> Result<()> {
367 download_files(
368 urls,
369 &self.cache_dir,
370 &self.http,
371 self.download_concurrency,
372 self.max_download_bytes,
373 self.retry,
374 self.progress.clone(),
375 )
376 .await
377 }
378
379 pub(crate) async fn download_files_for(
382 &self,
383 urls: HashMap<String, String>,
384 operation: &crate::progress::Operation,
385 ) -> Result<()> {
386 let reporter =
387 crate::progress::OperationDownloads::new(operation.clone(), self.progress.clone());
388
389 download_files(
390 urls,
391 &self.cache_dir,
392 &self.http,
393 self.download_concurrency,
394 self.max_download_bytes,
395 self.retry,
396 Arc::new(reporter),
397 )
398 .await
399 }
400
401 pub async fn create_profile_code(&self, payload: &[u8]) -> Result<String> {
416 let url = format!("{}/{}/create/", self.base_url, PROFILE_API_PATH);
417
418 let key = retry_http(&self.retry, || async {
419 let response = self
420 .http
421 .post(&url)
422 .header(header::CONTENT_TYPE, "application/octet-stream")
423 .body(payload.to_vec())
424 .send()
425 .await?
426 .error_for_status()?;
427
428 let body = read_capped_body(response, Some(MAX_PROFILE_CODE_BYTES)).await?;
429 let parsed: ProfileCodeResponse = serde_json::from_slice(&body)?;
430
431 Ok(parsed.key)
432 })
433 .await?;
434
435 Ok(key)
436 }
437
438 pub async fn fetch_profile_code(&self, code: &str) -> Result<Vec<u8>> {
454 validate_profile_code(code)?;
455
456 let url = format!("{}/{}/get/{}/", self.base_url, PROFILE_API_PATH, code);
457
458 let body = retry_http(&self.retry, || async {
459 let response = self.http.get(&url).send().await?.error_for_status()?;
460
461 read_capped_body(response, Some(MAX_PROFILE_CODE_BYTES)).await
462 })
463 .await?;
464
465 Ok(body)
466 }
467
468 pub async fn get_readme(&self, owner: &str, name: &str, version: &str) -> Result<Option<String>> {
486 for segment in [owner, name, version] {
487 validate_package_segment(segment)?;
488 }
489
490 let url = format!(
491 "{}/{}/{owner}/{name}/{version}/readme/",
492 self.base_url, PACKAGE_API_PATH
493 );
494
495 retry_http(&self.retry, || async {
496 let response = self.http.get(&url).send().await?;
497
498 if response.status() == reqwest::StatusCode::NOT_FOUND {
499 return Ok(None);
500 }
501
502 let body = read_capped_body(response.error_for_status()?, Some(MAX_README_BYTES)).await?;
503 let parsed: ReadmeResponse = serde_json::from_slice(&body)?;
504
505 Ok(Some(parsed.markdown))
506 })
507 .await
508 }
509}
510
511pub struct ThunderstoreClientBuilder {
513 base_url: Option<String>,
514 community: Option<String>,
515 package_index_url: Option<String>,
516 cache_dir: Option<PathBuf>,
517 progress: Option<Arc<dyn ProgressReporter>>,
518 download_concurrency: usize,
519 download_timeout: Duration,
520 max_download_bytes: Option<u64>,
521 max_manifest_bytes: Option<u64>,
522 max_manifest_decompressed_bytes: Option<u64>,
523 retry: RetryPolicy,
524 user_agent: Option<String>,
525}
526
527impl Default for ThunderstoreClientBuilder {
528 fn default() -> Self {
529 Self {
530 base_url: None,
531 community: None,
532 package_index_url: None,
533 cache_dir: None,
534 progress: None,
535 download_concurrency: 2,
536 download_timeout: Duration::from_secs(60),
537 max_download_bytes: Some(DEFAULT_MAX_DOWNLOAD_BYTES),
538 max_manifest_bytes: Some(DEFAULT_MAX_MANIFEST_BYTES),
539 max_manifest_decompressed_bytes: None,
542 retry: RetryPolicy::default(),
543 user_agent: None,
544 }
545 }
546}
547
548impl ThunderstoreClientBuilder {
549 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
551 self.base_url = Some(base_url.into());
552
553 self
554 }
555
556 pub fn community(mut self, community: impl Into<String>) -> Self {
559 self.community = Some(community.into());
560
561 self
562 }
563
564 pub fn package_index_url(mut self, url: impl Into<String>) -> Self {
568 self.package_index_url = Some(url.into());
569
570 self
571 }
572
573 pub fn cache_dir(mut self, cache_dir: impl Into<PathBuf>) -> Self {
575 self.cache_dir = Some(cache_dir.into());
576
577 self
578 }
579
580 pub fn progress(mut self, progress: Arc<dyn ProgressReporter>) -> Self {
582 self.progress = Some(progress);
583
584 self
585 }
586
587 pub fn download_concurrency(mut self, concurrency: usize) -> Self {
589 self.download_concurrency = concurrency;
590
591 self
592 }
593
594 pub fn download_timeout(mut self, timeout: Duration) -> Self {
599 self.download_timeout = timeout;
600
601 self
602 }
603
604 pub fn manifest_max_bytes(mut self, max_bytes: u64) -> Self {
615 self.max_manifest_bytes = Some(max_bytes);
616
617 self
618 }
619
620 pub fn manifest_max_decompressed_bytes(mut self, max_bytes: u64) -> Self {
636 self.max_manifest_decompressed_bytes = Some(max_bytes);
637
638 self
639 }
640
641 pub fn retry(mut self, policy: RetryPolicy) -> Self {
647 self.retry = policy;
648
649 self
650 }
651
652 pub fn max_retries(mut self, max_retries: u32) -> Self {
655 self.retry.max_retries = max_retries;
656
657 self
658 }
659
660 pub fn download_max_bytes(mut self, max_bytes: u64) -> Self {
667 self.max_download_bytes = Some(max_bytes);
668
669 self
670 }
671
672 pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
679 self.user_agent = Some(user_agent.into());
680
681 self
682 }
683
684 pub fn build(self) -> Result<ThunderstoreClient> {
691 let cache_dir = self
692 .cache_dir
693 .ok_or_else(|| Error::Config("cache_dir is required".to_string()))?;
694
695 let base_url = self
696 .base_url
697 .clone()
698 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
699 .trim_end_matches('/')
700 .to_string();
701
702 let package_index_url = compose_index_url(
703 self.base_url.as_deref().unwrap_or(DEFAULT_BASE_URL),
704 self.community.as_deref(),
705 self.package_index_url.as_deref(),
706 )?;
707
708 let index_cache_key = format!("{:08x}", crc32fast::hash(package_index_url.as_bytes()));
709
710 let max_manifest_decompressed_bytes = resolve_decompressed_cap(
711 self.max_manifest_decompressed_bytes,
712 self.max_manifest_bytes,
713 );
714
715 let mut http = Client::builder()
722 .connect_timeout(self.download_timeout)
723 .read_timeout(self.download_timeout)
724 .redirect(reqwest::redirect::Policy::limited(10));
725
726 if let Some(user_agent) = self.user_agent {
727 http = http.user_agent(user_agent);
728 }
729
730 let http = http.build()?;
731 let progress = self.progress.unwrap_or_else(|| Arc::new(NoopProgress));
732
733 Ok(ThunderstoreClient {
734 http,
735 package_index_url,
736 base_url,
737 cache_dir,
738 index_cache_key,
739 progress,
740 download_concurrency: self.download_concurrency,
741 max_download_bytes: self.max_download_bytes,
742 max_manifest_bytes: self.max_manifest_bytes,
743 max_manifest_decompressed_bytes,
744 retry: self.retry,
745 })
746 }
747}
748
749fn validate_community(community: &str) -> Result<()> {
753 let is_slug = !community.is_empty()
754 && community
755 .chars()
756 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
757
758 if !is_slug {
759 return Err(Error::Config(format!(
760 "invalid community slug {:?}: expected only ASCII letters, digits, '-', and '_'",
761 community
762 )));
763 }
764
765 Ok(())
766}
767
768fn compose_index_url(
776 base_url: &str,
777 community: Option<&str>,
778 override_url: Option<&str>,
779) -> Result<String> {
780 if let Some(url) = override_url {
781 return Ok(url.to_string());
782 }
783
784 let community = community.ok_or_else(|| Error::Config("community is required".to_string()))?;
785
786 validate_community(community)?;
787
788 Ok(format!(
789 "{}/c/{}/api/v1/package/",
790 base_url.trim_end_matches('/'),
791 community
792 ))
793}
794
795#[derive(serde::Deserialize)]
797struct ProfileCodeResponse {
798 key: String,
799}
800
801fn validate_profile_code(code: &str) -> Result<()> {
805 let is_valid = !code.is_empty()
806 && code
807 .chars()
808 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
809
810 if !is_valid {
811 return Err(Error::Config(format!(
812 "invalid profile code {code:?}: expected only ASCII letters, digits, '-', and '_'"
813 )));
814 }
815
816 Ok(())
817}
818
819#[derive(serde::Deserialize)]
821struct ReadmeResponse {
822 markdown: String,
823}
824
825fn validate_package_segment(segment: &str) -> Result<()> {
828 let is_valid = !matches!(segment, "" | "." | "..")
829 && segment
830 .chars()
831 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
832
833 if !is_valid {
834 return Err(Error::Config(format!(
835 "invalid package segment {segment:?}: expected only ASCII letters, digits, '-', '_', and '.'"
836 )));
837 }
838
839 Ok(())
840}
841
842fn resolve_decompressed_cap(configured: Option<u64>, download_cap: Option<u64>) -> usize {
850 configured
851 .or(download_cap)
852 .map(|n| usize::try_from(n).unwrap_or(usize::MAX))
853 .unwrap_or(DEFAULT_MAX_MANIFEST_DECOMPRESSED_BYTES)
854}
855
856fn last_modified_path(cache_dir: &Path) -> PathBuf {
858 cache_dir.join(LAST_MODIFIED_FILENAME)
859}
860
861fn api_manifest_path(cache_dir: &Path) -> PathBuf {
863 cache_dir.join(API_MANIFEST_FILENAME)
864}
865
866#[cfg(test)]
878async fn get_manifest_from_disk(cache_dir: &Path) -> Result<PackageIndex> {
879 get_manifest_from_disk_with_limit(cache_dir, DEFAULT_MAX_MANIFEST_DECOMPRESSED_BYTES).await
880}
881
882async fn get_manifest_from_disk_with_limit(
884 cache_dir: &Path,
885 max_decompressed: usize,
886) -> Result<PackageIndex> {
887 let path = api_manifest_path(cache_dir);
888
889 if !path.exists() {
890 return Err(Error::Cache("No cached manifest found".to_string()));
891 }
892
893 tokio::task::spawn_blocking(move || decode_cached_manifest(&path, max_decompressed))
896 .await
897 .map_err(|e| Error::Cache(format!("cache decode task panicked: {}", e)))?
898}
899
900fn is_fresh(network: DateTime<FixedOffset>, local: DateTime<FixedOffset>) -> bool {
903 network <= local
904}
905
906async fn load_cached_index(index_dir: &Path, max_decompressed: usize) -> Option<PackageIndex> {
912 match get_manifest_from_disk_with_limit(index_dir, max_decompressed).await {
913 Ok(manifest) => Some(manifest),
914 Err(err) => {
915 tracing::warn!("Cached manifest unreadable ({}); re-fetching", err);
916
917 None
918 }
919 }
920}
921
922fn decode_cached_manifest(path: &Path, max_decompressed: usize) -> Result<PackageIndex> {
931 let limit = max_decompressed as u64;
932 let file = std::fs::File::open(path)?;
933
934 let mut decoder = zstd::Decoder::new(file)?;
935 let mut decompressed_data = Vec::new();
936
937 decoder
938 .by_ref()
939 .take(limit + 1)
940 .read_to_end(&mut decompressed_data)?;
941
942 if decompressed_data.len() as u64 > limit {
943 return Err(Error::SizeLimitExceeded {
944 context: "decompressed cache".to_string(),
945 limit,
946 actual: Some(decompressed_data.len() as u64),
947 });
948 }
949
950 let config = bincode::config::standard().with_limit::<MAX_DECODE_ALLOC>();
956 let (serializable, _): (SerializedPackageIndex, usize) =
957 bincode::decode_from_slice(&decompressed_data, config)
958 .map_err(|e| Error::Cache(format!("failed to decode cached manifest: {}", e)))?;
959
960 serializable.try_into()
961}
962
963async fn get_manifest_from_network(
969 http: &Client,
970 api_url: &str,
971 max_bytes: Option<u64>,
972 retry: &RetryPolicy,
973 progress: &dyn ProgressReporter,
974) -> Result<(Vec<Package>, DateTime<FixedOffset>)> {
975 let handle = progress.begin("Downloading Api Manifest", None);
976
977 let result = retry_http(retry, || async {
980 let response = http.get(api_url).send().await?.error_for_status()?;
981 let last_modified_str = response
982 .headers()
983 .get(header::LAST_MODIFIED)
984 .ok_or(Error::MissingHeader("Last-Modified".to_string()))?
985 .to_str()?;
986 let last_modified = DateTime::parse_from_rfc2822(last_modified_str)
987 .map_err(|e| Error::InvalidHeader(format!("invalid Last-Modified header: {}", e)))?;
988
989 let raw_response_data = read_capped_body(response, max_bytes).await?;
990
991 let packages: Vec<Package> = serde_json::from_slice(&raw_response_data)?;
992
993 Ok((packages, last_modified))
994 })
995 .await;
996
997 match result {
1000 Ok((packages, last_modified)) => {
1001 handle.finish(Some(" Downloaded Api Manifest"));
1002
1003 Ok((packages, last_modified))
1004 }
1005 Err(err) => {
1006 handle.finish(None);
1007
1008 Err(err)
1009 }
1010 }
1011}
1012
1013async fn read_capped_body(response: reqwest::Response, max_bytes: Option<u64>) -> Result<Vec<u8>> {
1017 let mut cap = max_bytes.map(|max| SizeCap::new("manifest body", max));
1018
1019 if let Some(cap) = &cap {
1020 cap.check_declared(response.content_length())?;
1021 }
1022
1023 let mut stream = response.bytes_stream();
1024 let mut body: Vec<u8> = Vec::new();
1025
1026 while let Some(chunk) = stream.next().await {
1027 let chunk = chunk?;
1028
1029 if let Some(cap) = cap.as_mut() {
1030 cap.add(chunk.len() as u64)?;
1031 }
1032
1033 body.extend_from_slice(&chunk);
1034 }
1035
1036 Ok(body)
1037}
1038
1039fn encode_manifest_cache(packages: Vec<Package>) -> Result<(PackageIndex, Vec<u8>)> {
1045 let manifest: PackageIndex = packages.into();
1046 let serializable: SerializedPackageIndex = (&manifest).into();
1047
1048 let binary_data = bincode::encode_to_vec(&serializable, bincode::config::standard())
1049 .map_err(|e| Error::Cache(format!("failed to encode manifest cache: {}", e)))?;
1050
1051 Ok((manifest, binary_data))
1052}
1053
1054async fn get_manifest_from_network_and_cache(
1061 cache_dir: &Path,
1062 http: &Client,
1063 api_url: &str,
1064 max_manifest_bytes: Option<u64>,
1065 retry: &RetryPolicy,
1066 progress: &dyn ProgressReporter,
1067) -> Result<PackageIndex> {
1068 let (packages, last_modified_from_network) =
1069 get_manifest_from_network(http, api_url, max_manifest_bytes, retry, progress).await?;
1070
1071 let (manifest, binary_data) =
1075 tokio::task::spawn_blocking(move || encode_manifest_cache(packages))
1076 .await
1077 .map_err(|e| Error::Cache(format!("cache encode task panicked: {}", e)))??;
1078
1079 write_cache_to_disk(api_manifest_path(cache_dir), &binary_data, true).await?;
1080
1081 if let Err(err) = write_cache_to_disk(
1086 last_modified_path(cache_dir),
1087 last_modified_from_network.to_rfc2822().as_bytes(),
1088 false,
1089 )
1090 .await
1091 {
1092 tracing::warn!(
1093 "Failed to write last_modified marker ({}); cached manifest kept, will re-fetch",
1094 err
1095 );
1096 }
1097
1098 Ok(manifest)
1099}
1100
1101async fn local_last_modified(cache_dir: &Path) -> Result<DateTime<FixedOffset>> {
1103 let path = last_modified_path(cache_dir);
1104
1105 if let Ok(file) = fs::File::open(&path).await {
1106 tracing::info!("Last modified file exists and was opened.");
1107
1108 let mut buf = Vec::new();
1113
1114 file
1115 .take(MAX_LAST_MODIFIED_BYTES)
1116 .read_to_end(&mut buf)
1117 .await?;
1118
1119 let contents = String::from_utf8_lossy(&buf);
1120
1121 match DateTime::parse_from_rfc2822(contents.trim()) {
1122 Ok(last_modified) => Ok(last_modified),
1123 Err(err) => {
1124 tracing::warn!(
1125 "Unparseable last_modified marker ({}); treating as stale",
1126 err
1127 );
1128
1129 Ok(epoch())
1130 }
1131 }
1132 } else {
1133 tracing::info!("Last modified file does not exist and was not opened.");
1134
1135 Ok(epoch())
1136 }
1137}
1138
1139fn epoch() -> DateTime<FixedOffset> {
1142 let dt = DateTime::from_timestamp(0, 0)
1143 .expect("timestamp 0 is valid")
1144 .naive_utc();
1145 let offset = FixedOffset::east_opt(0).expect("zero offset is valid");
1146
1147 DateTime::<FixedOffset>::from_naive_utc_and_offset(dt, offset)
1148}
1149
1150async fn network_last_modified(http: &Client, api_url: &str) -> Result<DateTime<FixedOffset>> {
1152 let response = http.head(api_url).send().await?.error_for_status()?;
1153
1154 let last_modified = response
1155 .headers()
1156 .get(header::LAST_MODIFIED)
1157 .ok_or(Error::MissingHeader(
1158 "Last-Modified for API manifest head request".to_string(),
1159 ))?;
1160 let last_modified_date = DateTime::parse_from_rfc2822(last_modified.to_str()?)
1161 .map_err(|e| Error::InvalidHeader(format!("invalid Last-Modified header: {}", e)))?;
1162
1163 Ok(last_modified_date)
1164}
1165
1166fn api_manifest_file_exists(cache_dir: &Path) -> bool {
1168 api_manifest_path(cache_dir).exists()
1169}
1170
1171fn temp_sibling_path(path: &Path) -> PathBuf {
1177 static COUNTER: AtomicU64 = AtomicU64::new(0);
1178
1179 let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
1180 let pid = std::process::id();
1181 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("cache");
1182 let tmp_name = format!(".{name}.{pid}.{seq}.tmp");
1183
1184 match path.parent() {
1185 Some(parent) => parent.join(tmp_name),
1186 None => PathBuf::from(tmp_name),
1187 }
1188}
1189
1190async fn write_cache_to_disk<T: AsRef<Path>>(
1196 path: T,
1197 contents: &[u8],
1198 use_compression: bool,
1199) -> Result<()> {
1200 let path = path.as_ref();
1201
1202 if let Some(parent) = path.parent() {
1203 fs::create_dir_all(parent).await?;
1204 }
1205
1206 let payload = if use_compression {
1207 let data = contents.to_vec();
1209
1210 tokio::task::spawn_blocking(move || zstd::encode_all(data.as_slice(), 9))
1211 .await
1212 .map_err(|e| Error::Cache(format!("cache encode task panicked: {}", e)))??
1213 } else {
1214 contents.to_vec()
1215 };
1216
1217 let tmp_path = temp_sibling_path(path);
1218
1219 if let Err(err) = write_and_rename(&tmp_path, path, &payload).await {
1222 let _ = fs::remove_file(&tmp_path).await;
1223
1224 return Err(err);
1225 }
1226
1227 Ok(())
1228}
1229
1230async fn write_and_rename(tmp_path: &Path, path: &Path, payload: &[u8]) -> Result<()> {
1234 let mut file = fs::File::create(tmp_path).await?;
1235
1236 file.write_all(payload).await?;
1237 file.flush().await?;
1238 file.sync_all().await?;
1239
1240 fs::rename(tmp_path, path).await?;
1241
1242 if let Some(parent) = path.parent()
1245 && let Ok(dir) = fs::File::open(parent).await
1246 {
1247 let _ = dir.sync_all().await;
1248 }
1249
1250 Ok(())
1251}
1252
1253fn parse_content_length(headers: &reqwest::header::HeaderMap) -> Option<u64> {
1256 headers
1257 .get(header::CONTENT_LENGTH)
1258 .and_then(|value| value.to_str().ok())
1259 .and_then(|value| value.parse::<u64>().ok())
1260}
1261
1262fn check_complete(content_length: Option<u64>, written: u64) -> Result<()> {
1269 if let Some(expected) = content_length
1270 && written != expected
1271 {
1272 return Err(Error::IncompleteDownload {
1273 expected,
1274 actual: written,
1275 });
1276 }
1277
1278 Ok(())
1279}
1280
1281fn aggregate_download_results(results: Vec<(String, Result<()>)>) -> Result<()> {
1285 let total = results.len();
1286 let mut failures: Vec<(String, Error)> = results
1287 .into_iter()
1288 .filter_map(|(name, result)| result.err().map(|err| (name, err)))
1289 .collect();
1290
1291 if failures.is_empty() {
1292 return Ok(());
1293 }
1294
1295 for (name, err) in &failures {
1296 tracing::error!("Download error for {name}: {err:?}");
1297 }
1298
1299 failures.sort_by(|(a, _), (b, _)| a.cmp(b));
1300
1301 Err(Error::Download { total, failures })
1302}
1303
1304async fn download_files(
1306 urls: HashMap<String, String>,
1307 cache_dir: &Path,
1308 http: &Client,
1309 concurrency: usize,
1310 max_bytes: Option<u64>,
1311 retry: RetryPolicy,
1312 progress: Arc<dyn ProgressReporter>,
1313) -> Result<()> {
1314 if urls.is_empty() {
1315 tracing::debug!("No files to download");
1316
1317 return Ok(());
1318 }
1319
1320 tracing::debug!("Processing {} mods", urls.len());
1321
1322 let concurrency = concurrency.max(1);
1323
1324 let results: Vec<(String, Result<()>)> =
1325 futures::stream::iter(urls.into_iter().map(|(archive_filename, url)| {
1326 let client = http.clone();
1327 let cache_dir = cache_dir.to_path_buf();
1328 let progress = progress.clone();
1329
1330 async move {
1331 let result = download_file(
1332 &client,
1333 &url,
1334 &archive_filename,
1335 &cache_dir,
1336 max_bytes,
1337 &retry,
1338 progress.as_ref(),
1339 )
1340 .await;
1341
1342 (archive_filename, result)
1343 }
1344 }))
1345 .buffer_unordered(concurrency)
1346 .collect()
1347 .await;
1348
1349 aggregate_download_results(results)
1350}
1351
1352fn safe_download_name(filename: &str) -> Result<&str> {
1356 let mut components = Path::new(filename).components();
1357 let only = components.next();
1358
1359 let is_single_normal = matches!(only, Some(std::path::Component::Normal(_)));
1360
1361 if !is_single_normal || components.next().is_some() {
1362 return Err(Error::UnsafeName(format!(
1363 "Unsafe download filename: {}",
1364 filename
1365 )));
1366 }
1367
1368 Ok(filename)
1369}
1370
1371struct TempFileGuard {
1379 path: Option<PathBuf>,
1380}
1381
1382impl TempFileGuard {
1383 fn new(path: PathBuf) -> Self {
1384 Self { path: Some(path) }
1385 }
1386
1387 fn disarm(&mut self) {
1389 self.path = None;
1390 }
1391}
1392
1393impl Drop for TempFileGuard {
1394 fn drop(&mut self) {
1395 if let Some(path) = self.path.take() {
1396 let _ = std::fs::remove_file(path);
1397 }
1398 }
1399}
1400
1401async fn download_file(
1419 client: &Client,
1420 url: &str,
1421 filename: &str,
1422 cache_dir: &Path,
1423 max_bytes: Option<u64>,
1424 retry: &RetryPolicy,
1425 progress: &dyn ProgressReporter,
1426) -> Result<()> {
1427 let downloads_directory = cache_dir.join("downloads");
1428 let file_path = downloads_directory.join(safe_download_name(filename)?);
1429
1430 tokio::fs::DirBuilder::new()
1431 .recursive(true)
1432 .create(&downloads_directory)
1433 .await
1434 .map_err(|e| {
1435 io_context(
1436 format!("creating downloads dir {}", downloads_directory.display()),
1437 e,
1438 )
1439 })?;
1440
1441 if file_path.exists() {
1442 tracing::debug!("{} already exists, skipping download", filename);
1443
1444 return Ok(());
1445 }
1446
1447 let tmp_path = temp_sibling_path(&file_path);
1448
1449 let mut tmp_guard = TempFileGuard::new(tmp_path.clone());
1452
1453 let handle = progress.begin(filename, None);
1457
1458 let attempt = retry_http(retry, || async {
1462 handle.set_position(0);
1465
1466 let response = client.get(url).send().await?.error_for_status()?;
1467
1468 let content_length = parse_content_length(response.headers());
1473 let mut cap = max_bytes.map(|max| SizeCap::new("download body", max));
1474
1475 if let Some(cap) = &cap {
1477 cap.check_declared(content_length)?;
1478 }
1479
1480 if let Some(total) = content_length {
1481 handle.set_length(total);
1482 }
1483
1484 let mut response_data = response.bytes_stream();
1485 let mut file = tokio::fs::File::create(&tmp_path).await.map_err(|e| {
1486 io_context(
1487 format!("creating temp download file {}", tmp_path.display()),
1488 e,
1489 )
1490 })?;
1491 let mut written: u64 = 0;
1492
1493 while let Some(result) = response_data.next().await {
1494 let chunk = result?;
1495
1496 written += chunk.len() as u64;
1497
1498 if let Some(cap) = cap.as_mut() {
1499 cap.add(chunk.len() as u64)?;
1500 }
1501
1502 file.write_all(&chunk).await?;
1503 handle.inc(chunk.len() as u64);
1504 }
1505
1506 file.flush().await?;
1507 file.sync_all().await?;
1508
1509 check_complete(content_length, written)
1510 })
1511 .await;
1512
1513 if let Err(err) = attempt {
1514 handle.finish(None);
1516
1517 return Err(err);
1518 }
1519
1520 if let Err(err) = tokio::fs::rename(&tmp_path, &file_path).await {
1524 handle.finish(None);
1525
1526 return Err(io_context(
1527 format!("renaming {} to {}", tmp_path.display(), file_path.display()),
1528 err,
1529 ));
1530 }
1531
1532 tmp_guard.disarm();
1534 handle.finish(None);
1535
1536 Ok(())
1537}
1538
1539#[cfg(test)]
1540mod tests {
1541 use super::*;
1542 use crate::progress::{NoopProgress, ProgressHandle};
1543 use mockito::Server;
1544 use std::fs::File;
1545 use std::io::Write;
1546 use tempfile::tempdir;
1547 use time::OffsetDateTime;
1548 use tokio::runtime::Runtime;
1549
1550 fn test_http() -> Client {
1551 Client::builder()
1552 .timeout(Duration::from_secs(60))
1553 .build()
1554 .unwrap()
1555 }
1556
1557 #[test]
1558 fn test_api_manifest_file_exists() {
1559 let temp_dir = tempdir().unwrap();
1560 let cache_dir = temp_dir.path();
1561
1562 assert!(!api_manifest_file_exists(cache_dir));
1563
1564 let _ = File::create(cache_dir.join(API_MANIFEST_FILENAME)).unwrap();
1565
1566 assert!(api_manifest_file_exists(cache_dir));
1567 }
1568
1569 #[test]
1570 fn test_path_construction() {
1571 let cache_dir = Path::new("/some/cache/dir");
1572
1573 let last_modified = last_modified_path(cache_dir);
1574 let api_manifest = api_manifest_path(cache_dir);
1575
1576 assert_eq!(last_modified, cache_dir.join(LAST_MODIFIED_FILENAME));
1577 assert_eq!(api_manifest, cache_dir.join(API_MANIFEST_FILENAME));
1578 }
1579
1580 #[test]
1581 fn test_builder_composes_url() {
1582 let temp_dir = tempdir().unwrap();
1583
1584 let client = ThunderstoreClient::builder()
1585 .base_url("https://stacklands.thunderstore.io")
1586 .community("valheim")
1587 .cache_dir(temp_dir.path())
1588 .build()
1589 .unwrap();
1590
1591 assert_eq!(
1592 client.package_index_url(),
1593 "https://stacklands.thunderstore.io/c/valheim/api/v1/package/"
1594 );
1595 }
1596
1597 #[test]
1598 fn test_builder_requires_cache_dir() {
1599 let result = ThunderstoreClient::builder().community("valheim").build();
1600
1601 assert!(matches!(result, Err(Error::Config(_))));
1602 }
1603
1604 #[test]
1605 fn parse_content_length_reads_valid_and_ignores_missing_or_bad() {
1606 use reqwest::header::{CONTENT_LENGTH, HeaderMap, HeaderValue};
1607
1608 let mut h = HeaderMap::new();
1609
1610 assert_eq!(parse_content_length(&h), None);
1611
1612 h.insert(CONTENT_LENGTH, HeaderValue::from_static("2048"));
1613
1614 assert_eq!(parse_content_length(&h), Some(2048));
1615
1616 h.insert(CONTENT_LENGTH, HeaderValue::from_static("not-a-number"));
1617
1618 assert_eq!(parse_content_length(&h), None);
1619 }
1620
1621 #[test]
1622 fn aggregate_download_results_all_ok_is_ok() {
1623 let ok = vec![
1624 ("A-1.0.0.zip".to_string(), Ok(())),
1625 ("B-1.0.0.zip".to_string(), Ok(())),
1626 ];
1627
1628 assert!(aggregate_download_results(ok).is_ok());
1629 assert!(aggregate_download_results(vec![]).is_ok());
1630 }
1631
1632 #[test]
1633 fn aggregate_download_results_names_every_failed_file() {
1634 let results = vec![
1635 (
1636 "C-1.0.0.zip".to_string(),
1637 Err(Error::IncompleteDownload {
1638 expected: 5,
1639 actual: 2,
1640 }),
1641 ),
1642 ("A-1.0.0.zip".to_string(), Ok(())),
1643 (
1644 "B-1.0.0.zip".to_string(),
1645 Err(Error::UnsafeName("bad".to_string())),
1646 ),
1647 ];
1648
1649 let err = aggregate_download_results(results).unwrap_err();
1650
1651 assert_eq!(
1652 err.to_string(),
1653 "2 of 3 downloads failed: B-1.0.0.zip: unsafe name: bad; \
1654 C-1.0.0.zip: incomplete download: expected 5 bytes, received 2"
1655 );
1656
1657 match err {
1658 Error::Download { total, failures } => {
1659 let failed: Vec<&str> = failures.iter().map(|(name, _)| name.as_str()).collect();
1660
1661 assert_eq!(total, 3);
1662 assert_eq!(failed, ["B-1.0.0.zip", "C-1.0.0.zip"]);
1663 assert!(matches!(failures[0].1, Error::UnsafeName(_)));
1664 }
1665 other => panic!("unexpected error: {other}"),
1666 }
1667 }
1668
1669 #[test]
1670 fn compose_index_url_prefers_override_then_builds_from_community() {
1671 assert_eq!(
1672 compose_index_url("https://thunderstore.io", Some("valheim"), None).unwrap(),
1673 "https://thunderstore.io/c/valheim/api/v1/package/"
1674 );
1675
1676 assert_eq!(
1678 compose_index_url("https://thunderstore.io/", Some("valheim"), None).unwrap(),
1679 "https://thunderstore.io/c/valheim/api/v1/package/"
1680 );
1681
1682 assert_eq!(
1684 compose_index_url("https://ignored", None, Some("https://custom/pkg/")).unwrap(),
1685 "https://custom/pkg/"
1686 );
1687
1688 assert!(matches!(
1690 compose_index_url("https://thunderstore.io", None, None),
1691 Err(Error::Config(_))
1692 ));
1693
1694 assert!(matches!(
1696 compose_index_url("https://thunderstore.io", Some("bad/slug"), None),
1697 Err(Error::Config(_))
1698 ));
1699 }
1700
1701 #[test]
1702 fn resolve_decompressed_cap_precedence() {
1703 assert_eq!(resolve_decompressed_cap(Some(42), Some(100)), 42);
1705
1706 assert_eq!(resolve_decompressed_cap(None, Some(100)), 100);
1708
1709 assert_eq!(
1711 resolve_decompressed_cap(None, None),
1712 DEFAULT_MAX_MANIFEST_DECOMPRESSED_BYTES
1713 );
1714 }
1715
1716 #[test]
1717 fn is_fresh_compares_last_modified() {
1718 let older = DateTime::parse_from_rfc2822("Wed, 21 Feb 2024 15:30:45 +0000").unwrap();
1719 let newer = DateTime::parse_from_rfc2822("Thu, 22 Feb 2024 15:30:45 +0000").unwrap();
1720
1721 assert!(is_fresh(older, older));
1723 assert!(is_fresh(older, newer));
1724
1725 assert!(!is_fresh(newer, older));
1727 }
1728
1729 #[test]
1730 fn encode_manifest_cache_builds_index_and_nonempty_blob() {
1731 let (index, bytes) = encode_manifest_cache(vec![sample_package("X", "O-X", "O")]).unwrap();
1732
1733 assert_eq!(index.len(), 1);
1734 assert!(!bytes.is_empty());
1735 }
1736
1737 #[test]
1738 fn check_complete_flags_short_and_accepts_exact_or_unknown() {
1739 assert!(check_complete(Some(100), 100).is_ok());
1741
1742 assert!(check_complete(None, 42).is_ok());
1744
1745 let err = check_complete(Some(100), 50).unwrap_err();
1747
1748 assert!(matches!(
1749 err,
1750 Error::IncompleteDownload {
1751 expected: 100,
1752 actual: 50,
1753 }
1754 ));
1755 }
1756
1757 #[test]
1758 fn safe_download_name_accepts_plain_and_rejects_traversal() {
1759 assert_eq!(
1761 safe_download_name("Author-Mod-1.0.0.zip").unwrap(),
1762 "Author-Mod-1.0.0.zip"
1763 );
1764
1765 assert!(matches!(
1770 safe_download_name("../escape.zip"),
1771 Err(Error::UnsafeName(_))
1772 ));
1773 assert!(matches!(
1774 safe_download_name("/etc/passwd"),
1775 Err(Error::UnsafeName(_))
1776 ));
1777 assert!(matches!(
1778 safe_download_name("a/b.zip"),
1779 Err(Error::UnsafeName(_))
1780 ));
1781 }
1782
1783 #[test]
1784 fn test_write_cache_to_disk() {
1785 let temp_dir = tempdir().unwrap();
1786 let cache_path = temp_dir.path().join("test_cache.txt");
1787 let test_data = b"Test cache data";
1788
1789 let rt = Runtime::new().unwrap();
1790 let result = rt.block_on(write_cache_to_disk(&cache_path, test_data, false));
1791
1792 assert!(result.is_ok());
1793 assert!(cache_path.exists());
1794
1795 let content = std::fs::read(&cache_path).unwrap();
1796 assert_eq!(content, test_data);
1797
1798 let new_data = b"Updated cache data";
1799 let result = rt.block_on(write_cache_to_disk(&cache_path, new_data, false));
1800
1801 assert!(result.is_ok());
1802 let content = std::fs::read(&cache_path).unwrap();
1803
1804 assert_eq!(content, new_data);
1805 }
1806
1807 #[test]
1808 fn test_write_cache_to_disk_creates_directories() {
1809 let temp_dir = tempdir().unwrap();
1810
1811 let nonexistent_subdir = temp_dir.path().join("subdir1/subdir2");
1812 let cache_path = nonexistent_subdir.join("test_cache.txt");
1813
1814 assert!(!nonexistent_subdir.exists());
1815 assert!(!cache_path.exists());
1816
1817 let test_data = b"Test cache data";
1818 let rt = Runtime::new().unwrap();
1819
1820 let result = rt.block_on(write_cache_to_disk(&cache_path, test_data, false));
1821 assert!(result.is_ok());
1822
1823 assert!(
1824 nonexistent_subdir.exists(),
1825 "Directory structure should be created"
1826 );
1827 assert!(cache_path.exists(), "File should be created");
1828
1829 let content = std::fs::read(&cache_path).unwrap();
1830 assert_eq!(content, test_data, "File should contain the expected data");
1831 }
1832
1833 #[test]
1834 fn test_write_cache_to_disk_with_compression() {
1835 let temp_dir = tempdir().unwrap();
1836 let api_manifest_path = temp_dir.path().join("test_compressed.bin");
1837
1838 let package = sample_package("TestMod", "TestOwner-TestMod", "TestOwner");
1839
1840 let packages = vec![package];
1841 let binary_data =
1842 bincode::serde::encode_to_vec(&packages, bincode::config::standard()).unwrap();
1843
1844 let rt = Runtime::new().unwrap();
1845 let result = rt.block_on(write_cache_to_disk(&api_manifest_path, &binary_data, true));
1846
1847 assert!(result.is_ok());
1848 assert!(api_manifest_path.exists());
1849
1850 let compressed_data = std::fs::read(&api_manifest_path).unwrap();
1851 let decompressed_data = zstd::decode_all(compressed_data.as_slice()).unwrap();
1852 let (decoded, _): (Vec<Package>, usize) =
1853 bincode::serde::decode_from_slice(&decompressed_data, bincode::config::standard()).unwrap();
1854
1855 assert_eq!(decoded.len(), 1);
1856 assert_eq!(decoded[0].full_name, Some("TestOwner-TestMod".to_string()));
1857 }
1858
1859 #[test]
1860 fn test_local_last_modified() {
1861 let temp_dir = tempdir().unwrap();
1862 let cache_dir = temp_dir.path();
1863 let rt = Runtime::new().unwrap();
1864
1865 {
1866 let result = rt.block_on(local_last_modified(cache_dir));
1867
1868 assert!(result.is_ok());
1869 }
1870
1871 let test_date = "Wed, 21 Feb 2024 15:30:45 GMT";
1872 let mut file = File::create(cache_dir.join(LAST_MODIFIED_FILENAME)).unwrap();
1873 file.write_all(test_date.as_bytes()).unwrap();
1874
1875 {
1876 let result = rt.block_on(local_last_modified(cache_dir));
1877
1878 assert!(result.is_ok());
1879 }
1880 }
1881
1882 #[test]
1883 fn test_get_manifest_from_disk() {
1884 let temp_dir = tempdir().unwrap();
1885 let cache_dir = temp_dir.path();
1886
1887 let package = sample_package("ModA", "Owner-ModA", "Owner");
1888
1889 let packages = vec![package];
1890 let interned_manifest: PackageIndex = packages.into();
1891 let serializable: SerializedPackageIndex = (&interned_manifest).into();
1892 let binary_data = bincode::encode_to_vec(&serializable, bincode::config::standard()).unwrap();
1893 let compressed_data = zstd::encode_all(binary_data.as_slice(), 9).unwrap();
1894 let mut file = File::create(cache_dir.join(API_MANIFEST_FILENAME)).unwrap();
1895 file.write_all(&compressed_data).unwrap();
1896
1897 let rt = Runtime::new().unwrap();
1898 let manifest = rt.block_on(get_manifest_from_disk(cache_dir)).unwrap();
1899
1900 assert_eq!(manifest.len(), 1);
1901 assert_eq!(
1902 manifest.resolve_full_name_at(0),
1903 Some("Owner-ModA".to_string())
1904 );
1905 }
1906
1907 #[test]
1908 fn test_get_manifest_from_disk_error() {
1909 let temp_dir = tempdir().unwrap();
1910 let cache_dir = temp_dir.path();
1911
1912 let mut file = File::create(cache_dir.join(API_MANIFEST_FILENAME)).unwrap();
1913 file
1914 .write_all(b"This is not valid compressed data")
1915 .unwrap();
1916
1917 let rt = Runtime::new().unwrap();
1918 let result = rt.block_on(get_manifest_from_disk(cache_dir));
1919
1920 assert!(result.is_err());
1921 }
1922
1923 #[test]
1924 fn test_network_last_modified() {
1925 let mut server = Server::new();
1926 let test_date = "Wed, 21 Feb 2024 15:30:45 GMT";
1927 let mock = server
1928 .mock("HEAD", "/c/valheim/api/v1/package/")
1929 .with_status(200)
1930 .with_header("Last-Modified", test_date)
1931 .create();
1932 let api_url = format!("{}/c/valheim/api/v1/package/", server.url());
1933 let rt = Runtime::new().unwrap();
1934
1935 let result = rt.block_on(network_last_modified(&test_http(), &api_url));
1936
1937 assert!(result.is_ok());
1938 if let Ok(parsed_date) = result {
1939 let expected_date = DateTime::parse_from_rfc2822(test_date).unwrap();
1940 assert_eq!(parsed_date, expected_date);
1941 }
1942
1943 mock.assert();
1944 }
1945
1946 #[test]
1947 fn test_get_manifest_from_network() {
1948 let mut server = Server::new();
1949 let test_date = "Wed, 21 Feb 2024 15:30:45 GMT";
1950
1951 let mock = server
1952 .mock("GET", "/c/valheim/api/v1/package/")
1953 .with_status(200)
1954 .with_header("Content-Type", "application/json")
1955 .with_header("Last-Modified", test_date)
1956 .with_body(sample_manifest_json())
1957 .create();
1958
1959 let api_url = format!("{}/c/valheim/api/v1/package/", server.url());
1960
1961 let rt = Runtime::new().unwrap();
1962 let result = rt.block_on(get_manifest_from_network(
1963 &test_http(),
1964 &api_url,
1965 None,
1966 &RetryPolicy::none(),
1967 &NoopProgress,
1968 ));
1969
1970 assert!(result.is_ok());
1971 if let Ok((packages, last_modified)) = result {
1972 assert_eq!(packages.len(), 1);
1973 assert_eq!(packages[0].full_name, Some("Owner-ModA".to_string()));
1974 let expected_date = DateTime::parse_from_rfc2822(test_date).unwrap();
1975 assert_eq!(last_modified, expected_date);
1976 }
1977
1978 mock.assert();
1979 }
1980
1981 fn seed_index_cache(index_dir: &Path, last_modified: &str) {
1983 std::fs::create_dir_all(index_dir).unwrap();
1984
1985 let package = sample_package("CachedMod", "CachedOwner-CachedMod", "CachedOwner");
1986 let interned_manifest: PackageIndex = vec![package].into();
1987 let serializable: SerializedPackageIndex = (&interned_manifest).into();
1988 let binary_data = bincode::encode_to_vec(&serializable, bincode::config::standard()).unwrap();
1989 let compressed_data = zstd::encode_all(binary_data.as_slice(), 9).unwrap();
1990
1991 File::create(index_dir.join(API_MANIFEST_FILENAME))
1992 .unwrap()
1993 .write_all(&compressed_data)
1994 .unwrap();
1995
1996 File::create(index_dir.join(LAST_MODIFIED_FILENAME))
1997 .unwrap()
1998 .write_all(last_modified.as_bytes())
1999 .unwrap();
2000 }
2001
2002 #[test]
2003 fn test_get_manifest_loads_fresh_cache() {
2004 let mut server = Server::new();
2005 let temp_dir = tempdir().unwrap();
2006 let cache_dir = temp_dir.path();
2007
2008 let mock = server
2010 .mock("HEAD", "/pkg/")
2011 .with_status(200)
2012 .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
2013 .create();
2014 let api_url = format!("{}/pkg/", server.url());
2015
2016 let client = ThunderstoreClient::builder()
2017 .package_index_url(&api_url)
2018 .cache_dir(cache_dir)
2019 .build()
2020 .unwrap();
2021
2022 let now = chrono::Utc::now().with_timezone(&chrono::FixedOffset::east_opt(0).unwrap());
2023 seed_index_cache(&client.index_cache_dir(), &now.to_rfc2822());
2024
2025 let rt = Runtime::new().unwrap();
2026 let manifest = rt.block_on(client.get_manifest()).unwrap();
2027
2028 assert_eq!(manifest.len(), 1);
2029 assert_eq!(
2030 manifest.resolve_full_name_at(0),
2031 Some("CachedOwner-CachedMod".to_string())
2032 );
2033
2034 mock.assert();
2035 }
2036
2037 #[test]
2038 fn cached_index_reports_no_cache_without_a_request() {
2039 let mut server = Server::new();
2040 let temp_dir = tempdir().unwrap();
2041 let head = server.mock("HEAD", "/pkg/").expect(0).create();
2042 let get = server.mock("GET", "/pkg/").expect(0).create();
2043
2044 let client = ThunderstoreClient::builder()
2045 .package_index_url(format!("{}/pkg/", server.url()))
2046 .cache_dir(temp_dir.path())
2047 .build()
2048 .unwrap();
2049
2050 let rt = Runtime::new().unwrap();
2051 let cached = rt.block_on(client.cached_index()).unwrap();
2052
2053 assert!(cached.is_none());
2054
2055 head.assert();
2056 get.assert();
2057 }
2058
2059 #[test]
2060 fn cached_index_loads_a_stale_cache_without_a_request() {
2061 let mut server = Server::new();
2062 let temp_dir = tempdir().unwrap();
2063 let head = server.mock("HEAD", "/pkg/").expect(0).create();
2064 let get = server.mock("GET", "/pkg/").expect(0).create();
2065
2066 let client = ThunderstoreClient::builder()
2067 .package_index_url(format!("{}/pkg/", server.url()))
2068 .cache_dir(temp_dir.path())
2069 .build()
2070 .unwrap();
2071
2072 seed_index_cache(&client.index_cache_dir(), "Thu, 01 Jan 1970 00:00:00 GMT");
2073
2074 let rt = Runtime::new().unwrap();
2075 let index = rt
2076 .block_on(client.cached_index())
2077 .unwrap()
2078 .expect("seeded cache is read");
2079
2080 assert_eq!(
2081 index.resolve_full_name_at(0),
2082 Some("CachedOwner-CachedMod".to_string())
2083 );
2084
2085 head.assert();
2086 get.assert();
2087 }
2088
2089 #[test]
2090 fn cached_index_reports_a_corrupt_cache_as_an_error() {
2091 let temp_dir = tempdir().unwrap();
2092
2093 let client = ThunderstoreClient::builder()
2094 .package_index_url("http://127.0.0.1:9/pkg/")
2095 .cache_dir(temp_dir.path())
2096 .build()
2097 .unwrap();
2098 let index_dir = client.index_cache_dir();
2099
2100 std::fs::create_dir_all(&index_dir).unwrap();
2101 std::fs::write(api_manifest_path(&index_dir), b"not zstd").unwrap();
2102
2103 let rt = Runtime::new().unwrap();
2104
2105 assert!(rt.block_on(client.cached_index()).is_err());
2106 }
2107
2108 #[test]
2109 fn test_get_manifest_falls_back_to_cache_when_head_fails() {
2110 let mut server = Server::new();
2111 let temp_dir = tempdir().unwrap();
2112 let cache_dir = temp_dir.path();
2113
2114 let mock = server
2116 .mock("HEAD", "/c/valheim/api/v1/package/")
2117 .with_status(500)
2118 .create();
2119 let api_url = format!("{}/c/valheim/api/v1/package/", server.url());
2120
2121 let client = ThunderstoreClient::builder()
2122 .package_index_url(&api_url)
2123 .cache_dir(cache_dir)
2124 .build()
2125 .unwrap();
2126
2127 seed_index_cache(&client.index_cache_dir(), "Wed, 21 Feb 2024 15:30:45 GMT");
2128
2129 let rt = Runtime::new().unwrap();
2130 let result = rt.block_on(client.get_manifest());
2131
2132 assert!(result.is_ok());
2133
2134 let manifest = result.unwrap();
2135
2136 assert_eq!(manifest.len(), 1);
2137 assert_eq!(
2138 manifest.resolve_full_name_at(0),
2139 Some("CachedOwner-CachedMod".to_string())
2140 );
2141
2142 mock.assert();
2143 }
2144
2145 fn pkg_client(server: &Server, cache_dir: &Path) -> ThunderstoreClient {
2147 ThunderstoreClient::builder()
2148 .package_index_url(format!("{}/pkg/", server.url()))
2149 .cache_dir(cache_dir)
2150 .build()
2151 .unwrap()
2152 }
2153
2154 #[test]
2155 fn refresh_if_stale_reports_a_fresh_cache_unchanged_without_downloading() {
2156 let mut server = Server::new();
2157 let temp_dir = tempdir().unwrap();
2158 let head = server
2159 .mock("HEAD", "/pkg/")
2160 .with_status(200)
2161 .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
2162 .create();
2163 let get = server.mock("GET", "/pkg/").expect(0).create();
2164 let client = pkg_client(&server, temp_dir.path());
2165 let index_dir = client.index_cache_dir();
2166
2167 seed_index_cache(&index_dir, "Wed, 21 Feb 2024 15:30:45 GMT");
2168 std::fs::write(api_manifest_path(&index_dir), b"not zstd").unwrap();
2171
2172 let rt = Runtime::new().unwrap();
2173 let refreshed = rt.block_on(client.refresh_if_stale()).unwrap();
2174
2175 assert!(matches!(refreshed, Refreshed::Unchanged));
2176
2177 head.assert();
2178 get.assert();
2179 }
2180
2181 #[test]
2182 fn refresh_if_stale_downloads_and_caches_a_stale_index() {
2183 let mut server = Server::new();
2184 let temp_dir = tempdir().unwrap();
2185 let head = server
2186 .mock("HEAD", "/pkg/")
2187 .with_status(200)
2188 .with_header("Last-Modified", "Wed, 28 Feb 2024 15:30:45 GMT")
2189 .create();
2190 let get = server
2191 .mock("GET", "/pkg/")
2192 .with_status(200)
2193 .with_header("Content-Type", "application/json")
2194 .with_header("Last-Modified", "Wed, 28 Feb 2024 15:30:45 GMT")
2195 .with_body(sample_manifest_json())
2196 .create();
2197 let client = pkg_client(&server, temp_dir.path());
2198
2199 seed_index_cache(&client.index_cache_dir(), "Wed, 21 Feb 2024 15:30:45 GMT");
2200
2201 let rt = Runtime::new().unwrap();
2202 let refreshed = rt.block_on(client.refresh_if_stale()).unwrap();
2203
2204 let Refreshed::Updated(index) = refreshed else {
2205 panic!("a stale cache is replaced");
2206 };
2207
2208 assert_eq!(
2209 index.resolve_full_name_at(0),
2210 Some("Owner-ModA".to_string())
2211 );
2212
2213 let cached = rt.block_on(client.cached_index()).unwrap().unwrap();
2214
2215 assert_eq!(
2216 cached.resolve_full_name_at(0),
2217 Some("Owner-ModA".to_string())
2218 );
2219
2220 head.assert();
2221 get.assert();
2222 }
2223
2224 #[test]
2225 fn refresh_if_stale_downloads_when_nothing_is_cached() {
2226 let mut server = Server::new();
2227 let temp_dir = tempdir().unwrap();
2228 let head = server.mock("HEAD", "/pkg/").expect(0).create();
2229 let get = server
2230 .mock("GET", "/pkg/")
2231 .with_status(200)
2232 .with_header("Content-Type", "application/json")
2233 .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
2234 .with_body(sample_manifest_json())
2235 .create();
2236 let client = pkg_client(&server, temp_dir.path());
2237
2238 let rt = Runtime::new().unwrap();
2239 let refreshed = rt.block_on(client.refresh_if_stale()).unwrap();
2240
2241 assert!(matches!(refreshed, Refreshed::Updated(ref index) if index.len() == 1));
2242 assert!(rt.block_on(client.cached_index()).unwrap().is_some());
2243
2244 head.assert();
2245 get.assert();
2246 }
2247
2248 #[test]
2249 fn refresh_if_stale_reports_a_failed_freshness_check() {
2250 let mut server = Server::new();
2251 let temp_dir = tempdir().unwrap();
2252 let head = server.mock("HEAD", "/pkg/").with_status(500).create();
2253 let get = server.mock("GET", "/pkg/").expect(0).create();
2254 let client = pkg_client(&server, temp_dir.path());
2255
2256 seed_index_cache(&client.index_cache_dir(), "Wed, 21 Feb 2024 15:30:45 GMT");
2257
2258 let rt = Runtime::new().unwrap();
2259 let result = rt.block_on(client.refresh_if_stale());
2260
2261 assert!(matches!(result, Err(Error::Http(_))), "got {result:?}");
2262
2263 head.assert();
2264 get.assert();
2265 }
2266
2267 #[test]
2268 fn refresh_if_stale_reports_a_failed_download() {
2269 let mut server = Server::new();
2270 let temp_dir = tempdir().unwrap();
2271 let get = server.mock("GET", "/pkg/").with_status(503).create();
2272 let client = ThunderstoreClient::builder()
2273 .package_index_url(format!("{}/pkg/", server.url()))
2274 .cache_dir(temp_dir.path())
2275 .retry(RetryPolicy::none())
2276 .build()
2277 .unwrap();
2278
2279 let rt = Runtime::new().unwrap();
2280 let result = rt.block_on(client.refresh_if_stale());
2281
2282 assert!(result.is_err());
2283
2284 get.assert();
2285 }
2286
2287 #[test]
2288 fn test_refresh_index_bypasses_cache_and_downloads() {
2289 let mut server = Server::new();
2290 let temp_dir = tempdir().unwrap();
2291 let cache_dir = temp_dir.path();
2292
2293 let get_mock = server
2295 .mock("GET", "/pkg/")
2296 .with_status(200)
2297 .with_header("Content-Type", "application/json")
2298 .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
2299 .with_body(sample_manifest_json())
2300 .create();
2301 let api_url = format!("{}/pkg/", server.url());
2302
2303 let client = ThunderstoreClient::builder()
2304 .package_index_url(&api_url)
2305 .cache_dir(cache_dir)
2306 .build()
2307 .unwrap();
2308
2309 let now = chrono::Utc::now().with_timezone(&chrono::FixedOffset::east_opt(0).unwrap());
2311 seed_index_cache(&client.index_cache_dir(), &now.to_rfc2822());
2312
2313 let rt = Runtime::new().unwrap();
2314 let manifest = rt.block_on(client.refresh_index()).unwrap();
2315
2316 assert_eq!(
2318 manifest.resolve_full_name_at(0),
2319 Some("Owner-ModA".to_string())
2320 );
2321
2322 get_mock.assert();
2323 }
2324
2325 #[test]
2326 fn test_get_manifest_downloads_when_cache_is_stale() {
2327 let mut server = Server::new();
2328 let temp_dir = tempdir().unwrap();
2329 let cache_dir = temp_dir.path();
2330
2331 let head_mock = server
2333 .mock("HEAD", "/pkg/")
2334 .with_status(200)
2335 .with_header("Last-Modified", "Wed, 28 Feb 2024 15:30:45 GMT")
2336 .create();
2337 let get_mock = server
2338 .mock("GET", "/pkg/")
2339 .with_status(200)
2340 .with_header("Content-Type", "application/json")
2341 .with_header("Last-Modified", "Wed, 28 Feb 2024 15:30:45 GMT")
2342 .with_body(sample_manifest_json())
2343 .create();
2344 let api_url = format!("{}/pkg/", server.url());
2345
2346 let client = ThunderstoreClient::builder()
2347 .package_index_url(&api_url)
2348 .cache_dir(cache_dir)
2349 .build()
2350 .unwrap();
2351
2352 seed_index_cache(&client.index_cache_dir(), "Wed, 21 Feb 2024 15:30:45 GMT");
2353
2354 let rt = Runtime::new().unwrap();
2355 let manifest = rt.block_on(client.get_manifest()).unwrap();
2356
2357 assert_eq!(
2359 manifest.resolve_full_name_at(0),
2360 Some("Owner-ModA".to_string())
2361 );
2362
2363 head_mock.assert();
2364 get_mock.assert();
2365 }
2366
2367 #[test]
2368 fn test_download_file_skips_existing_without_refetch() {
2369 let mut server = Server::new();
2370 let temp_dir = tempdir().unwrap();
2371 let cache_dir = temp_dir.path();
2372
2373 let mock = server
2376 .mock("GET", "/mod.zip")
2377 .with_status(200)
2378 .with_body("zip-bytes")
2379 .expect(1)
2380 .create();
2381 let file_url = format!("{}/mod.zip", server.url());
2382
2383 let rt = Runtime::new().unwrap();
2384
2385 rt.block_on(download_file(
2386 &test_http(),
2387 &file_url,
2388 "mod.zip",
2389 cache_dir,
2390 None,
2391 &RetryPolicy::none(),
2392 &NoopProgress,
2393 ))
2394 .unwrap();
2395
2396 rt.block_on(download_file(
2398 &test_http(),
2399 &file_url,
2400 "mod.zip",
2401 cache_dir,
2402 None,
2403 &RetryPolicy::none(),
2404 &NoopProgress,
2405 ))
2406 .unwrap();
2407
2408 mock.assert();
2409 }
2410
2411 #[test]
2412 fn test_head_error_status_is_not_trusted_as_freshness() {
2413 let mut server = Server::new();
2414 let temp_dir = tempdir().unwrap();
2415 let cache_dir = temp_dir.path();
2416
2417 let mock = server
2420 .mock("HEAD", "/pkg/")
2421 .with_status(500)
2422 .with_header("Last-Modified", "Wed, 21 Feb 2099 15:30:45 GMT")
2423 .create();
2424 let api_url = format!("{}/pkg/", server.url());
2425
2426 let client = ThunderstoreClient::builder()
2427 .package_index_url(&api_url)
2428 .cache_dir(cache_dir)
2429 .build()
2430 .unwrap();
2431
2432 seed_index_cache(&client.index_cache_dir(), "Wed, 21 Feb 2024 15:30:45 GMT");
2433
2434 let rt = Runtime::new().unwrap();
2435 let manifest = rt.block_on(client.get_manifest()).unwrap();
2436
2437 assert_eq!(manifest.len(), 1);
2438
2439 mock.assert();
2440 }
2441
2442 #[test]
2443 fn test_get_manifest_refetches_on_unsupported_cache_version() {
2444 let mut server = Server::new();
2445 let temp_dir = tempdir().unwrap();
2446 let cache_dir = temp_dir.path();
2447
2448 let test_date = "Wed, 21 Feb 2024 15:30:45 GMT";
2452 let head = server
2453 .mock("HEAD", "/pkg/")
2454 .with_status(200)
2455 .with_header("Last-Modified", test_date)
2456 .create();
2457 let get = server
2458 .mock("GET", "/pkg/")
2459 .with_status(200)
2460 .with_header("Content-Type", "application/json")
2461 .with_header("Last-Modified", test_date)
2462 .with_body(sample_manifest_json())
2463 .create();
2464 let api_url = format!("{}/pkg/", server.url());
2465
2466 let client = ThunderstoreClient::builder()
2467 .package_index_url(&api_url)
2468 .cache_dir(cache_dir)
2469 .build()
2470 .unwrap();
2471
2472 let index_dir = client.index_cache_dir();
2474 std::fs::create_dir_all(&index_dir).unwrap();
2475
2476 let interned: PackageIndex = vec![sample_package("X", "O-X", "O")].into();
2477 let mut serializable: SerializedPackageIndex = (&interned).into();
2478 serializable.format_version = 99;
2479 let binary_data = bincode::encode_to_vec(&serializable, bincode::config::standard()).unwrap();
2480 let compressed = zstd::encode_all(binary_data.as_slice(), 9).unwrap();
2481
2482 File::create(index_dir.join(API_MANIFEST_FILENAME))
2483 .unwrap()
2484 .write_all(&compressed)
2485 .unwrap();
2486
2487 let now = chrono::Utc::now().with_timezone(&chrono::FixedOffset::east_opt(0).unwrap());
2488
2489 File::create(index_dir.join(LAST_MODIFIED_FILENAME))
2490 .unwrap()
2491 .write_all(now.to_rfc2822().as_bytes())
2492 .unwrap();
2493
2494 let rt = Runtime::new().unwrap();
2495 let manifest = rt.block_on(client.get_manifest()).unwrap();
2496
2497 assert_eq!(
2499 manifest.resolve_full_name_at(0),
2500 Some("Owner-ModA".to_string())
2501 );
2502
2503 head.assert();
2504 get.assert();
2505 }
2506
2507 #[test]
2508 fn test_builder_rejects_invalid_community() {
2509 let temp_dir = tempdir().unwrap();
2510
2511 let result = ThunderstoreClient::builder()
2512 .community("../../etc")
2513 .cache_dir(temp_dir.path())
2514 .build();
2515
2516 assert!(matches!(result, Err(Error::Config(_))));
2517 }
2518
2519 #[test]
2520 fn test_index_cache_dir_is_namespaced_per_community() {
2521 let temp_dir = tempdir().unwrap();
2522 let cache_dir = temp_dir.path();
2523
2524 let a = ThunderstoreClient::builder()
2525 .community("valheim")
2526 .cache_dir(cache_dir)
2527 .build()
2528 .unwrap();
2529 let b = ThunderstoreClient::builder()
2530 .community("lethal-company")
2531 .cache_dir(cache_dir)
2532 .build()
2533 .unwrap();
2534
2535 assert_ne!(a.index_cache_dir(), b.index_cache_dir());
2536 assert!(a.index_cache_dir().starts_with(cache_dir));
2537 assert!(b.index_cache_dir().starts_with(cache_dir));
2538 }
2539
2540 #[test]
2541 fn test_local_last_modified_treats_corrupt_marker_as_stale() {
2542 let temp_dir = tempdir().unwrap();
2543 let cache_dir = temp_dir.path();
2544
2545 File::create(cache_dir.join(LAST_MODIFIED_FILENAME))
2546 .unwrap()
2547 .write_all(b"not a date")
2548 .unwrap();
2549
2550 let rt = Runtime::new().unwrap();
2551 let result = rt.block_on(local_last_modified(cache_dir)).unwrap();
2552
2553 assert_eq!(result, epoch());
2554 }
2555
2556 #[test]
2557 fn test_get_manifest_from_network_rejects_oversize_body() {
2558 let mut server = Server::new();
2559 let test_date = "Wed, 21 Feb 2024 15:30:45 GMT";
2560
2561 let mock = server
2562 .mock("GET", "/pkg/")
2563 .with_status(200)
2564 .with_header("Last-Modified", test_date)
2565 .with_body(sample_manifest_json())
2566 .create();
2567 let api_url = format!("{}/pkg/", server.url());
2568
2569 let rt = Runtime::new().unwrap();
2570 let result = rt.block_on(get_manifest_from_network(
2571 &test_http(),
2572 &api_url,
2573 Some(8),
2574 &RetryPolicy::none(),
2575 &NoopProgress,
2576 ));
2577
2578 assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
2579
2580 mock.assert();
2581 }
2582
2583 #[test]
2584 fn test_get_manifest_from_disk_rejects_oversized_decompressed() {
2585 let temp_dir = tempdir().unwrap();
2586 let cache_dir = temp_dir.path();
2587
2588 let interned: PackageIndex = vec![sample_package("X", "O-X", "O")].into();
2589 let serializable: SerializedPackageIndex = (&interned).into();
2590 let binary_data = bincode::encode_to_vec(&serializable, bincode::config::standard()).unwrap();
2591 let compressed = zstd::encode_all(binary_data.as_slice(), 9).unwrap();
2592
2593 File::create(cache_dir.join(API_MANIFEST_FILENAME))
2594 .unwrap()
2595 .write_all(&compressed)
2596 .unwrap();
2597
2598 let rt = Runtime::new().unwrap();
2599 let result = rt.block_on(get_manifest_from_disk_with_limit(cache_dir, 4));
2600
2601 assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
2602 }
2603
2604 #[test]
2605 fn test_read_cap_defaults_to_download_cap() {
2606 let temp_dir = tempdir().unwrap();
2607
2608 let client = ThunderstoreClient::builder()
2611 .community("valheim")
2612 .cache_dir(temp_dir.path())
2613 .build()
2614 .unwrap();
2615
2616 assert_eq!(
2617 client.max_manifest_decompressed_bytes as u64,
2618 DEFAULT_MAX_MANIFEST_BYTES
2619 );
2620
2621 let client = ThunderstoreClient::builder()
2623 .community("valheim")
2624 .cache_dir(temp_dir.path())
2625 .manifest_max_bytes(900 * 1024 * 1024)
2626 .build()
2627 .unwrap();
2628
2629 assert_eq!(
2630 client.max_manifest_decompressed_bytes as u64,
2631 900 * 1024 * 1024
2632 );
2633
2634 let client = ThunderstoreClient::builder()
2637 .community("valheim")
2638 .cache_dir(temp_dir.path())
2639 .manifest_max_bytes(900 * 1024 * 1024)
2640 .manifest_max_decompressed_bytes(64 * 1024 * 1024)
2641 .build()
2642 .unwrap();
2643
2644 assert_eq!(client.max_manifest_decompressed_bytes, 64 * 1024 * 1024);
2645 }
2646
2647 #[test]
2648 fn test_large_cache_roundtrips_within_cap_and_rejects_below() {
2649 let temp_dir = tempdir().unwrap();
2650 let cache_dir = temp_dir.path();
2651
2652 let packages: Vec<Package> = (0..500)
2656 .map(|i| {
2657 sample_package(
2658 &format!("Mod{i}"),
2659 &format!("Owner{i}-Mod{i}"),
2660 &format!("Owner{i}"),
2661 )
2662 })
2663 .collect();
2664 let count = packages.len();
2665
2666 let interned: PackageIndex = packages.into();
2667 let serializable: SerializedPackageIndex = (&interned).into();
2668 let binary_data = bincode::encode_to_vec(&serializable, bincode::config::standard()).unwrap();
2669 let decompressed_len = binary_data.len();
2670 let compressed = zstd::encode_all(binary_data.as_slice(), 9).unwrap();
2671
2672 File::create(cache_dir.join(API_MANIFEST_FILENAME))
2673 .unwrap()
2674 .write_all(&compressed)
2675 .unwrap();
2676
2677 let rt = Runtime::new().unwrap();
2678
2679 let manifest = rt
2681 .block_on(get_manifest_from_disk_with_limit(
2682 cache_dir,
2683 decompressed_len,
2684 ))
2685 .unwrap();
2686
2687 assert_eq!(manifest.len(), count);
2688
2689 assert!(decompressed_len < DEFAULT_MAX_MANIFEST_DECOMPRESSED_BYTES);
2692
2693 let manifest = rt
2694 .block_on(get_manifest_from_disk_with_limit(
2695 cache_dir,
2696 DEFAULT_MAX_MANIFEST_DECOMPRESSED_BYTES,
2697 ))
2698 .unwrap();
2699
2700 assert_eq!(manifest.len(), count);
2701
2702 let result = rt.block_on(get_manifest_from_disk_with_limit(
2705 cache_dir,
2706 decompressed_len - 1,
2707 ));
2708
2709 assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
2710 }
2711
2712 #[test]
2713 fn test_get_manifest_from_network_and_cache() {
2714 let mut server = Server::new();
2715 let test_date = "Wed, 21 Feb 2024 15:30:45 GMT";
2716
2717 let mock = server
2718 .mock("GET", "/c/valheim/api/v1/package/")
2719 .with_status(200)
2720 .with_header("Content-Type", "application/json")
2721 .with_header("Last-Modified", test_date)
2722 .with_body(sample_manifest_json())
2723 .create();
2724
2725 let api_url = format!("{}/c/valheim/api/v1/package/", server.url());
2726 let temp_dir = tempdir().unwrap();
2727 let cache_dir = temp_dir.path();
2728
2729 let rt = Runtime::new().unwrap();
2730 let result = rt.block_on(get_manifest_from_network_and_cache(
2731 cache_dir,
2732 &test_http(),
2733 &api_url,
2734 None,
2735 &RetryPolicy::none(),
2736 &NoopProgress,
2737 ));
2738
2739 assert!(result.is_ok());
2740 if let Ok(manifest) = result {
2741 assert_eq!(manifest.len(), 1);
2742 assert_eq!(
2743 manifest.resolve_full_name_at(0),
2744 Some("Owner-ModA".to_string())
2745 );
2746
2747 assert!(last_modified_path(cache_dir).exists());
2748 assert!(api_manifest_path(cache_dir).exists());
2749
2750 let last_mod_content = std::fs::read_to_string(last_modified_path(cache_dir)).unwrap();
2751 assert!(last_mod_content.contains("21 Feb 2024 15:30:45"));
2752 }
2753
2754 mock.assert();
2755 }
2756
2757 #[test]
2758 fn test_download_file() {
2759 let mut server = Server::new();
2760 let temp_dir = tempdir().unwrap();
2761 let cache_dir = temp_dir.path();
2762
2763 let test_data = b"This is test file content";
2764 let content_length = test_data.len();
2765
2766 let _mock = server
2767 .mock("GET", "/test-file.zip")
2768 .with_status(200)
2769 .with_header("Content-Type", "application/zip")
2770 .with_header("Content-Length", &content_length.to_string())
2771 .with_body(test_data)
2772 .create();
2773
2774 let file_url = format!("{}/test-file.zip", server.url());
2775 let filename = "test-file.zip".to_string();
2776
2777 let rt = Runtime::new().unwrap();
2778 let client = test_http();
2779
2780 let result = rt.block_on(download_file(
2781 &client,
2782 &file_url,
2783 &filename,
2784 cache_dir,
2785 None,
2786 &RetryPolicy::none(),
2787 &NoopProgress,
2788 ));
2789
2790 assert!(result.is_ok());
2791
2792 let downloads_dir = cache_dir.join("downloads");
2793 assert!(downloads_dir.exists());
2794
2795 let downloaded_file = downloads_dir.join(&filename);
2796 assert!(downloaded_file.exists());
2797
2798 let file_content = std::fs::read(&downloaded_file).unwrap();
2799 assert_eq!(file_content, test_data);
2800
2801 let result2 = rt.block_on(download_file(
2802 &client,
2803 &file_url,
2804 &filename,
2805 cache_dir,
2806 None,
2807 &RetryPolicy::none(),
2808 &NoopProgress,
2809 ));
2810
2811 assert!(result2.is_ok());
2812 }
2813
2814 #[test]
2815 fn test_download_file_without_content_length_succeeds() {
2816 let mut server = Server::new();
2817 let temp_dir = tempdir().unwrap();
2818 let cache_dir = temp_dir.path();
2819
2820 let test_data = b"This is test file content";
2821
2822 let mock = server
2825 .mock("GET", "/test-file.zip")
2826 .with_status(200)
2827 .with_header("Content-Type", "application/zip")
2828 .with_body(test_data)
2829 .create();
2830
2831 let file_url = format!("{}/test-file.zip", server.url());
2832 let filename = "test-file-no-header.zip".to_string();
2833
2834 let rt = Runtime::new().unwrap();
2835 let client = test_http();
2836
2837 let result = rt.block_on(download_file(
2838 &client,
2839 &file_url,
2840 &filename,
2841 cache_dir,
2842 None,
2843 &RetryPolicy::none(),
2844 &NoopProgress,
2845 ));
2846
2847 assert!(result.is_ok());
2848
2849 let downloaded = cache_dir.join("downloads").join(&filename);
2850
2851 assert!(downloaded.exists());
2852 assert_eq!(std::fs::read(&downloaded).unwrap(), test_data);
2853
2854 mock.assert();
2855 }
2856
2857 #[test]
2858 fn test_download_files() {
2859 let mut server = Server::new();
2860 let temp_dir = tempdir().unwrap();
2861 let cache_dir = temp_dir.path();
2862
2863 let test_data1 = b"This is test file 1 content";
2864 let content_length1 = test_data1.len();
2865
2866 let test_data2 = b"This is test file 2 content - longer content";
2867 let content_length2 = test_data2.len();
2868
2869 let mock1 = server
2870 .mock("GET", "/file1.zip")
2871 .with_status(200)
2872 .with_header("Content-Type", "application/zip")
2873 .with_header("Content-Length", &content_length1.to_string())
2874 .with_body(test_data1)
2875 .create();
2876
2877 let mock2 = server
2878 .mock("GET", "/file2.zip")
2879 .with_status(200)
2880 .with_header("Content-Type", "application/zip")
2881 .with_header("Content-Length", &content_length2.to_string())
2882 .with_body(test_data2)
2883 .create();
2884
2885 let mut urls = HashMap::new();
2886 urls.insert(
2887 "file1.zip".to_string(),
2888 format!("{}/file1.zip", server.url()),
2889 );
2890 urls.insert(
2891 "file2.zip".to_string(),
2892 format!("{}/file2.zip", server.url()),
2893 );
2894
2895 let rt = Runtime::new().unwrap();
2896 let result = rt.block_on(download_files(
2897 urls,
2898 cache_dir,
2899 &test_http(),
2900 2,
2901 None,
2902 RetryPolicy::none(),
2903 Arc::new(NoopProgress),
2904 ));
2905
2906 assert!(result.is_ok());
2907
2908 let downloads_dir = cache_dir.join("downloads");
2909 assert!(downloads_dir.exists());
2910
2911 let file1 = downloads_dir.join("file1.zip");
2912 let file2 = downloads_dir.join("file2.zip");
2913 assert!(file1.exists());
2914 assert!(file2.exists());
2915
2916 let file1_content = std::fs::read(&file1).unwrap();
2917 let file2_content = std::fs::read(&file2).unwrap();
2918 assert_eq!(file1_content, test_data1);
2919 assert_eq!(file2_content, test_data2);
2920
2921 mock1.assert();
2922 mock2.assert();
2923 }
2924
2925 #[test]
2926 fn test_download_files_empty() {
2927 let temp_dir = tempdir().unwrap();
2928 let cache_dir = temp_dir.path();
2929
2930 let urls = HashMap::new();
2931
2932 let rt = Runtime::new().unwrap();
2933 let result = rt.block_on(download_files(
2934 urls,
2935 cache_dir,
2936 &test_http(),
2937 2,
2938 None,
2939 RetryPolicy::none(),
2940 Arc::new(NoopProgress),
2941 ));
2942
2943 assert!(result.is_ok());
2944 }
2945
2946 #[test]
2947 fn test_download_files_reports_failure() {
2948 let mut server = Server::new();
2949 let temp_dir = tempdir().unwrap();
2950 let cache_dir = temp_dir.path();
2951
2952 let mock = server.mock("GET", "/missing.zip").with_status(500).create();
2953
2954 let mut urls = HashMap::new();
2955 urls.insert(
2956 "missing.zip".to_string(),
2957 format!("{}/missing.zip", server.url()),
2958 );
2959
2960 let rt = Runtime::new().unwrap();
2961 let result = rt.block_on(download_files(
2962 urls,
2963 cache_dir,
2964 &test_http(),
2965 2,
2966 None,
2967 RetryPolicy::none(),
2968 Arc::new(NoopProgress),
2969 ));
2970
2971 assert!(result.is_err());
2972
2973 mock.assert();
2974 }
2975
2976 #[test]
2977 fn test_download_file_rejects_unsafe_filename() {
2978 let temp_dir = tempdir().unwrap();
2979 let cache_dir = temp_dir.path();
2980
2981 let rt = Runtime::new().unwrap();
2982 let result = rt.block_on(download_file(
2983 &test_http(),
2984 "http://example.invalid/x.zip",
2985 "../escape.zip",
2986 cache_dir,
2987 None,
2988 &RetryPolicy::none(),
2989 &NoopProgress,
2990 ));
2991
2992 assert!(result.is_err());
2993 }
2994
2995 #[test]
2996 fn test_download_file_rejects_declared_oversize() {
2997 let mut server = Server::new();
2998 let temp_dir = tempdir().unwrap();
2999 let cache_dir = temp_dir.path();
3000
3001 let body = vec![0u8; 100];
3004 let mock = server
3005 .mock("GET", "/big.zip")
3006 .with_status(200)
3007 .with_header("Content-Length", "100")
3008 .with_body(&body)
3009 .create();
3010
3011 let file_url = format!("{}/big.zip", server.url());
3012
3013 let rt = Runtime::new().unwrap();
3014 let result = rt.block_on(download_file(
3015 &test_http(),
3016 &file_url,
3017 "big.zip",
3018 cache_dir,
3019 Some(8),
3020 &RetryPolicy::none(),
3021 &NoopProgress,
3022 ));
3023
3024 assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
3025 assert!(!cache_dir.join("downloads").join("big.zip").exists());
3026
3027 mock.assert();
3028 }
3029
3030 #[test]
3031 fn test_download_file_rejects_streamed_oversize() {
3032 let mut server = Server::new();
3033 let temp_dir = tempdir().unwrap();
3034 let cache_dir = temp_dir.path();
3035
3036 let mock = server
3039 .mock("GET", "/stream.zip")
3040 .with_status(200)
3041 .with_chunked_body(|w| w.write_all(&[0u8; 100]))
3042 .create();
3043
3044 let file_url = format!("{}/stream.zip", server.url());
3045
3046 let rt = Runtime::new().unwrap();
3047 let result = rt.block_on(download_file(
3048 &test_http(),
3049 &file_url,
3050 "stream.zip",
3051 cache_dir,
3052 Some(8),
3053 &RetryPolicy::none(),
3054 &NoopProgress,
3055 ));
3056
3057 assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
3058
3059 let downloads_dir = cache_dir.join("downloads");
3060 assert!(!downloads_dir.join("stream.zip").exists());
3061
3062 let leftover = std::fs::read_dir(&downloads_dir)
3063 .unwrap()
3064 .filter_map(|e| e.ok())
3065 .any(|e| e.file_name().to_string_lossy().contains(".tmp"));
3066
3067 assert!(!leftover, "no .tmp temp files should remain");
3068
3069 mock.assert();
3070 }
3071
3072 fn fast_retry(max_retries: u32) -> RetryPolicy {
3073 RetryPolicy {
3074 max_retries,
3075 base_delay: Duration::ZERO,
3076 max_delay: Duration::ZERO,
3077 }
3078 }
3079
3080 #[test]
3081 fn test_download_file_retries_transient_5xx() {
3082 let mut server = Server::new();
3083 let temp_dir = tempdir().unwrap();
3084 let cache_dir = temp_dir.path();
3085
3086 let mock = server
3088 .mock("GET", "/flaky.zip")
3089 .with_status(500)
3090 .expect(3)
3091 .create();
3092 let file_url = format!("{}/flaky.zip", server.url());
3093
3094 let rt = Runtime::new().unwrap();
3095 let result = rt.block_on(download_file(
3096 &test_http(),
3097 &file_url,
3098 "flaky.zip",
3099 cache_dir,
3100 None,
3101 &fast_retry(2),
3102 &NoopProgress,
3103 ));
3104
3105 assert!(result.is_err());
3106
3107 mock.assert();
3109 }
3110
3111 #[test]
3112 fn test_download_file_does_not_retry_4xx() {
3113 let mut server = Server::new();
3114 let temp_dir = tempdir().unwrap();
3115 let cache_dir = temp_dir.path();
3116
3117 let mock = server
3119 .mock("GET", "/missing.zip")
3120 .with_status(404)
3121 .expect(1)
3122 .create();
3123 let file_url = format!("{}/missing.zip", server.url());
3124
3125 let rt = Runtime::new().unwrap();
3126 let result = rt.block_on(download_file(
3127 &test_http(),
3128 &file_url,
3129 "missing.zip",
3130 cache_dir,
3131 None,
3132 &fast_retry(5),
3133 &NoopProgress,
3134 ));
3135
3136 assert!(result.is_err());
3137
3138 mock.assert();
3139 }
3140
3141 struct RecordingProgress {
3144 positions: Arc<std::sync::Mutex<Vec<u64>>>,
3145 }
3146
3147 impl RecordingProgress {
3148 fn new() -> Self {
3149 Self {
3150 positions: Arc::new(std::sync::Mutex::new(Vec::new())),
3151 }
3152 }
3153 }
3154
3155 impl ProgressReporter for RecordingProgress {
3156 fn begin(&self, _label: &str, _total: Option<u64>) -> Box<dyn ProgressHandle> {
3157 Box::new(RecordingHandle {
3158 positions: self.positions.clone(),
3159 })
3160 }
3161 }
3162
3163 struct RecordingHandle {
3164 positions: Arc<std::sync::Mutex<Vec<u64>>>,
3165 }
3166
3167 impl ProgressHandle for RecordingHandle {
3168 fn inc(&self, _delta: u64) {}
3169
3170 fn set_position(&self, position: u64) {
3171 self.positions.lock().unwrap().push(position);
3172 }
3173
3174 fn set_message(&self, _msg: &str) {}
3175 fn finish(&self, _msg: Option<&str>) {}
3176 }
3177
3178 #[test]
3179 fn test_download_file_resets_progress_each_attempt() {
3180 let mut server = Server::new();
3181 let temp_dir = tempdir().unwrap();
3182 let cache_dir = temp_dir.path();
3183
3184 let mock = server
3187 .mock("GET", "/flaky.zip")
3188 .with_status(500)
3189 .expect(3)
3190 .create();
3191 let file_url = format!("{}/flaky.zip", server.url());
3192
3193 let progress = RecordingProgress::new();
3194
3195 let rt = Runtime::new().unwrap();
3196 let result = rt.block_on(download_file(
3197 &test_http(),
3198 &file_url,
3199 "flaky.zip",
3200 cache_dir,
3201 None,
3202 &fast_retry(2),
3203 &progress,
3204 ));
3205
3206 assert!(result.is_err());
3207
3208 let positions = progress.positions.lock().unwrap();
3209
3210 assert_eq!(positions.as_slice(), &[0, 0, 0]);
3212
3213 mock.assert();
3214 }
3215
3216 #[test]
3217 fn test_get_manifest_from_network_and_cache_tolerates_marker_write_failure() {
3218 let mut server = Server::new();
3219 let test_date = "Wed, 21 Feb 2024 15:30:45 GMT";
3220
3221 let mock = server
3222 .mock("GET", "/pkg/")
3223 .with_status(200)
3224 .with_header("Content-Type", "application/json")
3225 .with_header("Last-Modified", test_date)
3226 .with_body(sample_manifest_json())
3227 .create();
3228
3229 let api_url = format!("{}/pkg/", server.url());
3230 let temp_dir = tempdir().unwrap();
3231 let cache_dir = temp_dir.path();
3232
3233 std::fs::create_dir(last_modified_path(cache_dir)).unwrap();
3237
3238 let rt = Runtime::new().unwrap();
3239 let result = rt.block_on(get_manifest_from_network_and_cache(
3240 cache_dir,
3241 &test_http(),
3242 &api_url,
3243 None,
3244 &RetryPolicy::none(),
3245 &NoopProgress,
3246 ));
3247
3248 assert!(result.is_ok());
3249
3250 let manifest = result.unwrap();
3251
3252 assert_eq!(manifest.len(), 1);
3253 assert!(api_manifest_path(cache_dir).exists());
3254
3255 assert!(last_modified_path(cache_dir).is_dir());
3258
3259 mock.assert();
3260 }
3261
3262 fn sample_package(name: &str, full_name: &str, owner: &str) -> Package {
3263 Package {
3264 name: Some(name.to_string()),
3265 full_name: Some(full_name.to_string()),
3266 owner: Some(owner.to_string()),
3267 package_url: Some(format!("https://example.com/{}", name)),
3268 date_created: OffsetDateTime::now_utc(),
3269 date_updated: OffsetDateTime::now_utc(),
3270 uuid4: Some("test-uuid".to_string()),
3271 rating_score: Some(5),
3272 is_pinned: Some(false),
3273 is_deprecated: Some(false),
3274 has_nsfw_content: Some(false),
3275 categories: vec!["test".to_string()],
3276 versions: vec![],
3277 }
3278 }
3279
3280 fn sample_manifest_json() -> &'static str {
3281 r#"[
3282 {
3283 "name": "ModA",
3284 "full_name": "Owner-ModA",
3285 "owner": "Owner",
3286 "package_url": "https://example.com/mods/ModA",
3287 "date_created": "2024-01-01T12:00:00Z",
3288 "date_updated": "2024-01-02T12:00:00Z",
3289 "uuid4": "test-uuid",
3290 "rating_score": 5,
3291 "is_pinned": false,
3292 "is_deprecated": false,
3293 "has_nsfw_content": false,
3294 "categories": ["category1"],
3295 "versions": [
3296 {
3297 "name": "ModA",
3298 "full_name": "Owner-ModA",
3299 "description": "Test description",
3300 "icon": "icon.png",
3301 "version_number": "1.0.0",
3302 "dependencies": [],
3303 "download_url": "https://example.com/mods/ModA/download",
3304 "downloads": 100,
3305 "date_created": "2024-01-01T12:00:00Z",
3306 "website_url": "https://example.com",
3307 "is_active": true,
3308 "uuid4": "test-version-uuid",
3309 "file_size": 1024
3310 }
3311 ]
3312 }
3313 ]"#
3314 }
3315
3316 #[test]
3317 fn create_profile_code_posts_payload_and_returns_key() {
3318 let mut server = Server::new();
3319
3320 let mock = server
3321 .mock("POST", "/api/experimental/legacyprofile/create/")
3322 .match_header("content-type", "application/octet-stream")
3323 .match_body(mockito::Matcher::Exact("#r2modman\nQUJD".to_string()))
3324 .with_status(200)
3325 .with_header("Content-Type", "application/json")
3326 .with_body(r#"{"key":"abc-123"}"#)
3327 .create();
3328
3329 let cache = tempdir().unwrap();
3330 let client = ThunderstoreClient::builder()
3331 .base_url(server.url())
3332 .community("valheim")
3333 .cache_dir(cache.path())
3334 .build()
3335 .unwrap();
3336
3337 let rt = Runtime::new().unwrap();
3338 let key = rt
3339 .block_on(client.create_profile_code(b"#r2modman\nQUJD"))
3340 .unwrap();
3341
3342 assert_eq!(key, "abc-123");
3343 mock.assert();
3344 }
3345
3346 #[test]
3347 fn fetch_profile_code_returns_body_bytes() {
3348 let mut server = Server::new();
3349
3350 let mock = server
3351 .mock("GET", "/api/experimental/legacyprofile/get/abc-123/")
3352 .with_status(200)
3353 .with_body("#r2modman\nQUJD")
3354 .create();
3355
3356 let cache = tempdir().unwrap();
3357 let client = ThunderstoreClient::builder()
3358 .base_url(server.url())
3359 .community("valheim")
3360 .cache_dir(cache.path())
3361 .build()
3362 .unwrap();
3363
3364 let rt = Runtime::new().unwrap();
3365 let body = rt.block_on(client.fetch_profile_code("abc-123")).unwrap();
3366
3367 assert_eq!(body, b"#r2modman\nQUJD");
3368 mock.assert();
3369 }
3370
3371 #[test]
3372 fn user_agent_is_sent_on_every_request() {
3373 let mut server = Server::new();
3374 let agent = "my-manager/1.2 (+https://example.com)";
3375 let index_path = "/c/valheim/api/v1/package/";
3376 let archive = b"zip bytes";
3377
3378 let index_get = server
3379 .mock("GET", index_path)
3380 .match_header("user-agent", agent)
3381 .with_status(200)
3382 .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
3383 .with_body(sample_manifest_json())
3384 .create();
3385 let index_head = server
3386 .mock("HEAD", index_path)
3387 .match_header("user-agent", agent)
3388 .with_status(200)
3389 .with_header("Last-Modified", "Wed, 21 Feb 2024 15:30:45 GMT")
3390 .create();
3391 let download = server
3392 .mock("GET", "/mod.zip")
3393 .match_header("user-agent", agent)
3394 .with_status(200)
3395 .with_header("Content-Length", &archive.len().to_string())
3396 .with_body(archive)
3397 .create();
3398 let create_code = server
3399 .mock("POST", "/api/experimental/legacyprofile/create/")
3400 .match_header("user-agent", agent)
3401 .with_status(200)
3402 .with_body(r#"{"key":"abc-123"}"#)
3403 .create();
3404 let fetch_code = server
3405 .mock("GET", "/api/experimental/legacyprofile/get/abc-123/")
3406 .match_header("user-agent", agent)
3407 .with_status(200)
3408 .with_body("#r2modman\nQUJD")
3409 .create();
3410 let readme = server
3411 .mock("GET", "/api/experimental/package/Owner/ModA/1.0.0/readme/")
3412 .match_header("user-agent", agent)
3413 .with_status(200)
3414 .with_body(r##"{"markdown":"# ModA"}"##)
3415 .create();
3416
3417 let cache = tempdir().unwrap();
3418 let client = ThunderstoreClient::builder()
3419 .base_url(server.url())
3420 .community("valheim")
3421 .cache_dir(cache.path())
3422 .user_agent(agent)
3423 .retry(RetryPolicy::none())
3424 .build()
3425 .unwrap();
3426 let urls = HashMap::from([("mod.zip".to_string(), format!("{}/mod.zip", server.url()))]);
3427
3428 let rt = Runtime::new().unwrap();
3429
3430 rt.block_on(async {
3431 client.refresh_index().await.unwrap();
3432 client.get_manifest().await.unwrap();
3433 client.download_files(urls).await.unwrap();
3434 client.create_profile_code(b"payload").await.unwrap();
3435 client.fetch_profile_code("abc-123").await.unwrap();
3436 client.get_readme("Owner", "ModA", "1.0.0").await.unwrap();
3437 });
3438
3439 index_get.assert();
3440 index_head.assert();
3441 download.assert();
3442 create_code.assert();
3443 fetch_code.assert();
3444 readme.assert();
3445 }
3446
3447 #[test]
3448 fn user_agent_is_not_sent_unless_set() {
3449 let mut server = Server::new();
3450
3451 let mock = server
3452 .mock("GET", "/api/experimental/legacyprofile/get/abc-123/")
3453 .match_header("user-agent", mockito::Matcher::Missing)
3454 .with_status(200)
3455 .with_body("#r2modman\nQUJD")
3456 .create();
3457
3458 let cache = tempdir().unwrap();
3459 let client = ThunderstoreClient::builder()
3460 .base_url(server.url())
3461 .community("valheim")
3462 .cache_dir(cache.path())
3463 .retry(RetryPolicy::none())
3464 .build()
3465 .unwrap();
3466
3467 let rt = Runtime::new().unwrap();
3468
3469 rt.block_on(client.fetch_profile_code("abc-123")).unwrap();
3470
3471 mock.assert();
3472 }
3473
3474 #[test]
3475 fn user_agent_that_is_not_a_header_value_fails_build() {
3476 let cache = tempdir().unwrap();
3477
3478 let result = ThunderstoreClient::builder()
3479 .community("valheim")
3480 .cache_dir(cache.path())
3481 .user_agent("bad\nagent")
3482 .build();
3483
3484 assert!(result.is_err());
3485 }
3486
3487 #[test]
3488 fn fetch_profile_code_rejects_unsafe_code() {
3489 let cache = tempdir().unwrap();
3490 let client = ThunderstoreClient::builder()
3491 .community("valheim")
3492 .cache_dir(cache.path())
3493 .build()
3494 .unwrap();
3495
3496 let rt = Runtime::new().unwrap();
3497
3498 assert!(matches!(
3500 rt.block_on(client.fetch_profile_code("../../evil")),
3501 Err(Error::Config(_))
3502 ));
3503 }
3504
3505 #[test]
3506 fn get_readme_retries_a_server_error_then_reports_it() {
3507 let mut server = Server::new();
3508
3509 let mock = server
3510 .mock("GET", "/api/experimental/package/Owner/ModA/1.0.0/readme/")
3511 .with_status(503)
3512 .expect(2)
3513 .create();
3514
3515 let cache = tempdir().unwrap();
3516 let client = ThunderstoreClient::builder()
3517 .base_url(server.url())
3518 .community("valheim")
3519 .cache_dir(cache.path())
3520 .retry(RetryPolicy {
3521 max_retries: 1,
3522 base_delay: Duration::ZERO,
3523 max_delay: Duration::ZERO,
3524 })
3525 .build()
3526 .unwrap();
3527
3528 let rt = Runtime::new().unwrap();
3529 let result = rt.block_on(client.get_readme("Owner", "ModA", "1.0.0"));
3530
3531 assert!(matches!(result, Err(Error::Http(_))), "{result:?}");
3532 mock.assert();
3533 }
3534
3535 #[test]
3536 fn get_readme_rejects_segments_that_would_change_the_path() {
3537 let cache = tempdir().unwrap();
3538 let client = ThunderstoreClient::builder()
3539 .community("valheim")
3540 .cache_dir(cache.path())
3541 .build()
3542 .unwrap();
3543
3544 let rt = Runtime::new().unwrap();
3545
3546 for (owner, name, version) in [
3547 ("..", "ModA", "1.0.0"),
3548 ("Owner", "Mod/A", "1.0.0"),
3549 ("Owner", "ModA", "1.0.0?x=1"),
3550 ("Owner", "", "1.0.0"),
3551 ] {
3552 assert!(
3553 matches!(
3554 rt.block_on(client.get_readme(owner, name, version)),
3555 Err(Error::Config(_))
3556 ),
3557 "{owner}/{name}/{version}"
3558 );
3559 }
3560 }
3561}