Skip to main content

nereids_endf/
retrieval.rs

1//! ENDF file download and local caching.
2//!
3//! Downloads ENDF files from official NNDC/IAEA sources and caches them locally
4//! for offline use. Follows the IAEA URL patterns established by PLEIADES.
5//!
6//! ## PLEIADES Reference
7//! - `pleiades/nuclear/manager.py` — URL construction, cache directory layout
8//! - `pleiades/nuclear/models.py` — library enum, filename patterns
9
10use 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";
20// Polite, identifiable UA: many nuclear-data servers either require a non-default
21// UA or treat default `reqwest` traffic as a bot (IAEA returning
22// HTTP 403 to v0.1.8 batch fetches). Version is derived from `CARGO_PKG_VERSION`
23// so it never drifts from `Cargo.toml`.
24const 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/// ENDF evaluated nuclear data libraries, serialized by name.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
35pub enum EndfLibrary {
36    /// ENDF/B-VIII.0 (previous release).
37    #[serde(rename = "ENDF/B-VIII.0")]
38    EndfB8_0,
39    /// ENDF/B-VIII.1 (latest release, Aug 2024).
40    #[serde(rename = "ENDF/B-VIII.1")]
41    EndfB8_1,
42    /// JEFF-3.3 (European library).
43    #[serde(rename = "JEFF-3.3")]
44    Jeff3_3,
45    /// JENDL-5 (Japanese library).
46    #[serde(rename = "JENDL-5")]
47    Jendl5,
48    /// TENDL-2023 (TALYS-based, 2,300 ground-state isotopes including activation
49    /// products and transuranics not covered by the major evaluated libraries).
50    #[serde(rename = "TENDL-2023")]
51    Tendl2023,
52    /// CENDL-3.2 (Chinese library, 258 ground-state isotopes plus free neutron;
53    /// Z=1–98 with no Br evaluations — no MAT entry for Br-79 / Br-81, so
54    /// `mat_number(.., EndfLibrary::Cendl3_2)` returns `None` for Br before any
55    /// retrieval call).
56    #[serde(rename = "CENDL-3.2")]
57    Cendl3_2,
58}
59
60impl EndfLibrary {
61    /// URL path component for this library.
62    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    /// Cache directory name.
74    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    /// Construct the ZIP filename for a given isotope.
86    ///
87    /// IAEA uses two naming conventions (MAT always 4-digit zero-padded):
88    /// - VIII.0, JEFF-3.3: MAT-first `n_{mat:04}_{z}-{Sym}-{a}.zip` (Z unpadded)
89    /// - VIII.1, JENDL-5, TENDL-2023, CENDL-3.2: Z-first
90    ///   `n_{z:03}-{Sym}-{a}_{mat:04}.zip` (Z 3-digit; free neutron uses `nn`)
91    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
107/// Compute the default on-disk cache directory for a given library without
108/// constructing an [`EndfRetriever`].
109///
110/// The retriever's constructor builds a `reqwest` blocking client + TLS
111/// configuration, which is wasted work when all the caller needs is the cache
112/// path for a UI hint or manual drop instruction. Mirrors the path layout
113/// that [`EndfRetriever::new`] would resolve to.
114pub fn default_cache_dir(library: EndfLibrary) -> PathBuf {
115    default_cache_root().join(library.cache_dir_name())
116}
117
118/// Compute the default cache file path for an isotope without constructing
119/// an [`EndfRetriever`]. Same layout as [`EndfRetriever::cache_file_path`].
120pub 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
125// Lets a site share one pre-filled folder where downloads are blocked.
126const 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
142/// ENDF file retrieval manager with local caching.
143pub struct EndfRetriever {
144    /// Root cache directory.
145    cache_root: PathBuf,
146    /// Base URL for IAEA downloads used by libraries that are not mirrored by
147    /// NNDC as raw ENDF-6 files.
148    base_url: String,
149    /// Shared HTTP client with explicit connect/total timeouts so a transport
150    /// stall surfaces as a clear error instead of hanging the GUI worker.
151    client: reqwest::blocking::Client,
152}
153
154impl EndfRetriever {
155    /// Create a new retriever with the cache root in `NEREIDS_ENDF_CACHE`, else `~/.cache/nereids/endf/`.
156    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    /// Create a retriever with a custom cache directory.
165    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    /// Get the cache directory for a specific library.
174    ///
175    /// Public so the GUI can show users exactly where to drop a manually-
176    /// downloaded ENDF file when a fetch fails.
177    pub fn cache_dir(&self, library: EndfLibrary) -> PathBuf {
178        self.cache_root.join(library.cache_dir_name())
179    }
180
181    /// Get the cached ENDF file path for an isotope.
182    ///
183    /// Public so callers can present the exact target path for manual file
184    /// drops; see [`Self::install_local_endf`] for the programmatic equivalent.
185    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    /// Retrieve the ENDF file for an isotope, using cache if available.
192    ///
193    /// Returns the path to the cached ENDF file and its contents as a string.
194    ///
195    /// # Arguments
196    /// * `isotope` — The isotope to retrieve data for.
197    /// * `library` — The ENDF library to use.
198    /// * `mat` — The ENDF MAT (material) number.
199    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        // Check cache first.
208        if cache_path.exists() {
209            let contents = fs::read_to_string(&cache_path)?;
210            return Ok((cache_path, contents));
211        }
212
213        // Download from the remote source.
214        let contents = self.download_endf(isotope, library, mat)?;
215
216        // Cache the file.
217        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    /// Download an ENDF file from NNDC raw files or IAEA ZIP archives.
226    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    /// Peek a user-supplied ENDF source: decode the body and parse the HEAD
300    /// record so the caller can route the upload to the correct isotope entry.
301    ///
302    /// Accepts the same input forms as [`Self::install_local_endf`] — a raw
303    /// ENDF text file or the IAEA ZIP archive distribution — and returns the
304    /// isotope declared by the file's MF=2 MT=151 HEAD record alongside the
305    /// decoded text. The GUI uses this to dispatch a manual upload to the
306    /// matching `IsotopeEntry` without re-reading or re-extracting the file
307    /// during install (avoid N-pass zip extraction).
308    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    /// Write already-validated ENDF text to the canonical cache slot for
323    /// `isotope`/`library`. Returns the cache file path.
324    ///
325    /// Use this when the caller has already obtained `text` via
326    /// [`Self::peek_local_endf`] and confirmed the isotope. For one-shot
327    /// install-from-path, use [`Self::install_local_endf`] instead.
328    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    /// Install a user-supplied ENDF file into the cache for `isotope`/`library`.
343    ///
344    /// Accepts either a raw ENDF text file (`.endf`, `.dat`, `.txt`, or
345    /// extensionless) or the IAEA ZIP archive distribution (`n_…_….zip`).
346    /// The file is parsed to verify that its declared isotope matches
347    /// `isotope`; on success the text is written to the canonical cache slot
348    /// returned by [`Self::cache_file_path`] and `(cache_path, text)` is
349    /// returned. Subsequent calls to [`Self::get_endf_file`] will then hit the
350    /// cache without any network access.
351    ///
352    /// This is the GUI's manual-upload escape hatch for users on networks
353    /// where IAEA/NNDC is blocked.
354    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
378/// Look up the ENDF MAT number for a ground-state isotope, library-aware.
379///
380/// Dispatches to the underlying `endf-mat` table for the requested library:
381/// - `Tendl2023`: ~2,300 ground-state isotopes from the TENDL-2023 neutrons sublibrary.
382/// - `Cendl3_2`: 258 isotopes plus free neutron from the CENDL-3.2 neutrons sublibrary (no Br entries).
383/// - All other variants: 535 isotopes from the ENDF/B-VIII.0 neutrons sublibrary
384///   (the MAT numbers in ENDF/B-VIII.1, JEFF-3.3, and JENDL-5 are identical to
385///   ENDF/B-VIII.0 for the isotopes they share).
386///
387/// MAT numbers are *almost* universal across libraries; the one documented exception
388/// is Es-255, which is MAT 9916 in ENDF/B-VIII.0 and MAT 9915 in TENDL-2023. CENDL-3.2
389/// has no MAT divergences from ENDF/B-VIII.0 for shared isotopes. The library-aware
390/// lookup ensures the correct MAT is used to construct retrieval URLs.
391pub 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
399/// All mass numbers with an evaluation for element Z in the given library.
400///
401/// Library-aware counterpart to [`endf_mat::known_isotopes`] (which is
402/// ENDF/B-VIII.0-only) — must be used wherever the GUI surfaces the set of
403/// selectable isotopes for the *currently selected* library, otherwise
404/// TENDL-2023-only isotopes (e.g. Fm-247) will be silently hidden, and Br
405/// will be incorrectly shown as available under CENDL-3.2.
406pub 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
414/// Whether the given library has an evaluation for `(Z, A)`.
415///
416/// Library-aware counterpart to [`endf_mat::has_endf_evaluation`] — must be
417/// used by GUI availability indicators that depend on the *currently
418/// selected* library.
419pub 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/// Errors from ENDF retrieval operations.
428#[derive(Debug, thiserror::Error)]
429pub enum EndfRetrievalError {
430    /// Transport-level failure (connection refused, DNS error, non-404 HTTP error, etc.).
431    #[error("Network error: {0}")]
432    NetworkError(String),
433
434    /// Upstream server actively blocked automated retrieval.
435    #[error("Remote access blocked: HTTP {status} for {url}. {message}")]
436    RemoteAccessBlocked {
437        status: u16,
438        url: String,
439        message: String,
440    },
441
442    /// The isotope exists in ENDF/B-VIII.0 but is not available in the requested library.
443    #[error("{isotope} is not available in the {library} library")]
444    NotInLibrary { isotope: String, library: String },
445
446    /// A user-supplied ENDF file did not describe the isotope it was being
447    /// installed against (manual upload path).
448    #[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    /// Whether this error means the upstream server is denying automated access.
463    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
532/// Extract the ENDF data file body from a ZIP archive.
533///
534/// Prefers archive entries ending in `.endf`, `.dat`, or `.txt`; falls back to
535/// the first entry if none match. IAEA distributes one ENDF per zip, so the
536/// fallback effectively only fires on hand-rolled archives.
537fn 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
575/// Detect a ZIP archive by extension or PK magic bytes.
576///
577/// IAEA-distributed `n_…_….zip` files always start with `PK\x03\x04`. The
578/// magic-byte check covers the case where a user has stripped or renamed the
579/// extension before uploading.
580fn 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
589/// Build the shared HTTP client used for ENDF downloads.
590///
591/// Connect timeout is short so DNS/TLS failures surface fast; total timeout
592/// is generous because some library zips are several hundred KB over slow
593/// links. ENDF zip files top out around ~1 MB.
594fn 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
662/// Render an error and its full `source()` chain on one line. reqwest's outer
663/// `Display` is uninformative ("error sending request for url ...") — the
664/// real cause (TLS, DNS, refused, timeout) lives in the source chain.
665fn 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    /// the polite User-Agent must carry the live package version
748    /// and the contact metadata the IAEA acceptance criterion calls for.
749    #[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    // Minimal valid ENDF MF=2/MT=151 fixture tagged W-184 (ZA=74184), kept
770    // inline so retrieval tests stay self-contained. These tests exercise
771    // install/zip/peek mechanics only, so the body is a synthetic evaluable
772    // MLBW (LRF=2) range — the real W-184 evaluation is LRF=7-only, which
773    // the parser now rejects as carrying no evaluable ranges, and a fixture
774    // that cannot parse would fail isotope extraction here.
775    // Layout: HEAD, isotope CONT (NER=1), range CONT (LRU=1/LRF=2),
776    // SPI/AP CONT (NLS=1), L CONT (L=0, NRS=1), one resonance LIST row
777    // [ER, AJ, GT, GN, GG, GF].
778    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        // Subsequent get_endf_file calls must read from cache (no network).
813        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    /// `default_cache_dir` / `default_cache_file_path` must agree with the
841    /// retriever's instance methods, otherwise UI hints would point users to
842    /// the wrong location after a fetch failure.
843    #[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        // Raw .endf path
879        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        // Zip path
886        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    /// Regression for the `looks_like_zip` magic-byte branch: an upload whose
894    /// path has no `.zip` extension must still be detected via `PK\x03\x04`
895    /// and routed through the zip extractor. Without this test, the magic-byte
896    /// branch could silently regress to extension-only detection.
897    #[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"); // no .zip suffix
901        write_zip_with_endf(&zip_path, "inner.endf", W184_FIXTURE).expect("write zip");
902
903        // Sanity-check we really did create a zip without the .zip extension.
904        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        // peek_local_endf must also handle the extensionless zip.
917        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}