Debian Codegraph @

beetsplug/_utils/requests.py

raw
1 from __future__ import annotations
2
3 import atexit
4 import threading
5 import time
6 from contextlib import contextmanager
7 from functools import cached_property
8 from http import HTTPStatus
9 from typing import TYPE_CHECKING, Any, ClassVar, Generic, Protocol, TypeVar
10
11 import requests
12 from requests.adapters import HTTPAdapter
13 from urllib3.util.retry import Retry
14
15 from beets import __version__
16
17 if TYPE_CHECKING:
18 from collections.abc import Iterator
19
20
21 class BeetsHTTPError(requests.exceptions.HTTPError):
22 STATUS: ClassVar[HTTPStatus]
23
24 def __init__(self, *args, message: str | None = None, **kwargs) -> None:
25 if not message:
26 message = f"HTTP Error: {self.STATUS.value} {self.STATUS.phrase}"
27
28 super().__init__(message, *args, **kwargs)
29
30
31 class HTTPNotFoundError(BeetsHTTPError):
32 STATUS = HTTPStatus.NOT_FOUND
33
34
35 class Closeable(Protocol):
36 """Protocol for objects that have a close method."""
37
38 def close(self) -> None: ...
39
40
41 C = TypeVar("C", bound=Closeable)
42
43
44 class SingletonMeta(type, Generic[C]):
45 """Metaclass ensuring a single shared instance per class.
46
47 Creates one instance per class type on first instantiation, reusing it
48 for all subsequent calls. Automatically registers cleanup on program exit
49 for proper resource management.
50 """
51
52 _instances: ClassVar[dict[type[Any], Any]] = {}
53 _lock: ClassVar[threading.Lock] = threading.Lock()
54
55 def __call__(cls, *args: Any, **kwargs: Any) -> C:
56 if cls not in cls._instances:
57 with cls._lock:
58 if cls not in SingletonMeta._instances:
59 instance = super().__call__(*args, **kwargs)
60 SingletonMeta._instances[cls] = instance
61 atexit.register(instance.close)
62 return SingletonMeta._instances[cls]
63
64
65 class TimeoutAndRetrySession(requests.Session, metaclass=SingletonMeta):
66 """HTTP session with sensible defaults.
67
68 * default beets User-Agent header
69 * default request timeout
70 * automatic retries on transient connection or server errors
71 * raises exceptions for HTTP error status codes
72 """
73
74 def __init__(self, *args, **kwargs) -> None:
75 super().__init__(*args, **kwargs)
76 self.headers["User-Agent"] = f"beets/{__version__} https://beets.io/"
77
78 retry = Retry(
79 total=6,
80 backoff_factor=0.5,
81 status_forcelist=[
82 HTTPStatus.INTERNAL_SERVER_ERROR,
83 HTTPStatus.BAD_GATEWAY,
84 HTTPStatus.SERVICE_UNAVAILABLE,
85 HTTPStatus.GATEWAY_TIMEOUT,
86 HTTPStatus.TOO_MANY_REQUESTS,
87 ],
88 )
89 adapter = RateLimitAdapter(rate_limit=0.25, max_retries=retry)
90 self.mount("https://", adapter)
91 self.mount("http://", adapter)
92
93 def request(self, *args, **kwargs) -> requests.Response:
94 """Execute HTTP request with automatic timeout and status validation.
95
96 Ensures all requests have a timeout (defaults to 10 seconds) and raises
97 an exception for HTTP error status codes.
98 """
99 kwargs.setdefault("timeout", 10)
100 r = super().request(*args, **kwargs)
101 r.raise_for_status()
102
103 return r
104
105
106 class RateLimitAdapter(HTTPAdapter):
107 """HTTPAdapter that enforces minimum interval between requests.
108
109 Prevents server overload and 429 errors by sleeping when requests
110 come too fast. Thread-safe via lock.
111
112 Attributes:
113 rate_limit: Minimum seconds between requests. Default 0.25 (4/sec).
114
115 Override `_wait_time()` for custom strategies (token bucket, burst, etc.).
116 """
117
118 def __init__(self, rate_limit: float = 0.25, **kwargs) -> None:
119 super().__init__(**kwargs)
120 self.rate_limit = rate_limit
121 self._last_request_time = 0.0
122 self._lock = threading.Lock()
123
124 def _wait_time(self, elapsed: float) -> float:
125 """Return seconds to wait. Override for custom rate limiting."""
126 return max(0, self.rate_limit - elapsed)
127
128 def send(
129 self, request: requests.PreparedRequest, *args, **kwargs
130 ) -> requests.Response:
131 with self._lock:
132 elapsed = time.monotonic() - self._last_request_time
133 wait = self._wait_time(elapsed)
134 if wait > 0:
135 time.sleep(wait)
136 self._last_request_time = time.monotonic()
137 return super().send(request, *args, **kwargs)
138
139
140 class RequestHandler:
141 """Manages HTTP requests with custom error handling and session management.
142
143 Provides a reusable interface for making HTTP requests with automatic
144 conversion of standard HTTP errors to beets-specific exceptions. Supports
145 custom session types and error mappings that can be overridden by
146 subclasses.
147
148 Usage:
149 Subclass and override :class:`RequestHandler.create_session`,
150 :class:`RequestHandler.explicit_http_errors` or
151 :class:`RequestHandler.status_to_error()` to customize behavior.
152
153 Use
154
155 - :class:`RequestHandler.get_json()` to get JSON response data
156 - :class:`RequestHandler.get()` to get HTTP response object
157 - :class:`RequestHandler.request()` to invoke arbitrary HTTP methods
158
159 Feel free to define common methods that are used in multiple plugins.
160 """
161
162 #: List of custom exceptions to be raised for specific status codes.
163 explicit_http_errors: ClassVar[list[type[BeetsHTTPError]]] = [
164 HTTPNotFoundError
165 ]
166
167 def create_session(self) -> TimeoutAndRetrySession:
168 """Create a new HTTP session instance.
169
170 Can be overridden by subclasses to provide custom session types.
171 """
172 return TimeoutAndRetrySession()
173
174 @cached_property
175 def session(self) -> TimeoutAndRetrySession:
176 return self.create_session()
177
178 def status_to_error(
179 self, code: int
180 ) -> type[requests.exceptions.HTTPError] | None:
181 """Map HTTP status codes to beets-specific exception types.
182
183 Searches the configured explicit HTTP errors for a matching status code.
184 Returns None if no specific error type is registered for the given code.
185 """
186 return next(
187 (e for e in self.explicit_http_errors if e.STATUS == code), None
188 )
189
190 @contextmanager
191 def handle_http_error(self) -> Iterator[None]:
192 """Convert standard HTTP errors to beets-specific exceptions.
193
194 Wraps operations that may raise HTTPError, automatically translating
195 recognized status codes into their corresponding beets exception types.
196 Unrecognized errors are re-raised unchanged.
197 """
198 try:
199 yield
200 except requests.exceptions.HTTPError as e:
201 if beets_error := self.status_to_error(e.response.status_code):
202 raise beets_error(response=e.response) from e
203
204 raise
205
206 def request(self, *args, **kwargs) -> requests.Response:
207 """Perform HTTP request using the session with automatic error handling.
208
209 Delegates to the underlying session method while converting recognized
210 HTTP errors to beets-specific exceptions through the error handler.
211 """
212 with self.handle_http_error():
213 return self.session.request(*args, **kwargs)
214
215 def get(self, *args, **kwargs) -> requests.Response:
216 """Perform HTTP GET request with automatic error handling."""
217 return self.request("get", *args, **kwargs)
218
219 def put(self, *args, **kwargs) -> requests.Response:
220 """Perform HTTP PUT request with automatic error handling."""
221 return self.request("put", *args, **kwargs)
222
223 def delete(self, *args, **kwargs) -> requests.Response:
224 """Perform HTTP DELETE request with automatic error handling."""
225 return self.request("delete", *args, **kwargs)
226
227 def get_json(self, *args, **kwargs) -> Any:
228 """Fetch and parse JSON data from an HTTP endpoint."""
229 return self.get(*args, **kwargs).json()