Source code for automated_document_parser.api

"""Optional FastAPI application for durable document ingestion and search."""

import hmac
import logging
import math
import os
import re
import stat
import time
import uuid
from collections import deque
from collections.abc import Sequence
from contextlib import asynccontextmanager
from pathlib import Path
from threading import Lock
from typing import Any

from .ingestion import DocumentIngestionPipeline
from .jobs import IngestionWorker, SQLiteJobStore
from .logging_config import correlation_context

logger = logging.getLogger(__name__)
_REQUEST_ID_PATTERN = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")


class _RequestBodyLimitMiddleware:
    """Enforce a request-body cap even when clients use chunked transfer."""

    def __init__(self, app, max_bytes: int):
        self.app = app
        self.max_bytes = max_bytes

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        content_length = next(
            (
                value.decode("latin-1")
                for name, value in scope.get("headers", [])
                if name.lower() == b"content-length"
            ),
            None,
        )
        if content_length is not None:
            try:
                declared_size = int(content_length)
            except ValueError:
                await self._reject(scope, receive, send, 400, "Invalid Content-Length")
                return
            if declared_size < 0:
                await self._reject(scope, receive, send, 400, "Invalid Content-Length")
                return
            if declared_size > self.max_bytes:
                await self._reject(
                    scope, receive, send, 413, "Request body is too large"
                )
                return

        body = bytearray()
        while True:
            message = await receive()
            if message["type"] == "http.disconnect":
                return
            if message["type"] != "http.request":
                continue
            body.extend(message.get("body", b""))
            if len(body) > self.max_bytes:
                await self._reject(
                    scope, receive, send, 413, "Request body is too large"
                )
                return
            if not message.get("more_body", False):
                break

        replayed = False

        async def replay_receive():
            nonlocal replayed
            if not replayed:
                replayed = True
                return {
                    "type": "http.request",
                    "body": bytes(body),
                    "more_body": False,
                }
            return await receive()

        await self.app(scope, replay_receive, send)

    @staticmethod
    async def _reject(scope, receive, send, status_code: int, detail: str):
        from starlette.responses import JSONResponse

        response = JSONResponse(
            status_code=status_code,
            content={"detail": detail},
            headers={
                "Cache-Control": "no-store",
                "Referrer-Policy": "no-referrer",
                "X-Content-Type-Options": "nosniff",
            },
        )
        await response(scope, receive, send)


class _InMemoryRateLimiter:
    """Bounded per-client sliding-window limiter for a single API process."""

    def __init__(self, limit: int, window_seconds: float, max_clients: int):
        self.limit = limit
        self.window_seconds = window_seconds
        self.max_clients = max_clients
        self._requests: dict[str, deque[float]] = {}
        self._lock = Lock()

    def check(self, client_id: str, now: float) -> tuple[bool, int, int]:
        """Return allowed, remaining, and retry-after seconds."""
        cutoff = now - self.window_seconds
        with self._lock:
            if (
                client_id not in self._requests
                and len(self._requests) >= self.max_clients
            ):
                for key, timestamps in list(self._requests.items()):
                    while timestamps and timestamps[0] <= cutoff:
                        timestamps.popleft()
                    if not timestamps:
                        self._requests.pop(key, None)
                if len(self._requests) >= self.max_clients:
                    oldest = min(
                        self._requests, key=lambda key: self._requests[key][-1]
                    )
                    self._requests.pop(oldest, None)

            timestamps = self._requests.setdefault(client_id, deque())
            while timestamps and timestamps[0] <= cutoff:
                timestamps.popleft()
            if len(timestamps) >= self.limit:
                retry_after = max(
                    1, int(timestamps[0] + self.window_seconds - now + 0.999)
                )
                return False, 0, retry_after
            timestamps.append(now)
            return True, self.limit - len(timestamps), 0


