"""Standard error envelope for cross-service communication. Every non-2xx response from this service uses this shape so NestJS can distinguish error categories and decide whether to retry. """ from enum import Enum from pydantic import BaseModel from typing import Optional from app.middleware.correlation import get_correlation_id class ErrorCode(str, Enum): """Stable error codes — never rename, only add new ones.""" VALIDATION_ERROR = "VALIDATION_ERROR" AUTH_INVALID_KEY = "AUTH_INVALID_KEY" IDEMPOTENCY_CONFLICT = "IDEMPOTENCY_CONFLICT" DOCUMENT_NOT_FOUND = "DOCUMENT_NOT_FOUND" FORBIDDEN = "FORBIDDEN" INGEST_FAILED = "INGEST_FAILED" LLM_UNAVAILABLE = "LLM_UNAVAILABLE" PDF_GENERATION_FAILED = "PDF_GENERATION_FAILED" INTERNAL_ERROR = "INTERNAL_ERROR" class ErrorEnvelope(BaseModel): code: ErrorCode message: str retryable: bool = False correlation_id: Optional[str] = None details: Optional[dict] = None def make_error( code: ErrorCode, message: str, *, retryable: bool = False, details: dict | None = None, ) -> dict: """Build an error dict suitable for JSONResponse / HTTPException detail.""" return ErrorEnvelope( code=code, message=message, retryable=retryable, correlation_id=get_correlation_id(), details=details, ).model_dump(exclude_none=True)