|
| 1 | +"""HTTP transport for the Agent Memory service. |
| 2 | +
|
| 3 | +Handles OAuth2 ``client_credentials`` token acquisition with lazy, |
| 4 | +expiry-aware caching. If ``token_url`` is not configured, requests are |
| 5 | +sent unauthenticated — expected for local development environments. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import logging |
| 11 | +from datetime import datetime, timedelta |
| 12 | +from typing import Any, Optional |
| 13 | +from urllib.parse import quote, urlencode |
| 14 | + |
| 15 | +import requests |
| 16 | +from oauthlib.oauth2 import BackendApplicationClient |
| 17 | +from requests.exceptions import RequestException, Timeout |
| 18 | +from requests_oauthlib import OAuth2Session |
| 19 | + |
| 20 | +from sap_cloud_sdk.agent_memory.config import AgentMemoryConfig |
| 21 | +from sap_cloud_sdk.agent_memory.exceptions import ( |
| 22 | + AgentMemoryHttpError, |
| 23 | + AgentMemoryNotFoundError, |
| 24 | +) |
| 25 | + |
| 26 | +logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | +_TOKEN_EXPIRY_BUFFER_SECONDS = 60 |
| 29 | + |
| 30 | + |
| 31 | +class HttpTransport: |
| 32 | + """Internal HTTP transport for the Agent Memory service. |
| 33 | +
|
| 34 | + Manages OAuth2 token lifecycle (lazy acquire + expiry-aware caching) and |
| 35 | + attaches the ``Authorization`` header to every request automatically via |
| 36 | + ``OAuth2Session``. In no-auth mode (no ``token_url``), a plain |
| 37 | + ``requests.Session`` is used instead. |
| 38 | +
|
| 39 | + Args: |
| 40 | + config: Service configuration. |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self, config: AgentMemoryConfig) -> None: |
| 44 | + self._config = config |
| 45 | + self._oauth: Optional[OAuth2Session] = None |
| 46 | + self._plain_session: Optional[requests.Session] = None |
| 47 | + self._token_expires_at: Optional[datetime] = None |
| 48 | + |
| 49 | + def close(self) -> None: |
| 50 | + """Close the underlying HTTP session(s) and release resources.""" |
| 51 | + if self._oauth is not None: |
| 52 | + self._oauth.close() |
| 53 | + self._oauth = None |
| 54 | + if self._plain_session is not None: |
| 55 | + self._plain_session.close() |
| 56 | + self._plain_session = None |
| 57 | + |
| 58 | + # ── Public HTTP methods ──────────────────────────────────────────────────── |
| 59 | + |
| 60 | + def get(self, path: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]: |
| 61 | + """Perform a GET request. |
| 62 | +
|
| 63 | + Args: |
| 64 | + path: API path (appended to ``base_url``). |
| 65 | + params: Optional query parameters. |
| 66 | +
|
| 67 | + Returns: |
| 68 | + Parsed JSON response body. |
| 69 | +
|
| 70 | + Raises: |
| 71 | + AgentMemoryHttpError: On HTTP errors or network failures. |
| 72 | + AgentMemoryNotFoundError: If the server returns 404. |
| 73 | + """ |
| 74 | + return self._request("GET", path, params=params) |
| 75 | + |
| 76 | + def post(self, path: str, json: Optional[dict[str, Any]] = None) -> dict[str, Any]: |
| 77 | + """Perform a POST request. |
| 78 | +
|
| 79 | + Args: |
| 80 | + path: API path (appended to ``base_url``). |
| 81 | + json: Optional request body dict (serialised to JSON). |
| 82 | +
|
| 83 | + Returns: |
| 84 | + Parsed JSON response body. Returns an empty dict for 204 responses. |
| 85 | +
|
| 86 | + Raises: |
| 87 | + AgentMemoryHttpError: On HTTP errors or network failures. |
| 88 | + AgentMemoryNotFoundError: If the server returns 404. |
| 89 | + """ |
| 90 | + return self._request("POST", path, json=json) |
| 91 | + |
| 92 | + def patch(self, path: str, json: Optional[dict[str, Any]] = None) -> dict[str, Any]: |
| 93 | + """Perform a PATCH request. |
| 94 | +
|
| 95 | + Args: |
| 96 | + path: API path (appended to ``base_url``). |
| 97 | + json: Optional request body dict (serialised to JSON). |
| 98 | +
|
| 99 | + Returns: |
| 100 | + Parsed JSON response body. Returns an empty dict for 204 responses. |
| 101 | +
|
| 102 | + Raises: |
| 103 | + AgentMemoryHttpError: On HTTP errors or network failures. |
| 104 | + AgentMemoryNotFoundError: If the server returns 404. |
| 105 | + """ |
| 106 | + return self._request("PATCH", path, json=json) |
| 107 | + |
| 108 | + def delete(self, path: str) -> None: |
| 109 | + """Perform a DELETE request. |
| 110 | +
|
| 111 | + Args: |
| 112 | + path: API path (appended to ``base_url``). |
| 113 | +
|
| 114 | + Raises: |
| 115 | + AgentMemoryHttpError: On HTTP errors or network failures. |
| 116 | + AgentMemoryNotFoundError: If the server returns 404. |
| 117 | + """ |
| 118 | + self._request("DELETE", path) |
| 119 | + |
| 120 | + # ── Internal helpers ─────────────────────────────────────────────────────── |
| 121 | + |
| 122 | + def _get_session(self) -> requests.Session: |
| 123 | + """Return a session ready to make requests. |
| 124 | +
|
| 125 | + In no-auth mode, returns a plain ``requests.Session`` (created once). |
| 126 | + In OAuth2 mode, returns an ``OAuth2Session`` with a valid token, |
| 127 | + fetching or refreshing the token if needed. |
| 128 | + """ |
| 129 | + if not self._config.token_url: |
| 130 | + if self._plain_session is None: |
| 131 | + self._plain_session = requests.Session() |
| 132 | + return self._plain_session |
| 133 | + |
| 134 | + if ( |
| 135 | + self._oauth is not None |
| 136 | + and self._token_expires_at is not None |
| 137 | + and datetime.now() < self._token_expires_at |
| 138 | + ): |
| 139 | + return self._oauth |
| 140 | + |
| 141 | + self._oauth = self._fetch_token() |
| 142 | + return self._oauth |
| 143 | + |
| 144 | + def _fetch_token(self) -> OAuth2Session: |
| 145 | + """Acquire a new OAuth2 ``client_credentials`` token. |
| 146 | +
|
| 147 | + Returns: |
| 148 | + An ``OAuth2Session`` with a valid token attached. |
| 149 | +
|
| 150 | + Raises: |
| 151 | + AgentMemoryHttpError: If the token endpoint returns an error or is unreachable. |
| 152 | + """ |
| 153 | + try: |
| 154 | + client = BackendApplicationClient(client_id=self._config.client_id) |
| 155 | + oauth = OAuth2Session(client=client) |
| 156 | + token = oauth.fetch_token( |
| 157 | + token_url=self._config.token_url, |
| 158 | + client_id=self._config.client_id, |
| 159 | + client_secret=self._config.client_secret, |
| 160 | + timeout=self._config.timeout, |
| 161 | + ) |
| 162 | + except Exception as exc: |
| 163 | + raise AgentMemoryHttpError(f"Failed to obtain OAuth2 token: {exc}") from exc |
| 164 | + |
| 165 | + expires_in: int = token.get("expires_in", 3600) |
| 166 | + self._token_expires_at = datetime.now() + timedelta( |
| 167 | + seconds=expires_in - _TOKEN_EXPIRY_BUFFER_SECONDS |
| 168 | + ) |
| 169 | + |
| 170 | + if self._oauth is not None: |
| 171 | + self._oauth.close() |
| 172 | + |
| 173 | + logger.debug( |
| 174 | + "Obtained new Agent Memory OAuth2 token (expires in %ds)", expires_in |
| 175 | + ) |
| 176 | + return oauth |
| 177 | + |
| 178 | + def _request(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]: |
| 179 | + """Execute an HTTP request using the appropriate session.""" |
| 180 | + logger.debug("%s %s", method, path) |
| 181 | + |
| 182 | + url = f"{self._config.base_url}{path}" |
| 183 | + if "params" in kwargs: |
| 184 | + raw_params: dict[str, Any] = kwargs.pop("params") |
| 185 | + if raw_params: |
| 186 | + url = f"{url}?{urlencode(raw_params, quote_via=quote)}" |
| 187 | + |
| 188 | + session = self._get_session() |
| 189 | + headers = {"Content-Type": "application/json"} |
| 190 | + |
| 191 | + try: |
| 192 | + response = session.request( |
| 193 | + method, url, headers=headers, timeout=self._config.timeout, **kwargs |
| 194 | + ) |
| 195 | + except Timeout as exc: |
| 196 | + raise AgentMemoryHttpError(f"Request timed out: {method} {path}") from exc |
| 197 | + except RequestException as exc: |
| 198 | + raise AgentMemoryHttpError( |
| 199 | + f"Request failed: {method} {path} — {exc}" |
| 200 | + ) from exc |
| 201 | + |
| 202 | + if response.status_code == 204 or not response.content: |
| 203 | + return {} |
| 204 | + |
| 205 | + if response.status_code == 404: |
| 206 | + raise AgentMemoryNotFoundError( |
| 207 | + f"Resource not found: {method} {path}", |
| 208 | + status_code=404, |
| 209 | + response_text=response.text, |
| 210 | + ) |
| 211 | + |
| 212 | + if not response.ok: |
| 213 | + raise AgentMemoryHttpError( |
| 214 | + f"Agent Memory service request failed. " |
| 215 | + f"Method: {method}, Path: {path}, " |
| 216 | + f"Status: {response.status_code}, Response: {response.text}", |
| 217 | + status_code=response.status_code, |
| 218 | + response_text=response.text, |
| 219 | + ) |
| 220 | + |
| 221 | + return response.json() |
0 commit comments