|
| 1 | +"""Async ScienceDirect client built on httpx.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +from collections.abc import Mapping |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +import httpx |
| 10 | + |
| 11 | +from . import rate_limits |
| 12 | +from .settings import Settings |
| 13 | + |
| 14 | +__all__ = ["ScienceDirectClient"] |
| 15 | + |
| 16 | + |
| 17 | +class ScienceDirectClient: |
| 18 | + """Thin wrapper around httpx.AsyncClient with Elsevier defaults.""" |
| 19 | + |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + settings: Settings, |
| 23 | + *, |
| 24 | + transport: httpx.AsyncBaseTransport | None = None, |
| 25 | + max_retries: int = 3, |
| 26 | + ) -> None: |
| 27 | + self._settings = settings |
| 28 | + self._transport = transport |
| 29 | + self._max_retries = max(0, max_retries) |
| 30 | + self._client: httpx.AsyncClient | None = None |
| 31 | + concurrency = settings.concurrency or 1 |
| 32 | + self._semaphore = asyncio.Semaphore(concurrency) |
| 33 | + |
| 34 | + async def __aenter__(self) -> ScienceDirectClient: |
| 35 | + await self._ensure_client() |
| 36 | + return self |
| 37 | + |
| 38 | + async def __aexit__(self, exc_type, exc, tb) -> None: # type: ignore[override] |
| 39 | + if self._client is not None: |
| 40 | + await self._client.aclose() |
| 41 | + self._client = None |
| 42 | + |
| 43 | + async def request( |
| 44 | + self, |
| 45 | + method: str, |
| 46 | + path: str, |
| 47 | + *, |
| 48 | + params: Mapping[str, Any] | None = None, |
| 49 | + accept: str | None = None, |
| 50 | + ) -> httpx.Response: |
| 51 | + """Perform an HTTP request and return the response.""" |
| 52 | + return await self._request(method, path, params=params, accept=accept) |
| 53 | + |
| 54 | + async def get_json( |
| 55 | + self, |
| 56 | + path: str, |
| 57 | + *, |
| 58 | + params: Mapping[str, Any] | None = None, |
| 59 | + ) -> dict[str, Any]: |
| 60 | + """Perform a GET request expecting JSON.""" |
| 61 | + response = await self.request( |
| 62 | + "GET", |
| 63 | + path, |
| 64 | + params=params, |
| 65 | + accept="application/json", |
| 66 | + ) |
| 67 | + return response.json() |
| 68 | + |
| 69 | + async def get_xml( |
| 70 | + self, |
| 71 | + path: str, |
| 72 | + *, |
| 73 | + params: Mapping[str, Any] | None = None, |
| 74 | + ) -> str: |
| 75 | + """Perform a GET request expecting XML.""" |
| 76 | + response = await self.request( |
| 77 | + "GET", |
| 78 | + path, |
| 79 | + params=params, |
| 80 | + accept="application/xml", |
| 81 | + ) |
| 82 | + return response.text |
| 83 | + |
| 84 | + async def _ensure_client(self) -> None: |
| 85 | + if self._client is not None: |
| 86 | + return |
| 87 | + headers: dict[str, str] = { |
| 88 | + "X-ELS-APIKey": self._settings.api_key, |
| 89 | + "User-Agent": self._settings.user_agent, |
| 90 | + } |
| 91 | + if self._settings.insttoken: |
| 92 | + headers["X-ELS-Insttoken"] = self._settings.insttoken |
| 93 | + timeout = httpx.Timeout(self._settings.timeout) |
| 94 | + proxy_value = self._settings.https_proxy or self._settings.http_proxy |
| 95 | + self._client = httpx.AsyncClient( |
| 96 | + base_url=self._settings.base_url, |
| 97 | + timeout=timeout, |
| 98 | + headers=headers, |
| 99 | + transport=self._transport, |
| 100 | + http2=True, |
| 101 | + proxy=proxy_value, |
| 102 | + ) |
| 103 | + |
| 104 | + async def _request( |
| 105 | + self, |
| 106 | + method: str, |
| 107 | + path: str, |
| 108 | + *, |
| 109 | + params: Mapping[str, Any] | None, |
| 110 | + accept: str | None, |
| 111 | + ) -> httpx.Response: |
| 112 | + await self._ensure_client() |
| 113 | + assert self._client is not None |
| 114 | + attempt = 0 |
| 115 | + while True: |
| 116 | + request_headers = {"Accept": accept} if accept else {} |
| 117 | + async with self._semaphore: |
| 118 | + response = await self._client.request( |
| 119 | + method, |
| 120 | + path, |
| 121 | + params=params, |
| 122 | + headers=request_headers, |
| 123 | + ) |
| 124 | + delay = rate_limits.get_retry_delay(response) |
| 125 | + if ( |
| 126 | + delay is not None |
| 127 | + and response.status_code in {429, 500, 503} |
| 128 | + and attempt < self._max_retries |
| 129 | + ): |
| 130 | + await asyncio.sleep(delay) |
| 131 | + attempt += 1 |
| 132 | + continue |
| 133 | + |
| 134 | + try: |
| 135 | + response.raise_for_status() |
| 136 | + except httpx.HTTPStatusError as exc: |
| 137 | + raise exc |
| 138 | + return response |
0 commit comments