Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

37.1 KB
Raw Blame
"""
Base Academic Content Downloader Abstract Class
"""

from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, NamedTuple, Optional
from enum import Enum
import time
import requests
from urllib.parse import urlparse
from loguru import logger

# Import our adaptive rate limiting system
from ...web_search_engines.rate_limiting import (
    AdaptiveRateLimitTracker,
)
from ...security import SafeSession, safe_requests
from ...security.egress.policy import PolicyDeniedError
from ...utilities.pdf_extraction_limits import (
    MAX_PDF_EXTRACTED_CHARS,
    MAX_PDF_EXTRACTION_CPU_SECONDS,
    MAX_PDF_EXTRACTION_PAGES,
)
from ...utilities.pdf_stream_release import PypdfWalkReleaser
from ...security.log_sanitizer import scrub_error
from ...security.ssrf_validator import (
    authority_may_be_userinfo,
    redact_url_for_log,
)
from ...utilities.resource_utils import safe_close

# Import centralized User-Agent from constants
from ...constants import USER_AGENT  # noqa: F401 - re-exported for backward compatibility


def rate_limit_authority(url: str) -> str:
    """Return *url*'s authority (``host`` or ``host:port``) for rate-limit keys.

    RFC 3986 userinfo, path, query and fragment are dropped and an IPv6
    literal keeps its brackets. A URL with no authority at all yields
    ``""``; one whose authority will not parse (an invalid port, an
    unterminated ``[``) or whose host carries whitespace or a control
    character yields ``"invalid_authority"``.

    All four downloader fetch paths derive their per-host adaptive
    rate-limit bucket through this one helper, so the keys cannot drift
    apart. It parses the *original* URL rather than re-parsing
    ``redact_url_for_log(url)``: that helper is a display formatter, and its
    rendering of an input it cannot parse has no authority left to recover
    -- ``"  https://slow-host.example/paper"`` renders as ``"?://  https"``,
    while ``requests`` lstrips that same leading whitespace and fetches the
    URL anyway. Re-parsing the rendering therefore dropped every
    whitespace-prefixed host into one shared bucket, where a single
    429-heavy host raises the wait for all the others.

    ``AdaptiveRateLimitTracker`` renders the key into its own log messages,
    so the value must stay one printable token. A host carrying whitespace
    or a control character is not a legal RFC 3986 reg-name, and is not the
    host contacted either -- ``requests`` percent-encodes it, preparing
    ``"https://exa mple.com/p"`` as ``https://exa%20mple.com/p`` -- so it
    buckets as ``"invalid_authority"`` rather than being echoed into a log
    line.

    An authority that may really be a userinfo prefix
    (``https://tok/en@host/`` parses to the host ``tok``,
    ``https://admin:[email protected]#1@host/`` to ``ss.example``; see
    ``authority_may_be_userinfo``) also yields ``"invalid_authority"``, so
    the tracker never logs a fragment of a credential as a key.
    """
    try:
        parsed = urlparse(url)
        hostname = parsed.hostname or ""
        host = f"[{hostname}]" if ":" in hostname else hostname
        authority = host
        if parsed.port is not None:
            authority = f"{authority}:{parsed.port}"
        # ``authority``, not ``host``: ``https://u:@:1#x@host/`` parses to
        # an empty host and the port ``1``, a fragment of the password.
        if authority and authority_may_be_userinfo(
            host,
            parsed.port is not None,
            url,
            has_userinfo="@" in parsed.netloc,
        ):
            return "invalid_authority"
    except ValueError:
        return "invalid_authority"
    if any(ch.isspace() or not ch.isprintable() for ch in authority):
        return "invalid_authority"
    return authority


class ContentType(Enum):
    """Supported content types for download."""

    PDF = "pdf"
    TEXT = "text"


class DownloadResult(NamedTuple):
    """Result of a download attempt."""

    content: Optional[bytes] = None
    skip_reason: Optional[str] = None
    is_success: bool = False
    status_code: Optional[int] = None
    # Abstract/metadata fallbacks are useful display text, but cannot
    # satisfy a later request for the complete source from a shared cache.
    content_is_complete: bool = True
    pdf_content: Optional[bytes] = None


