"""Cliente mínimo de Elasticsearch por HTTP (sirve para Elasticsearch 7.x y 8.x). Se usa la API REST directamente con httpx en vez de la librería oficial: así no hay que alinear la versión de la librería con la del servidor. """ import logging from functools import lru_cache from urllib.parse import quote import httpx from app.config import get_settings log = logging.getLogger("api") class ElasticError(Exception): """Elasticsearch no respondió o respondió con error.""" @lru_cache def cliente() -> httpx.Client: s = get_settings() headers = {"Content-Type": "application/json"} auth = None if s.es_api_key.get_secret_value(): headers["Authorization"] = f"ApiKey {s.es_api_key.get_secret_value()}" elif s.es_username: auth = (s.es_username, s.es_password.get_secret_value()) verificar = s.es_ca_cert or s.es_verify_tls # ruta al CA, o True/False return httpx.Client(base_url=s.es_url.rstrip("/"), headers=headers, auth=auth, verify=verificar, timeout=s.es_timeout) def _pedir(metodo: str, ruta: str, **kwargs) -> httpx.Response: try: r = cliente().request(metodo, ruta, **kwargs) except httpx.HTTPError as e: raise ElasticError(f"No se pudo conectar con Elasticsearch: {type(e).__name__}") from e if r.status_code in (401, 403): raise ElasticError("Elasticsearch rechazó las credenciales (revisar ES_USERNAME/ES_PASSWORD o ES_API_KEY)") return r def buscar(cuerpo: dict) -> dict: r = _pedir("POST", f"/{get_settings().es_index}/_search", json=cuerpo) if r.status_code != 200: log.error("Elasticsearch respondió %s a la búsqueda: %s", r.status_code, r.text[:500]) raise ElasticError(f"Elasticsearch respondió {r.status_code}") return r.json() def obtener(doc_id: str, campos: list[str]) -> dict | None: """Un documento por su id (el que genera FSCrawler), o None si no existe.""" r = _pedir("GET", f"/{get_settings().es_index}/_doc/{quote(doc_id, safe='')}", params={"_source_includes": ",".join(campos)}) if r.status_code == 404: return None if r.status_code != 200: raise ElasticError(f"Elasticsearch respondió {r.status_code}") return r.json().get("_source", {}) def disponible() -> bool: try: return _pedir("GET", f"/{get_settings().es_index}/_count").status_code == 200 except ElasticError: return False