diff --git a/service/Dockerfile b/service/Dockerfile index 90d1a619..1c1f95a2 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -13,7 +13,6 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "pytest~=8.1.0" \ "httpx~=0.27.0" \ "python-multipart~=0.0.19"\ - "elasticsearch~=9.4.0" \ "openai~=2.41.0" COPY [ "src/main", "/home" ] diff --git a/service/pyproject.toml b/service/pyproject.toml index 9e45ebc4..7a21303c 100644 --- a/service/pyproject.toml +++ b/service/pyproject.toml @@ -7,7 +7,6 @@ requires-python = ">=3.12" dependencies = [ "cryptography~=42.0.0", "dotenv>=0.9.9", - "elasticsearch~=9.4.0", "fastapi~=0.115.0", "httpx~=0.27.0", "openai~=2.41.0", diff --git a/service/src/main/inse/exceptions.py b/service/src/main/inse/exceptions.py index 772a9607..ed59f58b 100644 --- a/service/src/main/inse/exceptions.py +++ b/service/src/main/inse/exceptions.py @@ -1,3 +1,18 @@ class NotFoundException(Exception): def __init__(self, message: str): super().__init__(message) + + +class ElasticsearchException(Exception): + """Base exception for all Elasticsearch integrations.""" + pass + + +class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException): + """Raised when an Elasticsearch document or index is not found.""" + pass + + +class ElasticsearchConnectionException(ElasticsearchException): + """Raised when connecting to Elasticsearch fails.""" + pass diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index c7343e50..1cb37add 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,13 +1,36 @@ import json import logging -from typing import Any, Dict, Iterator, List, Optional, Tuple +from typing import Any, Dict, AsyncIterator, List, Optional, Tuple + import httpx +from inse.exceptions import ( + ElasticsearchException, + ElasticsearchNotFoundException, + ElasticsearchConnectionException, +) from inse.model import ESCluster, ESIndex from .. import config logger = logging.getLogger(__name__) +_client: Optional[httpx.AsyncClient] = None +_loop = None + + +def get_client() -> httpx.AsyncClient: + global _client, _loop + try: + import asyncio + current_loop = asyncio.get_running_loop() + except RuntimeError: + current_loop = None + + if _client is None or _loop is not current_loop: + _client = httpx.AsyncClient(timeout=httpx.Timeout(30.0)) + _loop = current_loop + return _client + def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: """Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration. @@ -21,7 +44,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: Returns: Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster. """ - + if cluster == ESCluster.NES: if ( not config.settings.elasticsearch_url @@ -30,6 +53,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]: raise ValueError( "Elasticsearch URL and API key must be set in the configuration for cluster 'nes'" ) + return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key elif cluster == ESCluster.INSE: if ( @@ -80,8 +104,18 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: return None -def search( - index: ESIndex | List[ESIndex], +def _wrap_exception(e: Exception) -> Exception: + if isinstance(e, httpx.HTTPStatusError): + if e.response.status_code == 404: + return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}") + return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}") + elif isinstance(e, httpx.RequestError): + return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}") + return ElasticsearchException(f"Unexpected Elasticsearch error: {e}") + + +async def search( + index: ESIndex | List[ESIndex] | str | List[str], query: Optional[Dict] = None, source: Optional[List] = None, size: Optional[int] = None, @@ -112,10 +146,11 @@ def search( clusters = set() if isinstance(index, list): for idx in index: - cluster_for_index = _index_to_cluster(idx) - if cluster_for_index is not None: - clusters.add(cluster_for_index) - else: + if isinstance(idx, ESIndex): + cluster_for_index = _index_to_cluster(idx) + if cluster_for_index is not None: + clusters.add(cluster_for_index) + elif isinstance(index, ESIndex): cluster_for_index = _index_to_cluster(index) if cluster_for_index is not None: clusters.add(cluster_for_index) @@ -156,111 +191,125 @@ def search( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided" ) - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" - ) - if isinstance(index, list): - index_str = ",".join(index) - else: - index_str = index + client = get_client() + logger.debug( + f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" + ) + if isinstance(index, list): + index_str = ",".join(str(idx) for idx in index) + else: + index_str = str(index) - response = client.post( + try: + response = await client.post( f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers ) response.raise_for_status() return response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc -def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str: +async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str: """Opens a point-in-time on the given index and returns its id.""" elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - response = client.post( + client = get_client() + try: + response = await client.post( f"{elasticsearch_url}/{index}/_pit", params={"keep_alive": keep_alive}, headers=headers, ) response.raise_for_status() return response.json()["id"] + except Exception as exc: + raise _wrap_exception(exc) from exc -def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: +async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: """Closes a previously opened point-in-time.""" elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - response = client.request( + client = get_client() + try: + response = await client.request( "DELETE", f"{elasticsearch_url}/_pit", json={"id": pit_id}, headers=headers, ) response.raise_for_status() + except Exception as exc: + raise _wrap_exception(exc) from exc -def scan( +async def scan( index: str, query: Dict, source: Optional[List] = None, page_size: int = 1000, keep_alive: str = "1m", cluster: str = "nes", -) -> Iterator[Dict[str, Any]]: +) -> AsyncIterator[Dict[str, Any]]: """Yields every hit matching ``query`` using a point-in-time + ``search_after``. - + Unlike ``from``/``size`` pagination, this is not bounded by ``index.max_result_window``, so it can stream result sets larger than 10k. """ elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - pit_id = open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) + pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) search_after: Optional[List] = None try: - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - while True: - payload: Dict[str, Any] = { - "size": page_size, - "query": query, - "pit": {"id": pit_id, "keep_alive": keep_alive}, - "sort": [{"_shard_doc": "asc"}], - "track_total_hits": False, - } - if source is not None: - payload["_source"] = source - if search_after is not None: - payload["search_after"] = search_after + client = get_client() + while True: + payload: Dict[str, Any] = { + "size": page_size, + "query": query, + "pit": {"id": pit_id, "keep_alive": keep_alive}, + "sort": [{"_shard_doc": "asc"}], + "track_total_hits": False, + } + if source is not None: + payload["_source"] = source + if search_after is not None: + payload["search_after"] = search_after - response = client.post( + try: + response = await client.post( f"{elasticsearch_url}/_search", json=payload, headers=headers ) response.raise_for_status() - result = response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc - hits = result.get("hits", {}).get("hits", []) - if not hits: - break + result = response.json() - yield from hits + hits = result.get("hits", {}).get("hits", []) + if not hits: + break + + for hit in hits: + yield hit # The pit id can be refreshed between requests; keep the latest. - pit_id = result.get("pit_id", pit_id) - search_after = hits[-1].get("sort") - if search_after is None or len(hits) < page_size: - break + pit_id = result.get("pit_id", pit_id) + search_after = hits[-1].get("sort") + if search_after is None or len(hits) < page_size: + break finally: try: - close_point_in_time(pit_id, cluster=cluster) + await close_point_in_time(pit_id, cluster=cluster) except Exception: logger.exception("Failed to close Elasticsearch point-in-time.") -def get( - index: ESIndex, +async def get( + index: ESIndex | str, doc_id: str, source: Optional[list] = None, cluster: ESCluster = ESCluster.NES, @@ -274,15 +323,18 @@ def get( if source is not None: params["_source_includes"] = ",".join(source) - with httpx.Client() as client: - response = client.get( + client = get_client() + try: + response = await client.get( f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers ) response.raise_for_status() return response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc -def update( +async def update( index: str, doc_id: str, doc: Dict[str, Any], @@ -291,17 +343,20 @@ def update( elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - response = client.post( + client = get_client() + try: + response = await client.post( f"{elasticsearch_url}/{index}/_update/{doc_id}", json={"doc": doc}, headers=headers, ) response.raise_for_status() return response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc -def index_doc( +async def index_doc( index: str, doc_id: str, document: Dict[str, Any], @@ -310,11 +365,14 @@ def index_doc( elasticsearch_url, api_key = _cluster_credentials(cluster) headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - with httpx.Client(timeout=httpx.Timeout(30.0)) as client: - response = client.put( + client = get_client() + try: + response = await client.put( f"{elasticsearch_url}/{index}/_doc/{doc_id}", json=document, headers=headers, ) response.raise_for_status() return response.json() + except Exception as exc: + raise _wrap_exception(exc) from exc diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index e82349d9..6c339764 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -14,7 +14,7 @@ from fastapi.responses import JSONResponse, RedirectResponse from inse.collaboration_network.router import router as collaboration_network_router from inse.company_connections.service import router as company_connections_router -from inse.exceptions import NotFoundException +from inse.exceptions import NotFoundException, ElasticsearchException from inse.funders.service import router as funders_service_router from inse.projects.router import router as projects_router from inse.university_ranking.router import router as university_ranking_router @@ -83,6 +83,12 @@ async def handle_not_found(request: Request, exc: NotFoundException): return JSONResponse(status_code=404, content={"message": str(exc)}) +@app.exception_handler(ElasticsearchException) +async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException): + logger.error("Elasticsearch integration error: %s", str(exc)) + return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"}) + + @app.exception_handler(404) async def redirect(_, __): return RedirectResponse(url="/inse-webapp/")