"""Input/output storage adapters. The HDFS adapter uses the installed hdfs CLI.""" import shutil import subprocess from pathlib import Path from .config import Settings class StorageError(Exception): pass def _hdfs(settings: Settings, *args: str) -> None: command = ["hdfs", "dfs"] if settings.hdfs_native_uri: command.extend(["-fs", settings.hdfs_native_uri]) try: subprocess.run([*command, *args], check=True, capture_output=True, text=True, timeout=600) except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc: detail = getattr(exc, "stderr", None) or str(exc) raise StorageError(f"HDFS operation failed: {detail[:500]}") from exc def fetch_pdf(settings: Settings, source: str, destination: Path) -> None: destination.parent.mkdir(parents=True, exist_ok=True) temporary = destination.with_suffix(".download") temporary.unlink(missing_ok=True) if settings.storage == "hdfs": from .webhdfs import download_pdf download_pdf(settings.hdfs_url, source, temporary, settings.max_pdf_bytes) elif settings.storage == "hdfs_cli": _hdfs(settings, "-get", source, str(temporary)) elif settings.storage == "local": source_path = Path(source).resolve() if not source_path.is_file(): raise StorageError(f"Source file not found: {source}") shutil.copyfile(source_path, temporary) else: raise StorageError(f"Unknown storage mode: {settings.storage}") if temporary.stat().st_size > settings.max_pdf_bytes: temporary.unlink(missing_ok=True) raise StorageError("PDF exceeds IDP_MAX_PDF_BYTES") temporary.replace(destination)