[docs] def create_app( *, pipeline: DocumentIngestionPipeline, job_store: SQLiteJobStore, allowed_roots: Sequence[str | Path], api_key: str | None = None, worker: IngestionWorker | None = None, start_worker: bool = True, max_file_size_bytes: int = 100 * 1024 * 1024, max_request_body_bytes: int = 16 * 1024, rate_limit_requests: int = 120, rate_limit_window_seconds: float = 60.0, rate_limit_max_clients: int = 10_000, max_job_attempts: int = 3, retry_base_delay: float = 1.0, retry_max_delay: float = 30.0, retry_jitter_fraction: float = 0.2, ): """Create an API app around injected pipeline and durable job storage. ``POST /v1/jobs`` accepts paths on the server, not uploaded bytes. Every requested path is resolved and constrained to ``allowed_roots`` before it enters the queue. Configure ``api_key`` when exposing the service beyond a trusted local network; all application endpoints except ``/healthz`` and ``/readyz`` then require the ``X-API-Key`` header. A bounded in-memory sliding-window limiter applies per connecting client address (120 requests per 60 seconds by default), excluding liveness/readiness probes. It is process-local and must not be treated as a distributed edge/WAF rate limit. Forwarded-IP headers are not trusted; configure a trusted proxy and its network controls separately. The caller owns the lifetime of the injected pipeline, vector store and job store. The app starts and stops only the worker it is given or creates. """ try: from fastapi import FastAPI, HTTPException, Query, Request from fastapi.responses import JSONResponse, Response from pydantic import BaseModel, ConfigDict, Field from .observability import ApiMetrics except ImportError as exc: raise ImportError( "The HTTP API requires the optional 'api' dependencies. Install " "them with `pip install automated-document-parser[api]`." ) from exc if isinstance(allowed_roots, (str, Path)): allowed_roots = (allowed_roots,) if not allowed_roots: raise ValueError("at least one allowed_root must be configured") roots = tuple(Path(root).expanduser().resolve() for root in allowed_roots) if any(not root.is_dir() for root in roots): raise ValueError("all allowed_roots must exist and be directories") if max_file_size_bytes < 1: raise ValueError("max_file_size_bytes must be positive") if max_request_body_bytes < 1: raise ValueError("max_request_body_bytes must be positive") if ( isinstance(rate_limit_requests, bool) or not isinstance(rate_limit_requests, int) or rate_limit_requests < 1 ): raise ValueError("rate_limit_requests must be a positive integer") if ( isinstance(rate_limit_window_seconds, bool) or not isinstance(rate_limit_window_seconds, (int, float)) or not math.isfinite(rate_limit_window_seconds) or rate_limit_window_seconds <= 0 ): raise ValueError("rate_limit_window_seconds must be a finite positive number") if ( isinstance(rate_limit_max_clients, bool) or not isinstance(rate_limit_max_clients, int) or rate_limit_max_clients < 1 ): raise ValueError("rate_limit_max_clients must be a positive integer") if api_key is not None and not api_key.strip(): raise ValueError("api_key must not be blank") class CreateJobRequest(BaseModel): model_config = ConfigDict(extra="forbid") source: str = Field(min_length=1, max_length=4096) allowed_root_paths = tuple(os.path.realpath(os.fspath(root)) for root in roots) def validate_source(source: str) -> Path: if not source.strip(): raise HTTPException(status_code=422, detail="Source file does not exist") # Canonicalize before constructing a Path or performing file operations. # realpath follows symlinks, so the containment check also rejects links # whose targets escape the configured roots. candidate_text = os.path.realpath(os.path.expanduser(source)) for root_text in allowed_root_paths: root_prefix = os.path.join(root_text, "") if candidate_text == root_text or candidate_text.startswith(root_prefix): candidate = Path(candidate_text) break else: raise HTTPException( status_code=403, detail="Source path is outside the configured allowed roots", ) # Validate the opened object, not only the path checked above. # O_NOFOLLOW also rejects a final-component symlink substitution. try: descriptor = os.open( candidate_text, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0), ) except OSError as exc: raise HTTPException( status_code=422, detail="Source file cannot be accessed" ) from exc try: file_info = os.fstat(descriptor) finally: os.close(descriptor) if not stat.S_ISREG(file_info.st_mode): raise HTTPException(status_code=422, detail="Source must be a regular file") size = file_info.st_size if size > max_file_size_bytes: raise HTTPException( status_code=413, detail=f"Source exceeds the {max_file_size_bytes}-byte API limit", ) return candidate if worker is not None and ( worker.job_store is not job_store or worker.pipeline is not pipeline ): raise ValueError("injected worker must use the supplied pipeline and job_store") ingestion_worker = worker or IngestionWorker( job_store, pipeline, max_attempts=max_job_attempts, retry_base_delay=retry_base_delay, retry_max_delay=retry_max_delay, retry_jitter_fraction=retry_jitter_fraction, ) ingestion_worker.source_validator = validate_source @asynccontextmanager async def lifespan(_: Any): if start_worker: ingestion_worker.start() try: yield finally: if start_worker: ingestion_worker.stop(timeout=None) app = FastAPI( title="Automated Document Parser API", version="0.2.0", description="Durable document ingestion jobs and retrieval API.", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None, ) app.add_middleware(_RequestBodyLimitMiddleware, max_bytes=max_request_body_bytes) app.state.pipeline = pipeline app.state.job_store = job_store app.state.worker = ingestion_worker app.state.allowed_roots = roots metrics = ApiMetrics() app.state.metrics = metrics rate_limiter = _InMemoryRateLimiter( rate_limit_requests, rate_limit_window_seconds, rate_limit_max_clients ) app.state.rate_limiter = rate_limiter @app.middleware("http") async def request_observability(request, call_next): supplied_id = request.headers.get("X-Request-ID", "") request_id = ( supplied_id if _REQUEST_ID_PATTERN.fullmatch(supplied_id) else uuid.uuid4().hex ) started = time.perf_counter() with correlation_context(request_id): try: response = await call_next(request) except Exception: logger.exception( "HTTP request failed", extra={ "event": "http_request_failed", "http_method": request.method, "http_path": request.url.path, "duration_ms": round((time.perf_counter() - started) * 1000, 3), }, ) metrics.observe_request( request.method, getattr(request.scope.get("route"), "path", "unmatched"), 500, time.perf_counter() - started, ) raise response.headers["X-Request-ID"] = request_id response.headers["X-Content-Type-Options"] = "nosniff" response.headers["Referrer-Policy"] = "no-referrer" response.headers["Cache-Control"] = "no-store" route = getattr(request.scope.get("route"), "path", "unmatched") duration_seconds = time.perf_counter() - started metrics.observe_request( request.method, route, response.status_code, duration_seconds ) logger.info( "HTTP request completed", extra={ "event": "http_request_completed", "http_method": request.method, "http_path": request.url.path, "http_status": response.status_code, "duration_ms": round(duration_seconds * 1000, 3), }, ) return response @app.middleware("http") async def authenticate(request, call_next): if request.url.path not in {"/healthz", "/readyz"}: client_id = request.client.host if request.client else "unknown" allowed, remaining, retry_after = rate_limiter.check( client_id, time.monotonic() ) if not allowed: logger.warning( "API request rate limit exceeded", extra={ "event": "security_rate_limit_exceeded", "client_ip": client_id, "http_method": request.method, "http_path": request.url.path, "rate_limit": rate_limit_requests, "rate_limit_window_seconds": rate_limit_window_seconds, }, ) return JSONResponse( status_code=429, content={"detail": "Rate limit exceeded; retry later"}, headers={ "Retry-After": str(retry_after), "X-RateLimit-Limit": str(rate_limit_requests), "X-RateLimit-Remaining": "0", }, ) else: remaining = rate_limit_requests if api_key is not None and request.url.path not in {"/healthz", "/readyz"}: supplied = request.headers.get("X-API-Key", "") if not supplied: authorization = request.headers.get("Authorization", "") scheme, separator, credential = authorization.partition(" ") if separator and scheme.lower() == "bearer": supplied = credential.strip() if not hmac.compare_digest(supplied, api_key): logger.warning( "API authentication failed", extra={ "event": "security_authentication_failed", "client_ip": request.client.host if request.client else "unknown", "http_method": request.method, "http_path": request.url.path, }, ) return JSONResponse( status_code=401, content={"detail": "Invalid or missing API key"}, headers={ "WWW-Authenticate": "ApiKey", "X-RateLimit-Limit": str(rate_limit_requests), "X-RateLimit-Remaining": str(remaining), }, ) response = await call_next(request) if request.url.path not in {"/healthz", "/readyz"}: response.headers["X-RateLimit-Limit"] = str(rate_limit_requests) response.headers["X-RateLimit-Remaining"] = str(remaining) return response @app.get("/healthz") def health() -> dict[str, Any]: """Liveness probe: confirms that the HTTP process can answer requests.""" return {"status": "ok"} @app.get("/readyz") def readiness(): """Readiness probe: check durable storage and managed worker availability.""" checks: dict[str, dict[str, Any]] = {} job_counts: dict[str, int] = {} worker_health = ingestion_worker.health() try: health_check = getattr(job_store, "health_check", None) if callable(health_check) and health_check() is False: raise RuntimeError("job store health check failed") job_counts = job_store.counts() checks["job_store"] = {"status": "ok"} except Exception as exc: # noqa: BLE001 - readiness must report dependency failures checks["job_store"] = { "status": "error", "error_type": type(exc).__name__, } vector_store = pipeline.vector_store if vector_store is None: checks["vector_store"] = {"status": "ok", "mode": "lexical"} else: try: health_check = getattr(vector_store, "health_check", None) if callable(health_check): if health_check() is False: raise RuntimeError("vector store health check failed") checks["vector_store"] = {"status": "ok"} else: checks["vector_store"] = { "status": "unknown", "reason": "adapter_has_no_health_check", } except Exception as exc: # noqa: BLE001 - readiness must report dependency failures checks["vector_store"] = { "status": "error", "error_type": type(exc).__name__, } if start_worker: worker_available = worker_health["running"] and not worker_health["paused"] checks["worker"] = { "status": "ok" if worker_available else "error", "running": worker_health["running"], "paused": worker_health["paused"], } else: checks["worker"] = {"status": "not_managed"} ready = all( check["status"] in {"ok", "not_managed", "unknown"} for check in checks.values() ) metrics.update_runtime(job_counts, worker_health) return JSONResponse( status_code=200 if ready else 503, content={"status": "ready" if ready else "not_ready", "checks": checks}, ) @app.get("/metrics", include_in_schema=False) def prometheus_metrics(): """Expose Prometheus text exposition; protected by API-key middleware.""" from prometheus_client import CONTENT_TYPE_LATEST, generate_latest try: counts = job_store.counts() worker_health = ingestion_worker.health() metrics.update_runtime(counts, worker_health) except Exception: logger.exception("Unable to refresh operational metrics") return Response( content=generate_latest(metrics.registry), media_type=CONTENT_TYPE_LATEST, ) @app.post("/v1/jobs", status_code=202) def submit_job(request: Request, payload: CreateJobRequest): """Queue one allowed local document; Idempotency-Key safely deduplicates retries.""" source = validate_source(payload.source) try: job, created = job_store.enqueue_with_status( source, idempotency_key=request.headers.get("Idempotency-Key") ) except ValueError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc if created: metrics.observe_job_enqueued() logger.info( "Ingestion job enqueued", extra={ "event": "job_enqueued", "job_id": job.id, "source_name": source.name, }, ) else: logger.info( "Idempotent ingestion submission replayed", extra={"event": "job_idempotency_replayed", "job_id": job.id}, ) return JSONResponse( status_code=202 if created else 200, content=job.to_dict(), headers={"Location": f"/v1/jobs/{job.id}"}, ) @app.get("/v1/jobs") def list_jobs( limit: int = Query(default=50, ge=1, le=500), status: str | None = Query( default=None, pattern="^(queued|running|succeeded|failed|cancelled)$" ), ) -> dict[str, Any]: """List recent ingestion jobs, optionally filtered by status.""" jobs = job_store.list_jobs(limit=limit, status=status) return {"count": len(jobs), "jobs": [job.to_dict() for job in jobs]} @app.get("/v1/jobs/{job_id}") def get_job(job_id: str) -> dict[str, Any]: """Retrieve the current state and result of one ingestion job.""" job = job_store.get(job_id) if job is None: raise HTTPException(status_code=404, detail="Ingestion job not found") return job.to_dict() @app.delete("/v1/jobs/{job_id}") def cancel_job(job_id: str) -> dict[str, Any]: """Cancel a queued job; active jobs are allowed to finish.""" if job_store.get(job_id) is None: raise HTTPException(status_code=404, detail="Ingestion job not found") try: result = job_store.cancel(job_id) logger.info( "Ingestion job cancellation requested", extra={"event": "job_cancel_requested", "job_id": job_id}, ) return result.to_dict() except ValueError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc @app.post("/v1/jobs/{job_id}/retry") def retry_job(job_id: str) -> dict[str, Any]: """Manually retry a terminal failed job.""" if job_store.get(job_id) is None: raise HTTPException(status_code=404, detail="Ingestion job not found") try: result = job_store.retry(job_id) logger.info( "Ingestion job retry requested", extra={"event": "job_retry_requested", "job_id": job_id}, ) return result.to_dict() except ValueError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc @app.post("/v1/worker/pause") def pause_worker() -> dict[str, Any]: """Pause new work claims while the current job completes.""" ingestion_worker.pause() logger.info("Ingestion worker paused", extra={"event": "worker_paused"}) return ingestion_worker.health() @app.post("/v1/worker/resume") def resume_worker() -> dict[str, Any]: """Resume background work claims.""" ingestion_worker.resume() logger.info("Ingestion worker resumed", extra={"event": "worker_resumed"}) return ingestion_worker.health() @app.get("/v1/search") def search( q: str = Query(min_length=1, max_length=2000), limit: int = Query(default=5, ge=1, le=50), ) -> dict[str, Any]: """Search indexed chunks and return their provenance and scores.""" try: with ingestion_worker.pipeline_lock: results = pipeline.search(q, k=limit) except ValueError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc return { "query": q, "count": len(results), "results": [ { "source": result.chunk.source, "chunk_index": result.chunk.chunk_index, "score": result.score, "lexical_score": result.lexical_score, "vector_score": result.vector_score, "content": result.chunk.content, "page_numbers": result.chunk.page_numbers, "metadata": result.chunk.metadata, } for result in results ], } return app