api_provider.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import asyncio
  2. import re
  3. from http import HTTPStatus
  4. from typing import Awaitable
  5. from typing import Callable
  6. from typing import Optional
  7. from urllib.parse import quote
  8. from urllib.parse import urlencode
  9. from urllib.parse import urljoin
  10. import aiohttp
  11. from aiohttp import ClientResponse
  12. from aiohttp import ClientSession
  13. from pydantic import AnyHttpUrl
  14. from clean_python import ctx
  15. from clean_python import Json
  16. from .exceptions import ApiException
  17. from .response import Response
  18. __all__ = ["ApiProvider"]
  19. RETRY_STATUSES = frozenset({413, 429, 503}) # like in urllib3
  20. def is_success(status: HTTPStatus) -> bool:
  21. """Returns True on 2xx status"""
  22. return (int(status) // 100) == 2
  23. JSON_CONTENT_TYPE_REGEX = re.compile(r"^application\/[^+]*[+]?(json);?.*$")
  24. def is_json_content_type(content_type: Optional[str]) -> bool:
  25. if not content_type:
  26. return False
  27. return bool(JSON_CONTENT_TYPE_REGEX.match(content_type))
  28. def join(url: str, path: str) -> str:
  29. """Results in a full url without trailing slash"""
  30. assert url.endswith("/")
  31. assert not path.startswith("/")
  32. result = urljoin(url, path)
  33. if result.endswith("/"):
  34. result = result[:-1]
  35. return result
  36. def add_query_params(url: str, params: Optional[Json]) -> str:
  37. if params is None:
  38. return url
  39. return url + "?" + urlencode(params, doseq=True)
  40. class ApiProvider:
  41. """Basic JSON API provider with retry policy and bearer tokens.
  42. The default retry policy has 3 retries with 1, 2, 4 second intervals.
  43. Args:
  44. url: The url of the API (with trailing slash)
  45. fetch_token: Callable that returns a token for a tenant id
  46. retries: Total number of retries per request
  47. backoff_factor: Multiplier for retry delay times (1, 2, 4, ...)
  48. """
  49. def __init__(
  50. self,
  51. url: AnyHttpUrl,
  52. fetch_token: Callable[[ClientSession, int], Awaitable[Optional[str]]],
  53. retries: int = 3,
  54. backoff_factor: float = 1.0,
  55. ):
  56. self._url = str(url)
  57. assert self._url.endswith("/")
  58. self._fetch_token = fetch_token
  59. assert retries > 0
  60. self._retries = retries
  61. self._backoff_factor = backoff_factor
  62. self._session = ClientSession()
  63. async def _request_with_retry(
  64. self,
  65. method: str,
  66. path: str,
  67. params: Optional[Json],
  68. json: Optional[Json],
  69. fields: Optional[Json],
  70. timeout: float,
  71. ) -> ClientResponse:
  72. assert ctx.tenant is not None
  73. headers = {}
  74. request_kwargs = {
  75. "method": method,
  76. "url": add_query_params(join(self._url, quote(path)), params),
  77. "timeout": timeout,
  78. "json": json,
  79. "data": fields,
  80. }
  81. token = await self._fetch_token(self._session, ctx.tenant.id)
  82. if token is not None:
  83. headers["Authorization"] = f"Bearer {token}"
  84. for attempt in range(self._retries):
  85. if attempt > 0:
  86. backoff = self._backoff_factor * 2 ** (attempt - 1)
  87. await asyncio.sleep(backoff)
  88. try:
  89. response = await self._session.request(
  90. headers=headers, **request_kwargs
  91. )
  92. await response.read()
  93. except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):
  94. if attempt == self._retries - 1:
  95. raise # propagate ClientError in case no retries left
  96. else:
  97. if response.status not in RETRY_STATUSES:
  98. return response # on all non-retry statuses: return response
  99. return response # retries exceeded; return the (possibly error) response
  100. async def request(
  101. self,
  102. method: str,
  103. path: str,
  104. params: Optional[Json] = None,
  105. json: Optional[Json] = None,
  106. fields: Optional[Json] = None,
  107. timeout: float = 5.0,
  108. ) -> Optional[Json]:
  109. response = await self._request_with_retry(
  110. method, path, params, json, fields, timeout
  111. )
  112. status = HTTPStatus(response.status)
  113. content_type = response.headers.get("Content-Type")
  114. if status is HTTPStatus.NO_CONTENT:
  115. return None
  116. if not is_json_content_type(content_type):
  117. raise ApiException(
  118. f"Unexpected content type '{content_type}'", status=status
  119. )
  120. body = await response.json()
  121. if is_success(status):
  122. return body
  123. else:
  124. raise ApiException(body, status=status)
  125. async def request_raw(
  126. self,
  127. method: str,
  128. path: str,
  129. params: Optional[Json] = None,
  130. json: Optional[Json] = None,
  131. fields: Optional[Json] = None,
  132. timeout: float = 5.0,
  133. ) -> Response:
  134. response = await self._request_with_retry(
  135. method, path, params, json, fields, timeout
  136. )
  137. return Response(
  138. status=response.status,
  139. data=await response.read(),
  140. content_type=response.headers.get("Content-Type"),
  141. )