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/company_connections/logic.py b/service/src/main/inse/company_connections/logic.py index 1ffea295..fa96a1f4 100644 --- a/service/src/main/inse/company_connections/logic.py +++ b/service/src/main/inse/company_connections/logic.py @@ -1,12 +1,9 @@ import logging from typing import Any -import httpx -from fastapi import HTTPException -from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE - from . import model -from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError +from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException +from .search_client import CompanyConnectionsSearchClient logger = logging.getLogger(__name__) @@ -23,22 +20,10 @@ async def get_company_connections_by_author_id( ) -> model.CompanyConnectionsResponse: search_client = client or CompanyConnectionsSearchClient() - try: - author_hit = await search_client.get_openalex_author(author_id) - except MissingApiKeyError as exc: - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Elasticsearch is not configured.", - ) from exc - except httpx.HTTPError as exc: - logger.exception("OpenAlex author lookup failed for %s.", author_id) - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex author lookup failed.", - ) from exc + author_hit = await search_client.get_openalex_author(author_id) if author_hit is None: - raise HTTPException(status_code=404, detail=f"Author {author_id} not found.") + raise NotFoundException(f"Author {author_id} not found.") source = author_hit.get("_source", {}) display_name = _clean(source.get("display_name")) @@ -59,21 +44,9 @@ async def get_company_connections_by_author_id( connections=[], ) - try: - hr_response = await search_client.search_handelsregister_by_officer_name( - display_name - ) - except MissingApiKeyError as exc: - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Elasticsearch is not configured.", - ) from exc - except httpx.HTTPError as exc: - logger.exception("Handelsregister lookup failed for %s.", display_name) - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="Handelsregister lookup failed.", - ) from exc + hr_response = await search_client.search_handelsregister_by_officer_name( + display_name + ) company_count, company_count_relation = _parse_total(hr_response) connections = _parse_company_connections( diff --git a/service/src/main/inse/company_connections/search_client.py b/service/src/main/inse/company_connections/search_client.py index 4516f4f7..b4fe2d1e 100644 --- a/service/src/main/inse/company_connections/search_client.py +++ b/service/src/main/inse/company_connections/search_client.py @@ -5,8 +5,12 @@ import httpx from .. import config -class MissingApiKeyError(Exception): - pass +from inse.integrations import elasticsearch +from inse.model import ESCluster +from inse.exceptions import ElasticsearchNotFoundException + + +from inse.exceptions import MissingApiKeyError class CompanyConnectionsSearchClient: @@ -28,7 +32,7 @@ class CompanyConnectionsSearchClient: api_key if api_key is not None else config.settings.elasticsearch_api_key -) + ) self.openalex_index = openalex_index self.handelsregister_index = handelsregister_index self.timeout = timeout @@ -39,26 +43,15 @@ class CompanyConnectionsSearchClient: return author_id.strip().removeprefix("https://openalex.org/") async def get_openalex_author(self, author_id: str) -> dict[str, Any] | None: - if not self.api_key: - raise MissingApiKeyError("Elasticsearch API key is not configured.") - doc_id = self.openalex_doc_id(author_id) - - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.get( - f"/{self.openalex_index}/_doc/{doc_id}", - headers={"Authorization": f"ApiKey {self.api_key}"}, + try: + return await elasticsearch.get( + index=self.openalex_index, + doc_id=doc_id, + cluster=ESCluster.NES, ) - - if response.status_code == 404: - return None - - response.raise_for_status() - return response.json() + except ElasticsearchNotFoundException: + return None async def search_handelsregister_by_officer_name( self, @@ -66,27 +59,16 @@ class CompanyConnectionsSearchClient: size: int = 10000, track_total_hits: bool = True, ) -> dict[str, Any]: - if not self.api_key: - raise MissingApiKeyError("Elasticsearch API key is not configured.") - payload = self.handelsregister_officer_name_query( officer_name=officer_name, size=size, track_total_hits=track_total_hits, ) - - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{self.handelsregister_index}/_search", - headers={"Authorization": f"ApiKey {self.api_key}"}, - json=payload, - ) - response.raise_for_status() - return response.json() + return await elasticsearch.search( + index=self.handelsregister_index, + body=payload, + cluster=ESCluster.NES, + ) @staticmethod def handelsregister_officer_name_query( diff --git a/service/src/main/inse/exceptions.py b/service/src/main/inse/exceptions.py index 772a9607..c642bca5 100644 --- a/service/src/main/inse/exceptions.py +++ b/service/src/main/inse/exceptions.py @@ -1,3 +1,36 @@ 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 + + +class MissingApiKeyError(Exception): + """Raised when a required API key is missing.""" + pass + + +class UpstreamAPIException(Exception): + """Raised when an upstream third-party service (e.g. REST API) fails.""" + def __init__(self, message: str, status_code: int = 502): + self.message = message + self.status_code = status_code + super().__init__(message) + + +class BadRequestException(Exception): + """Raised when request parameters are invalid or validation fails.""" + pass diff --git a/service/src/main/inse/funders/elastic_search_client.py b/service/src/main/inse/funders/elastic_search_client.py index a411cb0a..08dc6bde 100644 --- a/service/src/main/inse/funders/elastic_search_client.py +++ b/service/src/main/inse/funders/elastic_search_client.py @@ -8,10 +8,11 @@ from typing import Any import httpx from .. import config +from inse.integrations import elasticsearch +from inse.model import ESCluster -class MissingApiKeyError(Exception): - pass +from inse.exceptions import MissingApiKeyError class FundedPublicationsSearchClient: @@ -177,15 +178,8 @@ class FundedPublicationsSearchClient: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{self.index}/_search", - headers={"Authorization": f"ApiKey {self.api_key}"}, - json=payload, - ) - response.raise_for_status() - return response.json() + return await elasticsearch.search( + index=self.index, + body=payload, + cluster=ESCluster.NES, + ) diff --git a/service/src/main/inse/funders/logic.py b/service/src/main/inse/funders/logic.py index 1976a9c8..bad9e46e 100644 --- a/service/src/main/inse/funders/logic.py +++ b/service/src/main/inse/funders/logic.py @@ -6,16 +6,11 @@ import logging from typing import Any -import httpx -from fastapi import HTTPException from pydantic import ValidationError -from starlette.status import HTTP_502_BAD_GATEWAY -from starlette.status import HTTP_503_SERVICE_UNAVAILABLE - from ..persons import logic as person_logic from . import model from .elastic_search_client import FundedPublicationsSearchClient -from .elastic_search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException logger = logging.getLogger(__name__) @@ -62,7 +57,7 @@ async def get_funders_by_author_id( funder_counts: dict[str, dict[str, Any]] = {} normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id) - author_name = _get_author_name(author_id) + author_name = await _get_author_name(author_id) try: _, all_hits = await _fetch_all_author_work_hits( @@ -92,9 +87,9 @@ async def get_funders_by_author_id( ) except ValidationError as exc: logger.exception("Funders response could not be validated for author %s.", author_id) - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="Funders response could not be parsed.", + raise UpstreamAPIException( + message="Funders response could not be parsed.", + status_code=502, ) from exc @@ -144,26 +139,13 @@ async def _search_funded_publications( *, funded_only: bool = False, ) -> dict: - try: - payload = search_client.publications_by_author_query( - author_id, - page, - page_size, - funded_only=funded_only, - ) - return await search_client.search(payload) - except MissingApiKeyError as exc: - logger.error("OpenAlex works Elasticsearch API key is not configured.") - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="OpenAlex works search is not configured.", - ) from exc - except httpx.HTTPError as exc: - logger.exception("OpenAlex works search request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + payload = search_client.publications_by_author_query( + author_id, + page, + page_size, + funded_only=funded_only, + ) + return await search_client.search(payload) def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]: @@ -180,9 +162,9 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]: return total, results -def _get_author_name(author_id: str) -> str | None: +async def _get_author_name(author_id: str) -> str | None: short_author_id = author_id.replace("https://openalex.org/", "") - search_result = person_logic.search_persons(author_id=short_author_id) + search_result = await person_logic.search_persons(author_id=short_author_id) if not search_result.results: return None diff --git a/service/src/main/inse/funders/test_logic.py b/service/src/main/inse/funders/test_logic.py index 234ffdcf..52ff0fdb 100644 --- a/service/src/main/inse/funders/test_logic.py +++ b/service/src/main/inse/funders/test_logic.py @@ -1,8 +1,6 @@ -import json - -import httpx import pytest -from fastapi import HTTPException +from unittest.mock import AsyncMock, patch +from inse.exceptions import MissingApiKeyError from inse.funders import logic from inse.funders.elastic_search_client import FundedPublicationsSearchClient @@ -68,201 +66,177 @@ def _funded_publication_hit( @pytest.mark.anyio -async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - payload = json.loads(request.content.decode("utf-8")) - assert payload["from"] == 0 - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 2}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W1", - funder_id="https://openalex.org/F123", - funder_name="Funder A", - author_position="first", - pdf_url="https://example.org/w1.pdf", - abstract_inverted_index={ - "This": [0], - "is": [1], - "an": [2], - "abstract.": [3], +async def test_get_funders_by_author_id_aggregates_funders_and_awards(): + mock_es_response = { + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Funder A", + author_position="first", + pdf_url="https://example.org/w1.pdf", + abstract_inverted_index={ + "This": [0], + "is": [1], + "an": [2], + "abstract.": [3], + }, + extra_source={ + "title": "Example publication: full detail", + "funders": [ + { + "id": "https://openalex.org/F456", + "display_name": "Funder B", + } + ], + "publication_year": 2020, + "publication_date": "2020-05-10", + "type": "article", + "language": "en", + "cited_by_count": 12, + "is_retracted": False, + "primary_location": { + "pdf_url": "https://example.org/w1.pdf", + "is_oa": True, + "license": "cc-by", + "source": { + "display_name": "Example Journal", + "type": "journal", }, - extra_source={ - "title": "Example publication: full detail", - "funders": [ - { - "id": "https://openalex.org/F456", - "display_name": "Funder B", - } - ], - "publication_year": 2020, - "publication_date": "2020-05-10", - "type": "article", - "language": "en", - "cited_by_count": 12, - "is_retracted": False, - "primary_location": { - "pdf_url": "https://example.org/w1.pdf", - "is_oa": True, - "license": "cc-by", - "source": { - "display_name": "Example Journal", - "type": "journal", - }, - }, - "open_access": { - "is_oa": True, - "oa_status": "gold", - "any_repository_has_fulltext": True, - }, - "primary_topic": { - "display_name": "Clinical Trials", - "subfield": {"display_name": "Medicine"}, - "field": {"display_name": "Health Sciences"}, - "domain": {"display_name": "Life Sciences"}, - }, - "topics": [ - {"display_name": "Trials", "score": 0.8}, - {"display_name": "Guidelines", "score": 0.6}, - ], - "keywords": [ - {"display_name": "randomised trials", "score": 0.9}, - {"display_name": "reporting guideline", "score": 0.7}, - ], - "counts_by_year": [ - {"year": 2024, "cited_by_count": 3}, - {"year": 2023, "cited_by_count": 2}, - ], - }, - ), - _funded_publication_hit( - "https://openalex.org/W2", - funder_id=None, - funder_name=None, - award_funder_id="https://openalex.org/F123", - award_funder_name="Funder A", - award_display_name="Project Grant", - award_number="PG-42", - author_position="last", - ), - ], - }, - }, - ) + }, + "open_access": { + "is_oa": True, + "oa_status": "gold", + "any_repository_has_fulltext": True, + }, + "primary_topic": { + "display_name": "Clinical Trials", + "subfield": {"display_name": "Medicine"}, + "field": {"display_name": "Health Sciences"}, + "domain": {"display_name": "Life Sciences"}, + }, + "topics": [ + {"display_name": "Trials", "score": 0.8}, + {"display_name": "Guidelines", "score": 0.6}, + ], + "keywords": [ + {"display_name": "randomised trials", "score": 0.9}, + {"display_name": "reporting guideline", "score": 0.7}, + ], + "counts_by_year": [ + {"year": 2024, "cited_by_count": 3}, + {"year": 2023, "cited_by_count": 2}, + ], + }, + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + award_funder_id="https://openalex.org/F123", + award_funder_name="Funder A", + award_display_name="Project Grant", + award_number="PG-42", + author_position="last", + ), + ], + }, + } - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type( - "Result", - (), - {"results": [type("Author", (), {"display_name": "Example Author"})()]}, - )(), - ) + mock_author_result = type( + "Result", + (), + {"results": [type("Author", (), {"display_name": "Example Author"})()]} + )() - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - response = await logic.get_funders_by_author_id("A5023888391", client=client) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - assert response.author_id == "https://openalex.org/A5023888391" - assert response.author_name == "Example Author" - assert response.funder_count == 2 - assert response.funders[0].funder_id == "https://openalex.org/F123" - assert response.funders[0].funder_name == "Funder A" - assert response.funders[0].publication_count == 2 - assert response.funders[0].author_position_count.first == 1 - assert response.funders[0].author_position_count.last == 1 - assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"] - assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"] - assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf" - assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2" - publication_detail = response.funders[0].publication_details["https://openalex.org/W1"] - assert publication_detail.title == "Example publication: full detail" - assert publication_detail.funder_names == ["Funder A", "Funder B"] - assert publication_detail.abstract == "This is an abstract." - assert publication_detail.publication_date == "2020-05-10" - assert publication_detail.publication_type == "article" - assert publication_detail.source_name == "Example Journal" - assert publication_detail.source_type == "journal" - assert publication_detail.is_open_access is True - assert publication_detail.open_access_status == "gold" - assert publication_detail.has_fulltext is True - assert publication_detail.license == "cc-by" - assert publication_detail.cited_by_count == 12 - assert publication_detail.primary_topic == "Clinical Trials" - assert publication_detail.topic_field == "Health Sciences" - assert publication_detail.topic_subfield == "Medicine" - assert publication_detail.topic_domain == "Life Sciences" - assert publication_detail.topics == ["Trials", "Guidelines"] - assert publication_detail.keywords == ["randomised trials", "reporting guideline"] - assert publication_detail.counts_by_year == [ - {"year": 2024, "cited_by_count": 3}, - {"year": 2023, "cited_by_count": 2}, - ] - assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [ - "Project Grant" - ] + assert response.author_id == "https://openalex.org/A5023888391" + assert response.author_name == "Example Author" + assert response.funder_count == 2 + + funder_a = next(f for f in response.funders if f.funder_id == "https://openalex.org/F123") + assert funder_a.funder_name == "Funder A" + assert funder_a.publication_count == 2 + assert funder_a.author_position_count.first == 1 + assert funder_a.author_position_count.last == 1 + assert funder_a.publication_ids.first == ["https://openalex.org/W1"] + assert funder_a.publication_ids.last == ["https://openalex.org/W2"] + assert funder_a.publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf" + assert funder_a.publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2" + + pub1_detail = funder_a.publication_details["https://openalex.org/W1"] + assert pub1_detail.title == "Example publication: full detail" + assert pub1_detail.funder_names == ["Funder A", "Funder B"] + assert pub1_detail.abstract == "This is an abstract." + assert pub1_detail.publication_date == "2020-05-10" + assert pub1_detail.publication_type == "article" + assert pub1_detail.source_name == "Example Journal" + assert pub1_detail.source_type == "journal" + assert pub1_detail.is_open_access is True + assert pub1_detail.open_access_status == "gold" + assert pub1_detail.has_fulltext is True + assert pub1_detail.license == "cc-by" + assert pub1_detail.cited_by_count == 12 + assert pub1_detail.primary_topic == "Clinical Trials" + assert pub1_detail.topic_field == "Health Sciences" + assert pub1_detail.topic_subfield == "Medicine" + assert pub1_detail.topic_domain == "Life Sciences" + assert pub1_detail.topics == ["Trials", "Guidelines"] + assert pub1_detail.keywords == ["randomised trials", "reporting guideline"] + assert pub1_detail.counts_by_year == [ + {"year": 2024, "cited_by_count": 3}, + {"year": 2023, "cited_by_count": 2}, + ] + assert funder_a.publication_details["https://openalex.org/W2"].grant_labels == ["Project Grant"] @pytest.mark.anyio -async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 1}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W3", - funder_id="https://openalex.org/F123", - funder_name="Funder A", - award_funder_id="https://openalex.org/F123", - award_funder_name="Funder A", - award_display_name=None, - award_number="ANR-12-1234", - ), - ], - }, - }, - ) +async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(): + mock_es_response = { + "hits": { + "total": {"value": 1}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W3", + funder_id="https://openalex.org/F123", + funder_name="Funder A", + award_funder_id="https://openalex.org/F123", + award_funder_name="Funder A", + award_display_name=None, + award_number="ANR-12-1234", + ), + ], + }, + } + mock_author_result = type("Result", (), {"results": [type("Author", (), {"display_name": "Example Author"})()]})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type( - "Result", - (), - {"results": [type("Author", (), {"display_name": "Example Author"})()]}, - )(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - response = await logic.get_funders_by_author_id("A5023888391", client=client) - - assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == [] + assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == [] @pytest.mark.anyio -async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch): +async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(): requested_pages: list[int] = [] - def handler(request: httpx.Request) -> httpx.Response: - payload = json.loads(request.content.decode("utf-8")) - size = payload["size"] - offset = payload["from"] + async def mock_search_func(index, body, cluster=None): + size = body["size"] + offset = body["from"] page = offset // size + 1 requested_pages.append(page) total = size + 1 @@ -284,115 +258,87 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(m ) ] - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": total}, - "hits": hits, - }, + return { + "hits": { + "total": {"value": total}, + "hits": hits, }, - ) + } - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + mock_author_result = type("Result", (), {"results": []})() - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + with patch("inse.integrations.elasticsearch.search", side_effect=mock_search_func) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search_persons.return_value = mock_author_result - response = await logic.get_funders_by_author_id("A5023888391", client=client) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5023888391", client=client) - assert requested_pages == [1, 2] - assert response.funder_count > 1 - funder_names = {funder.funder_name for funder in response.funders} - assert "Funder 1" in funder_names + assert requested_pages == [1, 2] + assert response.funder_count > 1 + funder_names = {funder.funder_name for funder in response.funders} + assert "Funder 1" in funder_names @pytest.mark.anyio -async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "hits": { - "total": {"value": 2}, - "hits": [ - _funded_publication_hit( - "https://openalex.org/W1", - funder_id="https://openalex.org/F123", - funder_name="Bundesministerium", - ), - _funded_publication_hit( - "https://openalex.org/W2", - funder_id=None, - funder_name=None, - ), - ], - }, - }, - ) +async def test_get_funders_by_author_id_ignores_publications_without_funders(): + mock_es_response = { + "hits": { + "total": {"value": 2}, + "hits": [ + _funded_publication_hit( + "https://openalex.org/W1", + funder_id="https://openalex.org/F123", + funder_name="Bundesministerium", + ), + _funded_publication_hit( + "https://openalex.org/W2", + funder_id=None, + funder_name=None, + ), + ], + }, + } + mock_author_result = type("Result", (), {"results": []})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5093075883", client=client) - response = await logic.get_funders_by_author_id("A5093075883", client=client) - - assert response.funder_count == 1 - assert response.funders[0].funder_name == "Bundesministerium" - assert response.funders[0].publication_count == 1 + assert response.funder_count == 1 + assert response.funders[0].funder_name == "Bundesministerium" + assert response.funders[0].publication_count == 1 @pytest.mark.anyio -async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={"hits": {"total": {"value": 0}, "hits": []}}, - ) +async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(): + mock_es_response = {"hits": {"total": {"value": 0}, "hits": []}} + mock_author_result = type("Result", (), {"results": []})() - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \ + patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search.return_value = mock_es_response + mock_search_persons.return_value = mock_author_result - client = FundedPublicationsSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + client = FundedPublicationsSearchClient(api_key="test-key") + response = await logic.get_funders_by_author_id("A5093075883", client=client) - response = await logic.get_funders_by_author_id("A5093075883", client=client) - - assert response.funder_count == 0 - assert response.funders == [] + assert response.funder_count == 0 + assert response.funders == [] @pytest.mark.anyio -async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch): - monkeypatch.setattr( - logic.person_logic, - "search_persons", - lambda author_id: type("Result", (), {"results": []})(), - ) - client = FundedPublicationsSearchClient(api_key="") +async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(): + mock_author_result = type("Result", (), {"results": []})() - with pytest.raises(HTTPException) as exc: - await logic.get_funders_by_author_id("A5023888391", client=client) + with patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons: + mock_search_persons.return_value = mock_author_result - assert exc.value.status_code == 503 + client = FundedPublicationsSearchClient(api_key="") + + with pytest.raises(MissingApiKeyError): + await logic.get_funders_by_author_id("A5023888391", client=client) diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 0e86c8de..975d6c4d 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -20,7 +20,7 @@ class InstitutionsSearchClient: """ pass - def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution: + async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution: """Retrieves an institution by its raw OpenAlex institution ID. Args: @@ -38,7 +38,7 @@ class InstitutionsSearchClient: } } - res = elasticsearch.search(index="openalex-institutions", query=query, size=1) + res = await elasticsearch.search(index="openalex-institutions", query=query, size=1) hits = res.get("hits", {}).get("hits", []) if not hits: @@ -72,7 +72,7 @@ class InstitutionsSearchClient: # TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache. return cache.get(raw_institution_id) - def get_institutions_by_name( + async def get_institutions_by_name( self, name: str, page: int = 0, @@ -122,7 +122,7 @@ class InstitutionsSearchClient: query, ) try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-institutions", offset=page * size, size=size, @@ -189,7 +189,7 @@ class InstitutionsSearchClient: query, ) - res = elasticsearch.search(index="openalex-authors", query=query) + res = await elasticsearch.search(index="openalex-authors", query=query) hits = res.get("hits", {}).get("hits", []) # Extracting display_name directly from the author document source @@ -200,7 +200,7 @@ class InstitutionsSearchClient: } return list(authors) - def search_institutions( + async def search_institutions( self, query_text: str, country_code: str | None = None, @@ -265,7 +265,7 @@ class InstitutionsSearchClient: } } - res = elasticsearch.search( + res = await elasticsearch.search( index="openalex-institutions", query=query, size=limit, @@ -288,7 +288,7 @@ class InstitutionsSearchClient: return [Institution.from_dict(hit["_source"]) for hit in hits] - def get_institution_aliases_by_oa_institution_id( + async def get_institution_aliases_by_oa_institution_id( self, raw_oa_institution_id: str ) -> List[str]: """Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases. @@ -299,7 +299,7 @@ class InstitutionsSearchClient: Returns: List[str]: A list of aliases for the given institution ID. """ - institution = self.get_institution_by_id(raw_oa_institution_id) + institution = await self.get_institution_by_id(raw_oa_institution_id) aliases = list( self.augment_aliases(set(institution.display_name_alternatives or [])) | self.get_predefined_institution_aliases(raw_oa_institution_id) @@ -426,7 +426,7 @@ class InstitutionsSearchClient: ) return None - def get_cordis_eu_organisation_ids_by_oa_institution_id( + async def get_cordis_eu_organisation_ids_by_oa_institution_id( self, raw_oa_institution_id: str ) -> Optional[List[str]]: """Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices. @@ -439,7 +439,7 @@ class InstitutionsSearchClient: """ institution_aliases = set( - self.get_institution_aliases_by_oa_institution_id( + await self.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id=raw_oa_institution_id ) ) @@ -476,7 +476,7 @@ class InstitutionsSearchClient: try: # IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results - response = elasticsearch.search( + response = await elasticsearch.search( index="cordis_eu_*_organizations", body=body, cluster="inse" ) except Exception as e: diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index 10f53cc6..d001c646 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -9,10 +9,8 @@ from copy import deepcopy from typing import Any, Optional import httpx -from fastapi import HTTPException from pydantic import ValidationError -from starlette.status import HTTP_400_BAD_REQUEST -from starlette.status import HTTP_502_BAD_GATEWAY +from inse.exceptions import UpstreamAPIException, BadRequestException from inse.models.openalex.autocomplete_response import AutocompleteResponse from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta @@ -41,7 +39,7 @@ _VALID_INSTITUTION_TYPES = { async def get_institution_by_id( raw_institution_id: str, client: InstitutionsSearchClient ) -> Institution: - return client.get_institution_by_id(raw_institution_id) + return await client.get_institution_by_id(raw_institution_id) async def list_institutions( @@ -58,10 +56,7 @@ async def list_institutions( client: OpenAlexInstitutionsClient | None = None, ) -> InstitutionsListResponse: if sample is not None and (sort or page not in (None, 1)): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail="sample cannot be combined with sort or page.", - ) + raise BadRequestException("sample cannot be combined with sort or page.") openalex_client = client or OpenAlexInstitutionsClient() @@ -86,12 +81,12 @@ async def list_institutions( except ValueError: if exc.response.text: detail = exc.response.text - raise HTTPException(status_code=status_code, detail=detail) from exc + raise UpstreamAPIException(message=detail, status_code=status_code) from exc except httpx.HTTPError as exc: logger.exception("OpenAlex institutions request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex institutions request failed.", + raise UpstreamAPIException( + message="OpenAlex institutions request failed.", + status_code=502, ) from exc try: @@ -102,9 +97,9 @@ async def list_institutions( ) except ValidationError as exc: logger.exception("OpenAlex institutions response could not be parsed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex institutions response could not be parsed.", + raise UpstreamAPIException( + message="OpenAlex institutions response could not be parsed.", + status_code=502, ) from exc @@ -120,7 +115,7 @@ async def autocomplete_institutions( Returns institution options for autocomplete inputs using the local Elasticsearch cluster via the provided client. """ - institutions = client.search_institutions( + institutions = await client.search_institutions( query_text=query, country_code=country_code, institution_type=institution_type, diff --git a/service/src/main/inse/institutions/router.py b/service/src/main/inse/institutions/router.py index 423281c0..2709e4d9 100644 --- a/service/src/main/inse/institutions/router.py +++ b/service/src/main/inse/institutions/router.py @@ -72,7 +72,7 @@ async def search_institutions_by_name( ), ] = "asc", ) -> InstitutionPage: - return client.get_institutions_by_name( + return await client.get_institutions_by_name( name=name, page=page, size=size, diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index bebf52c0..11544b19 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -1,6 +1,6 @@ import httpx import pytest -from fastapi import HTTPException +from inse.exceptions import BadRequestException from inse.institutions import logic from inse.institutions.search_client import OpenAlexInstitutionsClient @@ -96,11 +96,9 @@ async def test_list_institutions_maps_openalex_response_to_model(): @pytest.mark.anyio async def test_list_institutions_rejects_sample_with_sort(): - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(BadRequestException) as exc_info: await logic.list_institutions(sample=10, sort="works_count:desc") - assert exc_info.value.status_code == 400 - @pytest.mark.anyio async def test_list_institutions_accepts_practical_openalex_type_variants(): diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index c7343e50..803aa212 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,13 +1,37 @@ 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, + MissingApiKeyError, +) 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,22 +45,23 @@ 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 or not config.settings.elasticsearch_api_key ): - raise ValueError( + raise MissingApiKeyError( "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 ( not config.settings.elasticsearch_inse_url or not config.settings.elasticsearch_inse_api_key ): - raise ValueError( + raise MissingApiKeyError( "Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'" ) @@ -80,8 +105,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 +147,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 +192,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 +324,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 +344,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 +366,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/logic.py b/service/src/main/inse/logic.py index 19e9dda3..bc3edcf6 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -18,6 +18,7 @@ import json from . import schema from . import model from . import config +from inse.integrations import elasticsearch from inse.models.openalex.topic import Topic @@ -103,56 +104,42 @@ def _load_topic_cache() -> dict: return {} -def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict: +async def build_topic_cache(save_json: bool = True) -> dict: """ Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task). Arguments: - page_size (int): Number of topics to fetch per request (default: 200) save_json (bool): Whether to save the cache as a JSON file (default: True) Returns: taxonomy_cache (dict): The topic hierarchy dictionary. """ output_filename: str = "topic_hierarchy_cache.json" - headers = { - "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", - "Content-Type": "application/json", - } taxonomy_cache = {} - offset = 0 - with httpx.Client(timeout=30.0) as client: - while True: - payload = {"query": {"match_all": {}}, "from": offset, "size": page_size} - response = client.post( - config.settings.elasticsearch_url + "/openalex-topics/_search", - json=payload, - headers=headers, - ) - response.raise_for_status() - data = response.json() + try: + async for hit in elasticsearch.scan( + index="openalex-topics", + query={"match_all": {}}, + source=["display_name", "name", "id", "subfield", "field", "domain"], + cluster="nes", + ): + source = hit.get("_source", {}) + topic_name = source.get("display_name") or source.get("name") + if not topic_name: + continue - hits = data.get("hits", {}).get("hits", []) - if not hits: - break + taxonomy_cache[topic_name] = { + "topic_id": source.get("id") or hit.get("_id", ""), + "subfield": source.get("subfield", {}).get("display_name", ""), + "field": source.get("field", {}).get("display_name", ""), + "domain": source.get("domain", {}).get("display_name", ""), + } + except Exception as exc: + logger.error("Failed to scan topics from Elasticsearch: %s", exc) - for hit in hits: - source = hit.get("_source", {}) - topic_name = source.get("display_name") or source.get("name") - if not topic_name: - continue - - taxonomy_cache[topic_name] = { - "topic_id": source.get("id") or hit.get("_id", ""), - "subfield": source.get("subfield", {}).get("display_name", ""), - "field": source.get("field", {}).get("display_name", ""), - "domain": source.get("domain", {}).get("display_name", ""), - } - - offset += len(hits) - logger.info("Processed %s topics total", len(taxonomy_cache)) + logger.info("Processed %s topics total", len(taxonomy_cache)) if save_json: data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index e82349d9..3af016e5 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -14,7 +14,13 @@ 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, + MissingApiKeyError, + UpstreamAPIException, + BadRequestException, +) 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 @@ -78,11 +84,37 @@ app.add_middleware( ) +# exception handlers + @app.exception_handler(NotFoundException) 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(MissingApiKeyError) +async def handle_missing_api_key(request: Request, exc: MissingApiKeyError): + logger.error("Configuration error: %s", str(exc)) + return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"}) + + +@app.exception_handler(UpstreamAPIException) +async def handle_upstream_api_error(request: Request, exc: UpstreamAPIException): + logger.error("Upstream API error: %s", str(exc)) + return JSONResponse(status_code=exc.status_code, content={"message": exc.message}) + + +@app.exception_handler(BadRequestException) +async def handle_bad_request(request: Request, exc: BadRequestException): + logger.error("Bad Request: %s", str(exc)) + return JSONResponse(status_code=400, content={"message": str(exc)}) + + @app.exception_handler(404) async def redirect(_, __): return RedirectResponse(url="/inse-webapp/") diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index b6b9d5fe..77cf31a0 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -8,8 +8,7 @@ import json import logging import re -from fastapi import HTTPException -from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR +from inse.exceptions import ElasticsearchException from ..integrations import elasticsearch, llm from ..persons.logic import find_ude_author_by_name, get_author_name_by_id @@ -36,7 +35,7 @@ RELATED_TOPIC_K = 1 EXACT_ID_CAP = 1000 -def get_news_page( +async def get_news_page( page: int, page_size: int, sort_order: str = "desc", @@ -46,10 +45,10 @@ def get_news_page( ) -> NewsPage: offset = (page - 1) * page_size - clauses = _filter_clauses(year_from, year_to, relevance_values) + clauses = await _filter_clauses(year_from, year_to, relevance_values) query = {"bool": {"filter": clauses}} if clauses else {"match_all": {}} - response = _run_search( + response = await _run_search( query=query, source=["date", "maintitle", "author", "url", "intro_content", "full_content"], size=page_size, @@ -57,10 +56,10 @@ def get_news_page( sort=[{"date_full": sort_order}], ) - return _build_page(response, page, page_size) + return await _build_page(response, page, page_size) -def search_news( +async def search_news( query_text: str, page: int, page_size: int, @@ -78,14 +77,14 @@ def search_news( } # Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage). - clauses = _filter_clauses(year_from, year_to, relevance_values) + clauses = await _filter_clauses(year_from, year_to, relevance_values) exact_query = { "bool": { "must": [{"match": {"full_content": query_text}}], "filter": clauses, } } - response = _run_search( + response = await _run_search( query=exact_query, source=["date", "maintitle", "author", "url"], size=page_size, @@ -94,19 +93,20 @@ def search_news( highlight=highlight, ) - news_page = _build_page(response, page, page_size) + news_page = await _build_page(response, page, page_size) if _is_last_page(page, page_size, news_page.total): - exclude_ids = _exact_match_ids(exact_query) + exclude_ids = await _exact_match_ids(exact_query) news_page.results.extend( - _related_articles( + await _related_articles( query_text, exclude_ids=exclude_ids, extra_filters=clauses ) ) return news_page -def get_news_by_author( + +async def get_news_by_author( author_id: str, page: int = 1, page_size: int = 10, @@ -114,11 +114,11 @@ def get_news_by_author( query_text: str | None = None, ) -> NewsPage: - author_name = get_author_name_by_id(author_id) + author_name = await get_author_name_by_id(author_id) if not author_name: return _empty_page(page, page_size) - news_ids = _find_news_ids_for_author(author_name) + news_ids = await _find_news_ids_for_author(author_name) if not news_ids: return _empty_page(page, page_size) @@ -129,7 +129,7 @@ def get_news_by_author( ] offset = (page - 1) * page_size - response = _run_search( + response = await _run_search( query=es_query, source=["date", "maintitle", "author", "url"], size=page_size, @@ -137,12 +137,12 @@ def get_news_by_author( sort=[{"date_full": sort_order}], ) - news_page = _build_page(response, page, page_size) + news_page = await _build_page(response, page, page_size) if query_text and _is_last_page(page, page_size, news_page.total): - exclude_ids = _exact_match_ids(es_query) + exclude_ids = await _exact_match_ids(es_query) news_page.results.extend( - _related_articles( + await _related_articles( query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids ) ) @@ -150,7 +150,7 @@ def get_news_by_author( return news_page -def _filter_clauses( +async def _filter_clauses( year_from: int | None, year_to: int | None, relevance_values: list | None, @@ -165,14 +165,14 @@ def _filter_clauses( date_range["lte"] = year_to clauses.append({"range": {"date_year": date_range}}) - relevant_ids = _relevance_news_ids(relevance_values) + relevant_ids = await _relevance_news_ids(relevance_values) if relevant_ids is not None: clauses.append({"ids": {"values": relevant_ids}}) return clauses -def _relevance_news_ids(relevance_values: list | None) -> list | None: +async def _relevance_news_ids(relevance_values: list | None) -> list | None: selected = set(relevance_values or []) if not selected or {"relevant", "not_relevant"} <= selected: @@ -182,7 +182,7 @@ def _relevance_news_ids(relevance_values: list | None) -> list | None: news_ids = [] try: - for hit in elasticsearch.scan( + async for hit in elasticsearch.scan( index="aktuell_postproc", query={"term": {"relevant": relevant_value}}, source=["news_id"], @@ -198,10 +198,10 @@ def _relevance_news_ids(relevance_values: list | None) -> list | None: return news_ids -def _find_news_ids_for_author(author_name: str) -> list: +async def _find_news_ids_for_author(author_name: str) -> list: try: - response = elasticsearch.search( + response = await elasticsearch.search( index="aktuell_postproc", query={"term": {"authors.keyword": author_name}}, source=["news_id"], @@ -225,26 +225,23 @@ def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage: return NewsPage(total=0, page=page, page_size=page_size, results=[]) -def get_news_by_id(news_id: str) -> NewsArticleDetail: +async def get_news_by_id(news_id: str) -> NewsArticleDetail: try: - response = elasticsearch.get( + response = await elasticsearch.get( index="aktuell", doc_id=news_id, source=["date", "maintitle", "author", "url", "full_content"], cluster="inse", ) - except Exception as exc: + except ElasticsearchException as exc: logger.exception("Abruf des News-Artikels fehlgeschlagen.") - raise HTTPException( - status_code=HTTP_500_INTERNAL_SERVER_ERROR, - detail="Etwas ist schiefgelaufen.", - ) from exc + raise source = response.get("_source", {}) - relevant, authors, cached_keywords, postproc_id = _get_postproc_labels(news_id) - topics = _get_article_topics(source.get("maintitle"), source.get("full_content")) - keywords = _get_article_keywords( + relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id) + topics = await _get_article_topics(source.get("maintitle"), source.get("full_content")) + keywords = await _get_article_keywords( news_id, postproc_id, cached_keywords, @@ -260,24 +257,24 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail: url=source.get("url"), full_content=source.get("full_content"), relevant=relevant, - authors=_build_mentioned_persons(authors), + authors=await _build_mentioned_persons(authors), topics=topics, keywords=keywords, ) -def _get_article_topics(maintitle: str | None, full_content: str | None) -> list: +async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list: query = " ".join( part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part ).strip() if not query: return [] - topics = _topic_vector_search(query, TOPIC_LIMIT, ["display_name"]) + topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"]) return [topic["display_name"] for topic in topics if topic.get("display_name")] -def _get_article_keywords( +async def _get_article_keywords( news_id: str, postproc_id: str | None, cached_keywords: list, @@ -301,7 +298,7 @@ def _get_article_keywords( keywords = _parse_keywords(raw) if keywords: - _store_keywords(news_id, postproc_id, keywords) + await _store_keywords(news_id, postproc_id, keywords) return keywords @@ -326,17 +323,17 @@ def _parse_keywords(raw: str) -> list: return keywords[:KEYWORD_LIMIT] -def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None: +async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None: try: if postproc_id: - elasticsearch.update( + await elasticsearch.update( index="aktuell_postproc", doc_id=postproc_id, doc={"keywords": keywords}, cluster="inse", ) else: - elasticsearch.index_doc( + await elasticsearch.index_doc( index="aktuell_postproc", doc_id=news_id, document={"news_id": news_id, "keywords": keywords}, @@ -346,7 +343,7 @@ def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> No logger.exception(f"Failed to cache keywords for {news_id}.") -def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: +async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: try: from ..util import get_model @@ -356,7 +353,7 @@ def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: return [] try: - response = elasticsearch.search( + response = await elasticsearch.search( index="topicvectors", body={ "knn": { @@ -378,13 +375,13 @@ def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list: return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])] -def _build_mentioned_persons(author_names: list) -> list: +async def _build_mentioned_persons(author_names: list) -> list: ude_persons = [] other_persons = [] for name in author_names: - match = find_ude_author_by_name(name) + match = await find_ude_author_by_name(name) if match: ude_persons.append( MentionedPerson(name=name, is_ude=True, person_id=match["id"]) @@ -395,9 +392,9 @@ def _build_mentioned_persons(author_names: list) -> list: return ude_persons + other_persons -def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]: +async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]: try: - response = elasticsearch.search( + response = await elasticsearch.search( index="aktuell_postproc", query={"term": {"news_id.keyword": news_id}}, source=["relevant", "authors", "keywords"], @@ -421,9 +418,9 @@ def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | N return relevant, authors, keywords, hit.get("_id") -def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: +async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict: try: - return elasticsearch.search( + return await elasticsearch.search( index="aktuell", query=query, source=source, @@ -434,15 +431,12 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort, highlig highlight=highlight, cluster="inse", ) - except Exception as exc: + except ElasticsearchException as exc: logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.") - raise HTTPException( - status_code=HTTP_500_INTERNAL_SERVER_ERROR, - detail="Etwas ist schiefgelaufen.", - ) from exc + raise -def _build_page(response: dict, page: int, page_size: int) -> NewsPage: +async def _build_page(response: dict, page: int, page_size: int) -> NewsPage: hits_section = response.get("hits", {}) total = hits_section.get("total", {}).get("value", 0) hits = hits_section.get("hits", []) @@ -453,7 +447,7 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage: if news_id: news_ids.append(news_id) - relevance_map = _get_relevance_map(news_ids) + relevance_map = await _get_relevance_map(news_ids) articles = [] for hit in hits: @@ -469,12 +463,12 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage: ) -def _get_relevance_map(news_ids: list) -> dict: +async def _get_relevance_map(news_ids: list) -> dict: if not news_ids: return {} try: - response = elasticsearch.search( + response = await elasticsearch.search( index="aktuell_postproc", query={"terms": {"news_id.keyword": news_ids}}, source=["news_id", "relevant"], @@ -499,7 +493,7 @@ def _parse_hit(hit: dict) -> NewsArticle: source = hit.get("_source", {}) fragments = hit.get("highlight", {}).get("full_content") - + if fragments: snippet = fragments[0] else: @@ -517,7 +511,7 @@ def _parse_hit(hit: dict) -> NewsArticle: def _make_preview(source: dict) -> str | None: text = source.get("intro_content") or source.get("full_content") - + if not text: return None @@ -534,9 +528,9 @@ def _is_last_page(page: int, page_size: int, total: int) -> bool: return page * page_size >= total -def _exact_match_ids(query: dict) -> list: +async def _exact_match_ids(query: dict) -> list: try: - response = _run_search( + response = await _run_search( query=query, source=[], size=EXACT_ID_CAP, @@ -554,14 +548,14 @@ def _exact_match_ids(query: dict) -> list: ] -def _related_articles( +async def _related_articles( query_text: str, exclude_ids: list | None = None, filter_news_ids: list | None = None, extra_filters: list | None = None, k: int = RELATED_BLOCK_SIZE, ) -> list: - related_terms = _related_search_terms(query_text) + related_terms = await _related_search_terms(query_text) if not related_terms: return [] @@ -577,7 +571,7 @@ def _related_articles( bool_query.setdefault("filter", []).extend(extra_filters) try: - response = elasticsearch.search( + response = await elasticsearch.search( index="aktuell", query={"bool": bool_query}, source=["date", "maintitle", "author", "url", "intro_content", "full_content"], @@ -595,15 +589,15 @@ def _related_articles( article.related = True articles.append(article) - relevance_map = _get_relevance_map([article.id for article in articles]) + relevance_map = await _get_relevance_map([article.id for article in articles]) for article in articles: article.relevant = relevance_map.get(article.id) return articles -def _related_search_terms(query_text: str) -> list: - topics = _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"]) +async def _related_search_terms(query_text: str) -> list: + topics = await _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"]) seen = {query_text.lower()} terms = [] diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index dcbf1b2d..b183d6fa 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -34,7 +34,7 @@ def _parse_relevance(relevance: str | None) -> list: summary="Returns a page of news articles, newest first.", tags=[Tags.NEWS], ) -def list_news( +async def list_news( page: Annotated[ int, Query(description="Page number (1-based).", ge=1) ] = 1, @@ -54,7 +54,7 @@ def list_news( int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0) ] = None, ): - return logic.get_news_page( + return await logic.get_news_page( page, page_size, sort_order, @@ -72,7 +72,7 @@ def list_news( summary="Searches news articles by full text (full_content).", tags=[Tags.NEWS], ) -def search_news( +async def search_news( query: Annotated[ str, Query(description="Search term, matched against the full text (full_content).", min_length=1) ], @@ -92,7 +92,7 @@ def search_news( int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0) ] = None, ): - return logic.search_news( + return await logic.search_news( query, page, page_size, @@ -110,7 +110,7 @@ def search_news( summary="Returns news articles in which the given person is mentioned.", tags=[Tags.NEWS], ) -def get_news_by_author( +async def get_news_by_author( author_id: Annotated[ str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.") ], @@ -127,7 +127,7 @@ def get_news_by_author( str | None, Query(description="Optional search term, matched against title/author.") ] = None, ): - return logic.get_news_by_author(author_id, page, page_size, sort_order, query) + return await logic.get_news_by_author(author_id, page, page_size, sort_order, query) @router.get( @@ -138,9 +138,9 @@ def get_news_by_author( summary="Returns a single news article including its full content.", tags=[Tags.NEWS], ) -def get_news_by_id( +async def get_news_by_id( news_id: Annotated[ str, Path(description="The unique id of the news article (Elasticsearch _id).") ], ): - return logic.get_news_by_id(news_id) + return await logic.get_news_by_id(news_id) diff --git a/service/src/main/inse/patents/elastic_search_all_patents_client.py b/service/src/main/inse/patents/elastic_search_all_patents_client.py index 4584f40b..bdca70f5 100644 --- a/service/src/main/inse/patents/elastic_search_all_patents_client.py +++ b/service/src/main/inse/patents/elastic_search_all_patents_client.py @@ -8,7 +8,10 @@ from typing import Any import httpx from .. import config -from .elastic_search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError + +from inse.integrations import elasticsearch +from inse.model import ESCluster EPO_INDEX = "epo_index_1.0" USPTO_INDEX = "uspto_patents_3.0" @@ -119,15 +122,4 @@ class AllPatentsSearchClient: return await self._search(USPTO_INDEX, payload) async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{index}/_search", - headers=self._headers(), - json=payload, - ) - response.raise_for_status() - return response.json() \ No newline at end of file + return await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE) \ No newline at end of file diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py index 698e9d84..a7860f4d 100644 --- a/service/src/main/inse/patents/elastic_search_client.py +++ b/service/src/main/inse/patents/elastic_search_client.py @@ -27,8 +27,7 @@ def _match_name_field(field: str, name: str) -> dict[str, Any]: } -class MissingApiKeyError(Exception): - pass +from inse.exceptions import MissingApiKeyError class PatentSearchClient: @@ -172,7 +171,7 @@ class PatentSearchClient: return await self._search(ESIndex.USPTO_INDEX, payload) async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]: - response = elasticsearch.search(index=index,body=payload,cluster=ESCluster.INSE) + response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE) return response async def get_by_id_or_title( diff --git a/service/src/main/inse/patents/ipc_search_client.py b/service/src/main/inse/patents/ipc_search_client.py index 6ab6afa4..834b82af 100644 --- a/service/src/main/inse/patents/ipc_search_client.py +++ b/service/src/main/inse/patents/ipc_search_client.py @@ -11,11 +11,14 @@ import httpx from .. import config from . import model -from .elastic_search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError from .ipc_lookup import IpcHierarchyKeys from .ipc_lookup import build_ipc_classification from .ipc_lookup import parse_ipc_symbol +from inse.integrations import elasticsearch +from inse.model import ESCluster + IPC_INDEX = "ipc" _LEVELS: tuple[tuple[str, str, str], ...] = ( @@ -136,15 +139,4 @@ class IpcSearchClient: return found async def _search(self, payload: dict[str, Any]) -> dict[str, Any]: - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{IPC_INDEX}/_search", - headers=self._headers(), - json=payload, - ) - response.raise_for_status() - return response.json() + return await elasticsearch.search(index=IPC_INDEX, body=payload, cluster=ESCluster.INSE) diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py index d6fe29d5..9ff5b490 100644 --- a/service/src/main/inse/patents/logic.py +++ b/service/src/main/inse/patents/logic.py @@ -7,15 +7,11 @@ import logging import asyncio import httpx -from fastapi import HTTPException -from starlette.status import HTTP_502_BAD_GATEWAY -from starlette.status import HTTP_503_SERVICE_UNAVAILABLE -from starlette.status import HTTP_404_NOT_FOUND from ..persons import logic as person_logic from ..models.openalex.author import Author from . import model -from .elastic_search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError, ElasticsearchException from .elastic_search_client import PatentSearchClient from .elastic_search_all_patents_client import AllPatentsSearchClient from .ipc_search_client import IpcSearchClient @@ -55,7 +51,7 @@ async def get_patents_by_author_id( search_client = client or PatentSearchClient() ipc_search_client = ipc_client or IpcSearchClient() - author = _get_author(author_id) + author = await _get_author(author_id) if not author: return model.PatentsByAuthorResponse( author_id=author_id, @@ -76,16 +72,9 @@ async def get_patents_by_author_id( patents=[], ) - try: - epo_data, uspto_data = await _search_both_indices( - search_client, last_name, first_name - ) - except MissingApiKeyError as exc: - raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Patent search is not configured.") from exc - except httpx.HTTPError as exc: - raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, - detail="Patent search request failed.") from exc + epo_data, uspto_data = await _search_both_indices( + search_client, last_name, first_name + ) all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) @@ -203,7 +192,7 @@ async def _enrich_patents_classifications( except MissingApiKeyError: logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.") return - except httpx.HTTPError as exc: + except ElasticsearchException as exc: logger.warning("Classification enrichment failed: %s", exc) return except Exception as exc: @@ -250,9 +239,9 @@ def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]: ) -def _get_author(author_id: str) -> Author | None: +async def _get_author(author_id: str) -> Author | None: short_id = author_id.replace("https://openalex.org/", "") - result = person_logic.search_persons(author_id=short_id) + result = await person_logic.search_persons(author_id=short_id) return result.results[0] if result.results else None @@ -283,43 +272,36 @@ async def get_all_patents( all_patents_client = AllPatentsSearchClient() ipc_search_client = ipc_client or IpcSearchClient() - try: - if source == "EPO": - epo_data = await all_patents_client.search_epo( - all_patents_client.epo_query(page, size, search, sort_direction) - ) - patents = _parse_epo_hits(epo_data) - total = epo_data.get("hits", {}).get("total", {}).get("value", 0) + if source == "EPO": + epo_data = await all_patents_client.search_epo( + all_patents_client.epo_query(page, size, search, sort_direction) + ) + patents = _parse_epo_hits(epo_data) + total = epo_data.get("hits", {}).get("total", {}).get("value", 0) - elif source == "USPTO": - uspto_data = await all_patents_client.search_uspto( - all_patents_client.uspto_query(page, size, search, sort_direction) - ) - patents = _parse_uspto_hits(uspto_data) - total = uspto_data.get("hits", {}).get("total", {}).get("value", 0) + elif source == "USPTO": + uspto_data = await all_patents_client.search_uspto( + all_patents_client.uspto_query(page, size, search, sort_direction) + ) + patents = _parse_uspto_hits(uspto_data) + total = uspto_data.get("hits", {}).get("total", {}).get("value", 0) - else: - half = size // 2 - epo_data, uspto_data = await asyncio.gather( - all_patents_client.search_epo( - all_patents_client.epo_query(page, half, search, sort_direction) - ), - all_patents_client.search_uspto( - all_patents_client.uspto_query(page, half, search, sort_direction) - ), - ) - patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) - total = ( - epo_data.get("hits", {}).get("total", {}).get("value", 0) + - uspto_data.get("hits", {}).get("total", {}).get("value", 0) - ) + else: + half = size // 2 + epo_data, uspto_data = await asyncio.gather( + all_patents_client.search_epo( + all_patents_client.epo_query(page, half, search, sort_direction) + ), + all_patents_client.search_uspto( + all_patents_client.uspto_query(page, half, search, sort_direction) + ), + ) + patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data) + total = ( + epo_data.get("hits", {}).get("total", {}).get("value", 0) + + uspto_data.get("hits", {}).get("total", {}).get("value", 0) + ) - except MissingApiKeyError as exc: - raise HTTPException(status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="Patent search is not configured.") from exc - except httpx.HTTPError as exc: - raise HTTPException(status_code=HTTP_502_BAD_GATEWAY, - detail="Patent search request failed.") from exc await _enrich_patents_classifications(patents, ipc_search_client) diff --git a/service/src/main/inse/patents/test_ipc_search_client.py b/service/src/main/inse/patents/test_ipc_search_client.py index 4bf064bd..78df758e 100644 --- a/service/src/main/inse/patents/test_ipc_search_client.py +++ b/service/src/main/inse/patents/test_ipc_search_client.py @@ -1,4 +1,4 @@ -import httpx +from unittest.mock import AsyncMock, patch import pytest from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient @@ -11,57 +11,51 @@ def anyio_backend(): @pytest.mark.anyio async def test_resolve_symbols_posts_to_ipc_index(): - requests: list[str] = [] + mock_response = { + "hits": { + "hits": [ + { + "_source": { + "cpc_section_number": "H", + "cpc_section_name": "ELECTRICITY", + } + }, + { + "_source": { + "cpc_class_number": "H01L", + "cpc_class_name": "SEMICONDUCTOR DEVICES", + } + }, + { + "_source": { + "cpc_group_number": "H01L21/02", + "cpc_group_name": "Manufacture or treatment of semiconductor devices", + } + }, + ] + } + } - def handler(request: httpx.Request) -> httpx.Response: - requests.append(request.url.path) - return httpx.Response( - 200, - json={ - "hits": { - "hits": [ - { - "_source": { - "cpc_section_number": "H", - "cpc_section_name": "ELECTRICITY", - } - }, - { - "_source": { - "cpc_class_number": "H01L", - "cpc_class_name": "SEMICONDUCTOR DEVICES", - } - }, - { - "_source": { - "cpc_group_number": "H01L21/02", - "cpc_group_name": "Manufacture or treatment of semiconductor devices", - } - }, - ] - } - }, - ) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = mock_response + client = IpcSearchClient() - transport = httpx.MockTransport(handler) - client = IpcSearchClient(api_key="test-key", transport=transport) + result = await client.resolve_symbols(["H01L 21/02"]) - result = await client.resolve_symbols(["H01L 21/02"]) - - assert len(requests) >= 1 - assert all(path.endswith(f"/{IPC_INDEX}/_search") for path in requests) - assert "H01L 21/02" in result - assert result["H01L 21/02"].section == "H - ELECTRICITY" - assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES" + assert mock_search.call_count >= 1 + _, kwargs = mock_search.call_args + assert kwargs.get("index") == IPC_INDEX + assert "H01L 21/02" in result + assert result["H01L 21/02"].section == "H - ELECTRICITY" + assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES" @pytest.mark.anyio async def test_resolve_symbols_does_not_crash_for_subclass_codes(): - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response(200, json={"hits": {"hits": []}}) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"hits": []}} + client = IpcSearchClient() + result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"]) - client = IpcSearchClient(api_key="test-key", transport=httpx.MockTransport(handler)) - result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"]) - - assert "A61J 1/14" in result - assert "C07D 319/06" in result + assert "A61J 1/14" in result + assert "C07D 319/06" in result diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 8c5238f9..a7d74fde 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -9,10 +9,15 @@ import logging import time from datetime import datetime from typing import Optional, Callable, Any, List -from elasticsearch import ApiError, NotFoundError import hashlib import httpx -from fastapi import HTTPException +from inse.exceptions import ( + NotFoundException, + ElasticsearchException, + ElasticsearchNotFoundException, + ElasticsearchConnectionException, + BadRequestException, +) from inse.model import ESIndex from .. import config @@ -35,7 +40,7 @@ logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen -def find_ude_author_by_name(display_name: str) -> Optional[dict]: +async def find_ude_author_by_name(display_name: str) -> Optional[dict]: query = { "_source": ["display_name"], "query": { @@ -63,7 +68,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]: } try: - data = elasticsearch.search(index=INDEX_NAME, body=query) + data = await elasticsearch.search(index=INDEX_NAME, body=query) except Exception: logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.") return None @@ -89,7 +94,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]: } -def get_author_name_by_id(author_id: str) -> Optional[str]: +async def get_author_name_by_id(author_id: str) -> Optional[str]: try: query = { "_source": ["id", "display_name"], @@ -99,7 +104,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]: "size": 1, } - data = elasticsearch.search(index=INDEX_NAME, body=query) + data = await elasticsearch.search(index=INDEX_NAME, body=query) hits = data.get("hits", {}).get("hits", []) if not hits: return None @@ -109,7 +114,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]: return None -def search_persons( +async def search_persons( author_id: Optional[str] = None, query: Optional[str] = None, ) -> AuthorsListResponse: @@ -131,7 +136,7 @@ def search_persons( else: return AuthorsListResponse(results=[], meta=Meta(count=0)) - data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_) + data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_) authors = [] for hit in data.get("hits", {}).get("hits", []): @@ -155,7 +160,7 @@ def search_persons( return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) -def _fetch_author_display_name(author_id: str) -> Optional[str]: +async def _fetch_author_display_name(author_id: str) -> Optional[str]: query = { "query_string": { @@ -164,7 +169,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]: } } - response = elasticsearch.search( + response = await elasticsearch.search( index=INDEX_NAME, query=query, source=["display_name"], @@ -178,7 +183,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]: return hits[0].get("_source", {}).get("display_name") -def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: +async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: WORK_SOURCE_FIELDS = [ "title", @@ -221,7 +226,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: }, } - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) @@ -251,7 +256,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics -def _get_publication_years_for_author(author_id: str) -> list[int]: +async def _get_publication_years_for_author(author_id: str) -> list[int]: author_url = f"https://openalex.org/{author_id.strip()}" body = { @@ -278,7 +283,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]: }, } - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) @@ -359,8 +364,8 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics: ) -def get_career_metrics_for_author(author_id: str) -> CareerMetrics: - publication_years = _get_publication_years_for_author(author_id) +async def get_career_metrics_for_author(author_id: str) -> CareerMetrics: + publication_years = await _get_publication_years_for_author(author_id) return _compute_career_metrics(publication_years) @@ -382,13 +387,13 @@ def _build_papers(works: list) -> list: return papers -def get_data_for_bio(author_id: str) -> Optional[dict]: +async def get_data_for_bio(author_id: str) -> Optional[dict]: - display_name = _fetch_author_display_name(author_id) + display_name = await _fetch_author_display_name(author_id) if display_name is None: return None - works, top_topics = _fetch_works_and_topics(author_id) + works, top_topics = await _fetch_works_and_topics(author_id) papers = _build_papers(works) author_data = { @@ -399,9 +404,9 @@ def get_data_for_bio(author_id: str) -> Optional[dict]: return author_data -def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str: +async def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str: start_time = time.time() - author_data = get_data_for_bio(author_id) + author_data = await get_data_for_bio(author_id) if author_data is None: return "No person found." @@ -430,27 +435,23 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s return bio -def get_person_by_id( +async def get_person_by_id( author_id: str, include: Optional[str] = None ) -> CustomAuthorsListResponse: source = include.split(",") if include else None try: - hit = elasticsearch.get( + hit = await elasticsearch.get( index="openalex-authors", doc_id=author_id, source=source, ) - except NotFoundError: - raise HTTPException( - status_code=404, detail=f"Person with id {author_id} not found" - ) - except ApiError as e: - raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") + except NotFoundException as e: + raise NotFoundException(f"Person with id {author_id} not found") from e author = util.get_persons_data(hit) start_time = time.time() - career_metrics = get_career_metrics_for_author(author_id) + career_metrics = await get_career_metrics_for_author(author_id) elapsed_time = time.time() - start_time logger.info( @@ -465,14 +466,14 @@ def get_person_by_id( return CustomAuthorsListResponse(results=[custom_author]) -def search_persons_by_name( +async def search_persons_by_name( author_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None, ) -> AuthorsListResponse: if not author_name: - raise HTTPException(status_code=400, detail="name must be provided") + raise BadRequestException("name must be provided") search_query = { "bool": { "should": [ @@ -495,7 +496,7 @@ def search_persons_by_name( } } try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-authors", query=search_query, offset=page_offset, @@ -504,10 +505,8 @@ def search_persons_by_name( track_total_hits=True, ) - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) + except ElasticsearchException as e: + raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e total_count = response.get("hits", {}).get("total", {}).get("value", 0) hits = response.get("hits", {}).get("hits", []) @@ -518,11 +517,11 @@ def search_persons_by_name( ) -def search_persons_autocomplete( +async def search_persons_autocomplete( author_name: str, limit: Optional[int] = 5, include: Optional[str] = None ) -> AuthorsListResponse: if not author_name: - raise HTTPException(status_code=400, detail="name must be provided") + raise BadRequestException("name must be provided") search_query = { "function_score": { "query": { @@ -555,11 +554,9 @@ def search_persons_autocomplete( "collapse": collapse, } try: - response = elasticsearch.search(index="openalex-authors", body=body) - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) + response = await elasticsearch.search(index="openalex-authors", body=body) + except ElasticsearchException as e: + raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e hits = response.get("hits", {}).get("hits", []) @@ -587,7 +584,7 @@ def search_persons_autocomplete( return AuthorsListResponse(results=persons) -def search_persons_by_institution( +async def search_persons_by_institution( institution_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, @@ -595,7 +592,7 @@ def search_persons_by_institution( ) -> AuthorsListResponse: if not institution_name: - raise HTTPException(status_code=400, detail="institution_name must be provided") + raise BadRequestException("institution_name must be provided") search_query = { "nested": { @@ -614,7 +611,7 @@ def search_persons_by_institution( } } try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-authors", query=search_query, source=include.split(",") if include else True, @@ -624,10 +621,8 @@ def search_persons_by_institution( track_total_hits=True, ) - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) + except ElasticsearchException as e: + raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e total_count = response.get("hits", {}).get("total", {}).get("value", 0) hits = response.get("hits", {}).get("hits", []) persons = [util.get_persons_data(hit) for hit in hits] @@ -679,7 +674,7 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]: return author -def advanced_search_persons( +async def advanced_search_persons( query: Optional[str] = None, institution_name: Optional[str] = None, sort_by: Optional[str] = None, @@ -707,39 +702,20 @@ def advanced_search_persons( filter_mode=filter_mode, filter_year=filter_year, ) - response_dict = elasticsearch.search( + response_dict = await elasticsearch.search( index=INDEX_NAME, body=query_body, ) - except httpx.HTTPStatusError as e: - if e.response.status_code == 404: - logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.") - return CustomAuthorsListResponse( - results=[], meta=Meta(count=0, page=page, per_page=page_size) - ) - elif e.response.status_code == 400: - logger.error(f"Elasticsearch request error: {str(e)}") - raise HTTPException( - status_code=400, detail=f"Elasticsearch request error: {str(e)}" - ) - else: - logger.error(f"Elasticsearch API error: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch API error: {str(e)}" - ) - except httpx.RequestError as e: - logger.error(f"Elasticsearch connection/request error: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}" + except ElasticsearchNotFoundException: + logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.") + return CustomAuthorsListResponse( + results=[], meta=Meta(count=0, page=page, per_page=page_size) ) - except Exception as e: + except ElasticsearchException as e: logger.error(f"Elasticsearch search failed: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) + raise total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) hits = response_dict.get("hits", {}).get("hits", []) - total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) include_career_metrics = include is None or "career_metrics" in include results = [] @@ -749,7 +725,7 @@ def advanced_search_persons( if custom_author: if include_career_metrics: start_time = time.time() - custom_author.career_metrics = get_career_metrics_for_author( + custom_author.career_metrics = await get_career_metrics_for_author( custom_author.id ) elapsed_time = time.time() - start_time diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index a1e08f62..dfdf7fd7 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -29,7 +29,7 @@ router = APIRouter( summary="Searches for persons by ID or name.", response_model_exclude_none=True, ) -def search_persons( +async def search_persons( author_id: Annotated[ str, Query(description="OpenAlex author ID (e.g., A5093075883)") ] = None, @@ -53,7 +53,7 @@ def search_persons( if include else None ) - return logic.search_persons(author_id, query) + return await logic.search_persons(author_id, query) @router.get( @@ -62,7 +62,7 @@ def search_persons( response_model=model.PersonBio, summary="Generates a bio for a person by author ID.", ) -def generate_person_bio( +async def generate_person_bio( author_id: Annotated[ str, Query(description="OpenAlex author ID (e.g., A5093075883)") ], @@ -79,7 +79,7 @@ def generate_person_bio( if include else None ) - bio = logic.generate_person_bio(author_id, include_set) + bio = await logic.generate_person_bio(author_id, include_set) return model.PersonBio(bio=bio) @router.get( @@ -89,7 +89,7 @@ def generate_person_bio( summary="Searches for person by ID.", tags=["Persons"], ) -def get_person_by_id( +async def get_person_by_id( id: Annotated[ str, Path(description="OpenAlex author ID", examples=["A5093075883"]) ], @@ -104,7 +104,7 @@ def get_person_by_id( ), ] = None, ): - return logic.get_person_by_id(author_id=id, include=include) + return await logic.get_person_by_id(author_id=id, include=include) @router.get( @@ -114,7 +114,7 @@ def get_person_by_id( summary="Searches for person by name.", tags=["Persons"], ) -def search_persons_by_name( +async def search_persons_by_name( author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], include: Annotated[ Optional[str], @@ -129,24 +129,25 @@ def search_persons_by_name( limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None, page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None, ): - return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit) + return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit) + @router.get( '/persons/autocomplete', operation_id='searchPersonsAutocomplete', response_model=AuthorsListResponse, summary='Searches for person by name.', - tags=[ 'Persons' ]) -def search_persons_autocomplete( + tags=['Persons']) +async def search_persons_autocomplete( author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], include : Annotated[Optional[str], Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share" - )]): - return logic.search_persons_autocomplete(author_name=author_name,include=include) + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share" + )]): + return await logic.search_persons_autocomplete(author_name=author_name, include=include) @router.get( @@ -156,7 +157,7 @@ def search_persons_autocomplete( summary="Searches for persons by institution name.", tags=["Persons"], ) -def search_persons_by_institution( +async def search_persons_by_institution( institution_name: Annotated[ str, Query(description="Institution name (e.g., MIT, Oxford University)") ], @@ -173,7 +174,8 @@ def search_persons_by_institution( limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None, page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None, ): - return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit) + return await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit) + @router.get( "/persons/search-list", @@ -183,7 +185,7 @@ def search_persons_by_institution( response_model_exclude_none=True, tags=["Persons"], ) -def search_persons_list( +async def search_persons_list( query: Annotated[ Optional[str], Query(description="Search query (e.g., Arman AND Arzani)") ] = None, @@ -227,7 +229,7 @@ def search_persons_list( if include else None ) - return logic.advanced_search_persons( + return await logic.advanced_search_persons( query=query, institution_name=institution_name, sort_by=sort_by, diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py index 5caff70e..cb120418 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py @@ -1,5 +1,5 @@ import logging -from concurrent.futures import ThreadPoolExecutor, as_completed +import asyncio from typing import Any, Dict, List, Optional, Union from inse.config import get_settings @@ -85,7 +85,7 @@ _HEU_ENTITY_CONFIGS = [ {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, ] -def get_enriched_cordis_project_by_id( +async def get_enriched_cordis_project_by_id( project_id: str, ) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: """ @@ -102,7 +102,7 @@ def get_enriched_cordis_project_by_id( query = {"bool": {"filter": [{"term": {"id": project_id}}]}} - response = elasticsearch.search( + response = await elasticsearch.search( query=query, index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, @@ -131,7 +131,7 @@ def get_enriched_cordis_project_by_id( logger.warning(f"Unknown programme type for index: {index}") return CordisEuProject.model_validate(source) - return enricher(project_id, source) + return await enricher(project_id, source) # helpers def _determine_program_type_from_index(index: str) -> str: @@ -146,10 +146,9 @@ def _determine_program_type_from_index(index: str) -> str: return "unknown" -def _fetch_related_entities_parallel( +async def _fetch_related_entities_parallel( project_id: str, entity_configs: List[Dict[str, Any]], - max_workers: int = 8, ) -> Dict[str, List[Any]]: """ Fetches all related entity types for a project in parallel. @@ -157,35 +156,35 @@ def _fetch_related_entities_parallel( Args: project_id: The project ID to fetch entities for. entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. - max_workers: Maximum number of concurrent Elasticsearch requests. Returns: Dictionary mapping each config 'key' to a list of validated entities. """ - def _fetch_one(config: Dict[str, Any]): - entities = _fetch_related_entities( + async def _fetch_one(config: Dict[str, Any]): + entities = await _fetch_related_entities( project_ids=[project_id], index_pattern=config["index_pattern"], model_class=config["model_class"], ) return config["key"], entities.get(project_id, []) + tasks = [_fetch_one(cfg) for cfg in entity_configs] + completed = await asyncio.gather(*tasks, return_exceptions=True) + results: Dict[str, List[Any]] = {} - with ThreadPoolExecutor(max_workers=max_workers) as executor: - futures = {executor.submit(_fetch_one, cfg): cfg["key"] for cfg in entity_configs} - for future in as_completed(futures): - try: - key, data = future.result() - results[key] = data - except Exception as e: - key = futures[future] - logger.error(f"Parallel fetch failed for '{key}': {e}") - results[key] = [] + for cfg, res in zip(entity_configs, completed): + key = cfg["key"] + if isinstance(res, Exception): + logger.error(f"Parallel fetch failed for '{key}': {res}") + results[key] = [] + else: + key_name, data = res + results[key_name] = data return results -def _fetch_related_entities( +async def _fetch_related_entities( project_ids: List[str], index_pattern: str, model_class: Any, @@ -204,7 +203,7 @@ def _fetch_related_entities( query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} try: - response = elasticsearch.search( + response = await elasticsearch.search( query=query, index=index_pattern, cluster=ESCluster.INSE, @@ -234,7 +233,7 @@ def _fetch_related_entities( return grouped -def _enrich_fp7_project( +async def _enrich_fp7_project( project_id: str, project_source: Dict[str, Any], ) -> Optional[Fp7ProjectDetails]: @@ -245,12 +244,12 @@ def _enrich_fp7_project( logger.error(f"Failed to validate FP7 project {project_id}: {e}") return None - related = _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) + related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) return Fp7ProjectDetails.from_project_with_relations(project=project, **related) -def _enrich_h2020_project( +async def _enrich_h2020_project( project_id: str, project_source: Dict[str, Any], ) -> Optional[H2020ProjectDetails]: @@ -261,12 +260,12 @@ def _enrich_h2020_project( logger.error(f"Failed to validate H2020 project {project_id}: {e}") return None - related = _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) + related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) return H2020ProjectDetails.from_project_with_relations(project=project, **related) -def _enrich_heu_project( +async def _enrich_heu_project( project_id: str, project_source: Dict[str, Any], ) -> Optional[HEUProjectDetails]: @@ -277,6 +276,6 @@ def _enrich_heu_project( logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") return None - related = _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) + related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) return HEUProjectDetails.from_project_with_relations(project=project, **related) \ No newline at end of file diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 4cd2812a..bbb09625 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -101,7 +101,7 @@ DFG_PERSON_FIELDS: List[str] = [ # BUND -def search_bund_projects( +async def search_bund_projects( filter_properties: ProjectsFilteringProperties, institution_names: List[str] = [], ) -> BundProjectPage: @@ -160,7 +160,7 @@ def search_bund_projects( } ] - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, query=query, sort=sort, @@ -194,7 +194,7 @@ def _complete_response_to_bund_project_page( return BundProjectPage(elements=elements, total=total_hits, page=page, size=size) -def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: +async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: """Decodes project_id and fetches the details of a single Bund project based on its project ID. Args: @@ -207,7 +207,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: decoded_id = urllib.parse.unquote(project_id) query = {"term": {"Förderkennzeichen.keyword": {"value": decoded_id}}} - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.PROJECTS_BUND_V1, query=query, size=1, @@ -224,7 +224,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]: # EU -def get_eu_organization_project_contributions( +async def get_eu_organization_project_contributions( organization_names: List[str], projects_filtering_properties: ProjectsFilteringProperties, ) -> EuOrganizationProjectSummaryPage: @@ -241,11 +241,11 @@ def get_eu_organization_project_contributions( # For FUNDING_AMOUNT before on the organization project contributions # For the rest after the contributions are known on the real projects - organization_project_contributions = get_eu_organization_contributions( + organization_project_contributions = await get_eu_organization_contributions( organization_names=organization_names, ) - total_projects, projects = get_eu_organization_projects( + total_projects, projects = await get_eu_organization_projects( project_contributions=list(organization_project_contributions.values()), projects_filtering_properties=projects_filtering_properties, ) @@ -271,7 +271,7 @@ def get_eu_organization_project_contributions( ) -def get_eu_organization_contributions( +async def get_eu_organization_contributions( organization_names: List[str], ) -> Dict[str, EuOrganizationShort]: """Fetches the contributions of EU organizations to projects based on the provided organization names. @@ -293,7 +293,7 @@ def get_eu_organization_contributions( } } - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD, cluster=ESCluster.INSE, source=source, @@ -343,7 +343,7 @@ def _process_organization_project_contributions( return project_contributions -def get_eu_organization_projects( +async def get_eu_organization_projects( project_contributions: List[EuOrganizationShort], projects_filtering_properties: ProjectsFilteringProperties, ) -> Tuple[int, Dict[str, EuProjectShort]]: @@ -388,7 +388,7 @@ def get_eu_organization_projects( # Project contributions have been filtered before based on ecContribution if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT: - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, source=source, @@ -396,7 +396,7 @@ def get_eu_organization_projects( size=10000, ) else: - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, source=source, @@ -496,7 +496,7 @@ def _get_raw_doi(doi: str) -> str: return doi -def get_cordis_eu_publications_by_dois(dois: List[str]): +async def get_cordis_eu_publications_by_dois(dois: List[str]): """Retrieves Cordis EU publications associated with the given list of DOIs. Args: @@ -508,7 +508,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]): raw_dois = [_get_raw_doi(doi) for doi in dois] query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}} - response = elasticsearch.search( + response = await elasticsearch.search( query=query, index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD, cluster=ESCluster.INSE, @@ -519,7 +519,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]): return response -def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: +async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: """Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs. Args: @@ -528,7 +528,7 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: Returns: List[str]: The list of project IDs. """ - response = get_cordis_eu_publications_by_dois(dois=dois) + response = await get_cordis_eu_publications_by_dois(dois=dois) hits_block = response.get("hits", {}) project_ids = set() for hit in hits_block.get("hits", []): @@ -539,12 +539,12 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]: return list(project_ids) -def get_cordis_eu_projects_by_project_ids( +async def get_cordis_eu_projects_by_project_ids( project_ids: List[str], ) -> CordisEuProjectPage: query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}} - response = elasticsearch.search( + response = await elasticsearch.search( query=query, index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, @@ -561,7 +561,7 @@ def get_cordis_eu_projects_by_project_ids( ) -def get_eu_cordis_projects_by_id( +async def get_eu_cordis_projects_by_id( project_id: str, ) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: """ @@ -573,14 +573,14 @@ def get_eu_cordis_projects_by_id( Returns: The enriched project details, or None if not found """ - enriched_project = get_enriched_cordis_project_by_id( + enriched_project = await get_enriched_cordis_project_by_id( project_id=project_id ) return enriched_project # DFG -def search_dfg_projects( +async def search_dfg_projects( page: int, size: int, names: Optional[List[str]] = None, @@ -750,7 +750,7 @@ def search_dfg_projects( body["sort"] = [sort_config] - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.PROJECTS_DFG_ALL, body=body, ) @@ -776,7 +776,7 @@ def _complete_response_to_dfg_project_page( return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size) -def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: +async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: """Fetches the details of a single DFG project based on its project ID. Args: @@ -787,7 +787,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: """ query = {"ids": {"values": [project_id]}} - response = elasticsearch.search( + response = await elasticsearch.search( index=ESIndex.PROJECTS_DFG_ALL, query=query, size=1, @@ -804,7 +804,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]: # All -def search_all_projects( +async def search_all_projects( projects_filtering_properties: ProjectsFilteringProperties, selected_project_types: Optional[Set[ProjectType]] = None, ) -> FundingProjectPage: @@ -882,7 +882,7 @@ def search_all_projects( size = projects_filtering_properties.size page = projects_filtering_properties.page offset = page * size - response = elasticsearch.search( + response = await elasticsearch.search( index=index, size=size, offset=offset, diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 32f206e4..fcd91844 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -51,13 +51,13 @@ router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS]) }, response_model_by_alias=False, ) -def get_eu_projects_for_author( +async def get_eu_projects_for_author( raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")], ) -> CordisEuProjectPage: logger.debug( f"Received request to get EU projects for author_id={raw_oa_author_id}" ) - return projects_service.search_cordis_eu_projects_for_author_id( + return await projects_service.search_cordis_eu_projects_for_author_id( raw_oa_author_id=raw_oa_author_id, ) @@ -85,7 +85,7 @@ async def search_bund_projects( Body(description="The filtering properties for the projects search."), ], ) -> BundProjectPage: - return projects_service.search_bund_projects( + return await projects_service.search_bund_projects( institutions_search_client=institutions_search_client, filtering_properties=filtering_properties, ) @@ -105,11 +105,11 @@ async def search_bund_projects( }, response_model_by_alias=False, ) -def get_single_dfg_project( +async def get_single_dfg_project( id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")], ) -> DfgProjectDetails: logger.debug(f"Received request to get single DFG project for id={id}") - return projects_service.get_single_dfg_project( + return await projects_service.get_single_dfg_project( project_id=id, ) @@ -128,11 +128,11 @@ def get_single_dfg_project( }, response_model_by_alias=False, ) -def get_single_bund_project( +async def get_single_bund_project( id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")], ) -> BundProjectDetails: logger.debug(f"Received request to get single BUND project for id={id}") - return projects_service.get_single_bund_project( + return await projects_service.get_single_bund_project( project_id=id, ) @@ -157,9 +157,7 @@ def get_single_bund_project( } }, ) - - -def get_single_eu_cordis_project( +async def get_single_eu_cordis_project( id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")], ) -> EuCordisProjectResponse: """ @@ -170,7 +168,7 @@ def get_single_eu_cordis_project( try: # Get the project from the service - project = projects_service.get_single_eu_cordis_project(project_id=id) + project = await projects_service.get_single_eu_cordis_project(project_id=id) # Check if project exists if project is None: @@ -216,6 +214,7 @@ def get_single_eu_cordis_project( error=f"Internal server error: {str(e)}" ) + @router.get( "/institution/bund/funding-over-time", summary="Get funding over time for bund projects.", @@ -230,7 +229,7 @@ def get_single_eu_cordis_project( }, response_model_by_alias=False, ) -def get_institution_bund_projects_funding_over_time( +async def get_institution_bund_projects_funding_over_time( institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -238,7 +237,7 @@ def get_institution_bund_projects_funding_over_time( str, Query(description="The institution ID to filter by.") ], ) -> InstitutionFunderSummary: - return projects_service.get_institution_bund_projects_funding_over_time( + return await projects_service.get_institution_bund_projects_funding_over_time( institutions_search_client=institutions_search_client, raw_oa_institution_id=raw_oa_institution_id, ) @@ -267,7 +266,7 @@ async def search_cordis_eu_projects( Body(description="The filtering properties for the projects search."), ], ) -> EuOrganizationProjectSummaryPage: - return projects_service.search_cordis_eu_projects( + return await projects_service.search_cordis_eu_projects( institutions_search_client=institutions_search_client, projects_filtering_properties=projects_filtering_properties, ) @@ -359,7 +358,7 @@ async def get_dfg_projects( }, response_model_by_alias=False, ) -def search_projects( +async def search_projects( page: Annotated[int, Query(description="The page number.", ge=0)] = 0, size: Annotated[int, Query(description="The page size.", ge=1)] = 10, selected_project_types: Annotated[ @@ -378,7 +377,7 @@ def search_projects( SortDirection, Query(description="The sort direction (asc or desc).") ] = SortDirection.ASC, ) -> FundingProjectPage: - return projects_service.search_all_projects( + return await projects_service.search_all_projects( page=page, size=size, selected_project_types=selected_project_types, diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 955d8289..e8d83281 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -35,7 +35,7 @@ from typing import Union logger = logging.getLogger(__name__) -def search_all_projects( +async def search_all_projects( page: int, size: int, sort_by: ProjectsSortBy, @@ -43,7 +43,7 @@ def search_all_projects( selected_project_types: Optional[Set[ProjectType]] = None, title: Optional[str] = None, ) -> FundingProjectPage: - return projects_search_client.search_all_projects( + return await projects_search_client.search_all_projects( projects_filtering_properties=ProjectsFilteringProperties( project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects page=page, @@ -56,7 +56,7 @@ def search_all_projects( ) -def search_bund_projects( +async def search_bund_projects( institutions_search_client: InstitutionsSearchClient, filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: @@ -69,13 +69,13 @@ def search_bund_projects( f"search_bund_projects called with filtering_properties: {filtering_properties}" ) - return get_bund_projects_by_institution_id( + return await get_bund_projects_by_institution_id( institutions_search_client=institutions_search_client, filtering_properties=filtering_properties, ) -def get_bund_projects_by_institution_id( +async def get_bund_projects_by_institution_id( institutions_search_client: InstitutionsSearchClient, filtering_properties: ProjectsFilteringProperties, ) -> BundProjectPage: @@ -93,7 +93,7 @@ def get_bund_projects_by_institution_id( logger.debug( f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - response = projects_search_client.search_bund_projects( + response = await projects_search_client.search_bund_projects( institution_names=institution_aliases, filter_properties=filtering_properties, ) @@ -101,7 +101,7 @@ def get_bund_projects_by_institution_id( return response -def search_cordis_eu_projects( +async def search_cordis_eu_projects( institutions_search_client: InstitutionsSearchClient, projects_filtering_properties: ProjectsFilteringProperties, ) -> EuOrganizationProjectSummaryPage: @@ -110,13 +110,13 @@ def search_cordis_eu_projects( f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'." ) - return get_cordis_eu_projects_by_institution_id( + return await get_cordis_eu_projects_by_institution_id( institutions_search_client=institutions_search_client, projects_filtering_properties=projects_filtering_properties, ) -def get_cordis_eu_projects_by_institution_id( +async def get_cordis_eu_projects_by_institution_id( institutions_search_client: InstitutionsSearchClient, projects_filtering_properties: ProjectsFilteringProperties, ) -> EuOrganizationProjectSummaryPage: @@ -137,7 +137,7 @@ def get_cordis_eu_projects_by_institution_id( f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}" ) - page = get_eu_organization_project_contributions( + page = await get_eu_organization_project_contributions( organization_names=institution_aliases, projects_filtering_properties=projects_filtering_properties, ) @@ -158,7 +158,7 @@ async def get_dfg_projects_by_author_id( logger.debug( f"Fetching DFG projects for author_id={author_id}, topic={topic}, page={page}, size={size}, sort_by={sort_by}, sort_direction={sort_direction}" ) - name = get_author_name_by_id(author_id) + name = await get_author_name_by_id(author_id) if not name: logger.debug(f"No author name found for author_id={author_id}") raise NotFoundException( @@ -166,7 +166,7 @@ async def get_dfg_projects_by_author_id( ) logger.debug(f"Found author name for author_id={author_id}: {name}") - response = projects_search_client.search_dfg_projects( + response = await projects_search_client.search_dfg_projects( page=page, size=size, names=[name], @@ -186,7 +186,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( raw_oa_institution_id ) ) - page = get_eu_organization_project_contributions( + page = await get_eu_organization_project_contributions( organization_names=institution_aliases, projects_filtering_properties=ProjectsFilteringProperties( project_type=ProjectType.EU, @@ -204,7 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time( ) -def get_institution_bund_projects_funding_over_time( +async def get_institution_bund_projects_funding_over_time( institutions_search_client: InstitutionsSearchClient, raw_oa_institution_id: str, ) -> InstitutionFunderSummary: @@ -219,7 +219,7 @@ def get_institution_bund_projects_funding_over_time( logger.debug( f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}" ) - response = projects_search_client.search_bund_projects( + response = await projects_search_client.search_bund_projects( filter_properties=ProjectsFilteringProperties( project_type=ProjectType.BUND, page=0, @@ -305,38 +305,40 @@ def _calculate_funding_over_time( ) -def get_single_dfg_project( +async def get_single_dfg_project( project_id: str, ) -> DfgProjectDetails: logger.debug(f"Fetching single DFG project for id={project_id}") - project = projects_search_client.get_dfg_project_by_id(project_id) + project = await projects_search_client.get_dfg_project_by_id(project_id) if not project: raise NotFoundException(f"DFG project with id {project_id} not found") return project -def get_single_bund_project( +async def get_single_bund_project( project_id: str, ) -> BundProjectDetails: logger.debug(f"Fetching single BUND project for id={project_id}") - project = projects_search_client.get_bund_project_by_id(project_id) + project = await projects_search_client.get_bund_project_by_id(project_id) if not project: raise NotFoundException(f"BUND project with id {project_id} not found") return project -def get_single_eu_cordis_project( + +async def get_single_eu_cordis_project( project_id: str, ) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: logger.debug(f"Fetching single EU Cordis project for id={project_id}") - project = projects_search_client.get_eu_cordis_projects_by_id(project_id) + project = await projects_search_client.get_eu_cordis_projects_by_id(project_id) if not project: raise NotFoundException(f"EU project with id {project_id} not found") return project -def search_cordis_eu_projects_for_author_id( + +async def search_cordis_eu_projects_for_author_id( raw_oa_author_id: str, ) -> CordisEuProjectPage: @@ -345,17 +347,17 @@ def search_cordis_eu_projects_for_author_id( # 2. CORDIS EU projects have associated publications with DOIs # 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author - dois = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id) + dois = await get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id) logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}") - project_ids = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) + project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois) logger.debug( f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}" ) - funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids( + funding_project_page = await projects_search_client.get_cordis_eu_projects_by_project_ids( project_ids=project_ids ) diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index 244f70c8..1d718ecf 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -8,10 +8,8 @@ from copy import deepcopy from typing import Any import httpx -from fastapi import HTTPException from pydantic import ValidationError -from starlette.status import HTTP_400_BAD_REQUEST -from starlette.status import HTTP_502_BAD_GATEWAY +from inse.exceptions import UpstreamAPIException, BadRequestException, ElasticsearchException from inse.models.openalex.autocomplete_response import AutocompleteResponse from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta @@ -38,10 +36,7 @@ async def list_topics( client: OpenAlexTopicsClient | None = None, ) -> TopicsListResponse: if sample is not None and (sort or page not in (None, 1)): - raise HTTPException( - status_code=HTTP_400_BAD_REQUEST, - detail="sample cannot be combined with sort or page.", - ) + raise BadRequestException("sample cannot be combined with sort or page.") openalex_client = client or OpenAlexTopicsClient() @@ -66,12 +61,12 @@ async def list_topics( except ValueError: if exc.response.text: detail = exc.response.text - raise HTTPException(status_code=status_code, detail=detail) from exc + raise UpstreamAPIException(message=detail, status_code=status_code) from exc except httpx.HTTPError as exc: logger.exception("OpenAlex topics request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex topics request failed.", + raise UpstreamAPIException( + message="OpenAlex topics request failed.", + status_code=502, ) from exc try: @@ -79,9 +74,9 @@ async def list_topics( return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse() except ValidationError as exc: logger.exception("OpenAlex topics response could not be parsed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex topics response could not be parsed.", + raise UpstreamAPIException( + message="OpenAlex topics response could not be parsed.", + status_code=502, ) from exc @@ -282,10 +277,7 @@ async def vector_search_topics( except Exception as exc: logger.exception("Failed to load elasticsearch integration.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail=f"Failed to load elasticsearch integration: {exc}" - ) + raise ElasticsearchException(f"Failed to load elasticsearch integration: {exc}") from exc # 1. Vectorize query try: @@ -293,10 +285,7 @@ async def vector_search_topics( query_vector = model.encode(query).tolist() except Exception as exc: logger.exception("Failed to encode query text.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail=f"Failed to encode query text: {exc}" - ) + raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc # 2. Query Elasticsearch using standard Bool Should hybrid search should_clauses = [] @@ -357,17 +346,14 @@ async def vector_search_topics( } try: - raw_results = elasticsearch.search( + raw_results = await elasticsearch.search( index="topicvectors", body=body, cluster="nes" ) except Exception as exc: - logger.exception("Elasticsearch vector search failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail=f"Elasticsearch vector search failed: {exc}" - ) + logger.exception("Elasticsearch vector search failed with unexpected error.") + raise ElasticsearchException(f"Unexpected vector search failure: {exc}") from exc # 3. Format result hits = raw_results.get("hits", {}).get("hits", []) @@ -389,8 +375,5 @@ async def vector_search_topics( return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse() except ValidationError as exc: logger.exception("Vector search response could not be parsed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="Vector search response could not be parsed.", - ) from exc + raise ElasticsearchException(f"Vector search response could not be parsed: {exc}") from exc diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py index e6f9a3a4..5e88a461 100644 --- a/service/src/main/inse/topics/test_logic.py +++ b/service/src/main/inse/topics/test_logic.py @@ -1,6 +1,6 @@ import httpx import pytest -from fastapi import HTTPException +from inse.exceptions import BadRequestException from inse.topics import logic from inse.topics.search_client import OpenAlexTopicsClient @@ -76,11 +76,9 @@ async def test_list_topics_maps_openalex_response_to_model(): @pytest.mark.anyio async def test_list_topics_rejects_sample_with_sort(): - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(BadRequestException) as exc_info: await logic.list_topics(sample=10, sort="works_count:desc") - assert exc_info.value.status_code == 400 - @pytest.mark.anyio async def test_list_topics_accepts_practical_openalex_type_variants(): diff --git a/service/src/main/inse/university_ranking/logic.py b/service/src/main/inse/university_ranking/logic.py index bd1e58f9..10d926ff 100644 --- a/service/src/main/inse/university_ranking/logic.py +++ b/service/src/main/inse/university_ranking/logic.py @@ -31,7 +31,7 @@ async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> Ran # Fetch top institutions for the topic by works_count - res = elasticsearch.search( + res = await elasticsearch.search( index="openalex-institutions", query=query, size=10, diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py index dc47d976..5848c92e 100644 --- a/service/src/main/inse/util.py +++ b/service/src/main/inse/util.py @@ -8,15 +8,14 @@ from typing import Optional from typing import TypeVar from inse.models.openalex import Author from . import model -from fastapi import HTTPException -from starlette.status import HTTP_404_NOT_FOUND +from inse.exceptions import NotFoundException T = TypeVar('T') def raise_not_found_if_none(value: Optional[T]) -> T: ''' Returns the value, if it is set, or raises a 404, if the value is None.''' if value == None: - raise HTTPException(HTTP_404_NOT_FOUND) + raise NotFoundException("Not found.") else: return value diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index 7b3ed7a0..2ffb73e4 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -9,11 +9,8 @@ from time import time from typing import Any, List import httpx -from fastapi import HTTPException from pydantic import ValidationError -from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_404_NOT_FOUND -from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse import config from inse.integrations import elasticsearch @@ -24,7 +21,7 @@ from inse.models.openalex.meta import Meta from inse.models.openalex.topic_count import TopicCount from inse.models.openalex.topics_by_year import TopicsByYear from inse.models.openalex.topics_by_time import TopicsByTime -from .search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException from .search_client import OpenAlexWorksSearchClient logger = logging.getLogger(__name__) @@ -122,10 +119,10 @@ async def get_primary_topic_counts( author_id: str, client: OpenAlexWorksSearchClient | None = None, ) -> List[TopicCount]: - topic_counts = _get_primary_topic_counts_from_es(author_id) + topic_counts = await _get_primary_topic_counts_from_es(author_id) topic_ids = [item["id"] for item in topic_counts if item["id"]] - details = _get_topic_details(topic_ids) + details = await _get_topic_details(topic_ids) result = [] @@ -148,7 +145,7 @@ async def get_primary_topic_counts( return result -def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: +async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: indexed_author_id = f"https://openalex.org/{author_id.strip()}" @@ -174,16 +171,13 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: } try: - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) - except httpx.HTTPError as exc: + except ElasticsearchException as exc: logger.exception("OpenAlex primary topic aggregation request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + raise aggregations = response.get("aggregations", {}) buckets = aggregations.get("primary_topics", {}).get("buckets", []) @@ -212,18 +206,18 @@ async def get_work( return elements[0] -def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: +async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: if not topic_ids: return {} try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-topics", query={"terms": {"id": topic_ids}}, source=TOPIC_DETAIL_SOURCE_FIELDS, size=len(topic_ids), ) - except httpx.HTTPError: + except Exception: logger.exception("Could not load topic details from Elasticsearch.") return {} @@ -242,7 +236,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: "domain": _extract_topic_hierarchy_item(source, "domain"), } - _enrich_topic_hierarchy_descriptions(details) + await _enrich_topic_hierarchy_descriptions(details) return details @@ -260,7 +254,7 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non } -def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: +async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items(): hierarchy_ids = { item.get(hierarchy_key, {}).get("id") @@ -268,7 +262,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: if item.get(hierarchy_key, {}).get("id") } - descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids)) + descriptions = await _get_topic_hierarchy_descriptions(index, list(hierarchy_ids)) for item in details.values(): hierarchy_item = item.get(hierarchy_key) or {} @@ -278,7 +272,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None: hierarchy_item["description"] = descriptions[hierarchy_id] -def _get_topic_hierarchy_descriptions( +async def _get_topic_hierarchy_descriptions( index: str, hierarchy_ids: list[str], ) -> dict[str, str | None]: @@ -286,13 +280,13 @@ def _get_topic_hierarchy_descriptions( return {} try: - response = elasticsearch.search( + response = await elasticsearch.search( index=index, query={"terms": {"id": hierarchy_ids}}, source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS, size=len(hierarchy_ids), ) - except httpx.HTTPError: + except Exception: logger.exception("Could not load topic hierarchy details from %s.", index) return {} @@ -433,7 +427,7 @@ async def get_topics_by_time_by_author( client=client, ) - return _get_topics_by_time_by_author_from_es( + return await _get_topics_by_time_by_author_from_es( author_id, max_topics_per_year=max_topics_per_year, target_publications=target_publications, @@ -521,7 +515,7 @@ async def _get_topics_by_time_by_author_from_work_pages( if topic["id"]: topic_ids.add(topic["id"]) - topic_details = _get_topic_details(list(topic_ids)) + topic_details = await _get_topic_details(list(topic_ids)) elements = [] @@ -580,13 +574,13 @@ async def _get_topics_by_time_by_author_from_work_pages( ) -def _get_topics_by_time_by_author_from_es( +async def _get_topics_by_time_by_author_from_es( author_id: str, max_topics_per_year: int = 3, target_publications: int = 300, include_all: bool = False, ) -> TopicsByTime: - year_buckets, total_publications = _get_publication_year_counts_from_es(author_id) + year_buckets, total_publications = await _get_publication_year_counts_from_es(author_id) selected_years, is_limited = _select_complete_timeline_years( year_buckets, target_publications=target_publications, @@ -602,13 +596,13 @@ def _get_topics_by_time_by_author_from_es( total_publications=total_publications, ) - year_topic_buckets = _get_timeline_topic_counts_from_es( + year_topic_buckets = await _get_timeline_topic_counts_from_es( author_id, years=selected_years, max_topics_per_year=max_topics_per_year, ) topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets) - topic_details = _get_topic_details(list(topic_ids)) + topic_details = await _get_topic_details(list(topic_ids)) elements = _build_timeline_elements_from_aggregations( year_topic_buckets, @@ -625,7 +619,7 @@ def _get_topics_by_time_by_author_from_es( ) -def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]: +async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]: body = { "size": 0, "track_total_hits": True, @@ -642,21 +636,18 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in } try: - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) - except httpx.HTTPError as exc: + except ElasticsearchException as exc: logger.exception("OpenAlex publication year aggregation request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + raise return _parse_year_count_buckets(response), _parse_total_hits(response) -def _get_timeline_topic_counts_from_es( +async def _get_timeline_topic_counts_from_es( author_id: str, years: list[int], max_topics_per_year: int, @@ -713,16 +704,13 @@ def _get_timeline_topic_counts_from_es( } try: - response = elasticsearch.search( + response = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=body, ) - except httpx.HTTPError as exc: + except ElasticsearchException as exc: logger.exception("OpenAlex timeline topic aggregation request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + raise return response.get("aggregations", {}).get("by_year", {}).get("buckets", []) @@ -883,29 +871,16 @@ async def _search_author_works_data( institution_id: list[str] | None = None, topic_id: list[str] | None = None, ) -> dict: - try: - return await search_client.search_author_works( - author_id, - page, - size, - publication_year=publication_year, - work_type=work_type, - language=language, - institution_id=institution_id, - topic_id=topic_id, - ) - except MissingApiKeyError as exc: - logger.error("OpenAlex works Elasticsearch API key is not configured.") - raise HTTPException( - status_code=HTTP_503_SERVICE_UNAVAILABLE, - detail="OpenAlex works search is not configured.", - ) from exc - except httpx.HTTPError as exc: - logger.exception("OpenAlex works search request failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search request failed.", - ) from exc + return await search_client.search_author_works( + author_id, + page, + size, + publication_year=publication_year, + work_type=work_type, + language=language, + institution_id=institution_id, + topic_id=topic_id, + ) def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]: @@ -946,15 +921,15 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]: elements.append(work) except ValidationError as exc: logger.exception("OpenAlex works search response could not be parsed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="OpenAlex works search response could not be parsed.", + raise UpstreamAPIException( + message="OpenAlex works search response could not be parsed.", + status_code=502, ) from exc return elements, total -def get_publication_dois_of_author( +async def get_publication_dois_of_author( raw_oa_author_id: str, ) -> List[str]: query = { @@ -976,19 +951,16 @@ def get_publication_dois_of_author( } try: - response = elasticsearch.search( + response = await elasticsearch.search( index="openalex-works", source=["doi"], size=10000, query=query, cluster="nes", ) - except httpx.HTTPError as exc: + except ElasticsearchException as exc: logger.exception("Request for publication DOIs of author failed.") - raise HTTPException( - status_code=HTTP_502_BAD_GATEWAY, - detail="Request for publication DOIs of author failed.", - ) from exc + raise dois = [] for hit in response.get("hits", {}).get("hits", []): diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py index 93188678..41e6cb1e 100644 --- a/service/src/main/inse/works/search_client.py +++ b/service/src/main/inse/works/search_client.py @@ -11,8 +11,7 @@ import urllib from .. import config from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex -class MissingApiKeyError(Exception): - pass +from inse.exceptions import MissingApiKeyError logger = logging.getLogger(__name__) @@ -141,62 +140,49 @@ class OpenAlexWorksSearchClient: if not self.api_key: raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.post( - f"/{self.index}/_search", - headers={"Authorization": f"ApiKey {self.api_key}"}, - json=self.author_works_query( - author_id, - page, - size, - publication_year=publication_year, - work_type=work_type, - language=language, - institution_id=institution_id, - topic_id=topic_id, - ), - ) - # logging.debug(f"Response: {response.text}") - response.raise_for_status() - return response.json() - + body = self.author_works_query( + author_id, + page, + size, + publication_year=publication_year, + work_type=work_type, + language=language, + institution_id=institution_id, + topic_id=topic_id, + ) + return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,) async def search_work(self, identifier: str) -> dict[str, Any]: - if not self.api_key: - raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") - decoded_id = urllib.parse.unquote(identifier) - body = { - "query": { - "bool": { + if not self.api_key: + raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.") + decoded_id = urllib.parse.unquote(identifier) + body = { + "query": { + "bool": { "should": [ { - "term": { - "_id": { - "value": decoded_id, - "boost": 5 + "term": { + "_id": { + "value": decoded_id, + "boost": 5 + } } - } }, { - "term": { - "doi": { - "value": "https://doi.org/" + decoded_id.lower(), - "boost": 3 + "term": { + "doi": { + "value": "https://doi.org/" + decoded_id.lower(), + "boost": 3 + } } } - } ], "minimum_should_match": 1 - } } - } - print(body) - response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1) - return response + } + } + response = await elasticsearch.search(index=f"{ESIndex.OPENALEX_WORKS}*",body=body,cluster=ESCluster.NES,size=1) + return response async def search_for_work_by_title( self, @@ -220,6 +206,6 @@ class OpenAlexWorksSearchClient: {"cited_by_count": {"order": "desc", "missing": "_last"}}, ], } - response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1) + response = await elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1) return response \ No newline at end of file diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py index 0bfe1a44..39dbf091 100644 --- a/service/src/main/inse/works/test_search_client.py +++ b/service/src/main/inse/works/test_search_client.py @@ -3,7 +3,7 @@ import json import httpx import pytest -from inse.works.search_client import MissingApiKeyError +from inse.exceptions import MissingApiKeyError from inse.works.search_client import OpenAlexWorksSearchClient @@ -152,37 +152,47 @@ def test_author_works_query_adds_topic_filter(): ] +from unittest.mock import AsyncMock, patch + + @pytest.mark.anyio async def test_search_author_works_passes_institution_filter_to_query(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) - assert body["query"]["bool"]["must"][1]["nested"]["path"] == ( - "authorships.institutions" + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + institution_id=["https://openalex.org/I205640436"], ) + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") + assert body["query"]["bool"]["must"][1]["nested"]["path"] == "authorships.institutions" assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == { "authorships.institutions.id": ["https://openalex.org/I205640436"], } - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_author_works( - "A5023888391", - page=1, - size=20, - institution_id=["https://openalex.org/I205640436"], - ) @pytest.mark.anyio async def test_search_author_works_passes_topic_filter_to_query(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_author_works( + "A5023888391", + page=1, + size=20, + topic_id=["https://openalex.org/T12419"], + ) + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") assert body["query"]["bool"]["filter"] == [ { "bool": { @@ -207,61 +217,55 @@ async def test_search_author_works_passes_topic_filter_to_query(): }, }, ] - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_author_works( - "A5023888391", - page=1, - size=20, - topic_id=["https://openalex.org/T12419"], - ) @pytest.mark.anyio async def test_search_author_works_calls_elasticsearch_index_with_api_key(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.method == "POST" - assert request.url.path == "/elastic/openalex-works/_search" - assert request.headers["Authorization"] == "ApiKey test-key" - return httpx.Response(200, json={"hits": {"total": {"value": 0}, "hits": []}}) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 0}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) + result = await client.search_author_works("A5023888391", page=1, size=20) - result = await client.search_author_works("A5023888391", page=1, size=20) - - assert result == {"hits": {"total": {"value": 0}, "hits": []}} + assert result == {"hits": {"total": {"value": 0}, "hits": []}} @pytest.mark.anyio async def test_search_work_filters_by_work_id(): - def handler(request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) + with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search: + mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}} + client = OpenAlexWorksSearchClient(index="openalex-works") + + await client.search_work("W2741809807") + + assert mock_search.call_count == 1 + _, kwargs = mock_search.call_args + body = kwargs.get("body") assert body == { - "size": 1, - "query": {"term": {"id": "https://openalex.org/W2741809807"}}, + "query": { + "bool": { + "should": [ + { + "term": { + "_id": { + "value": "W2741809807", + "boost": 5 + } + } + }, + { + "term": { + "doi": { + "value": "https://doi.org/w2741809807", + "boost": 3 + } + } + } + ], + "minimum_should_match": 1 + } + } } - return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}}) - - client = OpenAlexWorksSearchClient( - base_url="https://project.nes.uni-due.de/elastic", - index="openalex-works", - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - await client.search_work("W2741809807") @pytest.mark.anyio diff --git a/service/uv.lock b/service/uv.lock index d4016c83..4a7e9873 100644 --- a/service/uv.lock +++ b/service/uv.lock @@ -178,36 +178,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" }, ] -[[package]] -name = "elastic-transport" -version = "9.4.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "sniffio" }, - { name = "urllib3" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" }, -] - -[[package]] -name = "elasticsearch" -version = "9.4.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "elastic-transport" }, - { name = "python-dateutil" }, - { name = "sniffio" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" }, -] - [[package]] name = "fastapi" version = "0.115.14" @@ -799,18 +769,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" }, ] -[[package]] -name = "python-dateutil" -version = "2.9.0.post0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, -] - [[package]] name = "python-dotenv" version = "1.2.2" @@ -1127,7 +1085,6 @@ source = { virtual = "." } dependencies = [ { name = "cryptography" }, { name = "dotenv" }, - { name = "elasticsearch" }, { name = "fastapi" }, { name = "httpx" }, { name = "openai" }, @@ -1148,7 +1105,6 @@ dependencies = [ requires-dist = [ { name = "cryptography", specifier = "~=42.0.0" }, { name = "dotenv", specifier = ">=0.9.9" }, - { name = "elasticsearch", specifier = "~=9.4.0" }, { name = "fastapi", specifier = "~=0.115.0" }, { name = "httpx", specifier = "~=0.27.0" }, { name = "openai", specifier = "~=2.41.0" }, @@ -1182,15 +1138,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, ] -[[package]] -name = "six" -version = "1.17.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, -] - [[package]] name = "sniffio" version = "1.3.1" @@ -1421,15 +1368,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, ] -[[package]] -name = "urllib3" -version = "2.7.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, -] - [[package]] name = "uvicorn" version = "0.29.0" diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 27cbb63a..db7e24ac 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -163,7 +163,10 @@ export const routes: Routes = [ import('./modules/person-projects/person-projects.component').then( (mod) => mod.PersonProjectsComponent, ), - resolve: { dfgProjectPage: dfgProjectsResolver }, + resolve: { + dfgProjectPage: dfgProjectsResolver, + personCordisEuProjectPage: personCordisEuProjectPageResolver, + }, runGuardsAndResolvers: (from, to) => { const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search']; return keys.some(