Skip to main content

doiget_core/
source.rs

1//! Source abstraction. Each Tier 1/2/3 fetcher implements this trait.
2//!
3//! Binding spec: `docs/PUBLIC_API.md` §2 (trait surface),
4//! `docs/ARCHITECTURE.md` §6 (per-fetch data flow), and
5//! `docs/PROVENANCE_LOG.md` §3 (the `Fetch` row source impls emit).
6//!
7//! Phase 1 ships the trait + supporting types; concrete impls (Crossref,
8//! Unpaywall, arXiv) land in follow-up PRs (see `docs/SOURCES.md` for the
9//! source matrix and tiering).
10
11use std::sync::Arc;
12
13use async_trait::async_trait;
14use bytes::Bytes;
15use thiserror::Error;
16
17use crate::http::{HttpClient, HttpError};
18use crate::provenance::{LogError, ProvenanceLog};
19use crate::rate_limiter::RateLimiter;
20use crate::{CapabilityProfile, Ref, RefParseError};
21
22/// What a successful fetch returns to the caller.
23///
24/// Whether `pdf_bytes` is `None` depends on the source: metadata-only
25/// sources (Phase 4) leave it unset; OA sources (Phase 1) return PDF bytes
26/// when an OA URL was discovered.
27#[derive(Debug, Clone)]
28#[non_exhaustive]
29pub struct FetchResult {
30    /// Source's name (matches `Source::name()`); set for the audit trail.
31    pub source: String,
32    /// OA license string (`"CC-BY-4.0"`, `"unknown"`, etc.).
33    pub license: String,
34    /// PDF bytes; `None` for metadata-only sources.
35    pub pdf_bytes: Option<Bytes>,
36    /// Final URL after redirect resolution; useful for the metadata
37    /// `[doiget].url` field.
38    pub final_url: Option<url::Url>,
39    /// Source-side metadata payload as a serde_json value. The Source impl
40    /// is responsible for the shape; the caller (Phase 1+ orchestrator)
41    /// maps it into `Metadata` when one exists (Phase 1+).
42    pub metadata_json: Option<serde_json::Value>,
43}
44
45/// Per-fetch context shared by all `Source` impls.
46///
47/// Held by the orchestrator (CLI / MCP server) and passed by reference into
48/// each [`Source::fetch`]. Sources MUST NOT construct their own
49/// [`HttpClient`] / [`RateLimiter`] / [`ProvenanceLog`] — they go through
50/// this context for uniform politeness, redirect allowlisting, and audit
51/// logging.
52#[derive(Clone)]
53pub struct FetchContext {
54    /// Shared, allowlist-aware HTTP client. See [`HttpClient`].
55    pub http: Arc<HttpClient>,
56    /// Process-wide async rate limiter. See [`RateLimiter`].
57    pub rate_limiter: Arc<RateLimiter>,
58    /// Append-only, hash-chained provenance log. Source impls MUST emit
59    /// one `LogEvent::Fetch` row per attempt via `log.append`. See
60    /// [`ProvenanceLog`].
61    pub log: Arc<ProvenanceLog>,
62    /// 26-char ULID identifying this process invocation. Mirrors the
63    /// `session_id` stamped into every provenance row by the writer; held
64    /// here so source impls can include it in their own structured logs
65    /// without re-reading the env.
66    pub session_id: String,
67    /// Resolver cache root (`<cache_root>/resolver/<safekey>.toml`, see
68    /// `docs/CACHE.md` and [`crate::resolver_cache`]). `Some` enables the
69    /// metadata-only resolve cache (repeat resolves served from disk,
70    /// avoiding upstream rate limits); `None` disables it (tests, or a
71    /// caller that opts out). Only `metadata_only` consults it — per-PDF
72    /// fetches are never cached.
73    pub cache_root: Option<camino::Utf8PathBuf>,
74}
75
76impl std::fmt::Debug for FetchContext {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        // Avoid printing the full HTTP / rate-limiter / log internals; only
79        // the session_id is human-meaningful for log breadcrumbs.
80        f.debug_struct("FetchContext")
81            .field("session_id", &self.session_id)
82            .finish_non_exhaustive()
83    }
84}
85
86/// Errors returned by [`Source::fetch`].
87///
88/// At the public CLI / MCP boundary, every variant collapses to an
89/// [`crate::ErrorCode`] via the `From<FetchError>` impl below — mirroring
90/// the [`RefParseError`] → [`crate::ErrorCode::InvalidRef`] collapse from
91/// PR #55.
92#[derive(Debug, Error)]
93#[non_exhaustive]
94pub enum FetchError {
95    /// The source does not handle the given ref under the runtime
96    /// capability profile (covers both `can_serve = false` outcomes and
97    /// runtime denials raised inside `fetch`).
98    #[error("source {source_key} cannot serve this ref")]
99    NotEligible {
100        /// The source key that declined.
101        source_key: String,
102    },
103    /// Tier 1 sources reported no OA URL for this ref.
104    #[error("Tier 1 sources reported no OA URL for this ref")]
105    NoOaAvailable,
106    /// A metadata source authoritatively reported that the identifier does
107    /// not exist — distinct from a transport failure. Surfaces as
108    /// [`crate::ErrorCode::NotFound`]. Used for sources whose
109    /// "absent" signal is NOT an HTTP 404/410 (e.g. the arXiv Atom API
110    /// returns HTTP 200 with an empty `<feed>` for an unknown id).
111    #[error("identifier not found: {hint}")]
112    NotFound {
113        /// Human-readable detail (which source, and how it signalled
114        /// absence); not parsed.
115        hint: String,
116    },
117    /// A name filter (author / venue / publisher) matched MORE than one
118    /// OpenAlex entity with no clear winner. Carries a candidate listing
119    /// so the caller can narrow the name (or pass an explicit id).
120    /// Collapses to [`crate::ErrorCode::Ambiguous`] (wire `"AMBIGUOUS"`) —
121    /// distinct from `NotFound` so an agent narrows rather than gives up.
122    /// Used by [`crate::discovery`].
123    #[error("{hint}")]
124    Ambiguous {
125        /// Human-readable candidate listing; not parsed.
126        hint: String,
127    },
128    /// Underlying HTTP / network failure. See [`HttpError`].
129    #[error("network error: {0}")]
130    Http(#[from] HttpError),
131    /// Provenance log write failed. Per `docs/SECURITY.md` §1.8 this is a
132    /// fail-closed signal; the surrounding fetch MUST be aborted.
133    #[error("provenance log error: {0}")]
134    Log(#[from] LogError),
135    /// Ref re-parse / validation failed inside the source (e.g. when a
136    /// source receives a borrowed string from upstream and re-validates).
137    #[error("invalid ref: {0}")]
138    InvalidRef(#[from] RefParseError),
139    /// A source found the record and **cannot supply a copy** — an access
140    /// refusal, not a failure.
141    ///
142    /// The distinction is the whole point: "the source has it and cannot
143    /// give it to us" and "the source broke" lead an operator to different
144    /// conclusions, and only the second is a bug to chase.
145    ///
146    /// This exists as a variant because it used to be a *substring search*.
147    /// A refusal was [`Self::SourceSchema`] with an explanatory hint, and
148    /// `orchestrator::is_access_refusal` read the hint back looking for
149    /// "not open access" / "openAccess" / "no retrievable PDF". #503
150    /// reworded Europe PMC's refusal for good reasons, the hint fell out of
151    /// that list, and every Europe PMC refusal silently became
152    /// `AttemptOutcome::Failed`. Nothing in the source said the wording was
153    /// load-bearing, and `hal` matched on `openAccess` — a JSON *field
154    /// name*, not prose anyone chose (#538).
155    ///
156    /// Collapses to [`crate::ErrorCode::NoOaAvailable`], which is an
157    /// EXISTING wire code: "found it, no free copy" is exactly what that
158    /// means, so the closed set in `docs/ERRORS.md` §3 does not widen. See
159    /// ADR-0054.
160    #[error("{source_key} has the record but no retrievable copy: {detail}")]
161    NotRetrievable {
162        /// Which source refused.
163        source_key: String,
164        /// Why, in the source's own terms — the flags or codes a reader
165        /// checks next. Displayed, never parsed: that is the point.
166        detail: String,
167    },
168    /// Source-side schema mismatch (unexpected JSON shape, missing
169    /// required field). Surfaces to [`crate::ErrorCode::InternalError`]
170    /// at the public boundary.
171    #[error("source-side schema error: {hint}")]
172    SourceSchema {
173        /// Human-readable hint at the offending field/path; not parsed.
174        hint: String,
175    },
176    /// Batch orchestrator received more refs than
177    /// [`crate::MAX_BATCH_REFS`]. Surfaced to the MCP `doiget_batch_fetch`
178    /// tool as `ErrorCode::InvalidRef` (closest closed-set fit — the
179    /// request shape itself is invalid; no `denial_context` channel
180    /// applies). Slice 2 / `docs/MCP_TOOLS.md` §1.
181    #[error("too many refs: got {got}, max {max}")]
182    TooManyRefs {
183        /// Number of refs the batch orchestrator was handed.
184        got: usize,
185        /// The hard cap ([`crate::MAX_BATCH_REFS`]).
186        max: usize,
187    },
188    /// A source returned a successful response that contained no usable
189    /// representation of the requested kind — currently `doiget text`'s
190    /// ar5iv leg returning a 200 with no extractable prose (the paper was
191    /// never converted to HTML). The identifier is valid; only this one
192    /// representation is missing. Surfaces as
193    /// [`crate::ErrorCode::TextUnavailable`] so an agent fetches the PDF
194    /// instead of concluding the reference is wrong (issue #302) — NOT
195    /// [`Self::NotFound`], which means the id itself does not exist.
196    #[error(
197        "no readable text for arXiv:{arxiv_id} (no ar5iv HTML render); \
198         the PDF may be fetchable instead"
199    )]
200    TextUnavailable {
201        /// The arXiv id whose ar5iv render was empty; echoed into the
202        /// human/MCP message so the actionable `doiget fetch <id>` hint is
203        /// self-contained. A validated [`crate::ArxivId`] (review #318) —
204        /// the id was already parsed, so the error cannot carry a malformed
205        /// string into the actionable `doiget fetch <id>` hint.
206        arxiv_id: crate::ArxivId,
207    },
208    /// A source returned a successful response that contained no file of the
209    /// requested kind for `doiget source` — a PDF-only / single-file
210    /// submission (no multi-file bundle), or `--figures-only` on a submission
211    /// with no image files. The identifier is valid; only the bundle / figure
212    /// representation is absent. Surfaces as
213    /// [`crate::ErrorCode::TextUnavailable`] (same "this representation is
214    /// missing; the PDF may be fetchable" class as [`Self::TextUnavailable`]),
215    /// but as a DISTINCT variant so the message is not ar5iv-specific
216    /// (issue #343 / ADR-0034; PR review).
217    #[error("no source files for arXiv:{arxiv_id} ({kind}); the PDF may be fetchable instead")]
218    SourceUnavailable {
219        /// The arXiv id whose source bundle / figures were absent.
220        arxiv_id: crate::ArxivId,
221        /// Which representation was requested: `"source bundle"` or `"figures"`.
222        kind: &'static str,
223    },
224}
225
226/// Map [`FetchError`] to the closed [`crate::ErrorCode`] set surfaced at
227/// the public CLI / MCP boundary. Mirrors the
228/// `From<RefParseError> for ErrorCode` collapse from PR #55.
229impl From<FetchError> for crate::ErrorCode {
230    fn from(e: FetchError) -> crate::ErrorCode {
231        crate::ErrorCode::from(&e)
232    }
233}
234
235/// Borrow-form of the collapse above, so a caller that still needs the
236/// error for its `Display` message / `denial_context` side-channel
237/// (notably the CLI human-persona renderer, issue #119) can obtain the
238/// closed code without consuming it. The owned impl delegates here so
239/// the mapping table lives in exactly one place.
240impl From<&FetchError> for crate::ErrorCode {
241    fn from(e: &FetchError) -> crate::ErrorCode {
242        match e {
243            FetchError::NotEligible { .. } => crate::ErrorCode::CapabilityDenied,
244            FetchError::NoOaAvailable => crate::ErrorCode::NoOaAvailable,
245            FetchError::NotFound { .. } => crate::ErrorCode::NotFound,
246            // A name filter that matched several entities is its own wire
247            // code so agents can distinguish "narrow the name" from
248            // "does not exist" (ADR-0031 D5).
249            FetchError::Ambiguous { .. } => crate::ErrorCode::Ambiguous,
250            // 404 / 410 / 451 are authoritative "this id does not exist"
251            // signals → `NotFound` (not retriable). 401 / 403 mean the
252            // server understood the request but denied access (IP block, auth
253            // required) — `CapabilityDenied` lets agents distinguish access
254            // denial from a transient connectivity failure. Everything else
255            // is treated as transient.
256            FetchError::Http(HttpError::HttpStatus {
257                status: 404 | 410 | 451,
258                ..
259            }) => crate::ErrorCode::NotFound,
260            FetchError::Http(HttpError::HttpStatus {
261                status: 401 | 403, ..
262            }) => crate::ErrorCode::CapabilityDenied,
263            // Exhaustive over `HttpError`, not `Http(_)`. The wildcard sent
264            // six deterministic outcomes to `NETWORK_ERROR`, whose disposition
265            // is `retry_after` -- so an agent was told to back off and retry an
266            // allowlist refusal, an http:// downgrade, a size cap, a
267            // wrong content type, an unregistered source key and a malformed
268            // header, none of which a retry can change. That is the defect
269            // ADR-0055 exists to remove, in the mapping every surface routes
270            // through. The `DenialContext` impl 100 lines down already matches
271            // all eight variants; this one opted out of the same protection.
272            FetchError::Http(e) => match e {
273                // Policy decisions. Settled until the configuration changes,
274                // which is what `needs_config` means -- and each of these
275                // carries a `DenialContext` naming the fix.
276                HttpError::RedirectDenied { .. } | HttpError::InsecureRedirect { .. } => {
277                    crate::ErrorCode::CapabilityDenied
278                }
279                // The response arrived and was not what was asked for.
280                // Re-requesting returns the same bytes.
281                HttpError::OversizedBody { .. } | HttpError::NotAPdf { .. } => {
282                    crate::ErrorCode::NoOaAvailable
283                }
284                // The caller asked for a source the client was never given.
285                // A build/wiring fault, not the network (#454, #462).
286                HttpError::UnknownSource { .. } | HttpError::InvalidHeader { .. } => {
287                    crate::ErrorCode::InternalError
288                }
289                // Genuinely transient: transport failures, and the statuses
290                // the arms above did not claim.
291                HttpError::Network(_) | HttpError::HttpStatus { .. } => {
292                    crate::ErrorCode::NetworkError
293                }
294            },
295            FetchError::Log(_) => crate::ErrorCode::LogError,
296            FetchError::InvalidRef(_) => crate::ErrorCode::InvalidRef,
297            // An access refusal is not an internal error. Before #538 it
298            // was reported as one, because it travelled as `SourceSchema`.
299            FetchError::NotRetrievable { .. } => crate::ErrorCode::NoOaAvailable,
300            FetchError::SourceSchema { .. } => crate::ErrorCode::InternalError,
301            // Slice 2: a too-large batch is a request-shape failure, so
302            // collapse to `INVALID_REF` (closest closed-set fit). The
303            // `#[non_exhaustive]` wildcard below would otherwise route
304            // it to `INTERNAL_ERROR`, which would mislead agents.
305            FetchError::TooManyRefs { .. } => crate::ErrorCode::InvalidRef,
306            // The id resolved; only the ar5iv text representation is
307            // missing. Its own code so an agent fetches the PDF rather
308            // than conclude the reference is wrong (issue #302).
309            FetchError::TextUnavailable { .. } => crate::ErrorCode::TextUnavailable,
310            // The id resolved; only the source-bundle / figure representation
311            // is absent. Same wire code as TextUnavailable (representation
312            // missing → fetch the PDF), distinct variant for a correct message.
313            FetchError::SourceUnavailable { .. } => crate::ErrorCode::TextUnavailable,
314        }
315    }
316}
317
318/// Map a [`FetchError`] reference to the structured [`crate::DenialContext`]
319/// channel introduced by ADR-0023 §4.
320///
321/// `&FetchError` (rather than `FetchError`) so the orchestrator can
322/// produce the structured side-channel without consuming the error it
323/// still needs for `error.message` and the `From<FetchError> for
324/// ErrorCode` collapse above. The `Http` arm delegates to the
325/// `From<&HttpError> for Option<DenialContext>` impl in [`crate::http`].
326/// The server's own `Retry-After` for this failure, in milliseconds (#506).
327///
328/// `None` when the server sent no header, which is most failures. Deliberately
329/// NOT backfilled from doiget's internal backoff: that is a guess about the
330/// server, and a guess wearing the name of a server-supplied value is exactly
331/// the defect `error.disposition` and this field exist to remove.
332///
333/// Pairs with [`crate::Disposition::RetryAfter`] -- the disposition says
334/// "retry", and this says how long the server asked you to wait before you do.
335#[must_use]
336pub fn retry_after_ms(e: &FetchError) -> Option<u64> {
337    match e {
338        FetchError::Http(HttpError::HttpStatus { retry_after_ms, .. }) => *retry_after_ms,
339        _ => None,
340    }
341}
342
343impl From<&FetchError> for Option<crate::DenialContext> {
344    fn from(e: &FetchError) -> Self {
345        use crate::{DenialContext, DenialReason};
346        match e {
347            FetchError::NotEligible { source_key } => Some(DenialContext {
348                reason: DenialReason::CapabilityNotGranted,
349                source: Some(source_key.clone()),
350                attempted: None,
351                // CapabilityNotGranted has no allowlist channel: the
352                // producer leaves `expected` at `None` (NOT `Some(vec![])`).
353                // See `DenialContext::expected` for the disambiguation.
354                expected: None,
355                hop_index: None,
356                cap: None,
357                actual: None,
358            }),
359            // Delegate to the HttpError mapping (ADR-0023 §4 mapping table).
360            FetchError::Http(http_err) => http_err.into(),
361            // Non-denial variants map to None per ADR-0023 §4. (Slice 2:
362            // `TooManyRefs` is a request-shape failure, not a denial —
363            // adding it to the None arm keeps the mapping table consistent.)
364            FetchError::NoOaAvailable
365            // #538: a source refusing because the work is not open there is
366            // NOT a denial in the ADR-0023 sense. Nothing was withheld by
367            // policy, so there is no capability to grant and no allowlist to
368            // widen -- a `DenialContext` would send a reader after a
369            // configuration change that does not exist.
370            | FetchError::NotRetrievable { .. }
371            | FetchError::NotFound { .. }
372            | FetchError::Ambiguous { .. }
373            | FetchError::Log(_)
374            | FetchError::InvalidRef(_)
375            | FetchError::SourceSchema { .. }
376            | FetchError::TooManyRefs { .. }
377            | FetchError::TextUnavailable { .. }
378            | FetchError::SourceUnavailable { .. } => None,
379        }
380    }
381}
382
383/// The trait implemented by every Tier 1 / 2 / 3 fetcher.
384///
385/// Binding signature: `docs/PUBLIC_API.md` §2 (NORMATIVE — the wire shape
386/// of these three methods is semver-locked).
387#[async_trait]
388pub trait Source: Send + Sync {
389    /// Stable name used in metadata (`[doiget].source`) and provenance
390    /// rows. Conventional values: `"crossref"`, `"unpaywall"`, `"arxiv"`,
391    /// `"openalex"`, `"semantic-scholar"`, `"doaj"`, `"tdm-elsevier"`,
392    /// etc. (see `docs/SOURCES.md`).
393    fn name(&self) -> &str;
394
395    /// True if this source can plausibly serve the given ref under the
396    /// runtime capability profile. Implementations MUST be fast and
397    /// non-blocking; the orchestrator calls `can_serve` to decide whether
398    /// to invoke `fetch` at all.
399    fn can_serve(&self, profile: &CapabilityProfile, ref_: &Ref) -> bool;
400
401    /// Perform the source-specific fetch.
402    ///
403    /// Implementations:
404    ///   1. acquire `ctx.rate_limiter.acquire(self.name()).await`,
405    ///   2. fetch via `ctx.http.fetch_bytes` / `ctx.http.fetch_pdf`,
406    ///   3. emit one `LogEvent::Fetch` row via `ctx.log.append`,
407    ///   4. return a [`FetchResult`].
408    ///
409    /// The trait does NOT enforce these steps; it documents the protocol
410    /// so concrete impls produce uniform audit trails (per
411    /// `docs/ARCHITECTURE.md` §6 and `docs/PROVENANCE_LOG.md` §3).
412    async fn fetch(
413        &self,
414        ref_: &Ref,
415        profile: &CapabilityProfile,
416        ctx: &FetchContext,
417    ) -> Result<FetchResult, FetchError>;
418
419    /// Fetch the publisher's own copy of the document itself, when this
420    /// source holds one.
421    ///
422    /// Distinct from [`Self::fetch`], which resolves a *record*. A Tier-3
423    /// TDM source is consulted for two different reasons at two different
424    /// points in the fetch, and conflating them is what #458 was:
425    ///
426    /// - [`fetch`](Self::fetch) answers "who can tell me about this DOI?"
427    ///   and runs when Crossref could not;
428    /// - `fetch_content` answers "who will give me the bytes?" and runs
429    ///   when the content leg was blocked — which is usually *after*
430    ///   Crossref answered perfectly well.
431    ///
432    /// The default is `Ok(None)`: "this source is metadata-only". Stating
433    /// it is the point. Before #458 the same fact was expressed by every
434    /// Tier-3 impl setting `FetchResult.pdf_bytes` to `None` and saying so
435    /// in a doc-comment, which the orchestrator could neither read nor act
436    /// on — so it could not tell a source that had nothing to offer from
437    /// one it had simply never asked.
438    ///
439    /// Implementations that override it MUST use a PDF-validating fetch
440    /// ([`HttpClient::fetch_pdf`] or
441    /// [`HttpClient::fetch_pdf_with_headers`]). A publisher error page or
442    /// a WAF holding response is a 200 with a body, and storing one under
443    /// `<safekey>.pdf` would be worse than returning nothing.
444    ///
445    /// # Errors
446    ///
447    /// Any [`FetchError`]. `Ok(None)` means "not me"; `Err` means "me, and
448    /// it went wrong". The orchestrator keeps the original content-leg
449    /// block either way, but records the two as different attempt
450    /// outcomes.
451    async fn fetch_content(
452        &self,
453        _ref_: &Ref,
454        _profile: &CapabilityProfile,
455        _ctx: &FetchContext,
456    ) -> Result<Option<Bytes>, FetchError> {
457        Ok(None)
458    }
459}
460
461// ---------------------------------------------------------------------------
462// Tests
463// ---------------------------------------------------------------------------
464
465#[cfg(test)]
466#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
467mod tests {
468    use super::*;
469
470    use camino::Utf8PathBuf;
471    use tempfile::TempDir;
472
473    use crate::http::{tier_1_allowlist, HttpClient};
474    use crate::provenance::ProvenanceLog;
475    use crate::rate_limiter::RateLimiter;
476    use crate::{CapabilityProfile, Doi, ErrorCode, RateLimits, Ref};
477
478    /// Minimal `Source` impl exercised purely to pin the trait shape and
479    /// verify dispatch through `Box<dyn Source>`. Concrete sources land in
480    /// follow-up PRs (Crossref / Unpaywall / arXiv).
481    struct MockSource;
482
483    #[async_trait]
484    impl Source for MockSource {
485        fn name(&self) -> &str {
486            "mock"
487        }
488        fn can_serve(&self, _: &CapabilityProfile, _: &Ref) -> bool {
489            true
490        }
491        async fn fetch(
492            &self,
493            _: &Ref,
494            _: &CapabilityProfile,
495            _: &FetchContext,
496        ) -> Result<FetchResult, FetchError> {
497            Ok(FetchResult {
498                source: "mock".into(),
499                license: "unknown".into(),
500                pdf_bytes: None,
501                final_url: None,
502                metadata_json: None,
503            })
504        }
505    }
506
507    /// Build a `FetchContext` backed by real (but inert) Round-A
508    /// foundation modules: a `HttpClient` over the Tier-1 allowlist, a
509    /// `RateLimiter` at hard-coded politeness, and a `ProvenanceLog` in
510    /// a tempdir. Returns the dir as well so the caller keeps it alive
511    /// for the duration of the test.
512    fn build_test_context() -> (TempDir, FetchContext) {
513        let td = TempDir::new().expect("tempdir");
514        // Workspace lints ban `std::path::PathBuf` for log paths; convert
515        // via camino's `Utf8PathBuf::try_from`.
516        let log_dir =
517            Utf8PathBuf::try_from(td.path().to_path_buf()).expect("temp dir path must be UTF-8");
518        let log_path = log_dir.join("test.jsonl");
519
520        let http = Arc::new(HttpClient::new(tier_1_allowlist()).expect("http client builds"));
521        let rate_limiter = Arc::new(RateLimiter::new(RateLimits::HARD_CODED));
522        let session_id = "01J0000000000000000000TEST".to_string();
523        let log = Arc::new(
524            ProvenanceLog::open(log_path, session_id.clone()).expect("provenance log opens"),
525        );
526
527        (
528            td,
529            FetchContext {
530                http,
531                rate_limiter,
532                log,
533                session_id,
534                cache_root: None,
535            },
536        )
537    }
538
539    #[tokio::test]
540    async fn mock_source_compiles_as_trait_object() {
541        // Trait-shape pin: a `Source` impl is dyn-safe and can be boxed.
542        let s: Box<dyn Source> = Box::new(MockSource);
543        assert_eq!(s.name(), "mock");
544        let profile = CapabilityProfile::for_tests();
545        let r = Ref::Doi(Doi("10.1234/example".to_string()));
546        assert!(s.can_serve(&profile, &r));
547
548        let (_td, ctx) = build_test_context();
549        let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
550        assert_eq!(res.source, "mock");
551    }
552
553    #[tokio::test]
554    async fn mock_source_fetch_returns_result() {
555        // Direct dispatch (not through `dyn`) to exercise the async fn
556        // body and assert the populated FetchResult fields.
557        let s = MockSource;
558        let profile = CapabilityProfile::for_tests();
559        let r = Ref::Doi(Doi("10.1234/example".to_string()));
560        let (_td, ctx) = build_test_context();
561
562        let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
563        assert_eq!(res.source, "mock");
564        assert_eq!(res.license, "unknown");
565        assert!(res.pdf_bytes.is_none());
566        assert!(res.final_url.is_none());
567        assert!(res.metadata_json.is_none());
568    }
569
570    /// A deterministic HTTP outcome must not be advertised as retriable.
571    ///
572    /// `FetchError::Http(_) => NetworkError` was a wildcard over all eight
573    /// `HttpError` variants, and `NetworkError`'s disposition is
574    /// `retry_after`. Six of them cannot change on a retry, so the mapping
575    /// every surface routes through was telling agents to back off and try
576    /// again on an allowlist refusal, a size cap and an unregistered source
577    /// key -- the exact advice ADR-0055 exists to stop giving.
578    #[test]
579    fn a_deterministic_http_failure_is_not_advertised_as_retriable() {
580        let cases: Vec<(HttpError, crate::Disposition)> = vec![
581            (
582                HttpError::RedirectDenied {
583                    source_key: "oa-publisher".into(),
584                    host: "evil.example.com".into(),
585                    expected_hosts: vec!["*.wiley.com".to_string()],
586                },
587                crate::Disposition::NeedsConfig,
588            ),
589            (
590                HttpError::UnknownSource {
591                    source_key: "tdm-aps".into(),
592                },
593                crate::Disposition::Terminal,
594            ),
595        ];
596        for (he, want) in cases {
597            let code: ErrorCode = FetchError::Http(he).into();
598            assert_ne!(
599                code,
600                ErrorCode::NetworkError,
601                "a policy/wiring outcome is not a network error: {code:?}"
602            );
603            assert_eq!(
604                code.disposition(),
605                want,
606                "and its disposition must not say retry_after: {code:?}"
607            );
608        }
609    }
610
611    /// The transient ones keep saying retry, so the fix did not overshoot.
612    #[test]
613    fn a_transient_http_failure_still_says_retry() {
614        let code: ErrorCode = FetchError::Http(HttpError::HttpStatus {
615            status: 503,
616            retry_after_ms: None,
617            url: "https://api.crossref.org/works/10.5555/x".into(),
618        })
619        .into();
620        assert_eq!(code, ErrorCode::NetworkError);
621        assert_eq!(code.disposition(), crate::Disposition::RetryAfter);
622    }
623
624    #[test]
625    fn fetch_error_collapses_to_error_code() {
626        // Mirrors `docs/PUBLIC_API.md` §4 / PR #55 boundary collapse.
627        // Each variant must map to its documented code.
628        let e: ErrorCode = FetchError::NotEligible {
629            source_key: "mock".into(),
630        }
631        .into();
632        assert_eq!(e, ErrorCode::CapabilityDenied);
633
634        let e: ErrorCode = FetchError::NoOaAvailable.into();
635        assert_eq!(e, ErrorCode::NoOaAvailable);
636
637        // `UnknownSource` is "the caller asked HttpClient to fetch for a
638        // source it was never given" -- a wiring fault. This asserted
639        // `NetworkError` because the mapping used to be `Http(_) =>
640        // NetworkError`, i.e. it pinned the wildcard rather than a decision:
641        // retrying cannot register a missing source, and `NetworkError`'s
642        // `retry_after` disposition told an agent to try anyway. It is the
643        // error #462's TDM reproduction actually hit, and calling it a network
644        // problem is part of why it read as one.
645        let e: ErrorCode = FetchError::Http(HttpError::UnknownSource {
646            source_key: "mock".into(),
647        })
648        .into();
649        assert_eq!(e, ErrorCode::InternalError);
650        assert_eq!(e.disposition(), crate::Disposition::Terminal);
651
652        // 404 / 410 / 451 from a metadata source are authoritative "id does
653        // not exist" → NotFound (network-independent), NOT NetworkError.
654        for status in [404u16, 410, 451] {
655            let e: ErrorCode = FetchError::Http(HttpError::HttpStatus {
656                status,
657                retry_after_ms: None,
658                url: "https://api.crossref.org/works/10.5555/absent".into(),
659            })
660            .into();
661            assert_eq!(
662                e,
663                ErrorCode::NotFound,
664                "status {status} should map to NotFound"
665            );
666        }
667        // ...and a `Retry-After` on that response does not change it. #506
668        // added `retry_after_ms` to this variant, and the arm above briefly
669        // matched `retry_after_ms: None`, which silently sent a 404 carrying
670        // the header to `NETWORK_ERROR` -- disposition `retry_after` -- so an
671        // agent was told to retry a DOI that will never resolve. The header
672        // says how long to wait IF you retry; it does not make an
673        // authoritative absence provisional.
674        for status in [404u16, 410, 451] {
675            let e: ErrorCode = FetchError::Http(HttpError::HttpStatus {
676                status,
677                retry_after_ms: Some(30_000),
678                url: "https://api.crossref.org/works/10.5555/absent".into(),
679            })
680            .into();
681            assert_eq!(
682                e,
683                ErrorCode::NotFound,
684                "status {status} with Retry-After is still NotFound"
685            );
686            assert_eq!(
687                e.disposition(),
688                crate::Disposition::Terminal,
689                "and stays terminal, so nothing tells the agent to retry it"
690            );
691        }
692        // A non-HTTP authoritative absence (e.g. arXiv's empty Atom feed)
693        // also maps to NotFound.
694        let e: ErrorCode = FetchError::NotFound {
695            hint: "arxiv empty feed".into(),
696        }
697        .into();
698        assert_eq!(e, ErrorCode::NotFound);
699        // A transient upstream status (e.g. 503) stays NetworkError so
700        // `doiget verify` tolerates it rather than failing a live id.
701        let e: ErrorCode = FetchError::Http(HttpError::HttpStatus {
702            status: 503,
703            retry_after_ms: None,
704            url: "https://api.crossref.org/works/10.5555/down".into(),
705        })
706        .into();
707        assert_eq!(e, ErrorCode::NetworkError);
708
709        let e: ErrorCode = FetchError::Log(LogError::Io(std::io::Error::other("synthetic"))).into();
710        assert_eq!(e, ErrorCode::LogError);
711
712        let e: ErrorCode = FetchError::InvalidRef(RefParseError::Empty).into();
713        assert_eq!(e, ErrorCode::InvalidRef);
714
715        let e: ErrorCode = FetchError::SourceSchema {
716            hint: "missing field 'license'".into(),
717        }
718        .into();
719        assert_eq!(e, ErrorCode::InternalError);
720
721        // Slice 2 — TooManyRefs collapses to INVALID_REF, NOT
722        // InternalError (the `#[non_exhaustive]` wildcard would
723        // otherwise misroute this to InternalError).
724        let e: ErrorCode = FetchError::TooManyRefs { got: 101, max: 100 }.into();
725        assert_eq!(e, ErrorCode::InvalidRef);
726
727        // #343 / ADR-0034 — SourceUnavailable shares the TextUnavailable wire
728        // code (representation missing; the PDF may be fetchable), distinct
729        // variant for a non-ar5iv message.
730        let arxiv = match Ref::parse("arxiv:2401.12345").expect("parse arxiv id") {
731            Ref::Arxiv(a) => a,
732            Ref::Doi(_) => unreachable!("parsed an arxiv id"),
733        };
734        let e: ErrorCode = FetchError::SourceUnavailable {
735            arxiv_id: arxiv,
736            kind: "figures",
737        }
738        .into();
739        assert_eq!(e, ErrorCode::TextUnavailable);
740    }
741
742    #[test]
743    fn fetch_context_debug_redacts_internals() {
744        // Pin the Debug shape — only `session_id` is printed, the rest is
745        // elided. Prevents accidental log leakage when a context is
746        // included in a `tracing::debug!` event.
747        let (_td, ctx) = build_test_context();
748        let s = format!("{:?}", ctx);
749        assert!(
750            s.contains("session_id"),
751            "session_id must be in Debug: {}",
752            s
753        );
754        assert!(s.contains("01J0000000000000000000TEST"));
755        assert!(
756            !s.contains("HttpClient") && !s.contains("RateLimiter") && !s.contains("ProvenanceLog"),
757            "FetchContext Debug must not dump foundation internals: {}",
758            s,
759        );
760    }
761
762    // ---------------------------------------------------------------
763    // FetchError -> Option<DenialContext>  (ADR-0023 §4)
764    // ---------------------------------------------------------------
765
766    #[test]
767    fn denial_from_not_eligible_carries_source_key() {
768        use crate::{DenialContext, DenialReason};
769        let e = FetchError::NotEligible {
770            source_key: "tdm-elsevier".to_string(),
771        };
772        let dc: Option<DenialContext> = (&e).into();
773        let dc = dc.expect("NotEligible -> Some(DenialContext)");
774        assert_eq!(dc.reason, DenialReason::CapabilityNotGranted);
775        assert_eq!(dc.source.as_deref(), Some("tdm-elsevier"));
776        assert!(dc.attempted.is_none());
777        // Post-refinement: `expected: None` ("producer did not populate")
778        // rather than `Some(vec![])` ("explicit empty allowlist"). See
779        // `DenialContext::expected` field doc for the disambiguation.
780        assert!(dc.expected.is_none());
781    }
782
783    #[test]
784    fn denial_from_http_delegates_to_http_mapping() {
785        use crate::http::HttpError;
786        use crate::{DenialContext, DenialReason, PDF_MAX_BYTES};
787        // The Http arm must delegate to the HttpError mapping rather than
788        // reinventing it, so an OversizedBody surfaces with cap/actual
789        // populated and the SizeCapExceeded reason — proving delegation
790        // works without per-variant duplication.
791        let e = FetchError::Http(HttpError::OversizedBody {
792            actual: 209_715_200,
793            cap: PDF_MAX_BYTES,
794        });
795        let dc: Option<DenialContext> = (&e).into();
796        let dc = dc.expect("Http(OversizedBody) -> Some(DenialContext)");
797        assert_eq!(dc.reason, DenialReason::SizeCapExceeded);
798        assert_eq!(dc.cap, Some(PDF_MAX_BYTES));
799        assert_eq!(dc.actual, Some(209_715_200));
800    }
801
802    #[test]
803    fn denial_from_non_denial_variants_returns_none() {
804        use crate::DenialContext;
805        // Each of the four non-denial FetchError arms maps to None per
806        // ADR-0023 §4.
807        let e = FetchError::NoOaAvailable;
808        let dc: Option<DenialContext> = (&e).into();
809        assert!(dc.is_none(), "NoOaAvailable must not produce DenialContext");
810
811        let e = FetchError::Log(LogError::Io(std::io::Error::other("synthetic")));
812        let dc: Option<DenialContext> = (&e).into();
813        assert!(dc.is_none(), "Log must not produce DenialContext");
814
815        let e = FetchError::InvalidRef(RefParseError::Empty);
816        let dc: Option<DenialContext> = (&e).into();
817        assert!(dc.is_none(), "InvalidRef must not produce DenialContext");
818
819        let e = FetchError::SourceSchema {
820            hint: "missing field 'license'".into(),
821        };
822        let dc: Option<DenialContext> = (&e).into();
823        assert!(dc.is_none(), "SourceSchema must not produce DenialContext");
824    }
825}