|
| 1 | +# Copyright 2025 LINE Corporation |
| 2 | +# |
| 3 | +# LINE Corporation licenses this file to you under the Apache License, |
| 4 | +# version 2.0 (the "License"); you may not use this file except in compliance |
| 5 | +# with the License. You may obtain a copy of the License at: |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | +# License for the specific language governing permissions and limitations |
| 13 | +# under the License. |
| 14 | + |
| 15 | +from typing import Any, Dict, Union, Callable, TypeVar, Optional |
| 16 | + |
| 17 | +from httpx import AsyncClient, Limits, Response |
| 18 | +from tenacity import stop_after_attempt, wait_exponential, AsyncRetrying |
| 19 | + |
| 20 | +from centraldogma.exceptions import to_exception |
| 21 | + |
| 22 | +T = TypeVar("T") |
| 23 | + |
| 24 | + |
| 25 | +class BaseClient: |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + base_url: str, |
| 29 | + token: str, |
| 30 | + http2: bool = True, |
| 31 | + retries: int = 1, |
| 32 | + max_connections: int = 10, |
| 33 | + max_keepalive_connections: int = 2, |
| 34 | + **configs, |
| 35 | + ): |
| 36 | + assert retries >= 0, "retries must be greater than or equal to zero" |
| 37 | + assert max_connections > 0, "max_connections must be greater than zero" |
| 38 | + assert ( |
| 39 | + max_keepalive_connections > 0 |
| 40 | + ), "max_keepalive_connections must be greater than zero" |
| 41 | + |
| 42 | + base_url = base_url[:-1] if base_url[-1] == "/" else base_url |
| 43 | + |
| 44 | + for key in ["transport", "limits"]: |
| 45 | + if key in configs: |
| 46 | + del configs[key] |
| 47 | + |
| 48 | + self.retries = retries |
| 49 | + self.client = AsyncClient( |
| 50 | + base_url=f"{base_url}/api/v1", |
| 51 | + http2=http2, |
| 52 | + limits=Limits( |
| 53 | + max_connections=max_connections, |
| 54 | + max_keepalive_connections=max_keepalive_connections, |
| 55 | + ), |
| 56 | + **configs, |
| 57 | + ) |
| 58 | + self.token = token |
| 59 | + self.headers = self._get_headers(token) |
| 60 | + self.patch_headers = self._get_patch_headers(token) |
| 61 | + |
| 62 | + async def __aexit__(self, *_: Any) -> None: |
| 63 | + await self.client.aclose() |
| 64 | + |
| 65 | + async def request( |
| 66 | + self, |
| 67 | + method: str, |
| 68 | + path: str, |
| 69 | + handler: Optional[Dict[int, Callable[[Response], T]]] = None, |
| 70 | + **kwargs, |
| 71 | + ) -> Union[Response, T]: |
| 72 | + kwargs = self._set_request_headers(method, **kwargs) |
| 73 | + retryer = AsyncRetrying( |
| 74 | + stop=stop_after_attempt(self.retries + 1), |
| 75 | + wait=wait_exponential(max=60), |
| 76 | + reraise=True, |
| 77 | + ) |
| 78 | + return retryer(self._request, method, path, handler, **kwargs) |
| 79 | + |
| 80 | + def _set_request_headers(self, method: str, **kwargs) -> Dict: |
| 81 | + default_headers = self.patch_headers if method == "patch" else self.headers |
| 82 | + kwargs["headers"] = {**default_headers, **(kwargs.get("headers") or {})} |
| 83 | + return kwargs |
| 84 | + |
| 85 | + async def _request( |
| 86 | + self, |
| 87 | + method: str, |
| 88 | + path: str, |
| 89 | + handler: Optional[Dict[int, Callable[[Response], T]]] = None, |
| 90 | + **kwargs, |
| 91 | + ): |
| 92 | + resp = await self.client.request(method, path, **kwargs) |
| 93 | + if handler: |
| 94 | + converter = handler.get(resp.status_code) |
| 95 | + if converter: |
| 96 | + return converter(resp) |
| 97 | + else: # Unexpected response status |
| 98 | + raise to_exception(resp) |
| 99 | + return resp |
| 100 | + |
| 101 | + @staticmethod |
| 102 | + def _get_headers(token: str) -> Dict: |
| 103 | + return { |
| 104 | + "Authorization": f"bearer {token}", |
| 105 | + "Content-Type": "application/json", |
| 106 | + } |
| 107 | + |
| 108 | + @staticmethod |
| 109 | + def _get_patch_headers(token: str) -> Dict: |
| 110 | + return { |
| 111 | + "Authorization": f"bearer {token}", |
| 112 | + "Content-Type": "application/json-patch+json", |
| 113 | + } |
0 commit comments