1use nereids_core::elements;
11use nereids_core::types::Isotope;
12use std::fs;
13use std::io::Read;
14use std::path::{Path, PathBuf};
15use std::sync::{Mutex, OnceLock};
16use std::time::{Duration, Instant};
17
18const IAEA_BASE_URL: &str = "https://www-nds.iaea.org/public/download-endf";
19const NNDC_ENDF_BASE_URL: &str = "https://www.nndc.bnl.gov/endf-data/ENDF";
20const ENDF_USER_AGENT: &str = concat!(
25 "NEREIDS/",
26 env!("CARGO_PKG_VERSION"),
27 " (https://github.com/ornlneutronimaging/NEREIDS; contact: zhangc@ornl.gov)",
28);
29const IAEA_MIN_REQUEST_INTERVAL: Duration = Duration::from_secs(3);
30
31static LAST_IAEA_REQUEST: OnceLock<Mutex<Option<Instant>>> = OnceLock::new();
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
35pub enum EndfLibrary {
36 #[serde(rename = "ENDF/B-VIII.0")]
38 EndfB8_0,
39 #[serde(rename = "ENDF/B-VIII.1")]
41 EndfB8_1,
42 #[serde(rename = "JEFF-3.3")]
44 Jeff3_3,
45 #[serde(rename = "JENDL-5")]
47 Jendl5,
48 #[serde(rename = "TENDL-2023")]
51 Tendl2023,
52 #[serde(rename = "CENDL-3.2")]
57 Cendl3_2,
58}
59
60impl EndfLibrary {
61 fn url_path(&self) -> &'static str {
63 match self {
64 Self::EndfB8_0 => "ENDF-B-VIII.0/n",
65 Self::EndfB8_1 => "ENDF-B-VIII.1/n",
66 Self::Jeff3_3 => "JEFF-3.3/n",
67 Self::Jendl5 => "JENDL-5/n",
68 Self::Tendl2023 => "TENDL-2023/n",
69 Self::Cendl3_2 => "CENDL-3.2/n",
70 }
71 }
72
73 fn cache_dir_name(&self) -> &'static str {
75 match self {
76 Self::EndfB8_0 => "ENDF-B-VIII.0",
77 Self::EndfB8_1 => "ENDF-B-VIII.1",
78 Self::Jeff3_3 => "JEFF-3.3",
79 Self::Jendl5 => "JENDL-5",
80 Self::Tendl2023 => "TENDL-2023",
81 Self::Cendl3_2 => "CENDL-3.2",
82 }
83 }
84
85 fn zip_filename(&self, isotope: &Isotope, mat: u32) -> String {
92 let sym = elements::element_symbol(isotope.z()).unwrap_or("X");
93 let z = isotope.z();
94 let a = isotope.a();
95 match self {
96 Self::EndfB8_0 | Self::Jeff3_3 => {
97 format!("n_{mat:04}_{z}-{sym}-{a}.zip")
98 }
99 Self::EndfB8_1 | Self::Jendl5 | Self::Tendl2023 | Self::Cendl3_2 => {
100 let zip_sym = if z == 0 && a == 1 { "nn" } else { sym };
101 format!("n_{z:03}-{zip_sym}-{a}_{mat:04}.zip")
102 }
103 }
104 }
105}
106
107pub fn default_cache_dir(library: EndfLibrary) -> PathBuf {
115 default_cache_root().join(library.cache_dir_name())
116}
117
118pub fn default_cache_file_path(isotope: &Isotope, library: EndfLibrary) -> PathBuf {
121 let sym = elements::element_symbol(isotope.z()).unwrap_or("X");
122 default_cache_dir(library).join(format!("{}-{}.endf", sym, isotope.a()))
123}
124
125const ENDF_CACHE_ENV: &str = "NEREIDS_ENDF_CACHE";
127
128fn default_cache_root() -> PathBuf {
129 cache_root_from(std::env::var_os(ENDF_CACHE_ENV))
130}
131
132fn cache_root_from(env_root: Option<std::ffi::OsString>) -> PathBuf {
133 match env_root {
134 Some(root) if !root.is_empty() => PathBuf::from(root),
135 _ => dirs::cache_dir()
136 .unwrap_or_else(|| PathBuf::from(".cache"))
137 .join("nereids")
138 .join("endf"),
139 }
140}
141
142pub struct EndfRetriever {
144 cache_root: PathBuf,
146 base_url: String,
149 client: reqwest::blocking::Client,
152}
153
154impl EndfRetriever {
155 pub fn new() -> Self {
157 Self {
158 cache_root: default_cache_root(),
159 base_url: IAEA_BASE_URL.to_string(),
160 client: build_http_client(),
161 }
162 }
163
164 pub fn with_cache_dir(cache_dir: impl Into<PathBuf>) -> Self {
166 Self {
167 cache_root: cache_dir.into(),
168 base_url: IAEA_BASE_URL.to_string(),
169 client: build_http_client(),
170 }
171 }
172
173 pub fn cache_dir(&self, library: EndfLibrary) -> PathBuf {
178 self.cache_root.join(library.cache_dir_name())
179 }
180
181 pub fn cache_file_path(&self, isotope: &Isotope, library: EndfLibrary) -> PathBuf {
186 let sym = elements::element_symbol(isotope.z()).unwrap_or("X");
187 let filename = format!("{}-{}.endf", sym, isotope.a());
188 self.cache_dir(library).join(filename)
189 }
190
191 pub fn get_endf_file(
200 &self,
201 isotope: &Isotope,
202 library: EndfLibrary,
203 mat: u32,
204 ) -> Result<(PathBuf, String), EndfRetrievalError> {
205 let cache_path = self.cache_file_path(isotope, library);
206
207 if cache_path.exists() {
209 let contents = fs::read_to_string(&cache_path)?;
210 return Ok((cache_path, contents));
211 }
212
213 let contents = self.download_endf(isotope, library, mat)?;
215
216 if let Some(parent) = cache_path.parent() {
218 fs::create_dir_all(parent)?;
219 }
220 fs::write(&cache_path, &contents)?;
221
222 Ok((cache_path, contents))
223 }
224
225 fn download_endf(
227 &self,
228 isotope: &Isotope,
229 library: EndfLibrary,
230 mat: u32,
231 ) -> Result<String, EndfRetrievalError> {
232 let nndc_url = nndc_endf_url(isotope, library);
233 let nndc_already_tried = if let Some(primary_url) = &nndc_url {
234 if let Ok(text) = self.fetch_text(primary_url, false) {
235 return Ok(text);
236 }
237 true
238 } else {
239 false
240 };
241
242 let zip_filename = library.zip_filename(isotope, mat);
243 let url = format!("{}/{}/{}", self.base_url, library.url_path(), zip_filename);
244 let iaea_result = self.fetch_bytes(&url, true);
245 match iaea_result {
246 Ok(bytes) => extract_endf_from_zip(&bytes),
247 Err(err) if should_try_nndc_fallback(&err) => {
248 if !nndc_already_tried
249 && let Some(fallback_url) = &nndc_url
250 && let Ok(text) = self.fetch_text(fallback_url, false)
251 {
252 return Ok(text);
253 }
254 Err(err.into_retrieval_error(isotope, library))
255 }
256 Err(err) => Err(err.into_retrieval_error(isotope, library)),
257 }
258 }
259
260 fn fetch_bytes(&self, url: &str, pace_iaea: bool) -> Result<Vec<u8>, DownloadError> {
261 if pace_iaea {
262 wait_for_iaea_slot();
263 }
264 let response = self
265 .client
266 .get(url)
267 .send()
268 .map_err(|e| DownloadError::Transport {
269 url: url.to_string(),
270 message: format_error_chain(&e),
271 })?;
272
273 let status = response.status();
274 if !status.is_success() {
275 return Err(DownloadError::Http {
276 url: url.to_string(),
277 status,
278 cloudflare_challenge: has_cloudflare_challenge(&response),
279 });
280 }
281
282 response
283 .bytes()
284 .map(|bytes| bytes.to_vec())
285 .map_err(|e| DownloadError::Transport {
286 url: url.to_string(),
287 message: format!("Failed to read response body: {}", format_error_chain(&e)),
288 })
289 }
290
291 fn fetch_text(&self, url: &str, pace_iaea: bool) -> Result<String, EndfRetrievalError> {
292 let bytes = self
293 .fetch_bytes(url, pace_iaea)
294 .map_err(|err| err.into_retrieval_error_for_url())?;
295 String::from_utf8(bytes)
296 .map_err(|e| EndfRetrievalError::Parse(format!("Invalid UTF-8 ENDF response: {e}")))
297 }
298
299 pub fn peek_local_endf(source: &Path) -> Result<(Isotope, String), EndfRetrievalError> {
309 let raw = fs::read(source)?;
310 let endf_text = if looks_like_zip(source, &raw) {
311 extract_endf_from_zip(&raw)?
312 } else {
313 String::from_utf8(raw).map_err(|e| {
314 EndfRetrievalError::Parse(format!("ENDF file is not valid UTF-8: {e}"))
315 })?
316 };
317 let parsed = crate::parser::parse_endf_file2(&endf_text)
318 .map_err(|e| EndfRetrievalError::Parse(format!("Failed to parse ENDF file: {e}")))?;
319 Ok((parsed.isotope, endf_text))
320 }
321
322 pub fn install_endf_text(
329 &self,
330 isotope: &Isotope,
331 library: EndfLibrary,
332 text: &str,
333 ) -> Result<PathBuf, EndfRetrievalError> {
334 let cache_path = self.cache_file_path(isotope, library);
335 if let Some(parent) = cache_path.parent() {
336 fs::create_dir_all(parent)?;
337 }
338 fs::write(&cache_path, text)?;
339 Ok(cache_path)
340 }
341
342 pub fn install_local_endf(
355 &self,
356 isotope: &Isotope,
357 library: EndfLibrary,
358 source: &Path,
359 ) -> Result<(PathBuf, String), EndfRetrievalError> {
360 let (found, endf_text) = Self::peek_local_endf(source)?;
361 if found != *isotope {
362 return Err(EndfRetrievalError::IsotopeMismatch {
363 expected: isotope_label(isotope),
364 found: isotope_label(&found),
365 });
366 }
367 let cache_path = self.install_endf_text(isotope, library, &endf_text)?;
368 Ok((cache_path, endf_text))
369 }
370}
371
372impl Default for EndfRetriever {
373 fn default() -> Self {
374 Self::new()
375 }
376}
377
378pub fn mat_number(isotope: &Isotope, library: EndfLibrary) -> Option<u32> {
392 match library {
393 EndfLibrary::Tendl2023 => endf_mat::mat_number_tendl(isotope.z(), isotope.a()),
394 EndfLibrary::Cendl3_2 => endf_mat::mat_number_cendl(isotope.z(), isotope.a()),
395 _ => endf_mat::mat_number(isotope.z(), isotope.a()),
396 }
397}
398
399pub fn known_isotopes_for(z: u32, library: EndfLibrary) -> Vec<u32> {
407 match library {
408 EndfLibrary::Tendl2023 => endf_mat::known_isotopes_tendl(z),
409 EndfLibrary::Cendl3_2 => endf_mat::known_isotopes_cendl(z),
410 _ => endf_mat::known_isotopes(z),
411 }
412}
413
414pub fn has_endf_evaluation_for(z: u32, a: u32, library: EndfLibrary) -> bool {
420 match library {
421 EndfLibrary::Tendl2023 => endf_mat::has_endf_evaluation_tendl(z, a),
422 EndfLibrary::Cendl3_2 => endf_mat::has_endf_evaluation_cendl(z, a),
423 _ => endf_mat::has_endf_evaluation(z, a),
424 }
425}
426
427#[derive(Debug, thiserror::Error)]
429pub enum EndfRetrievalError {
430 #[error("Network error: {0}")]
432 NetworkError(String),
433
434 #[error("Remote access blocked: HTTP {status} for {url}. {message}")]
436 RemoteAccessBlocked {
437 status: u16,
438 url: String,
439 message: String,
440 },
441
442 #[error("{isotope} is not available in the {library} library")]
444 NotInLibrary { isotope: String, library: String },
445
446 #[error("ENDF file is for {found}, but expected {expected}")]
449 IsotopeMismatch { expected: String, found: String },
450
451 #[error("Parse error: {0}")]
452 Parse(String),
453
454 #[error("I/O error: {0}")]
455 Io(#[from] std::io::Error),
456
457 #[error("Isotope not found in MAT database: {0}")]
458 UnknownIsotope(String),
459}
460
461impl EndfRetrievalError {
462 pub fn is_remote_access_blocked(&self) -> bool {
464 matches!(self, Self::RemoteAccessBlocked { .. })
465 }
466
467 pub fn is_unavailable(&self) -> bool {
468 match self {
469 Self::NetworkError(_) | Self::RemoteAccessBlocked { .. } => true,
470 Self::NotInLibrary { .. }
471 | Self::IsotopeMismatch { .. }
472 | Self::Parse(_)
473 | Self::Io(_)
474 | Self::UnknownIsotope(_) => false,
475 }
476 }
477}
478
479#[derive(Debug)]
480enum DownloadError {
481 Http {
482 url: String,
483 status: reqwest::StatusCode,
484 cloudflare_challenge: bool,
485 },
486 Transport {
487 url: String,
488 message: String,
489 },
490}
491
492impl DownloadError {
493 fn into_retrieval_error(self, isotope: &Isotope, library: EndfLibrary) -> EndfRetrievalError {
494 match self {
495 Self::Http { status, .. } if status == reqwest::StatusCode::NOT_FOUND => {
496 EndfRetrievalError::NotInLibrary {
497 isotope: isotope_label(isotope),
498 library: library.cache_dir_name().to_string(),
499 }
500 }
501 other => other.into_retrieval_error_for_url(),
502 }
503 }
504
505 fn into_retrieval_error_for_url(self) -> EndfRetrievalError {
506 match self {
507 Self::Http {
508 url,
509 status,
510 cloudflare_challenge,
511 } if is_access_block_status(status) => EndfRetrievalError::RemoteAccessBlocked {
512 status: status.as_u16(),
513 url,
514 message: if cloudflare_challenge {
515 "The server returned a Cloudflare managed challenge; stop batch fetches and retry later from a normal browser/network."
516 .to_string()
517 } else {
518 "The upstream server denied automated access; stop batch fetches and retry later."
519 .to_string()
520 },
521 },
522 Self::Http { url, status, .. } => {
523 EndfRetrievalError::NetworkError(format!("HTTP {status} for {url}"))
524 }
525 Self::Transport { url, message } => {
526 EndfRetrievalError::NetworkError(format!("Failed to fetch {url}: {message}"))
527 }
528 }
529 }
530}
531
532fn extract_endf_from_zip(zip_bytes: &[u8]) -> Result<String, EndfRetrievalError> {
538 let cursor = std::io::Cursor::new(zip_bytes);
539 let mut archive = zip::ZipArchive::new(cursor)
540 .map_err(|e| EndfRetrievalError::Parse(format!("Invalid ZIP archive: {}", e)))?;
541
542 for i in 0..archive.len() {
543 let mut file = archive
544 .by_index(i)
545 .map_err(|e| EndfRetrievalError::Parse(format!("Failed to read ZIP entry: {}", e)))?;
546 let name = file
547 .name()
548 .map_err(|e| EndfRetrievalError::Parse(format!("Failed to read ZIP entry: {}", e)))?
549 .to_lowercase();
550 if name.ends_with(".endf") || name.ends_with(".dat") || name.ends_with(".txt") {
551 let mut contents = String::new();
552 file.read_to_string(&mut contents).map_err(|e| {
553 EndfRetrievalError::Parse(format!("Failed to read ENDF content: {}", e))
554 })?;
555 return Ok(contents);
556 }
557 }
558
559 if !archive.is_empty() {
560 let mut file = archive
561 .by_index(0)
562 .map_err(|e| EndfRetrievalError::Parse(format!("Failed to read ZIP entry: {}", e)))?;
563 let mut contents = String::new();
564 file.read_to_string(&mut contents).map_err(|e| {
565 EndfRetrievalError::Parse(format!("Failed to read ENDF content: {}", e))
566 })?;
567 return Ok(contents);
568 }
569
570 Err(EndfRetrievalError::Parse(
571 "No ENDF data file found in ZIP archive".to_string(),
572 ))
573}
574
575fn looks_like_zip(source: &Path, raw: &[u8]) -> bool {
581 let by_ext = source
582 .extension()
583 .and_then(|s| s.to_str())
584 .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"));
585 let by_magic = raw.len() >= 4 && &raw[..4] == b"PK\x03\x04";
586 by_ext || by_magic
587}
588
589fn build_http_client() -> reqwest::blocking::Client {
595 reqwest::blocking::Client::builder()
596 .user_agent(ENDF_USER_AGENT)
597 .connect_timeout(Duration::from_secs(15))
598 .timeout(Duration::from_secs(60))
599 .build()
600 .expect("failed to build reqwest blocking client")
601}
602
603fn wait_for_iaea_slot() {
604 let mut last_request = LAST_IAEA_REQUEST
605 .get_or_init(|| Mutex::new(None))
606 .lock()
607 .expect("IAEA request throttle mutex poisoned");
608 if let Some(last) = *last_request {
609 let elapsed = last.elapsed();
610 if elapsed < IAEA_MIN_REQUEST_INTERVAL {
611 std::thread::sleep(IAEA_MIN_REQUEST_INTERVAL - elapsed);
612 }
613 }
614 *last_request = Some(Instant::now());
615}
616
617fn nndc_endf_url(isotope: &Isotope, library: EndfLibrary) -> Option<String> {
618 let version = match library {
619 EndfLibrary::EndfB8_0 => "ENDF-B-VIII.0",
620 EndfLibrary::EndfB8_1 => "ENDF-B-VIII.1",
621 _ => return None,
622 };
623 let sym = elements::element_symbol(isotope.z())?;
624 Some(format!(
625 "{NNDC_ENDF_BASE_URL}/{version}/n-{z:03}_{sym}_{a:03}.endf",
626 z = isotope.z(),
627 a = isotope.a()
628 ))
629}
630
631fn should_try_nndc_fallback(err: &DownloadError) -> bool {
632 match err {
633 DownloadError::Http { status, .. } => {
634 *status == reqwest::StatusCode::NOT_FOUND || is_access_block_status(*status)
635 }
636 DownloadError::Transport { .. } => true,
637 }
638}
639
640fn is_access_block_status(status: reqwest::StatusCode) -> bool {
641 status == reqwest::StatusCode::FORBIDDEN
642 || status == reqwest::StatusCode::TOO_MANY_REQUESTS
643 || status == reqwest::StatusCode::SERVICE_UNAVAILABLE
644}
645
646fn has_cloudflare_challenge(response: &reqwest::blocking::Response) -> bool {
647 response
648 .headers()
649 .get("cf-mitigated")
650 .and_then(|value| value.to_str().ok())
651 .is_some_and(|value| value.eq_ignore_ascii_case("challenge"))
652}
653
654fn isotope_label(isotope: &Isotope) -> String {
655 format!(
656 "{}-{}",
657 nereids_core::elements::element_symbol(isotope.z()).unwrap_or("?"),
658 isotope.a()
659 )
660}
661
662fn format_error_chain(err: &dyn std::error::Error) -> String {
666 let mut out = err.to_string();
667 let mut cur = err.source();
668 while let Some(s) = cur {
669 out.push_str(": ");
670 out.push_str(&s.to_string());
671 cur = s.source();
672 }
673 out
674}
675
676#[cfg(test)]
677mod tests {
678 use super::*;
679
680 #[test]
681 fn cendl_neutron_uses_upstream_nn_filename() {
682 let neutron = Isotope::new(0, 1).unwrap();
683 assert_eq!(
684 EndfLibrary::Cendl3_2.zip_filename(&neutron, 25),
685 "n_000-nn-1_0025.zip"
686 );
687 }
688
689 #[test]
690 fn cendl_neutron_has_library_aware_mat_lookup() {
691 let neutron = Isotope::new(0, 1).unwrap();
692 assert_eq!(mat_number(&neutron, EndfLibrary::Cendl3_2), Some(25));
693 }
694
695 #[test]
696 fn nndc_fallback_url_uses_raw_endf_naming() {
697 let ba138 = Isotope::new(56, 138).unwrap();
698 assert_eq!(
699 nndc_endf_url(&ba138, EndfLibrary::EndfB8_1).as_deref(),
700 Some("https://www.nndc.bnl.gov/endf-data/ENDF/ENDF-B-VIII.1/n-056_Ba_138.endf")
701 );
702 assert!(nndc_endf_url(&ba138, EndfLibrary::Cendl3_2).is_none());
703
704 let fe56 = Isotope::new(26, 56).unwrap();
705 assert_eq!(
706 nndc_endf_url(&fe56, EndfLibrary::EndfB8_1).as_deref(),
707 Some("https://www.nndc.bnl.gov/endf-data/ENDF/ENDF-B-VIII.1/n-026_Fe_056.endf")
708 );
709 let h1 = Isotope::new(1, 1).unwrap();
710 assert_eq!(
711 nndc_endf_url(&h1, EndfLibrary::EndfB8_0).as_deref(),
712 Some("https://www.nndc.bnl.gov/endf-data/ENDF/ENDF-B-VIII.0/n-001_H_001.endf")
713 );
714 }
715
716 #[test]
717 fn iaea_zip_filename_keeps_mass_unpadded() {
718 let fe56 = Isotope::new(26, 56).unwrap();
719 assert_eq!(
720 EndfLibrary::EndfB8_1.zip_filename(&fe56, 2631),
721 "n_026-Fe-56_2631.zip"
722 );
723 assert_eq!(
724 EndfLibrary::EndfB8_0.zip_filename(&fe56, 2631),
725 "n_2631_26-Fe-56.zip"
726 );
727 }
728
729 #[test]
730 fn remote_access_blocked_is_identifiable() {
731 let err = EndfRetrievalError::RemoteAccessBlocked {
732 status: 403,
733 url: "https://example.test/file.zip".into(),
734 message: "blocked".into(),
735 };
736 assert!(err.is_remote_access_blocked());
737 assert!(err.is_unavailable());
738 assert!(EndfRetrievalError::NetworkError("refused".into()).is_unavailable());
739 let absent = EndfRetrievalError::NotInLibrary {
740 isotope: "Fe-56".into(),
741 library: "endf8.1".into(),
742 };
743 assert!(!absent.is_unavailable());
744 assert!(!EndfRetrievalError::Io(std::io::Error::other("disk")).is_unavailable());
745 }
746
747 #[test]
750 fn endf_user_agent_contains_version_and_contact() {
751 assert!(
752 ENDF_USER_AGENT.starts_with("NEREIDS/"),
753 "UA must start with NEREIDS/, got {ENDF_USER_AGENT:?}"
754 );
755 assert!(
756 ENDF_USER_AGENT.contains(env!("CARGO_PKG_VERSION")),
757 "UA must carry CARGO_PKG_VERSION, got {ENDF_USER_AGENT:?}"
758 );
759 assert!(
760 ENDF_USER_AGENT.contains("github.com/ornlneutronimaging/NEREIDS"),
761 "UA must include the project URL, got {ENDF_USER_AGENT:?}"
762 );
763 assert!(
764 ENDF_USER_AGENT.contains("contact: zhangc@ornl.gov"),
765 "UA must include a contact mailbox, got {ENDF_USER_AGENT:?}"
766 );
767 }
768
769 const W184_FIXTURE: &str = concat!(
779 " 7.418400+4 1.820000+2 0 0 1 07437 2151 1\n",
780 " 7.418400+4 1.000000+0 0 0 1 07437 2151 2\n",
781 " 1.000000-5 1.000000+3 1 2 0 07437 2151 3\n",
782 " 0.000000+0 7.000000-1 0 0 1 07437 2151 4\n",
783 " 1.820000+2 0.000000+0 0 0 6 17437 2151 5\n",
784 " 1.000000+1 5.000000-1 2.600000-2 1.000000-3 2.500000-2 0.000000+07437 2151 6\n",
785 );
786
787 fn write_zip_with_endf(zip_path: &Path, inner_name: &str, body: &str) -> std::io::Result<()> {
788 let file = fs::File::create(zip_path)?;
789 let mut zw = zip::ZipWriter::new(file);
790 zw.start_file::<_, ()>(inner_name, zip::write::SimpleFileOptions::default())
791 .map_err(|e| std::io::Error::other(format!("zip start_file: {e}")))?;
792 std::io::Write::write_all(&mut zw, body.as_bytes())?;
793 zw.finish()
794 .map_err(|e| std::io::Error::other(format!("zip finish: {e}")))?;
795 Ok(())
796 }
797
798 #[test]
799 fn install_local_endf_accepts_raw_endf_with_matching_isotope() {
800 let cache = tempfile::tempdir().expect("tempdir");
801 let src = tempfile::NamedTempFile::new().expect("src file");
802 std::fs::write(src.path(), W184_FIXTURE).unwrap();
803
804 let retriever = EndfRetriever::with_cache_dir(cache.path());
805 let w184 = Isotope::new(74, 184).unwrap();
806 let (cache_path, text) = retriever
807 .install_local_endf(&w184, EndfLibrary::EndfB8_0, src.path())
808 .expect("install must succeed");
809
810 assert!(cache_path.exists(), "cache file must be written");
811 assert!(text.contains("7.418400+4"), "returned text matches input");
812 let (cached_path, cached_text) = retriever
814 .get_endf_file(&w184, EndfLibrary::EndfB8_0, 7437)
815 .expect("cache hit must succeed offline");
816 assert_eq!(cached_path, cache_path);
817 assert_eq!(cached_text, text);
818 }
819
820 #[test]
821 fn install_local_endf_accepts_zip_archive() {
822 let cache = tempfile::tempdir().expect("tempdir");
823 let zip_path = cache.path().join("upload.zip");
824 write_zip_with_endf(&zip_path, "n_7437_74-W-184.endf", W184_FIXTURE)
825 .expect("write zip fixture");
826
827 let retriever = EndfRetriever::with_cache_dir(cache.path());
828 let w184 = Isotope::new(74, 184).unwrap();
829 let (cache_path, _) = retriever
830 .install_local_endf(&w184, EndfLibrary::EndfB8_0, &zip_path)
831 .expect("zip install must succeed");
832 assert!(cache_path.exists());
833 assert_eq!(
834 fs::read_to_string(&cache_path).unwrap(),
835 W184_FIXTURE,
836 "cache must hold the extracted body, not the zip"
837 );
838 }
839
840 #[test]
844 fn default_cache_paths_agree_with_retriever_instance() {
845 let retriever = EndfRetriever::new();
846 let w184 = Isotope::new(74, 184).unwrap();
847 for lib in [
848 EndfLibrary::EndfB8_0,
849 EndfLibrary::EndfB8_1,
850 EndfLibrary::Jeff3_3,
851 EndfLibrary::Jendl5,
852 EndfLibrary::Tendl2023,
853 EndfLibrary::Cendl3_2,
854 ] {
855 assert_eq!(default_cache_dir(lib), retriever.cache_dir(lib));
856 assert_eq!(
857 default_cache_file_path(&w184, lib),
858 retriever.cache_file_path(&w184, lib)
859 );
860 }
861 }
862
863 #[test]
864 fn cache_root_follows_env_value_unless_empty() {
865 assert_eq!(
866 cache_root_from(Some("/site/endf".into())),
867 PathBuf::from("/site/endf")
868 );
869 let user_root = cache_root_from(None);
870 assert!(user_root.ends_with("nereids/endf"));
871 assert_eq!(cache_root_from(Some("".into())), user_root);
872 }
873
874 #[test]
875 fn peek_local_endf_extracts_isotope_from_zip_and_raw() {
876 let dir = tempfile::tempdir().expect("tempdir");
877
878 let raw_path = dir.path().join("W-184.endf");
880 std::fs::write(&raw_path, W184_FIXTURE).unwrap();
881 let (iso, text) = EndfRetriever::peek_local_endf(&raw_path).expect("raw peek");
882 assert_eq!(iso, Isotope::new(74, 184).unwrap());
883 assert_eq!(text, W184_FIXTURE);
884
885 let zip_path = dir.path().join("upload.zip");
887 write_zip_with_endf(&zip_path, "inner.endf", W184_FIXTURE).expect("zip");
888 let (iso_z, text_z) = EndfRetriever::peek_local_endf(&zip_path).expect("zip peek");
889 assert_eq!(iso_z, Isotope::new(74, 184).unwrap());
890 assert_eq!(text_z, W184_FIXTURE);
891 }
892
893 #[test]
898 fn install_local_endf_accepts_extensionless_zip_via_magic_bytes() {
899 let dir = tempfile::tempdir().expect("tempdir");
900 let zip_path = dir.path().join("upload-no-extension"); write_zip_with_endf(&zip_path, "inner.endf", W184_FIXTURE).expect("write zip");
902
903 assert!(zip_path.extension().is_none());
905 let head = std::fs::read(&zip_path).unwrap();
906 assert_eq!(&head[..4], b"PK\x03\x04");
907
908 let retriever = EndfRetriever::with_cache_dir(dir.path().join("cache"));
909 let w184 = Isotope::new(74, 184).unwrap();
910 let (cache_path, text) = retriever
911 .install_local_endf(&w184, EndfLibrary::EndfB8_0, &zip_path)
912 .expect("extensionless zip must still install");
913 assert!(cache_path.exists());
914 assert_eq!(text, W184_FIXTURE);
915
916 let (iso, peeked_text) =
918 EndfRetriever::peek_local_endf(&zip_path).expect("peek must also work");
919 assert_eq!(iso, w184);
920 assert_eq!(peeked_text, W184_FIXTURE);
921 }
922
923 #[test]
924 fn install_local_endf_rejects_isotope_mismatch() {
925 let cache = tempfile::tempdir().expect("tempdir");
926 let src = tempfile::NamedTempFile::new().expect("src file");
927 std::fs::write(src.path(), W184_FIXTURE).unwrap();
928
929 let retriever = EndfRetriever::with_cache_dir(cache.path());
930 let hf180 = Isotope::new(72, 180).unwrap();
931 let err = retriever
932 .install_local_endf(&hf180, EndfLibrary::EndfB8_0, src.path())
933 .expect_err("must reject ZA mismatch");
934
935 match err {
936 EndfRetrievalError::IsotopeMismatch { expected, found } => {
937 assert!(expected.contains("Hf"), "expected label, got {expected}");
938 assert!(found.contains("W"), "found label, got {found}");
939 }
940 other => panic!("expected IsotopeMismatch, got {other:?}"),
941 }
942 assert!(
943 !retriever
944 .cache_file_path(&hf180, EndfLibrary::EndfB8_0)
945 .exists(),
946 "no cache file must be written on mismatch"
947 );
948 }
949}