From 4ec7597e5aa32b7e67014349f6c255f3dd721417 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:24:10 -0500 Subject: [PATCH 1/8] fix(exceptions): truncate response bodies in HTTP error messages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SwgohComlinkHTTPError.from_response put the whole response body in the exception message, so a large HTML error page from a proxy or CDN ended up in logs, tracebacks and bot error replies. The message now cuts a body longer than 512 characters and appends "… (N bytes total)". Classification and the code/detail attributes still use the full body, so "Rate exceeded" past the cut-off is still detected as a rate limit, and exc.response is unchanged. Refs #238 Co-Authored-By: Claude Opus 5.5 --- docs/api/exceptions.md | 4 +++- docs/migration.md | 9 +++++++++ src/swgoh_comlink/exceptions.py | 31 ++++++++++++++++++++++++++----- tests/unit/test_exceptions.py | 25 +++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/docs/api/exceptions.md b/docs/api/exceptions.md index 2ee1d65..d046f2a 100644 --- a/docs/api/exceptions.md +++ b/docs/api/exceptions.md @@ -36,7 +36,9 @@ When comlink answers with an HTTP error status, the clients raise a `SwgohComlinkHTTPError` (or one of its subclasses) from the original `httpx.HTTPStatusError`. `str(exc)` is `"HTTP {status}: {body}"`, as it has always been, so existing handlers that catch `SwgohComlinkException` keep -working. +working. Since v2.9 a body longer than 512 characters is cut in the message and +followed by `… (N bytes total)`; classification, `code` and `detail` still use +the full body, which stays available as `exc.response.text`. | Exception | Raised for | |---|---| diff --git a/docs/migration.md b/docs/migration.md index 2b23de1..441c264 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -308,6 +308,15 @@ added together. `ERA_DEFINITION`, `UBS_UPDATE`. New legacy-name aliases: `AbilityDecisionTrees`, `EraDefinitions`, `UBSUpdate`, `EpisodeDefinitions` (plural), `AccountLinking`. +## 10. v2.9 changes + +Upgrading from v2.8 to v2.9. + +- **HTTP error messages are truncated.** `str(exc)` for `SwgohComlinkHTTPError` cuts a + body longer than 512 characters and appends `… (N bytes total)`. Read the full body + from `exc.response.text`; `exc.code`, `exc.detail` and the exception class still come + from the full body. + ## Summary of changes | Area | Before (v1.x) | After | diff --git a/src/swgoh_comlink/exceptions.py b/src/swgoh_comlink/exceptions.py index 3511b6d..86f009a 100644 --- a/src/swgoh_comlink/exceptions.py +++ b/src/swgoh_comlink/exceptions.py @@ -34,6 +34,10 @@ # body such as ``{"code": "GAME_6", "message": "Rate exceeded!"}``. _RATE_LIMIT_TEXT = "rate exceeded" +# Longest body excerpt, in characters, that ``from_response`` puts in the +# exception message. The full body stays on ``exc.response``. +_MESSAGE_BODY_LIMIT = 512 + class SwgohComlinkException(Exception): """Base class for exceptions in this module.""" @@ -58,10 +62,13 @@ class SwgohComlinkTypeError(SwgohComlinkException, TypeError): class SwgohComlinkHTTPError(SwgohComlinkException): """Raised when the comlink service answers with an HTTP error status. - ``str(exc)`` is always ``"HTTP {status}: {body}"``, and the exception is - raised from the originating ``httpx.HTTPStatusError``, so code that matched - on the message or on ``SwgohComlinkException`` keeps working. Use - :meth:`from_response` to build the most specific subclass for a response. + ``str(exc)`` is ``"HTTP {status}: {body}"``, and the exception is raised + from the originating ``httpx.HTTPStatusError``, so code that matched on the + message or on ``SwgohComlinkException`` keeps working. A body longer than + 512 characters is cut to its first 512 characters in the message and + followed by ``"… (N bytes total)"``; the full body stays available through + :attr:`response`. Use :meth:`from_response` to build the most specific + subclass for a response. Attributes: status: The HTTP status code. @@ -116,6 +123,9 @@ def from_response(cls, response: httpx.Response) -> SwgohComlinkHTTPError: 3. :class:`SwgohComlinkClientError`: any other 4xx status. 4. :class:`SwgohComlinkHTTPError`: everything else (5xx). + Classification and the ``code`` and ``detail`` attributes use the full + body; only the message is truncated (see the class docstring). + Args: response: The error response returned by ``httpx``. @@ -135,7 +145,7 @@ def from_response(cls, response: httpx.Response) -> SwgohComlinkHTTPError: code, detail = _parse_error_body(body) error_cls = _classify(status, code, detail) return error_cls( - f"HTTP {status}: {body}", + f"HTTP {status}: {_truncate_body(body, len(response.content))}", status=status, code=code, detail=detail, @@ -167,6 +177,17 @@ class SwgohComlinkClientError(SwgohComlinkHTTPError): """ +def _truncate_body(body: str, size: int) -> str: + """Return ``body`` cut to ``_MESSAGE_BODY_LIMIT`` characters for a message. + + A cut body is followed by ``"… (size bytes total)"``, where ``size`` is the + length of the raw response content. + """ + if len(body) <= _MESSAGE_BODY_LIMIT: + return body + return f"{body[:_MESSAGE_BODY_LIMIT]}… ({size} bytes total)" + + def _parse_error_body(body: str) -> tuple[str | None, str | None]: """Return ``(code, detail)`` from an error body. diff --git a/tests/unit/test_exceptions.py b/tests/unit/test_exceptions.py index 68c09ec..f8d1b48 100644 --- a/tests/unit/test_exceptions.py +++ b/tests/unit/test_exceptions.py @@ -106,6 +106,31 @@ def test_from_response_non_json_body() -> None: assert error.retry_after is None +def test_from_response_truncates_large_body_in_message() -> None: + body = "" + "x" * 100_000 + "Rate exceeded" + response = httpx.Response(502, text=body, request=httpx.Request("POST", "http://h/x")) + + error = SwgohComlinkHTTPError.from_response(response) + + message = str(error) + assert len(message) < 600 + assert message.startswith(f"HTTP 502: {body[:512]}") + assert message.endswith(f"… ({len(response.content)} bytes total)") + # Classification and detail still use the full body, past the cut-off. + assert type(error) is SwgohComlinkRateLimitError + assert error.detail == body + assert error.response is response + assert error.response.text == body + + +def test_from_response_keeps_body_at_truncation_limit() -> None: + body = "y" * 512 + + error = SwgohComlinkHTTPError.from_response(httpx.Response(500, text=body)) + + assert str(error) == f"HTTP 500: {body}" + + def test_from_response_json_non_object_body() -> None: error = SwgohComlinkHTTPError.from_response(httpx.Response(500, json=["a", "b"])) From 16728120e8a440a2d5b08f33e1c90d345c9b6275 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:24:58 -0500 Subject: [PATCH 2/8] fix(core): validate and URL-encode the get_unit_stats language parameter _build_unit_stats_endpoint concatenated `language` into the stats query string unchanged, so a value such as "eng_us&flags=onlyGP#x" could add query parameters or a fragment to the request. - A value that is not a language code (^[A-Za-z]{2,3}_[A-Za-z]{2}$, full match) now raises SwgohComlinkValueError before any request is sent. - A well-formed code not in Constants.LANGUAGES (case-insensitive) logs one warning and is still sent unchanged. - The query is built with urlencode(..., safe=","), so the output for valid input is byte-identical (api?flags=calcGP&language=eng_us) and the HMAC-signed path still matches the path on the wire. Shared code in _base.py, so both clients are covered; tests run against the sync and async clients. Refs #235 Co-Authored-By: Claude Opus 5.5 --- docs/migration.md | 9 ++ src/swgoh_comlink/_base.py | 39 ++++++--- tests/unit/test_unit_stats_query.py | 123 ++++++++++++++++++++++++++++ 3 files changed, 161 insertions(+), 10 deletions(-) create mode 100644 tests/unit/test_unit_stats_query.py diff --git a/docs/migration.md b/docs/migration.md index 2b23de1..da4d2f3 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -308,6 +308,15 @@ added together. `ERA_DEFINITION`, `UBS_UPDATE`. New legacy-name aliases: `AbilityDecisionTrees`, `EraDefinitions`, `UBSUpdate`, `EpisodeDefinitions` (plural), `AccountLinking`. +## 10. v2.9 changes + +Upgrading from v2.8 to v2.9. + +- **`get_unit_stats(language=)` must be a language code.** A value that doesn't match + `xx_yy` / `xxx_yy` (letters only, e.g. `eng_us`) now raises `SwgohComlinkValueError` + instead of being passed through into the query string. A well-formed code that isn't in + `Constants.LANGUAGES` logs a warning and is still sent. Case is unchanged. + ## Summary of changes | Area | Before (v1.x) | After | diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 7beee1b..865941e 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -8,19 +8,27 @@ import functools import hashlib import hmac +import logging import os +import re import time from collections.abc import Callable from dataclasses import dataclass from json import dumps from typing import Any, Self -from urllib.parse import urlparse, urlunparse +from urllib.parse import urlencode, urlparse, urlunparse from .exceptions import SwgohComlinkException, SwgohComlinkTypeError, SwgohComlinkValueError from .helpers import Constants, DataItems from .helpers._data_items import _items_wire_value from .retry import RetryPolicy, _no_release, _Pacer +logger = logging.getLogger(__name__) + +# A swgoh-stats language code such as ``eng_us``. Nothing that matches can carry ``&``, ``#``, ``=`` or ``/`` +# into the stats query string. +_LANGUAGE_CODE = re.compile(r"[A-Za-z]{2,3}_[A-Za-z]{2}") + __all__ = [ "SwgohComlinkBase", "param_alias", @@ -374,11 +382,15 @@ def _build_game_data_payload( def _build_unit_stats_endpoint(flags: list[str] | None = None, language: str | None = None) -> str: """Build the stats endpoint string with query parameters. + A well-formed ``language`` that is not in ``Constants.LANGUAGES`` logs a warning and is still sent, + so a language the game adds before the list is updated keeps working. + Returns: Endpoint string like ``"api?flags=calcGP&language=eng_us"``. Raises: - SwgohComlinkValueError: If flags contains invalid values. + SwgohComlinkValueError: If flags contains invalid values, or language is not a language code + such as ``eng_us``. """ _allowed_flags = { "gameStyle", @@ -394,23 +406,30 @@ def _build_unit_stats_endpoint(flags: list[str] | None = None, language: str | N "noSpace", } - flag_str = None + query: dict[str, str] = {} if flags: if isinstance(flags, list) and set(flags).issubset(_allowed_flags): - flag_str = "flags=" + ",".join(flags) + query["flags"] = ",".join(flags) else: raise SwgohComlinkValueError( f'Invalid argument. should be a list of strings with one or more of "' f"{_allowed_flags} flag values." ) - lang_str = f"language={language}" if language else None - - query_string = None - if flag_str or lang_str: - query_string = "?" + "&".join(filter(None, iter([flag_str, lang_str]))) + if language: + if not isinstance(language, str) or not _LANGUAGE_CODE.fullmatch(language): + raise SwgohComlinkValueError( + f"Invalid argument. should be a language code such as 'eng_us', got {language!r}." + ) + if language.lower() not in Constants.LANGUAGES: + logger.warning( + "Unknown language %r; sending it anyway. Known languages: %s", + language, + ", ".join(Constants.LANGUAGES), + ) + query["language"] = language - return "api" + query_string if query_string else "api" + return f"api?{urlencode(query, safe=',')}" if query else "api" @property def version(self) -> str: diff --git a/tests/unit/test_unit_stats_query.py b/tests/unit/test_unit_stats_query.py new file mode 100644 index 0000000..7e6a440 --- /dev/null +++ b/tests/unit/test_unit_stats_query.py @@ -0,0 +1,123 @@ +"""The stats ``language`` query parameter is validated and encoded before it reaches the URL.""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import logging +from collections.abc import Awaitable, Callable +from typing import Any, cast + +import pytest +from pytest_httpx import HTTPXMock + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync +from swgoh_comlink._base import SwgohComlinkBase +from swgoh_comlink.exceptions import SwgohComlinkValueError + +Client = SwgohComlink | SwgohComlinkAsync +Call = Callable[..., Awaitable[Any]] + +STATS_URL = "http://localhost:3223" +BASE_LOGGER = "swgoh_comlink._base" + +build = SwgohComlinkBase._build_unit_stats_endpoint + + +@pytest.mark.parametrize( + "language", + [ + "eng_us&flags=onlyGP#x", + "eng_us#x", + "eng_us&x=1", + "eng=us", + "eng/us", + "eng_us\n", + " eng_us", + "eng us", + "english", + "e_us", + "engl_us", + "eng_usa", + "éng_us", + ], +) +def test_value_that_is_not_a_language_code_raises(language: str) -> None: + with pytest.raises(SwgohComlinkValueError, match="language"): + build(flags=["calcGP"], language=language) + + +def test_non_string_language_raises() -> None: + with pytest.raises(SwgohComlinkValueError, match="language"): + build(language=cast(Any, 42)) + + +@pytest.mark.parametrize( + ("flags", "language", "expected"), + [ + (["calcGP"], "eng_us", "api?flags=calcGP&language=eng_us"), + (["calcGP", "onlyGP"], "eng_us", "api?flags=calcGP,onlyGP&language=eng_us"), + (None, "eng_us", "api?language=eng_us"), + (["calcGP"], None, "api?flags=calcGP"), + (None, None, "api"), + ], +) +def test_valid_input_builds_the_same_endpoint_as_before( + flags: list[str] | None, language: str | None, expected: str +) -> None: + assert build(flags=flags, language=language) == expected + + +@pytest.mark.parametrize("language", ["eng_us", "ENG_US", "Ger_De"]) +def test_known_language_is_accepted_without_a_warning(language: str, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + assert build(language=language) == f"api?language={language}" + + assert [r for r in caplog.records if r.levelno >= logging.WARNING] == [] + + +def test_unknown_well_formed_language_warns_once_and_is_still_sent(caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + assert build(flags=["calcGP"], language="eng_uk") == "api?flags=calcGP&language=eng_uk" + + warnings = [r for r in caplog.records if r.levelno >= logging.WARNING] + assert len(warnings) == 1 + assert "eng_uk" in warnings[0].getMessage() + assert "eng_us" in warnings[0].getMessage() + + +async def test_client_rejects_injection_before_sending(comlink: Client, call: Call, httpx_mock: HTTPXMock) -> None: + with pytest.raises(SwgohComlinkValueError, match="language"): + await call(comlink, "get_unit_stats", request_payload=[{"unit": "data"}], language="eng_us&flags=onlyGP#x") + + assert httpx_mock.get_requests() == [] + + +async def test_hmac_signature_matches_a_request_path_with_a_query_string( + make_comlink: Callable[..., Client], call: Call, httpx_mock: HTTPXMock +) -> None: + httpx_mock.add_response(json=[{"unit": "data"}]) + + await call( + make_comlink(access_key="pub", secret_key="priv"), + "get_unit_stats", + request_payload=[{"unit": "data"}], + flags=["calcGP", "gameStyle"], + language="eng_us", + ) + + request = httpx_mock.get_request() + assert request is not None + assert str(request.url) == f"{STATS_URL}/api?flags=calcGP,gameStyle&language=eng_us" + # Recompute from the request as it arrived: the signed path must be byte-identical to the + # path and query on the wire. + signed_path = request.url.raw_path + assert signed_path == b"/api?flags=calcGP,gameStyle&language=eng_us" + body = json.loads(request.content) + signature = hmac.new(b"priv", digestmod=hashlib.sha256) + signature.update(request.headers["X-Date"].encode()) + signature.update(request.method.encode()) + signature.update(signed_path) + signature.update(hashlib.md5(json.dumps(body, separators=(",", ":")).encode()).hexdigest().encode()) # noqa: S324 + assert request.headers["Authorization"] == f"HMAC-SHA256 Credential=pub,Signature={signature.hexdigest()}" From 0467afe9c11329ced8b34483bb7c86314dbb6abc Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:27:09 -0500 Subject: [PATCH 3/8] fix(core): replace runtime asserts and raw KeyErrors with library errors Invalid input reached callers as a bare KeyError or AssertionError, and the assert guards vanished under python -O. - get_leaderboard (both clients) maps an unknown league or division name to SwgohComlinkValueError listing the valid names. - StatCalc.set_game_data checks all six required tables up front and raises SwgohComlinkValueError naming any that are missing or None, leaving previously loaded data in place. - _construct_request_headers raises SwgohComlinkException when HMAC is enabled without a secret_key. - get_localization (both clients) drops a redundant assert; the type checker already narrows the id. - The remaining StatCalc asserts only narrow types after _require_game_data() and now carry a "# type narrowing" comment; a unit test keeps src/ free of uncommented asserts. Refs #239 Co-Authored-By: Claude Opus 5.5 --- docs/migration.md | 8 ++++ src/swgoh_comlink/StatCalc/calculator.py | 54 ++++++++++++++---------- src/swgoh_comlink/_base.py | 20 ++++++++- src/swgoh_comlink/swgoh_comlink.py | 8 ++-- src/swgoh_comlink/swgoh_comlink_async.py | 8 ++-- tests/unit/test_base.py | 27 +++++++++++- tests/unit/test_calculator.py | 21 +++++++++ tests/unit/test_client_requests.py | 22 ++++++++++ 8 files changed, 135 insertions(+), 33 deletions(-) diff --git a/docs/migration.md b/docs/migration.md index 441c264..21c96c5 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -316,6 +316,14 @@ Upgrading from v2.8 to v2.9. body longer than 512 characters and appends `… (N bytes total)`. Read the full body from `exc.response.text`; `exc.code`, `exc.detail` and the exception class still come from the full body. +- **Bad league or division names raise `SwgohComlinkValueError`.** `get_leaderboard` + raised a bare `KeyError` for an unknown `league` or `division` name; it now raises + `SwgohComlinkValueError` (a `ValueError`, not a `KeyError`) listing the valid names. + Catch `SwgohComlinkValueError` instead of `KeyError`. +- **`StatCalc.set_game_data` validates its tables.** A missing `unitData`, `gearData`, + `modSetData`, `crTables`, `gpTables` or `relicData` table, or one set to `None`, raises + `SwgohComlinkValueError` naming it, instead of `KeyError` or `AssertionError`. The + previously loaded data is kept. ## Summary of changes diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index fa016ec..fa7095d 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -7,6 +7,7 @@ import urllib.request from typing import Any +from ..exceptions import SwgohComlinkValueError from ..helpers._stat_data import STATS as _CANONICAL_STATS @@ -28,6 +29,9 @@ class StatCalc: STATS_NAME_MAP: dict[str, dict[str, Any]] = _CANONICAL_STATS + # Tables set_game_data requires; each must be present and not None. + _REQUIRED_TABLES: tuple[str, ...] = ("unitData", "gearData", "modSetData", "crTables", "gpTables", "relicData") + def __init__(self, game_data: dict[str, Any] | None = None) -> None: """Initialize a calculator instance. @@ -54,16 +58,20 @@ def set_game_data(self, game_data: dict[str, Any]) -> None: Args: game_data: Game data payload containing unit, gear, CR, GP, relic, and mod set tables. + + Raises: + SwgohComlinkValueError: A required table is missing or ``None``. The + previously loaded game data, if any, is kept. """ + missing = [key for key in self._REQUIRED_TABLES if game_data.get(key) is None] + if missing: + raise SwgohComlinkValueError(f"Game data is missing required table(s): {', '.join(missing)}") self._unit_data = game_data["unitData"] self._gear_data = game_data["gearData"] self._mod_set_data = game_data["modSetData"] self._cr_tables = game_data["crTables"] self._gp_tables = game_data["gpTables"] self._relic_data = game_data["relicData"] - assert self._unit_data is not None - assert self._gear_data is not None - assert self._mod_set_data is not None self._LOGGER.info( "Game data loaded: units=%d gear=%d mod_sets=%d", len(self._unit_data), @@ -138,7 +146,7 @@ def calc_roster_stats(self, units: Any) -> Any: (no `stats` or `gp` added) and a warning is logged. """ self._require_game_data() - assert self._unit_data is not None + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran self._LOGGER.debug("Calculating roster stats") if isinstance(units, list): @@ -380,9 +388,9 @@ def _normalize_ship_and_crew( return normalized_ship, normalized_crew def _get_char_raw_stats(self, char: dict[str, Any]) -> dict[str, Any]: - assert self._unit_data is not None - assert self._gear_data is not None - assert self._relic_data is not None + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran + assert self._gear_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran + assert self._relic_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran def_id = char["defId"] meta = self._unit_data.get(def_id) if meta is None: @@ -427,8 +435,8 @@ def _get_char_raw_stats(self, char: dict[str, Any]) -> dict[str, Any]: return stats def _get_ship_raw_stats(self, ship: dict[str, Any], crew: list[dict[str, Any]]) -> dict[str, Any]: - assert self._unit_data is not None - assert self._cr_tables is not None + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran + assert self._cr_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran def_id = ship["defId"] meta = self._unit_data.get(def_id) if meta is None: @@ -461,7 +469,7 @@ def _get_ship_raw_stats(self, ship: dict[str, Any], crew: list[dict[str, Any]]) return stats def _get_crew_rating(self, crew: list[dict[str, Any]]) -> float: - assert self._cr_tables is not None + assert self._cr_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran total_cr: float = 0 for char in crew: total_cr += self._table_get(self._cr_tables["unitLevelCR"], char["level"]) @@ -499,12 +507,12 @@ def _get_crew_rating(self, crew: list[dict[str, Any]]) -> float: return total_cr def _get_skill_crew_rating(self, skill: dict[str, Any]) -> float: - assert self._cr_tables is not None + assert self._cr_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran value: float = self._table_get(self._cr_tables["abilityLevelCR"], skill["tier"]) return value def _get_crewless_crew_rating(self, ship: dict[str, Any]) -> float: - assert self._cr_tables is not None + assert self._cr_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran return self._floor( self._table_get(self._cr_tables["crewRarityCR"], ship["rarity"]) + 3.5 * self._table_get(self._cr_tables["unitLevelCR"], ship["level"]) @@ -512,7 +520,7 @@ def _get_crewless_crew_rating(self, ship: dict[str, Any]) -> float: ) def _get_crewless_skills_crew_rating(self, skills: list[dict[str, Any]]) -> float: - assert self._cr_tables is not None + assert self._cr_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran cr = 0.0 for skill in skills: mult = 0.696 if str(skill["id"]).startswith("hardware") else 2.46 @@ -520,8 +528,8 @@ def _get_crewless_skills_crew_rating(self, skills: list[dict[str, Any]]) -> floa return cr def _calculate_base_stats(self, stats: dict[str, Any], level: int, base_id: str) -> dict[str, Any]: - assert self._unit_data is not None - assert self._cr_tables is not None + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran + assert self._cr_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran base = stats["base"] gms = stats["growthModifiers"] @@ -918,7 +926,7 @@ def _convert_percent( stats["mods"][sid] = convert_func(flat) - last def _calc_char_gp(self, char: dict[str, Any]) -> int: - assert self._gp_tables is not None + assert self._gp_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran gp = self._table_get(self._gp_tables["unitLevelGP"], char["level"]) gp += self._table_get(self._gp_tables["unitRarityGP"], char["rarity"]) gp += self._table_get(self._gp_tables["gearLevelGP"], char["gear"]) @@ -973,7 +981,7 @@ def _resolve_gear_slots(self, char: dict[str, Any]) -> list[Any]: for its current tier, taking the first unclaimed matching slot so duplicate pieces map to distinct slots. Unmatched pieces resolve to None and add no GP. """ - assert self._unit_data is not None + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran pieces = char.get("equipped", []) slots = [piece.get("slot") if isinstance(piece, dict) else None for piece in pieces] if None not in slots: @@ -998,8 +1006,8 @@ def _resolve_gear_slots(self, char: dict[str, Any]) -> list[Any]: return slots def _get_skill_gp(self, unit_id: str, skill: dict[str, Any]) -> float: - assert self._unit_data is not None - assert self._gp_tables is not None + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran + assert self._gp_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran skill_def = next( (s for s in self._unit_data[unit_id]["skills"] if s["id"] == skill["id"]), None, @@ -1014,8 +1022,8 @@ def _get_skill_gp(self, unit_id: str, skill: dict[str, Any]) -> float: return gp_value def _calc_ship_gp(self, ship: dict[str, Any], crew: list[dict[str, Any]] | None = None) -> int: - assert self._unit_data is not None - assert self._gp_tables is not None + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran + assert self._gp_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran if crew is None: crew = [] @@ -1046,8 +1054,8 @@ def _calc_ship_gp(self, ship: dict[str, Any], crew: list[dict[str, Any]] | None return int(self._floor(gp * 1.5)) def _get_crewless_skills_gp(self, unit_id: str, skills: list[dict[str, Any]]) -> dict[str, float]: - assert self._unit_data is not None - assert self._gp_tables is not None + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran + assert self._gp_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran ability = 0.0 reinforcement = 0.0 diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 7beee1b..c2ef0d6 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -93,6 +93,23 @@ def sanitize_url(url: str) -> str: return url +def _lookup_name(kind: str, table: dict[str, int], name: str) -> int: + """Return ``table[name.lower()]``, or raise a library error listing the valid names. + + Args: + kind: What the name identifies (``"league"`` or ``"division"``), for the message. + table: Mapping of lower-case names to wire values, such as ``Constants.LEAGUES``. + name: The caller-supplied name. Matching ignores case. + + Raises: + SwgohComlinkValueError: ``name`` is not a key of ``table``. + """ + try: + return table[name.lower()] + except KeyError: + raise SwgohComlinkValueError(f"Unknown {kind} {name!r}. Valid {kind} names: {', '.join(table)}") from None + + def _replace_port(url: str, port: int) -> str: """Return *url* with its port set to *port*, keeping its scheme and host.""" parsed = urlparse(url) @@ -243,7 +260,8 @@ def _construct_request_headers( if self.hmac: req_time = str(int(time.time() * 1000)) req_headers = {"X-Date": f"{req_time}"} - assert self.secret_key is not None + if self.secret_key is None: + raise SwgohComlinkException("HMAC signing is enabled but secret_key is not set.") hmac_obj = hmac.new(key=self.secret_key.encode(), digestmod=hashlib.sha256) hmac_obj.update(req_time.encode()) hmac_obj.update(method.upper().encode()) diff --git a/src/swgoh_comlink/swgoh_comlink.py b/src/swgoh_comlink/swgoh_comlink.py index f6a7332..9fae8bb 100644 --- a/src/swgoh_comlink/swgoh_comlink.py +++ b/src/swgoh_comlink/swgoh_comlink.py @@ -18,6 +18,7 @@ GAME_DATA_TIMEOUT, SwgohComlinkBase, _CachedVersions, + _lookup_name, param_alias, ) from .exceptions import ( @@ -372,7 +373,6 @@ def get_localization( localization_id = self._get_versions().require_language() if locale: - assert localization_id is not None localization_id = localization_id + ":" + locale.upper() payload = {"unzip": unzip, "enums": enums, "payload": {"id": localization_id}} @@ -566,11 +566,11 @@ def get_leaderboard( leagues = Constants.LEAGUES divisions = Constants.DIVISIONS if isinstance(league, str): - league = leagues[league.lower()] + league = _lookup_name("league", leagues, league) if isinstance(division, int) and len(str(division)) == 1: - division = divisions[str(division).lower()] + division = _lookup_name("division", divisions, str(division)) if isinstance(division, str): - division = divisions[division.lower()] + division = _lookup_name("division", divisions, division) inner_payload: dict[str, Any] = {"leaderboardType": leaderboard_type} payload: dict[str, Any] = {"payload": inner_payload, "enums": enums} if leaderboard_type == 4: diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index 6e3193a..ebcdc30 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -18,6 +18,7 @@ GAME_DATA_TIMEOUT, SwgohComlinkBase, _CachedVersions, + _lookup_name, param_alias, ) from .exceptions import ( @@ -370,7 +371,6 @@ async def get_localization( localization_id = (await self._get_versions()).require_language() if locale: - assert localization_id is not None localization_id = localization_id + ":" + locale.upper() payload = {"unzip": unzip, "enums": enums, "payload": {"id": localization_id}} @@ -566,11 +566,11 @@ async def get_leaderboard( leagues = Constants.LEAGUES divisions = Constants.DIVISIONS if isinstance(league, str): - league = leagues[league.lower()] + league = _lookup_name("league", leagues, league) if isinstance(division, int) and len(str(division)) == 1: - division = divisions[str(division).lower()] + division = _lookup_name("division", divisions, str(division)) if isinstance(division, str): - division = divisions[division.lower()] + division = _lookup_name("division", divisions, division) inner_payload: dict[str, Any] = {"leaderboardType": leaderboard_type} payload: dict[str, Any] = {"payload": inner_payload, "enums": enums} if leaderboard_type == 4: diff --git a/tests/unit/test_base.py b/tests/unit/test_base.py index 0f83b93..28e2581 100644 --- a/tests/unit/test_base.py +++ b/tests/unit/test_base.py @@ -3,14 +3,16 @@ from __future__ import annotations import hashlib +import re from json import dumps +from pathlib import Path from typing import TYPE_CHECKING, Any, Self, assert_type, cast, get_type_hints import pytest from swgoh_comlink import SwgohComlink from swgoh_comlink._base import _SENSITIVE_KEYS, SwgohComlinkBase, param_alias, sanitize_url -from swgoh_comlink.exceptions import SwgohComlinkValueError +from swgoh_comlink.exceptions import SwgohComlinkException, SwgohComlinkValueError from swgoh_comlink.helpers import DataItems if TYPE_CHECKING: @@ -251,6 +253,29 @@ def _compute_sig(payload_string: str) -> str: assert actual_sig != old_sig client.close() + def test_hmac_without_secret_key_raises_library_error(self): + # A runtime guard, not an assert: it must hold under ``python -O`` too. + client = SwgohComlink(access_key="mykey", secret_key="mysecret") + client.secret_key = None + with pytest.raises(SwgohComlinkException, match="secret_key"): + client._construct_request_headers("POST", "player") + client.close() + + +# ── Runtime asserts (SEC-7) ────────────────────────────────────────────── + + +def test_src_asserts_are_only_commented_type_narrowing(): + """Runtime checks must not rely on ``assert``, which ``python -O`` strips.""" + src = Path(__file__).resolve().parents[2] / "src" + offenders = [ + f"{path.relative_to(src)}:{number}: {line.strip()}" + for path in sorted(src.rglob("*.py")) + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1) + if re.match(r"\s*assert ", line) and "# type narrowing" not in line + ] + assert offenders == [] + # ── _get_player_payload ────────────────────────────────────────────────── diff --git a/tests/unit/test_calculator.py b/tests/unit/test_calculator.py index 90a4692..9c9deab 100644 --- a/tests/unit/test_calculator.py +++ b/tests/unit/test_calculator.py @@ -15,6 +15,7 @@ import pytest from swgoh_comlink import StatCalc +from swgoh_comlink.exceptions import SwgohComlinkValueError _PLAYER_FILE = Path(__file__).resolve().parent.parent / "resources" / "example-player.json" @@ -235,6 +236,26 @@ def test_require_game_data_raises_without_data(): sc._require_game_data() +def test_set_game_data_names_missing_key(): + with pytest.raises(SwgohComlinkValueError, match="unitData"): + StatCalc(game_data={}) + + +@pytest.mark.parametrize("key", ["unitData", "gearData", "modSetData", "crTables", "gpTables", "relicData"]) +def test_set_game_data_rejects_missing_or_none_table(calc, game_data, key): + sc = copy.copy(calc) + before = (sc._unit_data, sc._gear_data, sc._mod_set_data, sc._cr_tables, sc._gp_tables, sc._relic_data) + missing = {k: v for k, v in game_data.items() if k != key} + + with pytest.raises(SwgohComlinkValueError, match=key): + sc.set_game_data(missing) + with pytest.raises(SwgohComlinkValueError, match=key): + sc.set_game_data({**game_data, key: None}) + + # A rejected payload leaves the previously loaded tables in place. + assert (sc._unit_data, sc._gear_data, sc._mod_set_data, sc._cr_tables, sc._gp_tables, sc._relic_data) == before + + def test_game_data_is_fetched_from_github_when_not_given(monkeypatch, game_data): seen_urls: list[str] = [] diff --git a/tests/unit/test_client_requests.py b/tests/unit/test_client_requests.py index 4f9c649..87925c7 100644 --- a/tests/unit/test_client_requests.py +++ b/tests/unit/test_client_requests.py @@ -326,6 +326,11 @@ async def test_request_error_raises_comlink_exception(comlink: Client, call: Cal pytest.param("get_game_data", {"version": "v1", "request_segment": -1}, id="game-data-segment-negative"), pytest.param("get_unit_stats", {"request_payload": [{}], "flags": ["invalidFlag"]}, id="unit-stats-bad-flag"), pytest.param("get_guild", {"guild_id": ""}, id="guild-empty-id"), + pytest.param("get_leaderboard", {"leaderboard_type": 6, "league": "bad", "division": 1}, id="bad-league"), + pytest.param("get_leaderboard", {"leaderboard_type": 6, "league": "kyber", "division": "9"}, id="bad-division"), + pytest.param( + "get_leaderboard", {"leaderboard_type": 6, "league": "kyber", "division": 0}, id="bad-int-division" + ), ], ) async def test_invalid_arguments_raise_before_any_request( @@ -337,6 +342,23 @@ async def test_invalid_arguments_raise_before_any_request( assert httpx_mock.get_requests() == [] +@pytest.mark.parametrize( + ("kwargs", "valid_names"), + [ + pytest.param({"league": "Bad", "division": 1}, "kyber, aurodium, chromium, bronzium, carbonite", id="league"), + pytest.param({"league": "kyber", "division": "six"}, "1, 2, 3, 4, 5", id="division"), + ], +) +async def test_unknown_leaderboard_name_lists_valid_names( + comlink: Client, call: Call, httpx_mock: HTTPXMock, kwargs: dict[str, Any], valid_names: str +) -> None: + with pytest.raises(SwgohComlinkValueError, match=valid_names) as excinfo: + await call(comlink, "get_leaderboard", leaderboard_type=6, **kwargs) + + assert not isinstance(excinfo.value, KeyError) + assert httpx_mock.get_requests() == [] + + # ── Authentication ─────────────────────────────────────────────────────── From 63ed3460ab1fa88ef861f8088bcad99350e75653 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:28:36 -0500 Subject: [PATCH 4/8] fix(client): read HMAC keys from COMLINK_ACCESS_KEY and COMLINK_SECRET_KEY Both clients fell back to the generic ACCESS_KEY / SECRET_KEY environment variables when no keys were passed. If another tool set those names, HMAC turned on silently and that tool's access key went to Comlink in the Authorization header. Credentials now resolve as: constructor arguments, then COMLINK_ACCESS_KEY / COMLINK_SECRET_KEY, then (only when neither new name is set) the old ACCESS_KEY / SECRET_KEY names. Using an old name emits one DeprecationWarning per client naming the new variables. When only one key of the pair ends up set, a warning is logged since HMAC stays off. The change is in SwgohComlinkBase, so it covers SwgohComlink and SwgohComlinkAsync alike; tests run against both. Refs #236 Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- docs/api/async.md | 2 +- docs/api/comlink.md | 6 +- docs/migration.md | 4 + src/swgoh_comlink/_base.py | 43 +++++++- tests/unit/test_base.py | 6 +- tests/unit/test_credential_env.py | 169 ++++++++++++++++++++++++++++++ 7 files changed, 224 insertions(+), 10 deletions(-) create mode 100644 tests/unit/test_credential_env.py diff --git a/README.md b/README.md index 0efe664..16d804f 100644 --- a/README.md +++ b/README.md @@ -216,8 +216,8 @@ Constructor parameters for `SwgohComlink` and `SwgohComlinkAsync`: |-----------|------|---------|-------------| | `url` | `str` | `http://localhost:3000` | URL where swgoh-comlink is running | | `stats_url` | `str` | `http://localhost:3223` | URL where swgoh-stats service is running | -| `access_key` | `str` | `None` | HMAC public key. Also reads from `ACCESS_KEY` env var | -| `secret_key` | `str` | `None` | HMAC private key. Also reads from `SECRET_KEY` env var | +| `access_key` | `str` | `None` | HMAC public key. Also reads from `COMLINK_ACCESS_KEY` env var (`ACCESS_KEY` is deprecated) | +| `secret_key` | `str` | `None` | HMAC private key. Also reads from `COMLINK_SECRET_KEY` env var (`SECRET_KEY` is deprecated) | | `host` | `str` | `None` | Server hostname (overrides `url` and `stats_url`) | | `port` | `int` | `None` | Comlink TCP port. With `host` it defaults to `3000`; without `host` it replaces the port in `url` | | `stats_port` | `int` | `None` | Stats service TCP port. With `host` it defaults to `3223`; without `host` it replaces the port in `stats_url` | diff --git a/docs/api/async.md b/docs/api/async.md index e1d857f..ec3f275 100644 --- a/docs/api/async.md +++ b/docs/api/async.md @@ -28,7 +28,7 @@ finally: `SwgohComlinkAsync` takes the same constructor arguments as the synchronous client: `url` or `host`/`port` to choose the service, and `access_key`/ -`secret_key` (or the `ACCESS_KEY`/`SECRET_KEY` environment variables) for HMAC +`secret_key` (or the `COMLINK_ACCESS_KEY`/`COMLINK_SECRET_KEY` environment variables) for HMAC signing. See [Connecting to Comlink](comlink.md#connecting-to-comlink). ```python diff --git a/docs/api/comlink.md b/docs/api/comlink.md index f9e2983..7a90fa3 100644 --- a/docs/api/comlink.md +++ b/docs/api/comlink.md @@ -39,8 +39,10 @@ When `host` is given, `url` and `stats_url` are ignored. If your comlink service requires HMAC signing, pass `access_key` and `secret_key`. When they are not passed, the client reads them from the -`ACCESS_KEY` and `SECRET_KEY` environment variables. Signing is turned on only -when both keys are set. +`COMLINK_ACCESS_KEY` and `COMLINK_SECRET_KEY` environment variables. Signing is +turned on only when both keys are set; if only one is set, the client logs a +warning. The old `ACCESS_KEY` and `SECRET_KEY` names still work but are +deprecated, and are read only when neither `COMLINK_*` name is set. See the [API Reference](#swgoh_comlink.swgoh_comlink.SwgohComlink) below for every constructor argument. diff --git a/docs/migration.md b/docs/migration.md index da4d2f3..fe3d5af 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -316,6 +316,10 @@ Upgrading from v2.8 to v2.9. `xx_yy` / `xxx_yy` (letters only, e.g. `eng_us`) now raises `SwgohComlinkValueError` instead of being passed through into the query string. A well-formed code that isn't in `Constants.LANGUAGES` logs a warning and is still sent. Case is unchanged. +- **HMAC keys move to `COMLINK_ACCESS_KEY` / `COMLINK_SECRET_KEY`.** Rename the + `ACCESS_KEY` / `SECRET_KEY` environment variables. The old names still work until v3 + with a `DeprecationWarning`, and are read only when neither new name is set. + Constructor arguments still win. Setting only one key now logs a warning. ## Summary of changes diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 865941e..00cceb1 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -12,6 +12,7 @@ import os import re import time +import warnings from collections.abc import Callable from dataclasses import dataclass from json import dumps @@ -40,6 +41,11 @@ # Keys whose values must be masked in logs, repr, and debug output. _SENSITIVE_KEYS = frozenset({"secret_key", "access_key"}) +# Environment variables holding the HMAC (access, secret) key pair. The generic names are deprecated and are +# read only when neither namespaced name is set, so a pair is never assembled from both namespaces. +_CREDENTIAL_ENV_VARS = ("COMLINK_ACCESS_KEY", "COMLINK_SECRET_KEY") +_DEPRECATED_CREDENTIAL_ENV_VARS = ("ACCESS_KEY", "SECRET_KEY") + DEFAULT_TIMEOUT: float = 120.0 GAME_DATA_TIMEOUT: float = 300.0 DEFAULT_VERSION_CACHE_TTL: float = 3600.0 @@ -192,11 +198,42 @@ def __init__( if stats_port is not None: self.stats_url_base = _replace_port(self.stats_url_base, stats_port) - # Use values passed from client first, otherwise check for environment variables - self.access_key = access_key or os.environ.get("ACCESS_KEY") - self.secret_key = secret_key or os.environ.get("SECRET_KEY") + self.access_key, self.secret_key = self._resolve_credentials(access_key, secret_key) if self.access_key and self.secret_key: self.hmac = True + elif self.access_key or self.secret_key: + present, missing = ("access_key", "secret_key") if self.access_key else ("secret_key", "access_key") + logger.warning( + "HMAC signing is off: %s is set but %s is not. Pass both keys, or set both %s and %s.", + present, + missing, + *_CREDENTIAL_ENV_VARS, + ) + + @staticmethod + def _resolve_credentials(access_key: str | None, secret_key: str | None) -> tuple[str | None, str | None]: + """Return the HMAC (access, secret) keys: constructor arguments first, then the environment. + + Emits one ``DeprecationWarning`` when a key is taken from ``ACCESS_KEY`` or ``SECRET_KEY``. + """ + env_names = _CREDENTIAL_ENV_VARS + env_values = [os.environ.get(name) or None for name in env_names] + if not any(env_values): + env_names = _DEPRECATED_CREDENTIAL_ENV_VARS + env_values = [os.environ.get(name) or None for name in env_names] + args = (access_key or None, secret_key or None) + if env_names is _DEPRECATED_CREDENTIAL_ENV_VARS and ( + used := [name for name, arg, value in zip(env_names, args, env_values, strict=True) if value and not arg] + ): + # stacklevel 4: this method, SwgohComlinkBase.__init__, the client's __init__, then the caller. + warnings.warn( + f"Reading HMAC keys from {' and '.join(used)} is deprecated and will be removed in v3. " + f"Set {' and '.join(_CREDENTIAL_ENV_VARS)} instead.", + DeprecationWarning, + stacklevel=4, + ) + access, secret = (arg or value for arg, value in zip(args, env_values, strict=True)) + return access, secret def _pace_delay(self, endpoint: str, stats: bool) -> float: """Reserve the next call slot for *endpoint* and return the seconds to wait for it. diff --git a/tests/unit/test_base.py b/tests/unit/test_base.py index 0f83b93..498a52d 100644 --- a/tests/unit/test_base.py +++ b/tests/unit/test_base.py @@ -162,8 +162,10 @@ def test_hmac_disabled_without_keys(self): client.close() def test_hmac_from_env(self, monkeypatch): - monkeypatch.setenv("ACCESS_KEY", "env_pub") - monkeypatch.setenv("SECRET_KEY", "env_priv") + monkeypatch.delenv("ACCESS_KEY", raising=False) + monkeypatch.delenv("SECRET_KEY", raising=False) + monkeypatch.setenv("COMLINK_ACCESS_KEY", "env_pub") + monkeypatch.setenv("COMLINK_SECRET_KEY", "env_priv") client = SwgohComlink() assert client.hmac is True assert client.access_key == "env_pub" diff --git a/tests/unit/test_credential_env.py b/tests/unit/test_credential_env.py new file mode 100644 index 0000000..a23f5b6 --- /dev/null +++ b/tests/unit/test_credential_env.py @@ -0,0 +1,169 @@ +"""HMAC credentials come from the namespaced COMLINK_* environment variables, with the old names deprecated.""" + +from __future__ import annotations + +import logging +import warnings +from collections.abc import Callable + +import pytest + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync + +Client = SwgohComlink | SwgohComlinkAsync + +BASE_LOGGER = "swgoh_comlink._base" +ENV_NAMES = ("COMLINK_ACCESS_KEY", "COMLINK_SECRET_KEY", "ACCESS_KEY", "SECRET_KEY") + + +@pytest.fixture(autouse=True) +def clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Start every test with none of the credential variables set, whatever the outer shell exports.""" + for name in ENV_NAMES: + monkeypatch.delenv(name, raising=False) + + +def _build(make_comlink: Callable[..., Client], **kwargs: str) -> tuple[Client, list[warnings.WarningMessage]]: + """Build a client and return it with the DeprecationWarnings raised while constructing it.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + client = make_comlink(**kwargs) + return client, [w for w in caught if issubclass(w.category, DeprecationWarning)] + + +def test_new_names_enable_hmac(make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("COMLINK_ACCESS_KEY", "new_pub") + monkeypatch.setenv("COMLINK_SECRET_KEY", "new_priv") + client, deprecations = _build(make_comlink) + assert (client.hmac, client.access_key, client.secret_key) == (True, "new_pub", "new_priv") + assert deprecations == [] + + +def test_new_names_take_precedence_over_old( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("COMLINK_ACCESS_KEY", "new_pub") + monkeypatch.setenv("COMLINK_SECRET_KEY", "new_priv") + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + client, deprecations = _build(make_comlink) + assert (client.hmac, client.access_key, client.secret_key) == (True, "new_pub", "new_priv") + assert deprecations == [] + + +def test_old_names_still_work_with_one_deprecation_warning( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + client, deprecations = _build(make_comlink) + assert (client.hmac, client.access_key, client.secret_key) == (True, "old_pub", "old_priv") + assert len(deprecations) == 1 + message = str(deprecations[0].message) + assert "COMLINK_ACCESS_KEY" in message + assert "COMLINK_SECRET_KEY" in message + assert "old_pub" not in message + assert "old_priv" not in message + + +def test_each_client_warns_once(make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + assert len(_build(make_comlink)[1]) == 1 + assert len(_build(make_comlink)[1]) == 1 + + +def test_deprecation_points_at_the_caller(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + with pytest.warns(DeprecationWarning) as record: + client = SwgohComlink() + client.close() + assert record[0].filename == __file__ + + +async def test_async_deprecation_points_at_the_caller(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + with pytest.warns(DeprecationWarning) as record: + client = SwgohComlinkAsync() + await client.aclose() + assert record[0].filename == __file__ + + +def test_constructor_arguments_beat_all_env_vars( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch +) -> None: + for name in ENV_NAMES: + monkeypatch.setenv(name, f"env_{name}") + client, deprecations = _build(make_comlink, access_key="arg_pub", secret_key="arg_priv") + assert (client.hmac, client.access_key, client.secret_key) == (True, "arg_pub", "arg_priv") + assert deprecations == [] + + +def test_constructor_argument_overrides_one_env_var( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("COMLINK_ACCESS_KEY", "new_pub") + monkeypatch.setenv("COMLINK_SECRET_KEY", "new_priv") + client, _ = _build(make_comlink, secret_key="arg_priv") + assert (client.access_key, client.secret_key) == ("new_pub", "arg_priv") + + +def test_old_names_ignored_once_a_new_name_is_set( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The two namespaces are never mixed: one new name stops both old names from being read.""" + monkeypatch.setenv("COMLINK_ACCESS_KEY", "new_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + client, deprecations = _build(make_comlink) + assert (client.hmac, client.access_key, client.secret_key) == (False, "new_pub", None) + assert deprecations == [] + assert "COMLINK_SECRET_KEY" in caplog.text + + +@pytest.mark.parametrize( + ("env", "missing"), + [ + ({"COMLINK_ACCESS_KEY": "new_pub"}, "secret_key"), + ({"COMLINK_SECRET_KEY": "new_priv"}, "access_key"), + ({"ACCESS_KEY": "old_pub"}, "secret_key"), + ({"SECRET_KEY": "old_priv"}, "access_key"), + ], +) +def test_half_a_pair_logs_a_warning( + make_comlink: Callable[..., Client], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + env: dict[str, str], + missing: str, +) -> None: + for name, value in env.items(): + monkeypatch.setenv(name, value) + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + client, _ = _build(make_comlink) + assert client.hmac is False + warnings_logged = [r for r in caplog.records if r.levelno == logging.WARNING and r.name == BASE_LOGGER] + assert len(warnings_logged) == 1 + text = warnings_logged[0].getMessage() + assert "HMAC" in text + assert missing in text + assert all(value not in text for value in env.values()) + + +def test_half_a_pair_from_arguments_logs_a_warning( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture +) -> None: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + client, _ = _build(make_comlink, access_key="arg_pub") + assert client.hmac is False + assert "secret_key" in caplog.text + + +def test_no_credentials_is_silent(make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + client, deprecations = _build(make_comlink) + assert client.hmac is False + assert deprecations == [] + assert caplog.records == [] From 7288a1f7ed71500c6040f34e212c89c7a4ae1d75 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:29:34 -0500 Subject: [PATCH 5/8] fix(hmac): warn when HMAC is used over plain HTTP to a non-loopback host HMAC signing authenticates requests but does not protect responses or stop replays within the server's X-Date window. Over http:// to a remote host, both are open to anyone on the network path, and the client accepted that setup silently. When HMAC is on, each client now logs one warning naming its url and/or stats_url that use plain http to a host other than localhost, 127.0.0.0/8 or ::1 (literal IPs checked with ipaddress; host names are not resolved). The connection is never blocked. docs/index.md gains a paragraph recommending TLS or a private network for a remote Comlink. The check is in SwgohComlinkBase, so it covers SwgohComlink and SwgohComlinkAsync alike; tests run against both. Refs #237 Co-Authored-By: Claude Opus 5.5 --- docs/index.md | 6 ++ docs/migration.md | 3 + src/swgoh_comlink/_base.py | 22 ++++++ tests/unit/test_hmac_plain_http.py | 114 +++++++++++++++++++++++++++++ 4 files changed, 145 insertions(+) create mode 100644 tests/unit/test_hmac_plain_http.py diff --git a/docs/index.md b/docs/index.md index ca384fc..4e679b6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -36,6 +36,12 @@ async with SwgohComlinkAsync(host="127.0.0.1", port=3000) as comlink: player = await comlink.get_player(allycode=245866537) ``` +If Comlink runs on another machine, reach it over `https` or a private network you trust, +such as a VPN or an SSH tunnel. HMAC signing (`access_key`/`secret_key`) proves who sent a +request, but over plain `http` it does not stop anyone on the network path from altering +responses or replaying signed requests. The client logs a warning when it signs requests sent +over plain `http` to a host other than `localhost`, `127.0.0.0/8` or `::1`; it still connects. + ## Choosing a Stats Method `SwgohComlink.get_unit_stats()` and `StatCalc.calc_player_stats()` are similar in outcome but different in execution model: diff --git a/docs/migration.md b/docs/migration.md index fe3d5af..87e6eea 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -320,6 +320,9 @@ Upgrading from v2.8 to v2.9. `ACCESS_KEY` / `SECRET_KEY` environment variables. The old names still work until v3 with a `DeprecationWarning`, and are read only when neither new name is set. Constructor arguments still win. Setting only one key now logs a warning. +- **Plain-HTTP HMAC warning.** A client with HMAC keys whose `url` or `stats_url` is + `http://` to a non-loopback host logs one warning. Requests are still sent; switch to + `https` or a private network, or filter the `swgoh_comlink._base` logger. ## Summary of changes diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 00cceb1..07fef53 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -8,6 +8,7 @@ import functools import hashlib import hmac +import ipaddress import logging import os import re @@ -107,6 +108,20 @@ def sanitize_url(url: str) -> str: return url +def _is_plain_http_remote(url: str) -> bool: + """Whether *url* is plain ``http`` to a host other than ``localhost``, ``127.0.0.0/8`` or ``::1``.""" + parsed = urlparse(url) + if parsed.scheme.lower() != "http": + return False + host = (parsed.hostname or "").rstrip(".") + if host == "localhost": + return False + try: + return not ipaddress.ip_address(host).is_loopback + except ValueError: # a host name; resolving it would need a DNS lookup + return True + + def _replace_port(url: str, port: int) -> str: """Return *url* with its port set to *port*, keeping its scheme and host.""" parsed = urlparse(url) @@ -201,6 +216,13 @@ def __init__( self.access_key, self.secret_key = self._resolve_credentials(access_key, secret_key) if self.access_key and self.secret_key: self.hmac = True + if plain := [url for url in (self.url_base, self.stats_url_base) if _is_plain_http_remote(url)]: + logger.warning( + "HMAC signing is on but %s uses plain HTTP to a non-loopback host. Signing does not protect " + "responses from being altered in transit or stop signed requests from being replayed; use " + "https or a private network.", + " and ".join(plain), + ) elif self.access_key or self.secret_key: present, missing = ("access_key", "secret_key") if self.access_key else ("secret_key", "access_key") logger.warning( diff --git a/tests/unit/test_hmac_plain_http.py b/tests/unit/test_hmac_plain_http.py new file mode 100644 index 0000000..2d708e5 --- /dev/null +++ b/tests/unit/test_hmac_plain_http.py @@ -0,0 +1,114 @@ +"""A client that signs requests over plain HTTP to a non-loopback host logs one warning.""" + +from __future__ import annotations + +import logging +from collections.abc import Callable +from typing import Any + +import pytest + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync + +Client = SwgohComlink | SwgohComlinkAsync + +BASE_LOGGER = "swgoh_comlink._base" +KEYS = {"access_key": "pub_key", "secret_key": "priv_key"} + + +@pytest.fixture(autouse=True) +def clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep credential variables from the outer shell from switching HMAC on.""" + for name in ("COMLINK_ACCESS_KEY", "COMLINK_SECRET_KEY", "ACCESS_KEY", "SECRET_KEY"): + monkeypatch.delenv(name, raising=False) + + +def _plain_http_warnings( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture, **kwargs: Any +) -> list[logging.LogRecord]: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + make_comlink(**kwargs) + return [r for r in caplog.records if r.name == BASE_LOGGER and "plain HTTP" in r.getMessage()] + + +@pytest.mark.parametrize( + "kwargs", + [ + {"url": "http://comlink.example.com:3000"}, + {"url": "http://comlink.example.com"}, + {"url": "HTTP://comlink.example.com:3000"}, + {"url": "http://192.168.1.10:3000"}, + {"url": "http://[2001:db8::1]:3000"}, + {"url": "http://128.0.0.1:3000"}, + {"url": "http://localhost.example.com:3000"}, + {"host": "comlink.lab"}, + {"url": "https://comlink.example.com", "stats_url": "http://stats.example.com:3223"}, + ], + ids=lambda kwargs: next(iter(kwargs.values())), +) +def test_warns_for_plain_http_to_a_remote_host( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture, kwargs: dict[str, str] +) -> None: + records = _plain_http_warnings(make_comlink, caplog, **KEYS, **kwargs) + assert len(records) == 1 + assert records[0].levelno == logging.WARNING + text = records[0].getMessage() + assert "HMAC" in text + assert "priv_key" not in text + assert "pub_key" not in text + + +def test_one_warning_when_both_urls_are_remote( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture +) -> None: + records = _plain_http_warnings( + make_comlink, caplog, url="http://comlink.example.com:3000", stats_url="http://stats.example.com:3223", **KEYS + ) + assert len(records) == 1 + assert "comlink.example.com" in records[0].getMessage() + assert "stats.example.com" in records[0].getMessage() + + +def test_each_client_warns_once(make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture) -> None: + assert len(_plain_http_warnings(make_comlink, caplog, url="http://comlink.example.com:3000", **KEYS)) == 1 + caplog.clear() + assert len(_plain_http_warnings(make_comlink, caplog, url="http://comlink.example.com:3000", **KEYS)) == 1 + + +@pytest.mark.parametrize( + "url", + [ + "http://localhost:3000", + "http://LOCALHOST:3000", + "http://localhost", + "http://127.0.0.1:3000", + "http://127.0.0.1", + "http://127.10.20.30:3000", + "http://[::1]:3000", + "https://comlink.example.com", + "https://comlink.example.com:8443", + "https://192.168.1.10:3000", + ], +) +def test_no_warning_for_loopback_or_https( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture, url: str +) -> None: + assert _plain_http_warnings(make_comlink, caplog, url=url, **KEYS) == [] + + +def test_no_warning_without_keys(make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture) -> None: + assert _plain_http_warnings(make_comlink, caplog, url="http://comlink.example.com:3000") == [] + + +def test_warns_for_env_keys( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("COMLINK_ACCESS_KEY", "pub_key") + monkeypatch.setenv("COMLINK_SECRET_KEY", "priv_key") + assert len(_plain_http_warnings(make_comlink, caplog, url="http://comlink.example.com:3000")) == 1 + + +def test_the_connection_is_not_blocked(make_comlink: Callable[..., Client]) -> None: + client = make_comlink(url="http://comlink.example.com:3000", **KEYS) + assert client.hmac is True + assert client.url_base == "http://comlink.example.com:3000" From 81623d0d573e1a0e6f2c0c1463d129e9a2c632b2 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:39:25 -0500 Subject: [PATCH 6/8] feat(client): add opt-in max_response_bytes and max_game_data_bytes limits Both clients accept two keyword-only constructor arguments, defaulting to None (no limit, and the existing buffered request path unchanged): - max_response_bytes applies to every endpoint except /data, including the stats service. - max_game_data_bytes applies to /data (get_game_data), whose responses are far larger, mirroring DEFAULT_TIMEOUT / GAME_DATA_TIMEOUT. When the applicable limit is set, _send streams the response. A success whose Content-Length is over the limit raises SwgohComlinkValueError before the body is read; otherwise decoded bytes from iter_bytes() are counted and the read aborts with SwgohComlinkValueError past the limit, which also stops gzip bombs. An error body is read only up to the limit and cut there before SwgohComlinkHTTPError.from_response, so status classification and retries are unchanged. Adds a UTF-8 BOM regression test: a BOM-prefixed body still raises SwgohComlinkDecodeError, buffered and streamed. Refs #240 Co-Authored-By: Claude Opus 5.5 --- docs/api/async.md | 5 + docs/api/comlink.md | 53 +++++ docs/migration.md | 5 + src/swgoh_comlink/_base.py | 56 +++++ src/swgoh_comlink/swgoh_comlink.py | 50 ++++- src/swgoh_comlink/swgoh_comlink_async.py | 50 ++++- tests/unit/test_response_decoding.py | 9 + tests/unit/test_response_size_cap.py | 259 +++++++++++++++++++++++ 8 files changed, 481 insertions(+), 6 deletions(-) create mode 100644 tests/unit/test_response_size_cap.py diff --git a/docs/api/async.md b/docs/api/async.md index ec3f275..d4c29a1 100644 --- a/docs/api/async.md +++ b/docs/api/async.md @@ -41,6 +41,11 @@ async with SwgohComlinkAsync(host="192.168.1.10", port=3000) as comlink: Failed calls raise the same [typed HTTP errors](exceptions.md#http-errors) as the synchronous client. +## Limiting Response Size + +`max_response_bytes` and `max_game_data_bytes` work as in the synchronous +client; see [Limiting Response Size](comlink.md#limiting-response-size). + ## Retries and Pacing The `retry` argument takes the same [`RetryPolicy`](comlink.md#retries-and-pacing) diff --git a/docs/api/comlink.md b/docs/api/comlink.md index 7a90fa3..89bf633 100644 --- a/docs/api/comlink.md +++ b/docs/api/comlink.md @@ -54,6 +54,59 @@ When comlink answers with an HTTP error status, the client raises a `SwgohComlinkRateLimitError` for a rate refusal or `SwgohComlinkClientError` for a rejected request. All of them subclass `SwgohComlinkException`. +## Limiting Response Size + +By default the client reads each response in full, however large it is. On a +host with little memory, such as a Raspberry Pi, two keyword-only arguments +cap how much of a response body the client will read: + +- `max_response_bytes`: every endpoint except `/data`, including the stats + service used by `get_unit_stats`. +- `max_game_data_bytes`: `/data` only (`get_game_data`). It is separate + because game data is far larger than any other response, for the same reason + `/data` has its own, longer timeout. + +Both default to `None`, which means no limit. Limits count decoded bytes, +after any gzip decompression. When a limit is set: + +- A success response whose `Content-Length` is over the limit raises + `SwgohComlinkValueError` before any of the body is read. `Content-Length` is + the compressed size, so this check catches only bodies that are too large + even before decompression. +- Otherwise the client counts bytes as they arrive and raises + `SwgohComlinkValueError` as soon as the count passes the limit. This also + stops a small compressed body that would expand to a very large one. The + count is checked after each decoded chunk, so memory use can pass the limit + by up to one chunk. +- An HTTP error response is read up to the limit, and the body is cut there. + The [typed HTTP error](exceptions.md#http-errors) is raised as usual, so + `retry` still applies. + +`SwgohComlinkValueError` from a limit is never retried. Raise the limit, or set +it to `None`, for calls that need more. + +Measured decoded sizes in November 2026 (they grow with game updates, so leave +headroom): + +| Call | Size | +|------|------| +| `get_game_metadata()` | 43 KB | +| `get_player()` | 1.5 MB | +| `get_localization()` | 46 MB | +| `get_localization(unzip=True)` | 228 MB | +| `get_game_data(request_segment=1)` | 111 MB | +| `get_game_data()`, all collections | 405 MB | + +```python +from swgoh_comlink import SwgohComlink + +MiB = 1024 * 1024 +comlink = SwgohComlink(max_response_bytes=64 * MiB, max_game_data_bytes=512 * MiB) +``` + +With these values `get_localization(unzip=True)` fails; use `unzip=False` or a +larger `max_response_bytes` for it. + ## Retries and Pacing By default a client makes exactly one attempt per call and raises the diff --git a/docs/migration.md b/docs/migration.md index 87e6eea..73753a5 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -323,6 +323,11 @@ Upgrading from v2.8 to v2.9. - **Plain-HTTP HMAC warning.** A client with HMAC keys whose `url` or `stats_url` is `http://` to a non-loopback host logs one warning. Requests are still sent; switch to `https` or a private network, or filter the `swgoh_comlink._base` logger. +- **Optional response size limits.** New keyword-only `max_response_bytes` and + `max_game_data_bytes` (for `/data`) arguments make the clients raise + `SwgohComlinkValueError` for a larger response, instead of reading it all into + memory. Both default to `None`, so nothing changes unless you set them. See + [Limiting Response Size](api/comlink.md#limiting-response-size). ## Summary of changes diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 07fef53..9583863 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -20,6 +20,8 @@ from typing import Any, Self from urllib.parse import urlencode, urlparse, urlunparse +import httpx + from .exceptions import SwgohComlinkException, SwgohComlinkTypeError, SwgohComlinkValueError from .helpers import Constants, DataItems from .helpers._data_items import _items_wire_value @@ -122,6 +124,41 @@ def _is_plain_http_remote(url: str) -> bool: return True +def _check_size_limit(name: str, value: int | None) -> int | None: + """Validate a response size limit argument: ``None`` or a positive ``int``.""" + if value is None: + return None + if not isinstance(value, int) or isinstance(value, bool): + raise SwgohComlinkTypeError(f"{name} must be an int or None, got {type(value).__name__}.") + if value <= 0: + raise SwgohComlinkValueError(f"{name} must be a positive number of bytes or None.") + return value + + +def _declared_length(headers: httpx.Headers) -> int | None: + """The ``Content-Length`` header as an ``int``, or ``None`` when absent or unreadable.""" + try: + return int(headers["content-length"]) + except (KeyError, ValueError): + return None + + +def _bounded_error_response(response: httpx.Response, body: bytes) -> httpx.Response: + """A copy of a streamed error *response* carrying *body*, its decoded and possibly cut-short content. + + The transfer headers are dropped because they described the encoded body, not *body*. + """ + headers = [ + (name, value) + for name, value in response.headers.multi_items() + if name.lower() not in ("content-encoding", "content-length", "transfer-encoding") + ] + extensions = {key: value for key, value in response.extensions.items() if key in ("http_version", "reason_phrase")} + return httpx.Response( + response.status_code, headers=headers, content=body, request=response.request, extensions=extensions + ) + + def _replace_port(url: str, port: int) -> str: """Return *url* with its port set to *port*, keeping its scheme and host.""" parsed = urlparse(url) @@ -182,6 +219,8 @@ def __init__( version_cache_ttl: float = DEFAULT_VERSION_CACHE_TTL, *, retry: RetryPolicy | None = None, + max_response_bytes: int | None = None, + max_game_data_bytes: int | None = None, ): from swgoh_comlink import version @@ -202,6 +241,8 @@ def __init__( raise SwgohComlinkTypeError(f"retry must be a RetryPolicy or None, got {type(retry).__name__}.") self.retry_policy = retry self._pacer = _Pacer(retry.min_interval, retry.unpaced_endpoints) if retry is not None else None + self.max_response_bytes = _check_size_limit("max_response_bytes", max_response_bytes) + self.max_game_data_bytes = _check_size_limit("max_game_data_bytes", max_game_data_bytes) # host replaces url and stats_url outright; port and stats_port alone replace only their ports if host: @@ -257,6 +298,21 @@ def _resolve_credentials(access_key: str | None, secret_key: str | None) -> tupl access, secret = (arg or value for arg, value in zip(args, env_values, strict=True)) return access, secret + def _size_limit(self, endpoint: str, stats: bool) -> tuple[str, int | None]: + """The name and value of the response size limit for *endpoint*: ``/data`` has its own.""" + if endpoint == "data" and not stats: + return "max_game_data_bytes", self.max_game_data_bytes + return "max_response_bytes", self.max_response_bytes + + @staticmethod + def _too_large(endpoint: str, limit_name: str, limit: int, declared: int | None = None) -> SwgohComlinkValueError: + """The error for a response from *endpoint* larger than *limit* bytes.""" + size = f"declares {declared} bytes, over" if declared is not None else "is over" + return SwgohComlinkValueError( + f"Response from /{endpoint} {size} {limit_name} ({limit} bytes). " + f"Raise {limit_name}, or set it to None to remove the limit." + ) + def _pace_delay(self, endpoint: str, stats: bool) -> float: """Reserve the next call slot for *endpoint* and return the seconds to wait for it. diff --git a/src/swgoh_comlink/swgoh_comlink.py b/src/swgoh_comlink/swgoh_comlink.py index f6a7332..a6f5d91 100644 --- a/src/swgoh_comlink/swgoh_comlink.py +++ b/src/swgoh_comlink/swgoh_comlink.py @@ -17,7 +17,9 @@ DEFAULT_TIMEOUT, GAME_DATA_TIMEOUT, SwgohComlinkBase, + _bounded_error_response, _CachedVersions, + _declared_length, param_alias, ) from .exceptions import ( @@ -57,6 +59,11 @@ class SwgohComlink(SwgohComlinkBase): retry (RetryPolicy | None): Keyword-only. Retry rate refusals and HTTP 503 responses, and optionally space calls to the same endpoint, as described by a :class:`~swgoh_comlink.retry.RetryPolicy`. [Default: None, one attempt per call and no waiting] + max_response_bytes (int | None): Keyword-only. Largest response body, in decoded bytes, accepted from any + endpoint except /data. A larger response raises ``SwgohComlinkValueError``; an HTTP error body is cut + to this size. [Default: None, no limit] + max_game_data_bytes (int | None): Keyword-only. The same limit for /data (``get_game_data``), whose + responses are far larger than any other endpoint's. [Default: None, no limit] Notes: If the 'host' parameter is provided, the 'url' and 'stats_url' parameters are ignored. @@ -191,10 +198,15 @@ def _send( if method.upper() != "GET": request_kwargs["content"] = body + limit_name, limit = self._size_limit(endpoint, stats) try: - r = client.request(method.upper(), f"/{endpoint}", **request_kwargs) - r.raise_for_status() - decoded = loads(r.content.decode("utf-8")) + if limit is None: + r = client.request(method.upper(), f"/{endpoint}", **request_kwargs) + r.raise_for_status() + content = r.content + else: + content = self._receive_limited(client, method, endpoint, request_kwargs, limit_name, limit) + decoded = loads(content.decode("utf-8")) if not isinstance(decoded, (dict, list)): raise SwgohComlinkDecodeError("Expected a JSON object or array in the service response.") return decoded @@ -205,6 +217,38 @@ def _send( except httpx.RequestError as e: raise SwgohComlinkException(e) from e + def _receive_limited( + self, + client: httpx.Client, + method: str, + endpoint: str, + request_kwargs: dict[str, Any], + limit_name: str, + limit: int, + ) -> bytes: + """Stream one response, reading at most *limit* decoded bytes of its body. + + A success larger than *limit* raises ``SwgohComlinkValueError``, before any of the body is read when + ``Content-Length`` already exceeds it. An error body is cut to *limit* bytes and raised through + ``raise_for_status``. + """ + with client.stream(method.upper(), f"/{endpoint}", **request_kwargs) as r: + if r.is_success and (declared := _declared_length(r.headers)) is not None and declared > limit: + raise self._too_large(endpoint, limit_name, limit, declared) + chunks: list[bytes] = [] + size = 0 + for chunk in r.iter_bytes(): + chunks.append(chunk) + size += len(chunk) + if size > limit: + if r.is_success: + raise self._too_large(endpoint, limit_name, limit) + break + body = b"".join(chunks) + if not r.is_success: + _bounded_error_response(r, body[:limit]).raise_for_status() + return body + def _post( self, endpoint: str = "", diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index 6e3193a..fb53d4b 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -17,7 +17,9 @@ DEFAULT_TIMEOUT, GAME_DATA_TIMEOUT, SwgohComlinkBase, + _bounded_error_response, _CachedVersions, + _declared_length, param_alias, ) from .exceptions import ( @@ -57,6 +59,11 @@ class SwgohComlinkAsync(SwgohComlinkBase): retry (RetryPolicy | None): Keyword-only. Retry rate refusals and HTTP 503 responses, and optionally space calls to the same endpoint, as described by a :class:`~swgoh_comlink.retry.RetryPolicy`. [Default: None, one attempt per call and no waiting] + max_response_bytes (int | None): Keyword-only. Largest response body, in decoded bytes, accepted from any + endpoint except /data. A larger response raises ``SwgohComlinkValueError``; an HTTP error body is cut + to this size. [Default: None, no limit] + max_game_data_bytes (int | None): Keyword-only. The same limit for /data (``get_game_data``), whose + responses are far larger than any other endpoint's. [Default: None, no limit] Notes: If the 'host' parameter is provided, the 'url' and 'stats_url' parameters are ignored. @@ -189,10 +196,15 @@ async def _send( if method.upper() != "GET": request_kwargs["content"] = body + limit_name, limit = self._size_limit(endpoint, stats) try: - r = await client.request(method.upper(), f"/{endpoint}", **request_kwargs) - r.raise_for_status() - decoded = loads(r.content.decode("utf-8")) + if limit is None: + r = await client.request(method.upper(), f"/{endpoint}", **request_kwargs) + r.raise_for_status() + content = r.content + else: + content = await self._receive_limited(client, method, endpoint, request_kwargs, limit_name, limit) + decoded = loads(content.decode("utf-8")) if not isinstance(decoded, (dict, list)): raise SwgohComlinkDecodeError("Expected a JSON object or array in the service response.") return decoded @@ -203,6 +215,38 @@ async def _send( except httpx.RequestError as e: raise SwgohComlinkException(e) from e + async def _receive_limited( + self, + client: httpx.AsyncClient, + method: str, + endpoint: str, + request_kwargs: dict[str, Any], + limit_name: str, + limit: int, + ) -> bytes: + """Stream one response, reading at most *limit* decoded bytes of its body. + + A success larger than *limit* raises ``SwgohComlinkValueError``, before any of the body is read when + ``Content-Length`` already exceeds it. An error body is cut to *limit* bytes and raised through + ``raise_for_status``. + """ + async with client.stream(method.upper(), f"/{endpoint}", **request_kwargs) as r: + if r.is_success and (declared := _declared_length(r.headers)) is not None and declared > limit: + raise self._too_large(endpoint, limit_name, limit, declared) + chunks: list[bytes] = [] + size = 0 + async for chunk in r.aiter_bytes(): + chunks.append(chunk) + size += len(chunk) + if size > limit: + if r.is_success: + raise self._too_large(endpoint, limit_name, limit) + break + body = b"".join(chunks) + if not r.is_success: + _bounded_error_response(r, body[:limit]).raise_for_status() + return body + async def _post( self, endpoint: str = "", diff --git a/tests/unit/test_response_decoding.py b/tests/unit/test_response_decoding.py index 5e2f47c..3f8db9e 100644 --- a/tests/unit/test_response_decoding.py +++ b/tests/unit/test_response_decoding.py @@ -35,3 +35,12 @@ async def test_scalar_json_is_rejected(comlink, call, httpx_mock, body): async def test_supported_response_shapes(comlink, call, httpx_mock, body): httpx_mock.add_response(json=body) assert await call(comlink, "_post", endpoint="test") == body + + +@pytest.mark.parametrize("caps", [{}, {"max_response_bytes": 1_000}], ids=["buffered", "capped"]) +async def test_utf8_bom_is_rejected(make_comlink, call, httpx_mock, caps): + """Regression guard: a BOM-prefixed body stays a decode error, as ``json.loads(str)`` rejects the BOM.""" + httpx_mock.add_response(content=b'\xef\xbb\xbf{"latestGamedataVersion": "g"}') + with pytest.raises(SwgohComlinkDecodeError) as caught: + await call(make_comlink(**caps), "get_game_metadata") + assert isinstance(caught.value.__cause__, json.JSONDecodeError) diff --git a/tests/unit/test_response_size_cap.py b/tests/unit/test_response_size_cap.py new file mode 100644 index 0000000..8ae93c8 --- /dev/null +++ b/tests/unit/test_response_size_cap.py @@ -0,0 +1,259 @@ +"""The opt-in ``max_response_bytes`` / ``max_game_data_bytes`` caps on response bodies, in both clients.""" + +from __future__ import annotations + +import gzip +import json +from collections.abc import Callable, Iterator +from typing import Any + +import httpx +import pytest +from pytest_httpx import HTTPXMock, IteratorStream + +from swgoh_comlink import RetryPolicy, SwgohComlink, SwgohComlinkAsync +from swgoh_comlink import retry as retry_module +from swgoh_comlink._base import GAME_DATA_TIMEOUT +from swgoh_comlink.exceptions import ( + SwgohComlinkHTTPError, + SwgohComlinkRateLimitError, + SwgohComlinkTypeError, + SwgohComlinkValueError, +) + +Client = SwgohComlink | SwgohComlinkAsync +CAP_ARGS = ("max_response_bytes", "max_game_data_bytes") + + +class Chunks: + """A response body served in fixed chunks that records how many chunks the client pulled.""" + + def __init__(self, body: bytes, size: int) -> None: + self.parts = [body[i : i + size] for i in range(0, len(body), size)] + self.served = 0 + + def __iter__(self) -> Iterator[bytes]: + for part in self.parts: + self.served += 1 + yield part + + +def padded_json(size: int) -> bytes: + """A JSON array of exactly *size* bytes.""" + return b"[" + b" " * (size - 2) + b"]" + + +@pytest.fixture +def no_stream(monkeypatch: pytest.MonkeyPatch) -> Callable[[Client], None]: + """Make ``client.stream`` fail, to prove a request did not take the streaming path.""" + + def patch(comlink: Client) -> None: + def boom(*args: Any, **kwargs: Any) -> None: + raise AssertionError("client.stream() must not be used without a cap") + + for http_client in (comlink.client, comlink.stats_client): + monkeypatch.setattr(http_client, "stream", boom) + + return patch + + +# ── Constructor ────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("arg", CAP_ARGS) +async def test_caps_default_to_none(comlink: Client, arg: str) -> None: + assert getattr(comlink, arg) is None + + +@pytest.mark.parametrize("arg", CAP_ARGS) +async def test_caps_are_stored(make_comlink: Callable[..., Client], arg: str) -> None: + assert getattr(make_comlink(**{arg: 1024}), arg) == 1024 + + +@pytest.mark.parametrize("arg", CAP_ARGS) +@pytest.mark.parametrize("value", [0, -1]) +async def test_caps_must_be_positive(make_comlink: Callable[..., Client], arg: str, value: int) -> None: + with pytest.raises(SwgohComlinkValueError, match=arg): + make_comlink(**{arg: value}) + + +@pytest.mark.parametrize("arg", CAP_ARGS) +@pytest.mark.parametrize("value", ["1024", 1024.0, True]) +async def test_caps_must_be_int(make_comlink: Callable[..., Client], arg: str, value: object) -> None: + with pytest.raises(SwgohComlinkTypeError, match=arg): + make_comlink(**{arg: value}) + + +# ── Default path is unchanged ──────────────────────────────────────────── + + +async def test_no_cap_does_not_stream(comlink: Client, call, httpx_mock: HTTPXMock, no_stream) -> None: + no_stream(comlink) + httpx_mock.add_response(json={"latestGamedataVersion": "g"}) + httpx_mock.add_response(json={"units": []}) + assert await call(comlink, "get_game_metadata") == {"latestGamedataVersion": "g"} + assert await call(comlink, "get_game_data", version="g") == {"units": []} + + +async def test_game_data_cap_alone_leaves_other_endpoints_unstreamed( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock, no_stream +) -> None: + comlink = make_comlink(max_game_data_bytes=10) + no_stream(comlink) + httpx_mock.add_response(content=padded_json(100)) + assert await call(comlink, "get_game_metadata") == [] + + +async def test_response_cap_alone_leaves_game_data_unstreamed( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock, no_stream +) -> None: + comlink = make_comlink(max_response_bytes=10) + no_stream(comlink) + httpx_mock.add_response(content=b'{"units": []' + b" " * 100 + b"}") + assert await call(comlink, "get_game_data", version="g") == {"units": []} + + +# ── Oversized bodies ───────────────────────────────────────────────────── + + +async def test_oversized_body_raises_and_stops_reading( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + comlink = make_comlink(max_response_bytes=100) + body = Chunks(padded_json(500), 50) + httpx_mock.add_response(stream=IteratorStream(body)) + with pytest.raises(SwgohComlinkValueError, match=r"/metadata.*max_response_bytes.*100"): + await call(comlink, "get_game_metadata") + assert body.served == 3 # stopped at the first chunk past the cap + + +async def test_body_at_cap_is_accepted(make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock) -> None: + comlink = make_comlink(max_response_bytes=100) + httpx_mock.add_response(stream=IteratorStream(Chunks(padded_json(100), 30))) + assert await call(comlink, "get_game_metadata") == [] + + +async def test_content_length_over_cap_fails_before_reading( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + comlink = make_comlink(max_response_bytes=100) + body = Chunks(padded_json(500), 50) + httpx_mock.add_response(headers={"Content-Length": "500"}, stream=IteratorStream(body)) + with pytest.raises(SwgohComlinkValueError, match=r"500 bytes.*max_response_bytes.*100"): + await call(comlink, "get_game_metadata") + assert body.served == 0 + + +async def test_decompressed_size_is_what_counts( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + """A small gzip body that inflates past the cap is stopped: Content-Length gives only the compressed size.""" + compressed = gzip.compress(padded_json(1_000_000)) + assert len(compressed) < 10_000 + comlink = make_comlink(max_response_bytes=10_000) + httpx_mock.add_response( + headers={"Content-Encoding": "gzip", "Content-Length": str(len(compressed))}, + stream=IteratorStream(Chunks(compressed, 512)), + ) + with pytest.raises(SwgohComlinkValueError, match="max_response_bytes"): + await call(comlink, "get_game_metadata") + + +async def test_game_data_uses_its_own_cap(make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock) -> None: + comlink = make_comlink(max_response_bytes=10, max_game_data_bytes=1_000) + httpx_mock.add_response(content=padded_json(500)) + assert await call(comlink, "get_game_data", version="g") == [] + httpx_mock.add_response(content=padded_json(2_000)) + with pytest.raises(SwgohComlinkValueError, match=r"/data.*max_game_data_bytes.*1000"): + await call(comlink, "get_game_data", version="g") + + +async def test_stats_service_uses_response_cap( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + comlink = make_comlink(max_response_bytes=10, max_game_data_bytes=1_000) + httpx_mock.add_response(content=padded_json(100)) + with pytest.raises(SwgohComlinkValueError, match="max_response_bytes"): + await call(comlink, "get_unit_stats", request_payload=[]) + + +# ── The request itself is unchanged ────────────────────────────────────── + + +@pytest.mark.parametrize("caps", [{}, {"max_response_bytes": 10**6, "max_game_data_bytes": 10**6}]) +async def test_streamed_request_matches_buffered_request( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock, caps: dict[str, int] +) -> None: + comlink = make_comlink(access_key="access", secret_key="secret", **caps) + httpx_mock.add_response(json={}) + await call(comlink, "get_game_data", version="g", items=1) + request = httpx_mock.get_request() + assert request is not None + assert request.method == "POST" + assert request.url == "http://localhost:3000/data" + assert json.loads(request.content)["payload"]["version"] == "g" + assert request.headers["Authorization"].startswith("HMAC-SHA256 ") + assert request.extensions["timeout"]["read"] == GAME_DATA_TIMEOUT + + +# ── Error statuses ─────────────────────────────────────────────────────── + +RATE_LIMIT_BODY = b'{"code": "RATE_LIMITED", "message": "slow down"}' + + +async def test_error_within_cap_matches_uncapped_error( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + errors = [] + for caps in ({}, {"max_response_bytes": 1_000}): + httpx_mock.add_response(status_code=429, headers={"Retry-After": "3"}, content=RATE_LIMIT_BODY) + with pytest.raises(SwgohComlinkRateLimitError) as caught: + await call(make_comlink(**caps), "get_game_metadata") + errors.append(caught.value) + uncapped, capped = errors + assert str(capped) == str(uncapped) + assert (capped.status, capped.code, capped.detail, capped.retry_after) == (429, "RATE_LIMITED", "slow down", 3.0) + assert capped.response is not None + assert capped.response.content == RATE_LIMIT_BODY + assert capped.response.headers["Retry-After"] == "3" + assert isinstance(capped.__cause__, httpx.HTTPStatusError) + + +async def test_error_body_over_cap_is_cut_to_cap( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + """An error body is read only up to the cap; the status still decides the exception class.""" + comlink = make_comlink(max_response_bytes=100) + body = Chunks(b'{"code": "GAME_6", "message": "Rate exceeded!"}' + b" " * 10_000, 64) + httpx_mock.add_response(status_code=502, headers={"Content-Length": "10047"}, stream=IteratorStream(body)) + with pytest.raises(SwgohComlinkRateLimitError) as caught: + await call(comlink, "get_game_metadata") + assert caught.value.status == 502 + assert caught.value.response is not None + assert len(caught.value.response.content) == 100 + assert body.served == 2 + + +async def test_gzip_error_body_is_decoded(make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock) -> None: + comlink = make_comlink(max_response_bytes=1_000) + httpx_mock.add_response( + status_code=400, headers={"Content-Encoding": "gzip"}, stream=IteratorStream([gzip.compress(b"bad")]) + ) + with pytest.raises(SwgohComlinkHTTPError, match="HTTP 400: bad") as caught: + await call(comlink, "get_game_metadata") + assert caught.value.response is not None + assert "content-encoding" not in caught.value.response.headers + + +async def test_retry_policy_still_retries_with_a_cap( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock, monkeypatch: pytest.MonkeyPatch +) -> None: + async def no_wait(seconds: float) -> None: + return None + + monkeypatch.setattr(retry_module, "_sleep", lambda seconds: None) + monkeypatch.setattr(retry_module, "_async_sleep", no_wait) + comlink = make_comlink(max_response_bytes=1_000, retry=RetryPolicy(attempts=2)) + httpx_mock.add_response(status_code=503, headers={"Retry-After": "0"}) + httpx_mock.add_response(json={"ok": True}) + assert await call(comlink, "get_game_metadata") == {"ok": True} From 8b51989b02639d8005788be4c71d884eba2ca433 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:42:57 -0500 Subject: [PATCH 7/8] fix(async): use httpx default keep-alive and add a limits argument SwgohComlinkAsync built its httpx clients with httpx.Limits(keepalive_expiry=None), so idle pooled connections were never closed, while SwgohComlink used the httpx default of 5 s. A stale connection after a Comlink restart or NAT idle timeout could then fail the next call with RemoteProtocolError. Remove the async override so both clients use the httpx default pool limits, and add a keyword-only limits: httpx.Limits | None = None argument to both constructors. None passes no limits to httpx, keeping its defaults; a value is passed to every httpx client both classes build. Request timeouts are unchanged. Refs #241 Co-Authored-By: Claude Opus 5.5 --- docs/migration.md | 5 ++ src/swgoh_comlink/_base.py | 15 +++- src/swgoh_comlink/swgoh_comlink.py | 5 ++ src/swgoh_comlink/swgoh_comlink_async.py | 8 +- tests/unit/test_connection_limits.py | 95 ++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 4 deletions(-) create mode 100644 tests/unit/test_connection_limits.py diff --git a/docs/migration.md b/docs/migration.md index 73753a5..949f303 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -328,6 +328,11 @@ Upgrading from v2.8 to v2.9. `SwgohComlinkValueError` for a larger response, instead of reading it all into memory. Both default to `None`, so nothing changes unless you set them. See [Limiting Response Size](api/comlink.md#limiting-response-size). +- **`SwgohComlinkAsync` closes idle connections after 5 s.** It no longer keeps idle + pooled connections open forever; both clients now use the httpx default pool limits. + A new keyword-only `limits=httpx.Limits(...)` argument on both clients sets other + limits, e.g. `limits=httpx.Limits(keepalive_expiry=None)` restores the old async + behaviour. Request timeouts are unchanged. ## Summary of changes diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 9583863..db6db1f 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -17,7 +17,7 @@ from collections.abc import Callable from dataclasses import dataclass from json import dumps -from typing import Any, Self +from typing import Any, Self, TypedDict from urllib.parse import urlencode, urlparse, urlunparse import httpx @@ -57,6 +57,12 @@ _now: Callable[[], float] = time.monotonic +class _PoolLimits(TypedDict, total=False): + """Connection pool keyword for ``httpx.Client`` / ``httpx.AsyncClient``; empty keeps the httpx defaults.""" + + limits: httpx.Limits + + @dataclass(frozen=True) class _CachedVersions: """Game data and localization bundle versions cached from a /metadata response. @@ -221,6 +227,7 @@ def __init__( retry: RetryPolicy | None = None, max_response_bytes: int | None = None, max_game_data_bytes: int | None = None, + limits: httpx.Limits | None = None, ): from swgoh_comlink import version @@ -243,6 +250,12 @@ def __init__( self._pacer = _Pacer(retry.min_interval, retry.unpaced_endpoints) if retry is not None else None self.max_response_bytes = _check_size_limit("max_response_bytes", max_response_bytes) self.max_game_data_bytes = _check_size_limit("max_game_data_bytes", max_game_data_bytes) + if limits is not None and not isinstance(limits, httpx.Limits): + raise SwgohComlinkTypeError(f"limits must be an httpx.Limits or None, got {type(limits).__name__}.") + self.limits = limits + # Both clients splat this into every httpx client they build, so their pools always match. + # Empty when limits is None, which leaves the httpx defaults (5 s idle keep-alive) in place. + self._pool_limits: _PoolLimits = {} if limits is None else {"limits": limits} # host replaces url and stats_url outright; port and stats_port alone replace only their ports if host: diff --git a/src/swgoh_comlink/swgoh_comlink.py b/src/swgoh_comlink/swgoh_comlink.py index a6f5d91..f7bcdfe 100644 --- a/src/swgoh_comlink/swgoh_comlink.py +++ b/src/swgoh_comlink/swgoh_comlink.py @@ -64,6 +64,9 @@ class SwgohComlink(SwgohComlinkBase): to this size. [Default: None, no limit] max_game_data_bytes (int | None): Keyword-only. The same limit for /data (``get_game_data``), whose responses are far larger than any other endpoint's. [Default: None, no limit] + limits (httpx.Limits | None): Keyword-only. Connection pool limits for both underlying httpx clients, + such as ``httpx.Limits(keepalive_expiry=30)``. Timeouts are not affected. + [Default: None, the httpx defaults: 100 connections, 20 kept alive, idle ones closed after 5 s] Notes: If the 'host' parameter is provided, the 'url' and 'stats_url' parameters are ignored. @@ -91,12 +94,14 @@ def __init__(self, **kwargs: Any) -> None: headers={"Content-Type": "application/json"}, verify=self.verify_ssl, timeout=DEFAULT_TIMEOUT, + **self._pool_limits, ) self.stats_client = httpx.Client( base_url=self.stats_url_base, headers={"Content-Type": "application/json"}, verify=self.verify_ssl, timeout=DEFAULT_TIMEOUT, + **self._pool_limits, ) def __enter__(self) -> SwgohComlink: diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index fb53d4b..745c90b 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -64,6 +64,9 @@ class SwgohComlinkAsync(SwgohComlinkBase): to this size. [Default: None, no limit] max_game_data_bytes (int | None): Keyword-only. The same limit for /data (``get_game_data``), whose responses are far larger than any other endpoint's. [Default: None, no limit] + limits (httpx.Limits | None): Keyword-only. Connection pool limits for both underlying httpx clients, + such as ``httpx.Limits(keepalive_expiry=30)``. Timeouts are not affected. + [Default: None, the httpx defaults: 100 connections, 20 kept alive, idle ones closed after 5 s] Notes: If the 'host' parameter is provided, the 'url' and 'stats_url' parameters are ignored. @@ -81,20 +84,19 @@ def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) self._version_lock = asyncio.Lock() self._enums_lock = asyncio.Lock() - connection_limits = httpx.Limits(keepalive_expiry=None) self.client = httpx.AsyncClient( base_url=self.url_base, headers={"Content-Type": "application/json"}, verify=self.verify_ssl, timeout=DEFAULT_TIMEOUT, - limits=connection_limits, + **self._pool_limits, ) self.stats_client = httpx.AsyncClient( base_url=self.stats_url_base, headers={"Content-Type": "application/json"}, verify=self.verify_ssl, timeout=DEFAULT_TIMEOUT, - limits=connection_limits, + **self._pool_limits, ) async def __aenter__(self) -> SwgohComlinkAsync: diff --git a/tests/unit/test_connection_limits.py b/tests/unit/test_connection_limits.py new file mode 100644 index 0000000..034b6d1 --- /dev/null +++ b/tests/unit/test_connection_limits.py @@ -0,0 +1,95 @@ +"""Connection-pool ``limits`` parity between the sync and async clients.""" + +from __future__ import annotations + +import inspect +from typing import Any + +import httpx +import pytest + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync +from swgoh_comlink._base import DEFAULT_TIMEOUT, SwgohComlinkBase +from swgoh_comlink.exceptions import SwgohComlinkTypeError + +_MISSING = object() + + +def _record_client_kwargs(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]: + """Patch both httpx client classes to record the keyword arguments each instance is built with.""" + calls: list[dict[str, Any]] = [] + + for cls in (httpx.Client, httpx.AsyncClient): + + def init(self: Any, *args: Any, _original: Any = cls.__init__, **kwargs: Any) -> None: + calls.append(kwargs) + _original(self, *args, **kwargs) + + monkeypatch.setattr(cls, "__init__", init) + return calls + + +def _limits_passed(calls: list[dict[str, Any]]) -> list[Any]: + return [kwargs.get("limits", _MISSING) for kwargs in calls] + + +def _pool(client: Any) -> Any: + """The httpcore connection pool behind an httpx client's default transport.""" + return client._transport._pool + + +@pytest.mark.parametrize( + "limits", + [None, httpx.Limits(max_connections=7, max_keepalive_connections=3, keepalive_expiry=30.0)], + ids=["default", "custom"], +) +def test_sync_and_async_pass_identical_limits_to_httpx(monkeypatch: pytest.MonkeyPatch, limits: Any) -> None: + calls = _record_client_kwargs(monkeypatch) + sync = SwgohComlink(limits=limits) + sync_limits = _limits_passed(calls) + calls.clear() + SwgohComlinkAsync(limits=limits) + async_limits = _limits_passed(calls) + + assert len(sync_limits) == len(async_limits) == 2 # client and stats_client + assert sync_limits == async_limits + expected = _MISSING if limits is None else limits + assert sync_limits == [expected, expected] + sync.close() + + +def test_default_keepalive_expiry_matches_httpx_default_in_both_clients() -> None: + reference = _pool(httpx.Client()) + sync = SwgohComlink() + async_client = SwgohComlinkAsync() + for pool in (_pool(c) for c in (sync.client, sync.stats_client, async_client.client, async_client.stats_client)): + assert pool._keepalive_expiry == reference._keepalive_expiry == 5.0 + assert pool._max_connections == reference._max_connections + assert pool._max_keepalive_connections == reference._max_keepalive_connections + sync.close() + + +@pytest.mark.parametrize("cls", [SwgohComlink, SwgohComlinkAsync]) +def test_custom_limits_reach_both_connection_pools(cls: type[SwgohComlink] | type[SwgohComlinkAsync]) -> None: + client = cls(limits=httpx.Limits(max_connections=7, max_keepalive_connections=3, keepalive_expiry=None)) + for pool in (_pool(client.client), _pool(client.stats_client)): + assert (pool._max_connections, pool._max_keepalive_connections, pool._keepalive_expiry) == (7, 3, None) + + +def test_limits_is_keyword_only() -> None: + param = inspect.signature(SwgohComlinkBase.__init__).parameters["limits"] + assert param.kind is inspect.Parameter.KEYWORD_ONLY + assert param.default is None + + +@pytest.mark.parametrize("cls", [SwgohComlink, SwgohComlinkAsync]) +@pytest.mark.parametrize("bad", [{"max_connections": 5}, 5, "limits"]) +def test_limits_must_be_httpx_limits(cls: type[SwgohComlink] | type[SwgohComlinkAsync], bad: Any) -> None: + with pytest.raises(SwgohComlinkTypeError, match="limits must be an httpx.Limits or None"): + cls(limits=bad) + + +@pytest.mark.parametrize("cls", [SwgohComlink, SwgohComlinkAsync]) +def test_limits_do_not_change_timeouts(cls: type[SwgohComlink] | type[SwgohComlinkAsync]) -> None: + client = cls(limits=httpx.Limits(keepalive_expiry=1.0)) + assert client.client.timeout == client.stats_client.timeout == httpx.Timeout(DEFAULT_TIMEOUT) From 07b3db2226b7d0f72d89161369fa25afe3797677 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:51:06 -0500 Subject: [PATCH 8/8] refactor(core): move request preparation and retry decisions into a sans-I/O core Both clients duplicated the whole retry and pacing loop in _request and the request building and response decoding in _send. That logic now lives once, without I/O: - retry.py: _retry_step (given an error and attempt number, the delay and whether a rate hold applies) and _Admission (the waits a caller sleeps before an attempt, including the requeue when a hold is extended). - _base.py: _prepare_request (method, body, headers, client choice, size limit), _interpret_response (an httpx.Response into a result or a typed exception) and _retry_wait (logging, holds, jitter). Each client keeps only a short loop that sends, sleeps and handles cancellation for its runtime: _request is 28 lines and _admit keeps the existing cancellation rules (sync releases the slot on BaseException, async on asyncio.CancelledError). Retry log records keep the client module logger names. Behaviour is unchanged; the retry, pacing and hold tests pass unmodified. Adds a test that every public method of SwgohComlinkAsync exists on SwgohComlink with the same signature, aliases included. Refs #246 Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 4 +- src/swgoh_comlink/_base.py | 113 ++++++++++- src/swgoh_comlink/retry.py | 75 ++++++++ src/swgoh_comlink/swgoh_comlink.py | 131 ++++--------- src/swgoh_comlink/swgoh_comlink_async.py | 131 ++++--------- tests/unit/test_client_parity.py | 49 +++++ tests/unit/test_retry_core.py | 231 +++++++++++++++++++++++ 7 files changed, 548 insertions(+), 186 deletions(-) create mode 100644 tests/unit/test_client_parity.py create mode 100644 tests/unit/test_retry_core.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d8d8049..cd975ea 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -196,10 +196,10 @@ comlink-python/ | Module | Purpose | |--------|---------| -| `_base.py` | `SwgohComlinkBase` — shared payload construction, HMAC signing, and config for both clients | +| `_base.py` | `SwgohComlinkBase` — shared payload construction, HMAC signing, config, and the sans-I/O request core (request preparation, response interpretation, retry waits) for both clients | | `swgoh_comlink.py` | `SwgohComlink` — synchronous HTTP client (all endpoint methods) | | `swgoh_comlink_async.py` | `SwgohComlinkAsync` — asynchronous HTTP client (mirrors sync API) | -| `retry.py` | Retry and backoff behavior for transient HTTP failures | +| `retry.py` | Retry and backoff behavior for transient HTTP failures; the pacer, the per-attempt admission state and the retry step, all without I/O | | `StatCalc/calculator.py` | `StatCalc` — local stat and GP calculation for game units | | `helpers/` | `DataItems` IntFlag enum, `Constants` class, and utility functions split across focused submodules | | `exceptions.py` | `SwgohComlinkException`, `SwgohComlinkValueError`, and `SwgohComlinkTypeError` | diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 6c84d03..3e3dcff 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -16,16 +16,22 @@ import warnings from collections.abc import Callable from dataclasses import dataclass -from json import dumps -from typing import Any, Self, TypedDict +from json import JSONDecodeError, dumps, loads +from typing import Any, ClassVar, Self, TypedDict from urllib.parse import urlencode, urlparse, urlunparse import httpx -from .exceptions import SwgohComlinkException, SwgohComlinkTypeError, SwgohComlinkValueError +from .exceptions import ( + SwgohComlinkDecodeError, + SwgohComlinkException, + SwgohComlinkHTTPError, + SwgohComlinkTypeError, + SwgohComlinkValueError, +) from .helpers import Constants, DataItems from .helpers._data_items import _items_wire_value -from .retry import RetryPolicy, _no_release, _Pacer +from .retry import RetryPolicy, _Admission, _no_release, _Pacer, _retry_step logger = logging.getLogger(__name__) @@ -86,6 +92,22 @@ def require_language(self) -> str: return self.language +@dataclass(frozen=True, slots=True) +class _PreparedRequest: + """One attempt at a request, ready to send: the method, URL path and httpx keyword arguments. + + ``stats`` picks the httpx client (``stats_client`` when set, else ``client``). ``limit`` is the response + size limit named ``limit_name``; ``None`` reads the response in one go, any other value streams it. + """ + + method: str + url: str + kwargs: dict[str, Any] + stats: bool + limit_name: str + limit: int | None + + def param_alias(param: str, alias: str) -> Callable[..., Any]: """Decorator to support legacy camelCase parameter aliases. @@ -199,6 +221,8 @@ class SwgohComlinkBase: __comlink_type__: str | None = None PROTOCOL = "http" + # Retry log messages go to the client module's logger, as they did before the retry core moved here. + _log: ClassVar[logging.Logger] = logger @staticmethod def _mask(value: str | None, visible: int = 4) -> str: @@ -428,6 +452,87 @@ def _serialize_payload(payload: dict[str, Any] | list[Any]) -> bytes: except ValueError as exc: raise SwgohComlinkValueError(f"Request payload cannot be sent as JSON: {exc}") from exc + # ── Sans-I/O request core ──────────────────────────────────────────── + # + # Each client's _request is a short loop over these: admit the attempt (sleeping the waits _admission + # hands out), send it, and on an HTTP error ask _retry_wait whether to go round again. Only sending, + # sleeping and cancellation differ between the runtimes, so only they live in the clients. + + def _prepare_request( + self, + method: str, + endpoint: str, + payload: dict[str, Any] | list[Any] | None, + stats: bool, + timeout: float | None, + ) -> _PreparedRequest: + """Build one attempt. Headers, including the HMAC signature, are rebuilt for every attempt.""" + method = method.upper() + body = self._serialize_payload(payload) if method != "GET" and payload is not None else None + kwargs: dict[str, Any] = {"headers": self._construct_request_headers(method, endpoint, payload, body=body)} + if timeout is not None: + kwargs["timeout"] = timeout + if method != "GET": + kwargs["content"] = body + limit_name, limit = self._size_limit(endpoint, stats) + return _PreparedRequest(method, f"/{endpoint}", kwargs, stats, limit_name, limit) + + @staticmethod + def _interpret_response(response: httpx.Response, content: bytes) -> dict[str, Any] | list[Any]: + """Turn a received *response* and its body *content* into the decoded JSON object or array. + + Raises: + SwgohComlinkHTTPError: The response has an HTTP error status (subclass by kind of error). + SwgohComlinkDecodeError: The body is not UTF-8 JSON, or not a JSON object or array. + """ + try: + response.raise_for_status() + except httpx.HTTPStatusError as e: + raise SwgohComlinkHTTPError.from_response(e.response) from e + try: + decoded = loads(content.decode("utf-8")) + except (JSONDecodeError, UnicodeDecodeError) as e: + raise SwgohComlinkDecodeError("Unable to decode the service response as UTF-8 JSON.") from e + if not isinstance(decoded, (dict, list)): + raise SwgohComlinkDecodeError("Expected a JSON object or array in the service response.") + return decoded + + def _admission(self, endpoint: str, stats: bool, extra: float) -> _Admission: + """Reserve a slot for one attempt at *endpoint*, *extra* seconds later than pacing alone would.""" + return _Admission( + endpoint, + extra, + lambda: self._pace_slot(endpoint, stats), + lambda deadline: self._hold_changed(endpoint, stats, deadline), + self._log, + ) + + def _retry_wait(self, error: SwgohComlinkHTTPError, attempt: int, endpoint: str, stats: bool) -> float | None: + """Decide what follows attempt *attempt* at *endpoint* failing with *error*. + + Returns ``None`` when the client must re-raise *error*, otherwise the seconds to carry into the next + attempt's admission. A rate refusal on a paced endpoint holds the endpoint for the retry delay + instead, so only the jitter is carried and every caller waits out the hold together. + """ + policy = self.retry_policy + if policy is None: + return None + step = _retry_step(policy, error, attempt) + if step is None: + if attempt > 1: + self._log.info("%s on %s; giving up after %d attempts", type(error).__name__, endpoint, attempt) + return None + self._log.info( + "%s on %s (attempt %d of %d); retrying in %.1fs", + type(error).__name__, + endpoint, + attempt, + policy.attempts, + step.delay, + ) + held = step.hold and self._hold_endpoint(endpoint, stats, step.delay) + return policy.jitter_extra(step.delay) + (0.0 if held else step.delay) + # ── Version cache ──────────────────────────────────────────────────── def invalidate_version_cache(self) -> None: diff --git a/src/swgoh_comlink/retry.py b/src/swgoh_comlink/retry.py index 9252950..c09df35 100644 --- a/src/swgoh_comlink/retry.py +++ b/src/swgoh_comlink/retry.py @@ -6,6 +6,7 @@ from __future__ import annotations import asyncio +import logging import math import random import threading @@ -266,3 +267,77 @@ def hold(self, key: str, endpoint: str, seconds: float) -> bool: def _no_release() -> None: """Release callable for a call that reserved no slot.""" + + +@dataclass(frozen=True, slots=True) +class _RetryStep: + """What to do after a retryable failure: wait *delay* seconds, holding back the endpoint when *hold* is set.""" + + delay: float + hold: bool + + +def _retry_step(policy: RetryPolicy, error: SwgohComlinkHTTPError, attempt: int) -> _RetryStep | None: + """Decide whether attempt number *attempt*, which failed with *error*, is retried. + + Returns ``None`` to give up. A rate refusal asks for a hold on its endpoint, so concurrent callers back + off together; any other retryable error is waited out by the failed caller alone. + """ + delay = policy.retry_delay(error, attempt) + if delay is None: + return None + return _RetryStep(delay, isinstance(error, SwgohComlinkRateLimitError)) + + +class _Admission: + """Sans-I/O admission of one attempt to an endpoint: the waits the caller sleeps before it sends. + + The caller sleeps each wait :meth:`next_wait` returns and sends once it returns ``None``. If the sleep + is abandoned (an exception, or cancellation of an async task), the caller calls :meth:`abandon` to + give the reserved slot back. After each wait, a rate hold that was extended past the caller's slot + while it slept sends it back into the queue for a new slot. + + Args: + endpoint: The endpoint, for the debug log. + extra: A retry wait carried from the previous attempt, added to the first slot only. + reserve: Reserves the next slot; returns its wait and a callable that gives it back. + held_after: Whether a hold on the endpoint now ends after the given deadline. + log: Logger for the ``Pacing ...`` debug message. + """ + + __slots__ = ("_deadline", "_endpoint", "_held_after", "_log", "_release", "_reserve", "_wait") + + def __init__( + self, + endpoint: str, + extra: float, + reserve: Callable[[], tuple[float, Callable[[], None]]], + held_after: Callable[[float], bool], + log: logging.Logger, + ) -> None: + self._endpoint = endpoint + self._reserve = reserve + self._held_after = held_after + self._log = log + wait, self._release = reserve() + self._wait = wait + extra + self._deadline: float | None = None + + def next_wait(self) -> float | None: + """Return the next number of seconds to sleep, or ``None`` when the attempt may be sent now.""" + while True: + if self._deadline is not None: + if not self._held_after(self._deadline): + return None + # A refusal arrived while this caller slept. Requeue behind the + # current hold, preserving spacing with other delayed callers. + self._release() + self._wait, self._release = self._reserve() + self._deadline = _clock() + self._wait + if self._wait > 0: + self._log.debug("Pacing %s for %.2fs", self._endpoint, self._wait) + return self._wait + + def abandon(self) -> None: + """Give back the slot this admission holds, when the caller stops waiting for it.""" + self._release() diff --git a/src/swgoh_comlink/swgoh_comlink.py b/src/swgoh_comlink/swgoh_comlink.py index cbcf9ba..a70ff84 100644 --- a/src/swgoh_comlink/swgoh_comlink.py +++ b/src/swgoh_comlink/swgoh_comlink.py @@ -7,7 +7,6 @@ import logging import threading -from json import JSONDecodeError, loads from typing import Any, cast import httpx @@ -21,13 +20,12 @@ _CachedVersions, _declared_length, _lookup_name, + _PreparedRequest, param_alias, ) from .exceptions import ( - SwgohComlinkDecodeError, SwgohComlinkException, SwgohComlinkHTTPError, - SwgohComlinkRateLimitError, SwgohComlinkValueError, ) from .helpers import Constants, DataItems @@ -85,6 +83,7 @@ class SwgohComlink(SwgohComlinkBase): """ __comlink_type__ = "SwgohComlink" + _log = logger def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) @@ -124,67 +123,41 @@ def _request( stats: bool = False, timeout: float | None = None, ) -> dict[str, Any] | list[Any]: - """Send an HTTP request to the comlink service. + """Send an HTTP request to the comlink service: the single gateway for all HTTP communication. - This is the single gateway for all HTTP communication. Every public - method should route through here so that HMAC authentication, TLS - verification, and error handling are applied consistently. - - Args: - method: HTTP method (``"GET"`` or ``"POST"``). - endpoint: API endpoint path. - payload: JSON body for the request (ignored for GET requests). - stats: If True, use the stats service client. - timeout: Per-request timeout override. - - Returns: - Decoded JSON response (dict or list). + Each attempt waits for admission (pacing and rate holds), is sent, and on an HTTP error asks the + shared retry core in ``_base`` whether to try again, so both clients retry identically. Raises: SwgohComlinkHTTPError: When the service answers with an HTTP error status, after any retries allowed by the client's retry policy. Subclasses identify rate refusals, HTTP 503 and 4xx. SwgohComlinkException: On any network or decoding error. """ - policy = self.retry_policy - attempt = 1 - extra = 0.0 # retry wait carried into the next pass, on top of its pacing slot + attempt, extra = 1, 0.0 while True: - wait, release = self._pace_slot(endpoint, stats) - wait += extra - extra = 0.0 - while True: - deadline = _retry._clock() + wait - if wait > 0: - logger.debug("Pacing %s for %.2fs", endpoint, wait) - try: - _retry._sleep(wait) - except BaseException: - release() - raise - if not self._hold_changed(endpoint, stats, deadline): - break - release() - wait, release = self._pace_slot(endpoint, stats) + self._admit(endpoint, stats, extra) try: return self._send(method, endpoint, payload, stats, timeout) except SwgohComlinkHTTPError as exc: - delay = None if policy is None else policy.retry_delay(exc, attempt) - if policy is None or delay is None: - if policy is not None and attempt > 1: - logger.info("%s on %s; giving up after %d attempts", type(exc).__name__, endpoint, attempt) + extra = self._retry_wait(exc, attempt, endpoint, stats) + if extra is None: raise - logger.info( - "%s on %s (attempt %d of %d); retrying in %.1fs", - type(exc).__name__, - endpoint, - attempt, - policy.attempts, - delay, - ) - held = isinstance(exc, SwgohComlinkRateLimitError) and self._hold_endpoint(endpoint, stats, delay) - extra = policy.jitter_extra(delay) + (0.0 if held else delay) attempt += 1 + def _admit(self, endpoint: str, stats: bool, extra: float) -> None: + """Sleep until *endpoint* admits the next attempt. + + Any exception while sleeping, ``KeyboardInterrupt`` included, gives the reserved slot back before it + propagates, so an interrupted caller never leaves a gap that later callers wait out. + """ + admission = self._admission(endpoint, stats, extra) + while (wait := admission.next_wait()) is not None: + try: + _retry._sleep(wait) + except BaseException: + admission.abandon() + raise + def _send( self, method: str, @@ -194,53 +167,30 @@ def _send( timeout: float | None, ) -> dict[str, Any] | list[Any]: """Make one attempt at a request. Headers, including the HMAC signature, are rebuilt per attempt.""" - body = self._serialize_payload(payload) if method.upper() != "GET" and payload is not None else None - req_headers = self._construct_request_headers(method, endpoint, payload, body=body) - client = self.stats_client if stats else self.client - - request_kwargs: dict[str, Any] = {"headers": req_headers} - if timeout is not None: - request_kwargs["timeout"] = timeout - if method.upper() != "GET": - request_kwargs["content"] = body - - limit_name, limit = self._size_limit(endpoint, stats) + request = self._prepare_request(method, endpoint, payload, stats, timeout) + client = self.stats_client if request.stats else self.client try: - if limit is None: - r = client.request(method.upper(), f"/{endpoint}", **request_kwargs) - r.raise_for_status() - content = r.content + if request.limit is None: + response = client.request(request.method, request.url, **request.kwargs) + content = response.content else: - content = self._receive_limited(client, method, endpoint, request_kwargs, limit_name, limit) - decoded = loads(content.decode("utf-8")) - if not isinstance(decoded, (dict, list)): - raise SwgohComlinkDecodeError("Expected a JSON object or array in the service response.") - return decoded - except (JSONDecodeError, UnicodeDecodeError) as e: - raise SwgohComlinkDecodeError("Unable to decode the service response as UTF-8 JSON.") from e - except httpx.HTTPStatusError as e: - raise SwgohComlinkHTTPError.from_response(e.response) from e + response, content = self._receive_limited(client, request, endpoint, request.limit) except httpx.RequestError as e: raise SwgohComlinkException(e) from e + return self._interpret_response(response, content) def _receive_limited( - self, - client: httpx.Client, - method: str, - endpoint: str, - request_kwargs: dict[str, Any], - limit_name: str, - limit: int, - ) -> bytes: - """Stream one response, reading at most *limit* decoded bytes of its body. + self, client: httpx.Client, request: _PreparedRequest, endpoint: str, limit: int + ) -> tuple[httpx.Response, bytes]: + """Stream one response, reading at most *limit* decoded bytes of its body; return it and the body. A success larger than *limit* raises ``SwgohComlinkValueError``, before any of the body is read when - ``Content-Length`` already exceeds it. An error body is cut to *limit* bytes and raised through - ``raise_for_status``. + ``Content-Length`` already exceeds it. An error response comes back as a copy whose body is cut to + *limit* bytes. """ - with client.stream(method.upper(), f"/{endpoint}", **request_kwargs) as r: + with client.stream(request.method, request.url, **request.kwargs) as r: if r.is_success and (declared := _declared_length(r.headers)) is not None and declared > limit: - raise self._too_large(endpoint, limit_name, limit, declared) + raise self._too_large(endpoint, request.limit_name, limit, declared) chunks: list[bytes] = [] size = 0 for chunk in r.iter_bytes(): @@ -248,12 +198,13 @@ def _receive_limited( size += len(chunk) if size > limit: if r.is_success: - raise self._too_large(endpoint, limit_name, limit) + raise self._too_large(endpoint, request.limit_name, limit) break body = b"".join(chunks) if not r.is_success: - _bounded_error_response(r, body[:limit]).raise_for_status() - return body + error = _bounded_error_response(r, body[:limit]) + return error, error.content + return r, body def _post( self, diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index e69908c..d9b5862 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -7,7 +7,6 @@ import asyncio import logging -from json import JSONDecodeError, loads from typing import Any, cast import httpx @@ -21,13 +20,12 @@ _CachedVersions, _declared_length, _lookup_name, + _PreparedRequest, param_alias, ) from .exceptions import ( - SwgohComlinkDecodeError, SwgohComlinkException, SwgohComlinkHTTPError, - SwgohComlinkRateLimitError, SwgohComlinkValueError, ) from .helpers import Constants, DataItems @@ -80,6 +78,7 @@ class SwgohComlinkAsync(SwgohComlinkBase): """ __comlink_type__ = "SwgohComlinkAsync" + _log = logger def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) @@ -119,67 +118,41 @@ async def _request( stats: bool = False, timeout: float | None = None, ) -> dict[str, Any] | list[Any]: - """Send an async HTTP request to the comlink service. + """Send an async HTTP request to the comlink service: the single gateway for all HTTP communication. - This is the single gateway for all HTTP communication. - - Args: - method: HTTP method (``"GET"`` or ``"POST"``). - endpoint: API endpoint path. - payload: JSON body for the request (ignored for GET requests). - stats: If True, use the stats service client. - timeout: Per-request timeout override. - - Returns: - Decoded JSON response (dict or list). + Each attempt waits for admission (pacing and rate holds), is sent, and on an HTTP error asks the + shared retry core in ``_base`` whether to try again, so both clients retry identically. Raises: SwgohComlinkHTTPError: When the service answers with an HTTP error status, after any retries allowed by the client's retry policy. Subclasses identify rate refusals, HTTP 503 and 4xx. SwgohComlinkException: On any network or decoding error. """ - policy = self.retry_policy - attempt = 1 - extra = 0.0 # retry wait carried into the next pass, on top of its pacing slot + attempt, extra = 1, 0.0 while True: - wait, release = self._pace_slot(endpoint, stats) - wait += extra - extra = 0.0 - while True: - deadline = _retry._clock() + wait - if wait > 0: - logger.debug("Pacing %s for %.2fs", endpoint, wait) - try: - await _retry._async_sleep(wait) - except asyncio.CancelledError: - release() - raise - if not self._hold_changed(endpoint, stats, deadline): - break - # A refusal arrived while this caller slept. Requeue behind the - # current hold, preserving spacing with other delayed callers. - release() - wait, release = self._pace_slot(endpoint, stats) + await self._admit(endpoint, stats, extra) try: return await self._send(method, endpoint, payload, stats, timeout) except SwgohComlinkHTTPError as exc: - delay = None if policy is None else policy.retry_delay(exc, attempt) - if policy is None or delay is None: - if policy is not None and attempt > 1: - logger.info("%s on %s; giving up after %d attempts", type(exc).__name__, endpoint, attempt) + extra = self._retry_wait(exc, attempt, endpoint, stats) + if extra is None: raise - logger.info( - "%s on %s (attempt %d of %d); retrying in %.1fs", - type(exc).__name__, - endpoint, - attempt, - policy.attempts, - delay, - ) - held = isinstance(exc, SwgohComlinkRateLimitError) and self._hold_endpoint(endpoint, stats, delay) - extra = policy.jitter_extra(delay) + (0.0 if held else delay) attempt += 1 + async def _admit(self, endpoint: str, stats: bool, extra: float) -> None: + """Sleep until *endpoint* admits the next attempt. + + Cancelling the task while it sleeps gives the reserved slot back before ``asyncio.CancelledError`` + propagates, so a cancelled caller never leaves a gap that later callers wait out. + """ + admission = self._admission(endpoint, stats, extra) + while (wait := admission.next_wait()) is not None: + try: + await _retry._async_sleep(wait) + except asyncio.CancelledError: + admission.abandon() + raise + async def _send( self, method: str, @@ -189,53 +162,30 @@ async def _send( timeout: float | None, ) -> dict[str, Any] | list[Any]: """Make one attempt at a request. Headers, including the HMAC signature, are rebuilt per attempt.""" - body = self._serialize_payload(payload) if method.upper() != "GET" and payload is not None else None - req_headers = self._construct_request_headers(method, endpoint, payload, body=body) - client = self.stats_client if stats else self.client - - request_kwargs: dict[str, Any] = {"headers": req_headers} - if timeout is not None: - request_kwargs["timeout"] = timeout - if method.upper() != "GET": - request_kwargs["content"] = body - - limit_name, limit = self._size_limit(endpoint, stats) + request = self._prepare_request(method, endpoint, payload, stats, timeout) + client = self.stats_client if request.stats else self.client try: - if limit is None: - r = await client.request(method.upper(), f"/{endpoint}", **request_kwargs) - r.raise_for_status() - content = r.content + if request.limit is None: + response = await client.request(request.method, request.url, **request.kwargs) + content = response.content else: - content = await self._receive_limited(client, method, endpoint, request_kwargs, limit_name, limit) - decoded = loads(content.decode("utf-8")) - if not isinstance(decoded, (dict, list)): - raise SwgohComlinkDecodeError("Expected a JSON object or array in the service response.") - return decoded - except (JSONDecodeError, UnicodeDecodeError) as e: - raise SwgohComlinkDecodeError("Unable to decode the service response as UTF-8 JSON.") from e - except httpx.HTTPStatusError as e: - raise SwgohComlinkHTTPError.from_response(e.response) from e + response, content = await self._receive_limited(client, request, endpoint, request.limit) except httpx.RequestError as e: raise SwgohComlinkException(e) from e + return self._interpret_response(response, content) async def _receive_limited( - self, - client: httpx.AsyncClient, - method: str, - endpoint: str, - request_kwargs: dict[str, Any], - limit_name: str, - limit: int, - ) -> bytes: - """Stream one response, reading at most *limit* decoded bytes of its body. + self, client: httpx.AsyncClient, request: _PreparedRequest, endpoint: str, limit: int + ) -> tuple[httpx.Response, bytes]: + """Stream one response, reading at most *limit* decoded bytes of its body; return it and the body. A success larger than *limit* raises ``SwgohComlinkValueError``, before any of the body is read when - ``Content-Length`` already exceeds it. An error body is cut to *limit* bytes and raised through - ``raise_for_status``. + ``Content-Length`` already exceeds it. An error response comes back as a copy whose body is cut to + *limit* bytes. """ - async with client.stream(method.upper(), f"/{endpoint}", **request_kwargs) as r: + async with client.stream(request.method, request.url, **request.kwargs) as r: if r.is_success and (declared := _declared_length(r.headers)) is not None and declared > limit: - raise self._too_large(endpoint, limit_name, limit, declared) + raise self._too_large(endpoint, request.limit_name, limit, declared) chunks: list[bytes] = [] size = 0 async for chunk in r.aiter_bytes(): @@ -243,12 +193,13 @@ async def _receive_limited( size += len(chunk) if size > limit: if r.is_success: - raise self._too_large(endpoint, limit_name, limit) + raise self._too_large(endpoint, request.limit_name, limit) break body = b"".join(chunks) if not r.is_success: - _bounded_error_response(r, body[:limit]).raise_for_status() - return body + error = _bounded_error_response(r, body[:limit]) + return error, error.content + return r, body async def _post( self, diff --git a/tests/unit/test_client_parity.py b/tests/unit/test_client_parity.py new file mode 100644 index 0000000..6c40f90 --- /dev/null +++ b/tests/unit/test_client_parity.py @@ -0,0 +1,49 @@ +"""The sync and async clients expose the same public API and share one retry core.""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable +from typing import Any + +import pytest + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync + +# Lifecycle methods named for their runtime: async name -> sync name. +RUNTIME_NAMES = {"aclose": "close"} + + +def _public_methods(cls: type) -> dict[str, Callable[..., Any]]: + return {name: member for name, member in inspect.getmembers(cls, callable) if not name.startswith("_")} + + +ASYNC_METHODS = _public_methods(SwgohComlinkAsync) +SYNC_METHODS = _public_methods(SwgohComlink) + + +def test_public_names_match() -> None: + assert {RUNTIME_NAMES.get(name, name) for name in ASYNC_METHODS} == set(SYNC_METHODS) + + +@pytest.mark.parametrize("name", sorted(ASYNC_METHODS)) +def test_every_async_method_exists_on_the_sync_client_with_the_same_signature(name: str) -> None: + async_method = ASYNC_METHODS[name] + sync_method = getattr(SwgohComlink, RUNTIME_NAMES.get(name, name), None) + assert sync_method is not None, f"SwgohComlink has no {RUNTIME_NAMES.get(name, name)}" + assert inspect.signature(async_method) == inspect.signature(sync_method) + # An alias such as getPlayer names the same function in both clients. + assert RUNTIME_NAMES.get(async_method.__name__, async_method.__name__) == sync_method.__name__ + # Methods defined on the client are coroutines in the async one and plain in the sync one. + # unwrap() looks through param_alias, whose wrapper is a plain function in both. + if async_method.__qualname__.startswith("SwgohComlinkAsync."): + assert inspect.iscoroutinefunction(inspect.unwrap(async_method)) + assert not inspect.iscoroutinefunction(inspect.unwrap(sync_method)) + + +@pytest.mark.parametrize("cls", [SwgohComlink, SwgohComlinkAsync]) +def test_request_is_a_short_loop_without_retry_decisions(cls: type) -> None: + source = inspect.getsource(cls._request) + assert len(source.splitlines()) < 40 + for decision in ("retry_policy", "retry_delay", "jitter", "_hold_endpoint", "_hold_changed", "_pace_slot"): + assert decision not in source diff --git a/tests/unit/test_retry_core.py b/tests/unit/test_retry_core.py new file mode 100644 index 0000000..a8a5358 --- /dev/null +++ b/tests/unit/test_retry_core.py @@ -0,0 +1,231 @@ +"""The sans-I/O request core shared by both clients: preparation, interpretation, admission and retry steps.""" + +from __future__ import annotations + +import json +import logging +from collections.abc import Callable + +import httpx +import pytest + +from swgoh_comlink import RetryPolicy, SwgohComlink +from swgoh_comlink import retry as retry_module +from swgoh_comlink.exceptions import ( + SwgohComlinkClientError, + SwgohComlinkDecodeError, + SwgohComlinkHTTPError, + SwgohComlinkRateLimitError, + SwgohComlinkUnavailableError, +) +from swgoh_comlink.retry import _Admission, _retry_step, _RetryStep + +LOG = logging.getLogger("tests.retry_core") +REQUEST = httpx.Request("POST", "http://localhost:3000/player") + + +def _error(status: int, body: dict[str, str] | None = None) -> SwgohComlinkHTTPError: + return SwgohComlinkHTTPError.from_response(httpx.Response(status, json=body or {}, request=REQUEST)) + + +@pytest.fixture +def now(monkeypatch: pytest.MonkeyPatch) -> list[float]: + clock = [100.0] + monkeypatch.setattr(retry_module, "_clock", lambda: clock[0]) + return clock + + +# ── Retry step ─────────────────────────────────────────────────────────── + + +def test_retry_step_holds_the_endpoint_after_a_rate_refusal() -> None: + assert _retry_step(RetryPolicy(), _error(429), attempt=1) == _RetryStep(delay=5.0, hold=True) + + +def test_retry_step_waits_without_a_hold_after_unavailable() -> None: + error = _error(503) + assert isinstance(error, SwgohComlinkUnavailableError) + assert _retry_step(RetryPolicy(), error, attempt=2) == _RetryStep(delay=10.0, hold=False) + + +@pytest.mark.parametrize(("status", "attempt"), [(400, 1), (500, 1), (429, 3)]) +def test_retry_step_gives_up(status: int, attempt: int) -> None: + assert _retry_step(RetryPolicy(attempts=3), _error(status), attempt=attempt) is None + + +# ── Admission ──────────────────────────────────────────────────────────── + + +class FakeSlots: + """Hands out a scripted wait per reservation and records which slots were given back.""" + + def __init__(self, waits: list[float], holds: list[bool]) -> None: + self.waits = waits + self.holds = holds + self.deadlines: list[float] = [] + self.released: list[int] = [] + self.taken = 0 + + def reserve(self) -> tuple[float, Callable[[], None]]: + slot = self.taken + self.taken += 1 + return self.waits.pop(0), lambda: self.released.append(slot) + + def held_after(self, deadline: float) -> bool: + self.deadlines.append(deadline) + return self.holds.pop(0) + + def admission(self, extra: float = 0.0) -> _Admission: + return _Admission("player", extra, self.reserve, self.held_after, LOG) + + +def test_admission_with_no_wait_admits_at_once(now: list[float]) -> None: + slots = FakeSlots(waits=[0.0], holds=[False]) + assert slots.admission().next_wait() is None + assert slots.deadlines == [100.0] + assert slots.released == [] + + +def test_admission_adds_the_carried_retry_wait_to_the_first_slot(now: list[float]) -> None: + slots = FakeSlots(waits=[1.0], holds=[False]) + admission = slots.admission(extra=5.0) + assert admission.next_wait() == 6.0 + now[0] += 6.0 + assert admission.next_wait() is None + assert slots.deadlines == [106.0] + + +def test_admission_requeues_behind_a_hold_set_while_waiting(now: list[float]) -> None: + slots = FakeSlots(waits=[1.0, 5.0], holds=[True, False]) + admission = slots.admission(extra=2.0) + assert admission.next_wait() == 3.0 + now[0] += 3.0 + # The carried retry wait is not added again to the new slot. + assert admission.next_wait() == 5.0 + assert slots.released == [0] + now[0] += 5.0 + assert admission.next_wait() is None + assert slots.deadlines == [103.0, 108.0] + + +def test_abandon_gives_back_the_current_slot(now: list[float]) -> None: + slots = FakeSlots(waits=[1.0, 5.0], holds=[True]) + admission = slots.admission() + admission.next_wait() + admission.next_wait() + admission.abandon() + assert slots.released == [0, 1] + + +def test_admission_logs_each_wait(now: list[float], caplog: pytest.LogCaptureFixture) -> None: + slots = FakeSlots(waits=[0.25], holds=[False]) + with caplog.at_level(logging.DEBUG, logger=LOG.name): + slots.admission().next_wait() + assert caplog.messages == ["Pacing player for 0.25s"] + + +# ── Request preparation ────────────────────────────────────────────────── + + +def test_prepare_post_serializes_the_payload_once() -> None: + with SwgohComlink() as client: + request = client._prepare_request("post", "player", {"payload": {"allyCode": "é"}}, stats=False, timeout=None) + assert request.method == "POST" + assert request.url == "/player" + assert request.kwargs == {"headers": {}, "content": '{"payload":{"allyCode":"é"}}'.encode()} + assert request.stats is False + assert (request.limit_name, request.limit) == ("max_response_bytes", None) + + +def test_prepare_get_sends_no_body_and_keeps_the_timeout() -> None: + with SwgohComlink(access_key="a", secret_key="s", max_response_bytes=10) as client: + request = client._prepare_request("GET", "enums", None, stats=True, timeout=7.0) + assert request.method == "GET" + assert "content" not in request.kwargs + assert request.kwargs["timeout"] == 7.0 + assert set(request.kwargs["headers"]) == {"X-Date", "Authorization"} + assert request.stats is True + assert (request.limit_name, request.limit) == ("max_response_bytes", 10) + + +def test_prepare_game_data_uses_its_own_limit() -> None: + with SwgohComlink(max_response_bytes=10, max_game_data_bytes=20) as client: + request = client._prepare_request("POST", "data", {}, stats=False, timeout=None) + assert (request.limit_name, request.limit) == ("max_game_data_bytes", 20) + + +# ── Response interpretation ────────────────────────────────────────────── + + +def test_interpret_decodes_a_json_object() -> None: + response = httpx.Response(200, json={"a": 1}, request=REQUEST) + assert SwgohComlink._interpret_response(response, response.content) == {"a": 1} + + +def test_interpret_raises_the_typed_http_error() -> None: + response = httpx.Response(400, json={"code": "BAD", "message": "no"}, request=REQUEST) + with pytest.raises(SwgohComlinkClientError) as caught: + SwgohComlink._interpret_response(response, response.content) + assert isinstance(caught.value.__cause__, httpx.HTTPStatusError) + + +@pytest.mark.parametrize(("body", "cause"), [(b"nope", json.JSONDecodeError), (b"\xff", UnicodeDecodeError)]) +def test_interpret_raises_a_decode_error(body: bytes, cause: type[Exception]) -> None: + response = httpx.Response(200, content=body, request=REQUEST) + with pytest.raises(SwgohComlinkDecodeError) as caught: + SwgohComlink._interpret_response(response, response.content) + assert isinstance(caught.value.__cause__, cause) + + +# ── Retry wait ─────────────────────────────────────────────────────────── + + +def test_retry_wait_without_a_policy_gives_up() -> None: + with SwgohComlink() as client: + assert client._retry_wait(_error(429), 1, "player", False) is None + + +def test_retry_wait_holds_a_paced_endpoint_instead_of_waiting(now: list[float], monkeypatch) -> None: + monkeypatch.setattr(retry_module, "_random", lambda: 0.5) + with SwgohComlink(retry=RetryPolicy(min_interval=0.4, jitter=0.2)) as client: + error = _error(429) + assert isinstance(error, SwgohComlinkRateLimitError) + # Only the jitter is carried; the hold makes every caller, this one included, wait out the delay. + assert client._retry_wait(error, 1, "player", False) == pytest.approx(0.5) + assert client._pace_delay("player", False) == pytest.approx(5.0) + + +def test_retry_wait_carries_the_delay_for_an_unpaced_endpoint(now: list[float], monkeypatch) -> None: + monkeypatch.setattr(retry_module, "_random", lambda: 0.0) + with SwgohComlink(retry=RetryPolicy(unpaced_endpoints=frozenset({"metadata"}))) as client: + assert client._retry_wait(_error(429), 1, "metadata", False) == 5.0 + assert client._retry_wait(_error(503), 1, "player", False) == 5.0 + + +def test_retry_wait_logs_under_the_client_module(caplog: pytest.LogCaptureFixture, monkeypatch) -> None: + monkeypatch.setattr(retry_module, "_random", lambda: 0.0) + with SwgohComlink(retry=RetryPolicy(attempts=2)) as client, caplog.at_level(logging.INFO, logger="swgoh_comlink"): + client._retry_wait(_error(503), 1, "player", False) + client._retry_wait(_error(503), 2, "player", False) + assert [record.name for record in caplog.records] == ["swgoh_comlink.swgoh_comlink"] * 2 + assert caplog.messages == [ + "SwgohComlinkUnavailableError on player (attempt 1 of 2); retrying in 5.0s", + "SwgohComlinkUnavailableError on player; giving up after 2 attempts", + ] + + +# ── Runtime cancellation ───────────────────────────────────────────────── + + +def test_sync_interrupt_while_pacing_gives_the_slot_back(now: list[float], monkeypatch) -> None: + """The sync client releases its slot on any exception while sleeping, KeyboardInterrupt included.""" + + def interrupted(seconds: float) -> None: + raise KeyboardInterrupt + + with SwgohComlink(retry=RetryPolicy(min_interval=1)) as client: + client._pace_delay("metadata", False) + monkeypatch.setattr(retry_module, "_sleep", interrupted) + with pytest.raises(KeyboardInterrupt): + client.get_game_metadata() + assert client._pace_delay("metadata", False) == 1