1"""I/O-free pieces shared by the sync and async clients: defaults, retry policy, tokens and response parsing."""
2
3import email.utils
4import random
5from dataclasses import dataclass, field
6from datetime import UTC, datetime, timedelta
7from importlib.metadata import version
8from typing import TYPE_CHECKING, Final
9
10import httpx
11import msgspec
12
13from wow._exceptions import APIConnectionError, APIResponseValidationError, APITimeoutError, error_for_response
14
15if TYPE_CHECKING:
16 from collections.abc import Mapping
17
18 from wow._types import Locale, NamespaceKind, Region
19
20__all__ = [
21 "DEFAULT_MAX_RETRIES",
22 "DEFAULT_TIMEOUT",
23 "OAUTH_URL",
24 "OAuthToken",
25 "api_url",
26 "backoff",
27 "connection_error",
28 "is_transient",
29 "namespace_for",
30 "parse_model",
31 "parse_token",
32 "raise_for_status",
33 "request_params",
34 "retry_delay",
35 "should_retry",
36]
37
38DEFAULT_TIMEOUT: Final = httpx.Timeout(15.0, connect=5.0)
39"""Fifteen seconds per read, write and pool wait; five to connect."""
40
41DEFAULT_MAX_RETRIES: Final = 2
42"""Retries after the first attempt for connection errors, timeouts, 408, 429 and 5xx responses."""
43
44OAUTH_URL: Final = "https://oauth.battle.net"
45"""The OAuth host shared by the US, EU, KR and TW regions."""
46
47USER_AGENT: Final = f"wow-python/{version('wow')} httpx/{httpx.__version__}"
48
49INITIAL_RETRY_DELAY: Final = 0.5
50MAX_RETRY_DELAY: Final = 8.0
51MAX_RETRY_AFTER: Final = 60.0
52"""A ``Retry-After`` longer than this is not waited out; the error is raised instead."""
53
54TOKEN_EXPIRY_MARGIN: Final = timedelta(minutes=5)
55"""App tokens are refreshed this long before Battle.net says they expire."""
56
57_RETRYABLE_CLIENT_ERRORS: Final = frozenset({httpx.codes.REQUEST_TIMEOUT, httpx.codes.TOO_MANY_REQUESTS})
58
59_PERMANENT_FAILURES: Final = (httpx.UnsupportedProtocol, httpx.TooManyRedirects)
60"""Failures that every attempt would repeat: a URL with no ``http://`` or ``https://``, and a redirect loop."""
61
62
63def api_url(region: Region) -> str:
64 """Return the API host for a region, such as ``https://us.api.blizzard.com``."""
65 return f"https://{region.value}.api.blizzard.com"
66
67
68def namespace_for(kind: NamespaceKind, region: Region, static_version: str | None = None) -> str:
69 """Return the WoW Forever namespace for a document family, such as ``static-forever-us``.
70
71 ``static_version`` pins a ``static`` request to a specific build, such as ``static-1.60.1_70399-forever-us``.
72 It is ignored for ``dynamic`` and ``profile`` requests, which carry no build version.
73 """
74 if kind == "static" and static_version:
75 return f"{kind}-{static_version}-forever-{region.value}"
76 return f"{kind}-forever-{region.value}"
77
78
79def should_retry(response: httpx.Response) -> bool:
80 """Whether a failed response is worth another attempt: 408, 429 and every 5xx."""
81 return response.is_server_error or response.status_code in _RETRYABLE_CLIENT_ERRORS
82
83
84def is_transient(error: httpx.RequestError) -> bool:
85 """Whether a request that got no usable response is worth another attempt."""
86 return not isinstance(error, _PERMANENT_FAILURES)
87
88
89def backoff(retries_done: int) -> float:
90 """Exponential backoff: half a second doubling up to eight, minus up to 25% jitter so clients spread out."""
91 delay = min(INITIAL_RETRY_DELAY * 2**retries_done, MAX_RETRY_DELAY)
92 return delay * (1 - 0.25 * random.random()) # noqa: S311 - jitter, not cryptography
93
94
95def retry_delay(retries_done: int, response: httpx.Response) -> float | None:
96 """Seconds to wait before retrying ``response``, or ``None`` when the server asked for too long a wait.
97
98 ``Retry-After`` wins when it is valid, as whole seconds or an HTTP date (RFC 9110); otherwise :func:`backoff`
99 decides.
100 """
101 header = response.headers.get("retry-after")
102 if header is None:
103 return backoff(retries_done)
104 if header.isascii() and header.isdigit():
105 seconds = float(header)
106 else:
107 try:
108 seconds = (email.utils.parsedate_to_datetime(header) - datetime.now(UTC)).total_seconds()
109 except TypeError, ValueError:
110 return backoff(retries_done)
111 if seconds > MAX_RETRY_AFTER:
112 return None
113 return max(seconds, 0.0)
114
115
116def raise_for_status(response: httpx.Response) -> None:
117 """Raise the matching :class:`~wow.APIStatusError` subclass for a 4xx or 5xx response."""
118 if response.is_error:
119 raise error_for_response(response)
120
121
122def connection_error(method: str, error: httpx.RequestError) -> APIConnectionError:
123 """Wrap an ``httpx`` request failure in :class:`~wow.APITimeoutError` or :class:`~wow.APIConnectionError`."""
124 if isinstance(error, httpx.TimeoutException):
125 return APITimeoutError(f"timed out: {method} {error.request.url}", request=error.request)
126 return APIConnectionError(f"connection failed: {method} {error.request.url}: {error}", request=error.request)
127
128
129def parse_model[ModelT: msgspec.Struct](response: httpx.Response, model: type[ModelT]) -> ModelT:
130 """Decode a successful response body into ``model``."""
131 try:
132 return msgspec.json.decode(response.content, type=model)
133 except msgspec.DecodeError as error:
134 message = f"response from {response.request.url} does not match {model.__name__}"
135 raise APIResponseValidationError(message, response=response, error=error) from error
136
137
138@dataclass(frozen=True, slots=True)
[docs]
139class OAuthToken:
140 """An access token issued by ``oauth.battle.net``.
141
142 Attributes:
143 access_token: The bearer token to send to the API.
144 expires_at: When Battle.net stops accepting it.
145 scopes: The scopes it was granted; ``wow.profile`` is needed for profile routes.
146 token_type: Always ``bearer`` today.
147 sub: The Battle.net account id, for user tokens.
148 id_token: The OpenID Connect ID token, when ``openid`` was requested.
149 """
150
151 access_token: str = field(repr=False)
152 expires_at: datetime
153 scopes: frozenset[str] = frozenset()
154 token_type: str = "bearer" # noqa: S105 - a token type, not a secret
155 sub: str | None = None
156 id_token: str | None = field(default=None, repr=False)
157
[docs]
158 def expires_within(self, margin: timedelta) -> bool:
159 """Whether the token expires within ``margin`` from now."""
160 return datetime.now(UTC) + margin >= self.expires_at
161
162
163class _TokenPayload(msgspec.Struct, frozen=True):
164 """The JSON body of a successful ``/token`` response."""
165
166 access_token: str
167 expires_in: int
168 token_type: str = "bearer" # noqa: S105 - a token type, not a secret
169 scope: str = ""
170 sub: str | None = None
171 id_token: str | None = None
172
173
174def parse_token(response: httpx.Response) -> OAuthToken:
175 """Read a token endpoint response.
176
177 Raises:
178 APIStatusError: The token endpoint answered with an error, such as :class:`~wow.AuthenticationError`.
179 APIResponseValidationError: The body is not a token.
180 """
181 raise_for_status(response)
182 payload = parse_model(response, _TokenPayload)
183 return OAuthToken(
184 access_token=payload.access_token,
185 expires_at=datetime.now(UTC) + timedelta(seconds=payload.expires_in),
186 scopes=frozenset(payload.scope.split()),
187 token_type=payload.token_type,
188 sub=payload.sub,
189 id_token=payload.id_token,
190 )
191
192
193def request_params(
194 kind: NamespaceKind | None,
195 region: Region,
196 locale: Locale,
197 params: Mapping[str, str | int] | None,
198 static_version: str | None = None,
199) -> dict[str, str | int]:
200 """Merge the namespace and locale into a request's query parameters; explicit params win."""
201 merged: dict[str, str | int] = {"locale": locale}
202 if kind is not None:
203 merged["namespace"] = namespace_for(kind, region, static_version)
204 if params:
205 merged.update(params)
206 return merged