|
| 1 | +import asyncio |
| 2 | +from typing import Any, Dict, Optional, Union |
| 3 | + |
| 4 | +import aiohttp |
| 5 | + |
| 6 | +from common.config.app_config import config |
| 7 | + |
| 8 | + |
| 9 | +class BaseAPIService: |
| 10 | + """Minimal async HTTP API service. |
| 11 | +
|
| 12 | + - Reads base endpoints from AppConfig using `from_config` factory. |
| 13 | + - Provides simple GET/POST helpers with JSON payloads. |
| 14 | + - Designed to be subclassed (e.g., MCPService, FoundryService). |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + base_url: str, |
| 20 | + *, |
| 21 | + default_headers: Optional[Dict[str, str]] = None, |
| 22 | + timeout_seconds: int = 30, |
| 23 | + session: Optional[aiohttp.ClientSession] = None, |
| 24 | + ) -> None: |
| 25 | + if not base_url: |
| 26 | + raise ValueError("base_url is required") |
| 27 | + self.base_url = base_url.rstrip("/") |
| 28 | + self.default_headers = default_headers or {} |
| 29 | + self.timeout = aiohttp.ClientTimeout(total=timeout_seconds) |
| 30 | + self._session_external = session is not None |
| 31 | + self._session: Optional[aiohttp.ClientSession] = session |
| 32 | + |
| 33 | + @classmethod |
| 34 | + def from_config( |
| 35 | + cls, |
| 36 | + endpoint_attr: str, |
| 37 | + *, |
| 38 | + default: Optional[str] = None, |
| 39 | + **kwargs: Any, |
| 40 | + ) -> "BaseAPIService": |
| 41 | + """Create a service using an endpoint attribute from AppConfig. |
| 42 | +
|
| 43 | + Args: |
| 44 | + endpoint_attr: Name of the attribute on AppConfig (e.g., 'AZURE_AI_AGENT_ENDPOINT'). |
| 45 | + default: Optional default if attribute missing or empty. |
| 46 | + **kwargs: Passed through to the constructor. |
| 47 | + """ |
| 48 | + base_url = getattr(config, endpoint_attr, None) or default |
| 49 | + if not base_url: |
| 50 | + raise ValueError( |
| 51 | + f"Endpoint '{endpoint_attr}' not configured in AppConfig and no default provided" |
| 52 | + ) |
| 53 | + return cls(base_url, **kwargs) |
| 54 | + |
| 55 | + async def _ensure_session(self) -> aiohttp.ClientSession: |
| 56 | + if self._session is None or self._session.closed: |
| 57 | + self._session = aiohttp.ClientSession(timeout=self.timeout) |
| 58 | + return self._session |
| 59 | + |
| 60 | + def _url(self, path: str) -> str: |
| 61 | + path = path or "" |
| 62 | + if not path: |
| 63 | + return self.base_url |
| 64 | + return f"{self.base_url}/{path.lstrip('/')}" |
| 65 | + |
| 66 | + async def _request( |
| 67 | + self, |
| 68 | + method: str, |
| 69 | + path: str = "", |
| 70 | + *, |
| 71 | + headers: Optional[Dict[str, str]] = None, |
| 72 | + params: Optional[Dict[str, Union[str, int, float]]] = None, |
| 73 | + json: Optional[Dict[str, Any]] = None, |
| 74 | + ) -> aiohttp.ClientResponse: |
| 75 | + session = await self._ensure_session() |
| 76 | + url = self._url(path) |
| 77 | + merged_headers = {**self.default_headers, **(headers or {})} |
| 78 | + return await session.request( |
| 79 | + method.upper(), url, headers=merged_headers, params=params, json=json |
| 80 | + ) |
| 81 | + |
| 82 | + async def get_json( |
| 83 | + self, |
| 84 | + path: str = "", |
| 85 | + *, |
| 86 | + headers: Optional[Dict[str, str]] = None, |
| 87 | + params: Optional[Dict[str, Union[str, int, float]]] = None, |
| 88 | + ) -> Any: |
| 89 | + resp = await self._request("GET", path, headers=headers, params=params) |
| 90 | + resp.raise_for_status() |
| 91 | + return await resp.json() |
| 92 | + |
| 93 | + async def post_json( |
| 94 | + self, |
| 95 | + path: str = "", |
| 96 | + *, |
| 97 | + headers: Optional[Dict[str, str]] = None, |
| 98 | + params: Optional[Dict[str, Union[str, int, float]]] = None, |
| 99 | + json: Optional[Dict[str, Any]] = None, |
| 100 | + ) -> Any: |
| 101 | + resp = await self._request( |
| 102 | + "POST", path, headers=headers, params=params, json=json |
| 103 | + ) |
| 104 | + resp.raise_for_status() |
| 105 | + return await resp.json() |
| 106 | + |
| 107 | + async def close(self) -> None: |
| 108 | + if self._session and not self._session.closed and not self._session_external: |
| 109 | + await self._session.close() |
| 110 | + |
| 111 | + async def __aenter__(self) -> "BaseAPIService": |
| 112 | + await self._ensure_session() |
| 113 | + return self |
| 114 | + |
| 115 | + async def __aexit__(self, exc_type, exc, tb) -> None: |
| 116 | + await self.close() |
0 commit comments