class _ResponseBodyTooLarge(Exception):
    """A response body exceeded the size cap while being decoded.

    Internal to this module: it separates the body-cap abort (raised by
    ``safe_requests._install_body_guard``'s bounded reader during
    ``response.content``/``response.text`` access) from the
    ``ValueError``s ``SafeSession`` raises for SSRF validation, so the
    retry loop below can label it precisely instead of mislabeling an
    SSRF rejection as a size problem (or vice versa).
    """


# HTTP statuses that answer "no such document" rather than signalling a
# failing host: a fetch ending on one of these is not reported through the
# ``on_transport_failure`` callbacks of ``_download_pdf`` and
# ``HTMLDownloader._fetch_html_with_final_url``.
_DOCUMENT_ABSENT_STATUSES: frozenset[int] = frozenset({404, 410})


class BaseDownloader(ABC):
    """Abstract base class for academic content downloaders."""

    def __init__(
        self,
        timeout: int = 30,
        username: Optional[str] = None,
        password: Optional[str] = None,
        settings_snapshot: Optional[Dict[str, Any]] = None,
        enable_fetch_persistence: bool = True,
        **kwargs,
    ):
        """
        Initialize the downloader.

        Args:
            timeout: Request timeout in seconds
            username: Optional username for identity propagation
            password: Optional database password
            settings_snapshot: Optional settings dictionary
            enable_fetch_persistence: When True, research-fetch paths may
                persist PDFs on-the-spot. DownloadService constructs its
                downloaders with False because it saves synchronously —
                otherwise each sweep download would persist twice.
        """
        if kwargs:
            # ``language`` is forwarded by several subclasses and consumed
            # by them, not here. Anything else is a caller typo: warn
            # instead of silently dropping it.
            unknown = sorted(set(kwargs) - {"language"})
            if unknown:
                logger.warning(
                    f"BaseDownloader ignoring unknown arguments: {unknown}"
                )
        self.timeout = timeout
        self.username = username
        self.password = password
        self.settings_snapshot = settings_snapshot
        self.enable_fetch_persistence = enable_fetch_persistence
        # Last redirect final URL and raw PDF bytes seen by _download_pdf, exposed
        # so the single fetch-time writer (ContentFetcher) can track and persist them.
        self._last_final_url: Optional[str] = None
        self._last_pdf_content: Optional[bytes] = None
        if not self.username or not self.password:
            try:
                from ...utilities.thread_context import resolve_fetch_identity

                (
                    self.username,
                    self.password,
                    self.settings_snapshot,
                ) = resolve_fetch_identity(
                    username=self.username,
                    password=self.password,
                    settings_snapshot=self.settings_snapshot,
                )
            except Exception:  # allow: silent-exception
                pass

        self.session = SafeSession(block_https_downgrade=True)
        self.session.headers.update({"User-Agent": USER_AGENT})

        # Initialize rate limiter for PDF downloads
        # We'll use domain-specific rate limiting
        self.rate_tracker = AdaptiveRateLimitTracker(
            programmatic_mode=False  # We want to persist rate limit data
        )

    def close(self):
        """
        Close the HTTP session and clean up resources.

        Call this method when done using the downloader to prevent
        connection/file descriptor leaks.
        """
        if hasattr(self, "session") and self.session:
            try:
                self.session.close()
            except Exception as exc:
                # Keep the scrubbed message -- an event saying only that
                # *something* failed is not a usable diagnostic -- but not
                # the traceback, whose frame-locals loguru's ``diagnose``
                # renders. That is the middle ground ``log_sanitizer``
                # documents ("log without the traceback instead --
                # ``logger.warning(scrub_error(exc, *known_secrets))``") and
                # the ``safe_msg`` shape the sibling ``openalex`` downloader
                # already uses. ERROR is kept (the level the
                # ``logger.exception`` this replaced logged at): this
                # handler's frames hold no URL and no credential.
                safe_msg = scrub_error(exc)
                logger.opt(exception=False).error(
                    f"Error closing downloader session: {safe_msg}"
                )
            finally:
                self.session = None  # type: ignore[assignment]

    def __del__(self):
        """Destructor to ensure session is closed."""
        self.close()

    def __enter__(self):
        """Context manager entry."""
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Context manager exit - ensures session cleanup."""
        self.close()
        return False

    @abstractmethod
    def can_handle(self, url: str) -> bool:
        """
        Check if this downloader can handle the given URL.

        Args:
            url: The URL to check

        Returns:
            True if this downloader can handle the URL
        """
        pass

    @abstractmethod
    def download(
        self, url: str, content_type: ContentType = ContentType.PDF
    ) -> Optional[bytes]:
        """
        Download content from the given URL.

        Args:
            url: The URL to download from
            content_type: Type of content to download (PDF or TEXT)

        Returns:
            Content as bytes, or None if download failed
            For TEXT type, returns UTF-8 encoded text as bytes
        """
        pass

    def download_pdf(self, url: str) -> Optional[bytes]:
        """
        Convenience method to download PDF.

        Args:
            url: The URL to download from

        Returns:
            PDF content as bytes, or None if download failed
        """
        return self.download(url, ContentType.PDF)

    def download_with_result(
        self, url: str, content_type: ContentType = ContentType.PDF
    ) -> DownloadResult:
        """
        Download content and return detailed result with skip reason.

        Args:
            url: The URL to download from
            content_type: Type of content to download

        Returns:
            DownloadResult with content and/or skip reason
        """
        # Default implementation - derived classes should override for specific reasons
        content = self.download(url, content_type)
        if content:
            return DownloadResult(content=content, is_success=True)
        return DownloadResult(
            skip_reason="Download failed - content not available"
        )

    def download_text(self, url: str) -> Optional[str]:
        """
        Convenience method to download and return text content.

        Args:
            url: The URL to download from

        Returns:
            Text content as string, or None if download failed
        """
        content = self.download(url, ContentType.TEXT)
        if content:
            try:
                return content.decode("utf-8")
            except UnicodeDecodeError:
                logger.opt(exception=False).error(
                    f"Failed to decode text content from "
                    f"{redact_url_for_log(url)}"
                )
        return None

    @staticmethod
    def _has_pdf_signature(content: bytes) -> bool:
        """Allow whitespace and one UTF-8 BOM within a bounded PDF prefix."""
        header = content[:1024].lstrip()
        if header.startswith(b"\xef\xbb\xbf"):
            header = header[3:].lstrip()
        return len(header) > 4 and header.startswith(b"%PDF")

    def _is_pdf_content(
        self, response: requests.Response, content: bytes | None = None
    ) -> bool:
        """
        Check if response contains PDF content.

        Args:
            response: The response to check
            content: Body bytes the caller has already read (and bounded)
                under its own error accounting. Sniffed instead of
                ``response.content`` so a caller that has read the body
                itself never has a second, silently swallowed read here.
                See ``HTMLDownloader._fetch_html_with_final_url``, which
                needs an aborted body read to reach its own transport-
                failure path.

        Returns:
            True if response appears to contain PDF content
        """
        # Inspect the body even when the server declares a PDF media type.
        if content is not None:
            # Caller-supplied bytes: the read already happened and
            # succeeded, so there is nothing left to swallow here.
            return self._has_pdf_signature(content)
        try:
            body = getattr(response, "content", b"") or b""
            if len(body) > 4:
                return self._has_pdf_signature(body)
        except Exception:
            logger.debug("base.pdf_magic_check_failed")

        return False

    def _ensure_decoded_body_cap(self, response: requests.Response) -> None:
        """Install a second decoded-byte body guard for a valid, under-cap
        ``Content-Length``.

        ``SafeSession.send`` installs ``_install_body_guard`` (which
        bounds ``raw.read()``/``read_chunked()`` at
        ``MAX_RESPONSE_SIZE``, counting already-decoded bytes) on every
        response it accepts, including one whose *valid, under-cap*
        ``Content-Length`` says nothing about how far a gzip body can
        decode while ``response.content`` / ``response.text`` is read.
        Install the same guard again for that case, so the decoded body
        of *this* response stays bounded without relying on the session's
        guard. For a ``SafeSession`` response the two counters count the
        same bytes against the same threshold, so the second is harmless.

        This only bounds the body of the final response that callers of
        this method go on to read (``response.content`` in
        ``_download_pdf``, the streamed body in
        ``_fetch_html_with_final_url``). With ``allow_redirects=True``,
        intermediate redirect responses never reach this guard;
        ``SafeSession.resolve_redirects`` size-checks their
        ``Content-Length`` and discards their bodies unread.

        The request must have been made with ``stream=True`` for this to
        matter: with ``stream=False``, ``requests.Session.send`` consumes
        the body before returning, i.e. before this guard could wrap
        anything.
        """
        if getattr(response, "raw", None) is None:
            # No raw stream to wrap (the body is already materialised, e.g.
            # a Response built in memory): nothing left to bound here.
            return
        content_length = response.headers.get("Content-Length")
        if not content_length:
            # Absent/empty: SafeSession.send already installed the guard.
            return
        try:
            parts = [
                p.strip() for p in str(content_length).split(",") if p.strip()
            ]
            sizes = {int(p) for p in parts}
        except ValueError:
            # Unparseable: _check_response_size treated it as absent and
            # already installed the guard (differing duplicate values were
            # rejected inside SafeSession.send before we got here).
            return
        if (
            len(sizes) == 1
            and next(iter(sizes)) <= safe_requests.MAX_RESPONSE_SIZE
        ):
            # A single valid Content-Length within the cap, where the
            # decoded body can still exceed the header (e.g. gzip).
            # SafeSession.send has guarded this response already; stacking
            # a second guard here (or on the negative or duplicate CL
            # corner cases) is harmless — both counters share the same
            # threshold.
            safe_requests._install_body_guard(response)

    def _download_pdf(
        self,
        url: str,
        headers: Optional[Dict[str, str]] = None,
        *,
        max_attempts: int = 3,
        on_rate_limited: Optional[Callable[[], None]] = None,
        on_transport_failure: Optional[Callable[[], None]] = None,
    ) -> Optional[bytes]:
        """
        Helper method to download PDF with error handling and retry logic.
        Uses our optimized adaptive rate limiting/retry system.

        Args:
            url: The URL to download
            headers: Optional additional headers
            max_attempts: Attempts made before giving up on HTTP 429/503,
                timeouts and connection errors (default 3). A caller that
                must not retry into a rate-limited host passes 1.
            on_rate_limited: Called once when the download gives up on
                HTTP 429/503, so a caller can stop sending further
                requests to that host. When given, that give-up is logged
                as a warning rather than an error: the caller handles it.
            on_transport_failure: Called once when the download fails
                without the host answering "no such document" (HTTP 404
                or 410) or "not a PDF", and without a 429/503 give-up:
                timeouts and connection errors after the last attempt,
                any other request error, any other non-200 status, the
                decoded-body cap, or an unexpected error. A caller fetching
                several documents uses it to stop instead of paying a
                timeout per document. When given, every one of these
                failures is logged as a warning rather than an error.

        Returns:
            PDF content as bytes, or None if download failed
        """
        engine_type = f"pdf_download_{rate_limit_authority(url)}"

        logger.debug(
            f"Downloading PDF from {redact_url_for_log(url)} with adaptive "
            f"rate limiting (max {max_attempts} attempts)"
        )
        self._last_pdf_content = None
        self._last_final_url = None

        for attempt in range(1, max_attempts + 1):
            # Apply adaptive rate limiting before the request
            wait_time = self.rate_tracker.apply_rate_limit(engine_type)

            try:
                # Prepare headers
                if headers:
                    request_headers = dict(self.session.headers)
                    request_headers.update(headers)
                else:
                    request_headers = dict(self.session.headers)

                # Make the request. stream=True leaves the body unread
                # until the status check below, so a non-200 body is closed
                # unread and _ensure_decoded_body_cap can wrap the reads
                # before response.content. SafeSession.send bounds the
                # decoded read at MAX_RESPONSE_SIZE either way; with
                # stream=False it would read the body before returning,
                # before that second guard could wrap anything. That covers
                # the final response only; SafeSession discards
                # intermediate redirect bodies unread.
                response = self.session.get(
                    url,
                    headers=request_headers,
                    timeout=self.timeout,
                    allow_redirects=True,
                    stream=True,
                )

                try:
                    # Check response
                    if response.status_code == 200:
                        self._ensure_decoded_body_cap(response)
                        try:
                            body = response.content
                        except ValueError as e:
                            raise _ResponseBodyTooLarge(str(e)) from e
                        if self._is_pdf_content(response, content=body):
                            logger.debug(
                                f"Successfully downloaded PDF from "
                                f"{redact_url_for_log(url)} on attempt {attempt}"
                            )
                            # Record successful outcome
                            self.rate_tracker.record_outcome(
                                engine_type=engine_type,
                                wait_time=wait_time,
                                success=True,
                                retry_count=attempt,
                                search_result_count=1,  # We got the PDF
                            )
                            self._last_pdf_content = body
                            # Single fetch-time writer lives in ContentFetcher;
                            # downloaders only record the redirect final URL.
                            # Library downloads persist synchronously in
                            # DownloadService._download_pdf.
                            try:
                                resp_url = getattr(response, "url", None)
                                if resp_url and resp_url != url:
                                    self._last_final_url = resp_url
                                else:
                                    self._last_final_url = None
                            except Exception as exc:
                                logger.opt(exception=False).debug(
                                    "pdf.final_url_track_failed url={url} exc_class={exc_class}",
                                    url=redact_url_for_log(url),
                                    exc_class=type(exc).__name__,
                                )
                            return body
                        logger.warning(
                            f"Response is not a PDF: {response.headers.get('content-type', 'unknown')}"
                        )
                        # Record failure but don't retry for wrong content type
                        self.rate_tracker.record_outcome(
                            engine_type=engine_type,
                            wait_time=wait_time,
                            success=False,
                            retry_count=attempt,
                            error_type="NotPDF",
                        )
                        return None
                    if response.status_code in [
                        429,
                        503,
                    ]:  # Rate limit or service unavailable
                        logger.warning(
                            f"Attempt {attempt}/{max_attempts} - HTTP "
                            f"{response.status_code} from {redact_url_for_log(url)}"
                        )
                        # Record rate limit failure
                        self.rate_tracker.record_outcome(
                            engine_type=engine_type,
                            wait_time=wait_time,
                            success=False,
                            retry_count=attempt,
                            error_type=f"HTTP_{response.status_code}",
                        )
                        if attempt == max_attempts:
                            # A caller that passed on_rate_limited handles
                            # the give-up itself (the arXiv full-text step
                            # stops and keeps summaries), so it is not an
                            # error here; ERROR records also reach the
                            # user's browser via frontend_progress_sink.
                            give_up = (
                                f"Failed to download from "
                                f"{redact_url_for_log(url)}: HTTP "
                                f"{response.status_code} after {max_attempts} attempts"
                            )
                            if on_rate_limited is not None:
                                logger.warning(give_up)
                                on_rate_limited()
                            else:
                                logger.error(give_up)
                            return None
                        # Continue retry loop with adaptive wait
                        continue
                    logger.warning(
                        f"Failed to download from {redact_url_for_log(url)}: "
                        f"HTTP {response.status_code}"
                    )
                    # Record failure but don't retry for other status codes
                    self.rate_tracker.record_outcome(
                        engine_type=engine_type,
                        wait_time=wait_time,
                        success=False,
                        retry_count=attempt,
                        error_type=f"HTTP_{response.status_code}",
                    )
                    if (
                        on_transport_failure is not None
                        and response.status_code
                        not in _DOCUMENT_ABSENT_STATUSES
                    ):
                        on_transport_failure()
                    return None
                finally:
                    # stream=True leaves the connection unreleased until the
                    # body is consumed or the response is closed; close on
                    # every path so non-200/NotPDF responses return their
                    # connection to the pool instead of leaking it.
                    safe_close(response, "downloader response")

            except PolicyDeniedError:
                raise
            except (
                requests.exceptions.Timeout,
                requests.exceptions.ConnectionError,
            ) as e:
                # Record network failure
                self.rate_tracker.record_outcome(
                    engine_type=engine_type,
                    wait_time=wait_time,
                    success=False,
                    retry_count=attempt,
                    error_type=type(e).__name__,
                )
                if attempt == max_attempts:
                    give_up = (
                        f"{type(e).__name__} downloading from "
                        f"{redact_url_for_log(url)} after {max_attempts} attempts"
                    )
                    if on_transport_failure is not None:
                        # The caller handles the give-up (see
                        # on_transport_failure), so it is not an error here.
                        logger.warning(give_up)
                        on_transport_failure()
                    else:
                        logger.opt(exception=False).error(give_up)
                    return None
                logger.warning(
                    f"Attempt {attempt}/{max_attempts} - {type(e).__name__} "
                    f"downloading from {redact_url_for_log(url)}"
                )
                continue  # Retry with adaptive wait
            except requests.exceptions.RequestException as e:
                request_error = (
                    f"Request error downloading from {redact_url_for_log(url)} "
                    f"({type(e).__name__})"
                )
                if on_transport_failure is not None:
                    logger.warning(request_error)
                else:
                    logger.opt(exception=False).error(request_error)
                # Record failure but don't retry
                self.rate_tracker.record_outcome(
                    engine_type=engine_type,
                    wait_time=wait_time,
                    success=False,
                    retry_count=attempt,
                    error_type=type(e).__name__,
                )
                if on_transport_failure is not None:
                    on_transport_failure()
                return None
            except _ResponseBodyTooLarge:
                # The decoded body passed MAX_RESPONSE_SIZE mid-read (guard
                # installed by _ensure_decoded_body_cap). Not retryable: the
                # body is oversized regardless of attempt count. The
                # exception carries only the byte counts; its detail is
                # kept out of the log line per the sensitive-logging hook.
                logger.warning(
                    f"Response body exceeded size cap downloading from "
                    f"{redact_url_for_log(url)}"
                )
                self.rate_tracker.record_outcome(
                    engine_type=engine_type,
                    wait_time=wait_time,
                    success=False,
                    retry_count=attempt,
                    error_type="ResponseBodyTooLarge",
                )
                if on_transport_failure is not None:
                    on_transport_failure()
                return None
            except Exception as e:
                # Includes the ValueError SafeSession raises when the URL
                # fails validation, which is also how a failed DNS lookup
                # surfaces, so an offline machine lands here. A caller that
                # passed on_transport_failure handles it (see the docstring),
                # so it is not an error here; ERROR records reach the
                # user's browser via frontend_progress_sink.
                unexpected_error = (
                    f"Unexpected error downloading from "
                    f"{redact_url_for_log(url)} ({type(e).__name__})"
                )
                if on_transport_failure is not None:
                    logger.warning(unexpected_error)
                else:
                    logger.opt(exception=False).error(unexpected_error)
                # Record failure but don't retry
                self.rate_tracker.record_outcome(
                    engine_type=engine_type,
                    wait_time=wait_time,
                    success=False,
                    retry_count=attempt,
                    error_type="UnexpectedError",
                )
                if on_transport_failure is not None:
                    on_transport_failure()
                return None

        return None

    @staticmethod
    def extract_text_from_pdf(
        pdf_content: bytes, max_pages: Optional[int] = None
    ) -> Optional[str]:
        """
        Extract text from PDF content using in-memory processing.

        This is part of the public API and can be used by other modules.

        What is bounded (``utilities/pdf_extraction_limits``): at most
        ``MAX_PDF_EXTRACTION_PAGES`` pages are extracted, at most
        ``MAX_PDF_EXTRACTED_CHARS`` characters are returned (separators
        included; the page that crosses the ceiling is truncated to the
        budget left), and no new page is started once the calling thread
        has spent ``MAX_PDF_EXTRACTION_CPU_SECONDS`` of its own CPU time
        (``time.thread_time()``, so GIL waits and other requests' load do
        not count) since entry. pypdf keeps every stream it decodes and
        every object it parses on the reader; a releaser
        (``utilities/pdf_stream_release``) releases them once they reach
        ``MAX_PDF_RETAINED_DECODED_BYTES``, so what the walk holds
        between pages stays near that threshold.

        What is NOT bounded: the budget is checked between pages only,
        so neither a single page's ``extract_text()`` nor pypdf's
        page-tree construction (``PdfReader`` and the first access to its
        pages, O(all pages) in time and memory for a file with many pages)
        can be interrupted, and what one page decodes and parses is held
        until the release after it.

        Args:
            pdf_content: PDF file content as bytes
            max_pages: Maximum number of pages to extract (oldest-first).
                None (default) extracts all pages, preserving the historic
                behavior for dedicated PDF paths. Bounded callers (e.g. the
                HTML-downloader recovery path, reachable from any
                HTML-classified URL) pass a small cap so a crafted PDF with
                many pages cannot turn one ingest into unbounded CPU/memory
                work -- pypdf caps each stream but not the document total.

        Returns:
            Extracted text, or None if extraction failed
        """
        # Started at entry so the budget covers the whole call, parse
        # included, as in the download service's extractor. Per-thread CPU
        # time, not wall time, so time spent waiting on other requests is
        # not charged (GIL-switch overhead still is; see the constant).
        deadline = time.thread_time() + MAX_PDF_EXTRACTION_CPU_SECONDS
        try:
            import io

            # Use pypdf for in-memory PDF text extraction (no disk writes)
            from pypdf import PdfReader

            pdf_file = io.BytesIO(pdf_content)
            pdf_reader = PdfReader(pdf_file)

            text_content = []
            extracted_chars = 0
            releaser = PypdfWalkReleaser(pdf_reader)
            # The CPU budget is checked BETWEEN pages only — the sole check
            # point available without running the extractor in its own
            # process — so a single slow page still runs to completion
            # inside pypdf.
            for page_number, page in enumerate(pdf_reader.pages):
                if max_pages is not None and page_number >= max_pages:
                    logger.warning(
                        "PDF extraction stopped at caller page cap "
                        f"({max_pages}); document has "
                        f"{len(pdf_reader.pages)} pages"
                    )
                    break
                if page_number >= MAX_PDF_EXTRACTION_PAGES:
                    logger.warning(
                        "PDF extraction stopped at page ceiling "
                        f"({MAX_PDF_EXTRACTION_PAGES}); document has "
                        f"{len(pdf_reader.pages)} pages"
                    )
                    break
                if time.thread_time() >= deadline:
                    logger.warning(
                        "PDF extraction stopped at the CPU-time ceiling "
                        f"({MAX_PDF_EXTRACTION_CPU_SECONDS}s) after "
                        f"{page_number} pages"
                    )
                    break
                # The running count reserves the next join separator too.
                # Do not risk a failing page when none of its text can fit.
                remaining = MAX_PDF_EXTRACTED_CHARS - extracted_chars
                if remaining <= 0:
                    logger.warning(
                        "PDF extraction stopped at character ceiling "
                        f"({MAX_PDF_EXTRACTED_CHARS})"
                    )
                    break
                releaser.before_page()
                text = page.extract_text()
                # pypdf keeps what it decodes and parses cached on the
                # reader; release it once it reaches
                # MAX_PDF_RETAINED_DECODED_BYTES.
                releaser.after_page()
                if text:
                    if len(text) > remaining:
                        # Keep the slice that fits rather than dropping
                        # the tripping page whole.
                        if remaining > 0:
                            text_content.append(text[:remaining])
                            extracted_chars += remaining
                        logger.warning(
                            "PDF extraction truncated at character ceiling "
                            f"({MAX_PDF_EXTRACTED_CHARS})"
                        )
                        break
                    # + 1 for the "\n" separator the join adds.
                    extracted_chars += len(text) + 1
                    text_content.append(text)

            full_text = "\n".join(text_content)
            return full_text if full_text.strip() else None

        except Exception as exc:
            # Scrubbed message, no traceback -- see ``close`` above. pypdf can
            # raise ``PdfReadError`` with a message that embeds a slice of
            # the raw stream (e.g. a malformed header byte sequence). The
            # message is kept here not because it is always the whole
            # diagnostic, but because this frame holds only the PDF bytes --
            # no URL or credential -- so there is nothing for it to leak.
            safe_msg = scrub_error(exc)
            logger.opt(exception=False).error(
                f"Failed to extract text from PDF: {safe_msg}"
            )
            return None

    def _fetch_text_from_api(self, url: str) -> Optional[str]:
        """
        Fetch full text directly from API.

        This is a placeholder - derived classes should implement
        API-specific text fetching logic.

        Args:
            url: The URL or identifier

        Returns:
            Full text content, or None if not available
        """
        return None

    def get_metadata(self, url: str) -> Dict[str, Any]:
        """
        Get metadata about the resource (optional override).

        Args:
            url: The URL to get metadata for

        Returns:
            Dictionary with metadata
        """
        return {}