|
| 1 | +from __future__ import annotations |
| 2 | + |
1 | 3 | import atexit |
| 4 | +import threading |
| 5 | +from contextlib import contextmanager |
| 6 | +from functools import cached_property |
2 | 7 | from http import HTTPStatus |
| 8 | +from typing import TYPE_CHECKING, Any, ClassVar, Generic, Protocol, TypeVar |
3 | 9 |
|
4 | 10 | import requests |
5 | 11 |
|
6 | 12 | from beets import __version__ |
7 | 13 |
|
| 14 | +if TYPE_CHECKING: |
| 15 | + from collections.abc import Iterator |
| 16 | + |
| 17 | + |
| 18 | +class BeetsHTTPError(requests.exceptions.HTTPError): |
| 19 | + STATUS: ClassVar[HTTPStatus] |
| 20 | + |
| 21 | + def __init__(self, *args, **kwargs) -> None: |
| 22 | + super().__init__( |
| 23 | + f"HTTP Error: {self.STATUS.value} {self.STATUS.phrase}", |
| 24 | + *args, |
| 25 | + **kwargs, |
| 26 | + ) |
| 27 | + |
| 28 | + |
| 29 | +class HTTPNotFoundError(BeetsHTTPError): |
| 30 | + STATUS = HTTPStatus.NOT_FOUND |
| 31 | + |
| 32 | + |
| 33 | +class Closeable(Protocol): |
| 34 | + """Protocol for objects that have a close method.""" |
| 35 | + |
| 36 | + def close(self) -> None: ... |
| 37 | + |
| 38 | + |
| 39 | +C = TypeVar("C", bound=Closeable) |
| 40 | + |
| 41 | + |
| 42 | +class SingletonMeta(type, Generic[C]): |
| 43 | + """Metaclass ensuring a single shared instance per class. |
| 44 | +
|
| 45 | + Creates one instance per class type on first instantiation, reusing it |
| 46 | + for all subsequent calls. Automatically registers cleanup on program exit |
| 47 | + for proper resource management. |
| 48 | + """ |
| 49 | + |
| 50 | + _instances: ClassVar[dict[type[Any], Any]] = {} |
| 51 | + _lock: ClassVar[threading.Lock] = threading.Lock() |
8 | 52 |
|
9 | | -class HTTPNotFoundError(requests.exceptions.HTTPError): |
10 | | - pass |
| 53 | + def __call__(cls, *args: Any, **kwargs: Any) -> C: |
| 54 | + if cls not in cls._instances: |
| 55 | + with cls._lock: |
| 56 | + if cls not in SingletonMeta._instances: |
| 57 | + instance = super().__call__(*args, **kwargs) |
| 58 | + SingletonMeta._instances[cls] = instance |
| 59 | + atexit.register(instance.close) |
| 60 | + return SingletonMeta._instances[cls] |
11 | 61 |
|
12 | 62 |
|
13 | | -class CaptchaError(requests.exceptions.HTTPError): |
14 | | - pass |
| 63 | +class TimeoutSession(requests.Session, metaclass=SingletonMeta): |
| 64 | + """HTTP session with automatic timeout and status checking. |
15 | 65 |
|
| 66 | + Extends requests.Session to provide sensible defaults for beets HTTP |
| 67 | + requests: automatic timeout enforcement, status code validation, and |
| 68 | + proper user agent identification. |
| 69 | + """ |
16 | 70 |
|
17 | | -class TimeoutSession(requests.Session): |
18 | 71 | def __init__(self, *args, **kwargs) -> None: |
19 | 72 | super().__init__(*args, **kwargs) |
20 | 73 | self.headers["User-Agent"] = f"beets/{__version__} https://beets.io/" |
21 | 74 |
|
22 | | - @atexit.register |
23 | | - def close_session(): |
24 | | - """Close the requests session on shut down.""" |
25 | | - self.close() |
26 | | - |
27 | 75 | def request(self, *args, **kwargs): |
28 | | - """Wrap the request method to raise an exception on HTTP errors.""" |
| 76 | + """Execute HTTP request with automatic timeout and status validation. |
| 77 | +
|
| 78 | + Ensures all requests have a timeout (defaults to 10 seconds) and raises |
| 79 | + an exception for HTTP error status codes. |
| 80 | + """ |
29 | 81 | kwargs.setdefault("timeout", 10) |
30 | 82 | r = super().request(*args, **kwargs) |
31 | | - if r.status_code == HTTPStatus.NOT_FOUND: |
32 | | - raise HTTPNotFoundError("HTTP Error: Not Found", response=r) |
33 | | - if 300 <= r.status_code < 400: |
34 | | - raise CaptchaError("Captcha is required", response=r) |
35 | | - |
36 | 83 | r.raise_for_status() |
37 | 84 |
|
38 | 85 | return r |
| 86 | + |
| 87 | + |
| 88 | +class RequestHandler: |
| 89 | + """Manages HTTP requests with custom error handling and session management. |
| 90 | +
|
| 91 | + Provides a reusable interface for making HTTP requests with automatic |
| 92 | + conversion of standard HTTP errors to beets-specific exceptions. Supports |
| 93 | + custom session types and error mappings that can be overridden by |
| 94 | + subclasses. |
| 95 | + """ |
| 96 | + |
| 97 | + session_type: ClassVar[type[TimeoutSession]] = TimeoutSession |
| 98 | + explicit_http_errors: ClassVar[list[type[BeetsHTTPError]]] = [ |
| 99 | + HTTPNotFoundError |
| 100 | + ] |
| 101 | + |
| 102 | + @cached_property |
| 103 | + def session(self) -> Any: |
| 104 | + """Lazily initialize and cache the HTTP session.""" |
| 105 | + return self.session_type() |
| 106 | + |
| 107 | + def status_to_error( |
| 108 | + self, code: int |
| 109 | + ) -> type[requests.exceptions.HTTPError] | None: |
| 110 | + """Map HTTP status codes to beets-specific exception types. |
| 111 | +
|
| 112 | + Searches the configured explicit HTTP errors for a matching status code. |
| 113 | + Returns None if no specific error type is registered for the given code. |
| 114 | + """ |
| 115 | + return next( |
| 116 | + (e for e in self.explicit_http_errors if e.STATUS == code), None |
| 117 | + ) |
| 118 | + |
| 119 | + @contextmanager |
| 120 | + def handle_http_error(self) -> Iterator[None]: |
| 121 | + """Convert standard HTTP errors to beets-specific exceptions. |
| 122 | +
|
| 123 | + Wraps operations that may raise HTTPError, automatically translating |
| 124 | + recognized status codes into their corresponding beets exception types. |
| 125 | + Unrecognized errors are re-raised unchanged. |
| 126 | + """ |
| 127 | + try: |
| 128 | + yield |
| 129 | + except requests.exceptions.HTTPError as e: |
| 130 | + if beets_error := self.status_to_error(e.response.status_code): |
| 131 | + raise beets_error(response=e.response) from e |
| 132 | + raise |
| 133 | + |
| 134 | + def request(self, method: str, *args, **kwargs) -> requests.Response: |
| 135 | + """Perform HTTP request using the session with automatic error handling. |
| 136 | +
|
| 137 | + Delegates to the underlying session method while converting recognized |
| 138 | + HTTP errors to beets-specific exceptions through the error handler. |
| 139 | + """ |
| 140 | + with self.handle_http_error(): |
| 141 | + return getattr(self.session, method)(*args, **kwargs) |
| 142 | + |
| 143 | + def get(self, *args, **kwargs) -> requests.Response: |
| 144 | + """Perform HTTP GET request with automatic error handling.""" |
| 145 | + return self.request("get", *args, **kwargs) |
| 146 | + |
| 147 | + def fetch_json(self, *args, **kwargs): |
| 148 | + """Fetch and parse JSON data from an HTTP endpoint.""" |
| 149 | + return self.get(*args, **kwargs).json() |
0 commit comments