From 4ec7597e5aa32b7e67014349f6c255f3dd721417 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:24:10 -0500 Subject: [PATCH 01/47] 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 652af41f6203eeda9437c7ce4e5d27d3c7d8f89c Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:24:26 -0500 Subject: [PATCH 02/47] ci: pin GitHub Actions to commit SHAs Pin every third-party `uses:` line in .github/workflows to the full 40-character commit SHA of the latest release in the major version already in use, with a `# vX.Y.Z` comment so Dependabot's github-actions updates keep bumping them. Each SHA equals the commit the moving major tag pointed at when pinned, so behaviour is unchanged. The existing pypa/gh-action-pypi-publish pin is kept. Add tests/unit/test_workflow_pins.py to fail if a workflow uses an action by tag or branch, or drops the version comment. Refs #242 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/backmerge.yml | 2 +- .github/workflows/ci.yml | 40 ++++++++++---------- .github/workflows/commitlint.yml | 6 +-- .github/workflows/docs.yml | 6 +-- .github/workflows/integration.yml | 6 +-- .github/workflows/issue-fixed-in-develop.yml | 2 +- .github/workflows/labeler.yml | 4 +- .github/workflows/prepare-release.yml | 6 +-- .github/workflows/release.yml | 10 ++--- tests/unit/test_workflow_pins.py | 31 +++++++++++++++ 10 files changed, 72 insertions(+), 41 deletions(-) create mode 100644 tests/unit/test_workflow_pins.py diff --git a/.github/workflows/backmerge.yml b/.github/workflows/backmerge.yml index 91724c7..0dec931 100644 --- a/.github/workflows/backmerge.yml +++ b/.github/workflows/backmerge.yml @@ -38,7 +38,7 @@ jobs: github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: main fetch-depth: 0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 822c2c8..8af80e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,13 +20,13 @@ jobs: name: Lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" @@ -44,13 +44,13 @@ jobs: name: Type Check runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" @@ -69,13 +69,13 @@ jobs: matrix: python-version: ["3.11", "3.12", "3.13", "3.14"] steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python-version }} @@ -92,7 +92,7 @@ jobs: - name: Upload coverage artifact if: matrix.python-version == '3.12' - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: coverage-report path: coverage.xml @@ -102,13 +102,13 @@ jobs: name: Docs runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" @@ -123,13 +123,13 @@ jobs: name: Build runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" @@ -154,12 +154,12 @@ jobs: name: Offline StatCalc parity runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 - - uses: astral-sh/setup-uv@v7 - - uses: actions/setup-python@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: "24" - run: uv sync --locked --group test diff --git a/.github/workflows/commitlint.yml b/.github/workflows/commitlint.yml index 5b095b6..e413982 100644 --- a/.github/workflows/commitlint.yml +++ b/.github/workflows/commitlint.yml @@ -12,7 +12,7 @@ jobs: name: Validate Commit Messages runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -21,10 +21,10 @@ jobs: # same hook through pre-commit rather than its own npm install, so local and CI # validation cannot drift. - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Cache the pre-commit hook environment - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/pre-commit key: pre-commit-${{ runner.os }}-${{ hashFiles('.pre-commit-config.yaml') }} diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 5631519..65f012b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -62,7 +62,7 @@ jobs: if: github.repository == 'swgoh-utils/comlink-python' && startsWith(github.ref, 'refs/heads/release/') runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # Full history: hatch-vcs needs the tags, and mike builds on top of the # existing origin/gh-pages history. @@ -72,14 +72,14 @@ jobs: persist-credentials: true - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 with: # This job publishes the site, so it must not restore a cache that # other workflows (e.g. PR runs) can write. enable-cache: false - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 50384e0..04b647b 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -57,13 +57,13 @@ jobs: done done - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" diff --git a/.github/workflows/issue-fixed-in-develop.yml b/.github/workflows/issue-fixed-in-develop.yml index 93ecb0c..f8d49ba 100644 --- a/.github/workflows/issue-fixed-in-develop.yml +++ b/.github/workflows/issue-fixed-in-develop.yml @@ -31,7 +31,7 @@ jobs: issues: write pull-requests: read steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index dd7f457..d079c89 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -13,8 +13,8 @@ jobs: name: Auto Label runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 - - uses: actions/labeler@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/labeler@bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13 # v7.0.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} sync-labels: false diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 6ff794e..11151e5 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -36,16 +36,16 @@ jobs: if: github.ref == 'refs/heads/develop' steps: - name: Check out develop - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: develop fetch-depth: 0 - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 08e6b75..e3342cd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,16 +34,16 @@ jobs: steps: - name: Check-out repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} fetch-depth: 0 # full history + tags for version derivation - name: Install uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - name: Set up Python - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" @@ -87,7 +87,7 @@ jobs: test -f "dist/swgoh_comlink-${{ steps.version.outputs.version }}-py3-none-any.whl" - name: Upload build artifacts - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: dist path: dist/ @@ -107,7 +107,7 @@ jobs: steps: - name: Retrieve release distributions - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: dist path: dist/ diff --git a/tests/unit/test_workflow_pins.py b/tests/unit/test_workflow_pins.py new file mode 100644 index 0000000..213b1a0 --- /dev/null +++ b/tests/unit/test_workflow_pins.py @@ -0,0 +1,31 @@ +"""Guard that every third-party GitHub Action is pinned to a full commit SHA.""" + +import re +from pathlib import Path + +WORKFLOWS = Path(__file__).resolve().parents[2] / ".github/workflows" +USES = re.compile(r"^\s*(?:-\s+)?uses:\s*(?P\S+)(?P.*)$") +PINNED = re.compile(r"^[\w.-]+/[\w./-]+@[0-9a-f]{40}$") +VERSION_COMMENT = re.compile(r"^\s+#\s+v\d+\.\d+\.\d+\s*$") + + +def _uses_lines() -> list[tuple[str, int, str, str]]: + return [ + (path.name, number, match["ref"], match["rest"]) + for path in sorted(WORKFLOWS.glob("*.y*ml")) + for number, line in enumerate(path.read_text().splitlines(), start=1) + if (match := USES.match(line)) and not match["ref"].startswith("./") + ] + + +def test_workflows_have_uses_lines(): + assert _uses_lines(), "no `uses:` lines found; the workflow glob is wrong" + + +def test_every_action_is_pinned_to_a_commit_sha_with_a_version_comment(): + unpinned = [ + f"{name}:{number}: {ref}{rest}" + for name, number, ref, rest in _uses_lines() + if not PINNED.match(ref) or not VERSION_COMMENT.match(rest) + ] + assert not unpinned, "actions must use `@<40-char sha> # vX.Y.Z`:\n" + "\n".join(unpinned) From 16728120e8a440a2d5b08f33e1c90d345c9b6275 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:24:58 -0500 Subject: [PATCH 03/47] 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 04/47] 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 05/47] 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 06/47] 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 06b02274e91de2ff09851fad83e7e43e63385324 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:32:36 -0500 Subject: [PATCH 07/47] fix(statcalc): cap and optionally verify the game data download StatCalc() with no game_data downloaded gameData.json with no size limit and no way to check its integrity, and the sync path used urllib, which trusts the system CA store instead of certifi. - Fetch through httpx.Client (sync) and httpx.AsyncClient (async), both following redirects with the existing 30 s timeout. - Stream the body through one shared helper, _GameDataDownload, which aborts past _MAX_GAMEDATA_BYTES (64 MiB, counted after Content-Encoding decoding) and, when asked, checks the SHA-256 of the body before parsing. Both raise SwgohComlinkValueError. - Add keyword-only game_data_url and expected_sha256 to StatCalc.__init__ and StatCalcAsync.create. The default stays the latest main of swgoh-utils/gamedata. Refs #234 Co-Authored-By: Claude Opus 5.5 --- docs/api/statcalc.md | 17 ++ docs/migration.md | 6 + src/swgoh_comlink/StatCalc/calculator.py | 114 ++++++++- .../StatCalc/calculator_async.py | 51 +++- tests/unit/test_calculator.py | 14 +- tests/unit/test_statcalc_async.py | 2 +- tests/unit/test_statcalc_gamedata.py | 217 ++++++++++++++++++ 7 files changed, 388 insertions(+), 33 deletions(-) create mode 100644 tests/unit/test_statcalc_gamedata.py diff --git a/docs/api/statcalc.md b/docs/api/statcalc.md index 9ba741a..8251377 100644 --- a/docs/api/statcalc.md +++ b/docs/api/statcalc.md @@ -27,11 +27,28 @@ calc = StatCalc() # Offline — supply pre-loaded game data calc = StatCalc(game_data=my_game_data_dict) + +# Fetch from a mirror or fork, and check the bytes against a known digest +calc = StatCalc(game_data_url="https://mirror.example/gameData.json", expected_sha256="<64 hex digits>") + +# Async — same options on the factory +calc = await StatCalcAsync.create(expected_sha256="<64 hex digits>") ``` The `game_data` parameter accepts the JSON payload from the [swgoh-utils/gamedata](https://github.com/swgoh-utils/gamedata) repository. +When `game_data` is omitted, the calculator downloads the latest `gameData.json` +from the `main` branch of that repository over `httpx` (sync and async alike). +The download is capped at 64 MiB, counted after any gzip decoding; a larger body +raises `SwgohComlinkValueError`. The keyword-only options apply only to that download: + +- `game_data_url` fetches from another URL instead of the default. +- `expected_sha256` hashes the downloaded bytes before parsing and raises + `SwgohComlinkValueError` if they do not match. + +Passing either option together with `game_data` raises `SwgohComlinkValueError`. + ## Usage Examples ### Calculate stats for a single character diff --git a/docs/migration.md b/docs/migration.md index 21c96c5..2ee2538 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -324,6 +324,12 @@ Upgrading from v2.8 to v2.9. `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. +- **StatCalc game data download is capped and uses httpx.** `StatCalc()` fetches through + `httpx` (certifi CA bundle, not the system store) and follows redirects in both the sync + and async paths. A body over 64 MiB raises `SwgohComlinkValueError`. New keyword-only + `game_data_url` and `expected_sha256` on `StatCalc()` and `StatCalcAsync.create()` pick + the source and verify its SHA-256; the default stays the latest `main` of + swgoh-utils/gamedata. ## Summary of changes diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index fa7095d..448b8ad 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -1,15 +1,77 @@ from __future__ import annotations import copy +import hashlib import json import logging import math -import urllib.request +import re from typing import Any +import httpx + from ..exceptions import SwgohComlinkValueError from ..helpers._stat_data import STATS as _CANONICAL_STATS +# Largest game data body accepted, counted after any Content-Encoding is decoded +# (gameData.json is about 1.6 MB). +_MAX_GAMEDATA_BYTES = 64 * 1024 * 1024 +_GAMEDATA_TIMEOUT = 30.0 +_SHA256_HEX = re.compile(r"[0-9a-f]{64}") + + +def _check_fetch_options( + game_data: dict[str, Any] | None, game_data_url: str | None, expected_sha256: str | None +) -> str | None: + """Validate the game data fetch options and return *expected_sha256* normalised to lower case. + + Raises: + SwgohComlinkValueError: A fetch option was combined with *game_data*, or + *expected_sha256* is not 64 hex digits. + """ + if game_data is not None and (game_data_url is not None or expected_sha256 is not None): + raise SwgohComlinkValueError("game_data_url and expected_sha256 apply only when game_data is not given") + if expected_sha256 is None: + return None + normalized = expected_sha256.strip().lower() + if not _SHA256_HEX.fullmatch(normalized): + raise SwgohComlinkValueError("expected_sha256 must be a SHA-256 digest of 64 hexadecimal digits") + return normalized + + +class _GameDataDownload: + """Collect a streamed game data body, enforcing the size cap and optional SHA-256 check. + + Shared by the sync and async fetches: each feeds the decoded chunks it reads + from ``iter_bytes``/``aiter_bytes`` into :meth:`feed`, then calls :meth:`parse`. + """ + + __slots__ = ("_body", "_expected_sha256", "_hasher", "_url") + + def __init__(self, url: str, expected_sha256: str | None) -> None: + self._url = url + self._expected_sha256 = expected_sha256 + self._hasher = hashlib.sha256() if expected_sha256 is not None else None + self._body = bytearray() + + def feed(self, chunk: bytes) -> None: + """Append *chunk*, raising once the body passes ``_MAX_GAMEDATA_BYTES``.""" + if len(self._body) + len(chunk) > _MAX_GAMEDATA_BYTES: + raise SwgohComlinkValueError( + f"Game data from {self._url} exceeds the {_MAX_GAMEDATA_BYTES} bytes limit; download aborted" + ) + self._body += chunk + if self._hasher is not None: + self._hasher.update(chunk) + + def parse(self) -> Any: + """Check the SHA-256 digest, if one was expected, then decode the body as JSON.""" + if self._hasher is not None and (actual := self._hasher.hexdigest()) != self._expected_sha256: + raise SwgohComlinkValueError( + f"Game data SHA-256 mismatch for {self._url}: expected {self._expected_sha256}, got {actual}" + ) + return json.loads(self._body.decode("utf-8")) + class StatCalc: """SWGOH stat calculator @@ -18,6 +80,12 @@ class StatCalc: game_data: Optional preloaded game data payload. If omitted, the calculator fetches the latest payload from the swgoh-utils GitHub game data repository. + game_data_url: Keyword-only. URL to fetch the game data from instead + of the latest ``main`` of swgoh-utils/gamedata, such as a mirror + or a fork. Only used when *game_data* is omitted. + expected_sha256: Keyword-only. Hex SHA-256 digest the fetched body + must match; checked before parsing. Only used when *game_data* + is omitted. """ _FIXED_GAME_STYLE = True @@ -32,12 +100,28 @@ class StatCalc: # 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: + def __init__( + self, + game_data: dict[str, Any] | None = None, + *, + game_data_url: str | None = None, + expected_sha256: str | None = None, + ) -> None: """Initialize a calculator instance. Args: game_data: Optional game data payload to load immediately. + game_data_url: URL to fetch the game data from when *game_data* is + omitted. Defaults to the latest ``main`` of swgoh-utils/gamedata. + expected_sha256: Hex SHA-256 digest the fetched body must match. + + Raises: + SwgohComlinkValueError: *expected_sha256* is malformed, a fetch option + is combined with *game_data*, the fetched body is larger than + 64 MiB, or its digest does not match *expected_sha256*. + RuntimeError: The game data could not be fetched or parsed. """ + expected_sha256 = _check_fetch_options(game_data, game_data_url, expected_sha256) self._unit_data: dict[str, Any] | None = None self._mod_set_data: dict[str, Any] | None = None self._gear_data: dict[str, Any] | None = None @@ -47,7 +131,7 @@ def __init__(self, game_data: dict[str, Any] | None = None) -> None: if game_data is None: self._LOGGER.info("No game data provided, loading from GitHub") - game_data = self._fetch_game_data_from_github() + game_data = self._fetch_game_data_from_github(game_data_url, expected_sha256) else: self._LOGGER.debug("Using caller-provided game data") self.set_game_data(game_data) @@ -265,14 +349,24 @@ def _require_game_data(self) -> None: raise RuntimeError("set_game_data(game_data) must be called first") @classmethod - def _fetch_game_data_from_github(cls) -> dict[str, Any]: + def _fetch_game_data_from_github(cls, url: str | None = None, expected_sha256: str | None = None) -> dict[str, Any]: + url = cls._DEFAULT_GAMEDATA_URL if url is None else url + download = _GameDataDownload(url, expected_sha256) try: - cls._LOGGER.info("Fetching game data from %s", cls._DEFAULT_GAMEDATA_URL) - with urllib.request.urlopen(cls._DEFAULT_GAMEDATA_URL, timeout=30) as response: - payload = json.loads(response.read().decode("utf-8")) - except Exception as exc: # pragma: no cover - network failure path - cls._LOGGER.exception("Failed to fetch game data from GitHub") - raise RuntimeError(f"Unable to retrieve game data from {cls._DEFAULT_GAMEDATA_URL}") from exc + cls._LOGGER.info("Fetching game data from %s", url) + with ( + httpx.Client(follow_redirects=True, timeout=_GAMEDATA_TIMEOUT) as client, + client.stream("GET", url) as response, + ): + response.raise_for_status() + for chunk in response.iter_bytes(): + download.feed(chunk) + payload = download.parse() + except SwgohComlinkValueError: + raise + except Exception as exc: + cls._LOGGER.exception("Failed to fetch game data from %s", url) + raise RuntimeError(f"Unable to retrieve game data from {url}") from exc return cls._normalize_game_data_payload(payload) diff --git a/src/swgoh_comlink/StatCalc/calculator_async.py b/src/swgoh_comlink/StatCalc/calculator_async.py index e64dc95..a737d24 100644 --- a/src/swgoh_comlink/StatCalc/calculator_async.py +++ b/src/swgoh_comlink/StatCalc/calculator_async.py @@ -5,7 +5,8 @@ import httpx -from .calculator import StatCalc +from ..exceptions import SwgohComlinkValueError +from .calculator import _GAMEDATA_TIMEOUT, StatCalc, _check_fetch_options, _GameDataDownload class StatCalcAsync(StatCalc): @@ -13,8 +14,8 @@ class StatCalcAsync(StatCalc): Inherits all computation methods from :class:`StatCalc`. The only difference is how game data is fetched during initialization: this - class uses ``httpx.AsyncClient`` instead of blocking - ``urllib.request``. + class uses ``httpx.AsyncClient`` instead of the blocking + ``httpx.Client``. Both apply the same size cap and SHA-256 check. Because ``__init__`` cannot be ``async``, use the :meth:`create` classmethod factory when game data needs to be fetched from GitHub: @@ -49,7 +50,13 @@ def __init__(self, game_data: dict[str, Any]) -> None: super().__init__(game_data=game_data) @classmethod - async def create(cls, game_data: dict[str, Any] | None = None) -> StatCalcAsync: + async def create( + cls, + game_data: dict[str, Any] | None = None, + *, + game_data_url: str | None = None, + expected_sha256: str | None = None, + ) -> StatCalcAsync: """Factory method to create a :class:`StatCalcAsync` instance. If *game_data* is ``None``, the latest payload is fetched @@ -57,28 +64,48 @@ async def create(cls, game_data: dict[str, Any] | None = None) -> StatCalcAsync: Args: game_data: Optional pre-loaded game data payload. + game_data_url: URL to fetch the game data from when *game_data* is + omitted. Defaults to the latest ``main`` of swgoh-utils/gamedata. + expected_sha256: Hex SHA-256 digest the fetched body must match. Returns: A fully initialized :class:`StatCalcAsync` instance. + + Raises: + SwgohComlinkValueError: *expected_sha256* is malformed, a fetch option + is combined with *game_data*, the fetched body is larger than + 64 MiB, or its digest does not match *expected_sha256*. + RuntimeError: The game data could not be fetched or parsed. """ + expected_sha256 = _check_fetch_options(game_data, game_data_url, expected_sha256) if game_data is None: cls._LOGGER.info("No game data provided, loading from GitHub (async)") - game_data = await cls._async_fetch_game_data_from_github() + game_data = await cls._async_fetch_game_data_from_github(game_data_url, expected_sha256) else: cls._LOGGER.debug("Using caller-provided game data") return cls(game_data=game_data) @classmethod - async def _async_fetch_game_data_from_github(cls) -> dict[str, Any]: + async def _async_fetch_game_data_from_github( + cls, url: str | None = None, expected_sha256: str | None = None + ) -> dict[str, Any]: """Fetch game data from GitHub asynchronously using httpx.""" + url = cls._DEFAULT_GAMEDATA_URL if url is None else url + download = _GameDataDownload(url, expected_sha256) try: - cls._LOGGER.info("Fetching game data from %s", cls._DEFAULT_GAMEDATA_URL) - async with httpx.AsyncClient() as client: - response = await client.get(cls._DEFAULT_GAMEDATA_URL, timeout=30) + cls._LOGGER.info("Fetching game data from %s", url) + async with ( + httpx.AsyncClient(follow_redirects=True, timeout=_GAMEDATA_TIMEOUT) as client, + client.stream("GET", url) as response, + ): response.raise_for_status() - payload = response.json() + async for chunk in response.aiter_bytes(): + download.feed(chunk) + payload = download.parse() + except SwgohComlinkValueError: + raise except Exception as exc: - cls._LOGGER.exception("Failed to fetch game data from GitHub") - raise RuntimeError(f"Unable to retrieve game data from {cls._DEFAULT_GAMEDATA_URL}") from exc + cls._LOGGER.exception("Failed to fetch game data from %s", url) + raise RuntimeError(f"Unable to retrieve game data from {url}") from exc return cls._normalize_game_data_payload(payload) diff --git a/tests/unit/test_calculator.py b/tests/unit/test_calculator.py index 9c9deab..e90d6c0 100644 --- a/tests/unit/test_calculator.py +++ b/tests/unit/test_calculator.py @@ -7,12 +7,12 @@ from __future__ import annotations import copy -import io import json from pathlib import Path from typing import Any import pytest +from pytest_httpx import HTTPXMock from swgoh_comlink import StatCalc from swgoh_comlink.exceptions import SwgohComlinkValueError @@ -256,20 +256,14 @@ def test_set_game_data_rejects_missing_or_none_table(calc, game_data, key): 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] = [] - - def urlopen(url: str, timeout: float) -> io.BytesIO: - seen_urls.append(url) - return io.BytesIO(json.dumps({"data": {"unitData": game_data["unitData"]}}).encode()) - - monkeypatch.setattr("urllib.request.urlopen", urlopen) +def test_game_data_is_fetched_from_github_when_not_given(monkeypatch, game_data, httpx_mock: HTTPXMock): + httpx_mock.add_response(url=StatCalc._DEFAULT_GAMEDATA_URL, json={"data": {"unitData": game_data["unitData"]}}) loaded: list[dict[str, Any]] = [] monkeypatch.setattr(StatCalc, "set_game_data", lambda self, data: loaded.append(data)) StatCalc() - assert seen_urls == [StatCalc._DEFAULT_GAMEDATA_URL] + assert [str(r.url) for r in httpx_mock.get_requests()] == [StatCalc._DEFAULT_GAMEDATA_URL] assert loaded == [{"unitData": game_data["unitData"]}] # the {"data": ...} wrapper is unwrapped diff --git a/tests/unit/test_statcalc_async.py b/tests/unit/test_statcalc_async.py index 3b026d1..eb2be66 100644 --- a/tests/unit/test_statcalc_async.py +++ b/tests/unit/test_statcalc_async.py @@ -27,7 +27,7 @@ async def test_create_with_game_data(game_data): async def test_create_without_game_data_fetches_it(monkeypatch, game_data): - async def fetch() -> dict[str, Any]: + async def fetch(url: str | None = None, expected_sha256: str | None = None) -> dict[str, Any]: return game_data monkeypatch.setattr(StatCalcAsync, "_async_fetch_game_data_from_github", staticmethod(fetch)) diff --git a/tests/unit/test_statcalc_gamedata.py b/tests/unit/test_statcalc_gamedata.py new file mode 100644 index 0000000..7674c68 --- /dev/null +++ b/tests/unit/test_statcalc_gamedata.py @@ -0,0 +1,217 @@ +"""Tests for the StatCalc / StatCalcAsync game data download: size cap, SHA-256 check and URL override. + +Every test runs against both the sync fetch (``httpx.Client``) and the async fetch +(``httpx.AsyncClient``); pytest-httpx mocks both, so nothing touches the network. +""" + +from __future__ import annotations + +import gzip +import hashlib +import inspect +import json +from collections.abc import Awaitable, Callable, Iterator +from pathlib import Path +from typing import Any + +import pytest +from pytest_httpx import HTTPXMock, IteratorStream + +from swgoh_comlink import StatCalc, StatCalcAsync +from swgoh_comlink.exceptions import SwgohComlinkValueError +from swgoh_comlink.StatCalc import calculator + +DEFAULT_URL = StatCalc._DEFAULT_GAMEDATA_URL +MIRROR_URL = "https://mirror.example/gameData.json" +SMALL_CAP = 1024 + +Fetch = Callable[..., Awaitable[dict[str, Any]]] +Create = Callable[..., Awaitable[StatCalc]] + + +async def _sync_fetch(url: str | None = None, expected_sha256: str | None = None) -> dict[str, Any]: + return StatCalc._fetch_game_data_from_github(url, expected_sha256) + + +async def _async_fetch(url: str | None = None, expected_sha256: str | None = None) -> dict[str, Any]: + return await StatCalcAsync._async_fetch_game_data_from_github(url, expected_sha256) + + +async def _sync_create(**kwargs: Any) -> StatCalc: + return StatCalc(**kwargs) + + +@pytest.fixture(params=[_sync_fetch, _async_fetch], ids=["sync", "async"]) +def fetch(request: pytest.FixtureRequest) -> Fetch: + """Call the sync or async game data fetch with the same signature.""" + return request.param + + +@pytest.fixture(params=[_sync_create, StatCalcAsync.create], ids=["sync", "async"]) +def create(request: pytest.FixtureRequest) -> Create: + """Build a calculator through ``StatCalc(...)`` or ``await StatCalcAsync.create(...)``.""" + return request.param + + +@pytest.fixture +def small_cap(monkeypatch: pytest.MonkeyPatch) -> int: + """Lower the download cap so oversized bodies stay small in tests.""" + monkeypatch.setattr(calculator, "_MAX_GAMEDATA_BYTES", SMALL_CAP) + return SMALL_CAP + + +@pytest.fixture(scope="module") +def body() -> bytes: + """A valid wrapped game data payload, as served by swgoh-utils/gamedata.""" + return (Path(__file__).resolve().parent.parent / "resources" / "gameData.json").read_bytes() + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +# ── Transport ──────────────────────────────────────────────────────────── + + +def test_statcalc_does_not_use_urllib(): + sources = Path(calculator.__file__).parent.rglob("*.py") + assert [p.name for p in sources if "urllib" in p.read_text(encoding="utf-8")] == [] + + +async def test_default_url_is_the_latest_main_branch(fetch: Fetch, httpx_mock: HTTPXMock): + assert DEFAULT_URL == "https://raw.githubusercontent.com/swgoh-utils/gamedata/main/gameData.json" + httpx_mock.add_response(url=DEFAULT_URL, json={"data": {"unitData": {"X": {}}}}) + + assert await fetch() == {"unitData": {"X": {}}} + + +async def test_game_data_url_overrides_the_default(fetch: Fetch, httpx_mock: HTTPXMock): + httpx_mock.add_response(url=MIRROR_URL, json={"unitData": {"Y": {}}}) + + assert await fetch(MIRROR_URL) == {"unitData": {"Y": {}}} + + +async def test_redirects_are_followed(fetch: Fetch, httpx_mock: HTTPXMock): + httpx_mock.add_response(url=DEFAULT_URL, status_code=302, headers={"Location": MIRROR_URL}) + httpx_mock.add_response(url=MIRROR_URL, json={"unitData": {"Z": {}}}) + + assert await fetch() == {"unitData": {"Z": {}}} + + +async def test_http_errors_still_raise_runtime_error(fetch: Fetch, httpx_mock: HTTPXMock): + httpx_mock.add_response(url=MIRROR_URL, status_code=404) + + with pytest.raises(RuntimeError, match=f"Unable to retrieve game data from {MIRROR_URL}"): + await fetch(MIRROR_URL) + + +# ── Size cap ───────────────────────────────────────────────────────────── + + +def test_cap_is_64_mib(): + assert calculator._MAX_GAMEDATA_BYTES == 64 * 1024 * 1024 + + +async def test_oversized_body_raises_before_it_is_fully_read(fetch: Fetch, httpx_mock: HTTPXMock, small_cap: int): + chunk = b" " * 256 + total_chunks = 100 + served: list[int] = [] + + def chunks() -> Iterator[bytes]: + for i in range(total_chunks): + served.append(i) + yield chunk + + httpx_mock.add_response(url=DEFAULT_URL, stream=IteratorStream(chunks())) + + with pytest.raises(SwgohComlinkValueError, match=f"{small_cap} bytes"): + await fetch() + # The cap trips on the first chunk past 1 KiB; the remaining chunks are never pulled. + assert len(served) == small_cap // len(chunk) + 1 + assert len(served) < total_chunks + + +async def test_body_at_the_cap_loads(fetch: Fetch, httpx_mock: HTTPXMock, small_cap: int): + payload = json.dumps({"unitData": {}}).encode() + httpx_mock.add_response(url=DEFAULT_URL, content=payload.ljust(small_cap)) + + assert await fetch() == {"unitData": {}} + + +async def test_cap_counts_decompressed_bytes(fetch: Fetch, httpx_mock: HTTPXMock, small_cap: int): + decompressed = json.dumps({"unitData": {}}).encode().ljust(small_cap * 64) + compressed = gzip.compress(decompressed) + assert len(compressed) < small_cap # the wire size alone would pass the cap + httpx_mock.add_response(url=DEFAULT_URL, stream=IteratorStream([compressed]), headers={"Content-Encoding": "gzip"}) + + with pytest.raises(SwgohComlinkValueError, match="exceeds"): + await fetch() + + +# ── SHA-256 check ──────────────────────────────────────────────────────── + + +async def test_matching_hash_loads(fetch: Fetch, httpx_mock: HTTPXMock, body: bytes): + httpx_mock.add_response(url=DEFAULT_URL, content=body) + + data = await fetch(expected_sha256=_sha256(body)) + + assert set(StatCalc._REQUIRED_TABLES) <= set(data) + + +async def test_hash_is_taken_over_the_decompressed_body(fetch: Fetch, httpx_mock: HTTPXMock, body: bytes): + gzipped = IteratorStream([gzip.compress(body)]) + httpx_mock.add_response(url=DEFAULT_URL, stream=gzipped, headers={"Content-Encoding": "gzip"}) + + assert "unitData" in await fetch(expected_sha256=_sha256(body)) + + +async def test_hash_mismatch_raises(fetch: Fetch, httpx_mock: HTTPXMock, body: bytes): + httpx_mock.add_response(url=DEFAULT_URL, content=body) + + with pytest.raises(SwgohComlinkValueError, match="SHA-256 mismatch"): + await fetch(expected_sha256=_sha256(b"something else")) + + +async def test_hash_mismatch_is_checked_before_parsing(fetch: Fetch, httpx_mock: HTTPXMock): + httpx_mock.add_response(url=DEFAULT_URL, content=b"not json") + + with pytest.raises(SwgohComlinkValueError, match="SHA-256 mismatch"): + await fetch(expected_sha256="0" * 64) + + +# ── Constructor arguments ──────────────────────────────────────────────── + + +async def test_create_with_url_and_hash(create: Create, httpx_mock: HTTPXMock, body: bytes): + httpx_mock.add_response(url=MIRROR_URL, content=body) + + calc = await create(game_data_url=MIRROR_URL, expected_sha256=_sha256(body).upper()) + + assert calc.calc_char_gp({"defId": "BOSSK", "rarity": 7, "level": 85, "gear": 13}) > 0 + + +async def test_create_rejects_a_hash_mismatch(create: Create, httpx_mock: HTTPXMock, body: bytes): + httpx_mock.add_response(url=DEFAULT_URL, content=body) + + with pytest.raises(SwgohComlinkValueError, match="SHA-256 mismatch"): + await create(expected_sha256="f" * 64) + + +@pytest.mark.parametrize("bad", ["", "abc", "g" * 64, "0" * 63, "0" * 65]) +async def test_malformed_hash_is_rejected_before_fetching(create: Create, httpx_mock: HTTPXMock, bad: str): + # No response is registered: any request would fail the test. + with pytest.raises(SwgohComlinkValueError, match="expected_sha256"): + await create(expected_sha256=bad) + + +@pytest.mark.parametrize("kwargs", [{"game_data_url": MIRROR_URL}, {"expected_sha256": "0" * 64}]) +async def test_fetch_options_with_game_data_are_rejected(create: Create, game_data: dict[str, Any], kwargs: dict): + with pytest.raises(SwgohComlinkValueError, match="game_data"): + await create(game_data=game_data, **kwargs) + + +@pytest.mark.parametrize("name", ["game_data_url", "expected_sha256"]) +def test_fetch_options_are_keyword_only(name: str): + for func in (StatCalc.__init__, StatCalcAsync.create): + assert inspect.signature(func).parameters[name].kind is inspect.Parameter.KEYWORD_ONLY From 3201dbee7322ad981dd334a145d5a105dbd10242 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:38:55 -0500 Subject: [PATCH 08/47] perf(statcalc): run StatCalcAsync calculations off the event loop Add acalc_char_stats, acalc_ship_stats, acalc_roster_stats and acalc_player_stats to StatCalcAsync. Each runs the matching calc_* method in a worker thread via asyncio.to_thread, so a 386-unit roster (tens of ms of CPU) no longer blocks the loop. The inherited sync methods are unchanged. The game data tables are only read during calculation (a test checks they are unchanged after a full roster), so concurrent calls on one instance are safe. The docstring and docs say not to call set_game_data mid-calculation or touch an input while its call is in progress. Docs, README and the async example now use the acalc_* methods. Refs #243 Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- docs/api/async.md | 7 +- docs/api/statcalc.md | 29 +++- docs/migration.md | 5 + examples/Async/calc_stats_local.py | 13 +- .../StatCalc/calculator_async.py | 72 +++++++++- tests/unit/test_statcalc_async.py | 129 ++++++++++++++++++ 7 files changed, 242 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 0efe664..ee5c770 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ calc = StatCalc(game_data=my_game_data_dict) ### Async usage (`StatCalcAsync`) -`StatCalcAsync` provides an async factory method for fetching game data without blocking the event loop. All calculation methods are inherited from `StatCalc` and remain synchronous (they are pure computation). +`StatCalcAsync` provides an async factory method for fetching game data without blocking the event loop. Its `acalc_char_stats`, `acalc_ship_stats`, `acalc_roster_stats` and `acalc_player_stats` methods run the matching `calc_*` method in a worker thread, so a large roster does not stall the event loop. The inherited synchronous `calc_*` methods still work but block the loop while they run. ```python from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync @@ -187,7 +187,7 @@ async with SwgohComlinkAsync() as comlink: calc = await StatCalcAsync.create() # fetches game data from GitHub async player = await comlink.get_player(allycode=245866537) - calc.calc_roster_stats(player['rosterUnit']) + await calc.acalc_roster_stats(player['rosterUnit']) ``` With pre-loaded game data (no async fetch needed): diff --git a/docs/api/async.md b/docs/api/async.md index e1d857f..338cde3 100644 --- a/docs/api/async.md +++ b/docs/api/async.md @@ -61,8 +61,9 @@ async with SwgohComlinkAsync(retry=RetryPolicy(min_interval=0.4)) as comlink: ## Stat Calculation -For local stat calculation in async code, use `StatCalcAsync` which fetches -game data without blocking the event loop: +For local stat calculation in async code, use `StatCalcAsync`. It fetches game +data without blocking the event loop, and its `acalc_*` methods run the +calculation in a worker thread: ```python from swgoh_comlink import StatCalcAsync, SwgohComlinkAsync @@ -70,7 +71,7 @@ from swgoh_comlink import StatCalcAsync, SwgohComlinkAsync async with SwgohComlinkAsync() as comlink: calc = await StatCalcAsync.create() player = await comlink.get_player(allycode=245866537) - calc.calc_roster_stats(player["rosterUnit"]) + await calc.acalc_roster_stats(player["rosterUnit"]) ``` See the [StatCalc API](statcalc.md) for full details. diff --git a/docs/api/statcalc.md b/docs/api/statcalc.md index 8251377..229c814 100644 --- a/docs/api/statcalc.md +++ b/docs/api/statcalc.md @@ -102,9 +102,17 @@ ship_gp = calc.calc_ship_gp(ship_unit, crew_list) ## Async Usage (`StatCalcAsync`) -`StatCalcAsync` inherits all calculation methods from `StatCalc`. The only -difference is initialization: use the async `create()` factory to fetch game -data without blocking the event loop. +Use the async `create()` factory to fetch game data without blocking the event +loop, and the `acalc_*` methods to calculate stats. Each one runs the matching +`calc_*` method in a worker thread (`asyncio.to_thread`), so a large roster or +guild does not stall the loop (for example a Discord bot's gateway heartbeat). + +| Async method | Runs | +|--------------|------| +| `await calc.acalc_char_stats(unit)` | `calc_char_stats` | +| `await calc.acalc_ship_stats(ship, crew)` | `calc_ship_stats` | +| `await calc.acalc_roster_stats(units)` | `calc_roster_stats` | +| `await calc.acalc_player_stats(players)` | `calc_player_stats` | ```python from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync @@ -113,9 +121,18 @@ async with SwgohComlinkAsync() as comlink: calc = await StatCalcAsync.create() # async fetch from GitHub player = await comlink.get_player(allycode=245866537) - calc.calc_roster_stats(player["rosterUnit"]) + await calc.acalc_player_stats(player) ``` +The inherited synchronous `calc_*` methods still work, but they block the event +loop while they run. + +The game data tables are only read during calculation, so concurrent `acalc_*` +calls on one instance are safe. Do not call `set_game_data()` while a +calculation is running, and do not touch a unit or player while its `acalc_*` +call is in progress: the worker thread updates it in place. Cancelling the +awaiting task does not stop the worker thread. + With pre-loaded data (no async fetch): ```python @@ -180,6 +197,10 @@ transforms them into the dict format expected by `StatCalc.set_game_data()`. members: - __init__ - create + - acalc_char_stats + - acalc_ship_stats + - acalc_roster_stats + - acalc_player_stats ### GameDataBuilder diff --git a/docs/migration.md b/docs/migration.md index 2ee2538..0ac42ef 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -330,6 +330,11 @@ Upgrading from v2.8 to v2.9. `game_data_url` and `expected_sha256` on `StatCalc()` and `StatCalcAsync.create()` pick the source and verify its SHA-256; the default stays the latest `main` of swgoh-utils/gamedata. +- **`StatCalcAsync` can calculate off the event loop.** New `acalc_char_stats`, + `acalc_ship_stats`, `acalc_roster_stats` and `acalc_player_stats` run the matching + `calc_*` method in a worker thread. The sync `calc_*` methods are unchanged but block the + loop; in async code, replace `calc.calc_player_stats(p)` with + `await calc.acalc_player_stats(p)`. ## Summary of changes diff --git a/examples/Async/calc_stats_local.py b/examples/Async/calc_stats_local.py index b33c4e8..ddd99af 100644 --- a/examples/Async/calc_stats_local.py +++ b/examples/Async/calc_stats_local.py @@ -2,6 +2,9 @@ calc_stats_local.py Example usage of async StatCalcAsync support. +The acalc_* methods run the calculation in a worker thread so it does not +block the event loop. + Demonstrates: 1. Basic character stats (minimal unit definition) 2. Character with skills and mods (normalized format) @@ -26,7 +29,7 @@ async def main(): } calc = await StatCalcAsync.create() - stats = calc.calc_char_stats(basic_unit) + stats = await calc.acalc_char_stats(basic_unit) print("=== Basic unit (no skills/mods) ===") print(stats) @@ -65,17 +68,17 @@ async def main(): ], } - stats = calc.calc_char_stats(unit_with_skills_and_mods) + stats = await calc.acalc_char_stats(unit_with_skills_and_mods) print("\n=== Unit with skills and mods ===") print(stats) # --- Example 3: Player roster stats from Comlink API --- # Requires a running Comlink service. - # calc_player_stats accepts the raw player payload from get_player(). + # acalc_player_stats accepts the raw player payload from get_player(). # async with SwgohComlinkAsync() as comlink: # player = await comlink.get_player(allycode=123456789) - # calc.calc_player_stats(player) + # await calc.acalc_player_stats(player) # for unit in player["rosterUnit"][:3]: # name = unit["definitionId"].split(":")[0] # gp = unit.get("gp", "N/A") @@ -85,7 +88,7 @@ async def main(): # async with SwgohComlinkAsync() as comlink: # game_data = await GameDataBuilderAsync(comlink).build() # calc = StatCalcAsync(game_data=game_data) - # stats = calc.calc_char_stats(basic_unit) + # stats = await calc.acalc_char_stats(basic_unit) # print("From Comlink:", stats) diff --git a/src/swgoh_comlink/StatCalc/calculator_async.py b/src/swgoh_comlink/StatCalc/calculator_async.py index a737d24..8224b2b 100644 --- a/src/swgoh_comlink/StatCalc/calculator_async.py +++ b/src/swgoh_comlink/StatCalc/calculator_async.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import logging from typing import Any @@ -12,11 +13,24 @@ class StatCalcAsync(StatCalc): """Async-capable SWGOH stat calculator. - Inherits all computation methods from :class:`StatCalc`. The only - difference is how game data is fetched during initialization: this - class uses ``httpx.AsyncClient`` instead of the blocking + Game data is fetched with ``httpx.AsyncClient`` instead of the blocking ``httpx.Client``. Both apply the same size cap and SHA-256 check. + Stat calculation is CPU-bound: a full roster takes tens of milliseconds. + Use the ``acalc_*`` methods (:meth:`acalc_char_stats`, + :meth:`acalc_ship_stats`, :meth:`acalc_roster_stats`, + :meth:`acalc_player_stats`) from async code; they run the matching + ``calc_*`` method in a worker thread via :func:`asyncio.to_thread`, so the + event loop keeps running. The inherited synchronous ``calc_*`` methods + still work but block the loop while they run. + + The game data tables are only read during calculation, so concurrent + ``acalc_*`` calls on one instance are safe. Do not call + :meth:`set_game_data` while a calculation is running. Each call updates its + input in place from the worker thread: do not read or change that input + until the call returns. Cancelling the awaiting task does not stop the + thread, which still finishes updating the input. + Because ``__init__`` cannot be ``async``, use the :meth:`create` classmethod factory when game data needs to be fetched from GitHub: @@ -85,6 +99,58 @@ async def create( cls._LOGGER.debug("Using caller-provided game data") return cls(game_data=game_data) + async def acalc_char_stats(self, unit: dict[str, Any]) -> dict[str, Any]: + """Run :meth:`calc_char_stats` in a worker thread. + + Args: + unit: Character object in either normalized (`defId`) or raw game + format (`definitionId`). + + Returns: + The input unit with `stats` and `gp` keys added. + """ + return await asyncio.to_thread(self.calc_char_stats, unit) + + async def acalc_ship_stats(self, unit: dict[str, Any], crew_member: list[dict[str, Any]]) -> dict[str, Any]: + """Run :meth:`calc_ship_stats` in a worker thread. + + Args: + unit: Ship object in either normalized (`defId`) or raw game format. + crew_member: Crew member list for the ship. + + Returns: + The input unit with `stats` and `gp` keys added. + """ + return await asyncio.to_thread(self.calc_ship_stats, unit, crew_member) + + async def acalc_roster_stats(self, units: Any) -> Any: + """Run :meth:`calc_roster_stats` in a worker thread. + + Args: + units: Either a list of units or a legacy dict keyed by unit id. + + Returns: + Input object with `stats` and `gp` fields added for each unit. + """ + return await asyncio.to_thread(self.calc_roster_stats, units) + + async def acalc_player_stats( + self, players: dict[str, Any] | list[dict[str, Any]] + ) -> dict[str, Any] | list[dict[str, Any]]: + """Run :meth:`calc_player_stats` in a worker thread. + + Args: + players: One player object, or a list of player objects, each with a `rosterUnit` element. + + Returns: + The input object with `stats` and `gp` fields added for each player's roster. + + Raises: + RuntimeError: If a dict player is missing a 'rosterUnit' key. + TypeError: If the input object is not a list or dict. + """ + return await asyncio.to_thread(self.calc_player_stats, players) + @classmethod async def _async_fetch_game_data_from_github( cls, url: str | None = None, expected_sha256: str | None = None diff --git a/tests/unit/test_statcalc_async.py b/tests/unit/test_statcalc_async.py index eb2be66..551a80a 100644 --- a/tests/unit/test_statcalc_async.py +++ b/tests/unit/test_statcalc_async.py @@ -2,7 +2,14 @@ from __future__ import annotations +import asyncio +import copy +import gc import inspect +import json +import os +import time +from pathlib import Path from types import ModuleType from typing import Any from unittest.mock import AsyncMock, MagicMock @@ -38,6 +45,128 @@ async def fetch(url: str | None = None, expected_sha256: str | None = None) -> d assert calc._unit_data is game_data["unitData"] +# ── StatCalcAsync off-loop calculation ───────────────────────────────── + +_PLAYER_FILE = Path(__file__).resolve().parent.parent / "resources" / "example-player.json" + +# Ticks requested every 10 ms may run this late while acalc_* computes. A worker thread gives up +# the GIL every sys.getswitchinterval() (5 ms), so a tick normally lands well inside 50 ms. Shared +# CI runners stall for reasons unrelated to the code, so the bound is relaxed there. +_TICK_INTERVAL = 0.01 +_MAX_TICK_LATENESS = 0.25 if os.environ.get("CI") else 0.05 + + +@pytest.fixture(scope="module") +def player() -> dict[str, Any]: + """The 386-unit fixture player. Do not mutate; deep-copy it first.""" + return json.loads(_PLAYER_FILE.read_text()) + + +@pytest.fixture(scope="module") +def calc(game_data: dict[str, Any]) -> StatCalcAsync: + return StatCalcAsync(game_data=game_data) + + +def _def_id(unit: dict[str, Any]) -> str: + return unit["definitionId"].split(":")[0] + + +async def test_acalc_player_stats_matches_sync(calc: StatCalcAsync, player: dict[str, Any]) -> None: + expected = calc.calc_player_stats(copy.deepcopy(player)) + + assert await calc.acalc_player_stats(copy.deepcopy(player)) == expected + + +async def test_acalc_player_stats_accepts_a_list(calc: StatCalcAsync, player: dict[str, Any]) -> None: + players = [copy.deepcopy(player), copy.deepcopy(player)] + + result = await calc.acalc_player_stats(players) + + assert result is players + assert result == [calc.calc_player_stats(copy.deepcopy(player))] * 2 + + +async def test_acalc_roster_stats_matches_sync(calc: StatCalcAsync, player: dict[str, Any]) -> None: + expected = calc.calc_roster_stats(copy.deepcopy(player["rosterUnit"])) + + assert await calc.acalc_roster_stats(copy.deepcopy(player["rosterUnit"])) == expected + + +async def test_acalc_char_stats_matches_sync( + calc: StatCalcAsync, player: dict[str, Any], game_data: dict[str, Any] +) -> None: + unit = next(u for u in player["rosterUnit"] if game_data["unitData"][_def_id(u)]["combatType"] == 1) + expected = calc.calc_char_stats(copy.deepcopy(unit)) + + assert "stats" in expected + assert await calc.acalc_char_stats(copy.deepcopy(unit)) == expected + + +async def test_acalc_ship_stats_matches_sync( + calc: StatCalcAsync, player: dict[str, Any], game_data: dict[str, Any] +) -> None: + roster = calc.calc_player_stats(copy.deepcopy(player))["rosterUnit"] + by_id = {_def_id(u): u for u in roster} + ship, crew = next( + (u, [by_id[c] for c in meta["crew"]]) + for u in roster + if (meta := game_data["unitData"][_def_id(u)])["combatType"] == 2 + and meta["crew"] + and all(c in by_id for c in meta["crew"]) + ) + expected = calc.calc_ship_stats(copy.deepcopy(ship), copy.deepcopy(crew)) + + assert "stats" in expected + assert await calc.acalc_ship_stats(copy.deepcopy(ship), copy.deepcopy(crew)) == expected + + +async def test_acalc_errors_propagate(calc: StatCalcAsync) -> None: + not_a_player: Any = "not a player" + + with pytest.raises(TypeError, match="Expected a list or dict"): + await calc.acalc_player_stats(not_a_player) + + +async def test_calculation_leaves_game_data_unchanged(calc: StatCalcAsync, player: dict[str, Any]) -> None: + """acalc_* share the game data tables across threads, which is safe only while they are read-only.""" + tables = [calc._unit_data, calc._gear_data, calc._mod_set_data, calc._cr_tables, calc._gp_tables, calc._relic_data] + snapshot = json.dumps(tables, sort_keys=True) + + await calc.acalc_player_stats(copy.deepcopy(player)) + + assert json.dumps(tables, sort_keys=True) == snapshot + + +async def test_acalc_player_stats_keeps_the_event_loop_responsive(calc: StatCalcAsync, player: dict[str, Any]) -> None: + # Several rosters so the calculation spans many ticks (tens of ms per roster). + players = [copy.deepcopy(player) for _ in range(6)] + lateness: list[float] = [] + stop = asyncio.Event() + + async def ticker() -> None: + while not stop.is_set(): + due = time.perf_counter() + _TICK_INTERVAL + await asyncio.sleep(_TICK_INTERVAL) + lateness.append(time.perf_counter() - due) + + # A full GC pass holds the GIL; over the whole test session's heap it can stall the loop for + # tens of ms. That is not what this test measures, so keep existing objects out of collection. + gc.collect() + gc.freeze() + task = asyncio.create_task(ticker()) + await asyncio.sleep(0) # let the ticker start before the calculation + try: + await calc.acalc_player_stats(players) + finally: + stop.set() + await task + gc.unfreeze() + + assert any("stats" in u for u in players[-1]["rosterUnit"]) + assert len(lateness) >= 3, "calculation finished before the ticker could measure anything" + assert max(lateness) < _MAX_TICK_LATENESS, f"tick late by {max(lateness) * 1000:.1f} ms" + + # ── GameDataBuilder / GameDataBuilderAsync ───────────────────────────── # # The builders only fetch raw Comlink data and hand it to the shared transform, which From 81623d0d573e1a0e6f2c0c1463d129e9a2c632b2 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:39:25 -0500 Subject: [PATCH 09/47] 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 14b5858f82b51aa824b91f2b9ad122b639c5de84 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:39:52 -0500 Subject: [PATCH 10/47] test(parity): add a repeatable StatCalc benchmark script parity/scripts/bench_statcalc.py loads tests/resources/gameData.json ["data"] and the 386-unit example-player.json, warms up once, then times calc_player_stats over 20 runs (--runs N), each on a fresh deepcopy of the roster made outside the timed section. It prints the median, p95 and min/max in ms with the Python version and platform; --profile adds the top 15 functions by tottime from one extra cProfile run. It finishes in about 1.5 s locally and is deliberately not wired into CI: shared runners are too noisy for timing gates. Refs #244 Co-Authored-By: Claude Opus 5.5 --- parity/scripts/bench_statcalc.py | 88 ++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 parity/scripts/bench_statcalc.py diff --git a/parity/scripts/bench_statcalc.py b/parity/scripts/bench_statcalc.py new file mode 100644 index 0000000..f2c1e49 --- /dev/null +++ b/parity/scripts/bench_statcalc.py @@ -0,0 +1,88 @@ +"""Time StatCalc.calc_player_stats on the committed fixture roster. + +Usage: + + uv run python parity/scripts/bench_statcalc.py [--runs N] [--profile] + +Each timed run works on a fresh ``copy.deepcopy`` of the 386-unit fixture player; the copy is +made outside the timed section. Not wired into CI: shared runners are too noisy for timing gates. +""" + +from __future__ import annotations + +import argparse +import copy +import cProfile +import json +import math +import platform +import pstats +import statistics +import sys +import time +from pathlib import Path +from typing import Any + +from swgoh_comlink import StatCalc + +ROOT = Path(__file__).resolve().parents[2] +GAMEDATA_FILE = ROOT / "tests" / "resources" / "gameData.json" +PLAYER_FILE = ROOT / "tests" / "resources" / "example-player.json" +PROFILE_TOP = 15 + + +def _percentile(samples: list[float], pct: float) -> float: + """Nearest-rank percentile of *samples*.""" + ordered = sorted(samples) + return ordered[max(math.ceil(pct / 100 * len(ordered)) - 1, 0)] + + +def _time_runs(calc: StatCalc, player: dict[str, Any], runs: int) -> list[float]: + """Return the duration of each run in milliseconds, excluding the roster copy.""" + timings: list[float] = [] + for _ in range(runs): + payload = copy.deepcopy(player) + start = time.perf_counter() + calc.calc_player_stats(payload) + timings.append((time.perf_counter() - start) * 1000) + return timings + + +def _profile_run(calc: StatCalc, player: dict[str, Any]) -> None: + payload = copy.deepcopy(player) + profiler = cProfile.Profile() + profiler.runcall(calc.calc_player_stats, payload) + print(f"\nTop {PROFILE_TOP} functions by tottime (one profiled run):") + pstats.Stats(profiler, stream=sys.stdout).strip_dirs().sort_stats(pstats.SortKey.TIME).print_stats(PROFILE_TOP) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--runs", type=int, default=20, help="timed runs (default: 20)") + parser.add_argument("--profile", action="store_true", help=f"also print the top {PROFILE_TOP} functions by tottime") + args = parser.parse_args(argv) + if args.runs < 1: + parser.error("--runs must be at least 1") + + game_data = json.loads(GAMEDATA_FILE.read_text())["data"] + player = json.loads(PLAYER_FILE.read_text()) + calc = StatCalc(game_data=game_data) + + calc.calc_player_stats(copy.deepcopy(player)) # warm-up + timings = _time_runs(calc, player, args.runs) + + print(f"Python: {platform.python_implementation()} {platform.python_version()}") + print(f"Platform: {platform.platform()} ({platform.machine()})") + print(f"Roster: {len(player['rosterUnit'])} units ({PLAYER_FILE.relative_to(ROOT)})") + print(f"Runs: {args.runs} (after 1 warm-up)") + print(f"Median: {statistics.median(timings):.2f} ms") + print(f"p95: {_percentile(timings, 95):.2f} ms") + print(f"Min/max: {min(timings):.2f} / {max(timings):.2f} ms") + + if args.profile: + _profile_run(calc, player) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 8b51989b02639d8005788be4c71d884eba2ca433 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:42:57 -0500 Subject: [PATCH 11/47] 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 36484609918590e828f5354e0045df4594f59d63 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:46:17 -0500 Subject: [PATCH 12/47] perf(statcalc): normalise game data tables to str keys once set_game_data now rebuilds any table holding non-str keys with str keys (copy-on-write, so JSON game data is reused without copying and the caller's dict is never modified). _table_get becomes a single dict.get on str(key), keeping its list branch, and the base and mod stat steps read their str-keyed stat dicts with dict.get directly. Int-keyed game data previously produced different results because the copied stat dicts mixed int and str keys; it now matches JSON game data. Refs #245 Co-Authored-By: Claude Opus 5.5 --- docs/migration.md | 4 + src/swgoh_comlink/StatCalc/calculator.py | 97 +++++++++++++----------- tests/unit/test_statcalc_lookups.py | 65 ++++++++++++++++ 3 files changed, 123 insertions(+), 43 deletions(-) create mode 100644 tests/unit/test_statcalc_lookups.py diff --git a/docs/migration.md b/docs/migration.md index 0ac42ef..88d21db 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -335,6 +335,10 @@ Upgrading from v2.8 to v2.9. `calc_*` method in a worker thread. The sync `calc_*` methods are unchanged but block the loop; in async code, replace `calc.calc_player_stats(p)` with `await calc.acalc_player_stats(p)`. +- **StatCalc reads game data tables by `str` key.** `set_game_data` rebuilds any table + holding non-`str` keys (such as `int` keys from a hand-built dict) with `str` keys, so + it now gives the same results as JSON game data; your dict is not modified. Such a + rebuilt table is a copy: call `set_game_data` again after changing it. ## Summary of changes diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 448b8ad..c89352f 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -39,6 +39,24 @@ def _check_fetch_options( return normalized +def _str_keyed(value: Any) -> Any: + """Return *value* with every nested dict keyed by ``str``, never modifying *value*. + + Containers that already qualify are returned as is, so JSON-parsed game data is used + without copying; only a dict or list holding a non-``str`` key somewhere below it is + rebuilt. + """ + if isinstance(value, dict): + if all(type(k) is str and _str_keyed(v) is v for k, v in value.items()): + return value + return {str(k): _str_keyed(v) for k, v in value.items()} + if isinstance(value, list): + if all(_str_keyed(v) is v for v in value): + return value + return [_str_keyed(v) for v in value] + return value + + class _GameDataDownload: """Collect a streamed game data body, enforcing the size cap and optional SHA-256 check. @@ -150,12 +168,13 @@ def set_game_data(self, game_data: dict[str, Any]) -> None: 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"] + # Lookups use str keys only, so tables with int keys are rebuilt (not modified). + self._unit_data = _str_keyed(game_data["unitData"]) + self._gear_data = _str_keyed(game_data["gearData"]) + self._mod_set_data = _str_keyed(game_data["modSetData"]) + self._cr_tables = _str_keyed(game_data["crTables"]) + self._gp_tables = _str_keyed(game_data["gpTables"]) + self._relic_data = _str_keyed(game_data["relicData"]) self._LOGGER.info( "Game data loaded: units=%d gear=%d mod_sets=%d", len(self._unit_data), @@ -404,16 +423,8 @@ def _table_get(table: Any, key: Any, default: Any = 0) -> Any: if 0 <= idx < len(table): return table[idx] return default - if key in table: - return table[key] - skey = str(key) - if skey in table: - return table[skey] - try: - ikey = int(key) - except (TypeError, ValueError): - return default - return table.get(ikey, default) + # Game data tables are str-keyed by set_game_data; internal stat dicts use str keys too. + return table.get(str(key), default) @staticmethod def _add_stat(stats: dict[str, Any], stat_id: Any, value: float) -> None: @@ -627,50 +638,50 @@ def _calculate_base_stats(self, stats: dict[str, Any], level: int, base_id: str) base = stats["base"] gms = stats["growthModifiers"] - self._add_stat(base, 2, self._floor(self._table_get(gms, 2) * level, 8)) - self._add_stat(base, 3, self._floor(self._table_get(gms, 3) * level, 8)) - self._add_stat(base, 4, self._floor(self._table_get(gms, 4) * level, 8)) + self._add_stat(base, 2, self._floor(gms.get("2", 0) * level, 8)) + self._add_stat(base, 3, self._floor(gms.get("3", 0) * level, 8)) + self._add_stat(base, 4, self._floor(gms.get("4", 0) * level, 8)) ud = self._unit_data[base_id] - if self._table_get(base, 61): + if base.get("61", 0): mms = self._cr_tables.get(ud["masteryModifierID"], {}) for stat_id, value in mms.items(): - self._add_stat(base, stat_id, self._table_get(base, 61) * value) + self._add_stat(base, stat_id, base.get("61", 0) * value) - self._add_stat(base, 1, self._table_get(base, 2) * 18) + self._add_stat(base, 1, base.get("2", 0) * 18) self._add_stat( base, 6, self._floor( - self._table_get(base, 6) + (self._table_get(base, ud["primaryStat"]) * 1.4), + base.get("6", 0) + (base.get(str(ud["primaryStat"]), 0) * 1.4), 8, ) - - self._table_get(base, 6), + - base.get("6", 0), ) self._add_stat( base, 7, - self._floor(self._table_get(base, 7) + (self._table_get(base, 4) * 2.4), 8) - self._table_get(base, 7), + self._floor(base.get("7", 0) + (base.get("4", 0) * 2.4), 8) - base.get("7", 0), ) self._add_stat( base, 8, self._floor( - self._table_get(base, 8) + (self._table_get(base, 2) * 0.14) + (self._table_get(base, 3) * 0.07), + base.get("8", 0) + (base.get("2", 0) * 0.14) + (base.get("3", 0) * 0.07), 8, ) - - self._table_get(base, 8), + - base.get("8", 0), ) self._add_stat( base, 9, - self._floor(self._table_get(base, 9) + (self._table_get(base, 4) * 0.1), 8) - self._table_get(base, 9), + self._floor(base.get("9", 0) + (base.get("4", 0) * 0.1), 8) - base.get("9", 0), ) self._add_stat( base, 14, - self._floor(self._table_get(base, 14) + (self._table_get(base, 3) * 0.4), 8) - self._table_get(base, 14), + self._floor(base.get("14", 0) + (base.get("3", 0) * 0.4), 8) - base.get("14", 0), ) self._add_stat(base, 12, 24 * 1e8) @@ -771,38 +782,38 @@ def _calculate_mod_stats(self, base_stats: dict[str, Any], char: dict[str, Any]) mod_stats, 6, self._floor( - self._table_get(mod_stats, 6) + (self._table_get(base_stats, 6) * 1e-8 * value), + mod_stats.get("6", 0) + (base_stats.get("6", 0) * 1e-8 * value), 8, ) - - self._table_get(mod_stats, 6), + - mod_stats.get("6", 0), ) self._add_stat( mod_stats, 7, self._floor( - self._table_get(mod_stats, 7) + (self._table_get(base_stats, 7) * 1e-8 * value), + mod_stats.get("7", 0) + (base_stats.get("7", 0) * 1e-8 * value), 8, ) - - self._table_get(mod_stats, 7), + - mod_stats.get("7", 0), ) elif stat_id == 49: self._add_stat( mod_stats, 8, self._floor( - self._table_get(mod_stats, 8) + (self._table_get(base_stats, 8) * 1e-8 * value), + mod_stats.get("8", 0) + (base_stats.get("8", 0) * 1e-8 * value), 8, ) - - self._table_get(mod_stats, 8), + - mod_stats.get("8", 0), ) self._add_stat( mod_stats, 9, self._floor( - self._table_get(mod_stats, 9) + (self._table_get(base_stats, 9) * 1e-8 * value), + mod_stats.get("9", 0) + (base_stats.get("9", 0) * 1e-8 * value), 8, ) - - self._table_get(mod_stats, 9), + - mod_stats.get("9", 0), ) elif stat_id == 53: self._add_stat(mod_stats, 21, value) @@ -815,30 +826,30 @@ def _calculate_mod_stats(self, base_stats: dict[str, Any], char: dict[str, Any]) mod_stats, 1, self._floor( - self._table_get(mod_stats, 1) + (self._table_get(base_stats, 1) * 1e-8 * value), + mod_stats.get("1", 0) + (base_stats.get("1", 0) * 1e-8 * value), 8, ) - - self._table_get(mod_stats, 1), + - mod_stats.get("1", 0), ) elif stat_id == 56: self._add_stat( mod_stats, 28, self._floor( - self._table_get(mod_stats, 28) + (self._table_get(base_stats, 28) * 1e-8 * value), + mod_stats.get("28", 0) + (base_stats.get("28", 0) * 1e-8 * value), 8, ) - - self._table_get(mod_stats, 28), + - mod_stats.get("28", 0), ) elif stat_id == 57: self._add_stat( mod_stats, 5, self._floor( - self._table_get(mod_stats, 5) + (self._table_get(base_stats, 5) * 1e-8 * value), + mod_stats.get("5", 0) + (base_stats.get("5", 0) * 1e-8 * value), 8, ) - - self._table_get(mod_stats, 5), + - mod_stats.get("5", 0), ) else: self._add_stat(mod_stats, stat_id_str, value) diff --git a/tests/unit/test_statcalc_lookups.py b/tests/unit/test_statcalc_lookups.py new file mode 100644 index 0000000..19dd329 --- /dev/null +++ b/tests/unit/test_statcalc_lookups.py @@ -0,0 +1,65 @@ +"""StatCalc table lookups and input copying (REF-2). + +The calculator normalises game data tables to ``str`` keys once in ``set_game_data`` and +copies caller units only as deeply as it needs. These tests pin the results and prove the +caller's game data and units are never modified. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path +from typing import Any + +import pytest + +from swgoh_comlink import StatCalc + +_PLAYER_FILE = Path(__file__).resolve().parent.parent / "resources" / "example-player.json" + + +@pytest.fixture(scope="module") +def player() -> dict[str, Any]: + return json.loads(_PLAYER_FILE.read_text()) + + +@pytest.fixture(scope="module") +def calc(game_data: dict[str, Any]) -> StatCalc: + return StatCalc(game_data=game_data) + + +def _int_keyed(value: Any) -> Any: + """Copy of *value* with every digit-only dict key turned into an ``int``.""" + if isinstance(value, dict): + return {int(k) if isinstance(k, str) and k.isdigit() else k: _int_keyed(v) for k, v in value.items()} + if isinstance(value, list): + return [_int_keyed(v) for v in value] + return value + + +class TestGameDataKeys: + def test_int_keyed_tables_are_normalised_to_str_keys(self, game_data): + calc = StatCalc(game_data=_int_keyed(game_data)) + assert calc._gp_tables is not None + assert calc._unit_data is not None + assert all(isinstance(k, str) for k in calc._gp_tables["unitLevelGP"]) + assert all(isinstance(k, str) for k in calc._gp_tables["gearPieceGP"]["1"]) + assert all(isinstance(k, str) for k in calc._unit_data["CINTA"]["growthModifiers"]["7"]) + + def test_int_keyed_game_data_gives_identical_results(self, calc, game_data, player): + expected = calc.calc_player_stats(copy.deepcopy(player)) + actual = StatCalc(game_data=_int_keyed(game_data)).calc_player_stats(copy.deepcopy(player)) + assert actual == expected + + def test_caller_game_data_is_not_modified(self, game_data, player): + int_keyed = _int_keyed(game_data) + snapshot = copy.deepcopy(int_keyed) + StatCalc(game_data=int_keyed).calc_player_stats(copy.deepcopy(player)) + assert int_keyed == snapshot + assert isinstance(next(iter(int_keyed["gpTables"]["unitLevelGP"])), int) + + def test_str_keyed_tables_are_used_without_copying(self, calc, game_data): + # JSON game data already has str keys, so nothing is duplicated in memory. + assert calc._unit_data is game_data["unitData"] + assert calc._gp_tables is game_data["gpTables"] From 0190952e5a5f10ad559109063b8af556367b2359 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:47:17 -0500 Subject: [PATCH 13/47] perf(statcalc): copy normalized units shallowly instead of deep-copying _normalize_char and _normalize_ship_and_crew deep-copied every unit given in the normalized (defId) form. Later steps only set top-level keys (the setdefault defaults and a crew member's "gp") and read nested values, so a shallow dict copy keeps the caller's unit unmodified. New tests prove calc_char_stats, calc_char_gp, calc_ship_stats and calc_ship_gp leave the caller's units unchanged apart from the documented stats and gp keys. Refs #245 Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/StatCalc/calculator.py | 10 ++-- tests/unit/test_statcalc_lookups.py | 67 ++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index c89352f..1b388fe 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -1,6 +1,5 @@ from __future__ import annotations -import copy import hashlib import json import logging @@ -445,7 +444,9 @@ def _normalize_char(self, char: dict[str, Any]) -> dict[str, Any]: "purchasedAbilityId": char.get("purchasedAbilityId", []), } else: - normalized = copy.deepcopy(char) + # Only top-level keys are set below and nested values are only read, so a shallow + # copy keeps the caller's unit unmodified. + normalized = dict(char) normalized.setdefault("equipped", []) normalized.setdefault("skills", []) @@ -482,9 +483,10 @@ def _normalize_ship_and_crew( ) return normalized_ship, normalized_crew - normalized_ship = copy.deepcopy(ship) + # Shallow copies suffice: only top-level keys (defaults, crew "gp") are ever set. + normalized_ship = dict(ship) normalized_ship.setdefault("skills", []) - normalized_crew = [copy.deepcopy(c) for c in crew] + normalized_crew = [dict(c) for c in crew] for c in normalized_crew: c.setdefault("skills", []) c.setdefault("equipped", []) diff --git a/tests/unit/test_statcalc_lookups.py b/tests/unit/test_statcalc_lookups.py index 19dd329..0449381 100644 --- a/tests/unit/test_statcalc_lookups.py +++ b/tests/unit/test_statcalc_lookups.py @@ -17,6 +17,7 @@ from swgoh_comlink import StatCalc _PLAYER_FILE = Path(__file__).resolve().parent.parent / "resources" / "example-player.json" +_RESULT_KEYS = ("stats", "gp") @pytest.fixture(scope="module") @@ -38,6 +39,38 @@ def _int_keyed(value: Any) -> Any: return value +def _def_id(unit: dict[str, Any]) -> str: + return unit["definitionId"].split(":")[0] + + +def _normalized(raw: dict[str, Any]) -> dict[str, Any]: + """The normalized (``defId``) form of a raw Comlink roster unit.""" + return { + "defId": _def_id(raw), + "rarity": raw["currentRarity"], + "level": raw["currentLevel"], + "gear": raw.get("currentTier"), + "equipped": copy.deepcopy(raw.get("equipment", [])), + "relic": copy.deepcopy(raw.get("relic")), + "skills": [{"id": s["id"], "tier": s["tier"] + 2} for s in raw.get("skill", [])], + "purchasedAbilityId": list(raw.get("purchasedAbilityId", [])), + "equippedStatMod": copy.deepcopy(raw.get("equippedStatMod")), + } + + +def _without_results(unit: dict[str, Any]) -> dict[str, Any]: + return {k: v for k, v in unit.items() if k not in _RESULT_KEYS} + + +def _crewed_ship(game_data: dict[str, Any], player: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]: + roster = {_def_id(u): u for u in player["rosterUnit"]} + for def_id, unit in roster.items(): + meta = game_data["unitData"].get(def_id, {}) + if meta.get("combatType") == 2 and meta.get("crew") and all(c in roster for c in meta["crew"]): + return copy.deepcopy(unit), [copy.deepcopy(roster[c]) for c in meta["crew"]] + raise AssertionError("fixture roster has no fully crewed ship") + + class TestGameDataKeys: def test_int_keyed_tables_are_normalised_to_str_keys(self, game_data): calc = StatCalc(game_data=_int_keyed(game_data)) @@ -63,3 +96,37 @@ def test_str_keyed_tables_are_used_without_copying(self, calc, game_data): # JSON game data already has str keys, so nothing is duplicated in memory. assert calc._unit_data is game_data["unitData"] assert calc._gp_tables is game_data["gpTables"] + + +class TestCallerUnitsUnchanged: + def test_calc_char_stats_only_adds_results(self, calc, player): + char = _normalized(player["rosterUnit"][0]) + snapshot = copy.deepcopy(char) + calc.calc_char_stats(char) + assert _without_results(char) == snapshot + assert set(char) - set(snapshot) == set(_RESULT_KEYS) + + def test_calc_char_gp_leaves_unit_unchanged(self, calc, player): + char = _normalized(player["rosterUnit"][0]) + char.pop("equipped") # setdefault() on the copy must not reach the caller + snapshot = copy.deepcopy(char) + calc.calc_char_gp(char) + assert char == snapshot + + def test_calc_ship_stats_only_adds_results(self, calc, game_data, player): + raw_ship, raw_crew = _crewed_ship(game_data, player) + crew = [_normalized(c) for c in raw_crew] + for member, raw in zip(crew, raw_crew, strict=True): + member["gp"] = calc.calc_char_gp(raw) + ship = _normalized(raw_ship) + ship_snapshot, crew_snapshot = copy.deepcopy(ship), copy.deepcopy(crew) + calc.calc_ship_stats(ship, crew) + assert _without_results(ship) == ship_snapshot + assert crew == crew_snapshot + + def test_calc_ship_gp_leaves_ship_and_crew_unchanged(self, calc, game_data, player): + raw_ship, raw_crew = _crewed_ship(game_data, player) + ship, crew = _normalized(raw_ship), [_normalized(c) for c in raw_crew] + ship_snapshot, crew_snapshot = copy.deepcopy(ship), copy.deepcopy(crew) + calc.calc_ship_gp(ship, crew) + assert (ship, crew) == (ship_snapshot, crew_snapshot) From d228fa110e7854cb138f4adba0e752f606ddf16b Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:48:29 -0500 Subject: [PATCH 14/47] perf(statcalc): index each unit's skills by id in set_game_data _get_skill_gp and _get_crewless_skills_gp scanned the unit's skill list for every skill. set_game_data now builds a per-unit {skill id: skill definition} index (first definition of an id wins, as the scan did) and both functions look skills up through _find_skill_def. A unit with no skill list falls back to the old scan, so an unknown unit still raises KeyError. Refs #245 Co-Authored-By: Claude Opus 5.5 --- docs/migration.md | 3 +- src/swgoh_comlink/StatCalc/calculator.py | 29 ++++++++++++++------ tests/unit/test_statcalc_lookups.py | 35 ++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/docs/migration.md b/docs/migration.md index 88d21db..d0ef763 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -338,7 +338,8 @@ Upgrading from v2.8 to v2.9. - **StatCalc reads game data tables by `str` key.** `set_game_data` rebuilds any table holding non-`str` keys (such as `int` keys from a hand-built dict) with `str` keys, so it now gives the same results as JSON game data; your dict is not modified. Such a - rebuilt table is a copy: call `set_game_data` again after changing it. + rebuilt table is a copy: call `set_game_data` again after changing it. The same applies + to a unit's `skills` list, which `set_game_data` indexes by skill id. ## Summary of changes diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 1b388fe..82ae81d 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -145,6 +145,7 @@ def __init__( self._cr_tables: dict[str, Any] | None = None self._gp_tables: dict[str, Any] | None = None self._relic_data: dict[str, Any] | None = None + self._skill_index: dict[str, dict[Any, dict[str, Any]]] = {} if game_data is None: self._LOGGER.info("No game data provided, loading from GitHub") @@ -174,6 +175,12 @@ def set_game_data(self, game_data: dict[str, Any]) -> None: self._cr_tables = _str_keyed(game_data["crTables"]) self._gp_tables = _str_keyed(game_data["gpTables"]) self._relic_data = _str_keyed(game_data["relicData"]) + # Per-unit {skill id: skill definition}; reversed so the first definition of an id wins. + self._skill_index = { + unit_id: {skill["id"]: skill for skill in reversed(meta["skills"]) if "id" in skill} + for unit_id, meta in self._unit_data.items() + if isinstance(meta, dict) and isinstance(meta.get("skills"), list) + } self._LOGGER.info( "Game data loaded: units=%d gear=%d mod_sets=%d", len(self._unit_data), @@ -1115,10 +1122,7 @@ def _resolve_gear_slots(self, char: dict[str, Any]) -> list[Any]: def _get_skill_gp(self, unit_id: str, skill: dict[str, Any]) -> float: 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, - ) + skill_def = self._find_skill_def(unit_id, skill["id"]) if not skill_def: return 0 power_override = self._table_get(skill_def.get("powerOverrideTags", {}), skill["tier"], None) @@ -1128,6 +1132,18 @@ def _get_skill_gp(self, unit_id: str, skill: dict[str, Any]) -> float: gp_value = self._table_get(self._gp_tables["abilityLevelGP"], skill["tier"], 0) return gp_value + def _find_skill_def(self, unit_id: str, skill_id: Any) -> dict[str, Any] | None: + """Return the unit's first skill definition with *skill_id*, or None. + + Raises: + KeyError: *unit_id* is not in the game data, or its entry has no skill list. + """ + index = self._skill_index.get(unit_id) + if index is not None: + return index.get(skill_id) + assert self._unit_data is not None # type narrowing: set_game_data() set it; _require_game_data() ran + return next((s for s in self._unit_data[unit_id]["skills"] if s["id"] == skill_id), None) + def _calc_ship_gp(self, ship: dict[str, Any], crew: list[dict[str, Any]] | None = None) -> int: 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 @@ -1167,10 +1183,7 @@ def _get_crewless_skills_gp(self, unit_id: str, skills: list[dict[str, Any]]) -> reinforcement = 0.0 for skill in skills: - skill_def = next( - (s for s in self._unit_data[unit_id]["skills"] if s["id"] == skill["id"]), - None, - ) + skill_def = self._find_skill_def(unit_id, skill["id"]) if not skill_def: continue o_tag = self._table_get(skill_def.get("powerOverrideTags", {}), skill["tier"], None) diff --git a/tests/unit/test_statcalc_lookups.py b/tests/unit/test_statcalc_lookups.py index 0449381..132acb5 100644 --- a/tests/unit/test_statcalc_lookups.py +++ b/tests/unit/test_statcalc_lookups.py @@ -130,3 +130,38 @@ def test_calc_ship_gp_leaves_ship_and_crew_unchanged(self, calc, game_data, play ship_snapshot, crew_snapshot = copy.deepcopy(ship), copy.deepcopy(crew) calc.calc_ship_gp(ship, crew) assert (ship, crew) == (ship_snapshot, crew_snapshot) + + +class TestSkillLookup: + _UNIT = "CINTA" + + @staticmethod + def _with_skill(game_data: dict[str, Any], unit_id: str, skill: dict[str, Any]) -> dict[str, Any]: + data = copy.deepcopy(game_data) + data["unitData"][unit_id]["skills"].append(skill) + return data + + def test_first_matching_skill_definition_wins(self, calc, game_data): + first = game_data["unitData"][self._UNIT]["skills"][0] + shadow = {**first, "powerOverrideTags": {"8": "ultimate"}} + shadowed = StatCalc(game_data=self._with_skill(game_data, self._UNIT, shadow)) + skill = {"id": first["id"], "tier": 8} + assert shadowed._get_skill_gp(self._UNIT, skill) == calc._get_skill_gp(self._UNIT, skill) + assert shadowed._get_crewless_skills_gp(self._UNIT, [skill]) == calc._get_crewless_skills_gp( + self._UNIT, [skill] + ) + + def test_set_game_data_replaces_the_skill_definitions(self, game_data): + extra = {"id": "extra_skill", "maxTier": 8, "powerOverrideTags": {"8": "ultimate"}} + calc = StatCalc(game_data=game_data) + skill = {"id": "extra_skill", "tier": 8} + assert calc._get_skill_gp(self._UNIT, skill) == 0 + calc.set_game_data(self._with_skill(game_data, self._UNIT, extra)) + assert calc._get_skill_gp(self._UNIT, skill) == game_data["gpTables"]["abilitySpecialGP"]["ultimate"] > 0 + assert calc._get_crewless_skills_gp(self._UNIT, [skill])["ability"] > 0 + + def test_unknown_unit_still_raises_key_error(self, calc): + with pytest.raises(KeyError): + calc._get_skill_gp("NONEXISTENT_UNIT_XYZ", {"id": "x", "tier": 1}) + with pytest.raises(KeyError): + calc._get_crewless_skills_gp("NONEXISTENT_UNIT_XYZ", [{"id": "x", "tier": 1}]) From 07b3db2226b7d0f72d89161369fa25afe3797677 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:51:06 -0500 Subject: [PATCH 15/47] 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 From ae35c6db0f05c98c61ffdfa672fcdbaa0f33e87e Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 08:51:09 -0500 Subject: [PATCH 16/47] perf(statcalc): drop key-list copies and probing lookups in _format_stats The rounding and scaling loops only replace values of existing keys, so they iterate dict.items() instead of copying the keys first. The final stat id list becomes an insertion-ordered dict (same first-seen order, O(1) membership instead of a list scan), and _format_stats and _convert_percent read their str-keyed stat dicts with dict.get. New tests pin the order and sums of the formatted final stats for a character and a ship. Refs #245 Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/StatCalc/calculator.py | 93 ++++++++++++------------ tests/unit/test_statcalc_lookups.py | 24 ++++++ 2 files changed, 69 insertions(+), 48 deletions(-) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 82ae81d..2b2ce3d 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -874,22 +874,19 @@ def _scale_mod_stat_value(stat_id: int, value: float) -> float: def _format_stats(self, stats: dict[str, Any], level: int) -> dict[str, Any]: scale = 1e-8 - if stats.get("mods"): - for stat_id in list(stats["mods"].keys()): - stats["mods"][stat_id] = round(stats["mods"][stat_id]) + # Each loop only replaces values of existing keys, so it can iterate the dict itself. + mods = stats.get("mods") + if mods: + for stat_id, value in mods.items(): + mods[stat_id] = round(value) if scale != 1: - for stat_id in list(stats["base"].keys()): - stats["base"][stat_id] *= scale - for stat_id in list(stats.get("gear", {}).keys()): - stats["gear"][stat_id] *= scale - for stat_id in list(stats.get("crew", {}).keys()): - stats["crew"][stat_id] *= scale - for stat_id in list(stats["growthModifiers"].keys()): - stats["growthModifiers"][stat_id] *= scale - if stats.get("mods"): - for stat_id in list(stats["mods"].keys()): - stats["mods"][stat_id] *= scale + for table in (stats["base"], stats.get("gear", {}), stats.get("crew", {}), stats["growthModifiers"]): + for stat_id, value in table.items(): + table[stat_id] = value * scale + if mods: + for stat_id, value in mods.items(): + mods[stat_id] = value * scale if self._FIXED_PERCENT_VALS or self._FIXED_GAME_STYLE: self._convert_percent( @@ -954,23 +951,23 @@ def _format_stats(self, stats: dict[str, Any], level: int) -> dict[str, Any]: ) if self._FIXED_GAME_STYLE: - gs_stats: dict[str, Any] = {"final": {}} + final: dict[str, Any] = {} + gs_stats: dict[str, Any] = {"final": final} + base = stats["base"] - stat_list = list(stats["base"].keys()) - - def add_stat_id(sid: str) -> None: - if sid not in stat_list: - stat_list.append(sid) + # Stat ids in first-seen order: a dict is an insertion-ordered set with O(1) lookups. + stat_ids = dict.fromkeys(base) if "gear" in stats: - for sid in stats["gear"].keys(): - add_stat_id(sid) - if "mods" in stats: - for sid in stats["mods"].keys(): - add_stat_id(sid) + gear = stats["gear"] + stat_ids |= dict.fromkeys(gear) + has_mods = "mods" in stats + mod_values: dict[str, Any] = (stats["mods"] or {}) if has_mods else {} + if has_mods: + stat_ids |= dict.fromkeys(stats["mods"]) gs_stats["mods"] = stats["mods"] - for stat_id in stat_list: + for stat_id in stat_ids: stat_int = int(stat_id) flat_stat_id = stat_int if stat_int in {21, 22}: @@ -979,20 +976,16 @@ def add_stat_id(sid: str) -> None: flat_stat_id = stat_int + 4 key = str(flat_stat_id) - gs_stats["final"][key] = gs_stats["final"].get(key, 0) + ( - self._table_get(stats["base"], stat_id) - + self._table_get(stats["gear"], stat_id) - + (self._table_get(stats["mods"], stat_id) if "mods" in stats else 0) + final[key] = final.get(key, 0) + ( + base.get(stat_id, 0) + gear.get(stat_id, 0) + (mod_values.get(stat_id, 0) if has_mods else 0) ) else: - for sid in stats.get("crew", {}).keys(): - add_stat_id(sid) - gs_stats["crew"] = stats.get("crew", {}) + crew = stats.get("crew", {}) + stat_ids |= dict.fromkeys(crew) + gs_stats["crew"] = crew - for stat_id in stat_list: - gs_stats["final"][str(stat_id)] = self._table_get(stats["base"], stat_id) + self._table_get( - stats["crew"], stat_id - ) + for stat_id in stat_ids: + final[str(stat_id)] = base.get(stat_id, 0) + crew.get(stat_id, 0) stats = gs_stats @@ -1020,24 +1013,28 @@ def _convert_percent( ) -> None: del level sid = str(stat_id) - flat = self._table_get(stats["base"], sid) + base = stats["base"] + flat = base.get(sid, 0) percent = convert_func(flat) - stats["base"][sid] = percent + base[sid] = percent last = percent if "crew" in stats: - if self._table_get(stats["crew"], sid): - flat = flat + self._table_get(stats["crew"], sid) - stats["crew"][sid] = convert_func(flat) - last + crew = stats["crew"] + if crew and (crew_value := crew.get(sid, 0)): + flat = flat + crew_value + crew[sid] = convert_func(flat) - last else: - if "gear" in stats and self._table_get(stats["gear"], sid): - flat = flat + self._table_get(stats["gear"], sid) + gear = stats.get("gear") + if gear and (gear_value := gear.get(sid, 0)): + flat = flat + gear_value percent = convert_func(flat) - stats["gear"][sid] = percent - last + gear[sid] = percent - last last = percent - if "mods" in stats and self._table_get(stats["mods"], sid): - flat = flat + self._table_get(stats["mods"], sid) - stats["mods"][sid] = convert_func(flat) - last + mods = stats.get("mods") + if mods and (mod_value := mods.get(sid, 0)): + flat = flat + mod_value + mods[sid] = convert_func(flat) - last def _calc_char_gp(self, char: dict[str, Any]) -> int: assert self._gp_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran diff --git a/tests/unit/test_statcalc_lookups.py b/tests/unit/test_statcalc_lookups.py index 132acb5..23de7c6 100644 --- a/tests/unit/test_statcalc_lookups.py +++ b/tests/unit/test_statcalc_lookups.py @@ -165,3 +165,27 @@ def test_unknown_unit_still_raises_key_error(self, calc): calc._get_skill_gp("NONEXISTENT_UNIT_XYZ", {"id": "x", "tier": 1}) with pytest.raises(KeyError): calc._get_crewless_skills_gp("NONEXISTENT_UNIT_XYZ", [{"id": "x", "tier": 1}]) + + +class TestFormatStats: + def test_final_stats_keep_first_seen_order_and_sum_every_source(self, calc): + mods = {"35": 4e8} + stats = { + "base": {"1": 1e8, "21": 2e8}, + "growthModifiers": {"2": 1e8}, + "gear": {"5": 3e8, "1": 1e8}, + "mods": mods, + } + result = calc._format_stats(stats, 85) + # base ids (21 folds into 14, then the converted percent stats), then gear-only, then mods-only (35 -> 39) + assert list(result["final"]) == ["1", "14", "15", "8", "9", "37", "38", "12", "13", "39", "40", "5"] + assert (result["final"]["1"], result["final"]["5"]) == (2.0, 3.0) + assert result["mods"] is mods + assert mods["35"] == 4.0 + + def test_ship_final_stats_add_crew(self, calc): + stats = {"base": {"1": 1e8}, "growthModifiers": {}, "crew": {"1": 2e8, "5": 3e8}} + result = calc._format_stats(stats, 85) + assert result["crew"] is stats["crew"] + assert (result["final"]["1"], result["final"]["5"]) == (3.0, 3.0) + assert list(result["final"])[-1] == "5" From 1a715447ecfc18ba4774e3dcf7b0d98240447c0c Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 09:27:37 -0500 Subject: [PATCH 17/47] perf(statcalc): map mod stat ids to their target stats with lookup tables _calculate_mod_stats converted the summed mod stats with an eleven-branch if/elif chain that called _add_stat (and its str() key conversion) for every target. Two module-level tables now name the target stats of the split stats (41, 42, 53, 54) and the percent-of-base stats (48, 49, 55-57), and the loop updates the str-keyed dict directly. The arithmetic, the order targets are updated in, and the key insertion order are unchanged, so the output is identical. Refs #245 Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/StatCalc/calculator.py | 107 ++++++----------------- 1 file changed, 26 insertions(+), 81 deletions(-) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 2b2ce3d..d331653 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -19,6 +19,23 @@ _SHA256_HEX = re.compile(r"[0-9a-f]{64}") +# Mod stats that add their value to each of several stats (e.g. 41, Offense, adds to 6 and 7). +_MOD_STAT_SPLITS: dict[int, tuple[str, ...]] = { + 41: ("6", "7"), + 42: ("8", "9"), + 53: ("21", "22"), + 54: ("35", "36"), +} +# Percent mod stats that add a share of the unit's base stat to each target stat, floored to 8 digits. +_MOD_STAT_PERCENT_OF_BASE: dict[int, tuple[str, ...]] = { + 48: ("6", "7"), + 49: ("8", "9"), + 55: ("1",), + 56: ("28",), + 57: ("5",), +} + + def _check_fetch_options( game_data: dict[str, Any] | None, game_data_url: str | None, expected_sha256: str | None ) -> str | None: @@ -780,88 +797,16 @@ def _calculate_mod_stats(self, base_stats: dict[str, Any], char: dict[str, Any]) mod_stats: dict[str, float] = {} for stat_id_str, value in raw_mod_stats.items(): stat_id = int(stat_id_str) - if stat_id == 41: - self._add_stat(mod_stats, 6, value) - self._add_stat(mod_stats, 7, value) - elif stat_id == 42: - self._add_stat(mod_stats, 8, value) - self._add_stat(mod_stats, 9, value) - elif stat_id == 48: - self._add_stat( - mod_stats, - 6, - self._floor( - mod_stats.get("6", 0) + (base_stats.get("6", 0) * 1e-8 * value), - 8, - ) - - mod_stats.get("6", 0), - ) - self._add_stat( - mod_stats, - 7, - self._floor( - mod_stats.get("7", 0) + (base_stats.get("7", 0) * 1e-8 * value), - 8, - ) - - mod_stats.get("7", 0), - ) - elif stat_id == 49: - self._add_stat( - mod_stats, - 8, - self._floor( - mod_stats.get("8", 0) + (base_stats.get("8", 0) * 1e-8 * value), - 8, - ) - - mod_stats.get("8", 0), - ) - self._add_stat( - mod_stats, - 9, - self._floor( - mod_stats.get("9", 0) + (base_stats.get("9", 0) * 1e-8 * value), - 8, - ) - - mod_stats.get("9", 0), - ) - elif stat_id == 53: - self._add_stat(mod_stats, 21, value) - self._add_stat(mod_stats, 22, value) - elif stat_id == 54: - self._add_stat(mod_stats, 35, value) - self._add_stat(mod_stats, 36, value) - elif stat_id == 55: - self._add_stat( - mod_stats, - 1, - self._floor( - mod_stats.get("1", 0) + (base_stats.get("1", 0) * 1e-8 * value), - 8, - ) - - mod_stats.get("1", 0), - ) - elif stat_id == 56: - self._add_stat( - mod_stats, - 28, - self._floor( - mod_stats.get("28", 0) + (base_stats.get("28", 0) * 1e-8 * value), - 8, - ) - - mod_stats.get("28", 0), - ) - elif stat_id == 57: - self._add_stat( - mod_stats, - 5, - self._floor( - mod_stats.get("5", 0) + (base_stats.get("5", 0) * 1e-8 * value), - 8, - ) - - mod_stats.get("5", 0), - ) + if (targets := _MOD_STAT_SPLITS.get(stat_id)) is not None: + for target in targets: + mod_stats[target] = mod_stats.get(target, 0) + value + elif (targets := _MOD_STAT_PERCENT_OF_BASE.get(stat_id)) is not None: + for target in targets: + current = mod_stats.get(target, 0) + increase = self._floor(current + (base_stats.get(target, 0) * 1e-8 * value), 8) - current + mod_stats[target] = current + increase else: - self._add_stat(mod_stats, stat_id_str, value) + mod_stats[stat_id_str] = mod_stats.get(stat_id_str, 0) + value return mod_stats From d8b5b07b7d902654d7e716cdf12f1efc631f61fa Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 09:29:23 -0500 Subject: [PATCH 18/47] perf(statcalc): fold final stat ids by lookup and loop the percent conversions _format_stats built each character's final stats by turning every stat id into an int and back into a str to fold 21/22 into 14/15 and 35/36 into 39/40. A small str-keyed table now gives the folded id directly; the stat ids are already str (game data tables are str-keyed and the calculator's own stat dicts use str keys), so the keys are unchanged. The ten _convert_percent calls become one loop over (stat id, converter) pairs. The converters are defined once per call instead of as ten lambdas, and _convert_percent takes the str id directly. Output is byte-identical for raw, normalized, normalized-with-mods and legacy dict rosters. Refs #245 Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/StatCalc/calculator.py | 123 ++++++++--------------- 1 file changed, 41 insertions(+), 82 deletions(-) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index d331653..b8b5cee 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -5,6 +5,7 @@ import logging import math import re +from collections.abc import Callable from typing import Any import httpx @@ -35,6 +36,10 @@ 57: ("5",), } +# Character stat ids whose final value is added to another stat (Physical and Special Critical +# Chance to Critical Rating, Physical and Special Critical Avoidance to Critical Avoidance Rating). +_FLAT_STAT_IDS: dict[str, str] = {"21": "14", "22": "15", "35": "39", "36": "40"} + def _check_fetch_options( game_data: dict[str, Any] | None, game_data_url: str | None, expected_sha256: str | None @@ -834,66 +839,34 @@ def _format_stats(self, stats: dict[str, Any], level: int) -> dict[str, Any]: mods[stat_id] = value * scale if self._FIXED_PERCENT_VALS or self._FIXED_GAME_STYLE: - self._convert_percent( - stats, - 14, - lambda val: self._convert_flat_crit_to_percent(val, scale * 1e8), - level, - ) - self._convert_percent( - stats, - 15, - lambda val: self._convert_flat_crit_to_percent(val, scale * 1e8), - level, - ) - self._convert_percent( - stats, - 8, - lambda val: self._convert_flat_def_to_percent(val, level, scale * 1e8, "crew" in stats), - level, - ) - self._convert_percent( - stats, - 9, - lambda val: self._convert_flat_def_to_percent(val, level, scale * 1e8, "crew" in stats), - level, - ) - self._convert_percent( - stats, - 37, - lambda val: self._convert_flat_acc_to_percent(val, scale * 1e8), - level, - ) - self._convert_percent( - stats, - 38, - lambda val: self._convert_flat_acc_to_percent(val, scale * 1e8), - level, - ) - self._convert_percent( - stats, - 12, - lambda val: self._convert_flat_acc_to_percent(val, scale * 1e8), - level, - ) - self._convert_percent( - stats, - 13, - lambda val: self._convert_flat_acc_to_percent(val, scale * 1e8), - level, - ) - self._convert_percent( - stats, - 39, - lambda val: self._convert_flat_crit_avoid_to_percent(val, scale * 1e8), - level, - ) - self._convert_percent( - stats, - 40, - lambda val: self._convert_flat_crit_avoid_to_percent(val, scale * 1e8), - level, - ) + percent_scale = scale * 1e8 + is_ship = "crew" in stats + + def crit(val: float) -> float: + return self._convert_flat_crit_to_percent(val, percent_scale) + + def defense(val: float) -> float: + return self._convert_flat_def_to_percent(val, level, percent_scale, is_ship) + + def accuracy(val: float) -> float: + return self._convert_flat_acc_to_percent(val, percent_scale) + + def crit_avoidance(val: float) -> float: + return self._convert_flat_crit_avoid_to_percent(val, percent_scale) + + for stat_id, convert in ( + ("14", crit), + ("15", crit), + ("8", defense), + ("9", defense), + ("37", accuracy), + ("38", accuracy), + ("12", accuracy), + ("13", accuracy), + ("39", crit_avoidance), + ("40", crit_avoidance), + ): + self._convert_percent(stats, stat_id, convert) if self._FIXED_GAME_STYLE: final: dict[str, Any] = {} @@ -906,23 +879,16 @@ def _format_stats(self, stats: dict[str, Any], level: int) -> dict[str, Any]: if "gear" in stats: gear = stats["gear"] stat_ids |= dict.fromkeys(gear) - has_mods = "mods" in stats - mod_values: dict[str, Any] = (stats["mods"] or {}) if has_mods else {} - if has_mods: + mod_values: dict[str, Any] = {} + if "mods" in stats: + mod_values = stats["mods"] or {} stat_ids |= dict.fromkeys(stats["mods"]) gs_stats["mods"] = stats["mods"] for stat_id in stat_ids: - stat_int = int(stat_id) - flat_stat_id = stat_int - if stat_int in {21, 22}: - flat_stat_id = stat_int - 7 - elif stat_int in {35, 36}: - flat_stat_id = stat_int + 4 - - key = str(flat_stat_id) + key = _FLAT_STAT_IDS.get(stat_id, stat_id) final[key] = final.get(key, 0) + ( - base.get(stat_id, 0) + gear.get(stat_id, 0) + (mod_values.get(stat_id, 0) if has_mods else 0) + base.get(stat_id, 0) + gear.get(stat_id, 0) + mod_values.get(stat_id, 0) ) else: crew = stats.get("crew", {}) @@ -930,7 +896,7 @@ def _format_stats(self, stats: dict[str, Any], level: int) -> dict[str, Any]: gs_stats["crew"] = crew for stat_id in stat_ids: - final[str(stat_id)] = base.get(stat_id, 0) + crew.get(stat_id, 0) + final[stat_id] = base.get(stat_id, 0) + crew.get(stat_id, 0) stats = gs_stats @@ -949,15 +915,8 @@ def _rename_stats(self, stats: dict[str, Any], lang: str = "eng_us") -> dict[str self._LOGGER.debug("Done renaming stats") return rn_stats - def _convert_percent( - self, - stats: dict[str, Any], - stat_id: int, - convert_func: Any, - level: int, - ) -> None: - del level - sid = str(stat_id) + @staticmethod + def _convert_percent(stats: dict[str, Any], sid: str, convert_func: Callable[[float], float]) -> None: base = stats["base"] flat = base.get(sid, 0) percent = convert_func(flat) From 1f81a805f2a8e19ee99152db3a5e7cf03bc674cc Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 09:37:29 -0500 Subject: [PATCH 19/47] perf(statcalc): run all percent conversions in one _convert_percent call _format_stats called _convert_percent ten times per unit, and each call looked up the base, crew, gear and mods dicts again. _convert_percent now takes the (stat id, converter) pairs and loops over them itself, looking the dicts up once. The conversions only update those dicts in place, so the order and arithmetic are unchanged; a ship is still recognised by its "crew" key, whatever its value. Refs #245 Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/StatCalc/calculator.py | 67 ++++++++++++++---------- 1 file changed, 39 insertions(+), 28 deletions(-) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index b8b5cee..21df5bc 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -5,7 +5,7 @@ import logging import math import re -from collections.abc import Callable +from collections.abc import Callable, Iterable from typing import Any import httpx @@ -854,19 +854,21 @@ def accuracy(val: float) -> float: def crit_avoidance(val: float) -> float: return self._convert_flat_crit_avoid_to_percent(val, percent_scale) - for stat_id, convert in ( - ("14", crit), - ("15", crit), - ("8", defense), - ("9", defense), - ("37", accuracy), - ("38", accuracy), - ("12", accuracy), - ("13", accuracy), - ("39", crit_avoidance), - ("40", crit_avoidance), - ): - self._convert_percent(stats, stat_id, convert) + self._convert_percent( + stats, + ( + ("14", crit), + ("15", crit), + ("8", defense), + ("9", defense), + ("37", accuracy), + ("38", accuracy), + ("12", accuracy), + ("13", accuracy), + ("39", crit_avoidance), + ("40", crit_avoidance), + ), + ) if self._FIXED_GAME_STYLE: final: dict[str, Any] = {} @@ -916,26 +918,35 @@ def _rename_stats(self, stats: dict[str, Any], lang: str = "eng_us") -> dict[str return rn_stats @staticmethod - def _convert_percent(stats: dict[str, Any], sid: str, convert_func: Callable[[float], float]) -> None: + def _convert_percent(stats: dict[str, Any], conversions: Iterable[tuple[str, Callable[[float], float]]]) -> None: + """Convert each flat stat to a percent with its converter, in order. + + The base value becomes the percent of the base flat value. A ship's crew value, or a + character's gear and then mods value, becomes the percent it adds on top of the + values before it. + """ + # The stat dicts are only updated in place, so they are looked up once for all conversions. base = stats["base"] - flat = base.get(sid, 0) - percent = convert_func(flat) - base[sid] = percent - last = percent - - if "crew" in stats: - crew = stats["crew"] - if crew and (crew_value := crew.get(sid, 0)): - flat = flat + crew_value - crew[sid] = convert_func(flat) - last - else: - gear = stats.get("gear") + is_ship = "crew" in stats + crew = stats.get("crew") + gear = stats.get("gear") + mods = stats.get("mods") + for sid, convert_func in conversions: + flat = base.get(sid, 0) + percent = convert_func(flat) + base[sid] = percent + last = percent + + if is_ship: + if crew and (crew_value := crew.get(sid, 0)): + flat = flat + crew_value + crew[sid] = convert_func(flat) - last + continue if gear and (gear_value := gear.get(sid, 0)): flat = flat + gear_value percent = convert_func(flat) gear[sid] = percent - last last = percent - mods = stats.get("mods") if mods and (mod_value := mods.get(sid, 0)): flat = flat + mod_value mods[sid] = convert_func(flat) - last From e02f7fbb9c4006e43f7d7e401d2dd7c3a9b95770 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 09:39:48 -0500 Subject: [PATCH 20/47] perf(statcalc): key the summed raw mod stats by int stat id _calculate_mod_stats summed each mod stat under str(stat id) and then turned every key back into an int to pick its conversion. The raw sums are now keyed by int(stat id), which the conversion uses directly; only stats that keep their own id are turned into a str key, once each. Comlink stat ids and the mod set ids in game data are ints, so the same stats are summed together, in the same order, and the output is byte-identical for raw, normalized, normalized-with-mods and legacy dict rosters. Refs #245 Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/StatCalc/calculator.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 21df5bc..06d64d3 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -731,7 +731,8 @@ def _calculate_mod_stats(self, base_stats: dict[str, Any], char: dict[str, Any]) return {} set_bonuses: dict[int, dict[str, int]] = {} - raw_mod_stats: dict[str, float] = {} + # Keyed by int stat id; converted to the str-keyed mod stats below. + raw_mod_stats: dict[int, float] = {} if char.get("mods"): for mod in char["mods"]: @@ -751,16 +752,15 @@ def _calculate_mod_stats(self, base_stats: dict[str, Any], char: dict[str, Any]) if mod.get("stat"): for stat in mod["stat"]: sid, sval = stat - key = str(sid) - raw_mod_stats[key] = raw_mod_stats.get(key, 0) + self._scale_mod_stat_value(sid, sval) + key = int(sid) + raw_mod_stats[key] = raw_mod_stats.get(key, 0) + self._scale_mod_stat_value(key, sval) else: stat = mod.get("primaryStat") secondary = mod.get("secondaryStat", []) i = 0 while stat: - sid = stat["unitStat"] - key = str(sid) - raw_mod_stats[key] = raw_mod_stats.get(key, 0) + self._scale_mod_stat_value(sid, stat["value"]) + key = int(stat["unitStat"]) + raw_mod_stats[key] = raw_mod_stats.get(key, 0) + self._scale_mod_stat_value(key, stat["value"]) if i >= len(secondary): break stat = secondary[i] @@ -783,8 +783,7 @@ def _calculate_mod_stats(self, base_stats: dict[str, Any], char: dict[str, Any]) secondary = mod.get("secondaryStat", []) i = 0 while stat: - sid = stat["unitStatId"] - key = str(sid) + key = int(stat["unitStatId"]) raw_mod_stats[key] = raw_mod_stats.get(key, 0) + float(stat["unscaledDecimalValue"]) if i >= len(secondary): break @@ -796,12 +795,11 @@ def _calculate_mod_stats(self, base_stats: dict[str, Any], char: dict[str, Any]) if not set_def: continue multiplier = (bonus["count"] // set_def["count"]) + (bonus["maxLevel"] // set_def["count"]) - key = str(set_def["id"]) + key = int(set_def["id"]) raw_mod_stats[key] = raw_mod_stats.get(key, 0) + (set_def["value"] * multiplier) mod_stats: dict[str, float] = {} - for stat_id_str, value in raw_mod_stats.items(): - stat_id = int(stat_id_str) + for stat_id, value in raw_mod_stats.items(): if (targets := _MOD_STAT_SPLITS.get(stat_id)) is not None: for target in targets: mod_stats[target] = mod_stats.get(target, 0) + value @@ -811,7 +809,8 @@ def _calculate_mod_stats(self, base_stats: dict[str, Any], char: dict[str, Any]) increase = self._floor(current + (base_stats.get(target, 0) * 1e-8 * value), 8) - current mod_stats[target] = current + increase else: - mod_stats[stat_id_str] = mod_stats.get(stat_id_str, 0) + value + key = str(stat_id) + mod_stats[key] = mod_stats.get(key, 0) + value return mod_stats From 17d35deb528bafde93e1311ff1acc0f90a5330ae Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 09:42:11 -0500 Subject: [PATCH 21/47] perf(statcalc): index mod GP by int (pips, level, tier) in set_game_data _calc_char_gp read each mod's GP with three nested _table_get calls on modRarityLevelTierGP, 18 calls for a fully modded character. set_game_data now flattens that table into a {(pips, level, tier): GP} index with int keys, and _calc_char_gp reads a mod's GP with one dict lookup. Only entries whose keys are canonical int strings are indexed, so an int key finds exactly the value the nested lookups find. A key the index does not hold (a str pips, level or tier, or a value missing from the table) still takes the nested _table_get lookups, which keep their defaults. The mods are added in the same order as before. Refs #245 Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/StatCalc/calculator.py | 63 ++++++++++++++++-------- tests/unit/test_statcalc_lookups.py | 37 ++++++++++++++ 2 files changed, 79 insertions(+), 21 deletions(-) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 06d64d3..288670f 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -78,6 +78,36 @@ def _str_keyed(value: Any) -> Any: return value +def _int_keyed_mod_gp(table: Any) -> dict[tuple[int, int, int], Any]: + """Flatten ``modRarityLevelTierGP`` to ``{(pips, level, tier): GP}`` with int keys. + + Only entries whose three keys are canonical int strings (``str(int(key)) == key``) are + included, so looking up int keys gives exactly what the nested ``_table_get`` lookups + give. Other keys, and tables of any other shape, are left to those lookups. + """ + if not isinstance(table, dict): + return {} + flat: dict[tuple[int, int, int], Any] = {} + for pips, levels in table.items(): + if not (_is_int_key(pips) and isinstance(levels, dict)): + continue + for level, tiers in levels.items(): + if not (_is_int_key(level) and isinstance(tiers, dict)): + continue + for tier, gp in tiers.items(): + if _is_int_key(tier): + flat[int(pips), int(level), int(tier)] = gp + return flat + + +def _is_int_key(key: str) -> bool: + """Return True if *key* is the str form of an int, as JSON object keys of int ids are.""" + try: + return str(int(key)) == key + except ValueError: + return False + + class _GameDataDownload: """Collect a streamed game data body, enforcing the size cap and optional SHA-256 check. @@ -168,6 +198,7 @@ def __init__( self._gp_tables: dict[str, Any] | None = None self._relic_data: dict[str, Any] | None = None self._skill_index: dict[str, dict[Any, dict[str, Any]]] = {} + self._mod_gp_index: dict[tuple[int, int, int], Any] = {} if game_data is None: self._LOGGER.info("No game data provided, loading from GitHub") @@ -203,6 +234,7 @@ def set_game_data(self, game_data: dict[str, Any]) -> None: for unit_id, meta in self._unit_data.items() if isinstance(meta, dict) and isinstance(meta.get("skills"), list) } + self._mod_gp_index = _int_keyed_mod_gp(self._gp_tables.get("modRarityLevelTierGP")) self._LOGGER.info( "Game data loaded: units=%d gear=%d mod_sets=%d", len(self._unit_data), @@ -965,30 +997,19 @@ def _calc_char_gp(self, char: dict[str, Any]) -> int: if char.get("purchasedAbilityId"): gp += len(char["purchasedAbilityId"]) * self._table_get(self._gp_tables["abilitySpecialGP"], "ultimate") + mod_keys: list[tuple[Any, Any, Any]] = [] if char.get("mods"): - for mod in char["mods"]: - gp += self._table_get( - self._table_get( - self._table_get( - self._gp_tables["modRarityLevelTierGP"], - mod["pips"], - ), - mod["level"], - ), - mod["tier"], - ) + mod_keys = [(mod["pips"], mod["level"], mod["tier"]) for mod in char["mods"]] elif char.get("equippedStatMod"): - for mod in char["equippedStatMod"]: - gp += self._table_get( - self._table_get( - self._table_get( - self._gp_tables["modRarityLevelTierGP"], - int(mod["definitionId"][1]), - ), - mod["level"], - ), - mod["tier"], + mod_keys = [(int(mod["definitionId"][1]), mod["level"], mod["tier"]) for mod in char["equippedStatMod"]] + for key in mod_keys: + mod_gp = self._mod_gp_index.get(key) + if mod_gp is None: + pips, level, tier = key + mod_gp = self._table_get( + self._table_get(self._table_get(self._gp_tables["modRarityLevelTierGP"], pips), level), tier ) + gp += mod_gp relic = char.get("relic") if relic and relic.get("currentTier", 0) > 2: diff --git a/tests/unit/test_statcalc_lookups.py b/tests/unit/test_statcalc_lookups.py index 23de7c6..28097a1 100644 --- a/tests/unit/test_statcalc_lookups.py +++ b/tests/unit/test_statcalc_lookups.py @@ -15,6 +15,7 @@ import pytest from swgoh_comlink import StatCalc +from swgoh_comlink.StatCalc.calculator import _int_keyed_mod_gp _PLAYER_FILE = Path(__file__).resolve().parent.parent / "resources" / "example-player.json" _RESULT_KEYS = ("stats", "gp") @@ -167,6 +168,42 @@ def test_unknown_unit_still_raises_key_error(self, calc): calc._get_crewless_skills_gp("NONEXISTENT_UNIT_XYZ", [{"id": "x", "tier": 1}]) +class TestModGpIndex: + @staticmethod + def _modded_unit(player: dict[str, Any]) -> dict[str, Any]: + return _normalized(next(u for u in player["rosterUnit"] if u.get("equippedStatMod"))) + + def test_index_gives_the_nested_lookup_result(self, calc, game_data, player): + unit = self._modded_unit(player) + unindexed = StatCalc(game_data=game_data) + unindexed._mod_gp_index = {} + assert calc._mod_gp_index + assert calc.calc_char_gp(unit) == unindexed.calc_char_gp(unit) + + def test_str_mod_keys_take_the_nested_lookup(self, calc, player): + unit = self._modded_unit(player) + mods = [ + {"pips": int(m["definitionId"][1]), "level": m["level"], "tier": m["tier"]} for m in unit["equippedStatMod"] + ] + str_mods = [{key: str(value) for key, value in mod.items()} for mod in mods] + gp_int = calc.calc_char_gp({**unit, "equippedStatMod": None, "mods": mods}) + assert calc.calc_char_gp({**unit, "equippedStatMod": None, "mods": str_mods}) == gp_int + assert gp_int == calc.calc_char_gp(unit) + + def test_only_canonical_int_keys_are_indexed(self): + table = {"5": {"15": {"5": 10, "05": 11, "x": 12}, "+1": {"1": 13}}, "y": {"1": {"1": 14}}, "6": [1, 2]} + assert _int_keyed_mod_gp(table) == {(5, 15, 5): 10} + assert _int_keyed_mod_gp(None) == {} + + def test_set_game_data_replaces_the_index(self, game_data): + data = copy.deepcopy(game_data) + data["gpTables"]["modRarityLevelTierGP"]["5"]["15"]["5"] = 123456 + calc = StatCalc(game_data=game_data) + assert calc._mod_gp_index[5, 15, 5] == game_data["gpTables"]["modRarityLevelTierGP"]["5"]["15"]["5"] + calc.set_game_data(data) + assert calc._mod_gp_index[5, 15, 5] == 123456 + + class TestFormatStats: def test_final_stats_keep_first_seen_order_and_sum_every_source(self, calc): mods = {"35": 4e8} From ccc3198142f361c656274622a25d52e26adfc5dc Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 09:47:47 -0500 Subject: [PATCH 22/47] perf(statcalc): build renamed stat dicts with a comprehension _rename_stats looked STATS_NAME_MAP up on the instance and allocated an empty default dict for every stat, then filled each renamed dict one item at a time. It now binds the map once, uses a shared read-only empty dict as the default, and builds each renamed dict with a comprehension. Names, values and key order are unchanged. Refs #245 Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/StatCalc/calculator.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 288670f..4482bca 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -40,6 +40,9 @@ # Chance to Critical Rating, Physical and Special Critical Avoidance to Critical Avoidance Rating). _FLAT_STAT_IDS: dict[str, str] = {"21": "14", "22": "15", "35": "39", "36": "40"} +# Stand-in for a stat id missing from StatCalc.STATS_NAME_MAP; only ever read. +_NO_STAT_INFO: dict[str, Any] = {} + def _check_fetch_options( game_data: dict[str, Any] | None, game_data_url: str | None, expected_sha256: str | None @@ -936,15 +939,16 @@ def crit_avoidance(val: float) -> float: return stats def _rename_stats(self, stats: dict[str, Any], lang: str = "eng_us") -> dict[str, Any]: + name_map = self.STATS_NAME_MAP rn_stats = {} for stat_type, stat_values in stats.items(): if not isinstance(stat_values, dict): rn_stats[stat_type] = stat_values continue - rn_stats[stat_type] = {} - for stat_id, value in stat_values.items(): - stat_name = self.STATS_NAME_MAP.get(stat_id, {}).get("name", stat_id) - rn_stats[stat_type][stat_name] = value + rn_stats[stat_type] = { + name_map.get(stat_id, _NO_STAT_INFO).get("name", stat_id): value + for stat_id, value in stat_values.items() + } self._LOGGER.debug("Done renaming stats") return rn_stats From 24684ea7a1d90fba62367aadefbae0aace4d3225 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 09:51:42 -0500 Subject: [PATCH 23/47] docs(migration): note that set_game_data indexes the mod GP table Like the per-unit skill index, the mod GP index is built when set_game_data runs, so a modRarityLevelTierGP table changed in place afterwards needs another set_game_data call. Refs #245 Co-Authored-By: Claude Opus 5.5 --- docs/migration.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/migration.md b/docs/migration.md index d0ef763..aa33d75 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -339,7 +339,8 @@ Upgrading from v2.8 to v2.9. holding non-`str` keys (such as `int` keys from a hand-built dict) with `str` keys, so it now gives the same results as JSON game data; your dict is not modified. Such a rebuilt table is a copy: call `set_game_data` again after changing it. The same applies - to a unit's `skills` list, which `set_game_data` indexes by skill id. + to a unit's `skills` list, which `set_game_data` indexes by skill id, and to + `gpTables["modRarityLevelTierGP"]`, which it indexes by pips, level and tier. ## Summary of changes From 18bd2ee95d80c9f57e10ae67b1a147b243adaa25 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 10:17:38 -0500 Subject: [PATCH 24/47] fix(examples): skip comment lines when decoding language bundles Current localization bundles contain '#' comment lines with no '|' delimiter (e.g. '# Start Category: ...', a bare '#'). The Sync and Async get_language_bundle examples unpacked line.split("|") into two names and raised ValueError on the first of them. Both examples now skip blank and '#' lines and split on the first '|' only, matching the library parser. Their docstrings point to get_localization_dictionary / async_get_localization_dictionary as the supported way to build the lookup. Both print the lookup size, and the Async main() returns the dict so the script exposes der_str_lookup like the Sync one. Adds tests/examples/test_get_language_bundle.py, which runs each example against a patched client serving a bundle with comment lines, blank lines and a value containing '|'. Closes #248 Co-Authored-By: Claude Opus 5.5 --- examples/Async/get_language_bundle.py | 27 ++++++-- examples/Sync/get_language_bundle.py | 22 ++++-- tests/examples/test_get_language_bundle.py | 80 ++++++++++++++++++++++ 3 files changed, 119 insertions(+), 10 deletions(-) create mode 100644 tests/examples/test_get_language_bundle.py diff --git a/examples/Async/get_language_bundle.py b/examples/Async/get_language_bundle.py index 5251a0b..5e605a8 100644 --- a/examples/Async/get_language_bundle.py +++ b/examples/Async/get_language_bundle.py @@ -1,7 +1,13 @@ # coding=utf-8 """ get_language_bundle.py -Sample script for retrieving a specific language bundle using the async client. +Sample script for retrieving a specific language bundle using the async client and decoding it by hand. + +To get the same lookup in one call, use the supported helper instead, which also skips comment +lines and applies resource limits: + + from swgoh_comlink.helpers import async_get_localization_dictionary + der_str_lookup = await async_get_localization_dictionary(cl, language="ger_de") """ import asyncio @@ -12,7 +18,7 @@ from swgoh_comlink import SwgohComlinkAsync -async def main(): +async def main() -> dict[str, str]: # Create a SwgohComlinkAsync instance async with SwgohComlinkAsync() as cl: # Retrieve the German language strings (Default is to collect data as a base64 encoded compressed string @@ -39,12 +45,21 @@ async def main(): der_obj_lines = der_obj_decoded.splitlines() # Each line has a key value and the corresponding text separated by a pipe ('|') + # The file also contains comment lines starting with '#' (e.g. '# Start Category: ...') and + # blank lines, which have no key/value pair. Values may themselves contain '|'. # To create a dictionary for easy mapping of strings from IDs used in game data collections, - # loop through the lines, split on the '|' character and store the information in an empty dict + # loop through the lines, skip comments and blank lines, split on the first '|' only and + # store the information in an empty dict der_str_lookup = {} for line in der_obj_lines: - key, value = line.split("|") - der_str_lookup[key] = value + if not line or line.startswith("#"): + continue + key, sep, value = line.partition("|") + if sep: + der_str_lookup[key] = value + + print(f"Built a lookup of {len(der_str_lookup)} German strings") + return der_str_lookup -asyncio.run(main()) +der_str_lookup = asyncio.run(main()) diff --git a/examples/Sync/get_language_bundle.py b/examples/Sync/get_language_bundle.py index e37ca16..d067a12 100644 --- a/examples/Sync/get_language_bundle.py +++ b/examples/Sync/get_language_bundle.py @@ -1,7 +1,13 @@ # coding=utf-8 """ get_language_bundle.py -Sample script for retrieving a specific language bundle. +Sample script for retrieving a specific language bundle and decoding it by hand. + +To get the same lookup in one call, use the supported helper instead, which also skips comment +lines and applies resource limits: + + from swgoh_comlink.helpers import get_localization_dictionary + der_str_lookup = get_localization_dictionary(cl, language="ger_de") """ import base64 @@ -37,9 +43,17 @@ der_obj_lines = der_obj_decoded.splitlines() # Each line has a key value and the corresponding text separated by a pipe ('|') +# The file also contains comment lines starting with '#' (e.g. '# Start Category: ...') and +# blank lines, which have no key/value pair. Values may themselves contain '|'. # To create a dictionary for easy mapping of strings from IDs used in game data collections, -# loop through the lines, split on the '|' character and store the information in an empty dict +# loop through the lines, skip comments and blank lines, split on the first '|' only and +# store the information in an empty dict der_str_lookup = {} for line in der_obj_lines: - key, value = line.split("|") - der_str_lookup[key] = value + if not line or line.startswith("#"): + continue + key, sep, value = line.partition("|") + if sep: + der_str_lookup[key] = value + +print(f"Built a lookup of {len(der_str_lookup)} German strings") diff --git a/tests/examples/test_get_language_bundle.py b/tests/examples/test_get_language_bundle.py new file mode 100644 index 0000000..e7c3fdd --- /dev/null +++ b/tests/examples/test_get_language_bundle.py @@ -0,0 +1,80 @@ +"""Tests for examples/{Sync,Async}/get_language_bundle.py. + +These test example scripts, not the library, so they live outside tests/unit/. + +Each script fetches a localization bundle and decodes it by hand at import time. The client +class is patched to return an in-memory bundle, the script is executed, and the string lookup +it builds is checked. Current bundles contain ``#`` comment lines with no ``|`` delimiter. +""" + +from __future__ import annotations + +import base64 +import importlib.util +import io +import zipfile +from pathlib import Path +from typing import Any +from unittest import mock + +import pytest + +_EXAMPLES = Path(__file__).resolve().parents[2] / "examples" + +# Shaped like a current Loc_GER_DE.txt: category comments, a bare "#", a blank line and a +# value that contains the delimiter. +_BUNDLE_TEXT = ( + "# Start Category: Star_Wars_Strategy_RPG\n" + "#\n" + "UNIT_VADER_NAME|Darth Vader\n" + "\n" + "UNIT_VADER_DESC|Sith-Lord|Imperium\n" + "EMPTY_VALUE|\n" + "# End Category: Star_Wars_Strategy_RPG (3 strings)\n" +) + +_EXPECTED = { + "UNIT_VADER_NAME": "Darth Vader", + "UNIT_VADER_DESC": "Sith-Lord|Imperium", + "EMPTY_VALUE": "", +} + + +def _localization_response() -> dict[str, str]: + """A get_localization() response whose bundle zips Loc_GER_DE.txt and Loc_Key_Mapping.txt.""" + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: + zf.writestr("Loc_GER_DE.txt", _BUNDLE_TEXT) + zf.writestr("Loc_Key_Mapping.txt", "") + return {"localizationBundle": base64.b64encode(buf.getvalue()).decode("ascii")} + + +def _run_example(variant: str) -> Any: + """Execute examples//get_language_bundle.py against a patched client; return the module.""" + path = _EXAMPLES / variant / "get_language_bundle.py" + spec = importlib.util.spec_from_file_location(f"get_language_bundle_{variant.lower()}", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + + if variant == "Sync": + patcher = mock.patch("swgoh_comlink.SwgohComlink") + with patcher as client_cls: + client_cls.return_value.get_localization.return_value = _localization_response() + spec.loader.exec_module(module) + client_cls.return_value.get_localization.assert_called_once_with(locale="ger_de") + else: + client = mock.MagicMock() + client.get_localization = mock.AsyncMock(return_value=_localization_response()) + with mock.patch("swgoh_comlink.SwgohComlinkAsync") as client_cls: + client_cls.return_value.__aenter__.return_value = client + spec.loader.exec_module(module) + client.get_localization.assert_awaited_once_with(locale="ger_de") + return module + + +@pytest.mark.parametrize("variant", ["Sync", "Async"]) +def test_builds_lookup_skipping_comment_lines(variant: str, capsys: pytest.CaptureFixture[str]): + module = _run_example(variant) + + assert module.der_str_lookup == _EXPECTED + assert f"{len(_EXPECTED)} German strings" in capsys.readouterr().out From 20a7bb4e0d595ade5b4f608ff0df614d035280bc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:52:38 +0000 Subject: [PATCH 25/47] chore(deps): Bump astral-sh/setup-uv Bumps the github-actions group with 1 update: [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv). Updates `astral-sh/setup-uv` from 7.6.0 to 10.3.3 - [Release notes](https://github.com/astral-sh/setup-uv/releases) - [Commits](https://github.com/astral-sh/setup-uv/compare/37802adc94f370d6bfd71619e3f0bf239e1f3b78...68559e99cc807c1eb7e9238fd43a15bba460eec2) --- updated-dependencies: - dependency-name: astral-sh/setup-uv dependency-version: 10.3.3 dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 12 ++++++------ .github/workflows/commitlint.yml | 2 +- .github/workflows/docs.yml | 2 +- .github/workflows/integration.yml | 2 +- .github/workflows/prepare-release.yml | 2 +- .github/workflows/release.yml | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8af80e0..75d2c75 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -47,7 +47,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -72,7 +72,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -105,7 +105,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -126,7 +126,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -155,7 +155,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" diff --git a/.github/workflows/commitlint.yml b/.github/workflows/commitlint.yml index e413982..1ebf1b1 100644 --- a/.github/workflows/commitlint.yml +++ b/.github/workflows/commitlint.yml @@ -21,7 +21,7 @@ jobs: # same hook through pre-commit rather than its own npm install, so local and CI # validation cannot drift. - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Cache the pre-commit hook environment uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 65f012b..22f3909 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -72,7 +72,7 @@ jobs: persist-credentials: true - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: # This job publishes the site, so it must not restore a cache that # other workflows (e.g. PR runs) can write. diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 04b647b..091b453 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -60,7 +60,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 11151e5..1fcff6e 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -42,7 +42,7 @@ jobs: fetch-depth: 0 - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e3342cd..3bb79d0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,7 +40,7 @@ jobs: fetch-depth: 0 # full history + tags for version derivation - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 From f9aaaef94df006ce92a90bbad336a1360018c2be Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:53:21 +0000 Subject: [PATCH 26/47] chore(deps): Bump the astral-tools group with 2 updates Bumps the astral-tools group with 2 updates: [ty](https://github.com/astral-sh/ty) and [ruff](https://github.com/astral-sh/ruff). Updates `ty` from 0.0.91 to 0.0.98 - [Release notes](https://github.com/astral-sh/ty/releases) - [Changelog](https://github.com/astral-sh/ty/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ty/compare/0.0.91...0.0.98) Updates `ruff` from 0.17.2 to 0.17.4 - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/0.17.2...0.17.4) --- updated-dependencies: - dependency-name: ty dependency-version: 0.0.98 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: astral-tools - dependency-name: ruff dependency-version: 0.17.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: astral-tools ... Signed-off-by: dependabot[bot] --- uv.lock | 76 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/uv.lock b/uv.lock index 6b9f899..642b85b 100644 --- a/uv.lock +++ b/uv.lock @@ -829,27 +829,27 @@ wheels = [ [[package]] name = "ruff" -version = "0.17.2" +version = "0.17.4" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ae/58/690cf56da80c8f2c8bf12042b6017beac2c34fe961f65420bcb3fb7fac38/ruff-0.17.2.tar.gz", hash = "sha256:84d632402d14c23b488f941db23712d6736a013225162062d34558c3f3c780eb", size = 5333400, upload-time = "2026-10-22T18:38:00.181Z" } +sdist = { url = "https://files.pythonhosted.org/packages/84/0e/3d154514b5bad104f7e1c13169c2d09aa9959fccdc06eb47610ccdfa83ed/ruff-0.17.4.tar.gz", hash = "sha256:f32d178b50e826e00f6c6c1be3f56333068acb9b67fe167143527fa9b81e890d", size = 5357750, upload-time = "2026-11-05T18:52:17.638Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/98/b8/8b6d69c57e8fe1cc6af1aa7493b72a1a5b5a8afe34694e302025441729d4/ruff-0.17.2-py3-none-linux_armv6l.whl", hash = "sha256:96a65e755d8dba094707fb23ab602111d9a31ec2835b3a6992a1914a8fcb211e", size = 10183857, upload-time = "2026-10-22T18:37:14.956Z" }, - { url = "https://files.pythonhosted.org/packages/e8/61/12cc2ff7b2fa90a268ce1e2162c23aaf76e601d22623f6a31b0eeaa764b0/ruff-0.17.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:39c5b55c960515cdb32be16e69efb5734c589c06a0eb38a22694524a336b889d", size = 10210904, upload-time = "2026-10-22T18:37:17.985Z" }, - { url = "https://files.pythonhosted.org/packages/e8/7c/b8850a8e4ad29f64a827dd6c6902db4a9aa538fb2b9eef4e26084001a3bb/ruff-0.17.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:92a80d2f44584dabb0189b3a6c393e37e525e04942838482010575cb81945be7", size = 9408439, upload-time = "2026-10-22T18:37:20.964Z" }, - { url = "https://files.pythonhosted.org/packages/b7/b6/6a64fae86ca5e5e29d5adc311e5481de726cedf9aee607435a16c31c442a/ruff-0.17.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b7d0906677d89bbf3cf73cde64b5bbe2ab35df3ae43e49ee2627301e91265bac", size = 10047078, upload-time = "2026-10-22T18:37:23.717Z" }, - { url = "https://files.pythonhosted.org/packages/10/19/23d376547715175aa1bd46df48df6aacc7c6439d9daf19cac15975180aa5/ruff-0.17.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7cfd783590edf2b77317882631900f6a13ea2e8eacefe6ebf2370d2715299160", size = 9990478, upload-time = "2026-10-22T18:37:26.584Z" }, - { url = "https://files.pythonhosted.org/packages/93/6c/34cda32cbe13adac5c6b291a307a5570d8ebd37c0c86339f0fe628e55632/ruff-0.17.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:122258f6ecde0e0dd1bb60b24263c3edde4338caf723fca711cc729f9bfd414a", size = 10673624, upload-time = "2026-10-22T18:37:29.767Z" }, - { url = "https://files.pythonhosted.org/packages/bf/10/5d762a4dbc851d8bb47863cf3a28a61bf31c804d393b70d891fac899f5d1/ruff-0.17.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7f8fba429d6ac4128ab29cfb8fa6240d2fa671d04adf7f84d3b22fc7b6b6bea4", size = 11351797, upload-time = "2026-10-22T18:37:32.535Z" }, - { url = "https://files.pythonhosted.org/packages/3f/04/a0e92a81faf5c81c1c98d4374c8401734ccf2b8cca7d0170cb0fec08c6e2/ruff-0.17.2-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:583bd67bb9e7061dd09bc46a0a884bae2bbd214dbcd48e509813612619683869", size = 10949414, upload-time = "2026-10-22T18:37:35.501Z" }, - { url = "https://files.pythonhosted.org/packages/c3/d8/59894cf630d2d86882457a2a6a0a1533410c5c805bfbac6f6eb4b5aef69d/ruff-0.17.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c60f93fec7142dba5b8f487f94bf2f6231dae24dc11e4c48648347c8b0720004", size = 10528000, upload-time = "2026-10-22T18:37:37.88Z" }, - { url = "https://files.pythonhosted.org/packages/ab/95/d6e30c51e851d37e10762ad91fa1e76ddaad998589b5667962a3cfbc9edd/ruff-0.17.2-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:c555a877f8f41447e318101cfefea9bf12dfa9f82eedf90c376e57e069f917d0", size = 10571779, upload-time = "2026-10-22T18:37:40.444Z" }, - { url = "https://files.pythonhosted.org/packages/f4/5a/a7e1d74fb464250137d3d4eca645d323536533b672004d04ee0e46e0caf3/ruff-0.17.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:ba405cbd5ec7bda1f555d5e52be1fd68d02608d4d95d24591bdac92cfacb579f", size = 10051707, upload-time = "2026-10-22T18:37:42.812Z" }, - { url = "https://files.pythonhosted.org/packages/6e/f2/02fca29ca7999380f0350a7212fe755c11ab9c22d61327356cce8decdbc6/ruff-0.17.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:8c21b4ab24485358f17291a4f8dc5399b834e963b8efedd920fe4fdb02081bb4", size = 9998227, upload-time = "2026-10-22T18:37:45.224Z" }, - { url = "https://files.pythonhosted.org/packages/d1/00/55aa604a093dfdc1526e570fae0bb7d37a2221c7b4728d5f080b2add16ba/ruff-0.17.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:5875a16b0de70b43cb81eabea5ae5e8f5d1b2fd1b5e6ed07f80cfe5019d0bd5a", size = 10377692, upload-time = "2026-10-22T18:37:47.704Z" }, - { url = "https://files.pythonhosted.org/packages/e4/5a/a7a640f47bb906ec8fa233ea84319d503e6dee02b59e3901bd312ebd1f9b/ruff-0.17.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:2d086be452eed686aa51271ecf2cbe5037956517cc6ee39a17b4489ac12f8bbe", size = 10790587, upload-time = "2026-10-22T18:37:50.191Z" }, - { url = "https://files.pythonhosted.org/packages/2c/d4/c3b74e1b4808438ea7f14bb914478025e2d51261f60774a54a0fa222ec46/ruff-0.17.2-py3-none-win32.whl", hash = "sha256:6bce7d1f5165701ae18f5df85c65afe78cddfa6c5fb4b9bdb0014d60388f3edd", size = 9870537, upload-time = "2026-10-22T18:37:52.486Z" }, - { url = "https://files.pythonhosted.org/packages/1c/9a/c7da96c2c96d20704cf9027f7a5121da272a8c05f1d1531ba949e3b3df04/ruff-0.17.2-py3-none-win_amd64.whl", hash = "sha256:1b59d447f197bef9ef48a22ba1a6016137753c6099e9bac9c36eb566e422424c", size = 10282826, upload-time = "2026-10-22T18:37:55.2Z" }, - { url = "https://files.pythonhosted.org/packages/81/60/a3604c79cb02777b6cb84da894104021986f06c4bc41375102cc95049a32/ruff-0.17.2-py3-none-win_arm64.whl", hash = "sha256:195ad918027f817c119310ca89a42d347887dfc28934aaa869325e9c5dc9d962", size = 9827036, upload-time = "2026-10-22T18:37:58.031Z" }, + { url = "https://files.pythonhosted.org/packages/e0/61/c83c78bbb6108f6c6270a106cf12b54175f4f42da088b9bb880f18e31289/ruff-0.17.4-py3-none-linux_armv6l.whl", hash = "sha256:2b08c4ff98dc234f4a3871a3105353b922fa875ea1073ca31001eb8c06bb4d89", size = 10252195, upload-time = "2026-11-05T18:51:36.594Z" }, + { url = "https://files.pythonhosted.org/packages/0a/12/dd158708378866e8b53e145a465dbc51a7cccb9fa197a74d67eaedde7234/ruff-0.17.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:13e781c3c5f663e7fba737eaaeb70dd943dd55171daf316afb25cd5268cfe0c7", size = 10266044, upload-time = "2026-11-05T18:51:39.502Z" }, + { url = "https://files.pythonhosted.org/packages/28/32/89a94a8eb11fd505a381ae6f04e190d038d9958695209dc1786ce5cfcda3/ruff-0.17.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7ed2f416349944f908f9574215994602242b0836844eba48eec61473033afca0", size = 9432227, upload-time = "2026-11-05T18:51:41.968Z" }, + { url = "https://files.pythonhosted.org/packages/58/de/a392dc38b215798ae72e639d228b7f6c02d826a95d1c0ad7c4c0ee49ef5b/ruff-0.17.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8ea6e0017c785f7282092b11e46338e4ebed1b9e575ebf2e55a8a1eda968241a", size = 10136900, upload-time = "2026-11-05T18:51:44.562Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8f/a880f60f42005f6ffdf58f77af34c7ee327000b5607f48a2f6a69d8b242c/ruff-0.17.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7e061dcc0933c7031a616ac8d66ac540309b2aa21ab558101a8f53e9ac7a1185", size = 10051245, upload-time = "2026-11-05T18:51:46.7Z" }, + { url = "https://files.pythonhosted.org/packages/09/55/98844264108af7d5ec27ca3a9cd5a989094ca657a14599c4b69a537a0e9a/ruff-0.17.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f99e95a1515161138be3cbd1b06c06e739d8feb38ade35564556999fffc3686e", size = 10704341, upload-time = "2026-11-05T18:51:49.228Z" }, + { url = "https://files.pythonhosted.org/packages/28/a2/5edf97659c3ac7c73f978003bd314936f671037fdac6b978e9de3e4b2b65/ruff-0.17.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f28cf0dd37cb172fa5a8d2e92e6ada3a9dbd0609f094ed24039929eef0b7524", size = 11394465, upload-time = "2026-11-05T18:51:51.534Z" }, + { url = "https://files.pythonhosted.org/packages/f2/8f/51371ae856b2bef4d15a044a574695fbc0f6ae63aafa42a2a22428070fb6/ruff-0.17.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b21c771b296888e8a35c6f48555f4b44e4483f61675d6ed51810a5203469ce6", size = 10988262, upload-time = "2026-11-05T18:51:53.91Z" }, + { url = "https://files.pythonhosted.org/packages/af/1b/62874f14c7873f27c7887d2b1ea41de990e14ba9518801ffe8eacb5d51a6/ruff-0.17.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2cd025509b2e15721b426fc70fd946d71f43b3db3b08e946dfec2d696d911690", size = 10572829, upload-time = "2026-11-05T18:51:56.129Z" }, + { url = "https://files.pythonhosted.org/packages/98/30/860b9dae67432b16b88558a9cb2d3194825fa62838f8b9cc49f5d9022095/ruff-0.17.4-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:49b77f7b3921669466882a4881168801bdb06ec2cd83fb936049016cf5fdece1", size = 10617545, upload-time = "2026-11-05T18:51:58.172Z" }, + { url = "https://files.pythonhosted.org/packages/0f/08/781a4b41a1c83fd6e30fea610d6502a6f94e49cf94693fd37bdcbc6bfe11/ruff-0.17.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e3b84eb74f260d1c2dbd236fd9d4c011d4fdd0a52bdf8aea57a10e3a1b71fca5", size = 10111955, upload-time = "2026-11-05T18:52:00.59Z" }, + { url = "https://files.pythonhosted.org/packages/3c/e9/94b1c7b677120f30839254518924f73a8157e9bcfa200edcd5796fecdb99/ruff-0.17.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:20e43d7a08e712e33067ba887e6574546c79bd4831596ce8f16803ac7ff9ad90", size = 10058355, upload-time = "2026-11-05T18:52:03.61Z" }, + { url = "https://files.pythonhosted.org/packages/27/5f/a825910b9f309336dc33cb8c0774126662c1d2f765699b3e0a1bd538d01f/ruff-0.17.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:0d1f4848fd2ec0499be4046db9b7dfcc952666885f00233cc7033515282556a8", size = 10415932, upload-time = "2026-11-05T18:52:06.264Z" }, + { url = "https://files.pythonhosted.org/packages/8b/b8/0796468423413ea4df1a6e2442ae26cf49b8f7dda0eecf246e0d5d0dde54/ruff-0.17.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6007e7f3a0e55b0fbdb947af69cf24c21b4928df6be8ef3e767c69b5ccccf496", size = 10826033, upload-time = "2026-11-05T18:52:08.675Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ab/d8e407669ffe5014429baf780c2df47e001968a6e4c17f615e2e7b13a9ba/ruff-0.17.4-py3-none-win32.whl", hash = "sha256:3971a78cba76298b284c8321e6d40d93045ed348bec5c369d85099efc97fb7cf", size = 9931993, upload-time = "2026-11-05T18:52:11.169Z" }, + { url = "https://files.pythonhosted.org/packages/bd/15/42af8a72d8946e3c9efd2bbf6641e462b6832783b0d043d63ef5b280ba7f/ruff-0.17.4-py3-none-win_amd64.whl", hash = "sha256:67c5a894fc054cf41f75f7afa24815de5a74329d97634126c2a1015740ff4e8c", size = 10292922, upload-time = "2026-11-05T18:52:13.436Z" }, + { url = "https://files.pythonhosted.org/packages/68/9e/f1dbffcfb8ff25dadbc21f87a8b73c3848abe4abada9d4b08ccef8bec40c/ruff-0.17.4-py3-none-win_arm64.whl", hash = "sha256:181ae38a9a8fb94925bf7d0794327b48d7fd7f4b50cfd84c0e999cc09ef8d131", size = 9889396, upload-time = "2026-11-05T18:52:15.549Z" }, ] [[package]] @@ -998,27 +998,27 @@ wheels = [ [[package]] name = "ty" -version = "0.0.91" +version = "0.0.98" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/08/c0/9e26817a5c94d504aab30bffbbf53f836f4763dd0a947089246ff555eebe/ty-0.0.91.tar.gz", hash = "sha256:b9c434cc1e3b106b6b9353b78ef304d5904c82cf440abcafef7134270a22b41a", size = 8035848, upload-time = "2026-10-22T18:24:52.086Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/bc/a17167c26defcb6ce004b3668624deb47ed98955f5ef14d8aee6d533d6c8/ty-0.0.98.tar.gz", hash = "sha256:91778c8201da22ba553fb51c5b01c346b7ab37bbf0267536c86e5be4f09467ad", size = 8169824, upload-time = "2026-11-05T17:39:44.73Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/be/ad/0a850c1ca8e6e802e6b0f730f0d59c9769845b2fc956e3acd7f429b665f2/ty-0.0.91-py3-none-linux_armv6l.whl", hash = "sha256:5d39e6e485854838eb7fcdb747495f5b90283d58bce869c17445120fe0c7e40a", size = 14255787, upload-time = "2026-10-22T18:24:11.284Z" }, - { url = "https://files.pythonhosted.org/packages/33/87/9ccfa2d97b8b043e4d6fab10febc50ac7856b02cf7cd64910085db806bbe/ty-0.0.91-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:dcf953e25f90fbccf6cc27ef43fc4ef0961c89f54866e32cd1d7f24891b96084", size = 13822267, upload-time = "2026-10-22T18:24:14.31Z" }, - { url = "https://files.pythonhosted.org/packages/13/33/be8f62444c7840d1b0928c6d174540c0fe6b1b193ae9324c8249e8ed52b9/ty-0.0.91-py3-none-macosx_11_0_arm64.whl", hash = "sha256:78e3e66e88a9ae903afe0981ff9bd225d452ade2aeb070715842510dfcbf6de4", size = 12957620, upload-time = "2026-10-22T18:24:16.961Z" }, - { url = "https://files.pythonhosted.org/packages/31/9f/a742f273c065c4f5a054cc2b44076207136ff1cd346adfb23da38d8894d8/ty-0.0.91-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:89ecaf87b3d7b508f9ea1ef8715d4cf47942719659028c92fad819d82a82ccfa", size = 13746018, upload-time = "2026-10-22T18:24:19.221Z" }, - { url = "https://files.pythonhosted.org/packages/5a/a0/3eecf8717cbe4e05d6e02b53679aebad79f1bfcff6c9c03d7601cb7df5f9/ty-0.0.91-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:0ec8fe4243aab445abece38a2b8e9b3010230d5e6b3f4e15bfa811a914d99e73", size = 13993220, upload-time = "2026-10-22T18:24:21.328Z" }, - { url = "https://files.pythonhosted.org/packages/09/b0/fb3edee2857e97d85b6c735901469fd523cf6792382e4fbbb00b065c186c/ty-0.0.91-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:577701ec2a9cf7a50f6059069399b9437bb8af7a99df24012776e95d8a55831f", size = 14936911, upload-time = "2026-10-22T18:24:24.393Z" }, - { url = "https://files.pythonhosted.org/packages/b7/2c/82f29ee86f4171807af8ab2feaf4e51211143118a3e53e9da2c2e77eca7d/ty-0.0.91-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fc683f49197d63ec47b2eaa9763ddb32dafb2a31190d938b9bb8ebecc5b25173", size = 15336384, upload-time = "2026-10-22T18:24:26.472Z" }, - { url = "https://files.pythonhosted.org/packages/0b/85/e2419b19577ead84b8afa9137c12eb4bde19f926423bfe01e615db12c52c/ty-0.0.91-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b8bb2784572fa22f77e417844936f6a9f831a6b0ba64749ca1065c407aefcd23", size = 15332319, upload-time = "2026-10-22T18:24:28.979Z" }, - { url = "https://files.pythonhosted.org/packages/83/06/dc28cea0796ee0268bf987d1d6f0f168605bec8898dbdbc7676049d2667b/ty-0.0.91-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f68bb6bfc8171910335a47c7e84070f28bbbc0326bcd6ef08fe3690d0509556b", size = 14600250, upload-time = "2026-10-22T18:24:31.359Z" }, - { url = "https://files.pythonhosted.org/packages/1e/71/83dd28e628698059ba6fe7081acafa7a8f65cfd90fe6573907ca8219d561/ty-0.0.91-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:63f268c80697d614d18e988476d2517177d66ec732ae104d86e57b60f197a416", size = 14812339, upload-time = "2026-10-22T18:24:33.689Z" }, - { url = "https://files.pythonhosted.org/packages/9d/5a/63c0eae2d5b02cef98a9b327b1a16b36287c140b3a7d2306ff7560177f9c/ty-0.0.91-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:b0f34630aa92e222d7754d66222d116f027025cb2b9ed66e1b4b73623de74e84", size = 13703060, upload-time = "2026-10-22T18:24:36.278Z" }, - { url = "https://files.pythonhosted.org/packages/47/ac/fd6d20d00202949d775043c5f70679f38d0e48ea30eeacbffaf6e0a9754e/ty-0.0.91-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:e62f8bbc17d481e01cce39bdfbe36beefda0478cb210e8045ef618d3f674a731", size = 14006236, upload-time = "2026-10-22T18:24:38.464Z" }, - { url = "https://files.pythonhosted.org/packages/fa/26/53dddd4f927dfaa73ea14cd71d97b4d92d685e365b5b037bac457e271403/ty-0.0.91-py3-none-musllinux_1_2_i686.whl", hash = "sha256:f8bf4514a383b13d7cf86eddb55f0eb9f356fc7efeae0de714ad4fe5fc54fee8", size = 14356612, upload-time = "2026-10-22T18:24:40.621Z" }, - { url = "https://files.pythonhosted.org/packages/89/40/ccebba145dd244b2f6058ce2e4a6ff34dea36d4a5b38dd7a6ae983b65a3b/ty-0.0.91-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a6d93ab988c4c5ed92b52389b888d46ddede78e4646fe28db615bbeff89cdf82", size = 14674843, upload-time = "2026-10-22T18:24:43.325Z" }, - { url = "https://files.pythonhosted.org/packages/08/6f/8a7701adf1f539a893274358f12ba62773d5bb40920bfc53e0d852bfd576/ty-0.0.91-py3-none-win32.whl", hash = "sha256:b9f4bba8486a3d13babc11f8115369d0a0dc8bef127b7cf4f4c5eed9d4dbfa01", size = 13260545, upload-time = "2026-10-22T18:24:45.715Z" }, - { url = "https://files.pythonhosted.org/packages/fc/63/27c8051a72328ee81f47dace5e2c63e7db43bcae935db25a9dbd4d0e59b2/ty-0.0.91-py3-none-win_amd64.whl", hash = "sha256:5ac9eaf938e7fba4dd6c3358f852e6eb3127aa7bde0a76d9807c41f60ad73a29", size = 13759484, upload-time = "2026-10-22T18:24:48.111Z" }, - { url = "https://files.pythonhosted.org/packages/aa/a9/1f6c3694b7b33be4ae9a272f71a99a7dd27ec020c32a22049e9c0e79f576/ty-0.0.91-py3-none-win_arm64.whl", hash = "sha256:35820957639db1fb8c643273670967192c308038836005bdf3bfef111aff64a0", size = 13318343, upload-time = "2026-10-22T18:24:50.116Z" }, + { url = "https://files.pythonhosted.org/packages/33/91/de19c23f17dc3a4ad1caa30048c151681f21b90794b67d81adb6fd543b25/ty-0.0.98-py3-none-linux_armv6l.whl", hash = "sha256:4fc233f6f794ffde14d6bbe5ad0999e3d809f486a2a5500890076fd3e142beb4", size = 14681915, upload-time = "2026-11-05T17:39:07.196Z" }, + { url = "https://files.pythonhosted.org/packages/2b/51/1a9a2648c63e04bef27e2ab27e3e419f7e80d1ef567d41111e2b133065fb/ty-0.0.98-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9207be78d93bf5640caad7a6c93f8c4b5ba262e997774f288a0350220c7a7053", size = 14290511, upload-time = "2026-11-05T17:39:09.855Z" }, + { url = "https://files.pythonhosted.org/packages/77/5d/dd82abd70653d48b0e7a5f05582c38149a585e49dfde7f473b0a52064c54/ty-0.0.98-py3-none-macosx_11_0_arm64.whl", hash = "sha256:f1f411590d81edcc75013d220ee522ee083b07f9eb2f085c1eb63767b22d3022", size = 13285566, upload-time = "2026-11-05T17:39:11.956Z" }, + { url = "https://files.pythonhosted.org/packages/3c/da/6ef71f418084487c22f66de651a7db24595f44256ee239e4a78aa2e7047f/ty-0.0.98-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:01133c80ae420cd1c23e25299b10f852a6ae84ea4618b83db7c00d244d10a0cb", size = 14230025, upload-time = "2026-11-05T17:39:14.199Z" }, + { url = "https://files.pythonhosted.org/packages/20/14/25167823974fad33f83aa65fe5b5b90dda44add7b6041c2b2b1a3a108ac8/ty-0.0.98-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ec7cf10443de01c22a6ebd0e08c76f9092378d404f95c50a6efca352c3e671de", size = 14414136, upload-time = "2026-11-05T17:39:16.424Z" }, + { url = "https://files.pythonhosted.org/packages/4e/fb/8ed2e04688eb74d61a9875b20dee33097e01bcaf8dd541801819cfaf7b11/ty-0.0.98-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3ecc9c19acea7c00d834ce3eea181837293bda8113737815ca1044009689f8b1", size = 15377595, upload-time = "2026-11-05T17:39:18.747Z" }, + { url = "https://files.pythonhosted.org/packages/d2/6e/32eb263f83d404532cf7e580fdf464364195c8683725383e0c1f7f207dab/ty-0.0.98-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b46b175a61982dd835ad5e634ab7f5d6045f7e459c0324c1ecb656afa2a79124", size = 15834809, upload-time = "2026-11-05T17:39:20.772Z" }, + { url = "https://files.pythonhosted.org/packages/70/df/63773ba170878ff0e26a3ed432391faf903a1df712ddfdc929693745f0f7/ty-0.0.98-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a00992a56b56b783b4203e0762aa1157ec4721b190a9b0d3bbe6647ce3518f2c", size = 15761661, upload-time = "2026-11-05T17:39:23.102Z" }, + { url = "https://files.pythonhosted.org/packages/a8/a5/efaeb737756db133975085754f1bf0f1d720b322130b0f310ad26457ec59/ty-0.0.98-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1f08c4f7a7f368a0f8a5f8020a660f4cb325fec7ab48d1d073496cb17edd9796", size = 16544942, upload-time = "2026-11-05T17:39:25.267Z" }, + { url = "https://files.pythonhosted.org/packages/d4/b7/7d23d6e8cccbca995e47c0a26c85b3d600354cba5c57122b1a8bdd25edbf/ty-0.0.98-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:44b86d87bb79efd1cc0481cabfbbad45a425fe639fc832762649352e9c6dac2b", size = 15300511, upload-time = "2026-11-05T17:39:27.251Z" }, + { url = "https://files.pythonhosted.org/packages/b9/53/092e5c944f57324b9ca23227468aca022907e78a83477e7597f5a493b77d/ty-0.0.98-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:188df587adc6130d75445d8df7e1af01c3d9b18962f90382865d963893bd2fcb", size = 14131203, upload-time = "2026-11-05T17:39:29.477Z" }, + { url = "https://files.pythonhosted.org/packages/cd/ed/c1b0357ba7524f297d0c90cfeb6241dbf82382f451810db786965926676b/ty-0.0.98-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1d26a72fec5e2e1d21bacdc3ccf8f69b5b352a23f0c717ad5c6267aa25ed7958", size = 14425417, upload-time = "2026-11-05T17:39:31.717Z" }, + { url = "https://files.pythonhosted.org/packages/eb/4a/1ec3a4cbf80badff198d13b278c0cac4cc55256a73c3a7b52774815763e7/ty-0.0.98-py3-none-musllinux_1_2_i686.whl", hash = "sha256:c066c7985b3e6d30ddb23cae5b1e09b0689c98e91efcd0e1ba07da67a4a5db36", size = 14777544, upload-time = "2026-11-05T17:39:33.72Z" }, + { url = "https://files.pythonhosted.org/packages/8e/4b/6c914a633b4f2db404289b003aa87b62c0a15e17870f249a2a31585c03ec/ty-0.0.98-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a3c144a37cea1a2bd643563e7603974f2262132e7225e4e8d536b52092f84fb5", size = 15147963, upload-time = "2026-11-05T17:39:35.969Z" }, + { url = "https://files.pythonhosted.org/packages/9d/3c/fdfc54ed7e49148d166f130d16e1d2e034eaf685ef762f194c2b2b2969c6/ty-0.0.98-py3-none-win32.whl", hash = "sha256:b6dccf6abbb07d2d58db48b535465c9995c52047a208d7c5eda438539c0fdd4c", size = 13632434, upload-time = "2026-11-05T17:39:38.272Z" }, + { url = "https://files.pythonhosted.org/packages/42/94/dc9ba9966ce387f66a296c7b6dfe4e8754695cfa6946f16e8fbfd3beffeb/ty-0.0.98-py3-none-win_amd64.whl", hash = "sha256:c2c41c6923b149b520577fd0424cdbddad12760ddaaa5eda429266aab2d315b9", size = 14258971, upload-time = "2026-11-05T17:39:40.46Z" }, + { url = "https://files.pythonhosted.org/packages/44/5f/c0db82d5e4a5399771735653ce9e0173e1556feb69fcd0ac159aa1473cd9/ty-0.0.98-py3-none-win_arm64.whl", hash = "sha256:b1f9412cb766fec79d7586f72708152d3c97a5fbad826bef986ebbeff3dd0c4f", size = 13701979, upload-time = "2026-11-05T17:39:42.5Z" }, ] [[package]] From 48d2859345418a9a73efae9a0077486243206654 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:54:02 +0000 Subject: [PATCH 27/47] chore(deps): Bump the python group with 2 updates Bumps the python group with 2 updates: [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) and [mkdocs-material](https://github.com/squidfunk/mkdocs-material). Updates `pytest-asyncio` from 1.4.1 to 1.4.1.post1 - [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases) - [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v1.4.1...v1.4.1.post1) Updates `mkdocs-material` from 9.7.7 to 9.8.0 - [Release notes](https://github.com/squidfunk/mkdocs-material/releases) - [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG) - [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.7.7...9.8.0) --- updated-dependencies: - dependency-name: pytest-asyncio dependency-version: 1.4.1.post1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: python - dependency-name: mkdocs-material dependency-version: 9.8.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: python ... Signed-off-by: dependabot[bot] --- uv.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/uv.lock b/uv.lock index 6b9f899..35f8abb 100644 --- a/uv.lock +++ b/uv.lock @@ -536,7 +536,7 @@ wheels = [ [[package]] name = "mkdocs-material" -version = "9.7.7" +version = "9.8.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "babel" }, @@ -551,9 +551,9 @@ dependencies = [ { name = "pymdown-extensions" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f1/cd/c05d3a530ba7934f144fb45f7203cd236adc25c7bdcc34673d202f4b0278/mkdocs_material-9.7.7.tar.gz", hash = "sha256:c0649c065b1b0512d60aad8c10f947f8e455284475239b364b610f2deb4d0855", size = 4097923, upload-time = "2026-07-17T16:21:33.156Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b9/02/3c0df248819286810d8479b3a72d9531db0cc36c042fe1ab3985f137c664/mkdocs_material-9.8.0.tar.gz", hash = "sha256:1ed4c5edaf405a3fb62e55288b8fdff592971729361548b1ffa757bf9849fb81", size = 4094495, upload-time = "2026-10-24T09:50:16.181Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ad/21/17c1bc9e6f47c972ad66fb2ac2568f99f90f1207eeb6fc3b34d094dba7b5/mkdocs_material-9.7.7-py3-none-any.whl", hash = "sha256:8ea9bb1737a5b524a5f9dcf2e1b4ebda8274ae3008aa7845720a97083bef708f", size = 9305438, upload-time = "2026-07-17T16:21:30.017Z" }, + { url = "https://files.pythonhosted.org/packages/c8/16/360f44c7702f27ff4670a647a16c72432291e311371d72b4c34a57e990e0/mkdocs_material-9.8.0-py3-none-any.whl", hash = "sha256:19304a7263c5700428227122b3b2699aa73f432c9de8816876adaec7d7293ce3", size = 9302245, upload-time = "2026-10-24T09:50:12.636Z" }, ] [[package]] @@ -695,15 +695,15 @@ wheels = [ [[package]] name = "pytest-asyncio" -version = "1.4.1" +version = "1.4.1.post1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pytest" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f8/9a/887535e477847f5159377ab35303923644840b13c0ca03c0a467f84d4680/pytest_asyncio-1.4.1.tar.gz", hash = "sha256:e8266eb094e5ee9ffdb2068c9836f33e209ea77a970eb846933d416b5602669b", size = 145237, upload-time = "2026-10-25T21:05:37.135Z" } +sdist = { url = "https://files.pythonhosted.org/packages/73/7f/c60a4338420b33453d4f814ac0c930abd399f162b9bdd21af4b9e363037f/pytest_asyncio-1.4.1.post1.tar.gz", hash = "sha256:f582d9ea4a1c082195abe8bd29a1fe106aeb1cd435e3dad2d3bc2749935c36a2", size = 145360, upload-time = "2026-11-01T18:26:03.732Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/46/d7/cd9e2708afdbf059658adaf08bdb0792ca52489871051d6ce7d498b51277/pytest_asyncio-1.4.1-py3-none-any.whl", hash = "sha256:507afa78ec77c6661164ef1a2368bc7820383fd1a14b2a7f813de8b5a92949cc", size = 17061, upload-time = "2026-10-25T21:05:35.473Z" }, + { url = "https://files.pythonhosted.org/packages/e3/de/adbc7578959cfab07e5e7c05cf6d54224a51e7667ea2c07458b6bc571e75/pytest_asyncio-1.4.1.post1-py3-none-any.whl", hash = "sha256:0755e488cc0a2b9bd2eab7292cc6390d4cbb8390f1020745647bae5a708e0165", size = 17140, upload-time = "2026-11-01T18:26:02.168Z" }, ] [[package]] From a23b611f717189780968babc0971b077c5d5cfbe Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 15:10:48 -0500 Subject: [PATCH 28/47] fix(async): give back the pacing slot on any exception while sleeping SwgohComlinkAsync._admit returned its reserved slot only on asyncio.CancelledError, while the sync client returns it on any exception, KeyboardInterrupt included. A KeyboardInterrupt or other exception raised during an async pacing wait therefore kept the slot, and later calls to the endpoint waited out a call that never ran. Catch BaseException in both, so the clients behave the same and the sync loop can be generated from the async one without a runtime-specific branch. Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/swgoh_comlink_async.py | 7 ++++--- tests/unit/test_retry_core.py | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index d9b5862..c852b57 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -142,14 +142,15 @@ async def _request( 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. + Any exception raised while sleeping (a ``KeyboardInterrupt`` or, in the async client, a cancelled task) + 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: await _retry._async_sleep(wait) - except asyncio.CancelledError: + except BaseException: admission.abandon() raise diff --git a/tests/unit/test_retry_core.py b/tests/unit/test_retry_core.py index a8a5358..cbca188 100644 --- a/tests/unit/test_retry_core.py +++ b/tests/unit/test_retry_core.py @@ -9,7 +9,7 @@ import httpx import pytest -from swgoh_comlink import RetryPolicy, SwgohComlink +from swgoh_comlink import RetryPolicy, SwgohComlink, SwgohComlinkAsync from swgoh_comlink import retry as retry_module from swgoh_comlink.exceptions import ( SwgohComlinkClientError, @@ -229,3 +229,17 @@ def interrupted(seconds: float) -> None: with pytest.raises(KeyboardInterrupt): client.get_game_metadata() assert client._pace_delay("metadata", False) == 1 + + +async def test_async_interrupt_while_pacing_gives_the_slot_back(now: list[float], monkeypatch) -> None: + """The async client releases its slot on any exception while sleeping too, not only on cancellation.""" + + async def interrupted(seconds: float) -> None: + raise KeyboardInterrupt + + async with SwgohComlinkAsync(retry=RetryPolicy(min_interval=1)) as client: + client._pace_delay("metadata", False) + monkeypatch.setattr(retry_module, "_async_sleep", interrupted) + with pytest.raises(KeyboardInterrupt): + await client.get_game_metadata() + assert client._pace_delay("metadata", False) == 1 From 921148b6c64ebb836059753df00a9830e2715b25 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 15:11:06 -0500 Subject: [PATCH 29/47] refactor(core): generate the sync client from the async client swgoh_comlink.py is now generated from swgoh_comlink_async.py by .github/scripts/unasync.py, so the two clients can no longer drift. The script rewrites tokens and then runs ruff to import-sort and format the output. It uses only the standard library and ruff, so no new dependency. - async/await are dropped. - A grouping paren is removed only when it wraps a single awaited primary expression, so precedence cannot change. - Names, dotted names and the asyncio import are renamed from tables at the top of the script. - In docstrings and comments, only those names and the code in examples change. The async client becomes the source. Its runtime-specific prose is made neutral ("an HTTP request", not "an async HTTP request"), and its class docstring gains the context-manager example the sync one had. The generated sync client differs from the hand-written one only by its header and the reworded _admit docstring. CI's lint job runs the script with --check, which prints a diff and fails when swgoh_comlink.py is not what the async client generates. A hand edit to swgoh_comlink.py was shown to fail it. tests/unit/test_unasync.py pins the rewrite rules and checks the committed file is current. CONTRIBUTING.md documents the workflow. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/unasync.py | 235 +++++++++++++++++++++++ .github/workflows/ci.yml | 3 + CONTRIBUTING.md | 22 ++- src/swgoh_comlink/swgoh_comlink.py | 6 +- src/swgoh_comlink/swgoh_comlink_async.py | 11 +- tests/unit/test_unasync.py | 128 ++++++++++++ 6 files changed, 397 insertions(+), 8 deletions(-) create mode 100644 .github/scripts/unasync.py create mode 100644 tests/unit/test_unasync.py diff --git a/.github/scripts/unasync.py b/.github/scripts/unasync.py new file mode 100644 index 0000000..c0be569 --- /dev/null +++ b/.github/scripts/unasync.py @@ -0,0 +1,235 @@ +"""Generate the sync clients from the async ones. + +The async client is the source. Each sync client is its async twin with these token rewrites, passed +through ``ruff`` so it is import-sorted and formatted like any hand-written file: + +* ``async`` before ``def``, ``with`` or ``for`` is dropped, and so is every ``await``. Parentheses that + only group an awaited primary expression, as in ``(await self._get_versions()).require_game()``, go too. +* Names are renamed by :data:`NAME_RENAMES` and dotted names by :data:`DOTTED_RENAMES`; + ``import asyncio`` becomes ``import threading``. +* Docstrings and comments get :data:`NAME_RENAMES` as whole words plus :data:`TEXT_RENAMES`, which turn + the code in examples sync. Everything else in them is copied verbatim, so their prose must hold for both + runtimes. + +Usage:: + + uv run python .github/scripts/unasync.py # rewrite the sync files + uv run python .github/scripts/unasync.py --check # exit 1 and print a diff when one is out of date + +Only the standard library and ``ruff``, already a dev dependency, are used. +""" + +from __future__ import annotations + +import argparse +import difflib +import io +import keyword +import re +import shutil +import subprocess +import sys +import tokenize +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +PACKAGE = ROOT / "src" / "swgoh_comlink" + +#: (async source, sync target) pairs, relative to the package directory. +FILES: tuple[tuple[str, str], ...] = (("swgoh_comlink_async.py", "swgoh_comlink.py"),) + +#: Whole-name renames, applied to NAME tokens in code and as whole words in docstrings and comments. +NAME_RENAMES: dict[str, str] = { + "SwgohComlinkAsync": "SwgohComlink", + "swgoh_comlink_async": "swgoh_comlink", + "AsyncClient": "Client", + "aclose": "close", + "__aenter__": "__enter__", + "__aexit__": "__exit__", + "aiter_bytes": "iter_bytes", + "_async_sleep": "_sleep", +} + +#: Dotted-name renames in code, matched as ``NAME . NAME``. +DOTTED_RENAMES: dict[tuple[str, str], tuple[str, str]] = {("asyncio", "Lock"): ("threading", "Lock")} + +#: Module renames in a bare ``import x`` statement. +IMPORT_RENAMES: dict[str, str] = {"asyncio": "threading"} + +#: Extra regex renames for docstrings and comments: the runtime adjective and the code in examples. +TEXT_RENAMES: tuple[tuple[str, str], ...] = ( + (r"\bAsynchronous\b", "Synchronous"), + (r"\basync (def|with|for)\b", r"\1"), + (r"\bawait\s+", ""), +) + +HEADER = "# GENERATED from {source} by .github/scripts/unasync.py. Do not edit: change the source and rerun.\n" + +_TEXT_PATTERNS = tuple( + (re.compile(pattern), new) + for pattern, new in [*((rf"\b{re.escape(old)}\b", new) for old, new in NAME_RENAMES.items()), *TEXT_RENAMES] +) + +# Tokens after which ``(`` opens a call or subscript rather than a group. +_CALLABLE_ENDS = {")", "]"} + + +def _rename_text(text: str) -> str: + for pattern, replacement in _TEXT_PATTERNS: + text = pattern.sub(replacement, text) + return text + + +def _closing_paren(tokens: list[tokenize.TokenInfo], open_index: int) -> int: + """Index of the token that closes the bracket at *open_index*.""" + depth = 0 + for j in range(open_index, len(tokens)): + if tokens[j].string in "([{": + depth += 1 + elif tokens[j].string in ")]}": + depth -= 1 + if depth == 0: + return j + raise ValueError(f"unbalanced bracket at line {tokens[open_index].start[0]}") + + +def _is_grouping_paren(tokens: list[tokenize.TokenInfo], index: int) -> bool: + """Whether the ``(`` at *index* groups an expression instead of opening a call or a subscript.""" + if index == 0: + return True + before = tokens[index - 1] + if before.type == tokenize.NAME: + return keyword.iskeyword(before.string) and before.string not in ("True", "False", "None") + return before.string not in _CALLABLE_ENDS and before.type not in (tokenize.STRING, tokenize.NUMBER) + + +def _is_primary(tokens: list[tokenize.TokenInfo], start: int, stop: int) -> bool: + """Whether ``tokens[start:stop]`` is one primary expression: names, dots, calls and subscripts only.""" + j = start + while j < stop: + tok = tokens[j] + if tok.string in "([": + j = _closing_paren(tokens, j) + 1 + elif tok.type == tokenize.NAME and not keyword.iskeyword(tok.string) or tok.string == ".": + j += 1 + else: + return False + return True + + +def _ends_line(tok: tokenize.TokenInfo | None) -> bool: + return tok is None or tok.type == tokenize.NEWLINE + + +def unasync_source(source: str) -> str: + """Rewrite async Python *source* as its sync twin, before import sorting and formatting.""" + line_starts = [0] + for line in source.splitlines(keepends=True): + line_starts.append(line_starts[-1] + len(line)) + + def offset(point: tuple[int, int]) -> int: + return line_starts[point[0] - 1] + point[1] + + skipped = (tokenize.NL, tokenize.INDENT, tokenize.DEDENT, tokenize.ENDMARKER) + tokens = [t for t in tokenize.generate_tokens(io.StringIO(source).readline) if t.type not in skipped] + edits: dict[int, tuple[int, str]] = {} # start offset -> (end offset, replacement) + + def replace(first: tokenize.TokenInfo, until: tokenize.TokenInfo | None, text: str) -> None: + """Replace from the start of *first* to the start of *until* (or the end of *first*) with *text*.""" + end = offset(until.start) if until is not None else offset(first.end) + edits[offset(first.start)] = (end, text) + + for i, tok in enumerate(tokens): + prev = tokens[i - 1] if i else None + nxt = tokens[i + 1] if i + 1 < len(tokens) else None + if tok.type in (tokenize.STRING, tokenize.COMMENT): + if (renamed := _rename_text(tok.string)) != tok.string: + replace(tok, None, renamed) + elif tok.type != tokenize.NAME: + continue + elif tok.string == "async" and nxt is not None and nxt.string in ("def", "with", "for"): + replace(tok, nxt, "") + elif tok.string == "await": + assert nxt is not None + replace(tok, nxt, "") + if prev is not None and prev.string == "(" and _is_grouping_paren(tokens, i - 1): + close = _closing_paren(tokens, i - 1) + if _is_primary(tokens, i + 1, close): + replace(prev, tok, "") + replace(tokens[close], None, "") + elif prev is not None and prev.string == "import" and tok.string in IMPORT_RENAMES and _ends_line(nxt): + replace(tok, None, IMPORT_RENAMES[tok.string]) + elif nxt is not None and nxt.string == "." and i + 2 < len(tokens): + pair = (tok.string, tokens[i + 2].string) + if pair in DOTTED_RENAMES: + replace(tok, None, DOTTED_RENAMES[pair][0]) + replace(tokens[i + 2], None, DOTTED_RENAMES[pair][1]) + elif tok.string in NAME_RENAMES: + replace(tok, None, NAME_RENAMES[tok.string]) + elif tok.string in NAME_RENAMES: + replace(tok, None, NAME_RENAMES[tok.string]) + + out = source + for start in sorted(edits, reverse=True): + end, text = edits[start] + out = out[:start] + text + out[end:] + return out + + +def _ruff(source: str, filename: Path) -> str: + """Import-sort and format *source* with the project's ruff settings.""" + ruff = shutil.which("ruff") + if ruff is None: + raise SystemExit("ruff not found: run this through `uv run` so the dev dependencies are on PATH.") + for args in (["check", "--select", "I", "--fix", "--exit-zero", "--quiet"], ["format", "--quiet"]): + source = subprocess.run( + [ruff, *args, "--stdin-filename", str(filename), "-"], + input=source, + capture_output=True, + text=True, + check=True, + cwd=ROOT, + ).stdout + return source + + +def generate(source_path: Path, target_path: Path) -> str: + """The text *source_path* generates for *target_path*, header included.""" + body = unasync_source(source_path.read_text(encoding="utf-8")) + header = HEADER.format(source=source_path.name) + # A leading ``# coding`` line must stay first; the header follows it. + first, sep, rest = body.partition("\n") + body = f"{first}{sep}{header}{rest}" if first.startswith("# coding") else header + body + return _ruff(body, target_path) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Generate the sync clients from the async ones.") + parser.add_argument("--check", action="store_true", help="exit 1 and print a diff when a sync file is stale") + args = parser.parse_args(argv) + stale = [] + for source_name, target_name in FILES: + source_path, target_path = PACKAGE / source_name, PACKAGE / target_name + expected = generate(source_path, target_path) + current = target_path.read_text(encoding="utf-8") if target_path.exists() else "" + if current == expected: + continue + rel = target_path.relative_to(ROOT).as_posix() + if args.check: + stale.append(rel) + sys.stdout.writelines( + difflib.unified_diff( + current.splitlines(keepends=True), expected.splitlines(keepends=True), rel, f"{rel} (generated)" + ) + ) + else: + target_path.write_text(expected, encoding="utf-8") + print(f"wrote {rel}") + if stale: + print(f"\nOut of date: {', '.join(stale)}. Run `uv run python .github/scripts/unasync.py`.", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 75d2c75..275e20f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,9 @@ jobs: - name: Run Ruff formatter check run: uv run --no-sync ruff format --check src/ tests/ examples/ parity/ + - name: Check the generated sync client is current + run: uv run --no-sync python .github/scripts/unasync.py --check + # ── Type check ───────────────────────────────────────────────────────── type-check: name: Type Check diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cd975ea..328802e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -168,7 +168,7 @@ comlink-python/ │ ├── globals.py # Logging configuration │ ├── py.typed # PEP 561 marker: the package ships inline type hints │ ├── retry.py # Retry/backoff configuration -│ ├── swgoh_comlink.py # SwgohComlink (sync client) +│ ├── swgoh_comlink.py # SwgohComlink (sync client, generated from the async one) │ ├── swgoh_comlink_async.py # SwgohComlinkAsync (async client) │ └── version.py # Exposes __version__ (derived from the Git tag via hatch-vcs) ├── tests/ @@ -197,8 +197,8 @@ comlink-python/ | Module | Purpose | |--------|---------| | `_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) | +| `swgoh_comlink_async.py` | `SwgohComlinkAsync` — asynchronous HTTP client and the **source** of both clients: edit this one | +| `swgoh_comlink.py` | `SwgohComlink` — synchronous HTTP client, **generated** from `swgoh_comlink_async.py`; never edit it by hand | | `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 | @@ -206,6 +206,22 @@ comlink-python/ | `globals.py` | Shared logging setup (`get_logger()`) | | `version.py` | Exposes `__version__`, derived from the Git tag at build time via hatch-vcs | +### Changing a client + +The sync client is generated. Make every client change in `swgoh_comlink_async.py`, then regenerate: + +```bash +uv run python .github/scripts/unasync.py +``` + +Commit both files. CI runs the same script with `--check` and fails when `swgoh_comlink.py` is not what the +async client generates to, so a hand edit to it fails the build. + +The generator drops `async`/`await` and renames async names (`SwgohComlinkAsync`, `AsyncClient`, `aclose`, +`asyncio.Lock`, …) to their sync twins. In docstrings and comments it renames the same names and turns +example code sync, and copies the rest verbatim, so write prose that holds for both clients. The rename +tables are at the top of `.github/scripts/unasync.py`; extend them rather than special-casing a file. + --- ## Making Changes diff --git a/src/swgoh_comlink/swgoh_comlink.py b/src/swgoh_comlink/swgoh_comlink.py index a70ff84..33bf4e7 100644 --- a/src/swgoh_comlink/swgoh_comlink.py +++ b/src/swgoh_comlink/swgoh_comlink.py @@ -1,4 +1,5 @@ # coding=utf-8 +# GENERATED from swgoh_comlink_async.py by .github/scripts/unasync.py. Do not edit: change the source and rerun. """ Synchronous Python 3 interface for swgoh-comlink. """ @@ -147,8 +148,9 @@ def _request( 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. + Any exception raised while sleeping (a ``KeyboardInterrupt`` or, in the async client, a cancelled task) + 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: diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index c852b57..c2c260d 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -73,6 +73,11 @@ class SwgohComlinkAsync(SwgohComlinkBase): Examples: Basic usage:: + comlink = SwgohComlinkAsync() + player = await comlink.get_player(allycode=123456789) + + As a context manager:: + async with SwgohComlinkAsync() as comlink: player = await comlink.get_player(allycode=123456789) """ @@ -106,7 +111,7 @@ async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseExc await self.aclose() async def aclose(self) -> None: - """Close the underlying async HTTP client connections.""" + """Close the underlying HTTP client connections.""" await self.client.aclose() await self.stats_client.aclose() @@ -118,7 +123,7 @@ async def _request( stats: bool = False, timeout: float | None = None, ) -> dict[str, Any] | list[Any]: - """Send an async HTTP request to the comlink service: the single gateway for all HTTP communication. + """Send an HTTP request to the comlink service: the single gateway for all HTTP communication. 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. @@ -209,7 +214,7 @@ async def _post( stats: bool = False, timeout: float | None = None, ) -> dict[str, Any] | list[Any]: - """Send an async POST request to the comlink service. + """Send a POST request to the comlink service. Convenience wrapper around :meth:`_request`. """ diff --git a/tests/unit/test_unasync.py b/tests/unit/test_unasync.py new file mode 100644 index 0000000..36084ca --- /dev/null +++ b/tests/unit/test_unasync.py @@ -0,0 +1,128 @@ +"""The async -> sync generator in ``.github/scripts/unasync.py``, and the sync client it keeps current.""" + +from __future__ import annotations + +import importlib.util +import shutil +import sys +from pathlib import Path +from types import ModuleType + +import pytest + +SCRIPT = Path(__file__).resolve().parents[2] / ".github" / "scripts" / "unasync.py" + + +def _load() -> ModuleType: + spec = importlib.util.spec_from_file_location("unasync_script", SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +unasync = _load() + + +@pytest.mark.parametrize( + ("source", "expected"), + [ + pytest.param("async def f():\n pass\n", "def f():\n pass\n", id="async-def"), + pytest.param("async with a as b:\n pass\n", "with a as b:\n pass\n", id="async-with"), + pytest.param("async for x in y:\n pass\n", "for x in y:\n pass\n", id="async-for"), + pytest.param("x = await f(1)\n", "x = f(1)\n", id="await"), + pytest.param("return await self._post(a, b)\n", "return self._post(a, b)\n", id="await-return"), + ], +) +def test_async_keywords_are_dropped(source: str, expected: str) -> None: + assert unasync.unasync_source(source) == expected + + +@pytest.mark.parametrize( + ("source", "expected"), + [ + pytest.param("v = (await self.get()).version\n", "v = self.get().version\n", id="attribute-on-awaited-call"), + pytest.param("v = (await self.get(x=1))[0]\n", "v = self.get(x=1)[0]\n", id="subscript-on-awaited-call"), + pytest.param("return (await f())\n", "return f()\n", id="after-keyword"), + pytest.param("y = g(await f())\n", "y = g(f())\n", id="call-paren-kept"), + # Not a single primary: dropping the group would change precedence (x * a + b). + pytest.param("y = x * (await a + b)\n", "y = x * (a + b)\n", id="operator-group-kept"), + pytest.param("y = (await a) if c else d\n", "y = a if c else d\n", id="name-only"), + ], +) +def test_grouping_parens_go_only_around_a_single_primary(source: str, expected: str) -> None: + assert unasync.unasync_source(source) == expected + + +def test_names_dotted_names_and_imports_are_renamed() -> None: + source = ( + "import asyncio\n" + "class SwgohComlinkAsync(Base):\n" + " async def __aenter__(self): ...\n" + " async def aclose(self):\n" + " self._lock = asyncio.Lock()\n" + " await self.client.aclose()\n" + " client: httpx.AsyncClient\n" + " await _retry._async_sleep(1)\n" + " async for chunk in r.aiter_bytes(): ...\n" + ) + assert unasync.unasync_source(source) == ( + "import threading\n" + "class SwgohComlink(Base):\n" + " def __enter__(self): ...\n" + " def close(self):\n" + " self._lock = threading.Lock()\n" + " self.client.close()\n" + " client: httpx.Client\n" + " _retry._sleep(1)\n" + " for chunk in r.iter_bytes(): ...\n" + ) + + +def test_asyncio_names_other_than_lock_are_left_for_review() -> None: + """Only ``asyncio.Lock`` has a known sync twin; anything else must stay visible in the generated file.""" + assert unasync.unasync_source("except asyncio.CancelledError:\n") == "except asyncio.CancelledError:\n" + + +def test_docstrings_and_comments_get_names_and_example_code_only() -> None: + source = ( + "def f():\n" + ' """Asynchronous interface; see :class:`SwgohComlinkAsync` and :meth:`aclose`.\n' + "\n" + " Example::\n" + "\n" + " async with SwgohComlinkAsync() as comlink:\n" + " player = await comlink.get_player()\n" + "\n" + " The async client and asynchronous callers are described as written.\n" + ' """\n' + " # SwgohComlinkAsync keeps one pool\n" + ) + assert unasync.unasync_source(source) == ( + "def f():\n" + ' """Synchronous interface; see :class:`SwgohComlink` and :meth:`close`.\n' + "\n" + " Example::\n" + "\n" + " with SwgohComlink() as comlink:\n" + " player = comlink.get_player()\n" + "\n" + " The async client and asynchronous callers are described as written.\n" + ' """\n' + " # SwgohComlink keeps one pool\n" + ) + + +def test_names_that_merely_contain_a_renamed_name_are_untouched() -> None: + source = "SwgohComlinkAsyncFactory = aclose_all\n" + assert unasync.unasync_source(source) == source + + +@pytest.mark.skipif(shutil.which("ruff") is None, reason="ruff formats the generated file; the lint job runs this") +def test_committed_sync_clients_are_what_the_async_ones_generate() -> None: + for source_name, target_name in unasync.FILES: + target = unasync.PACKAGE / target_name + assert target.read_text(encoding="utf-8") == unasync.generate(unasync.PACKAGE / source_name, target), ( + f"{target_name} is out of date or was edited by hand: run `uv run python .github/scripts/unasync.py`." + ) From 374541ad5d564a931e3e589973346b107426618c Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 17:07:00 -0500 Subject: [PATCH 30/47] fix(client): attribute the credential deprecation warning past in-package subclasses A fixed stacklevel=4 assumed the client's own __init__ was the only frame between the caller and SwgohComlinkBase. A subclass defined inside the package adds one more, so the warning blamed that subclass's module and deduped onto its line. Count frames inside the package instead; skip_file_prefixes would do it but needs Python 3.12. Subclasses in user code are unchanged: the warning still points at their super().__init__ call, the first frame outside the package. Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/_base.py | 24 ++++++++++++++++++++++-- tests/unit/test_credential_env.py | 27 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 3e3dcff..5c85045 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -12,6 +12,7 @@ import logging import os import re +import sys import time import warnings from collections.abc import Callable @@ -138,6 +139,26 @@ def sanitize_url(url: str) -> str: return url +# Directory of this package, so a warning can be attributed to the first frame outside it. +_PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__)) + os.sep + + +def _stacklevel_outside_package() -> int: + """The ``stacklevel`` that makes the calling function's warning point at the first frame outside the package. + + A fixed number assumes a fixed call depth, which a subclass's ``__init__`` breaks: a subclass defined in + the package adds a frame, and a fixed level would blame its constructor instead of the code that built + the client. + ``warnings.warn(skip_file_prefixes=...)`` does this natively but needs Python 3.12. + """ + frame = sys._getframe(1) # the function about to warn: stacklevel 1 + level = 1 + while frame is not None and frame.f_code.co_filename.startswith(_PACKAGE_DIR): + frame = frame.f_back + level += 1 + return level + + 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) @@ -342,12 +363,11 @@ def _resolve_credentials(access_key: str | None, secret_key: str | None) -> tupl 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, + stacklevel=_stacklevel_outside_package(), ) access, secret = (arg or value for arg, value in zip(args, env_values, strict=True)) return access, secret diff --git a/tests/unit/test_credential_env.py b/tests/unit/test_credential_env.py index a23f5b6..387b0e0 100644 --- a/tests/unit/test_credential_env.py +++ b/tests/unit/test_credential_env.py @@ -3,11 +3,13 @@ from __future__ import annotations import logging +import os import warnings from collections.abc import Callable import pytest +import swgoh_comlink from swgoh_comlink import SwgohComlink, SwgohComlinkAsync Client = SwgohComlink | SwgohComlinkAsync @@ -91,6 +93,31 @@ async def test_async_deprecation_points_at_the_caller(monkeypatch: pytest.Monkey assert record[0].filename == __file__ +@pytest.mark.parametrize("parent", [SwgohComlink, SwgohComlinkAsync]) +async def test_deprecation_skips_a_subclass_inside_the_package( + parent: type[Client], monkeypatch: pytest.MonkeyPatch +) -> None: + """A subclass in the package adds a frame; the warning must still blame the code that built the client. + + The subclass is compiled under a file name inside the package, as a module there would be, so nothing is written. + """ + in_package = os.path.join(os.path.dirname(swgoh_comlink.__file__), "_subclass_under_test.py") + source = "class Child(Parent):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n" + namespace: dict[str, object] = {"Parent": parent} + exec(compile(source, in_package, "exec"), namespace) + child = namespace["Child"] + assert isinstance(child, type) + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + with pytest.warns(DeprecationWarning) as record: + client = child() + if isinstance(client, SwgohComlinkAsync): + await client.aclose() + else: + client.close() + assert record[0].filename == __file__ + + def test_constructor_arguments_beat_all_env_vars( make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch ) -> None: From a7d47ca89901b11cdbef17857b1aecba25913c47 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 12:59:58 -0500 Subject: [PATCH 31/47] chore(ci): regenerate the sync client in a pre-commit hook CI's lint job only checks that swgoh_comlink.py is current, so a forgotten regeneration surfaced at PR time. A local pre-commit hook now runs .github/scripts/unasync.py whenever either client or the generator is staged. When the file changes, the hook fails the commit; stage it and commit again. A hand edit to swgoh_comlink.py is overwritten the same way. It follows the existing local hooks (uv run, language: system) so ruff comes from uv.lock, as in CI. pre-commit sets unstaged changes aside first, so the generated file reflects only what is staged. CONTRIBUTING.md mentions the hook. Co-Authored-By: Claude Opus 5.5 --- .pre-commit-config.yaml | 14 ++++++++++++++ CONTRIBUTING.md | 8 +++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8ae997e..9824dd9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -34,6 +34,20 @@ repos: types: [python] require_serial: true + # ── Generated sync client (mirrors CI's `unasync.py --check`) ───────── + # Regenerates swgoh_comlink.py whenever the async client, the sync client or the + # generator is staged. A changed file fails the hook, so stage it and commit again; + # a hand edit to swgoh_comlink.py is overwritten the same way. + - repo: local + hooks: + - id: unasync + name: generate sync client + entry: uv run python .github/scripts/unasync.py + language: system + files: ^(src/swgoh_comlink/swgoh_comlink(_async)?\.py|\.github/scripts/unasync\.py)$ + pass_filenames: false + require_serial: true + # ── ty type checking (Astral, run via local uv) ─────────────────────── - repo: local hooks: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 328802e..d313e53 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,7 +92,7 @@ This project follows the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT. Run tools with `uv run ` — there is no need to activate the virtual environment. -4. **Install the pre-commit hooks** (runs Ruff, ty, and commitlint before each commit) +4. **Install the pre-commit hooks** (runs Ruff, ty, the sync-client generator, and commitlint before each commit) ```bash uvx pre-commit install --hook-type pre-commit --hook-type commit-msg @@ -214,8 +214,10 @@ The sync client is generated. Make every client change in `swgoh_comlink_async.p uv run python .github/scripts/unasync.py ``` -Commit both files. CI runs the same script with `--check` and fails when `swgoh_comlink.py` is not what the -async client generates to, so a hand edit to it fails the build. +Commit both files. With the pre-commit hooks installed you can skip the manual run: the `unasync` hook +regenerates `swgoh_comlink.py` whenever either client or the generator is staged, and stops the commit if the +file changed, so stage it and commit again. CI runs the same script with `--check` and fails when +`swgoh_comlink.py` is not what the async client generates to, so a hand edit to it fails the build. The generator drops `async`/`await` and renames async names (`SwgohComlinkAsync`, `AsyncClient`, `aclose`, `asyncio.Lock`, …) to their sync twins. In docstrings and comments it renames the same names and turns From 4f7e96e23227d092ab8bdb1118ce227e1bb667f8 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 2 Nov 2026 13:34:29 -0500 Subject: [PATCH 32/47] feat(helpers): accept type-prefixed enum names in guild roles and item names With enums=True, the public Comlink sends bare enum member names (GUILD_MEMBER, SEVEN_STAR, STATMOD_SLOT_02), which the helpers already read. A server may instead spell a value with its enum type as a prefix and no inner underscores (GUILDMEMBERLEVEL_GUILDMEMBER, RARITY_SEVENSTAR, STATMODSLOT_STATMODSLOT02). get_guild_activity and ItemNames/get_mod_catalog did not recognise that spelling: a member's role read as None and mod slots, tiers and rarities as unknown. Both now resolve names through parse_enum, which reads either spelling and checks the prefix against the enum's own type name, so a value from another enum is still rejected. Results for the bare spelling and for numbers are unchanged. Also update the territoryBattleVersion_3 comment: it is the spelling current servers send, and territoryBattleVersion3 is kept for older ones. Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/helpers/_guild.py | 16 ++++---- src/swgoh_comlink/helpers/_items.py | 38 ++++++++++++------- .../helpers/_territory_battle.py | 3 +- tests/unit/test_helpers.py | 24 +++++++++--- 4 files changed, 54 insertions(+), 27 deletions(-) diff --git a/src/swgoh_comlink/helpers/_guild.py b/src/swgoh_comlink/helpers/_guild.py index a0f9134..d7149a5 100644 --- a/src/swgoh_comlink/helpers/_guild.py +++ b/src/swgoh_comlink/helpers/_guild.py @@ -9,22 +9,20 @@ from ..exceptions import SwgohComlinkValueError from ._utils import _client_kind, get_function_name, sanitize_allycode -from ._wire import as_int +from ._wire import as_int, parse_enum if TYPE_CHECKING: from swgoh_comlink import SwgohComlink, SwgohComlinkAsync -# memberLevel (GuildMemberLevel), looked up as text: an integer (enums=False) or its enum name (enums=True) +# GuildMemberLevel members and their roles. memberLevel arrives as a number (enums=False) or a member name +# (enums=True), bare (GUILD_MEMBER) or type-prefixed (GUILDMEMBERLEVEL_GUILDMEMBER); parse_enum reads all three. _MEMBER_ROLES: dict[str, tuple[int, str]] = { - "1": (1, "Pending"), - "2": (2, "Member"), - "3": (3, "Officer"), - "4": (4, "Leader"), "GUILD_PENDING": (1, "Pending"), "GUILD_MEMBER": (2, "Member"), "GUILD_OFFICER": (3, "Officer"), "GUILD_LEADER": (4, "Leader"), } +_MEMBER_LEVELS = {name: level for name, (level, _) in _MEMBER_ROLES.items()} class TerritoryBattleResult(TypedDict): @@ -210,7 +208,8 @@ def get_guild_activity(guild: dict[str, Any]) -> GuildActivity: The payload's numbers are read whether they arrive as integers or as strings. Member join times (``guildJoinTime``) are epoch **seconds**, while ``lastActivityTime`` is epoch milliseconds; both are returned as datetimes, and a missing or zero value as ``None``. ``memberLevel`` is read as a number - or as its ``GuildMemberLevel`` enum name (``enums=True``). + or as its ``GuildMemberLevel`` enum name (``enums=True``), bare (``GUILD_MEMBER``) or type-prefixed + (``GUILDMEMBERLEVEL_GUILDMEMBER``). Args: guild: The response from ``SwgohComlink.get_guild(..., include_recent_guild_activity_info=True)``. @@ -272,7 +271,8 @@ def get_guild_activity(guild: dict[str, Any]) -> GuildActivity: member_activity: list[GuildMemberActivity] = [] for member in members: - level, role = _MEMBER_ROLES.get(str(member.get("memberLevel")), (None, None)) + level_name = parse_enum(member.get("memberLevel"), _MEMBER_LEVELS, enum_name="GuildMemberLevel") + level, role = _MEMBER_ROLES.get(level_name or "", (None, None)) player_id = member.get("playerId", "") member_activity.append( { diff --git a/src/swgoh_comlink/helpers/_items.py b/src/swgoh_comlink/helpers/_items.py index f95fc18..a54aa4b 100644 --- a/src/swgoh_comlink/helpers/_items.py +++ b/src/swgoh_comlink/helpers/_items.py @@ -9,6 +9,7 @@ from ..exceptions import SwgohComlinkValueError from ._localization import _localize from ._stat_data import CURRENCY_NAMES, CURRENCY_TYPES, ITEM_TYPES, MOD_SET_IDS, MOD_SLOTS, UNIT_RARITY_NAMES +from ._wire import parse_enum _ITEM_TYPE_NUMBERS = {name: number for number, name in ITEM_TYPES.items()} _UNIT = _ITEM_TYPE_NUMBERS["UNIT"] @@ -39,8 +40,9 @@ # A unit shard is a material whose id is the unit's baseId behind this prefix. _SHARD_PREFIX = "unitshard_" -# Enum member names that game data fetched with enums=True carries in place of the numbers. StatModSlot -# numbers start at 2: STATMOD_SLOT_01 is the Square (see MOD_SLOTS). +# Enum member names that game data fetched with enums=True carries in place of the numbers, bare +# (STATMOD_SLOT_01) or type-prefixed (STATMODSLOT_STATMODSLOT01). StatModSlot numbers start at 2: +# STATMOD_SLOT_01 is the Square (see MOD_SLOTS). _MOD_SLOT_ENUMS = {f"STATMOD_SLOT_{n:02d}": n + 1 for n in range(1, 7)} _MOD_TIER_ENUMS = {f"STATMOD_TIER_{n:02d}": n for n in range(1, 6)} # Rarity also has NO_STAR (8), which UNIT_RARITY_NAMES leaves out. @@ -102,8 +104,13 @@ class NamedReward(TypedDict): paid; otherwise ``None``.""" -def _as_int(value: Any, enum_names: Mapping[str, int] | None = None) -> int | None: - """Read an int field that may hold a number, a numeric string or (with ``enums=True``) an enum name.""" +def _as_int(value: Any, enum_names: Mapping[str, int] | None = None, enum_name: str | None = None) -> int | None: + """Read an int field that may hold a number, a numeric string or (with ``enums=True``) an enum name. + + A name is matched by :func:`parse_enum`, so the type-prefixed spelling some servers send + (``RARITY_SEVENSTAR``) reads like the bare one (``SEVEN_STAR``). *enum_name* is the enum's type name, + which that prefix must match. + """ if isinstance(value, bool): return None if isinstance(value, int): @@ -111,8 +118,8 @@ def _as_int(value: Any, enum_names: Mapping[str, int] | None = None) -> int | No if isinstance(value, str): if value.lstrip("-").isdigit(): return int(value) - if enum_names is not None: - return enum_names.get(value) + if enum_names is not None and (name := parse_enum(value, enum_names, enum_name=enum_name)) is not None: + return enum_names[name] return None @@ -295,14 +302,14 @@ def get_mod_catalog( if not isinstance(mod, dict) or not mod.get("id"): continue set_id = str(mod.get("setId", "")) - slot = _as_int(mod.get("slot"), _MOD_SLOT_ENUMS) or 0 + slot = _as_int(mod.get("slot"), _MOD_SLOT_ENUMS, "StatModSlot") or 0 definitions[mod["id"]] = { "definition_id": mod["id"], "set_id": set_id, "set_name": set_names.get(set_id) or MOD_SET_IDS.get(set_id, set_id), "slot": slot, "slot_name": MOD_SLOTS.get(str(slot), ""), - "rarity": _as_int(mod.get("rarity"), _RARITY_ENUMS) or 0, + "rarity": _as_int(mod.get("rarity"), _RARITY_ENUMS, "Rarity") or 0, } return {"sets": sets, "definitions": definitions} @@ -434,13 +441,18 @@ def _mystery_mod_name(self, item_id: str) -> str | None: mod = self._mystery_mods.get(item_id) if mod is None: return None - pips = _range(_as_int(mod.get("minRarity"), _RARITY_ENUMS), _as_int(mod.get("maxRarity"), _RARITY_ENUMS)) + pips = _range( + _as_int(mod.get("minRarity"), _RARITY_ENUMS, "Rarity"), + _as_int(mod.get("maxRarity"), _RARITY_ENUMS, "Rarity"), + ) tier = _range( - _as_int(mod.get("minTier"), _MOD_TIER_ENUMS), - _as_int(mod.get("maxTier"), _MOD_TIER_ENUMS), + _as_int(mod.get("minTier"), _MOD_TIER_ENUMS, "StatModTier"), + _as_int(mod.get("maxTier"), _MOD_TIER_ENUMS, "StatModTier"), _MOD_TIER_LETTERS, ) - slots = [MOD_SLOTS.get(str(_as_int(slot, _MOD_SLOT_ENUMS)), "?") for slot in mod.get("slot") or []] + slots = [ + MOD_SLOTS.get(str(_as_int(slot, _MOD_SLOT_ENUMS, "StatModSlot")), "?") for slot in mod.get("slot") or [] + ] slot = "any-slot" if len(set(slots)) >= len(MOD_SLOTS) else " or ".join(slots) set_id = str(mod.get("setId", "")) set_name = self._mod_sets.get(set_id) or MOD_SET_IDS.get(set_id, "") @@ -469,7 +481,7 @@ def item_type_number(self, item_type: Any) -> int | None: Returns ``None`` for a member name this instance's table does not list. """ - return _as_int(item_type, self._item_type_numbers) + return _as_int(item_type, self._item_type_numbers, "ItemType") def item_type_name(self, number: int) -> str | None: """Return the ``ItemType`` member name for a number, or ``None`` when the table does not list it.""" diff --git a/src/swgoh_comlink/helpers/_territory_battle.py b/src/swgoh_comlink/helpers/_territory_battle.py index de3b1c5..9b27cc7 100644 --- a/src/swgoh_comlink/helpers/_territory_battle.py +++ b/src/swgoh_comlink/helpers/_territory_battle.py @@ -24,7 +24,8 @@ # Over a third of the game's categories key their name as the literal 'PLACEHOLDER'; none is a real name. _PLACEHOLDER = "PLACEHOLDER" _SCORE_ROW = "GALACTIC_SCORE" -# The dump of the game data spells the flag with an underscore; Comlink sends it without. +# The game data dump and current servers spell the flag with an underscore; some older servers sent it +# without. _VERSION_3_KEYS = ("territoryBattleVersion3", "territoryBattleVersion_3") # int32 max: the game's "no limit" for maxUnitCountPerPlayer and maxAttemptsAllowed. _UNLIMITED = 2**31 - 1 diff --git a/tests/unit/test_helpers.py b/tests/unit/test_helpers.py index e6c058d..065bc53 100644 --- a/tests/unit/test_helpers.py +++ b/tests/unit/test_helpers.py @@ -1150,6 +1150,10 @@ def test_members(self): ("GUILD_MEMBER", (2, "Member")), ("GUILD_OFFICER", (3, "Officer")), ("GUILD_LEADER", (4, "Leader")), + # The type-prefixed spelling some servers send; another enum's prefix is not read. + ("GUILDMEMBERLEVEL_GUILDMEMBER", (2, "Member")), + ("GUILDMEMBERLEVEL_GUILDLEADER", (4, "Leader")), + ("RARITY_GUILDMEMBER", (None, None)), (0, (None, None)), (None, (None, None)), ([4], (None, None)), @@ -1806,6 +1810,9 @@ def test_wire_docstring_examples(): # Game data fetched with enums=True carries enum names in place of the numbers. {"id": "enum", "slot": ["STATMOD_SLOT_02"], "setId": "4", "minRarity": "SIX_STAR", "maxRarity": "SIX_STAR", "minTier": "STATMOD_TIER_05", "maxTier": "STATMOD_TIER_05"}, + # Some servers spell them prefixed with their type and without inner underscores. + {"id": "enum_prefixed", "slot": ["STATMODSLOT_STATMODSLOT02"], "setId": "4", "minRarity": "RARITY_SIXSTAR", + "maxRarity": "RARITY_SIXSTAR", "minTier": "STATMODTIER_STATMODTIER05", "maxTier": "STATMODTIER_STATMODTIER05"}, # Unreadable rarities are shown as "?". {"id": "unreadable", "slot": [2], "setId": "4", "minRarity": True, "maxRarity": None, "minTier": 1, "maxTier": 1}, @@ -1863,6 +1870,8 @@ class TestGetModCatalog: _STAT_MODS: list[dict[str, Any]] = [ {"id": "451", "setId": "4", "slot": 2, "rarity": 5}, {"id": "137", "setId": "3", "slot": "STATMOD_SLOT_06", "rarity": "SEVEN_STAR"}, + {"id": "138", "setId": "3", "slot": "STATMODSLOT_STATMODSLOT06", "rarity": "RARITY_SEVENSTAR"}, + {"id": "139", "setId": "3", "slot": "RARITY_STATMODSLOT06", "rarity": "STATMODSLOT_SEVENSTAR"}, {"id": "999", "setId": "9", "slot": 4, "rarity": 1}, ] @@ -1882,6 +1891,9 @@ def test_sets_and_definitions(self): # Enum names (enums=True) are read as their numbers. assert catalog["definitions"]["137"]["slot"] == 7 assert catalog["definitions"]["137"]["rarity"] == 7 + # So are the type-prefixed spellings, but only under their own type's prefix. + assert (catalog["definitions"]["138"]["slot"], catalog["definitions"]["138"]["rarity"]) == (7, 7) + assert (catalog["definitions"]["139"]["slot"], catalog["definitions"]["139"]["rarity"]) == (0, 0) # A set statModSet does not list keeps its id as its name. assert catalog["definitions"]["999"]["set_name"] == "9" @@ -1924,6 +1936,8 @@ class TestItemNames: ("MYSTERY_STAT_MOD", "11112", "1-2-dot Speed any-slot mod (E-D)"), (16, "two", "5-dot Speed Square or Arrow mod (E)"), (16, "enum", "6-dot Speed Arrow mod (A)"), + (16, "enum_prefixed", "6-dot Speed Arrow mod (A)"), + ("ITEMTYPE_MYSTERYSTATMOD", "enum_prefixed", "6-dot Speed Arrow mod (A)"), (16, "unreadable", "?-dot Speed Square mod (E)"), ], ) @@ -2178,8 +2192,8 @@ def _tb_platoon(platoon_id: str, points: str, reward_type: Any = 1) -> dict[str, }, { "id": "t05D", - # Comlink's spelling; the on-disk dump of the game data spells it territoryBattleVersion_3. - "territoryBattleVersion3": True, + # The current spelling; some older servers sent territoryBattleVersion3. + "territoryBattleVersion_3": True, "conflictZoneDefinition": [ { "zoneDefinition": _tb_zone("tb3_phase01_conflict01", name_key="PLANET_CORUSCANT"), @@ -2448,12 +2462,12 @@ def test_hidden_reasons(self): # Not a version 3 map, so a special mission in the strike array is a normal mission. assert missions["geo_phase01_conflict01_strike01"]["hidden_reason"] is None - def test_dump_spelling_of_the_version_3_flag(self): + def test_legacy_spelling_of_the_version_3_flag(self): - definition = {k: v for k, v in _TB_DEFS[1].items() if k != "territoryBattleVersion3"} + definition = {k: v for k, v in _TB_DEFS[1].items() if k != "territoryBattleVersion_3"} missions = get_tb_mission_requirements([definition], _TB_CAMPAIGNS, _TB_CATEGORIES) assert sum(m["hidden_reason"] == "special" for m in missions) == 0 - definition["territoryBattleVersion_3"] = True + definition["territoryBattleVersion3"] = True missions = get_tb_mission_requirements([definition], _TB_CAMPAIGNS, _TB_CATEGORIES) assert sum(m["hidden_reason"] == "special" for m in missions) == 1 From 07bffd6a960cf0a1afc6623bbbbf33997a2d553a Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:55:49 -0500 Subject: [PATCH 33/47] fix(helpers): accept tier 0 in is_omicron_skill is_omicron_skill treated a tier of 0 as missing and raised, both for a roster_unit_skill and for a skill_tier passed directly. Tier 0 is the value a freshly unlocked skill carries, and a skill whose only tier is its omicron has the omicron at index 0, so only a missing tier is now an error. Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/helpers/_omicron.py | 5 +++-- tests/unit/test_helpers.py | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/swgoh_comlink/helpers/_omicron.py b/src/swgoh_comlink/helpers/_omicron.py index 6063e71..d0ace5e 100644 --- a/src/swgoh_comlink/helpers/_omicron.py +++ b/src/swgoh_comlink/helpers/_omicron.py @@ -116,13 +116,14 @@ def is_omicron_skill( if roster_unit_skill is not None: skill_id = roster_unit_skill.get("id") skill_tier = roster_unit_skill.get("tier") - if not skill_id or not skill_tier: + # Tier 0 is a legitimate value for a freshly unlocked skill, so only a missing tier is an error. + if not skill_id or skill_tier is None: raise SwgohComlinkValueError("Invalid 'roster_unit_skill' argument.") else: # Validate that skill_id and skill_tier were provided directly if not isinstance(skill_id, str): raise SwgohComlinkValueError(f"'skill_id' must be a string, not {type(skill_id)}") - if not skill_id or not skill_tier: + if not skill_id or skill_tier is None: raise SwgohComlinkValueError( "'skill_id' and 'skill_tier' are required when 'roster_unit_skill' is not provided." ) diff --git a/tests/unit/test_helpers.py b/tests/unit/test_helpers.py index 065bc53..53533fa 100644 --- a/tests/unit/test_helpers.py +++ b/tests/unit/test_helpers.py @@ -333,6 +333,9 @@ def test_get_omicron_skill_tier(skill, expected): pytest.param(_SKILL_LIST, {"roster_unit_skill": {"id": "skill_A", "tier": 1}}, True, id="roster-unit-skill"), pytest.param(_SKILL_LIST, {"skill_id": "nonexistent", "skill_tier": 1}, False, id="not-in-list"), pytest.param([_SKILL_LIST[1]], {"skill_id": "skill_B", "skill_tier": 1}, False, id="skill-without-omicron"), + # Tier 0 is a freshly unlocked skill, not a missing tier; skill_C has its omicron at tier index 0. + pytest.param(_SKILL_LIST, {"skill_id": "skill_A", "skill_tier": 0}, False, id="direct-tier-zero"), + pytest.param(_SKILL_LIST, {"roster_unit_skill": {"id": "skill_C", "tier": 0}}, True, id="roster-tier-zero"), ], ) def test_is_omicron_skill(skills, kwargs, expected): From d79193a90341acfffc9a687b715003726d9d21dd Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:58:16 -0500 Subject: [PATCH 34/47] feat(statcalc): apply a named datacron's stat affixes to characters A player owns many datacrons and picks one per squad, so stats are asked for "with this datacron" rather than "with datacrons". calc_player_stats takes a datacron_id from the player's own collection; calc_roster_stats and calc_char_stats take the datacron object. The acalc_* wrappers on StatCalcAsync pass the same arguments through. Each character gains a `datacron` bucket beside `final`, never summed into it. The bucket is the last link of the percent-conversion chain, so `final + datacron` is correct for every stat, including the non-linear percentage stats such as Armor and Resistance. Ships get no bucket. Affixes are gated on the unit's gear tier and encoded relic tier; a unit with no relic sits at the locked tier rather than 0, so it still gets the affixes that require no relic. Ability affixes are skipped. Percent affixes expand onto their target stats through the mapping the mod path already uses, now shared from the new _datacron module, and resolve against base plus gear, excluding mods. A stat's affix percentages are summed and then rounded to the two decimals the datacron card shows, which is what in-game readings match. Without a datacron argument nothing changes: no bucket appears and the output is identical to before. Co-Authored-By: Claude Opus 5.5 --- docs/api/statcalc.md | 62 +- src/swgoh_comlink/StatCalc/_datacron.py | 134 ++++ src/swgoh_comlink/StatCalc/calculator.py | 102 ++- .../StatCalc/calculator_async.py | 19 +- tests/statcalc/test_datacron.py | 699 ++++++++++++++++++ tests/unit/test_statcalc_async.py | 42 ++ 6 files changed, 1023 insertions(+), 35 deletions(-) create mode 100644 src/swgoh_comlink/StatCalc/_datacron.py create mode 100644 tests/statcalc/test_datacron.py diff --git a/docs/api/statcalc.md b/docs/api/statcalc.md index 229c814..e57b3cb 100644 --- a/docs/api/statcalc.md +++ b/docs/api/statcalc.md @@ -100,6 +100,62 @@ gp = calc.calc_char_gp(unit) ship_gp = calc.calc_ship_gp(ship_unit, crew_list) ``` +### Apply a datacron + +A player owns many datacrons and picks one per squad when they deploy, so there +is no such thing as "this unit's stats with datacrons", only "this unit's stats +with *this* datacron". Name the one you mean: + +```python +player = comlink.get_player(allycode=245866537) +datacron_id = player["datacron"][0]["id"] +calc.calc_player_stats(player, datacron_id=datacron_id) + +unit = player["rosterUnit"][0] +print(unit["stats"]["final"]) # unchanged by the datacron +print(unit["stats"]["datacron"]) # what the datacron adds to this unit +``` + +`calc_player_stats` takes a datacron **id** and looks it up in the player's own +`datacron` collection, raising `KeyError` if the player does not own it. +`calc_roster_stats` and `calc_char_stats` take the datacron **object**, having +no player to look it up in: + +```python +datacron = next(d for d in player["datacron"] if d["id"] == datacron_id) +calc.calc_char_stats(unit, datacron) +``` + +Leave the argument out and nothing changes: no `datacron` key appears and the +output is the same as before. + +#### Combining the buckets + +The `datacron` bucket is deliberately **not** summed into `final`. Add the two +to get a unit's stats as it would fight with that datacron: + +```python +stats = unit["stats"] +combined = {name: value + stats["datacron"].get(name, 0) for name, value in stats["final"].items()} +``` + +That addition is correct for **every** stat, including ones reported as +percentages such as Armor and Resistance. Those are converted non-linearly, so +a raw percentage could not simply be added to them; the bucket instead holds +the amount the datacron actually adds on top of everything else. + +Worth knowing: + +- **Ships never get a bucket.** Datacrons are a squad mechanic and no game mode + applies one to a fleet battle, so ship stats are unaffected. +- **Affixes are gated per unit.** Each affix requires a gear tier and a relic + tier, so the same datacron adds different amounts to different units. Relic + tiers in the game data count the locked and unlocked states as their first + two values, so a `requiredRelicTier` of 5 means relic 3 as a player counts it. +- **Percentages apply as the datacron card shows them.** A stat's affix + percentages are summed, rounded to two decimals, and then applied to the + unit's base plus gear stats. Mods do not count toward that total. + ## Async Usage (`StatCalcAsync`) Use the async `create()` factory to fetch game data without blocking the event @@ -109,10 +165,10 @@ guild does not stall the loop (for example a Discord bot's gateway heartbeat). | Async method | Runs | |--------------|------| -| `await calc.acalc_char_stats(unit)` | `calc_char_stats` | +| `await calc.acalc_char_stats(unit, datacron=None)` | `calc_char_stats` | | `await calc.acalc_ship_stats(ship, crew)` | `calc_ship_stats` | -| `await calc.acalc_roster_stats(units)` | `calc_roster_stats` | -| `await calc.acalc_player_stats(players)` | `calc_player_stats` | +| `await calc.acalc_roster_stats(units, datacron=None)` | `calc_roster_stats` | +| `await calc.acalc_player_stats(players, datacron_id=None)` | `calc_player_stats` | ```python from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync diff --git a/src/swgoh_comlink/StatCalc/_datacron.py b/src/swgoh_comlink/StatCalc/_datacron.py new file mode 100644 index 0000000..04ed41a --- /dev/null +++ b/src/swgoh_comlink/StatCalc/_datacron.py @@ -0,0 +1,134 @@ +"""Datacron stat resolution. + +Pure computation: no instance state, no game data, no I/O. Datacron stat affixes +carry no unit scope of any kind, so resolving them needs nothing beyond the +datacron itself, the unit it is applied to, and that unit's stats before the +datacron is considered. + +Values are in unscaled space throughout: raw game-data fixed point, where ``1e8`` +represents ``1.0``. Callers scale for display afterwards. +""" + +from __future__ import annotations + +import math +from typing import Any + +__all__ = [ + "STAT_PERCENT_OF_BASE", + "STAT_SPLITS", + "resolve_datacron_stats", +] + +# Percent-additive stat ids do not name the stat they affect: they expand onto one +# or more real target stats. Mods and datacrons expand the same ids onto the same +# targets, so the mapping is shared. The arithmetic is not (mods resolve against +# base alone, datacrons against base plus gear), but two copies of the mapping +# could drift apart and silently credit the wrong stat. + +#: Stat ids that add their value to each of several stats (e.g. 41, Offense, adds to 6 and 7). +STAT_SPLITS: dict[int, tuple[str, ...]] = { + 41: ("6", "7"), + 42: ("8", "9"), + 53: ("21", "22"), + 54: ("35", "36"), +} + +#: Percent stat ids that add a share of an existing stat to each target, floored to whole units. +STAT_PERCENT_OF_BASE: dict[int, tuple[str, ...]] = { + 48: ("6", "7"), + 49: ("8", "9"), + 55: ("1",), + 56: ("28",), + 57: ("5",), +} + +# Relic tiers are encoded with their two base states, locked and unlocked, taking +# the first two values, so the relic number a player sees is two lower than the +# encoded one: an encoded 5 is relic 3. An affix's ``requiredRelicTier`` and a +# unit's ``currentTier`` both use this encoding, so they are compared directly. +_LOCKED_RELIC_TIER = 1 + +_UNIT = 1e8 + + +def resolve_datacron_stats( + datacron: dict[str, Any], + unit: dict[str, Any], + unmodded_total: dict[str, float], +) -> dict[str, float]: + """Resolve one datacron's stat contribution to one unit. + + Args: + datacron: A datacron from a player's ``datacron`` collection. + unit: A normalized character, with ``gear`` and ``relic`` keys. + unmodded_total: The unit's per-stat base plus gear totals, excluding mods, + in unscaled space. Datacron percentages resolve against this total; + in-game readings show mods are not part of it. + + Returns: + Per-stat contributions keyed by stat id, in unscaled space. Empty when the + datacron grants the unit nothing. + """ + gear_tier = int(unit.get("gear") or 0) + relic_tier = _relic_tier(unit) + + totals: dict[int, float] = {} + for affix in datacron.get("affix") or (): + # An ability affix grants an ability, not a stat. It reports stat type 1 + # with value 0 today; skipping it by its ability keeps a future non-zero + # value from being counted as Health. + if affix.get("abilityId"): + continue + if gear_tier < int(affix.get("requiredUnitTier") or 0): + continue + if relic_tier < int(affix.get("requiredRelicTier") or 0): + continue + if not (stat_id := int(affix.get("statType") or 0)): + continue + totals[stat_id] = totals.get(stat_id, 0.0) + float(affix.get("statValue") or 0) + + return _expand({stat_id: _as_displayed(value) for stat_id, value in totals.items()}, unmodded_total) + + +def _as_displayed(value: float) -> float: + """Round a stat's summed percentage to the two decimals the datacron card shows. + + In-game readings match the displayed percentage, not the six-decimal stored + one. Affixes are summed before rounding: two affixes of 2.828575% and + 19.515055% apply as 22.34%, not as 22.35%, the sum of the rounded parts. + """ + return round(value / 1e6, 2) * 1e6 + + +def _expand(totals: dict[int, float], unmodded_total: dict[str, float]) -> dict[str, float]: + """Resolve percent-additive stat ids onto the stats they actually modify.""" + expanded: dict[str, float] = {} + for stat_id, value in totals.items(): + if (targets := STAT_SPLITS.get(stat_id)) is not None: + for target in targets: + expanded[target] = expanded.get(target, 0.0) + value + elif (targets := STAT_PERCENT_OF_BASE.get(stat_id)) is not None: + for target in targets: + # Floored to whole units, as the mod path floors its own percentage growth. + current = expanded.get(target, 0.0) + grown = current + unmodded_total.get(target, 0.0) * 1e-8 * value + expanded[target] = math.floor(grown / _UNIT) * _UNIT + else: + key = str(stat_id) + expanded[key] = expanded.get(key, 0.0) + value + return expanded + + +def _relic_tier(unit: dict[str, Any]) -> int: + """Return the unit's encoded relic tier. + + A unit with no relic reports ``relic`` as ``None`` rather than a zeroed + structure, and sits at the locked base state. Treating it as 0 would fail + even the baseline relic requirement every affix carries and silently drop + the datacron's contribution to every relic-less unit. + """ + relic = unit.get("relic") + if not isinstance(relic, dict) or relic.get("currentTier") is None: + return _LOCKED_RELIC_TIER + return int(relic["currentTier"]) diff --git a/src/swgoh_comlink/StatCalc/calculator.py b/src/swgoh_comlink/StatCalc/calculator.py index 4482bca..95a1504 100644 --- a/src/swgoh_comlink/StatCalc/calculator.py +++ b/src/swgoh_comlink/StatCalc/calculator.py @@ -12,6 +12,9 @@ from ..exceptions import SwgohComlinkValueError from ..helpers._stat_data import STATS as _CANONICAL_STATS +from ._datacron import STAT_PERCENT_OF_BASE as _MOD_STAT_PERCENT_OF_BASE +from ._datacron import STAT_SPLITS as _MOD_STAT_SPLITS +from ._datacron import resolve_datacron_stats # Largest game data body accepted, counted after any Content-Encoding is decoded # (gameData.json is about 1.6 MB). @@ -20,22 +23,6 @@ _SHA256_HEX = re.compile(r"[0-9a-f]{64}") -# Mod stats that add their value to each of several stats (e.g. 41, Offense, adds to 6 and 7). -_MOD_STAT_SPLITS: dict[int, tuple[str, ...]] = { - 41: ("6", "7"), - 42: ("8", "9"), - 53: ("21", "22"), - 54: ("35", "36"), -} -# Percent mod stats that add a share of the unit's base stat to each target stat, floored to 8 digits. -_MOD_STAT_PERCENT_OF_BASE: dict[int, tuple[str, ...]] = { - 48: ("6", "7"), - 49: ("8", "9"), - 55: ("1",), - 56: ("28",), - 57: ("5",), -} - # Character stat ids whose final value is added to another stat (Physical and Special Critical # Chance to Critical Rating, Physical and Special Critical Avoidance to Critical Avoidance Rating). _FLAT_STAT_IDS: dict[str, str] = {"21": "14", "22": "15", "35": "39", "36": "40"} @@ -245,12 +232,17 @@ def set_game_data(self, game_data: dict[str, Any]) -> None: len(self._mod_set_data), ) - def calc_char_stats(self, unit: dict[str, Any]) -> dict[str, Any]: + def calc_char_stats(self, unit: dict[str, Any], datacron: dict[str, Any] | None = None) -> dict[str, Any]: """Calculate stats and GP for a character unit. Args: unit: Character object in either normalized (`defId`) or raw game format (`definitionId`). + datacron: Optional datacron object, as found in a player's + `datacron` collection. When given, `stats` gains a `datacron` + bucket holding what that datacron adds to this unit. The bucket + is not summed into `final`; `final + datacron` is the unit's + value with the datacron applied, for every stat. Returns: The input unit with `stats` and `gp` keys added, containing the calculated stats and GP. @@ -262,6 +254,8 @@ def calc_char_stats(self, unit: dict[str, Any]) -> dict[str, Any]: stats: dict[str, Any] = self._get_char_raw_stats(char) stats = self._calculate_base_stats(stats, char["level"], char["defId"]) stats["mods"] = self._calculate_mod_stats(stats["base"], char) + if datacron is not None: + stats["datacron"] = resolve_datacron_stats(datacron, char, self._unmodded_total(stats)) stats = self._format_stats(stats, char["level"]) stats = self._rename_stats(stats) @@ -300,11 +294,15 @@ def calc_ship_stats(self, unit: dict[str, Any], crew_member: list[dict[str, Any] return unit - def calc_roster_stats(self, units: Any) -> Any: + def calc_roster_stats(self, units: Any, datacron: dict[str, Any] | None = None) -> Any: """Calculate stats for all units in a roster-like payload. Args: units: Either a list of units or a legacy dict keyed by unit id. + datacron: Optional datacron object to apply to every character, as + in :meth:`calc_char_stats`. Ships get no `datacron` bucket and + their stats are unchanged: no game mode applies a datacron to + a fleet. Returns: Input object with `stats` and `gp` fields added for each unit. Ships @@ -330,7 +328,7 @@ def calc_roster_stats(self, units: Any) -> Any: ships.append((unit, def_id, meta)) else: crew[def_id] = unit - unit = self.calc_char_stats(unit) + unit = self.calc_char_stats(unit, datacron) for ship, def_id, meta in ships: crw = [crew[cid] for cid in meta["crew"] if cid in crew] @@ -360,7 +358,7 @@ def calc_roster_stats(self, units: Any) -> Any: "mods": unit.get("equippedStatMod"), "skills": unit.get("skill", []), } - temp_unit = self.calc_char_stats(temp_unit) + temp_unit = self.calc_char_stats(temp_unit, datacron) if "stats" in temp_unit: unit["stats"] = temp_unit["stats"] if "gp" in temp_unit: @@ -369,12 +367,18 @@ def calc_roster_stats(self, units: Any) -> Any: return units def calc_player_stats( - self, players: dict[str, Any] | list[dict[str, Any]] + self, players: dict[str, Any] | list[dict[str, Any]], datacron_id: str | None = None ) -> dict[str, Any] | list[dict[str, Any]]: """Calculate stats for one or more player payloads. Args: players: One player object, or a list of player objects, each with a `rosterUnit` element. + datacron_id: Optional id of a datacron in each player's own + `datacron` collection. When given, every character gains a + `datacron` stat bucket, as in :meth:`calc_char_stats`. This + method takes an id because the collection to look it up in is + part of the player payload; :meth:`calc_roster_stats` and + :meth:`calc_char_stats` take the datacron object itself. Returns: The input object with `stats` and `gp` fields added for each player's roster. @@ -382,6 +386,8 @@ def calc_player_stats( Raises: RuntimeError: If a dict player is missing a 'rosterUnit' key. TypeError: If the input object is not a list or dict. + KeyError: If `datacron_id` is given and a player has no `datacron` + collection or does not own that datacron. """ if not isinstance(players, (list, dict)): raise TypeError("Expected a list or dict of players") @@ -391,13 +397,39 @@ def calc_player_stats( if isinstance(players, list): for player in players: - self.calc_roster_stats(player.get("rosterUnit")) + self.calc_roster_stats(player.get("rosterUnit"), self._select_datacron(player, datacron_id)) return players if "rosterUnit" not in players: raise RuntimeError("Expected a dict with a 'rosterUnit' key") - self.calc_roster_stats(players["rosterUnit"]) + self.calc_roster_stats(players["rosterUnit"], self._select_datacron(players, datacron_id)) return players + @staticmethod + def _select_datacron(player: dict[str, Any], datacron_id: str | None) -> dict[str, Any] | None: + """Return the datacron *datacron_id* from *player*'s collection, or None if no id is given.""" + if datacron_id is None: + return None + collection = player.get("datacron") + if collection is None: + # A player who owns no datacrons reports an empty list, not a missing key. + raise KeyError("Player payload has no 'datacron' collection to look the datacron id up in") + for datacron in collection: + if datacron.get("id") == datacron_id: + return datacron + raise KeyError(f"Datacron {datacron_id!r} is not among the player's {len(collection)} datacrons") + + @staticmethod + def _unmodded_total(stats: dict[str, Any]) -> dict[str, float]: + """Return the per-stat sum of base and gear, excluding mods, in unscaled space. + + Datacron percentages resolve against this total; in-game readings show + that mods do not count toward it. + """ + total = dict(stats["base"]) + for stat_id, value in stats.get("gear", {}).items(): + total[stat_id] = total.get(stat_id, 0) + value + return total + def calc_char_gp(self, char: dict[str, Any]) -> int: """Calculate GP for a character. @@ -871,6 +903,9 @@ def _format_stats(self, stats: dict[str, Any], level: int) -> dict[str, Any]: if mods: for stat_id, value in mods.items(): mods[stat_id] = value * scale + if datacron := stats.get("datacron"): + for stat_id, value in datacron.items(): + datacron[stat_id] = value * scale if self._FIXED_PERCENT_VALS or self._FIXED_GAME_STYLE: percent_scale = scale * 1e8 @@ -920,6 +955,14 @@ def crit_avoidance(val: float) -> float: mod_values = stats["mods"] or {} stat_ids |= dict.fromkeys(stats["mods"]) gs_stats["mods"] = stats["mods"] + if "datacron" in stats: + # Kept beside final, never summed into it, and keyed the way final is so the + # two can be added stat by stat. + datacron_values: dict[str, Any] = {} + for stat_id, value in stats["datacron"].items(): + key = _FLAT_STAT_IDS.get(stat_id, stat_id) + datacron_values[key] = datacron_values.get(key, 0) + value + gs_stats["datacron"] = datacron_values for stat_id in stat_ids: key = _FLAT_STAT_IDS.get(stat_id, stat_id) @@ -957,8 +1000,9 @@ def _convert_percent(stats: dict[str, Any], conversions: Iterable[tuple[str, Cal """Convert each flat stat to a percent with its converter, in order. The base value becomes the percent of the base flat value. A ship's crew value, or a - character's gear and then mods value, becomes the percent it adds on top of the - values before it. + character's gear, mods and then datacron value, becomes the percent it adds on top + of the values before it. The datacron comes last, so ``final + datacron`` is the + converted value of the whole flat total. """ # The stat dicts are only updated in place, so they are looked up once for all conversions. base = stats["base"] @@ -966,6 +1010,7 @@ def _convert_percent(stats: dict[str, Any], conversions: Iterable[tuple[str, Cal crew = stats.get("crew") gear = stats.get("gear") mods = stats.get("mods") + datacron = stats.get("datacron") for sid, convert_func in conversions: flat = base.get(sid, 0) percent = convert_func(flat) @@ -984,7 +1029,12 @@ def _convert_percent(stats: dict[str, Any], conversions: Iterable[tuple[str, Cal last = percent if mods and (mod_value := mods.get(sid, 0)): flat = flat + mod_value - mods[sid] = convert_func(flat) - last + percent = convert_func(flat) + mods[sid] = percent - last + last = percent + if datacron and (datacron_value := datacron.get(sid, 0)): + flat = flat + datacron_value + datacron[sid] = convert_func(flat) - last def _calc_char_gp(self, char: dict[str, Any]) -> int: assert self._gp_tables is not None # type narrowing: set_game_data() set it; _require_game_data() ran diff --git a/src/swgoh_comlink/StatCalc/calculator_async.py b/src/swgoh_comlink/StatCalc/calculator_async.py index 8224b2b..da801ad 100644 --- a/src/swgoh_comlink/StatCalc/calculator_async.py +++ b/src/swgoh_comlink/StatCalc/calculator_async.py @@ -99,17 +99,18 @@ async def create( cls._LOGGER.debug("Using caller-provided game data") return cls(game_data=game_data) - async def acalc_char_stats(self, unit: dict[str, Any]) -> dict[str, Any]: + async def acalc_char_stats(self, unit: dict[str, Any], datacron: dict[str, Any] | None = None) -> dict[str, Any]: """Run :meth:`calc_char_stats` in a worker thread. Args: unit: Character object in either normalized (`defId`) or raw game format (`definitionId`). + datacron: Optional datacron object to apply, as in :meth:`calc_char_stats`. Returns: The input unit with `stats` and `gp` keys added. """ - return await asyncio.to_thread(self.calc_char_stats, unit) + return await asyncio.to_thread(self.calc_char_stats, unit, datacron) async def acalc_ship_stats(self, unit: dict[str, Any], crew_member: list[dict[str, Any]]) -> dict[str, Any]: """Run :meth:`calc_ship_stats` in a worker thread. @@ -123,24 +124,28 @@ async def acalc_ship_stats(self, unit: dict[str, Any], crew_member: list[dict[st """ return await asyncio.to_thread(self.calc_ship_stats, unit, crew_member) - async def acalc_roster_stats(self, units: Any) -> Any: + async def acalc_roster_stats(self, units: Any, datacron: dict[str, Any] | None = None) -> Any: """Run :meth:`calc_roster_stats` in a worker thread. Args: units: Either a list of units or a legacy dict keyed by unit id. + datacron: Optional datacron object to apply to every character, as + in :meth:`calc_roster_stats`. Returns: Input object with `stats` and `gp` fields added for each unit. """ - return await asyncio.to_thread(self.calc_roster_stats, units) + return await asyncio.to_thread(self.calc_roster_stats, units, datacron) async def acalc_player_stats( - self, players: dict[str, Any] | list[dict[str, Any]] + self, players: dict[str, Any] | list[dict[str, Any]], datacron_id: str | None = None ) -> dict[str, Any] | list[dict[str, Any]]: """Run :meth:`calc_player_stats` in a worker thread. Args: players: One player object, or a list of player objects, each with a `rosterUnit` element. + datacron_id: Optional id of a datacron in each player's own + `datacron` collection, as in :meth:`calc_player_stats`. Returns: The input object with `stats` and `gp` fields added for each player's roster. @@ -148,8 +153,10 @@ async def acalc_player_stats( Raises: RuntimeError: If a dict player is missing a 'rosterUnit' key. TypeError: If the input object is not a list or dict. + KeyError: If `datacron_id` is given and a player has no `datacron` + collection or does not own that datacron. """ - return await asyncio.to_thread(self.calc_player_stats, players) + return await asyncio.to_thread(self.calc_player_stats, players, datacron_id) @classmethod async def _async_fetch_game_data_from_github( diff --git a/tests/statcalc/test_datacron.py b/tests/statcalc/test_datacron.py new file mode 100644 index 0000000..07f154f --- /dev/null +++ b/tests/statcalc/test_datacron.py @@ -0,0 +1,699 @@ +"""Datacron behaviour, driven entirely through ``calc_player_stats``. + +Single seam by design: a player payload is an ordinary dict, so hand-authored +players give exact control over gear tiers, relic tiers and affix thresholds +without reaching into the resolution module. Nothing here may monkeypatch +private methods or assert on where the datacron step sits in the pipeline — +that position is an implementation detail. +""" + +from __future__ import annotations + +import copy +import json +import math +from pathlib import Path +from typing import Any + +import pytest + +from swgoh_comlink import StatCalc + +_RESOURCES = Path(__file__).resolve().parent.parent / "resources" +_GAME_DATA_FILE = _RESOURCES / "gameData.json" +_PLAYER_FILE = _RESOURCES / "example-player.json" + +# A character present in the committed game data, used wherever the test needs +# a real unit definition rather than a specific character's properties. +_CHAR = "CADBANE" + +DATACRON_ID = "test-datacron" + + +# ── Fixtures ───────────────────────────────────────────────────────────── + + +@pytest.fixture(scope="module") +def game_data() -> dict[str, Any]: + return json.loads(_GAME_DATA_FILE.read_text())["data"] + + +@pytest.fixture(scope="module") +def calc(game_data: dict[str, Any]) -> StatCalc: + return StatCalc(game_data=game_data) + + +@pytest.fixture(scope="module") +def example_player() -> dict[str, Any]: + return json.loads(_PLAYER_FILE.read_text()) + + +# ── Payload builders ───────────────────────────────────────────────────── + + +def stat_affix( + stat_type: int, + value: int, + *, + required_unit_tier: int = 0, + required_relic_tier: int = 1, +) -> dict[str, Any]: + """A Stat Affix. Never carries a target rule — real ones never do.""" + return { + "tag": [], + "targetRule": "", + "abilityId": "", + "statType": stat_type, + "statValue": str(value), + "requiredUnitTier": required_unit_tier, + "requiredRelicTier": required_relic_tier, + "scopeIcon": "", + } + + +def ability_affix(ability_id: str = "datacron_alignment_generic_030") -> dict[str, Any]: + """An Ability Affix, shaped as the game reports one: stat type 1, value 0.""" + return { + "tag": ["darkside"], + "targetRule": "target_datacron_darkside", + "abilityId": ability_id, + "statType": 1, + "statValue": "0", + "requiredUnitTier": 0, + "requiredRelicTier": 1, + "scopeIcon": "tex.datacronui_affix_darkside", + } + + +def datacron(*affixes: dict[str, Any], datacron_id: str = DATACRON_ID) -> dict[str, Any]: + return { + "id": datacron_id, + "setId": 25, + "templateId": "datacron_set_25_base", + "tag": [], + "affix": list(affixes), + "rerollOption": [], + "locked": False, + "rerollIndex": 0, + "rerollCount": 0, + "focused": False, + } + + +def character( + def_id: str = _CHAR, + *, + gear_tier: int = 13, + relic_tier: int | None = 11, + level: int = 85, + rarity: int = 7, +) -> dict[str, Any]: + """A roster unit. `relic_tier=None` produces a unit with no relic at all.""" + unit: dict[str, Any] = { + "definitionId": f"{def_id}:SEVEN_STAR", + "currentRarity": rarity, + "currentLevel": level, + "currentTier": gear_tier, + "equipment": [], + "skill": [], + "equippedStatMod": [], + "relic": None if relic_tier is None else {"currentTier": relic_tier}, + } + return unit + + +def player(*units: dict[str, Any], datacrons: list[dict[str, Any]] | None = None) -> dict[str, Any]: + return { + "rosterUnit": list(units), + "datacron": [] if datacrons is None else datacrons, + } + + +def datacron_bucket(calc: StatCalc, payload: dict[str, Any], datacron_id: str | None = DATACRON_ID) -> dict[str, Any]: + """Run one player through the seam and return the first unit's bucket.""" + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=datacron_id) + assert isinstance(result, dict) + return result["rosterUnit"][0]["stats"].get("datacron", {}) + + +# ── The bucket appears, and only when asked for ─────────────────────────── + + +def test_characters_gain_a_datacron_bucket(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(16, 50_000_000))]) + + assert datacron_bucket(calc, payload) == {"Critical Damage": pytest.approx(0.5)} + + +def test_bucket_is_absent_not_empty_when_no_datacron_requested(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(16, 50_000_000))]) + + result = calc.calc_player_stats(copy.deepcopy(payload)) + assert isinstance(result, dict) + + assert "datacron" not in result["rosterUnit"][0]["stats"] + + +def test_output_is_unchanged_when_no_datacron_requested(calc: StatCalc, example_player: dict[str, Any]) -> None: + """The whole feature is dormant unless a datacron is named.""" + before = calc.calc_player_stats(copy.deepcopy(example_player)) + after = calc.calc_player_stats(copy.deepcopy(example_player), datacron_id=None) + + assert after == before + + +# ── Passthrough stat types ──────────────────────────────────────────────── + + +def test_stat_values_are_scaled_for_display(calc: StatCalc) -> None: + """Affix values arrive in Unscaled Space and leave in display units.""" + payload = player(character(), datacrons=[datacron(stat_affix(17, 12_500_000))]) + + assert datacron_bucket(calc, payload)["Potency"] == pytest.approx(0.125) + + +def test_a_stat_type_repeated_across_levels_is_summed(calc: StatCalc) -> None: + payload = player( + character(), + datacrons=[ + datacron( + stat_affix(16, 21_927_327), + stat_affix(16, 23_172_075), + stat_affix(16, 42_891_143), + ) + ], + ) + + # 21.927327 + 23.172075 + 42.891143 = 87.990545%, applied as the 87.99% + # the card displays. + assert datacron_bucket(calc, payload)["Critical Damage"] == pytest.approx(0.8799) + + +def test_a_percentage_is_applied_as_the_card_displays_it(calc: StatCalc) -> None: + """The game applies the two-decimal percentage, not the stored value. + + Measured on Lord Vader: a 27.14327% Protection affix against a base of + 116,765 contributed 31,690, which is 27.14% of it. The stored value would + have given 31,693. + """ + payload = player(character(), datacrons=[datacron(stat_affix(16, 27_143_270))]) + + assert datacron_bucket(calc, payload)["Critical Damage"] == pytest.approx(0.2714) + + +def test_percentages_are_summed_before_they_are_rounded(calc: StatCalc) -> None: + """Rounding each affix first would give a different, wrong answer. + + Measured: affixes of 2.828575% and 19.515055% are applied as 22.34% — the + rounded sum. Rounding each part first gives 2.83 + 19.52 = 22.35%. + """ + payload = player( + character(), + datacrons=[datacron(stat_affix(16, 2_828_575), stat_affix(16, 19_515_055))], + ) + + assert datacron_bucket(calc, payload)["Critical Damage"] == pytest.approx(0.2234) + + +def test_distinct_stat_types_stay_distinct(calc: StatCalc) -> None: + payload = player( + character(), + datacrons=[datacron(stat_affix(17, 10_000_000), stat_affix(18, 20_000_000))], + ) + + assert datacron_bucket(calc, payload) == { + "Potency": pytest.approx(0.1), + "Tenacity": pytest.approx(0.2), + } + + +def test_bucket_stat_names_match_the_other_buckets(calc: StatCalc) -> None: + """Names must line up so a caller can pair buckets without a lookup table.""" + payload = player(character(), datacrons=[datacron(stat_affix(16, 50_000_000))]) + + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + stats = result["rosterUnit"][0]["stats"] + + assert set(stats["datacron"]) <= set(stats["final"]) + + +# ── Ability Affixes ─────────────────────────────────────────────────────── + + +def test_ability_affixes_contribute_nothing(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(ability_affix(), ability_affix())]) + + assert datacron_bucket(calc, payload) == {} + + +def test_ability_affixes_are_skipped_even_carrying_a_real_stat_value(calc: StatCalc) -> None: + """Identified by granting an ability, not by having a zero value.""" + affix = ability_affix() + affix["statValue"] = "50000000" + payload = player(character(), datacrons=[datacron(affix)]) + + assert datacron_bucket(calc, payload) == {} + + +def test_stat_affixes_survive_alongside_ability_affixes(calc: StatCalc) -> None: + payload = player( + character(), + datacrons=[datacron(stat_affix(16, 30_000_000), ability_affix(), stat_affix(17, 10_000_000))], + ) + + assert datacron_bucket(calc, payload) == { + "Critical Damage": pytest.approx(0.3), + "Potency": pytest.approx(0.1), + } + + +# ── Affix Requirement gating ────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("unit_gear_tier", "applies"), + [(13, True), (12, True), (11, False), (1, False)], + ids=["above", "met exactly", "one short", "far short"], +) +def test_gear_tier_requirement(calc: StatCalc, unit_gear_tier: int, applies: bool) -> None: + payload = player( + character(gear_tier=unit_gear_tier), + datacrons=[datacron(stat_affix(16, 50_000_000, required_unit_tier=12))], + ) + + assert bool(datacron_bucket(calc, payload)) is applies + + +@pytest.mark.parametrize( + ("unit_relic_tier", "applies"), + [(11, True), (8, True), (7, False), (3, False)], + ids=["above", "met exactly", "one short", "far short"], +) +def test_relic_tier_requirement(calc: StatCalc, unit_relic_tier: int, applies: bool) -> None: + """Encoded tiers on both sides, so the comparison is direct. + + Offsetting either side would shift this threshold by two tiers, which is + exactly what the 'one short' case would stop catching. + """ + payload = player( + character(relic_tier=unit_relic_tier), + datacrons=[datacron(stat_affix(16, 50_000_000, required_relic_tier=8))], + ) + + assert bool(datacron_bucket(calc, payload)) is applies + + +def test_both_requirements_must_be_met(calc: StatCalc) -> None: + affix = stat_affix(16, 50_000_000, required_unit_tier=12, required_relic_tier=8) + + both = player(character(gear_tier=13, relic_tier=9), datacrons=[datacron(affix)]) + assert datacron_bucket(calc, both) + + gear_short = player(character(gear_tier=11, relic_tier=9), datacrons=[datacron(affix)]) + assert datacron_bucket(calc, gear_short) == {} + + relic_short = player(character(gear_tier=13, relic_tier=7), datacrons=[datacron(affix)]) + assert datacron_bucket(calc, relic_short) == {} + + +def test_relic_less_unit_still_receives_unrestricted_affixes(calc: StatCalc) -> None: + """Regression: a unit with no relic sits at the locked base state, not zero. + + Treating it as zero fails even the baseline requirement every affix + carries, silently zeroing every relic-less unit while leaving the + high-relic units anyone would spot-check looking perfectly correct. + """ + payload = player( + character(gear_tier=1, relic_tier=None), + datacrons=[datacron(stat_affix(16, 50_000_000))], + ) + + assert datacron_bucket(calc, payload) == {"Critical Damage": pytest.approx(0.5)} + + +def test_relic_less_unit_is_denied_affixes_that_require_a_relic(calc: StatCalc) -> None: + payload = player( + character(gear_tier=13, relic_tier=None), + datacrons=[datacron(stat_affix(16, 50_000_000, required_relic_tier=3))], + ) + + assert datacron_bucket(calc, payload) == {} + + +def test_the_same_datacron_gives_different_units_different_contributions(calc: StatCalc) -> None: + """The whole point of gating: one datacron, a roster of varied progress.""" + dc = datacron( + stat_affix(16, 10_000_000), + stat_affix(17, 20_000_000, required_relic_tier=8), + stat_affix(18, 30_000_000, required_unit_tier=12, required_relic_tier=11), + ) + payload = player( + character(gear_tier=13, relic_tier=11), + character(gear_tier=13, relic_tier=8), + character(gear_tier=1, relic_tier=None), + datacrons=[dc], + ) + + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + buckets = [unit["stats"]["datacron"] for unit in result["rosterUnit"]] + + assert set(buckets[0]) == {"Critical Damage", "Potency", "Tenacity"} + assert set(buckets[1]) == {"Critical Damage", "Potency"} + assert set(buckets[2]) == {"Critical Damage"} + + +def test_a_relic_threshold_splits_the_real_roster(calc: StatCalc, example_player: dict[str, Any]) -> None: + """Gating against real units, whose relic tiers span the threshold. + + The committed player's characters sit across several relic tiers, so an + affix requiring a high one must reach strictly fewer of them than an + unrestricted affix does. + """ + payload = copy.deepcopy(example_player) + payload["datacron"] = [ + datacron(stat_affix(16, 10_000_000), datacron_id="unrestricted"), + datacron(stat_affix(16, 10_000_000, required_relic_tier=11), datacron_id="restricted"), + ] + + def reached(datacron_id: str) -> int: + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=datacron_id) + assert isinstance(result, dict) + return sum(1 for unit in result["rosterUnit"] if unit.get("stats", {}).get("datacron")) + + everyone = reached("unrestricted") + qualified = reached("restricted") + + assert everyone > 0 + assert 0 < qualified < everyone + + +# ── Percent-additive expansion ──────────────────────────────────────────── + + +def test_additive_offense_expands_onto_both_damage_stats(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(41, 5_000_000))]) + + assert datacron_bucket(calc, payload) == { + "Physical Damage": pytest.approx(0.05), + "Special Damage": pytest.approx(0.05), + } + + +@pytest.mark.parametrize( + ("stat_type", "targets"), + [ + (48, ["Physical Damage", "Special Damage"]), + (55, ["Health"]), + (56, ["Protection"]), + (57, ["Speed"]), + ], + ids=["offense%", "health%", "protection%", "speed%"], +) +def test_proportional_types_expand_onto_their_targets(calc: StatCalc, stat_type: int, targets: list[str]) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(stat_type, 30_000_000))]) + + assert sorted(datacron_bucket(calc, payload)) == sorted(targets) + + +def test_a_percentage_resolves_against_base_and_gear_excluding_mods( + calc: StatCalc, example_player: dict[str, Any] +) -> None: + """As measured in game, percentages resolve against base + gear. + + Mods are excluded. Health is not converted for display, so `final` minus the + `mods` bucket is exactly that base. Measured against Lord Vader: a +27.14% + Protection datacron contributed 31,690 on a total of 208,666 carrying 91,901 + from mods — 27.14% of 116,765, not of 208,666. + """ + fraction = 0.25 + payload = copy.deepcopy(example_player) + payload["datacron"] = [datacron(stat_affix(55, int(fraction * 1e8)))] + + result = calc.calc_player_stats(payload, datacron_id=DATACRON_ID) + assert isinstance(result, dict) + + checked = with_mods = 0 + for unit in result["rosterUnit"]: + stats = unit.get("stats", {}) + bucket = stats.get("datacron") + if not bucket: + continue + + total = stats["final"]["Health"] + from_mods = stats.get("mods", {}).get("Health", 0) + unmodded = total - from_mods + assert unmodded > 0 + + # floor(..., 8) in Unscaled Space quantises to whole display units. + assert bucket["Health"] == pytest.approx(unmodded * fraction, abs=1.0) + if from_mods: + # Only modded units can tell the two candidate bases apart. + assert bucket["Health"] != pytest.approx(total * fraction, abs=1.0) + with_mods += 1 + checked += 1 + + assert checked > 100, "expected most of the roster to be covered" + assert with_mods > 100, "without modded units this proves nothing" + + +@pytest.mark.parametrize( + ("stat_type", "targets"), + [ + (42, ["Armor", "Resistance"]), + (49, ["Armor", "Resistance"]), + (53, ["Physical Critical Chance", "Special Critical Chance"]), + (54, ["Physical Critical Avoidance", "Special Critical Avoidance"]), + ], + ids=["defense flat", "defense%", "crit chance%", "crit avoidance%"], +) +def test_types_reaching_converted_stats_expand(calc: StatCalc, stat_type: int, targets: list[str]) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(stat_type, 50_000_000))]) + + assert sorted(datacron_bucket(calc, payload)) == sorted(targets) + + +def test_expansion_and_passthrough_coexist(calc: StatCalc) -> None: + payload = player( + character(), + datacrons=[datacron(stat_affix(16, 40_000_000), stat_affix(57, 10_000_000))], + ) + bucket = datacron_bucket(calc, payload) + + assert bucket["Critical Damage"] == pytest.approx(0.4) + assert "Speed" in bucket + + +def test_gating_applies_before_expansion(calc: StatCalc) -> None: + """An affix the unit does not qualify for must not expand onto anything.""" + payload = player( + character(gear_tier=1, relic_tier=3), + datacrons=[datacron(stat_affix(48, 30_000_000, required_relic_tier=11))], + ) + + assert datacron_bucket(calc, payload) == {} + + +# ── Converted stats reconcile with final ────────────────────────────────── + + +def test_a_converted_stat_reconciles_against_an_independent_recomputation(calc: StatCalc) -> None: + """The promise of the feature: `final + datacron` is right for every stat. + + Armor is stored as a non-linear percentage, `v / (level*7.5 + v)`, so a + flat delta could not simply be added to it. The bucket must instead hold + the *marginal* percentage the datacron adds. + + The oracle here is independent of the datacron code: invert the published + conversion to recover the unit's flat armour, apply the percentage by hand, + convert forward again, and require the two buckets to sum to that. + """ + level = 85 + fraction = 0.5 + payload = player( + character(level=level), + datacrons=[datacron(stat_affix(49, int(fraction * 1e8)))], + ) + + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + stats = result["rosterUnit"][0]["stats"] + + level_effect = level * 7.5 + p0 = stats["final"]["Armor"] + assert 0 < p0 < 1 + + flat = level_effect * p0 / (1 - p0) + # Proportional growth is floored to whole display units in Unscaled Space. + grown = flat + math.floor(flat * fraction) + expected = grown / (level_effect + grown) + + assert p0 + stats["datacron"]["Armor"] == pytest.approx(expected, rel=1e-6) + + +def test_a_converted_stat_is_not_given_a_flat_delta(calc: StatCalc) -> None: + """Guard against the naive implementation: a flat armour delta would dwarf + the percentage it is meant to be added to.""" + payload = player(character(), datacrons=[datacron(stat_affix(49, 50_000_000))]) + + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + stats = result["rosterUnit"][0]["stats"] + + assert 0 < stats["datacron"]["Armor"] < 1 + assert 0 < stats["final"]["Armor"] + stats["datacron"]["Armor"] < 1 + + +def test_a_converted_stat_shows_diminishing_returns(calc: StatCalc) -> None: + """Non-linearity is applied, not decorative. + + The conversion is concave, so doubling an affix's value must yield *less* + than double the marginal contribution. A flat delta, or a percentage + applied linearly, would yield exactly double. + """ + + def marginal(value: int) -> float: + payload = player(character(), datacrons=[datacron(stat_affix(49, value))]) + result = calc.calc_player_stats(copy.deepcopy(payload), datacron_id=DATACRON_ID) + assert isinstance(result, dict) + return float(result["rosterUnit"][0]["stats"]["datacron"]["Armor"]) + + single = marginal(50_000_000) + double = marginal(100_000_000) + + assert single > 0 + assert single < double < 2 * single + + +def test_every_datacron_stat_has_a_matching_final_key(calc: StatCalc, example_player: dict[str, Any]) -> None: + """Across the whole roster and every expansion, the two buckets line up.""" + payload = copy.deepcopy(example_player) + payload["datacron"] = [ + datacron( + stat_affix(16, 20_000_000), + stat_affix(48, 30_000_000), + stat_affix(49, 30_000_000), + stat_affix(53, 10_000_000), + stat_affix(54, 10_000_000), + stat_affix(55, 20_000_000), + stat_affix(56, 20_000_000), + ) + ] + + result = calc.calc_player_stats(payload, datacron_id=DATACRON_ID) + assert isinstance(result, dict) + + checked = 0 + for unit in result["rosterUnit"]: + bucket = unit.get("stats", {}).get("datacron") + if not bucket: + continue + assert set(bucket) <= set(unit["stats"]["final"]) + checked += 1 + + assert checked > 100 + + +# ── Degenerate datacrons ────────────────────────────────────────────────── + + +def test_datacron_with_no_affixes_yields_an_empty_bucket(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron()]) + + assert datacron_bucket(calc, payload) == {} + + +def test_partially_levelled_datacron_is_handled(calc: StatCalc) -> None: + """A three-affix datacron is as valid as a fifteen-affix one.""" + payload = player( + character(), + datacrons=[datacron(stat_affix(16, 10_000_000), stat_affix(17, 10_000_000), ability_affix())], + ) + + assert datacron_bucket(calc, payload) == { + "Critical Damage": pytest.approx(0.1), + "Potency": pytest.approx(0.1), + } + + +# ── Selection errors ────────────────────────────────────────────────────── + + +def test_unknown_datacron_id_raises(calc: StatCalc) -> None: + payload = player(character(), datacrons=[datacron(stat_affix(16, 10_000_000))]) + + with pytest.raises(KeyError, match="not among the player's"): + calc.calc_player_stats(payload, datacron_id="no-such-datacron") + + +def test_player_owning_no_datacrons_is_distinct_from_a_missing_collection(calc: StatCalc) -> None: + """An empty collection is a real state; a missing one is a malformed payload.""" + owns_none = player(character(), datacrons=[]) + with pytest.raises(KeyError, match="not among the player's"): + calc.calc_player_stats(owns_none, datacron_id=DATACRON_ID) + + malformed = player(character()) + del malformed["datacron"] + with pytest.raises(KeyError, match="no 'datacron' collection"): + calc.calc_player_stats(malformed, datacron_id=DATACRON_ID) + + +def test_a_missing_collection_is_ignored_when_no_datacron_is_requested(calc: StatCalc) -> None: + payload = player(character()) + del payload["datacron"] + + result = calc.calc_player_stats(payload) + assert isinstance(result, dict) + assert "datacron" not in result["rosterUnit"][0]["stats"] + + +# ── Ships ───────────────────────────────────────────────────────────────── + + +def test_ships_gain_no_bucket_and_their_stats_are_unchanged( + calc: StatCalc, example_player: dict[str, Any], game_data: dict[str, Any] +) -> None: + """Datacrons are a squad mechanic — no game mode applies one to a fleet.""" + owned = example_player["datacron"][0]["id"] + + without = calc.calc_player_stats(copy.deepcopy(example_player)) + with_dc = calc.calc_player_stats(copy.deepcopy(example_player), datacron_id=owned) + assert isinstance(without, dict) + assert isinstance(with_dc, dict) + + ships = { + unit["definitionId"].split(":")[0] + for unit in with_dc["rosterUnit"] + if game_data["unitData"].get(unit["definitionId"].split(":")[0], {}).get("combatType") == 2 + } + assert ships, "example player has no ships; this test would prove nothing" + + by_id = {unit["definitionId"]: unit for unit in without["rosterUnit"]} + for unit in with_dc["rosterUnit"]: + if unit["definitionId"].split(":")[0] not in ships: + continue + assert "datacron" not in unit["stats"] + assert unit["stats"] == by_id[unit["definitionId"]]["stats"] + + +def test_characters_crewing_a_ship_still_receive_their_own_bucket( + calc: StatCalc, example_player: dict[str, Any], game_data: dict[str, Any] +) -> None: + """Crew rating reads a unit's raw attributes, never its calculated stats, + so a crew member's bucket cannot leak into the ship it crews.""" + owned = example_player["datacron"][0]["id"] + + result = calc.calc_player_stats(copy.deepcopy(example_player), datacron_id=owned) + assert isinstance(result, dict) + + crewed = { + crew_id + for unit in result["rosterUnit"] + for crew_id in game_data["unitData"].get(unit["definitionId"].split(":")[0], {}).get("crew", []) + } + assert crewed, "example player has no crewed ships; this test would prove nothing" + + seen = [unit for unit in result["rosterUnit"] if unit["definitionId"].split(":")[0] in crewed and "stats" in unit] + assert seen, "no crew members in roster" + assert all("datacron" in unit["stats"] for unit in seen) diff --git a/tests/unit/test_statcalc_async.py b/tests/unit/test_statcalc_async.py index 551a80a..a91f1e3 100644 --- a/tests/unit/test_statcalc_async.py +++ b/tests/unit/test_statcalc_async.py @@ -120,6 +120,48 @@ async def test_acalc_ship_stats_matches_sync( assert await calc.acalc_ship_stats(copy.deepcopy(ship), copy.deepcopy(crew)) == expected +_DATACRON: dict[str, Any] = { + "id": "test-datacron", + "affix": [ + # Critical Damage +50%, open to every unit. + {"abilityId": "", "statType": 16, "statValue": "50000000", "requiredUnitTier": 0, "requiredRelicTier": 1}, + ], +} + + +def _with_datacron(player: dict[str, Any]) -> dict[str, Any]: + payload = copy.deepcopy(player) + payload["datacron"] = [copy.deepcopy(_DATACRON)] + return payload + + +async def test_acalc_player_stats_passes_the_datacron_id(calc: StatCalcAsync, player: dict[str, Any]) -> None: + expected = calc.calc_player_stats(_with_datacron(player), datacron_id="test-datacron") + + result = await calc.acalc_player_stats(_with_datacron(player), datacron_id="test-datacron") + + assert result == expected + assert isinstance(result, dict) + assert any(u.get("stats", {}).get("datacron") == {"Critical Damage": 0.5} for u in result["rosterUnit"]) + + +async def test_acalc_roster_stats_passes_the_datacron(calc: StatCalcAsync, player: dict[str, Any]) -> None: + expected = calc.calc_roster_stats(copy.deepcopy(player["rosterUnit"]), _DATACRON) + + assert await calc.acalc_roster_stats(copy.deepcopy(player["rosterUnit"]), _DATACRON) == expected + + +async def test_acalc_char_stats_passes_the_datacron( + calc: StatCalcAsync, player: dict[str, Any], game_data: dict[str, Any] +) -> None: + unit = next(u for u in player["rosterUnit"] if game_data["unitData"][_def_id(u)]["combatType"] == 1) + + result = await calc.acalc_char_stats(copy.deepcopy(unit), _DATACRON) + + assert result["stats"]["datacron"] == {"Critical Damage": 0.5} + assert result == calc.calc_char_stats(copy.deepcopy(unit), _DATACRON) + + async def test_acalc_errors_propagate(calc: StatCalcAsync) -> None: not_a_player: Any = "not a player" From c20165597fac4fb4402f3d9413c0b3a403c700e4 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:58:18 -0500 Subject: [PATCH 35/47] test(statcalc): add the datacron golden fixture from in-game readings No reference calculator implements datacrons, so the parity suite cannot check them. The fixture records stat values read off the live game for a hand-authored unit under three datacrons and none, and the test asserts `final + datacron` against them at the precision the game displays. The readings are the measurement: when the implementation disagrees, the implementation changes. The fixture carries no account-identifying fields and the datacron ids are placeholders. Co-Authored-By: Claude Opus 5.5 --- tests/resources/datacron-golden.json | 919 +++++++++++++++++++++++++ tests/statcalc/test_datacron_golden.py | 119 ++++ 2 files changed, 1038 insertions(+) create mode 100644 tests/resources/datacron-golden.json create mode 100644 tests/statcalc/test_datacron_golden.py diff --git a/tests/resources/datacron-golden.json b/tests/resources/datacron-golden.json new file mode 100644 index 0000000..06262ef --- /dev/null +++ b/tests/resources/datacron-golden.json @@ -0,0 +1,919 @@ +{ + "_source": "Stat values read by hand off the live game on 2026-07-28 and typed in. They are the external ground truth for datacron calculation.", + "_warning": "DO NOT REGENERATE THIS FILE FROM StatCalc OUTPUT. Every other number this library produces is checked against the JavaScript reference calculator; datacrons cannot be, because no reference implements them. These readings are the only evidence the arithmetic is right. A fixture produced by the code it is meant to check proves nothing while looking exactly like proof. If a reading disagrees with the implementation, the implementation is what changes -- that has already happened twice: percentages resolve against base and gear, not mods, and apply as the two-decimal value the card displays.", + "_unit": "Hand-authored equivalent of a real roster entry: the gear tier, relic tier, mods and skills that determine the numbers, with every account-identifying field removed.", + "_precision": "Values are as the game displays them. Percent stats are recorded as percentages, at the number of decimals the game showed -- no reading may be asserted more precisely than it was displayed.", + "percent_stats": { + "Critical Damage": 2, + "Armor": 1 + }, + "unit": { + "definitionId": "LORDVADER:SEVEN_STAR", + "currentRarity": 7, + "currentLevel": 85, + "currentTier": 13, + "relic": { + "currentTier": 12 + }, + "equipment": [], + "purchasedAbilityId": [ + "ultimateability_lordvader" + ], + "skill": [ + { + "id": "basicskill_LORDVADER", + "tier": 1 + }, + { + "id": "uniqueskill_GALACTICLEGEND01", + "tier": 1 + }, + { + "id": "uniqueskill_LORDVADER01", + "tier": 1 + }, + { + "id": "leaderskill_LORDVADER", + "tier": 1 + }, + { + "id": "specialskill_LORDVADER02", + "tier": 1 + }, + { + "id": "specialskill_LORDVADER01", + "tier": 1 + } + ], + "equippedStatMod": [ + { + "secondaryStat": [ + { + "roll": [ + "0.18734", + "0.12766", + "0.14950", + "0.12557" + ], + "unscaledRollValue": [ + "1873", + "1277", + "1495", + "1256" + ], + "stat": { + "unitStatId": 55, + "statValueDecimal": "590", + "unscaledDecimalValue": "5901000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 4, + "statRollerBoundsMin": "1000", + "statRollerBoundsMax": "2000" + }, + { + "roll": [ + "0.17141", + "0.19955", + "0.19367", + "0.15874", + "0.18306" + ], + "unscaledRollValue": [ + "514230", + "598650", + "581010", + "476220", + "549180" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "280000", + "unscaledDecimalValue": "2800000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.11907", + "0.17519" + ], + "unscaledRollValue": [ + "1786", + "2628" + ], + "stat": { + "unitStatId": 18, + "statValueDecimal": "441", + "unscaledDecimalValue": "4414000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.16441" + ], + "unscaledRollValue": [ + "2466" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "246", + "unscaledDecimalValue": "2466000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 1, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 48, + "statValueDecimal": "850", + "unscaledDecimalValue": "8500000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "461", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.14159", + "0.10781" + ], + "unscaledRollValue": [ + "2124", + "1617" + ], + "stat": { + "unitStatId": 18, + "statValueDecimal": "374", + "unscaledDecimalValue": "3741000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.18124", + "0.11856", + "0.14520", + "0.17997", + "0.11070" + ], + "unscaledRollValue": [ + "543720", + "355680", + "435600", + "539910", + "332100" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "230000", + "unscaledDecimalValue": "2300000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.11534", + "0.19033" + ], + "unscaledRollValue": [ + "2883500", + "4758250" + ], + "stat": { + "unitStatId": 41, + "statValueDecimal": "770000", + "unscaledDecimalValue": "7700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "2500000", + "statRollerBoundsMax": "5000000" + }, + { + "roll": [ + "0.10581", + "0.17976", + "0.12210" + ], + "unscaledRollValue": [ + "1587", + "2696", + "1832" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "611", + "unscaledDecimalValue": "6115000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 3, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 56, + "statValueDecimal": "2400", + "unscaledDecimalValue": "24000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "462", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.13568", + "0.13129", + "0.18039" + ], + "unscaledRollValue": [ + "62412800", + "60393400", + "82979400" + ], + "stat": { + "unitStatId": 28, + "statValueDecimal": "20570000", + "unscaledDecimalValue": "205700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 3, + "statRollerBoundsMin": "46000000", + "statRollerBoundsMax": "92000000" + }, + { + "roll": [ + "0.10294", + "0.19986", + "0.19259", + "0.14617", + "0.15915" + ], + "unscaledRollValue": [ + "308820", + "599580", + "577770", + "438510", + "477450" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "250000", + "unscaledDecimalValue": "2500000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.11087", + "0.11377" + ], + "unscaledRollValue": [ + "1663", + "1707" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "337", + "unscaledDecimalValue": "3370000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.15034", + "0.11384" + ], + "unscaledRollValue": [ + "1278", + "968" + ], + "stat": { + "unitStatId": 48, + "statValueDecimal": "224", + "unscaledDecimalValue": "2246000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "850", + "statRollerBoundsMax": "1700" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 49, + "statValueDecimal": "2000", + "unscaledDecimalValue": "20000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "163", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.16206", + "0.16759" + ], + "unscaledRollValue": [ + "2431", + "2514" + ], + "stat": { + "unitStatId": 56, + "statValueDecimal": "494", + "unscaledDecimalValue": "4945000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.18997", + "0.19266", + "0.17079", + "0.16452", + "0.15041" + ], + "unscaledRollValue": [ + "569910", + "577980", + "512370", + "493560", + "451230" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "270000", + "unscaledDecimalValue": "2700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.17466", + "0.18903", + "0.15058" + ], + "unscaledRollValue": [ + "2052", + "2221", + "1769" + ], + "stat": { + "unitStatId": 53, + "statValueDecimal": "604", + "unscaledDecimalValue": "6043000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 3, + "statRollerBoundsMin": "1175", + "statRollerBoundsMax": "2350" + }, + { + "roll": [ + "0.16731", + "0.10734" + ], + "unscaledRollValue": [ + "1673", + "1073" + ], + "stat": { + "unitStatId": 55, + "statValueDecimal": "274", + "unscaledDecimalValue": "2747000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1000", + "statRollerBoundsMax": "2000" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 16, + "statValueDecimal": "4200", + "unscaledDecimalValue": "42000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "164", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.15387", + "0.17441", + "0.17100" + ], + "unscaledRollValue": [ + "2308", + "2616", + "2565" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "748", + "unscaledDecimalValue": "7489000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 3, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.19423", + "0.18788", + "0.13273", + "0.19407", + "0.16928" + ], + "unscaledRollValue": [ + "582690", + "563640", + "398190", + "582210", + "507840" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "270000", + "unscaledDecimalValue": "2700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.12147", + "0.15623" + ], + "unscaledRollValue": [ + "1032", + "1328" + ], + "stat": { + "unitStatId": 48, + "statValueDecimal": "236", + "unscaledDecimalValue": "2360000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "850", + "statRollerBoundsMax": "1700" + }, + { + "roll": [ + "0.18987", + "0.19711" + ], + "unscaledRollValue": [ + "2848", + "2957" + ], + "stat": { + "unitStatId": 18, + "statValueDecimal": "580", + "unscaledDecimalValue": "5805000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 56, + "statValueDecimal": "2400", + "unscaledDecimalValue": "24000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "465", + "tier": 5 + }, + { + "secondaryStat": [ + { + "roll": [ + "0.11440" + ], + "unscaledRollValue": [ + "915200" + ], + "stat": { + "unitStatId": 42, + "statValueDecimal": "90000", + "unscaledDecimalValue": "900000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 1, + "statRollerBoundsMin": "800000", + "statRollerBoundsMax": "1600000" + }, + { + "roll": [ + "0.14294", + "0.14832", + "0.15828", + "0.17381" + ], + "unscaledRollValue": [ + "2144", + "2225", + "2374", + "2607" + ], + "stat": { + "unitStatId": 17, + "statValueDecimal": "935", + "unscaledDecimalValue": "9350000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 4, + "statRollerBoundsMin": "1500", + "statRollerBoundsMax": "3000" + }, + { + "roll": [ + "0.15574", + "0.18536", + "0.19249", + "0.17482", + "0.17265" + ], + "unscaledRollValue": [ + "467220", + "556080", + "577470", + "524460", + "517950" + ], + "stat": { + "unitStatId": 5, + "statValueDecimal": "270000", + "unscaledDecimalValue": "2700000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 5, + "statRollerBoundsMin": "300000", + "statRollerBoundsMax": "600000" + }, + { + "roll": [ + "0.11378", + "0.19939" + ], + "unscaledRollValue": [ + "1337", + "2343" + ], + "stat": { + "unitStatId": 53, + "statValueDecimal": "368", + "unscaledDecimalValue": "3680000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 2, + "statRollerBoundsMin": "1175", + "statRollerBoundsMax": "2350" + } + ], + "level": 15, + "primaryStat": { + "roll": [], + "unscaledRollValue": [], + "stat": { + "unitStatId": 56, + "statValueDecimal": "2400", + "unscaledDecimalValue": "24000000", + "uiDisplayOverrideValue": "-1", + "scalar": "0" + }, + "statRolls": 0, + "statRollerBoundsMin": "0", + "statRollerBoundsMax": "0" + }, + "definitionId": "466", + "tier": 5 + } + ] + }, + "datacrons": [ + { + "id": "datacron-a", + "setId": 32, + "templateId": "datacron_set_32_base", + "affix": [ + { + "requiredUnitTier": 2, + "statType": 16, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "17443980" + }, + { + "requiredUnitTier": 2, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "2828575" + }, + { + "requiredUnitTier": 2, + "statType": 1, + "abilityId": "datacron_faction_generic_043", + "requiredRelicTier": 1, + "statValue": "0" + }, + { + "requiredUnitTier": 4, + "statType": 16, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "34405787" + }, + { + "requiredUnitTier": 4, + "statType": 16, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "33342140" + }, + { + "requiredUnitTier": 0, + "statType": 1, + "abilityId": "datacron_faction_generic_007", + "requiredRelicTier": 6, + "statValue": "0" + }, + { + "requiredUnitTier": 0, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 8, + "statValue": "19515055" + }, + { + "requiredUnitTier": 0, + "statType": 56, + "abilityId": "", + "requiredRelicTier": 8, + "statValue": "27143270" + }, + { + "requiredUnitTier": 0, + "statType": 1, + "abilityId": "datacron_character_talia_001", + "requiredRelicTier": 8, + "statValue": "0" + } + ] + }, + { + "id": "datacron-b", + "setId": 32, + "templateId": "datacron_set_32_base", + "affix": [ + { + "requiredUnitTier": 2, + "statType": 56, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "8305491" + }, + { + "requiredUnitTier": 2, + "statType": 55, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "6086343" + }, + { + "requiredUnitTier": 2, + "statType": 1, + "abilityId": "datacron_faction_generic_023", + "requiredRelicTier": 1, + "statValue": "0" + } + ] + }, + { + "id": "datacron-c", + "setId": 31, + "templateId": "datacron_set_31_base", + "affix": [ + { + "requiredUnitTier": 2, + "statType": 17, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "26721944" + }, + { + "requiredUnitTier": 2, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "3674536" + }, + { + "requiredUnitTier": 2, + "statType": 1, + "abilityId": "datacron_alignment_generic_003", + "requiredRelicTier": 1, + "statValue": "0" + }, + { + "requiredUnitTier": 4, + "statType": 56, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "11645456" + }, + { + "requiredUnitTier": 4, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 1, + "statValue": "9803783" + }, + { + "requiredUnitTier": 0, + "statType": 1, + "abilityId": "datacron_faction_separatist_002", + "requiredRelicTier": 6, + "statValue": "0" + }, + { + "requiredUnitTier": 0, + "statType": 48, + "abilityId": "", + "requiredRelicTier": 8, + "statValue": "11348363" + }, + { + "requiredUnitTier": 0, + "statType": 16, + "abilityId": "", + "requiredRelicTier": 8, + "statValue": "36362478" + }, + { + "requiredUnitTier": 0, + "statType": 1, + "abilityId": "datacron_character_trench_001", + "requiredRelicTier": 8, + "statValue": "0" + } + ] + } + ], + "readings": [ + { + "datacron": null, + "asserted": true, + "stats": { + "Health": 124335, + "Protection": 208666, + "Speed": 586, + "Physical Damage": 11004, + "Critical Damage": 192.0, + "Armor": 56.1 + } + }, + { + "datacron": "datacron-a", + "asserted": true, + "stats": { + "Health": 124335, + "Protection": 240356, + "Speed": 586, + "Physical Damage": 13162, + "Critical Damage": 277.19, + "Armor": 56.1 + } + }, + { + "datacron": "datacron-c", + "asserted": true, + "note": "Screenshot cropped to Health and Protection; nothing else was read.", + "stats": { + "Health": 124335, + "Protection": 222269 + } + }, + { + "datacron": "datacron-b", + "asserted": false, + "note": "Recorded but not asserted. This capture is the only one whose mod contribution displayed one higher on both stats -- 91902 and 19542, against 91901 and 19541 in every other reading -- so the unit was not in the same state. Reconstructing its baseline from its own mods figure gives base+gear identical to the other readings and reproduces both totals exactly, so it corroborates the displayed-percentage rule rather than contradicting it. Kept here so the data is visible and the reason for excluding it is on the record.", + "stats": { + "Health": 130717, + "Protection": 218370 + } + } + ] +} diff --git a/tests/statcalc/test_datacron_golden.py b/tests/statcalc/test_datacron_golden.py new file mode 100644 index 0000000..0556af7 --- /dev/null +++ b/tests/statcalc/test_datacron_golden.py @@ -0,0 +1,119 @@ +"""Datacron output against stat values read by hand off the live game. + +This is the only evidence that datacron arithmetic is correct. Every other +number `StatCalc` produces is diffed against the JavaScript reference +calculator; datacrons cannot be, because no reference implements them and the +stats service does not calculate them either. + +If a test here fails, the implementation is what changes -- not the fixture. +The fixture is a measurement. It has already overturned the implementation +twice: percentages resolve against base and gear, not base, gear and mods; and +the two-decimal percentage the card shows is what gets applied, summed before +it is rounded. + +Unlike the parity suite this runs by default and needs nothing external -- the +readings are committed. Putting it behind a marker would leave the feature's +only correctness guard skipped in normal runs. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path +from typing import Any + +import pytest + +from swgoh_comlink import StatCalc + +_RESOURCES = Path(__file__).resolve().parent.parent / "resources" +_GAME_DATA_FILE = _RESOURCES / "gameData.json" +_GOLDEN_FILE = _RESOURCES / "datacron-golden.json" + +# Loaded at import so every asserted reading becomes its own test case, named +# for the datacron it came from. +_GOLDEN: dict[str, Any] = json.loads(_GOLDEN_FILE.read_text()) +_ASSERTED: list[dict[str, Any]] = [r for r in _GOLDEN["readings"] if r["asserted"]] + + +@pytest.fixture(scope="module") +def golden() -> dict[str, Any]: + return json.loads(_GOLDEN_FILE.read_text()) + + +@pytest.fixture(scope="module") +def calc() -> StatCalc: + return StatCalc(game_data=json.loads(_GAME_DATA_FILE.read_text())["data"]) + + +def _asserted(golden: dict[str, Any]) -> list[dict[str, Any]]: + return [r for r in golden["readings"] if r["asserted"]] + + +def _observed(calc: StatCalc, golden: dict[str, Any], datacron_id: str | None) -> dict[str, float]: + """Run the hand-authored unit and return `final + datacron` per stat.""" + payload = { + "rosterUnit": [copy.deepcopy(golden["unit"])], + "datacron": copy.deepcopy(golden["datacrons"]), + } + result = calc.calc_player_stats(payload, datacron_id=datacron_id) + assert isinstance(result, dict) + stats = result["rosterUnit"][0]["stats"] + combined = dict(stats["final"]) + for name, value in stats.get("datacron", {}).items(): + combined[name] = combined.get(name, 0) + value + return combined + + +def _as_displayed(name: str, value: float, percent_stats: dict[str, int]) -> float: + """Express a computed stat the way the game printed it. + + A reading cannot be checked more precisely than it was displayed. + """ + if name in percent_stats: + return round(value * 100, percent_stats[name]) + return round(value) + + +@pytest.mark.parametrize( + "reading", + _ASSERTED, + ids=[r["datacron"] or "no-datacron" for r in _ASSERTED], +) +def test_matches_values_read_from_the_game(calc: StatCalc, golden: dict[str, Any], reading: dict[str, Any]) -> None: + combined = _observed(calc, golden, reading["datacron"]) + percent_stats = golden["percent_stats"] + + for name, expected in reading["stats"].items(): + assert name in combined, f"{name} missing from calculated output" + assert _as_displayed(name, combined[name], percent_stats) == expected, ( + f"datacron={reading['datacron']} stat={name}: " + f"calculated {combined[name]!r} does not match the value read in game. " + f"Fix the implementation, not this fixture." + ) + + +def test_every_asserted_reading_is_exercised(golden: dict[str, Any]) -> None: + """Guards the parametrisation above from silently covering fewer readings.""" + assert len(_asserted(golden)) == 3 + + +def test_unasserted_readings_carry_their_reason(golden: dict[str, Any]) -> None: + """A reading may be excluded, but never silently.""" + for reading in golden["readings"]: + if not reading["asserted"]: + assert reading.get("note"), "an unasserted reading must say why" + + +def test_fixture_warns_against_regeneration(golden: dict[str, Any]) -> None: + """The warning is the fixture's only defence against being 'refreshed'.""" + assert "DO NOT REGENERATE" in golden["_warning"] + + +def test_the_unit_carries_no_account_identifying_fields(golden: dict[str, Any]) -> None: + """The unit is a hand-authored equivalent, not a copied roster entry.""" + unit = golden["unit"] + assert not {"id", "currentXp", "unitStat", "promotionRecipeReference"} & set(unit) + for mod in unit["equippedStatMod"]: + assert "id" not in mod From c213f68a248b9b540b3eaffa545914f4d2dd8f5d Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:58:20 -0500 Subject: [PATCH 36/47] docs(examples): add sync and async datacron calculation examples Walks through applying a datacron, combining it with `final`, affix requirements across units, comparing datacrons, ships being unaffected, and applying one of a real player's datacrons fetched from Comlink. Co-Authored-By: Claude Opus 5.5 --- examples/Async/README.md | 1 + examples/Async/calc_datacron_stats.py | 237 ++++++++++++++++++++++++++ examples/Sync/README.md | 1 + examples/Sync/calc_datacron_stats.py | 235 +++++++++++++++++++++++++ 4 files changed, 474 insertions(+) create mode 100644 examples/Async/calc_datacron_stats.py create mode 100644 examples/Sync/calc_datacron_stats.py diff --git a/examples/Async/README.md b/examples/Async/README.md index 7a07a92..3d4c278 100644 --- a/examples/Async/README.md +++ b/examples/Async/README.md @@ -6,6 +6,7 @@ These examples use the `SwgohComlinkAsync` async client. All methods must be `aw | File | Description | |------|-------------| +| `calc_datacron_stats.py` | Apply a datacron to a roster and combine it with `final` stats | | `calc_stats_local.py` | Calculate character stats locally using `StatCalcAsync` | | `get_events.py` | Retrieve current game events with timestamps and status | | `get_gac_brackets.py` | Scan GAC brackets for a league and search for a player (parallel batches) | diff --git a/examples/Async/calc_datacron_stats.py b/examples/Async/calc_datacron_stats.py new file mode 100644 index 0000000..4a165b8 --- /dev/null +++ b/examples/Async/calc_datacron_stats.py @@ -0,0 +1,237 @@ +""" +calc_datacron_stats.py +Applying a datacron to a roster with async StatCalcAsync support. + +A datacron is never equipped to a unit — a player owns dozens and picks one per +squad when they deploy. So there is no such thing as "this unit's stats with +datacrons", only "this unit's stats given *this* datacron". You name the one you +mean; the library never chooses. + +`create()` fetches game data without blocking the event loop, and each +`acalc_*` method runs the matching `calc_*` method in a worker thread, so a +large roster does not stall the loop either. They take the same datacron +arguments as their synchronous counterparts. + +Demonstrates: + 1. Applying a datacron and reading its contribution + 2. Combining `final` and `datacron` to get battle-ready stats + 3. Affix requirements — the same datacron gives different units different amounts + 4. Comparing several datacrons for one unit + 5. Ships, which datacrons never touch + 6. Doing the same against a real player from a running Comlink service + +Examples 1 to 5 use a hand-authored roster and need only game data, which is +fetched from GitHub. Example 6 needs a running Comlink service. + +See the Sync example for the same walkthrough without the event loop. +""" + +import asyncio + +from swgoh_comlink import StatCalcAsync, SwgohComlinkAsync + +# ── A datacron, shaped as the game reports one ──────────────────────────── +# +# Affixes come in threes. Every third one grants an *ability* rather than a +# stat — it reports stat type 1 with value 0 and names a targeting rule. Those +# contribute nothing to stats and StatCalc skips them. +# +# `requiredUnitTier` is a gear tier and `requiredRelicTier` a relic tier. Both +# are compared directly against the unit. Note relic tiers are encoded with +# their locked and unlocked base states occupying the first two values, so a +# `requiredRelicTier` of 8 means relic 6 as a player would count it. +# +# Values are fixed point, where 1e8 is 100%. 27143270 is 27.14327%. + + +def stat_affix(stat_type, value, unit_tier=0, relic_tier=1): + return { + "statType": stat_type, + "statValue": str(value), + "requiredUnitTier": unit_tier, + "requiredRelicTier": relic_tier, + "abilityId": "", + "targetRule": "", + } + + +def ability_affix(ability_id, unit_tier=0, relic_tier=1): + return { + "statType": 1, + "statValue": "0", + "requiredUnitTier": unit_tier, + "requiredRelicTier": relic_tier, + "abilityId": ability_id, + "targetRule": "target_datacron_darkside", + } + + +# Stat types: 16 Critical Damage, 48 Offense%, 55 Health%, 56 Protection% +maxed_datacron = { + "id": "maxed", + "affix": [ + stat_affix(16, 17_443_980, unit_tier=2), + stat_affix(48, 2_828_575, unit_tier=2), + ability_affix("datacron_faction_generic_043", unit_tier=2), + stat_affix(16, 34_405_787, unit_tier=4), + stat_affix(16, 33_342_140, unit_tier=4), + ability_affix("datacron_faction_generic_007", relic_tier=6), + stat_affix(48, 19_515_055, relic_tier=8), + stat_affix(56, 27_143_270, relic_tier=8), + ability_affix("datacron_character_talia_001", relic_tier=8), + ], +} + +starter_datacron = { + "id": "starter", + "affix": [ + stat_affix(56, 8_305_491, unit_tier=2), + stat_affix(55, 6_086_343, unit_tier=2), + ability_affix("datacron_faction_generic_023", unit_tier=2), + ], +} + + +def character(def_id, gear_tier=13, relic_tier=12): + """A roster unit. `relic_tier=None` gives a unit with no relic at all.""" + return { + "definitionId": f"{def_id}:SEVEN_STAR", + "currentRarity": 7, + "currentLevel": 85, + "currentTier": gear_tier, + "equipment": [], + "skill": [], + "equippedStatMod": [], + "relic": None if relic_tier is None else {"currentTier": relic_tier}, + } + + +def show(value): + """Percentage stats come back as fractions; flat stats as whole numbers.""" + return f"{value:,.0f}" if abs(value) >= 100 else f"{value:.4f}" + + +async def main(): + calc = await StatCalcAsync.create() # fetches game data from GitHub + + # ── Example 1: apply a datacron and read its contribution ───────────── + + player = { + "rosterUnit": [character("CADBANE")], + "datacron": [maxed_datacron, starter_datacron], + } + + await calc.acalc_player_stats(player, datacron_id="maxed") + stats = player["rosterUnit"][0]["stats"] + + print("=== Example 1: what the datacron adds ===") + for name, amount in sorted(stats["datacron"].items()): + print(f" {name:<20} +{show(amount)}") + + # Ask for nothing and nothing changes — no `datacron` key appears at all. + untouched = {"rosterUnit": [character("CADBANE")], "datacron": []} + await calc.acalc_player_stats(untouched) + print("\n bucket present when no datacron requested:", "datacron" in untouched["rosterUnit"][0]["stats"]) + + # ── Example 2: combining the buckets ────────────────────────────────── + # + # The `datacron` bucket sits *beside* `final`, never inside it. A datacron + # is a hypothetical you supplied, so folding it into `final` would make that + # field mean different things depending on an argument. Add them yourself: + + combined = {name: value + stats["datacron"].get(name, 0) for name, value in stats["final"].items()} + + print("\n=== Example 2: final + datacron ===") + for name in ("Protection", "Physical Damage", "Critical Damage", "Health"): + before, after = stats["final"][name], combined[name] + moved = "" if before == after else " <- moved" + print(f" {name:<18} {show(before):>10} -> {show(after):>10}{moved}") + + # Health is untouched because this datacron carries no Health affix. That is + # the normal case: a datacron moves a handful of stats, not all of them. + # + # The addition is correct for *every* stat, including ones reported as + # percentages such as Armor. Those are stored non-linearly, so a raw + # percentage could not simply be added — the bucket holds the marginal + # amount the datacron actually contributes on top of everything else. + + # ── Example 3: affix requirements ───────────────────────────────────── + + squad = { + "rosterUnit": [ + character("CADBANE", gear_tier=13, relic_tier=12), # relic 10 — clears everything + character("BOSSK", gear_tier=13, relic_tier=7), # relic 5 — below the relic-8 affixes + character("JAWA", gear_tier=1, relic_tier=None), # no relic — clears nothing + ], + "datacron": [maxed_datacron], + } + await calc.acalc_player_stats(squad, datacron_id="maxed") + + print("\n=== Example 3: the same datacron, three units ===") + for unit in squad["rosterUnit"]: + name = unit["definitionId"].split(":")[0] + relic = (unit["relic"] or {}).get("currentTier", 1) + granted = sorted(unit["stats"]["datacron"]) or ["nothing"] + print(f" {name:<9} gear {unit['currentTier']:<3} relic {relic:<3} -> {', '.join(granted)}") + + # BOSSK sits below the relic requirement on two affixes, so he gets strictly + # less than CADBANE from the very same datacron. JAWA qualifies for nothing. + + # ── Example 4: comparing datacrons ──────────────────────────────────── + # + # The library never picks for you, so comparing means asking twice. + + print("\n=== Example 4: which datacron suits this unit? ===") + for datacron_id in ("maxed", "starter"): + candidate = {"rosterUnit": [character("CADBANE")], "datacron": [maxed_datacron, starter_datacron]} + await calc.acalc_player_stats(candidate, datacron_id=datacron_id) + bucket = candidate["rosterUnit"][0]["stats"]["datacron"] + protection = bucket.get("Protection", 0) + damage = bucket.get("Physical Damage", 0) + print(f" {datacron_id:<9} Protection +{protection:<10,.0f} Physical Damage +{damage:,.0f}") + + # ── Example 5: ships ────────────────────────────────────────────────── + # + # Datacrons are a squad mechanic. No game mode applies one to a fleet + # battle, so ships receive no bucket and their stats are untouched. + + fleet = { + "rosterUnit": [character("CADBANE"), character("VULTUREDROID")], # a crewless ship + "datacron": [maxed_datacron], + } + await calc.acalc_player_stats(fleet, datacron_id="maxed") + + print("\n=== Example 5: ships are never affected ===") + for unit in fleet["rosterUnit"]: + name = unit["definitionId"].split(":")[0] + print(f" {name:<14} datacron bucket: {'datacron' in unit['stats']}") + + # ── Example 6: a real player ────────────────────────────────────────── + # + # Requires a running Comlink service. The datacron id comes from the + # player's own collection, which is why this entry point takes an id rather + # than an object — `acalc_roster_stats` and `acalc_char_stats` take the + # object, having no player to look it up in. Naming a datacron the player + # does not own raises KeyError, so a mistyped id fails loudly rather than + # silently adding nothing. + + async with SwgohComlinkAsync() as comlink: + real_player = await comlink.get_player(allycode=314927874) + + print("\n=== Example 6: a real player ===") + if not real_player.get("datacron"): + print(" this player owns no datacrons") + return + + chosen = real_player["datacron"][0] + await calc.acalc_player_stats(real_player, datacron_id=chosen["id"]) + + affected = [unit for unit in real_player["rosterUnit"] if unit.get("stats", {}).get("datacron")] + print(f" {chosen['templateId']} adds stats to {len(affected)} of {len(real_player['rosterUnit'])} units") + for unit in affected[:3]: + name = unit["definitionId"].split(":")[0] + added = ", ".join(f"{stat} +{show(amount)}" for stat, amount in sorted(unit["stats"]["datacron"].items())) + print(f" {name:<20} {added}") + + +asyncio.run(main()) diff --git a/examples/Sync/README.md b/examples/Sync/README.md index a5060ed..454bc9d 100644 --- a/examples/Sync/README.md +++ b/examples/Sync/README.md @@ -6,6 +6,7 @@ These examples use the `SwgohComlink` synchronous client. They run in a standard | File | Description | |------|-------------| +| `calc_datacron_stats.py` | Apply a datacron to a roster and combine it with `final` stats | | `calc_stats_local.py` | Calculate character stats locally using the `StatCalc` module | | `get_events.py` | Retrieve current game events with timestamps and status | | `get_gac_brackets.py` | Scan GAC brackets for a league and search for a player | diff --git a/examples/Sync/calc_datacron_stats.py b/examples/Sync/calc_datacron_stats.py new file mode 100644 index 0000000..a8e5c37 --- /dev/null +++ b/examples/Sync/calc_datacron_stats.py @@ -0,0 +1,235 @@ +""" +calc_datacron_stats.py +Applying a datacron to a roster with local StatCalc support. + +A datacron is never equipped to a unit — a player owns dozens and picks one per +squad when they deploy. So there is no such thing as "this unit's stats with +datacrons", only "this unit's stats given *this* datacron". You name the one you +mean; the library never chooses. + +Demonstrates: + 1. Applying a datacron and reading its contribution + 2. Combining `final` and `datacron` to get battle-ready stats + 3. Affix requirements — the same datacron gives different units different amounts + 4. Comparing several datacrons for one unit + 5. Ships, which datacrons never touch + 6. Doing the same against a real player from a running Comlink service + +Examples 1 to 5 use a hand-authored roster and need only game data, which is +fetched from GitHub. Example 6 needs a running Comlink service. +""" + +from swgoh_comlink import StatCalc, SwgohComlink + +# ── A datacron, shaped as the game reports one ──────────────────────────── +# +# Affixes come in threes. Every third one grants an *ability* rather than a +# stat — it reports stat type 1 with value 0 and names a targeting rule. Those +# contribute nothing to stats and StatCalc skips them. +# +# `requiredUnitTier` is a gear tier and `requiredRelicTier` a relic tier. Both +# are compared directly against the unit. Note relic tiers are encoded with +# their locked and unlocked base states occupying the first two values, so a +# `requiredRelicTier` of 8 means relic 6 as a player would count it. +# +# Values are fixed point, where 1e8 is 100%. 27143270 is 27.14327%. + + +def stat_affix(stat_type, value, unit_tier=0, relic_tier=1): + return { + "statType": stat_type, + "statValue": str(value), + "requiredUnitTier": unit_tier, + "requiredRelicTier": relic_tier, + "abilityId": "", + "targetRule": "", + } + + +def ability_affix(ability_id, unit_tier=0, relic_tier=1): + return { + "statType": 1, + "statValue": "0", + "requiredUnitTier": unit_tier, + "requiredRelicTier": relic_tier, + "abilityId": ability_id, + "targetRule": "target_datacron_darkside", + } + + +# Stat types: 16 Critical Damage, 48 Offense%, 56 Protection% +maxed_datacron = { + "id": "maxed", + "affix": [ + stat_affix(16, 17_443_980, unit_tier=2), + stat_affix(48, 2_828_575, unit_tier=2), + ability_affix("datacron_faction_generic_043", unit_tier=2), + stat_affix(16, 34_405_787, unit_tier=4), + stat_affix(16, 33_342_140, unit_tier=4), + ability_affix("datacron_faction_generic_007", relic_tier=6), + stat_affix(48, 19_515_055, relic_tier=8), + stat_affix(56, 27_143_270, relic_tier=8), + ability_affix("datacron_character_talia_001", relic_tier=8), + ], +} + +# A shorter one, for the comparison in Example 4. +starter_datacron = { + "id": "starter", + "affix": [ + stat_affix(56, 8_305_491, unit_tier=2), + stat_affix(55, 6_086_343, unit_tier=2), + ability_affix("datacron_faction_generic_023", unit_tier=2), + ], +} + + +def character(def_id, gear_tier=13, relic_tier=12): + """A roster unit. `relic_tier=None` gives a unit with no relic at all.""" + return { + "definitionId": f"{def_id}:SEVEN_STAR", + "currentRarity": 7, + "currentLevel": 85, + "currentTier": gear_tier, + "equipment": [], + "skill": [], + "equippedStatMod": [], + "relic": None if relic_tier is None else {"currentTier": relic_tier}, + } + + +calc = StatCalc() # fetches game data from GitHub on init + + +# ── Example 1: apply a datacron and read its contribution ───────────────── + +player = { + "rosterUnit": [character("CADBANE")], + "datacron": [maxed_datacron, starter_datacron], +} + +calc.calc_player_stats(player, datacron_id="maxed") +stats = player["rosterUnit"][0]["stats"] + + +def show(value): + """Percentage stats come back as fractions; flat stats as whole numbers.""" + return f"{value:,.0f}" if abs(value) >= 100 else f"{value:.4f}" + + +print("=== Example 1: what the datacron adds ===") +for name, amount in sorted(stats["datacron"].items()): + print(f" {name:<20} +{show(amount)}") + +# Ask for nothing and nothing changes — no `datacron` key appears at all. +untouched = {"rosterUnit": [character("CADBANE")], "datacron": []} +calc.calc_player_stats(untouched) +print("\n bucket present when no datacron requested:", "datacron" in untouched["rosterUnit"][0]["stats"]) + + +# ── Example 2: combining the buckets ────────────────────────────────────── +# +# The `datacron` bucket sits *beside* `final`, never inside it. A datacron is a +# hypothetical you supplied, so folding it into `final` would make that field +# mean different things depending on an argument. Add them yourself: + +combined = {name: value + stats["datacron"].get(name, 0) for name, value in stats["final"].items()} + + +print("\n=== Example 2: final + datacron ===") +for name in ("Protection", "Physical Damage", "Critical Damage", "Health"): + before, after = stats["final"][name], combined[name] + moved = "" if before == after else " <- moved" + print(f" {name:<18} {show(before):>10} -> {show(after):>10}{moved}") + +# Health is untouched because this datacron carries no Health affix. That is +# the normal case: a datacron moves a handful of stats, not all of them. +# +# The addition is correct for *every* stat, including ones reported as +# percentages such as Armor. Those are stored non-linearly, so a raw percentage +# could not simply be added — the bucket holds the marginal amount the datacron +# actually contributes on top of everything else. + + +# ── Example 3: affix requirements ───────────────────────────────────────── +# +# Each affix names a gear tier and a relic tier the unit must reach. One +# datacron therefore contributes differently across a roster. + +squad = { + "rosterUnit": [ + character("CADBANE", gear_tier=13, relic_tier=12), # relic 10 — clears everything + character("BOSSK", gear_tier=13, relic_tier=7), # relic 5 — below the relic-8 affixes + character("JAWA", gear_tier=1, relic_tier=None), # no relic — clears nothing + ], + "datacron": [maxed_datacron], +} +calc.calc_player_stats(squad, datacron_id="maxed") + +print("\n=== Example 3: the same datacron, three units ===") +for unit in squad["rosterUnit"]: + name = unit["definitionId"].split(":")[0] + relic = (unit["relic"] or {}).get("currentTier", 1) + granted = sorted(unit["stats"]["datacron"]) or ["nothing"] + print(f" {name:<9} gear {unit['currentTier']:<3} relic {relic:<3} -> {', '.join(granted)}") + +# BOSSK sits below the relic requirement on two affixes, so he gets strictly +# less than CADBANE from the very same datacron. JAWA qualifies for nothing. + + +# ── Example 4: comparing datacrons ──────────────────────────────────────── +# +# The library never picks for you, so comparing means asking twice. + +print("\n=== Example 4: which datacron suits this unit? ===") +for datacron_id in ("maxed", "starter"): + candidate = {"rosterUnit": [character("CADBANE")], "datacron": [maxed_datacron, starter_datacron]} + calc.calc_player_stats(candidate, datacron_id=datacron_id) + bucket = candidate["rosterUnit"][0]["stats"]["datacron"] + protection = bucket.get("Protection", 0) + damage = bucket.get("Physical Damage", 0) + print(f" {datacron_id:<9} Protection +{protection:<10,.0f} Physical Damage +{damage:,.0f}") + + +# ── Example 5: ships ────────────────────────────────────────────────────── +# +# Datacrons are a squad mechanic. No game mode applies one to a fleet battle, +# so ships receive no bucket and their stats are untouched. + +fleet = { + "rosterUnit": [character("CADBANE"), character("VULTUREDROID")], # a crewless ship + "datacron": [maxed_datacron], +} +calc.calc_player_stats(fleet, datacron_id="maxed") + +print("\n=== Example 5: ships are never affected ===") +for unit in fleet["rosterUnit"]: + name = unit["definitionId"].split(":")[0] + has_bucket = "datacron" in unit["stats"] + print(f" {name:<14} datacron bucket: {has_bucket}") + + +# ── Example 6: a real player ────────────────────────────────────────────── +# +# Requires a running Comlink service. The datacron id comes from the player's +# own collection, which is why this entry point takes an id rather than an +# object — `calc_roster_stats` and `calc_char_stats` take the object, having no +# player to look it up in. Naming a datacron the player does not own raises +# KeyError, so a mistyped id fails loudly rather than silently adding nothing. + +comlink = SwgohComlink() +real_player = comlink.get_player(allycode=314927874) + +print("\n=== Example 6: a real player ===") +if not real_player.get("datacron"): + print(" this player owns no datacrons") +else: + chosen = real_player["datacron"][0] + calc.calc_player_stats(real_player, datacron_id=chosen["id"]) + + affected = [unit for unit in real_player["rosterUnit"] if unit.get("stats", {}).get("datacron")] + print(f" {chosen['templateId']} adds stats to {len(affected)} of {len(real_player['rosterUnit'])} units") + for unit in affected[:3]: + name = unit["definitionId"].split(":")[0] + added = ", ".join(f"{stat} +{show(amount)}" for stat, amount in sorted(unit["stats"]["datacron"].items())) + print(f" {name:<20} {added}") From ff158cd4891acda6823387e4bee925d1c6503c85 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:59:20 -0500 Subject: [PATCH 37/47] feat(helpers): add get_omicron_breakdown for guild-wide omicron adoption Summarise omicron adoption across a set of player profiles, grouped by game mode. Every omicron skill in game data becomes a row that splits the players into those who have applied it, those who own the unit but have not, and a count of those who do not own the unit. A skill is an omicron when one of its tiers is flagged isOmicronTier, never because of its omicronMode: mode 1 (ALL_OMICRON) is the value every skill without an omicron carries. The mode is read as a number whether the game data was fetched with enums=False or enums=True, including the type-prefixed spelling, through parse_enum and the OmicronMode members; a mode name the library does not know yet is kept as given. Labels default to OMICRON_MODE and can be overridden. Ownership is a property of the unit, resolved through the unit that can be in a roster. Many omicron skills are referenced by several base IDs, a playable unit plus a non-obtainable PVE_ mirror and sometimes an event variant, so playable units (get_playable_units, which also reads an enums=True rarity) claim their skills first. A skill missing from an owner's roster is star-gated, not evidence of non-ownership, and a listed skill without a tier is at tier 0. An optional ability_list names each omicron from the ability its skill references; a skill's own nameKey is a placeholder shared across unrelated skills, and a unit often has several omicrons in one mode. Unit and omicron names are localized through _localize. Co-Authored-By: Claude Opus 5.5 --- docs/api/helpers.md | 63 ++++++ src/swgoh_comlink/helpers/__init__.py | 10 + src/swgoh_comlink/helpers/_omicron.py | 294 +++++++++++++++++++++++++- tests/unit/test_helpers.py | 266 +++++++++++++++++++++++ 4 files changed, 632 insertions(+), 1 deletion(-) diff --git a/docs/api/helpers.md b/docs/api/helpers.md index e9f9ae0..7b48679 100644 --- a/docs/api/helpers.md +++ b/docs/api/helpers.md @@ -1207,6 +1207,69 @@ Functions for querying omicron skill data from game data collections. show_root_heading: true show_root_full_path: false +### get_omicron_breakdown + +Summarizes omicron adoption across a set of player profiles, grouped by game mode. For every +omicron in game data it lists the players who have applied it, the players who own the unit +but have not, and how many do not own the unit. + +It takes **player profiles**, not guild member entries: a guild's `member` list carries no +roster, so fetch each member's profile first. Pass `ability_list` whenever a person will read +the result. A unit often has several omicrons in one mode, so the unit name alone does not +tell the rows apart, and the omicron's own name comes from the `ability` collection. + +```python +from swgoh_comlink import SwgohComlink +from swgoh_comlink.helpers import DataItems, get_guild_members, get_localization_dictionary, get_omicron_breakdown + +comlink = SwgohComlink() +members = get_guild_members(comlink, allycode=314927874) +profiles = [comlink.get_player(player_id=member["playerId"]) for member in members] +game_data = comlink.get_game_data( + items=DataItems.SKILL | DataItems.UNITS | DataItems.ABILITY, include_pve_units=False +) + +breakdown = get_omicron_breakdown( + profiles, + game_data["skill"], + game_data["units"], + ability_list=game_data["ability"], + localization=get_localization_dictionary(comlink), +) +for mode in breakdown["modes"]: + for row in mode["skills"]: + print(mode["mode_name"], row["unit_name"], row["skill_name"], len(row["applied"])) +``` + +See `examples/Sync/guild_omicron_breakdown.py` for a full report, and +`examples/Async/guild_omicron_breakdown.py` for the same report with the profiles fetched +concurrently. + +::: swgoh_comlink.helpers._omicron.get_omicron_breakdown + options: + show_root_heading: true + show_root_full_path: false + +::: swgoh_comlink.helpers._omicron.OmicronBreakdown + options: + show_root_heading: true + show_root_full_path: false + +::: swgoh_comlink.helpers._omicron.OmicronModeBreakdown + options: + show_root_heading: true + show_root_full_path: false + +::: swgoh_comlink.helpers._omicron.OmicronSkillStats + options: + show_root_heading: true + show_root_full_path: false + +::: swgoh_comlink.helpers._omicron.OmicronMember + options: + show_root_heading: true + show_root_full_path: false + --- ## Localization Helpers diff --git a/src/swgoh_comlink/helpers/__init__.py b/src/swgoh_comlink/helpers/__init__.py index ab90e5b..f5d0811 100644 --- a/src/swgoh_comlink/helpers/__init__.py +++ b/src/swgoh_comlink/helpers/__init__.py @@ -61,6 +61,11 @@ parse_swgoh_string, ) from ._omicron import ( + OmicronBreakdown, + OmicronMember, + OmicronModeBreakdown, + OmicronSkillStats, + get_omicron_breakdown, get_omicron_skill_tier, get_omicron_skills, get_tw_omicrons, @@ -217,6 +222,11 @@ "get_named_rewards", "get_player_title_names", # Omicron + "OmicronBreakdown", + "OmicronMember", + "OmicronModeBreakdown", + "OmicronSkillStats", + "get_omicron_breakdown", "get_omicron_skill_tier", "get_omicron_skills", "get_tw_omicrons", diff --git a/src/swgoh_comlink/helpers/_omicron.py b/src/swgoh_comlink/helpers/_omicron.py index d0ace5e..afb24c9 100644 --- a/src/swgoh_comlink/helpers/_omicron.py +++ b/src/swgoh_comlink/helpers/_omicron.py @@ -3,9 +3,38 @@ from __future__ import annotations -from typing import Any, NamedTuple +from collections.abc import Mapping +from typing import Any, NamedTuple, TypedDict from ..exceptions import SwgohComlinkValueError +from ._game_data import get_playable_units +from ._localization import _localize +from ._stat_data import OMICRON_MODE +from ._utils import get_function_name +from ._wire import as_int, as_list, as_scalar, as_str, base_id, parse_enum + +# OmicronMode members. omicronMode arrives as a number (enums=False) or a member name (enums=True), bare +# (TERRITORY_WAR_OMICRON) or type-prefixed (OMICRONMODE_TERRITORYWAROMICRON); parse_enum reads all three. +_OMICRON_MODES: dict[str, int] = { + "OmicronMode_DEFAULT": 0, + "ALL_OMICRON": 1, + "PVE_OMICRON": 2, + "PVP_OMICRON": 3, + "GUILD_RAID_OMICRON": 4, + "TERRITORY_STRIKE_OMICRON": 5, + "TERRITORY_COVERT_OMICRON": 6, + "TERRITORY_BATTLE_BOTH_OMICRON": 7, + "TERRITORY_WAR_OMICRON": 8, + "TERRITORY_TOURNAMENT_OMICRON": 9, + "WAR_OMICRON": 10, + "CONQUEST_OMICRON": 11, + "GALACTIC_CHALLENGE_OMICRON": 12, + "PVE_EVENT_OMICRON": 13, + "TERRITORY_TOURNAMENT_3_OMICRON": 14, + "TERRITORY_TOURNAMENT_5_OMICRON": 15, + "GALACTIC_CHALLENGE_3_OMICRON": 16, + "GALACTIC_CHALLENGE_5_OMICRON": 17, +} class Unit(NamedTuple): @@ -177,3 +206,266 @@ def skill_exists(value: Any, dict_list: list[dict[str, Any]] | None) -> bool: ), None, ) + + +# ── Guild omicron breakdown ───────────────────────────────────────────── + + +class OmicronMember(TypedDict): + """One player's standing on a single omicron, as listed in :class:`OmicronSkillStats`.""" + + player_id: str + player_name: str + tier: int | None + """The tier the player has taken the skill to, or ``None`` when they own the unit but the skill is + absent from their roster: a star-gated skill is left out until the unit reaches the rarity that + unlocks it.""" + + +class OmicronSkillStats(TypedDict): + """Adoption of one omicron skill, as listed in :attr:`OmicronModeBreakdown.skills`. + + ``len(applied) + len(owned_not_applied) + not_owned_count`` always equals + :attr:`OmicronBreakdown.total_members`. + """ + + skill_id: str + """The game data ``skill`` id carrying the omicron tier.""" + skill_name_key: str | None + """Localization key of the omicron's name, read from the ``ability`` the skill references. ``None`` + when no ``ability_list`` was given. The skill's own ``nameKey`` is a placeholder shared across + unrelated skills (``DEFENSE_UP_NAME_KEY``) and is not used.""" + skill_name: str | None + """Localized omicron name, when both ``ability_list`` and ``localization`` were given.""" + unit_base_id: str | None + """The unit the skill belongs to, or ``None`` when no unit in ``unit_list`` references it.""" + unit_name_key: str | None + unit_name: str | None + """Localized unit name, when ``localization`` was given and holds the key.""" + omicron_tier: int + """Index into the game data skill's ``tier`` list at which the omicron applies.""" + applied: list[OmicronMember] + """Players who own the unit and have taken the skill to the omicron tier.""" + owned_not_applied: list[OmicronMember] + """Players who own the unit but have not.""" + not_owned_count: int + """Players who do not own the unit.""" + + +class OmicronModeBreakdown(TypedDict): + """Every omicron of one game mode, as listed in :attr:`OmicronBreakdown.modes`.""" + + mode: int | str + """The skills' ``omicronMode`` as a number (see ``OMICRON_MODE``), whether the game data was fetched + with ``enums=True`` or not. A mode name the library does not know yet is kept as given.""" + mode_name: str + """Label from ``mode_names``, or ``"Mode "`` when it has none.""" + skills: list[OmicronSkillStats] + """Ordered by applied count, highest first, then by skill id.""" + + +class OmicronBreakdown(TypedDict): + """Omicron adoption across player profiles, as returned by :func:`get_omicron_breakdown`.""" + + total_members: int + """Number of player profiles the statistics cover.""" + modes: list[OmicronModeBreakdown] + """Numbered modes in ascending order, then any mode kept as a name.""" + + +def _omicron_mode(value: Any) -> int | str: + """A skill's ``omicronMode`` as its number; a name missing from ``_OMICRON_MODES`` is kept as given.""" + raw = as_scalar(value) + if raw is None: + return 0 # proto3 leaves out a zero enum, so a missing mode is OmicronMode_DEFAULT. + if isinstance(raw, int): + return raw + name = parse_enum(raw, _OMICRON_MODES, enum_name="OmicronMode") + return _OMICRON_MODES[name] if name is not None else raw + + +def _omicron_tier_index(skill: dict[str, Any]) -> int | None: + """The index of a game data skill's omicron tier, or ``None`` when it has none.""" + return next( + ( + index + for index, tier in enumerate(as_list(skill.get("tier"))) + if isinstance(tier, dict) and tier.get("isOmicronTier") is True + ), + None, + ) + + +def _owning_units(units: list[dict[str, Any]]) -> dict[str, tuple[str | None, str | None]]: + """Map each skill id to the ``(baseId, nameKey)`` of the unit a player must own to have it. + + A skill is commonly referenced by several base ids: the playable unit, a non-obtainable ``PVE_`` + mirror the AI uses, and sometimes a raid or event variant. Only the playable unit can be in a + roster, so resolving a skill to any other reports every player as not owning it. Playable units + (:func:`get_playable_units`) are therefore read first; the rest only name skills no playable unit + references. The first unit read wins, and the per-rarity rows of one unit agree. + """ + owners: dict[str, tuple[str | None, str | None]] = {} + for unit in (*get_playable_units(units), *units): + identity = (as_str(unit.get("baseId")) or None, as_str(unit.get("nameKey")) or None) + for reference in as_list(unit.get("skillReference")): + skill_id = reference.get("skillId") if isinstance(reference, dict) else None + if isinstance(skill_id, str): + owners.setdefault(skill_id, identity) + return owners + + +def _read_profile(profile: dict[str, Any]) -> tuple[set[str], dict[str, int]]: + """A player profile's owned base ids and the tier of each skill in its roster.""" + owned: set[str] = set() + tiers: dict[str, int] = {} + for unit in as_list(profile.get("rosterUnit")): + if not isinstance(unit, dict): + continue + if unit_id := base_id(unit.get("definitionId")): + owned.add(unit_id) + for skill in as_list(unit.get("skill")): + if isinstance(skill, dict) and isinstance(skill_id := skill.get("id"), str): + # A listed skill is unlocked; proto3 leaves out tier 0. + tiers[skill_id] = as_int(skill.get("tier")) + return owned, tiers + + +def get_omicron_breakdown( + player_profiles: list[dict[str, Any]], + skill_list: list[dict[str, Any]], + unit_list: list[dict[str, Any]], + *, + ability_list: list[dict[str, Any]] | None = None, + localization: dict[str, str] | None = None, + mode_names: Mapping[int, str] | None = None, +) -> OmicronBreakdown: + """Summarise omicron adoption across a set of player profiles, grouped by game mode. + + Every omicron skill in the game data becomes a row, whether or not anybody owns it, so the result + also answers "which omicrons exist, by mode". Each row splits the players into those who have + applied the omicron, those who own the unit but have not, and a count of those who do not own the + unit. + + A skill is an omicron when one of its tiers is flagged ``isOmicronTier``. Its ``omicronMode`` only + says where the omicron applies: skills without one carry mode 1 (``ALL_OMICRON``) by default. + + A player owns a unit when it is in their roster; whether the skill is listed there does not + decide it, because a star-gated skill is left out until unlocked. Only when no unit in + ``unit_list`` references a skill does a listed skill stand in for ownership. + + Args: + player_profiles: Full player profiles, as returned by ``get_player()``. Guild member entries do + not work: they carry no roster. + skill_list: The game data ``skill`` collection. + unit_list: The game data ``units`` collection, which names the unit owning each skill and so + decides ownership. ``include_pve_units=False`` is enough. + ability_list: Optional game data ``ability`` collection. It names each omicron, which matters + because a unit often has several omicrons in one mode (Doctor Aphra has three in 5v5 Grand + Arena) and the unit name alone does not tell them apart. + localization: Optional localization dictionary, e.g. from :func:`get_localization_dictionary`, + used for the unit and omicron names. + mode_names: Optional labels for the mode numbers. [Default: ``OMICRON_MODE``, which does not + name every mode; an unnamed mode is labelled ``"Mode "``] + + Returns: + An :class:`OmicronBreakdown`. Players within a row are ordered by name, then by player id. + + Raises: + SwgohComlinkValueError: If an argument has the wrong type, a profile has no ``playerId``, or two + profiles share one. + + Examples: + >>> game_data = comlink.get_game_data( + ... items=DataItems.SKILL | DataItems.UNITS | DataItems.ABILITY, include_pve_units=False + ... ) # doctest: +SKIP + >>> profiles = [comlink.get_player(player_id=m["playerId"]) for m in guild["member"]] # doctest: +SKIP + >>> breakdown = get_omicron_breakdown( + ... profiles, game_data["skill"], game_data["units"], ability_list=game_data["ability"] + ... ) # doctest: +SKIP + """ + for arg_name, arg in (("player_profiles", player_profiles), ("skill_list", skill_list), ("unit_list", unit_list)): + if not isinstance(arg, list): + raise SwgohComlinkValueError(f"{get_function_name()}: '{arg_name}' must be a list, not {type(arg)}") + if ability_list is not None and not isinstance(ability_list, list): + raise SwgohComlinkValueError(f"{get_function_name()}: 'ability_list' must be a list, not {type(ability_list)}") + if localization is not None and not isinstance(localization, dict): + raise SwgohComlinkValueError( + f"{get_function_name()}: 'localization' must be a dictionary, not {type(localization)}" + ) + if mode_names is not None and not isinstance(mode_names, Mapping): + raise SwgohComlinkValueError(f"{get_function_name()}: 'mode_names' must be a mapping, not {type(mode_names)}") + + members: list[tuple[str, str, set[str], dict[str, int]]] = [] + seen: set[str] = set() + for profile in player_profiles: + if not isinstance(profile, dict): + raise SwgohComlinkValueError( + f"{get_function_name()}: every player profile must be a dictionary, not {type(profile)}" + ) + player_id = as_str(profile.get("playerId")) + if not player_id: + raise SwgohComlinkValueError(f"{get_function_name()}: every player profile must carry a 'playerId'.") + if player_id in seen: + raise SwgohComlinkValueError( + f"{get_function_name()}: duplicate 'playerId' {player_id!r} in 'player_profiles'." + ) + seen.add(player_id) + members.append((player_id, as_str(profile.get("name")), *_read_profile(profile))) + members.sort(key=lambda member: (member[1], member[0])) + + labels = OMICRON_MODE if mode_names is None else mode_names + owners = _owning_units([unit for unit in unit_list if isinstance(unit, dict)]) + ability_names = { + ability["id"]: ability["nameKey"] + for ability in ability_list or [] + if isinstance(ability, dict) and isinstance(ability.get("id"), str) and isinstance(ability.get("nameKey"), str) + } + + by_mode: dict[int | str, list[OmicronSkillStats]] = {} + for skill in skill_list: + if not isinstance(skill, dict) or not isinstance(skill_id := skill.get("id"), str): + continue + if (omicron_tier := _omicron_tier_index(skill)) is None: + continue + unit_id, unit_name_key = owners.get(skill_id, (None, None)) + skill_name_key = ability_names.get(as_str(skill.get("abilityReference"))) + + applied: list[OmicronMember] = [] + owned_not_applied: list[OmicronMember] = [] + for player_id, player_name, owned, tiers in members: + if not (unit_id in owned if unit_id is not None else skill_id in tiers): + continue + tier = tiers.get(skill_id) + member: OmicronMember = {"player_id": player_id, "player_name": player_name, "tier": tier} + (applied if tier is not None and tier >= omicron_tier else owned_not_applied).append(member) + + by_mode.setdefault(_omicron_mode(skill.get("omicronMode")), []).append( + { + "skill_id": skill_id, + "skill_name_key": skill_name_key, + "skill_name": _localize(localization, skill_name_key, "") or None, + "unit_base_id": unit_id, + "unit_name_key": unit_name_key, + "unit_name": _localize(localization, unit_name_key, "") or None, + "omicron_tier": omicron_tier, + "applied": applied, + "owned_not_applied": owned_not_applied, + "not_owned_count": len(members) - len(applied) - len(owned_not_applied), + } + ) + + def mode_order(mode: int | str) -> tuple[bool, int, str]: + return (True, 0, mode) if isinstance(mode, str) else (False, mode, "") + + return { + "total_members": len(members), + "modes": [ + { + "mode": mode, + "mode_name": (labels.get(mode) if isinstance(mode, int) else None) or f"Mode {mode}", + "skills": sorted(stats, key=lambda s: (-len(s["applied"]), s["skill_id"])), + } + for mode, stats in sorted(by_mode.items(), key=lambda item: mode_order(item[0])) + ], + } diff --git a/tests/unit/test_helpers.py b/tests/unit/test_helpers.py index 53533fa..552e899 100644 --- a/tests/unit/test_helpers.py +++ b/tests/unit/test_helpers.py @@ -92,6 +92,7 @@ parse_swgoh_string, ) from swgoh_comlink.helpers._omicron import ( + get_omicron_breakdown, get_omicron_skill_tier, get_omicron_skills, get_tw_omicrons, @@ -398,6 +399,271 @@ def test_invalid_skill_type_raises(self): get_unit_from_skill([], cast(Any, 123)) +# ── _omicron.get_omicron_breakdown ───────────────────────────────────── + + +def _omi_skill(skill_id: str, mode: Any, *, omicron: int | None, tiers: int = 7, ability: str | None = None): + """A game data 'skill' with *tiers* upgrade tiers; *omicron* is the omicron's tier index.""" + skill: dict[str, Any] = { + "id": skill_id, + "omicronMode": mode, + "tier": [{"isZetaTier": False, "isOmicronTier": i == omicron} for i in range(tiers)], + } + if ability is not None: + skill["abilityReference"] = ability + return skill + + +# Modelled on live JEDIKNIGHTCAL game data. uniqueskill_JEDIKNIGHTCAL01 is a zeta that carries mode 1, the +# value every skill without an omicron has, so it is not an omicron. +_BREAKDOWN_SKILLS = [ + _omi_skill("specialskill_JEDIKNIGHTCAL03", 7, omicron=6, ability="specialability_jediknightcal03"), + _omi_skill("uniqueskill_JEDIKNIGHTCAL01", 1, omicron=None), + # Star-gated: missing from a roster until the unit reaches the rarity that unlocks it. + _omi_skill("uniqueskill_JEDIKNIGHTCAL02", 8, omicron=3, tiers=4), + # A mode OMICRON_MODE has no label for (13 is PVE_EVENT_OMICRON). + _omi_skill("specialskill_OTHERUNIT01", 13, omicron=1, tiers=2), +] +_JKCAL = {"baseId": "JEDIKNIGHTCAL", "nameKey": "UNIT_JEDIKNIGHTCAL_NAME", "obtainable": True, "obtainableTime": "0"} +_JKCAL_SKILLS = [{"skillId": s} for s in ("specialskill_JEDIKNIGHTCAL03", "uniqueskill_JEDIKNIGHTCAL01")] +# The 'units' collection has a row per unit per rarity, so a baseId recurs. +_BREAKDOWN_UNITS: list[dict[str, Any]] = [ + {**_JKCAL, "rarity": 7, "skillReference": [*_JKCAL_SKILLS, {"skillId": "uniqueskill_JEDIKNIGHTCAL02"}]}, + {**_JKCAL, "rarity": 1, "skillReference": _JKCAL_SKILLS}, + { + "baseId": "OTHERUNIT", + "nameKey": "UNIT_OTHERUNIT_NAME", + "skillReference": [{"skillId": "specialskill_OTHERUNIT01"}], + }, +] +_BREAKDOWN_ABILITIES = [ + {"id": "specialability_jediknightcal03", "nameKey": "SPECIALABILITY_JEDIKNIGHTCAL03_NAME"}, + {"id": "unrelated_ability", "nameKey": "UNRELATED_NAME"}, +] + + +def _cal_owner(player_id: str, name: str, *skills: dict[str, Any]) -> dict[str, Any]: + """A player profile owning JEDIKNIGHTCAL with the given roster skills.""" + return { + "playerId": player_id, + "name": name, + "rosterUnit": [{"definitionId": "JEDIKNIGHTCAL:SEVEN_STAR", "skill": list(skills)}], + } + + +_APPLIED = _cal_owner("p1", "Applied", {"id": "specialskill_JEDIKNIGHTCAL03", "tier": 6}) +_ONE_SHORT = _cal_owner("p2", "OneShort", {"id": "specialskill_JEDIKNIGHTCAL03", "tier": 5}) +# Owns JEDIKNIGHTCAL, but uniqueskill_JEDIKNIGHTCAL02 is not in the roster at all. +_GATED = _cal_owner("p3", "Gated", {"id": "specialskill_JEDIKNIGHTCAL03", "tier": 6}) +_NO_UNIT = {"playerId": "p4", "name": "NoUnit", "rosterUnit": []} + + +def _omi_row(breakdown: Any, skill_id: str) -> Any: + return next(row for mode in breakdown["modes"] for row in mode["skills"] if row["skill_id"] == skill_id) + + +def _with_modes(**modes: Any) -> list[dict[str, Any]]: + """_BREAKDOWN_SKILLS with the omicronMode of the named skills replaced; None removes the field.""" + skills = [dict(skill) for skill in _BREAKDOWN_SKILLS] + for skill in skills: + if skill["id"] in modes: + if (mode := modes[skill["id"]]) is None: + del skill["omicronMode"] + else: + skill["omicronMode"] = mode + return skills + + +def test_omicron_breakdown_lists_every_omicron_and_only_omicrons(): + breakdown = get_omicron_breakdown([], _BREAKDOWN_SKILLS, _BREAKDOWN_UNITS) + assert breakdown["total_members"] == 0 + assert {row["skill_id"] for mode in breakdown["modes"] for row in mode["skills"]} == { + "specialskill_JEDIKNIGHTCAL03", + "uniqueskill_JEDIKNIGHTCAL02", + "specialskill_OTHERUNIT01", + } + + +@pytest.mark.parametrize( + ("profiles", "units", "skill_id", "applied", "owned_not_applied", "not_owned"), + [ + pytest.param([_APPLIED], _BREAKDOWN_UNITS, "specialskill_JEDIKNIGHTCAL03", ["p1"], [], 0, id="at-omicron-tier"), + pytest.param( + [_ONE_SHORT], _BREAKDOWN_UNITS, "specialskill_JEDIKNIGHTCAL03", [], [("p2", 5)], 0, id="one-tier-short" + ), + # Owning the unit decides ownership, not whether the skill is listed. + pytest.param([_GATED], _BREAKDOWN_UNITS, "uniqueskill_JEDIKNIGHTCAL02", [], [("p3", None)], 0, id="star-gated"), + pytest.param([_NO_UNIT], _BREAKDOWN_UNITS, "specialskill_JEDIKNIGHTCAL03", [], [], 1, id="unit-not-owned"), + pytest.param( + [{"playerId": "p9", "name": "Fresh"}], _BREAKDOWN_UNITS, "specialskill_JEDIKNIGHTCAL03", [], [], 1, + id="no-roster", + ), + # A listed skill is unlocked, and proto3 leaves out a tier of 0. + pytest.param( + [_cal_owner("p5", "Fresh", {"id": "specialskill_JEDIKNIGHTCAL03"})], _BREAKDOWN_UNITS, + "specialskill_JEDIKNIGHTCAL03", [], [("p5", 0)], 0, id="tier-left-out", + ), + # No unit references the skill, so a listed skill stands in for owning the unit. + pytest.param([_APPLIED, _NO_UNIT], [], "specialskill_JEDIKNIGHTCAL03", ["p1"], [], 1, id="unknown-unit"), + ], +) # fmt: skip +def test_omicron_breakdown_cohorts(profiles, units, skill_id, applied, owned_not_applied, not_owned): + row = _omi_row(get_omicron_breakdown(profiles, _BREAKDOWN_SKILLS, units), skill_id) + assert [m["player_id"] for m in row["applied"]] == applied + assert [(m["player_id"], m["tier"]) for m in row["owned_not_applied"]] == owned_not_applied + assert row["not_owned_count"] == not_owned + + +def test_omicron_breakdown_cohorts_sum_to_total_members(): + breakdown = get_omicron_breakdown([_APPLIED, _ONE_SHORT, _GATED, _NO_UNIT], _BREAKDOWN_SKILLS, _BREAKDOWN_UNITS) + assert breakdown["total_members"] == 4 + for mode in breakdown["modes"]: + for row in mode["skills"]: + assert len(row["applied"]) + len(row["owned_not_applied"]) + row["not_owned_count"] == 4, row["skill_id"] + + +_JKCAL03, _JKCAL02, _OTHER01 = "specialskill_JEDIKNIGHTCAL03", "uniqueskill_JEDIKNIGHTCAL02", "specialskill_OTHERUNIT01" + + +@pytest.mark.parametrize( + ("skills", "kwargs", "expected"), + [ + pytest.param(_BREAKDOWN_SKILLS, {}, [(7, "TB"), (8, "TW"), (13, "Mode 13")], id="numbers"), + # enums=True sends the member name. + pytest.param( + _with_modes( + **{ + _JKCAL03: "TERRITORY_BATTLE_BOTH_OMICRON", + _JKCAL02: "TERRITORY_WAR_OMICRON", + _OTHER01: "PVE_EVENT_OMICRON", + } + ), + {}, + [(7, "TB"), (8, "TW"), (13, "Mode 13")], + id="enum-names", + ), + pytest.param( + _with_modes(**{_JKCAL02: "OMICRONMODE_TERRITORYWAROMICRON", _OTHER01: "13"}), + {}, + [(7, "TB"), (8, "TW"), (13, "Mode 13")], + id="type-prefixed-and-numeric-string", + ), + # A mode added by a newer game version keeps its name and sorts after the numbered modes. + pytest.param( + _with_modes(**{_JKCAL03: "NEW_EVENT_OMICRON"}), + {}, + [(8, "TW"), (13, "Mode 13"), ("NEW_EVENT_OMICRON", "Mode NEW_EVENT_OMICRON")], + id="unknown-name", + ), + # proto3 leaves out the zero enum value. + pytest.param(_with_modes(**{_OTHER01: None}), {}, [(0, "Default"), (7, "TB"), (8, "TW")], id="mode-left-out"), + pytest.param( + _BREAKDOWN_SKILLS, + {"mode_names": {13: "PVE Event"}}, + [(7, "Mode 7"), (8, "Mode 8"), (13, "PVE Event")], + id="custom-labels", + ), + ], +) +def test_omicron_breakdown_modes(skills, kwargs, expected): + breakdown = get_omicron_breakdown([_APPLIED], skills, _BREAKDOWN_UNITS, **kwargs) + assert [(mode["mode"], mode["mode_name"]) for mode in breakdown["modes"]] == expected + + +def test_omicron_breakdown_orders_skills_by_applied_count_then_members_by_name(): + # Both omicrons in one mode: the one more players applied comes first, ahead of skill id order. + skills = _with_modes(**{_JKCAL03: 8}) + alice = _cal_owner("pz", "Alice", {"id": _JKCAL02, "tier": 3}) + bob = _cal_owner("pa", "Bob", {"id": _JKCAL02, "tier": 3}) + breakdown = get_omicron_breakdown([bob, _APPLIED, alice], skills, _BREAKDOWN_UNITS) + rows = next(mode for mode in breakdown["modes"] if mode["mode"] == 8)["skills"] + assert [row["skill_id"] for row in rows] == [_JKCAL02, _JKCAL03] + assert [m["player_name"] for m in rows[0]["applied"]] == ["Alice", "Bob"] + + +# A skill referenced by several base ids, as in live game data: a non-obtainable PVE_ mirror listed first, an +# event variant whose obtainableTime is in the future, and the playable unit. +_PVE_MIRROR = {"baseId": "PVE_JEDIKNIGHTCAL", "nameKey": "PVE_NAME", "rarity": 8, "obtainable": False} +_EVENT_VARIANT = {"baseId": "JEDIKNIGHTCAL_EVENT", "rarity": 7, "obtainable": True, "obtainableTime": "2396822400000"} + + +@pytest.mark.parametrize( + ("units", "base_id", "not_owned"), + [ + pytest.param([_PVE_MIRROR, _EVENT_VARIANT, {**_JKCAL, "rarity": 7}], "JEDIKNIGHTCAL", 0, id="playable-wins"), + pytest.param( + [_PVE_MIRROR, {**_JKCAL, "rarity": "SEVEN_STAR"}], "JEDIKNIGHTCAL", 0, id="playable-wins-enum-rarity" + ), + # With no playable unit, the first unit read wins and the owner of JEDIKNIGHTCAL is not counted. + pytest.param([_PVE_MIRROR, _EVENT_VARIANT], "PVE_JEDIKNIGHTCAL", 1, id="none-playable"), + ], +) +def test_omicron_breakdown_resolves_the_playable_unit(units, base_id, not_owned): + units = [{**unit, "skillReference": [{"skillId": _JKCAL03}]} for unit in units] + row = _omi_row(get_omicron_breakdown([_APPLIED], _BREAKDOWN_SKILLS, units), _JKCAL03) + assert row["unit_base_id"] == base_id + assert row["not_owned_count"] == not_owned + + +_CAL_NAMES = { + "UNIT_JEDIKNIGHTCAL_NAME": "[c][ffff33]Cal Kestis[-][/c]", + "SPECIALABILITY_JEDIKNIGHTCAL03_NAME": "Impetuous Assault", +} + + +@pytest.mark.parametrize( + ("skill_id", "kwargs", "expected"), + [ + pytest.param(_JKCAL03, {}, (None, None, "UNIT_JEDIKNIGHTCAL_NAME", None), id="keys-only"), + # The omicron's name comes from the ability, never from the skill's placeholder nameKey. + pytest.param( + _JKCAL03, + {"ability_list": _BREAKDOWN_ABILITIES}, + ("SPECIALABILITY_JEDIKNIGHTCAL03_NAME", None, "UNIT_JEDIKNIGHTCAL_NAME", None), + id="ability-key", + ), + pytest.param( + _JKCAL03, + {"ability_list": _BREAKDOWN_ABILITIES, "localization": _CAL_NAMES}, + ("SPECIALABILITY_JEDIKNIGHTCAL03_NAME", "Impetuous Assault", "UNIT_JEDIKNIGHTCAL_NAME", "Cal Kestis"), + id="localized", + ), + pytest.param( + _JKCAL02, + {"ability_list": _BREAKDOWN_ABILITIES, "localization": _CAL_NAMES}, + (None, None, "UNIT_JEDIKNIGHTCAL_NAME", "Cal Kestis"), + id="no-ability-reference", + ), + ], +) +def test_omicron_breakdown_names(skill_id, kwargs, expected): + row = _omi_row(get_omicron_breakdown([_APPLIED], _BREAKDOWN_SKILLS, _BREAKDOWN_UNITS, **kwargs), skill_id) + assert (row["skill_name_key"], row["skill_name"], row["unit_name_key"], row["unit_name"]) == expected + + +@pytest.mark.parametrize( + ("call", "match"), + [ + pytest.param(lambda: get_omicron_breakdown(cast(Any, "bad"), [], []), "player_profiles", id="profiles"), + pytest.param(lambda: get_omicron_breakdown([], cast(Any, "bad"), []), "skill_list", id="skills"), + pytest.param(lambda: get_omicron_breakdown([], [], cast(Any, "bad")), "unit_list", id="units"), + pytest.param( + lambda: get_omicron_breakdown([], [], [], ability_list=cast(Any, "bad")), "ability_list", id="abilities" + ), + pytest.param( + lambda: get_omicron_breakdown([], [], [], localization=cast(Any, "bad")), "localization", id="localization" + ), + pytest.param(lambda: get_omicron_breakdown([], [], [], mode_names=cast(Any, 8)), "mode_names", id="mode-names"), + pytest.param(lambda: get_omicron_breakdown(cast(Any, ["nope"]), [], []), "dictionary", id="profile-not-dict"), + pytest.param(lambda: get_omicron_breakdown([{"name": "Anon"}], [], []), "playerId", id="no-player-id"), + pytest.param(lambda: get_omicron_breakdown([_APPLIED, _APPLIED], [], []), "duplicate", id="duplicate-player"), + ], +) +def test_omicron_breakdown_rejects_invalid_input(call, match): + with pytest.raises(SwgohComlinkValueError, match=match): + call() + + # ── _game_data ────────────────────────────────────────────────────────── From 0c3bf6ad5dae0b1f58914d136fade3f74627b966 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 14:03:14 -0500 Subject: [PATCH 38/47] docs(examples): add guild omicron breakdown examples Add a Sync and an Async guild_omicron_breakdown.py that report omicron adoption across a guild by game mode. Both list the members with get_guild_members(), fetch every member's profile (concurrently with asyncio.TaskGroup in the Async one), request only the skill, units and ability collections by combining DataItems bits with |, and print the top omicrons per mode followed by the members who own the unit behind the biggest unapplied omicron. List both in the examples READMEs, docs/examples.md and the README. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + docs/examples.md | 2 + examples/Async/README.md | 1 + examples/Async/guild_omicron_breakdown.py | 110 ++++++++++++++++++++++ examples/Sync/README.md | 1 + examples/Sync/guild_omicron_breakdown.py | 100 ++++++++++++++++++++ 6 files changed, 216 insertions(+) create mode 100644 examples/Async/guild_omicron_breakdown.py create mode 100644 examples/Sync/guild_omicron_breakdown.py diff --git a/README.md b/README.md index 651164e..d782d9b 100644 --- a/README.md +++ b/README.md @@ -292,6 +292,7 @@ The [`examples/`](https://github.com/swgoh-utils/comlink-python/tree/main/exampl | [`get_gac_brackets.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_gac_brackets.py) | Scan GAC brackets and search for a player | | [`calc_stats_local.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/calc_stats_local.py) | Calculate character stats locally with `StatCalc` | | [`search_for_guilds.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/search_for_guilds.py) | Search for guilds by name or criteria | +| [`guild_omicron_breakdown.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/guild_omicron_breakdown.py) | Report omicron adoption across a guild by game mode | ### Asynchronous ([`examples/Async/`](https://github.com/swgoh-utils/comlink-python/tree/main/examples/Async)) @@ -301,6 +302,7 @@ The [`examples/`](https://github.com/swgoh-utils/comlink-python/tree/main/exampl | [`concurrent_requests.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/concurrent_requests.py) | Fetch multiple players in parallel with `asyncio.gather()` | | [`streaming_guild_roster.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/streaming_guild_roster.py) | Fetch all guild members concurrently with `asyncio.TaskGroup` | | [`streaming_guild_roster_advanced.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/streaming_guild_roster_advanced.py) | Production-quality guild roster fetch with CLI args and retry logic | +| [`guild_omicron_breakdown.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/guild_omicron_breakdown.py) | Report omicron adoption across a guild, fetching member profiles concurrently | | [`calc_stats_local.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/calc_stats_local.py) | Calculate character stats locally with `StatCalcAsync` | See the [full examples listing](https://github.com/swgoh-utils/comlink-python/blob/main/examples/README.md) for all available scripts and usage details. diff --git a/docs/examples.md b/docs/examples.md index 3f0c06e..54222b2 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -16,6 +16,7 @@ These examples use `SwgohComlink` — the synchronous client. Simple blocking ca | [`get_gac_leaderboard.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_gac_leaderboard.py) | Get GAC bracket or league/division leaderboards | | [`get_gac_brackets.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_gac_brackets.py) | Scan GAC brackets for a league and search for a player | | [`get_guild_leaderboard.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_guild_leaderboard.py) | Get guild-level leaderboards (TW, raids, GP, TB) | +| [`guild_omicron_breakdown.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/guild_omicron_breakdown.py) | Report omicron adoption across a guild by game mode | | [`get_language_bundle.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_language_bundle.py) | Retrieve and parse a specific language bundle | | [`get_location_bundle.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_location_bundle.py) | Retrieve the full localization bundle (zipped or unzipped) | | [`get_location_bundle_adv.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_location_bundle_adv.py) | Advanced localization bundle retrieval | @@ -46,6 +47,7 @@ These examples use `SwgohComlinkAsync` — the asynchronous client. Supports con | [`get_gac_leaderboard.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_gac_leaderboard.py) | Get GAC bracket or league/division leaderboards | | [`get_gac_brackets.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_gac_brackets.py) | Scan GAC brackets for a league and search for a player (parallel batches) | | [`get_guild_leaderboard.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_guild_leaderboard.py) | Get guild-level leaderboards (TW, raids, GP, TB) | +| [`guild_omicron_breakdown.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/guild_omicron_breakdown.py) | Report omicron adoption across a guild by game mode, fetching member profiles concurrently | | [`get_language_bundle.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_language_bundle.py) | Retrieve and parse a specific language bundle | | [`get_location_bundle.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_location_bundle.py) | Retrieve the full localization bundle (zipped or unzipped) | | [`get_latest_game_data_version.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_latest_game_data_version.py) | Get current game data and language version strings | diff --git a/examples/Async/README.md b/examples/Async/README.md index 7a07a92..3cbcd23 100644 --- a/examples/Async/README.md +++ b/examples/Async/README.md @@ -13,6 +13,7 @@ These examples use the `SwgohComlinkAsync` async client. All methods must be `aw | `get_game_data.py` | Retrieve game data collections (all, by segment, or by name) | | `get_guild.py` | Look up guild info from a player's ally code | | `get_guild_leaderboard.py` | Get guild-level leaderboards (TW, raids, GP, TB) | +| `guild_omicron_breakdown.py` | Report omicron adoption across a guild by game mode, fetching member profiles concurrently | | `get_language_bundle.py` | Retrieve and parse a specific language bundle | | `get_latest_game_data_version.py` | Get current game data and language version strings | | `get_location_bundle.py` | Retrieve the full localization bundle (zipped or unzipped) | diff --git a/examples/Async/guild_omicron_breakdown.py b/examples/Async/guild_omicron_breakdown.py new file mode 100644 index 0000000..3806024 --- /dev/null +++ b/examples/Async/guild_omicron_breakdown.py @@ -0,0 +1,110 @@ +""" +guild_omicron_breakdown.py +Report omicron adoption across an entire guild, separated by game mode. + +This example demonstrates how to: + 1. List a guild's members from one player's ally code with async_get_guild_members() + 2. Fetch every member's full profile concurrently using asyncio.TaskGroup + 3. Pull only the 'skill', 'units' and 'ability' game data collections, by combining + individual DataItems bits with | rather than requesting whole segments + 4. Resolve unit and omicron names through a localization dictionary + 5. Summarise adoption with helpers.get_omicron_breakdown() + +Why the profiles have to be fetched: a guild's 'member' list holds identity stubs (player ID, +name, galactic power) and carries no roster. Whether a member has an omicron applied lives in +player['rosterUnit'][n]['skill'], so every member needs a full get_player() call. That fan-out +is the bulk of this program; the breakdown itself is one call. +""" + +import asyncio +import time + +from swgoh_comlink import SwgohComlinkAsync +from swgoh_comlink.helpers import ( + DataItems, + async_get_guild_members, + async_get_localization_dictionary, + get_omicron_breakdown, +) + +# CONFIGURATION +# Change these to any valid values to look up that player's guild +ALLY_CODE = 314927874 +COMLINK_HOST = "localhost" +COMLINK_PORT = 3000 +LANGUAGE = "eng_us" + +# How many omicrons to list per game mode +TOP_N = 5 + + +async def main(): + async with SwgohComlinkAsync(host=COMLINK_HOST, port=COMLINK_PORT) as comlink: + # Step 1: The guild's member list, from any one member's ally code. + members = await async_get_guild_members(comlink, allycode=ALLY_CODE) + print(f"Members: {len(members)}") + + # Step 2: Every member profile, concurrently. + start = time.perf_counter() + async with asyncio.TaskGroup() as tg: + tasks = [tg.create_task(comlink.get_player(player_id=member["playerId"])) for member in members] + profiles = [task.result() for task in tasks] + print(f"Fetched {len(profiles)} profiles in {time.perf_counter() - start:.2f}s") + + # Step 3: Game data. Request exactly the three collections needed by combining the + # individual DataItems bits; whole segments pull far more than this needs. 'ability' + # supplies the omicron names: a unit often has several omicrons in one game mode, so + # the unit name alone does not identify them. PvE units are left out, since only + # playable units can be in a roster. + game_data = await comlink.get_game_data( + items=DataItems.SKILL | DataItems.UNITS | DataItems.ABILITY, + include_pve_units=False, + ) + print( + f"Game data: {len(game_data['skill'])} skills, {len(game_data['units'])} unit rows, " + f"{len(game_data['ability'])} abilities" + ) + + # Step 4: Localization, so units and omicrons read as names rather than IDs. + localization = await async_get_localization_dictionary(comlink, language=LANGUAGE) + + # Step 5: The breakdown itself. It needs no client, so it runs after the session closes. + breakdown = get_omicron_breakdown( + profiles, + game_data["skill"], + game_data["units"], + ability_list=game_data["ability"], + localization=localization, + ) + + # Step 6: Report. Counts first, then the detail behind one of them. + total = breakdown["total_members"] + for mode in breakdown["modes"]: + print(f"\n=== {mode['mode_name']} (mode {mode['mode']}): {len(mode['skills'])} omicrons ===") + for row in mode["skills"][:TOP_N]: + applied = len(row["applied"]) + owners = applied + len(row["owned_not_applied"]) + label = f"{row['unit_name'] or row['unit_base_id'] or '?'}: {row['skill_name'] or row['skill_id']}" + print(f" {label:<60} {applied:>3}/{total} guild | {applied:>3}/{owners} owners") + + # The member lists are the point of the helper, so show one in full: the omicron with the + # most owners who have not applied it, the guild's largest single opportunity. + rows = [(mode["mode_name"], row) for mode in breakdown["modes"] for row in mode["skills"]] + if not rows: + return + mode_name, target = max(rows, key=lambda pair: len(pair[1]["owned_not_applied"])) + if not target["owned_not_applied"]: + return + + unit = target["unit_name"] or target["unit_base_id"] or "?" + print(f"\n=== Biggest opportunity: {unit}: {target['skill_name'] or target['skill_id']} ({mode_name}) ===") + print(f" applied by {len(target['applied'])}, missing on {len(target['owned_not_applied'])} rosters") + print(f" {target['not_owned_count']} members do not own the unit\n") + for member in target["owned_not_applied"]: + # tier is None when the skill is not in the roster at all: star-gated and not yet + # unlocked, rather than merely not upgraded. + position = "not unlocked" if member["tier"] is None else f"tier {member['tier']}/{target['omicron_tier']}" + print(f" {member['player_name']:<24} {position}") + + +asyncio.run(main()) diff --git a/examples/Sync/README.md b/examples/Sync/README.md index a5060ed..81abf1a 100644 --- a/examples/Sync/README.md +++ b/examples/Sync/README.md @@ -13,6 +13,7 @@ These examples use the `SwgohComlink` synchronous client. They run in a standard | `get_game_data.py` | Retrieve game data collections (all, by segment, or by name) | | `get_guild.py` | Look up guild info from a player's ally code | | `get_guild_leaderboard.py` | Get guild-level leaderboards (TW, raids, GP, TB) | +| `guild_omicron_breakdown.py` | Report omicron adoption across a guild by game mode | | `get_language_bundle.py` | Retrieve and parse a specific language bundle | | `get_latest_game_data_version.py` | Get current game data and language version strings | | `get_location_bundle.py` | Retrieve the full localization bundle (zipped or unzipped) | diff --git a/examples/Sync/guild_omicron_breakdown.py b/examples/Sync/guild_omicron_breakdown.py new file mode 100644 index 0000000..d033c1a --- /dev/null +++ b/examples/Sync/guild_omicron_breakdown.py @@ -0,0 +1,100 @@ +""" +guild_omicron_breakdown.py +Report omicron adoption across an entire guild, separated by game mode. + +This example demonstrates how to: + 1. List a guild's members from one player's ally code with get_guild_members() + 2. Fetch every member's full profile + 3. Pull only the 'skill', 'units' and 'ability' game data collections, by combining + individual DataItems bits with | rather than requesting whole segments + 4. Resolve unit and omicron names through a localization dictionary + 5. Summarise adoption with helpers.get_omicron_breakdown() + +Why the profiles have to be fetched: a guild's 'member' list holds identity stubs (player ID, +name, galactic power) and carries no roster. Whether a member has an omicron applied lives in +player['rosterUnit'][n]['skill'], so every member needs a full get_player() call. Here they are +fetched one after another; see examples/Async/guild_omicron_breakdown.py to fetch them +concurrently. +""" + +import time + +from swgoh_comlink import SwgohComlink +from swgoh_comlink.helpers import ( + DataItems, + get_guild_members, + get_localization_dictionary, + get_omicron_breakdown, +) + +# CONFIGURATION +# Change these to any valid values to look up that player's guild +ALLY_CODE = 314927874 +COMLINK_HOST = "localhost" +COMLINK_PORT = 3000 +LANGUAGE = "eng_us" + +# How many omicrons to list per game mode +TOP_N = 5 + +comlink = SwgohComlink(host=COMLINK_HOST, port=COMLINK_PORT) + +# Step 1: The guild's member list, from any one member's ally code. +members = get_guild_members(comlink, allycode=ALLY_CODE) +print(f"Members: {len(members)}") + +# Step 2: Every member profile. +start = time.perf_counter() +profiles = [comlink.get_player(player_id=member["playerId"]) for member in members] +print(f"Fetched {len(profiles)} profiles in {time.perf_counter() - start:.2f}s") + +# Step 3: Game data. Request exactly the three collections needed by combining the individual +# DataItems bits; whole segments pull far more than this needs. 'ability' supplies the omicron +# names: a unit often has several omicrons in one game mode, so the unit name alone does not +# identify them. PvE units are left out, since only playable units can be in a roster. +game_data = comlink.get_game_data( + items=DataItems.SKILL | DataItems.UNITS | DataItems.ABILITY, + include_pve_units=False, +) +print( + f"Game data: {len(game_data['skill'])} skills, {len(game_data['units'])} unit rows, " + f"{len(game_data['ability'])} abilities" +) + +# Step 4: Localization, so units and omicrons read as names rather than IDs. +localization = get_localization_dictionary(comlink, language=LANGUAGE) + +# Step 5: The breakdown itself. +breakdown = get_omicron_breakdown( + profiles, + game_data["skill"], + game_data["units"], + ability_list=game_data["ability"], + localization=localization, +) + +# Step 6: Report. Counts first, then the detail behind one of them. +total = breakdown["total_members"] +for mode in breakdown["modes"]: + print(f"\n=== {mode['mode_name']} (mode {mode['mode']}): {len(mode['skills'])} omicrons ===") + for row in mode["skills"][:TOP_N]: + applied = len(row["applied"]) + owners = applied + len(row["owned_not_applied"]) + label = f"{row['unit_name'] or row['unit_base_id'] or '?'}: {row['skill_name'] or row['skill_id']}" + print(f" {label:<60} {applied:>3}/{total} guild | {applied:>3}/{owners} owners") + +# The member lists are the point of the helper, so show one in full: the omicron with the most +# owners who have not applied it, the guild's largest single opportunity. +rows = [(mode["mode_name"], row) for mode in breakdown["modes"] for row in mode["skills"]] +if rows: + mode_name, target = max(rows, key=lambda pair: len(pair[1]["owned_not_applied"])) + if target["owned_not_applied"]: + unit = target["unit_name"] or target["unit_base_id"] or "?" + print(f"\n=== Biggest opportunity: {unit}: {target['skill_name'] or target['skill_id']} ({mode_name}) ===") + print(f" applied by {len(target['applied'])}, missing on {len(target['owned_not_applied'])} rosters") + print(f" {target['not_owned_count']} members do not own the unit\n") + for member in target["owned_not_applied"]: + # tier is None when the skill is not in the roster at all: star-gated and not yet + # unlocked, rather than merely not upgraded. + position = "not unlocked" if member["tier"] is None else f"tier {member['tier']}/{target['omicron_tier']}" + print(f" {member['player_name']:<24} {position}") From 3b63a7a73aed527f052c59e1e9f2bd7f14785c58 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 19:29:51 -0500 Subject: [PATCH 39/47] feat(client): add strip_empty option to get_game_data /data returns every collection key, populating only the requested ones: unrequested list collections come back as [] and unrequested single-object collections as null. The new keyword-only strip_empty flag drops those keys so the response holds only the collections that came back with data. Falsy scalars such as 0, False and "" are kept. Defaults to False, so existing callers get the full response unchanged. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- examples/Async/get_game_data.py | 4 +++ examples/Sync/get_game_data.py | 4 +++ src/swgoh_comlink/_base.py | 14 +++++++++ src/swgoh_comlink/swgoh_comlink.py | 7 ++++- src/swgoh_comlink/swgoh_comlink_async.py | 7 ++++- tests/unit/test_client_requests.py | 38 ++++++++++++++++++++++++ 7 files changed, 73 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d782d9b..a399142 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ Methods available on both `SwgohComlink` and `SwgohComlinkAsync` (async methods | `get_guild(guild_id, include_recent_guild_activity_info, enums)` | Get guild data by guild ID | | `get_guilds_by_name(name, start_index, count, enums)` | Search guilds by name | | `get_guilds_by_criteria(search_criteria, start_index, count, enums)` | Search guilds by criteria | -| `get_game_data(version, include_pve_units, request_segment, enums, items, device_platform)` | Get game data collections (select them with `items=DataItems...`) | +| `get_game_data(version, include_pve_units, request_segment, enums, items, device_platform, *, strip_empty)` | Get game data collections (select them with `items=DataItems...`; `strip_empty=True` drops the empty ones) | | `get_game_metadata(client_specs, enums)` | Get current game and localization versions | | `get_localization(localization_id, locale, unzip, enums)` | Get localization bundles | | `get_enums(refresh)` | Get game data enums (cached per game data version) | diff --git a/examples/Async/get_game_data.py b/examples/Async/get_game_data.py index dd87137..c59cb61 100644 --- a/examples/Async/get_game_data.py +++ b/examples/Async/get_game_data.py @@ -23,6 +23,10 @@ async def main(): # The same call without the PVE units units_no_pve = await cl.get_game_data(items=DataItems.UNITS, include_pve_units=False) + # The response always holds every collection key, empty or null when not requested. + # strip_empty=True drops those, leaving only the collections that came back with data. + units_only = await cl.get_game_data(items=DataItems.UNITS, strip_empty=True) + # Combine collections with `|` (not `+`, which breaks for aliased members) skill_equipment = await cl.get_game_data(items=DataItems.SKILL | DataItems.EQUIPMENT) diff --git a/examples/Sync/get_game_data.py b/examples/Sync/get_game_data.py index ced8f14..2dfc1ac 100644 --- a/examples/Sync/get_game_data.py +++ b/examples/Sync/get_game_data.py @@ -20,6 +20,10 @@ # The same call without the PVE units units_no_pve = cl.get_game_data(items=DataItems.UNITS, include_pve_units=False) +# The response always holds every collection key, empty or null when not requested. +# strip_empty=True drops those, leaving only the collections that came back with data. +units_only = cl.get_game_data(items=DataItems.UNITS, strip_empty=True) + # Combine collections with `|` (not `+`, which breaks for aliased members) skill_equipment = cl.get_game_data(items=DataItems.SKILL | DataItems.EQUIPMENT) diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 5c85045..4828cd1 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -649,6 +649,20 @@ def _build_game_data_payload( inner_payload["requestSegment"] = request_segment return payload + @staticmethod + def _strip_empty_collections(game_data: dict[str, Any]) -> dict[str, Any]: + """Return ``game_data`` without the keys whose value is ``None`` or an empty list or dict. + + ``/data`` returns every collection key, populating only the requested ones: unrequested list + collections come back as ``[]`` and unrequested single-object collections as ``None``. Falsy + scalars (``0``, ``False``, ``""``) are kept. + """ + return { + key: value + for key, value in game_data.items() + if value is not None and (value or not isinstance(value, (list, dict))) + } + @staticmethod def _build_unit_stats_endpoint(flags: list[str] | None = None, language: str | None = None) -> str: """Build the stats endpoint string with query parameters. diff --git a/src/swgoh_comlink/swgoh_comlink.py b/src/swgoh_comlink/swgoh_comlink.py index 33bf4e7..2838404 100644 --- a/src/swgoh_comlink/swgoh_comlink.py +++ b/src/swgoh_comlink/swgoh_comlink.py @@ -322,6 +322,8 @@ def get_game_data( enums: bool = False, items: str | DataItems | int | None = None, device_platform: str = "Android", + *, + strip_empty: bool = False, ) -> dict[str, Any]: """ Get game data. @@ -334,6 +336,8 @@ def get_game_data( items: string [Defaults to None] bitwise value indicating the collections to retrieve from game. NOTE: this parameter is mutually exclusive with request_segment. device_platform: string [Defaults to "Android"] + strip_empty: Keyword-only. Drop collections that came back empty (``[]``) or null, e.g. the ones + not selected by ``items``. [Defaults to False, which returns every collection key] Returns: A dictionary containing the game data. @@ -351,7 +355,8 @@ def get_game_data( items=items, device_platform=device_platform, ) - return cast(dict[str, Any], self._post(endpoint="data", payload=payload, timeout=GAME_DATA_TIMEOUT)) + game_data = cast(dict[str, Any], self._post(endpoint="data", payload=payload, timeout=GAME_DATA_TIMEOUT)) + return self._strip_empty_collections(game_data) if strip_empty else game_data # alias for non PEP usage of direct endpoint calls getGameData = get_game_data diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index c2c260d..8f7677e 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -321,6 +321,8 @@ async def get_game_data( enums: bool = False, items: str | DataItems | int | None = None, device_platform: str = "Android", + *, + strip_empty: bool = False, ) -> dict[str, Any]: """ Get game data. @@ -333,6 +335,8 @@ async def get_game_data( items: string [Defaults to None] bitwise value indicating the collections to retrieve from game. NOTE: this parameter is mutually exclusive with request_segment. device_platform: string [Defaults to "Android"] + strip_empty: Keyword-only. Drop collections that came back empty (``[]``) or null, e.g. the ones + not selected by ``items``. [Defaults to False, which returns every collection key] Returns: A dictionary containing the game data. @@ -350,7 +354,8 @@ async def get_game_data( items=items, device_platform=device_platform, ) - return cast(dict[str, Any], await self._post(endpoint="data", payload=payload, timeout=GAME_DATA_TIMEOUT)) + game_data = cast(dict[str, Any], await self._post(endpoint="data", payload=payload, timeout=GAME_DATA_TIMEOUT)) + return self._strip_empty_collections(game_data) if strip_empty else game_data # alias for non PEP usage of direct endpoint calls getGameData = get_game_data diff --git a/tests/unit/test_client_requests.py b/tests/unit/test_client_requests.py index 87925c7..a2308e2 100644 --- a/tests/unit/test_client_requests.py +++ b/tests/unit/test_client_requests.py @@ -9,6 +9,7 @@ import hashlib import hmac +import inspect import json from collections.abc import Awaitable, Callable from typing import Any @@ -259,6 +260,43 @@ async def test_get_guild_unwraps_guild_key( assert await call(comlink, "get_guild", guild_id="guild-1") == expected +GAME_DATA_RESPONSE = { + "units": [{"id": "U1"}], + "skill": [], + "category": {}, + "guildBanner": None, + "requestSegment": 0, + "version": "", +} + + +@pytest.mark.parametrize( + ("kwargs", "expected"), + [ + pytest.param({}, GAME_DATA_RESPONSE, id="default-keeps-everything"), + pytest.param({"strip_empty": False}, GAME_DATA_RESPONSE, id="false-keeps-everything"), + pytest.param( + {"strip_empty": True}, + {"units": [{"id": "U1"}], "requestSegment": 0, "version": ""}, + id="true-drops-empty-and-null-collections-only", + ), + ], +) +async def test_get_game_data_strip_empty( + comlink: Client, call: Call, httpx_mock: HTTPXMock, kwargs: dict[str, Any], expected: dict[str, Any] +) -> None: + httpx_mock.add_response(json=GAME_DATA_RESPONSE) + + assert await call(comlink, "get_game_data", version="v1", items="UNITS", **kwargs) == expected + + +async def test_get_game_data_strip_empty_is_keyword_only(comlink: Client) -> None: + parameter = inspect.signature(comlink.get_game_data).parameters["strip_empty"] + + assert parameter.kind is inspect.Parameter.KEYWORD_ONLY + assert parameter.default is False + + @pytest.mark.parametrize( ("method", "metadata", "endpoint", "payload_key", "version"), [ From 48fa5666406f95490aff044cf8a9fa2b0febb75a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:53:22 +0000 Subject: [PATCH 40/47] chore(deps): Bump the astral-tools group with 2 updates Bumps the astral-tools group with 2 updates: [ty](https://github.com/astral-sh/ty) and [ruff](https://github.com/astral-sh/ruff). Updates `ty` from 0.0.98 to 0.0.102 - [Release notes](https://github.com/astral-sh/ty/releases) - [Changelog](https://github.com/astral-sh/ty/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ty/compare/0.0.98...0.0.102) Updates `ruff` from 0.17.4 to 0.17.5 - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/0.17.4...0.17.5) --- updated-dependencies: - dependency-name: ty dependency-version: 0.0.102 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: astral-tools - dependency-name: ruff dependency-version: 0.17.5 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: astral-tools ... Signed-off-by: dependabot[bot] --- uv.lock | 76 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/uv.lock b/uv.lock index c47ada0..9e708a0 100644 --- a/uv.lock +++ b/uv.lock @@ -829,27 +829,27 @@ wheels = [ [[package]] name = "ruff" -version = "0.17.4" +version = "0.17.5" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/84/0e/3d154514b5bad104f7e1c13169c2d09aa9959fccdc06eb47610ccdfa83ed/ruff-0.17.4.tar.gz", hash = "sha256:f32d178b50e826e00f6c6c1be3f56333068acb9b67fe167143527fa9b81e890d", size = 5357750, upload-time = "2026-11-05T18:52:17.638Z" } +sdist = { url = "https://files.pythonhosted.org/packages/86/cc/7b71512eb8b49926efb887cc66c74dd993642943c29eba51a877f6b85692/ruff-0.17.5.tar.gz", hash = "sha256:625e57d80cd43352d12ea81690f3eac46cddc8c0f35026d137fb0f157f94592e", size = 5368382, upload-time = "2026-11-12T17:54:55.04Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e0/61/c83c78bbb6108f6c6270a106cf12b54175f4f42da088b9bb880f18e31289/ruff-0.17.4-py3-none-linux_armv6l.whl", hash = "sha256:2b08c4ff98dc234f4a3871a3105353b922fa875ea1073ca31001eb8c06bb4d89", size = 10252195, upload-time = "2026-11-05T18:51:36.594Z" }, - { url = "https://files.pythonhosted.org/packages/0a/12/dd158708378866e8b53e145a465dbc51a7cccb9fa197a74d67eaedde7234/ruff-0.17.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:13e781c3c5f663e7fba737eaaeb70dd943dd55171daf316afb25cd5268cfe0c7", size = 10266044, upload-time = "2026-11-05T18:51:39.502Z" }, - { url = "https://files.pythonhosted.org/packages/28/32/89a94a8eb11fd505a381ae6f04e190d038d9958695209dc1786ce5cfcda3/ruff-0.17.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7ed2f416349944f908f9574215994602242b0836844eba48eec61473033afca0", size = 9432227, upload-time = "2026-11-05T18:51:41.968Z" }, - { url = "https://files.pythonhosted.org/packages/58/de/a392dc38b215798ae72e639d228b7f6c02d826a95d1c0ad7c4c0ee49ef5b/ruff-0.17.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8ea6e0017c785f7282092b11e46338e4ebed1b9e575ebf2e55a8a1eda968241a", size = 10136900, upload-time = "2026-11-05T18:51:44.562Z" }, - { url = "https://files.pythonhosted.org/packages/b7/8f/a880f60f42005f6ffdf58f77af34c7ee327000b5607f48a2f6a69d8b242c/ruff-0.17.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7e061dcc0933c7031a616ac8d66ac540309b2aa21ab558101a8f53e9ac7a1185", size = 10051245, upload-time = "2026-11-05T18:51:46.7Z" }, - { url = "https://files.pythonhosted.org/packages/09/55/98844264108af7d5ec27ca3a9cd5a989094ca657a14599c4b69a537a0e9a/ruff-0.17.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f99e95a1515161138be3cbd1b06c06e739d8feb38ade35564556999fffc3686e", size = 10704341, upload-time = "2026-11-05T18:51:49.228Z" }, - { url = "https://files.pythonhosted.org/packages/28/a2/5edf97659c3ac7c73f978003bd314936f671037fdac6b978e9de3e4b2b65/ruff-0.17.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f28cf0dd37cb172fa5a8d2e92e6ada3a9dbd0609f094ed24039929eef0b7524", size = 11394465, upload-time = "2026-11-05T18:51:51.534Z" }, - { url = "https://files.pythonhosted.org/packages/f2/8f/51371ae856b2bef4d15a044a574695fbc0f6ae63aafa42a2a22428070fb6/ruff-0.17.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b21c771b296888e8a35c6f48555f4b44e4483f61675d6ed51810a5203469ce6", size = 10988262, upload-time = "2026-11-05T18:51:53.91Z" }, - { url = "https://files.pythonhosted.org/packages/af/1b/62874f14c7873f27c7887d2b1ea41de990e14ba9518801ffe8eacb5d51a6/ruff-0.17.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2cd025509b2e15721b426fc70fd946d71f43b3db3b08e946dfec2d696d911690", size = 10572829, upload-time = "2026-11-05T18:51:56.129Z" }, - { url = "https://files.pythonhosted.org/packages/98/30/860b9dae67432b16b88558a9cb2d3194825fa62838f8b9cc49f5d9022095/ruff-0.17.4-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:49b77f7b3921669466882a4881168801bdb06ec2cd83fb936049016cf5fdece1", size = 10617545, upload-time = "2026-11-05T18:51:58.172Z" }, - { url = "https://files.pythonhosted.org/packages/0f/08/781a4b41a1c83fd6e30fea610d6502a6f94e49cf94693fd37bdcbc6bfe11/ruff-0.17.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e3b84eb74f260d1c2dbd236fd9d4c011d4fdd0a52bdf8aea57a10e3a1b71fca5", size = 10111955, upload-time = "2026-11-05T18:52:00.59Z" }, - { url = "https://files.pythonhosted.org/packages/3c/e9/94b1c7b677120f30839254518924f73a8157e9bcfa200edcd5796fecdb99/ruff-0.17.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:20e43d7a08e712e33067ba887e6574546c79bd4831596ce8f16803ac7ff9ad90", size = 10058355, upload-time = "2026-11-05T18:52:03.61Z" }, - { url = "https://files.pythonhosted.org/packages/27/5f/a825910b9f309336dc33cb8c0774126662c1d2f765699b3e0a1bd538d01f/ruff-0.17.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:0d1f4848fd2ec0499be4046db9b7dfcc952666885f00233cc7033515282556a8", size = 10415932, upload-time = "2026-11-05T18:52:06.264Z" }, - { url = "https://files.pythonhosted.org/packages/8b/b8/0796468423413ea4df1a6e2442ae26cf49b8f7dda0eecf246e0d5d0dde54/ruff-0.17.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6007e7f3a0e55b0fbdb947af69cf24c21b4928df6be8ef3e767c69b5ccccf496", size = 10826033, upload-time = "2026-11-05T18:52:08.675Z" }, - { url = "https://files.pythonhosted.org/packages/b9/ab/d8e407669ffe5014429baf780c2df47e001968a6e4c17f615e2e7b13a9ba/ruff-0.17.4-py3-none-win32.whl", hash = "sha256:3971a78cba76298b284c8321e6d40d93045ed348bec5c369d85099efc97fb7cf", size = 9931993, upload-time = "2026-11-05T18:52:11.169Z" }, - { url = "https://files.pythonhosted.org/packages/bd/15/42af8a72d8946e3c9efd2bbf6641e462b6832783b0d043d63ef5b280ba7f/ruff-0.17.4-py3-none-win_amd64.whl", hash = "sha256:67c5a894fc054cf41f75f7afa24815de5a74329d97634126c2a1015740ff4e8c", size = 10292922, upload-time = "2026-11-05T18:52:13.436Z" }, - { url = "https://files.pythonhosted.org/packages/68/9e/f1dbffcfb8ff25dadbc21f87a8b73c3848abe4abada9d4b08ccef8bec40c/ruff-0.17.4-py3-none-win_arm64.whl", hash = "sha256:181ae38a9a8fb94925bf7d0794327b48d7fd7f4b50cfd84c0e999cc09ef8d131", size = 9889396, upload-time = "2026-11-05T18:52:15.549Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/61df414cb4338617290a9023ad09486e207fb9a6d09357a7be34f2e369a4/ruff-0.17.5-py3-none-linux_armv6l.whl", hash = "sha256:d511dd302982e46a285528942fa6557d57730edc4bdb9def95e86a2603d77396", size = 10231309, upload-time = "2026-11-12T17:54:09.314Z" }, + { url = "https://files.pythonhosted.org/packages/d1/72/8ed970f3361f7c8d3f8e1b3b1af27cf086bc4b3a6b62ec20e21a1aaaaff5/ruff-0.17.5-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b72fbc232e328bdbb9cdddf4f1aedcd61bd1aa64d75fc012114b4add0bd7f26b", size = 10250018, upload-time = "2026-11-12T17:54:11.983Z" }, + { url = "https://files.pythonhosted.org/packages/dc/4b/8b10f6c9d0a18413301ae8dd2af9d180a81bb738b1b731d944a37404c523/ruff-0.17.5-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6f0db748508f04a04e3fbebcc636a5c8b3bd76274f8ed28f497c44d75c2ea2d7", size = 9504737, upload-time = "2026-11-12T17:54:14.567Z" }, + { url = "https://files.pythonhosted.org/packages/b7/ea/1b3afa3943239dede7a0755ea139bdb51879f0f3f96f92894081d5c7d2e5/ruff-0.17.5-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f6a7b138edf9cc402ca736a59d9525e6d766e5395760b72e7e146e6251ac963", size = 10168006, upload-time = "2026-11-12T17:54:17.195Z" }, + { url = "https://files.pythonhosted.org/packages/31/08/ee641daa45f83792f91274b65796cb011f1065f588911bfa3909ad9e31e7/ruff-0.17.5-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e52622ecf3a0df9d03e796fe3eed4aa085adda65520db7e0619cbd2192a97342", size = 10043751, upload-time = "2026-11-12T17:54:19.815Z" }, + { url = "https://files.pythonhosted.org/packages/f8/cf/1c59fdb42d0b5671ad5b160636fab4005ee28db72cb06aef6e3f3c04f377/ruff-0.17.5-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:54c0f67d1be11b55d12c184a819fc229f5eee3ef45c16c4fcad41258e83b4882", size = 10690562, upload-time = "2026-11-12T17:54:22.789Z" }, + { url = "https://files.pythonhosted.org/packages/49/c5/578074716173fb0c1591e9648a9f85c469888d9530cb35b89b757dc1208b/ruff-0.17.5-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dd0dfe7c6fe5a447fce467c58e69893be1d9a7e4378f5b9906432da33d94a97f", size = 11338465, upload-time = "2026-11-12T17:54:25.523Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b9/d6428bcf5ed88f4dc1d6e3417ee350236ed36e7a35f9477b727c00e437bf/ruff-0.17.5-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ec4ecf40fb4d6e1265b009dbe551727920926fc0f769070c452d6d84b422a74d", size = 10895501, upload-time = "2026-11-12T17:54:28.441Z" }, + { url = "https://files.pythonhosted.org/packages/f2/8a/1e29c0c3785ae7e5cd0d54ee8717a08867ef71545796340be4c653c57e24/ruff-0.17.5-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40ca8afaac309b41a5b2e09e4e7beb1f824826b93c25697c4d74f573324fba4e", size = 10613231, upload-time = "2026-11-12T17:54:30.862Z" }, + { url = "https://files.pythonhosted.org/packages/32/b6/88944350c14bb90651014d678ad554e233ae2a79c14ad52101845f93d15b/ruff-0.17.5-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:8e85601bd6d9b6c3e3b95c0e0dccdbac1d23c6bcef006d187fbcddaf8225a5df", size = 10562789, upload-time = "2026-11-12T17:54:33.869Z" }, + { url = "https://files.pythonhosted.org/packages/6f/fd/2792e955b0bf54295cdcdddc4bb3f380c0790d7e60e789f528a9e6e48a31/ruff-0.17.5-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:f93d2b7d449ed9545304f6923699ca20d13c675b69f258481709a08ae61076db", size = 10069824, upload-time = "2026-11-12T17:54:36.663Z" }, + { url = "https://files.pythonhosted.org/packages/07/9c/d7cad341b4c19237948a6dd1fcea1c9c39c9d08b70f22f0e157d1236ebd6/ruff-0.17.5-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:0e5c125c5b31dc8efc948d41357496a4c4a312977565ccba740030efdff83580", size = 10038961, upload-time = "2026-11-12T17:54:39.452Z" }, + { url = "https://files.pythonhosted.org/packages/cc/a1/9cd0d4c371ddc70267d3bd557e718e2bdfb94c25e49d25605edfabb764bd/ruff-0.17.5-py3-none-musllinux_1_2_i686.whl", hash = "sha256:50dfc3c6b3ebd0a932f11dfd579bd42234b0b7137e68940eb6abdbfdb9d69697", size = 10385012, upload-time = "2026-11-12T17:54:41.808Z" }, + { url = "https://files.pythonhosted.org/packages/8f/a9/35f078ce98d4df318328ea5270382b5b65e680f7953b3db54f8e009c420c/ruff-0.17.5-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:86bd1f3b83c25f9b8055c6e796f0685b39d3127ce947322098c3108cf82fd586", size = 10793672, upload-time = "2026-11-12T17:54:44.342Z" }, + { url = "https://files.pythonhosted.org/packages/2c/a5/2e136dede2a88aaaf54498bbbdc81bc810f788ef6ef01efb97037d73cd1d/ruff-0.17.5-py3-none-win32.whl", hash = "sha256:e1546609b2ad73f1d6c5c076881b788672b7b3cc3283981182cbdbb6524ed88a", size = 9929908, upload-time = "2026-11-12T17:54:47.067Z" }, + { url = "https://files.pythonhosted.org/packages/ec/8c/e4db9ae1e0ee233c04df007ab6d0d42f799ae9abd95d352b6092ee7bc4bf/ruff-0.17.5-py3-none-win_amd64.whl", hash = "sha256:aa415d57c244299279901d776607fee3df7831c2a7435433fbfacde8632c6550", size = 10275454, upload-time = "2026-11-12T17:54:49.401Z" }, + { url = "https://files.pythonhosted.org/packages/e6/65/a1648bc1550e7683bf7bf1e2ce2485c9f8535cbca6cca9ec7b73cc12fb8e/ruff-0.17.5-py3-none-win_arm64.whl", hash = "sha256:64a6fd668a336df959c522991de33e9e3c8be463afc0c9ac8f029f9d19ef756e", size = 9849020, upload-time = "2026-11-12T17:54:52.055Z" }, ] [[package]] @@ -998,27 +998,27 @@ wheels = [ [[package]] name = "ty" -version = "0.0.98" +version = "0.0.102" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a9/bc/a17167c26defcb6ce004b3668624deb47ed98955f5ef14d8aee6d533d6c8/ty-0.0.98.tar.gz", hash = "sha256:91778c8201da22ba553fb51c5b01c346b7ab37bbf0267536c86e5be4f09467ad", size = 8169824, upload-time = "2026-11-05T17:39:44.73Z" } +sdist = { url = "https://files.pythonhosted.org/packages/26/c1/29d3275a804e0d34a02dfdb161b21aab3ecd0ac8d94ab593cd74086fe495/ty-0.0.102.tar.gz", hash = "sha256:70574ac3706625e5be43ec86e2f57cef179877abe76fef5e9f48539d2f176e78", size = 8265194, upload-time = "2026-11-12T22:09:21.399Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/33/91/de19c23f17dc3a4ad1caa30048c151681f21b90794b67d81adb6fd543b25/ty-0.0.98-py3-none-linux_armv6l.whl", hash = "sha256:4fc233f6f794ffde14d6bbe5ad0999e3d809f486a2a5500890076fd3e142beb4", size = 14681915, upload-time = "2026-11-05T17:39:07.196Z" }, - { url = "https://files.pythonhosted.org/packages/2b/51/1a9a2648c63e04bef27e2ab27e3e419f7e80d1ef567d41111e2b133065fb/ty-0.0.98-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9207be78d93bf5640caad7a6c93f8c4b5ba262e997774f288a0350220c7a7053", size = 14290511, upload-time = "2026-11-05T17:39:09.855Z" }, - { url = "https://files.pythonhosted.org/packages/77/5d/dd82abd70653d48b0e7a5f05582c38149a585e49dfde7f473b0a52064c54/ty-0.0.98-py3-none-macosx_11_0_arm64.whl", hash = "sha256:f1f411590d81edcc75013d220ee522ee083b07f9eb2f085c1eb63767b22d3022", size = 13285566, upload-time = "2026-11-05T17:39:11.956Z" }, - { url = "https://files.pythonhosted.org/packages/3c/da/6ef71f418084487c22f66de651a7db24595f44256ee239e4a78aa2e7047f/ty-0.0.98-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:01133c80ae420cd1c23e25299b10f852a6ae84ea4618b83db7c00d244d10a0cb", size = 14230025, upload-time = "2026-11-05T17:39:14.199Z" }, - { url = "https://files.pythonhosted.org/packages/20/14/25167823974fad33f83aa65fe5b5b90dda44add7b6041c2b2b1a3a108ac8/ty-0.0.98-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ec7cf10443de01c22a6ebd0e08c76f9092378d404f95c50a6efca352c3e671de", size = 14414136, upload-time = "2026-11-05T17:39:16.424Z" }, - { url = "https://files.pythonhosted.org/packages/4e/fb/8ed2e04688eb74d61a9875b20dee33097e01bcaf8dd541801819cfaf7b11/ty-0.0.98-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3ecc9c19acea7c00d834ce3eea181837293bda8113737815ca1044009689f8b1", size = 15377595, upload-time = "2026-11-05T17:39:18.747Z" }, - { url = "https://files.pythonhosted.org/packages/d2/6e/32eb263f83d404532cf7e580fdf464364195c8683725383e0c1f7f207dab/ty-0.0.98-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b46b175a61982dd835ad5e634ab7f5d6045f7e459c0324c1ecb656afa2a79124", size = 15834809, upload-time = "2026-11-05T17:39:20.772Z" }, - { url = "https://files.pythonhosted.org/packages/70/df/63773ba170878ff0e26a3ed432391faf903a1df712ddfdc929693745f0f7/ty-0.0.98-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a00992a56b56b783b4203e0762aa1157ec4721b190a9b0d3bbe6647ce3518f2c", size = 15761661, upload-time = "2026-11-05T17:39:23.102Z" }, - { url = "https://files.pythonhosted.org/packages/a8/a5/efaeb737756db133975085754f1bf0f1d720b322130b0f310ad26457ec59/ty-0.0.98-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1f08c4f7a7f368a0f8a5f8020a660f4cb325fec7ab48d1d073496cb17edd9796", size = 16544942, upload-time = "2026-11-05T17:39:25.267Z" }, - { url = "https://files.pythonhosted.org/packages/d4/b7/7d23d6e8cccbca995e47c0a26c85b3d600354cba5c57122b1a8bdd25edbf/ty-0.0.98-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:44b86d87bb79efd1cc0481cabfbbad45a425fe639fc832762649352e9c6dac2b", size = 15300511, upload-time = "2026-11-05T17:39:27.251Z" }, - { url = "https://files.pythonhosted.org/packages/b9/53/092e5c944f57324b9ca23227468aca022907e78a83477e7597f5a493b77d/ty-0.0.98-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:188df587adc6130d75445d8df7e1af01c3d9b18962f90382865d963893bd2fcb", size = 14131203, upload-time = "2026-11-05T17:39:29.477Z" }, - { url = "https://files.pythonhosted.org/packages/cd/ed/c1b0357ba7524f297d0c90cfeb6241dbf82382f451810db786965926676b/ty-0.0.98-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1d26a72fec5e2e1d21bacdc3ccf8f69b5b352a23f0c717ad5c6267aa25ed7958", size = 14425417, upload-time = "2026-11-05T17:39:31.717Z" }, - { url = "https://files.pythonhosted.org/packages/eb/4a/1ec3a4cbf80badff198d13b278c0cac4cc55256a73c3a7b52774815763e7/ty-0.0.98-py3-none-musllinux_1_2_i686.whl", hash = "sha256:c066c7985b3e6d30ddb23cae5b1e09b0689c98e91efcd0e1ba07da67a4a5db36", size = 14777544, upload-time = "2026-11-05T17:39:33.72Z" }, - { url = "https://files.pythonhosted.org/packages/8e/4b/6c914a633b4f2db404289b003aa87b62c0a15e17870f249a2a31585c03ec/ty-0.0.98-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a3c144a37cea1a2bd643563e7603974f2262132e7225e4e8d536b52092f84fb5", size = 15147963, upload-time = "2026-11-05T17:39:35.969Z" }, - { url = "https://files.pythonhosted.org/packages/9d/3c/fdfc54ed7e49148d166f130d16e1d2e034eaf685ef762f194c2b2b2969c6/ty-0.0.98-py3-none-win32.whl", hash = "sha256:b6dccf6abbb07d2d58db48b535465c9995c52047a208d7c5eda438539c0fdd4c", size = 13632434, upload-time = "2026-11-05T17:39:38.272Z" }, - { url = "https://files.pythonhosted.org/packages/42/94/dc9ba9966ce387f66a296c7b6dfe4e8754695cfa6946f16e8fbfd3beffeb/ty-0.0.98-py3-none-win_amd64.whl", hash = "sha256:c2c41c6923b149b520577fd0424cdbddad12760ddaaa5eda429266aab2d315b9", size = 14258971, upload-time = "2026-11-05T17:39:40.46Z" }, - { url = "https://files.pythonhosted.org/packages/44/5f/c0db82d5e4a5399771735653ce9e0173e1556feb69fcd0ac159aa1473cd9/ty-0.0.98-py3-none-win_arm64.whl", hash = "sha256:b1f9412cb766fec79d7586f72708152d3c97a5fbad826bef986ebbeff3dd0c4f", size = 13701979, upload-time = "2026-11-05T17:39:42.5Z" }, + { url = "https://files.pythonhosted.org/packages/7b/9f/8d54df76ce6c2da5310db706b15c790745dc4428cde298c09cbc6391dffd/ty-0.0.102-py3-none-linux_armv6l.whl", hash = "sha256:e7b8896943a22352668e7e98026c57d45b37e8519079ae501dc93851a58b517b", size = 14936179, upload-time = "2026-11-12T22:08:38.345Z" }, + { url = "https://files.pythonhosted.org/packages/d4/b8/1e6feaa23991a72f25092e61b8f79f109d7607b9418e263f35ae21607cc1/ty-0.0.102-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9d35c179c7d3ddf617523fe7236bb99cc31a73294e355ce1b21ba6535e8a5a63", size = 14503027, upload-time = "2026-11-12T22:08:40.916Z" }, + { url = "https://files.pythonhosted.org/packages/74/53/11e41ea80aadc78eaab9f445f1fa5568b43baa24cd8ad213680b178287eb/ty-0.0.102-py3-none-macosx_11_0_arm64.whl", hash = "sha256:2c4a192eff3d714f928df64e41d053d71876bbbeeb41c73917b488deea94df45", size = 13912010, upload-time = "2026-11-12T22:08:44.422Z" }, + { url = "https://files.pythonhosted.org/packages/7e/41/81130c436218d79916be84ec1384b24f999440ebd1a15ec449ce380fe43d/ty-0.0.102-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:92f4ad28b304e4ddd4aad01e025752b61972aeb0be9f54a863a723a053c750f6", size = 14771137, upload-time = "2026-11-12T22:08:46.687Z" }, + { url = "https://files.pythonhosted.org/packages/ce/fa/b39c8d2744a815619f13717ab60c46c2f225db9531f168ddd48457c8bcd6/ty-0.0.102-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d0abee8af845c61443333b09a81980057c11eaffd74abbbb8359ea55c8746622", size = 14667289, upload-time = "2026-11-12T22:08:49.125Z" }, + { url = "https://files.pythonhosted.org/packages/e3/51/1b4cfd8ad2d5d6f674a589ffbb03a734bd91b6dc1e9e4f7861db3988fa56/ty-0.0.102-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:233cba65505ccfec3402e49c6b3a520bf056831c794b12e8375d705379181c07", size = 15621864, upload-time = "2026-11-12T22:08:51.322Z" }, + { url = "https://files.pythonhosted.org/packages/67/67/43c2b79e2d8a19cd1f00ef550a43bdd41bc7d569ecac010bf2ebb20a8c1b/ty-0.0.102-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a0a1c9eb2c3304dd9dffbc846ba658a7084656d4527275308a9433081f5661f9", size = 16057459, upload-time = "2026-11-12T22:08:53.319Z" }, + { url = "https://files.pythonhosted.org/packages/63/f1/6e0f68d3badb37cfea0f024801595bf29b9bdceac26bd3cdaa8559ef7cf1/ty-0.0.102-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c3576cbdfa25397eba9c7364b47ab8ba2b5625a081c902d77aa813da34bb7bc3", size = 16117882, upload-time = "2026-11-12T22:08:55.677Z" }, + { url = "https://files.pythonhosted.org/packages/f0/a0/ac065c8d4f0111a0a035512b62961f39f431574ea662a793db4c74116bad/ty-0.0.102-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:27c6832227103b9f2a6e3e5264449cdeeb07e13209695f520d1f45bfca6434a9", size = 17481827, upload-time = "2026-11-12T22:08:57.772Z" }, + { url = "https://files.pythonhosted.org/packages/21/56/8e26881415317517d7c3ebbe6b965a185b61cd4062f8840b411c04a53083/ty-0.0.102-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:2b54244c642ac85ca0466924151d3942c7112067ea5cc3ec360f477f63c937af", size = 15490042, upload-time = "2026-11-12T22:09:00.114Z" }, + { url = "https://files.pythonhosted.org/packages/e7/04/6fcba36ccc7f0b1c83a3daf5ec7b6b9b09f98019fedadd08d419640ec5b2/ty-0.0.102-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:09e993afcd0114d11815d55abab688b1930b8f6368ea8941540e93de91debd4d", size = 14333438, upload-time = "2026-11-12T22:09:02.307Z" }, + { url = "https://files.pythonhosted.org/packages/5b/f6/e113fb35fde2a3719f5bb23bfd555518ca5acea776a95f831e5f739f7bf6/ty-0.0.102-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:6cb3da97686d50f782707fdecf132398e1d880c5c53afc4fac5534efe02c4c54", size = 14672545, upload-time = "2026-11-12T22:09:04.623Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b3/a033cf2c3eed957d0fa2f0ebc66fdaa352c5324d0f843b76704c38ed2c96/ty-0.0.102-py3-none-musllinux_1_2_i686.whl", hash = "sha256:edd9b6b44b7f2041d9d0b6b415677a49f4efae8762440d1c2ba75708b742e7c2", size = 15007356, upload-time = "2026-11-12T22:09:06.947Z" }, + { url = "https://files.pythonhosted.org/packages/90/79/36eeafa07bec5d83d3f69d1be400e9996bf9b08653c85feb7f452f339e9d/ty-0.0.102-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:8fbc6a5a26d4232e184f10410cbecd910313f109d58d4bafaef08bf281bd00bc", size = 15392802, upload-time = "2026-11-12T22:09:09.187Z" }, + { url = "https://files.pythonhosted.org/packages/a9/ff/4142a0891191f12a96754df20fcb6596b6a36e7dfe41bbb96cda1f38bc2c/ty-0.0.102-py3-none-win32.whl", hash = "sha256:218d0d77f60f394fc3bb09c4517e387de1e9c508441f2e04f38c9e9d38efcfad", size = 13838366, upload-time = "2026-11-12T22:09:11.244Z" }, + { url = "https://files.pythonhosted.org/packages/05/9a/e02c6aa273d28a35746ffbf72a5f6c957b9b8c782b9a787220af2832beaf/ty-0.0.102-py3-none-win_amd64.whl", hash = "sha256:63e65ea865b5d87a25ea464d7a0ee26c4823aa15bbe0f7210f4db8b0947f69ab", size = 14909230, upload-time = "2026-11-12T22:09:13.383Z" }, + { url = "https://files.pythonhosted.org/packages/ec/68/795f0aebb0d73e6784ce0225e7bd479a603628cc28f9b415c4caba492d73/ty-0.0.102-py3-none-win_arm64.whl", hash = "sha256:a97d4594af618ccfc065f230c2b492cb1bb123e8535a6ab5e2459d48c4050e6a", size = 13907167, upload-time = "2026-11-12T22:09:15.725Z" }, ] [[package]] From 7a6c9f0bd71e34c7cf7a0bf08ab5a944b94d3fbf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:53:59 +0000 Subject: [PATCH 41/47] chore(deps): Bump the python group with 3 updates Bumps the python group with 3 updates: [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio), [git-changelog](https://github.com/pawamoy/git-changelog) and [mkdocs-material](https://github.com/squidfunk/mkdocs-material). Updates `pytest-asyncio` from 1.4.1.post1 to 1.5.0 - [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases) - [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v1.4.1.post1...v1.5.0) Updates `git-changelog` from 2.10.0 to 2.11.0 - [Release notes](https://github.com/pawamoy/git-changelog/releases) - [Changelog](https://github.com/pawamoy/git-changelog/blob/main/CHANGELOG.md) - [Commits](https://github.com/pawamoy/git-changelog/compare/2.10.0...2.11.0) Updates `mkdocs-material` from 9.8.0 to 9.8.1 - [Release notes](https://github.com/squidfunk/mkdocs-material/releases) - [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG) - [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.8.0...9.8.1) --- updated-dependencies: - dependency-name: pytest-asyncio dependency-version: 1.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: python - dependency-name: git-changelog dependency-version: 2.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: python - dependency-name: mkdocs-material dependency-version: 9.8.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: python ... Signed-off-by: dependabot[bot] --- uv.lock | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/uv.lock b/uv.lock index c47ada0..f7c6958 100644 --- a/uv.lock +++ b/uv.lock @@ -274,7 +274,7 @@ wheels = [ [[package]] name = "git-changelog" -version = "2.10.0" +version = "2.11.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jinja2" }, @@ -283,9 +283,9 @@ dependencies = [ { name = "semver" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/24/13/7c5ef6f683868f632f47aa0b7f0e2d755031b0558fe7af7988185deffab3/git_changelog-2.10.0.tar.gz", hash = "sha256:1b6a7d6a12561919be598c3bf4beb2b42a403fb26724b61b810dd58276eb22da", size = 95025, upload-time = "2026-09-26T14:15:43.666Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/dd/64cfc980e35e658f769d7282172ac45cdeb75380a0fdecb188cb9ffd5cef/git_changelog-2.11.0.tar.gz", hash = "sha256:67595f2090c0f017faf5cb27feecfe6edb03f02b5f56d63101c2defc004475e6", size = 104544, upload-time = "2026-11-09T14:50:17.812Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/a6/1200fadeff6d02100afe4606cc1f92417844c44f0f2807395aefb164ef3d/git_changelog-2.10.0-py3-none-any.whl", hash = "sha256:fca6bdaaa966a9cdda11076891a39291ef15fdf38d33820b6f16057e365d1ab5", size = 41598, upload-time = "2026-09-26T14:15:42.39Z" }, + { url = "https://files.pythonhosted.org/packages/5b/9c/4c105b6f311a16dbf72859db89be0f9ae05ac4df43e2716a3528eddf9a0a/git_changelog-2.11.0-py3-none-any.whl", hash = "sha256:8a42fd014d24604d1a5c4ce6b2dd88e21915c3bd4582c07754af3745d8859ecb", size = 45221, upload-time = "2026-11-09T14:49:01.54Z" }, ] [[package]] @@ -536,7 +536,7 @@ wheels = [ [[package]] name = "mkdocs-material" -version = "9.8.0" +version = "9.8.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "babel" }, @@ -551,9 +551,9 @@ dependencies = [ { name = "pymdown-extensions" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b9/02/3c0df248819286810d8479b3a72d9531db0cc36c042fe1ab3985f137c664/mkdocs_material-9.8.0.tar.gz", hash = "sha256:1ed4c5edaf405a3fb62e55288b8fdff592971729361548b1ffa757bf9849fb81", size = 4094495, upload-time = "2026-10-24T09:50:16.181Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e2/b2/dee93bf227b481e28ba4d800c322dffc41b16d524ae84ca8d85aa7ec3a81/mkdocs_material-9.8.1.tar.gz", hash = "sha256:cddae7d77bb98d1d347aa68ee252ab40926171a1b34ba8777c44e16de9629f00", size = 4160481, upload-time = "2026-11-07T13:05:04.482Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c8/16/360f44c7702f27ff4670a647a16c72432291e311371d72b4c34a57e990e0/mkdocs_material-9.8.0-py3-none-any.whl", hash = "sha256:19304a7263c5700428227122b3b2699aa73f432c9de8816876adaec7d7293ce3", size = 9302245, upload-time = "2026-10-24T09:50:12.636Z" }, + { url = "https://files.pythonhosted.org/packages/70/05/a4011d6a6af86cd03059a5b165cd69a3695ef4bd7bd477c66befe399640a/mkdocs_material-9.8.1-py3-none-any.whl", hash = "sha256:2115af67ee680e1398bdd0ea02e517721e4bba88b342503a93f97ea8eb3de51c", size = 9302217, upload-time = "2026-11-07T13:05:00.747Z" }, ] [[package]] @@ -695,15 +695,15 @@ wheels = [ [[package]] name = "pytest-asyncio" -version = "1.4.1.post1" +version = "1.5.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pytest" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/73/7f/c60a4338420b33453d4f814ac0c930abd399f162b9bdd21af4b9e363037f/pytest_asyncio-1.4.1.post1.tar.gz", hash = "sha256:f582d9ea4a1c082195abe8bd29a1fe106aeb1cd435e3dad2d3bc2749935c36a2", size = 145360, upload-time = "2026-11-01T18:26:03.732Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/de/80724f9b5b9eca1a654179cae6edc51aaa0a355a9834a736e2a188b91780/pytest_asyncio-1.5.0.tar.gz", hash = "sha256:92c8fa83ca419fd0d4bd6a34df6520dae435841d3733c319343249492adf37f7", size = 146227, upload-time = "2026-11-12T16:35:49.845Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e3/de/adbc7578959cfab07e5e7c05cf6d54224a51e7667ea2c07458b6bc571e75/pytest_asyncio-1.4.1.post1-py3-none-any.whl", hash = "sha256:0755e488cc0a2b9bd2eab7292cc6390d4cbb8390f1020745647bae5a708e0165", size = 17140, upload-time = "2026-11-01T18:26:02.168Z" }, + { url = "https://files.pythonhosted.org/packages/27/2d/e600d8f47597a803641704aba367c7266cd621f86561ec36da9888f160ec/pytest_asyncio-1.5.0-py3-none-any.whl", hash = "sha256:557f255ee03cc84f84a8d5f438bc9c6e0f714bf86970ae743c7ecb5a38d7e07d", size = 17215, upload-time = "2026-11-12T16:35:48.446Z" }, ] [[package]] From f41fa55ca9c51ce1558a703149ce9a4a11495984 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:52:45 +0000 Subject: [PATCH 42/47] chore(deps): Bump astral-sh/setup-uv Bumps the github-actions group with 1 update: [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv). Updates `astral-sh/setup-uv` from 10.3.3 to 10.4.0 - [Release notes](https://github.com/astral-sh/setup-uv/releases) - [Commits](https://github.com/astral-sh/setup-uv/compare/68559e99cc807c1eb7e9238fd43a15bba460eec2...1db35dd8eee11c5894872e0b383ae6c406cf738d) --- updated-dependencies: - dependency-name: astral-sh/setup-uv dependency-version: 10.4.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 12 ++++++------ .github/workflows/commitlint.yml | 2 +- .github/workflows/docs.yml | 2 +- .github/workflows/integration.yml | 2 +- .github/workflows/prepare-release.yml | 2 +- .github/workflows/release.yml | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 275e20f..c8ef180 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -50,7 +50,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -75,7 +75,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -108,7 +108,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -129,7 +129,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 @@ -158,7 +158,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" diff --git a/.github/workflows/commitlint.yml b/.github/workflows/commitlint.yml index 1ebf1b1..3e169d2 100644 --- a/.github/workflows/commitlint.yml +++ b/.github/workflows/commitlint.yml @@ -21,7 +21,7 @@ jobs: # same hook through pre-commit rather than its own npm install, so local and CI # validation cannot drift. - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Cache the pre-commit hook environment uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 22f3909..1ba3b0b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -72,7 +72,7 @@ jobs: persist-credentials: true - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: # This job publishes the site, so it must not restore a cache that # other workflows (e.g. PR runs) can write. diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 091b453..91e8315 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -60,7 +60,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 1fcff6e..e664d66 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -42,7 +42,7 @@ jobs: fetch-depth: 0 - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3bb79d0..cef0606 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,7 +40,7 @@ jobs: fetch-depth: 0 # full history + tags for version derivation - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 From 3f35921eef7e452c0965aa86f5384d4b924094ad Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:53:19 +0000 Subject: [PATCH 43/47] chore(deps): Bump the astral-tools group with 2 updates Bumps the astral-tools group with 2 updates: [ty](https://github.com/astral-sh/ty) and [ruff](https://github.com/astral-sh/ruff). Updates `ty` from 0.0.102 to 0.0.107 - [Release notes](https://github.com/astral-sh/ty/releases) - [Changelog](https://github.com/astral-sh/ty/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ty/compare/0.0.102...0.0.107) Updates `ruff` from 0.17.5 to 0.17.6 - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/0.17.5...0.17.6) --- updated-dependencies: - dependency-name: ty dependency-version: 0.0.107 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: astral-tools - dependency-name: ruff dependency-version: 0.17.6 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: astral-tools ... Signed-off-by: dependabot[bot] --- uv.lock | 76 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/uv.lock b/uv.lock index 5697ce4..7270531 100644 --- a/uv.lock +++ b/uv.lock @@ -829,27 +829,27 @@ wheels = [ [[package]] name = "ruff" -version = "0.17.5" +version = "0.17.6" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/86/cc/7b71512eb8b49926efb887cc66c74dd993642943c29eba51a877f6b85692/ruff-0.17.5.tar.gz", hash = "sha256:625e57d80cd43352d12ea81690f3eac46cddc8c0f35026d137fb0f157f94592e", size = 5368382, upload-time = "2026-11-12T17:54:55.04Z" } +sdist = { url = "https://files.pythonhosted.org/packages/df/8e/6929d337aa5380aafc7355f3149f3ccfe55cba5fdd34a045697ebaceb5a0/ruff-0.17.6.tar.gz", hash = "sha256:2b04276561331300325040bdca21460770029ec574d4c479099e39e8ad1ed43c", size = 5374388, upload-time = "2026-11-19T15:56:27.106Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d4/f2/61df414cb4338617290a9023ad09486e207fb9a6d09357a7be34f2e369a4/ruff-0.17.5-py3-none-linux_armv6l.whl", hash = "sha256:d511dd302982e46a285528942fa6557d57730edc4bdb9def95e86a2603d77396", size = 10231309, upload-time = "2026-11-12T17:54:09.314Z" }, - { url = "https://files.pythonhosted.org/packages/d1/72/8ed970f3361f7c8d3f8e1b3b1af27cf086bc4b3a6b62ec20e21a1aaaaff5/ruff-0.17.5-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b72fbc232e328bdbb9cdddf4f1aedcd61bd1aa64d75fc012114b4add0bd7f26b", size = 10250018, upload-time = "2026-11-12T17:54:11.983Z" }, - { url = "https://files.pythonhosted.org/packages/dc/4b/8b10f6c9d0a18413301ae8dd2af9d180a81bb738b1b731d944a37404c523/ruff-0.17.5-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6f0db748508f04a04e3fbebcc636a5c8b3bd76274f8ed28f497c44d75c2ea2d7", size = 9504737, upload-time = "2026-11-12T17:54:14.567Z" }, - { url = "https://files.pythonhosted.org/packages/b7/ea/1b3afa3943239dede7a0755ea139bdb51879f0f3f96f92894081d5c7d2e5/ruff-0.17.5-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f6a7b138edf9cc402ca736a59d9525e6d766e5395760b72e7e146e6251ac963", size = 10168006, upload-time = "2026-11-12T17:54:17.195Z" }, - { url = "https://files.pythonhosted.org/packages/31/08/ee641daa45f83792f91274b65796cb011f1065f588911bfa3909ad9e31e7/ruff-0.17.5-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e52622ecf3a0df9d03e796fe3eed4aa085adda65520db7e0619cbd2192a97342", size = 10043751, upload-time = "2026-11-12T17:54:19.815Z" }, - { url = "https://files.pythonhosted.org/packages/f8/cf/1c59fdb42d0b5671ad5b160636fab4005ee28db72cb06aef6e3f3c04f377/ruff-0.17.5-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:54c0f67d1be11b55d12c184a819fc229f5eee3ef45c16c4fcad41258e83b4882", size = 10690562, upload-time = "2026-11-12T17:54:22.789Z" }, - { url = "https://files.pythonhosted.org/packages/49/c5/578074716173fb0c1591e9648a9f85c469888d9530cb35b89b757dc1208b/ruff-0.17.5-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dd0dfe7c6fe5a447fce467c58e69893be1d9a7e4378f5b9906432da33d94a97f", size = 11338465, upload-time = "2026-11-12T17:54:25.523Z" }, - { url = "https://files.pythonhosted.org/packages/aa/b9/d6428bcf5ed88f4dc1d6e3417ee350236ed36e7a35f9477b727c00e437bf/ruff-0.17.5-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ec4ecf40fb4d6e1265b009dbe551727920926fc0f769070c452d6d84b422a74d", size = 10895501, upload-time = "2026-11-12T17:54:28.441Z" }, - { url = "https://files.pythonhosted.org/packages/f2/8a/1e29c0c3785ae7e5cd0d54ee8717a08867ef71545796340be4c653c57e24/ruff-0.17.5-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40ca8afaac309b41a5b2e09e4e7beb1f824826b93c25697c4d74f573324fba4e", size = 10613231, upload-time = "2026-11-12T17:54:30.862Z" }, - { url = "https://files.pythonhosted.org/packages/32/b6/88944350c14bb90651014d678ad554e233ae2a79c14ad52101845f93d15b/ruff-0.17.5-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:8e85601bd6d9b6c3e3b95c0e0dccdbac1d23c6bcef006d187fbcddaf8225a5df", size = 10562789, upload-time = "2026-11-12T17:54:33.869Z" }, - { url = "https://files.pythonhosted.org/packages/6f/fd/2792e955b0bf54295cdcdddc4bb3f380c0790d7e60e789f528a9e6e48a31/ruff-0.17.5-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:f93d2b7d449ed9545304f6923699ca20d13c675b69f258481709a08ae61076db", size = 10069824, upload-time = "2026-11-12T17:54:36.663Z" }, - { url = "https://files.pythonhosted.org/packages/07/9c/d7cad341b4c19237948a6dd1fcea1c9c39c9d08b70f22f0e157d1236ebd6/ruff-0.17.5-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:0e5c125c5b31dc8efc948d41357496a4c4a312977565ccba740030efdff83580", size = 10038961, upload-time = "2026-11-12T17:54:39.452Z" }, - { url = "https://files.pythonhosted.org/packages/cc/a1/9cd0d4c371ddc70267d3bd557e718e2bdfb94c25e49d25605edfabb764bd/ruff-0.17.5-py3-none-musllinux_1_2_i686.whl", hash = "sha256:50dfc3c6b3ebd0a932f11dfd579bd42234b0b7137e68940eb6abdbfdb9d69697", size = 10385012, upload-time = "2026-11-12T17:54:41.808Z" }, - { url = "https://files.pythonhosted.org/packages/8f/a9/35f078ce98d4df318328ea5270382b5b65e680f7953b3db54f8e009c420c/ruff-0.17.5-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:86bd1f3b83c25f9b8055c6e796f0685b39d3127ce947322098c3108cf82fd586", size = 10793672, upload-time = "2026-11-12T17:54:44.342Z" }, - { url = "https://files.pythonhosted.org/packages/2c/a5/2e136dede2a88aaaf54498bbbdc81bc810f788ef6ef01efb97037d73cd1d/ruff-0.17.5-py3-none-win32.whl", hash = "sha256:e1546609b2ad73f1d6c5c076881b788672b7b3cc3283981182cbdbb6524ed88a", size = 9929908, upload-time = "2026-11-12T17:54:47.067Z" }, - { url = "https://files.pythonhosted.org/packages/ec/8c/e4db9ae1e0ee233c04df007ab6d0d42f799ae9abd95d352b6092ee7bc4bf/ruff-0.17.5-py3-none-win_amd64.whl", hash = "sha256:aa415d57c244299279901d776607fee3df7831c2a7435433fbfacde8632c6550", size = 10275454, upload-time = "2026-11-12T17:54:49.401Z" }, - { url = "https://files.pythonhosted.org/packages/e6/65/a1648bc1550e7683bf7bf1e2ce2485c9f8535cbca6cca9ec7b73cc12fb8e/ruff-0.17.5-py3-none-win_arm64.whl", hash = "sha256:64a6fd668a336df959c522991de33e9e3c8be463afc0c9ac8f029f9d19ef756e", size = 9849020, upload-time = "2026-11-12T17:54:52.055Z" }, + { url = "https://files.pythonhosted.org/packages/12/5d/38ef6310c22cacb094e9ae0ff7964062e04ffeecb45ee296894c2b1acc54/ruff-0.17.6-py3-none-linux_armv6l.whl", hash = "sha256:084d9c8f5ec718e7eba007dba339e7cb4f7571d2f267558ae080bf428fb6a69b", size = 10174693, upload-time = "2026-11-19T15:55:52.414Z" }, + { url = "https://files.pythonhosted.org/packages/a2/ed/fd35261049920a4888ef7c787a5c27089502077a4910f6ca8f1213157d6d/ruff-0.17.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9d44ef2140402043fd6f689ef541858b80883a8b0a02e38539ef0614ebe57d0c", size = 10221650, upload-time = "2026-11-19T15:55:54.962Z" }, + { url = "https://files.pythonhosted.org/packages/ba/d4/c31391b36c729cd9fafa65b7a52a58850b99afb2b65da6be4263a53302f2/ruff-0.17.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9fbddc08577592e283c265d865e0182de6e33db185494db7b06290d989d888e5", size = 9580986, upload-time = "2026-11-19T15:55:57.391Z" }, + { url = "https://files.pythonhosted.org/packages/eb/11/f3032684dcb3a676d7924545153d76fb56f76753e038f2ea650b99c71bdf/ruff-0.17.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:435241c61af5909a022f76219d3d1bf24730dc1bf0acabb5ddf4b569ab3cbb30", size = 10271368, upload-time = "2026-11-19T15:55:59.654Z" }, + { url = "https://files.pythonhosted.org/packages/08/30/c1e024eeb5bae99ae78c6b896ed108f64c9c845a03b56eaeff098e99b6e6/ruff-0.17.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d006bbb2945edb17b0ce6a0c1b5f5a8d81ba11dbac294a0a925effa22ce34feb", size = 9981564, upload-time = "2026-11-19T15:56:01.807Z" }, + { url = "https://files.pythonhosted.org/packages/7d/a5/da3e0c2d4bf02b3ca6c1d7fa4bb04d0081e340b1dd03c4f83b1bec3e15c1/ruff-0.17.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fd661702202a89c00a4c9d0339008805fa5876bfa1c57e165495c2e62230dfbf", size = 10641991, upload-time = "2026-11-19T15:56:03.981Z" }, + { url = "https://files.pythonhosted.org/packages/4d/c1/6d7f981e86201c9db457cca99fd2c09b77574ebab37dff3e9239b218603c/ruff-0.17.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6a12c50a33936dc00db2be21ba25fb168a8b95c55eda2a3ac85005af69885e4b", size = 11403484, upload-time = "2026-11-19T15:56:05.778Z" }, + { url = "https://files.pythonhosted.org/packages/c3/92/8182f07b94998541d5f8f38f53da465aa28062afce24ecc398f45bfc62f1/ruff-0.17.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b5aba93b3db4b70c5697e4fee6e0d5b9c8452a9a3a03679611cadc25915a2173", size = 10892316, upload-time = "2026-11-19T15:56:08.016Z" }, + { url = "https://files.pythonhosted.org/packages/be/48/3df7d81249fd69ee6a49519b149fb5d11e13118fd7d0e8d65329a237087b/ruff-0.17.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa3b08254a732acba246891089a152c47c5733dc36b8ecb76ce8602f8326e5e4", size = 10645279, upload-time = "2026-11-19T15:56:09.785Z" }, + { url = "https://files.pythonhosted.org/packages/71/80/4d232281544345d7beb98d1d32c24dae804ed360780a6f7753738b81225e/ruff-0.17.6-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:0692088e6b33455572fb18465e891b443f196e98dc1986825685c77ff6f4c5ac", size = 10534501, upload-time = "2026-11-19T15:56:11.718Z" }, + { url = "https://files.pythonhosted.org/packages/98/0a/b477f075a4a94eb541bf1c759a3e72b2a3d6390af7a13a5be0887229f67c/ruff-0.17.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:fb589e032806bb942e4fb526f30b80a1a64112147ed9f1d38cc3de2e255b6f45", size = 10136036, upload-time = "2026-11-19T15:56:13.779Z" }, + { url = "https://files.pythonhosted.org/packages/f1/d8/cf32fbfeb1fcda1470fb5c3bee50c69ee6bca257d487ec1eb17a0387edb4/ruff-0.17.6-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1939b3d701c7b6981b7cf93473de5bf88b129b9ba84efaed5154cc517c44634d", size = 9969640, upload-time = "2026-11-19T15:56:15.738Z" }, + { url = "https://files.pythonhosted.org/packages/a7/22/bb9f9752f7fcdfdc8b9c51576cc142bb377ade745290e35085173963c7be/ruff-0.17.6-py3-none-musllinux_1_2_i686.whl", hash = "sha256:1a0bea6aa1216e0ec4cd35d3dbccec0d772a7c2aad28ec9c6e82571dff2c20b0", size = 10389427, upload-time = "2026-11-19T15:56:17.617Z" }, + { url = "https://files.pythonhosted.org/packages/81/c7/e09d220818ab146b736d62e0676dad215215d7de0884bbdad9fa075dc7d2/ruff-0.17.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:3db61f5015600543a581b07fa7f6f64afa0eeedefe16034cadd88c4074087582", size = 10760296, upload-time = "2026-11-19T15:56:19.463Z" }, + { url = "https://files.pythonhosted.org/packages/2e/09/28329441dfa2c463e2d377a69d4ebbe4d51665e9dbd49fb421f3bc80d775/ruff-0.17.6-py3-none-win32.whl", hash = "sha256:c2f4af6670b7a0501904e881bb3f1f24bd0d964dec1eedbd85f0eb73786e1128", size = 9966266, upload-time = "2026-11-19T15:56:21.581Z" }, + { url = "https://files.pythonhosted.org/packages/4b/9d/18ba9730addfc7554c70d6f171fb8dc2c08e774d9fb2b98e7946ef845c59/ruff-0.17.6-py3-none-win_amd64.whl", hash = "sha256:9cd2fd9923e9806b8b6b67a3469e2258e84bd4d21e45d5a1a690afdfb9c8e57d", size = 10365847, upload-time = "2026-11-19T15:56:23.582Z" }, + { url = "https://files.pythonhosted.org/packages/70/8a/59c33e2a64a4f9672f7f842a0dc522915cfbbaffd13d37d0cec57d1c5c5d/ruff-0.17.6-py3-none-win_arm64.whl", hash = "sha256:d8b14e1473dc86ab9069cf7a2ba5041dc012f59110201844ed04cfddf07055a0", size = 9926224, upload-time = "2026-11-19T15:56:25.269Z" }, ] [[package]] @@ -998,27 +998,27 @@ wheels = [ [[package]] name = "ty" -version = "0.0.102" +version = "0.0.107" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/26/c1/29d3275a804e0d34a02dfdb161b21aab3ecd0ac8d94ab593cd74086fe495/ty-0.0.102.tar.gz", hash = "sha256:70574ac3706625e5be43ec86e2f57cef179877abe76fef5e9f48539d2f176e78", size = 8265194, upload-time = "2026-11-12T22:09:21.399Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e1/21/096166a4d1118a6ce923223d53d14dc6262046604b6f1e667882db8d80b3/ty-0.0.107.tar.gz", hash = "sha256:e792277547cd55f5e75208665da705825f0af627397aa7abb169d5ad994277ca", size = 8342007, upload-time = "2026-11-18T21:08:00.423Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7b/9f/8d54df76ce6c2da5310db706b15c790745dc4428cde298c09cbc6391dffd/ty-0.0.102-py3-none-linux_armv6l.whl", hash = "sha256:e7b8896943a22352668e7e98026c57d45b37e8519079ae501dc93851a58b517b", size = 14936179, upload-time = "2026-11-12T22:08:38.345Z" }, - { url = "https://files.pythonhosted.org/packages/d4/b8/1e6feaa23991a72f25092e61b8f79f109d7607b9418e263f35ae21607cc1/ty-0.0.102-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9d35c179c7d3ddf617523fe7236bb99cc31a73294e355ce1b21ba6535e8a5a63", size = 14503027, upload-time = "2026-11-12T22:08:40.916Z" }, - { url = "https://files.pythonhosted.org/packages/74/53/11e41ea80aadc78eaab9f445f1fa5568b43baa24cd8ad213680b178287eb/ty-0.0.102-py3-none-macosx_11_0_arm64.whl", hash = "sha256:2c4a192eff3d714f928df64e41d053d71876bbbeeb41c73917b488deea94df45", size = 13912010, upload-time = "2026-11-12T22:08:44.422Z" }, - { url = "https://files.pythonhosted.org/packages/7e/41/81130c436218d79916be84ec1384b24f999440ebd1a15ec449ce380fe43d/ty-0.0.102-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:92f4ad28b304e4ddd4aad01e025752b61972aeb0be9f54a863a723a053c750f6", size = 14771137, upload-time = "2026-11-12T22:08:46.687Z" }, - { url = "https://files.pythonhosted.org/packages/ce/fa/b39c8d2744a815619f13717ab60c46c2f225db9531f168ddd48457c8bcd6/ty-0.0.102-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d0abee8af845c61443333b09a81980057c11eaffd74abbbb8359ea55c8746622", size = 14667289, upload-time = "2026-11-12T22:08:49.125Z" }, - { url = "https://files.pythonhosted.org/packages/e3/51/1b4cfd8ad2d5d6f674a589ffbb03a734bd91b6dc1e9e4f7861db3988fa56/ty-0.0.102-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:233cba65505ccfec3402e49c6b3a520bf056831c794b12e8375d705379181c07", size = 15621864, upload-time = "2026-11-12T22:08:51.322Z" }, - { url = "https://files.pythonhosted.org/packages/67/67/43c2b79e2d8a19cd1f00ef550a43bdd41bc7d569ecac010bf2ebb20a8c1b/ty-0.0.102-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a0a1c9eb2c3304dd9dffbc846ba658a7084656d4527275308a9433081f5661f9", size = 16057459, upload-time = "2026-11-12T22:08:53.319Z" }, - { url = "https://files.pythonhosted.org/packages/63/f1/6e0f68d3badb37cfea0f024801595bf29b9bdceac26bd3cdaa8559ef7cf1/ty-0.0.102-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c3576cbdfa25397eba9c7364b47ab8ba2b5625a081c902d77aa813da34bb7bc3", size = 16117882, upload-time = "2026-11-12T22:08:55.677Z" }, - { url = "https://files.pythonhosted.org/packages/f0/a0/ac065c8d4f0111a0a035512b62961f39f431574ea662a793db4c74116bad/ty-0.0.102-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:27c6832227103b9f2a6e3e5264449cdeeb07e13209695f520d1f45bfca6434a9", size = 17481827, upload-time = "2026-11-12T22:08:57.772Z" }, - { url = "https://files.pythonhosted.org/packages/21/56/8e26881415317517d7c3ebbe6b965a185b61cd4062f8840b411c04a53083/ty-0.0.102-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:2b54244c642ac85ca0466924151d3942c7112067ea5cc3ec360f477f63c937af", size = 15490042, upload-time = "2026-11-12T22:09:00.114Z" }, - { url = "https://files.pythonhosted.org/packages/e7/04/6fcba36ccc7f0b1c83a3daf5ec7b6b9b09f98019fedadd08d419640ec5b2/ty-0.0.102-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:09e993afcd0114d11815d55abab688b1930b8f6368ea8941540e93de91debd4d", size = 14333438, upload-time = "2026-11-12T22:09:02.307Z" }, - { url = "https://files.pythonhosted.org/packages/5b/f6/e113fb35fde2a3719f5bb23bfd555518ca5acea776a95f831e5f739f7bf6/ty-0.0.102-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:6cb3da97686d50f782707fdecf132398e1d880c5c53afc4fac5534efe02c4c54", size = 14672545, upload-time = "2026-11-12T22:09:04.623Z" }, - { url = "https://files.pythonhosted.org/packages/d9/b3/a033cf2c3eed957d0fa2f0ebc66fdaa352c5324d0f843b76704c38ed2c96/ty-0.0.102-py3-none-musllinux_1_2_i686.whl", hash = "sha256:edd9b6b44b7f2041d9d0b6b415677a49f4efae8762440d1c2ba75708b742e7c2", size = 15007356, upload-time = "2026-11-12T22:09:06.947Z" }, - { url = "https://files.pythonhosted.org/packages/90/79/36eeafa07bec5d83d3f69d1be400e9996bf9b08653c85feb7f452f339e9d/ty-0.0.102-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:8fbc6a5a26d4232e184f10410cbecd910313f109d58d4bafaef08bf281bd00bc", size = 15392802, upload-time = "2026-11-12T22:09:09.187Z" }, - { url = "https://files.pythonhosted.org/packages/a9/ff/4142a0891191f12a96754df20fcb6596b6a36e7dfe41bbb96cda1f38bc2c/ty-0.0.102-py3-none-win32.whl", hash = "sha256:218d0d77f60f394fc3bb09c4517e387de1e9c508441f2e04f38c9e9d38efcfad", size = 13838366, upload-time = "2026-11-12T22:09:11.244Z" }, - { url = "https://files.pythonhosted.org/packages/05/9a/e02c6aa273d28a35746ffbf72a5f6c957b9b8c782b9a787220af2832beaf/ty-0.0.102-py3-none-win_amd64.whl", hash = "sha256:63e65ea865b5d87a25ea464d7a0ee26c4823aa15bbe0f7210f4db8b0947f69ab", size = 14909230, upload-time = "2026-11-12T22:09:13.383Z" }, - { url = "https://files.pythonhosted.org/packages/ec/68/795f0aebb0d73e6784ce0225e7bd479a603628cc28f9b415c4caba492d73/ty-0.0.102-py3-none-win_arm64.whl", hash = "sha256:a97d4594af618ccfc065f230c2b492cb1bb123e8535a6ab5e2459d48c4050e6a", size = 13907167, upload-time = "2026-11-12T22:09:15.725Z" }, + { url = "https://files.pythonhosted.org/packages/ea/b3/ed4d2f9899657b3fef03df61f5937570ff68c5fe43b1110b70350487e986/ty-0.0.107-py3-none-linux_armv6l.whl", hash = "sha256:dcf2567fe5ed95f21bf3e3fcc5de68a4b570a8b0e6029b3a57b8098e784b90d1", size = 15002472, upload-time = "2026-11-18T21:07:11.018Z" }, + { url = "https://files.pythonhosted.org/packages/cb/ae/164d1aeaf968a4d4104bf48c978a8bef8de1e258574b33fdb2d9fa9f5c21/ty-0.0.107-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:39dfc6a2ce0b1df3e53a518e92cd331f30c11355e44f55df9096581437be1e24", size = 14576636, upload-time = "2026-11-18T21:07:14.615Z" }, + { url = "https://files.pythonhosted.org/packages/a7/a4/c7b60685da0db9d7699459afe75fd17b1143e6fc14f6484fc55c2e705c1a/ty-0.0.107-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6f4169889ecb5ee42e15227c6b6f978c6638548c9929cb19f76022afef903361", size = 13973376, upload-time = "2026-11-18T21:07:17.377Z" }, + { url = "https://files.pythonhosted.org/packages/00/12/bf50a964941e6e03e3d526576a3f3c942029e06666f8db4a4541940ff743/ty-0.0.107-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9733e57559906229a897ed2834b7175013455c6b800aa3c029b15876fa11a75e", size = 14914214, upload-time = "2026-11-18T21:07:20.148Z" }, + { url = "https://files.pythonhosted.org/packages/a8/7f/1b283835c397fcb58d86a6355f8b138978e9c1121fe7514e4247dc9f7038/ty-0.0.107-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8ffa6cad4f057f45a7f68605622b16ed18fcb5a817ea1a1130ad689d0ec69c82", size = 14727467, upload-time = "2026-11-18T21:07:23.377Z" }, + { url = "https://files.pythonhosted.org/packages/7b/91/6a59b43159a9810f42d185e4d04fb52e5c8f48e786a75facd56f5990fa3a/ty-0.0.107-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6693dfa209355f0257a904f65eb6a37e50633af5bad9d304291956d84084c15e", size = 15718081, upload-time = "2026-11-18T21:07:26.053Z" }, + { url = "https://files.pythonhosted.org/packages/e0/62/c2d5a02dcaa19e674c79e527f1706f6691278c7ca85504a83240a602734a/ty-0.0.107-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f915ce2277bcb914c36134d8142ff7c209e0fe43647055a28df5001bdf1b173b", size = 16153080, upload-time = "2026-11-18T21:07:28.941Z" }, + { url = "https://files.pythonhosted.org/packages/88/f2/94af1c34c93ae9226e4c58f3c0a6ccb848f962f2838bf36d300f5a70f4a1/ty-0.0.107-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4d9f968afebb4e25239383029600073bbcdd2e82a1a7d3ff438d1ae8efd662c1", size = 16018858, upload-time = "2026-11-18T21:07:31.757Z" }, + { url = "https://files.pythonhosted.org/packages/21/17/16cb65301cd21f50634480b4fff3d4c25e61c4cd73f7e9c850681dddc08f/ty-0.0.107-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1fe5917b9ed2b4e500610cafb90f4a84ba936cf83eb3e2b8a9e44449b59b77cb", size = 17434891, upload-time = "2026-11-18T21:07:34.618Z" }, + { url = "https://files.pythonhosted.org/packages/14/54/dba49f1255a2fe2b49fed88e56ae385a977f3ab5b9c0579e92fb1380b235/ty-0.0.107-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:714447884645175ce96f566063fd31539960832423f748af5a4c3b5c817f0604", size = 15540910, upload-time = "2026-11-18T21:07:37.448Z" }, + { url = "https://files.pythonhosted.org/packages/c2/90/f87b2c5fa3323fd1d4ab30a7a78f4b363ca8337087dea9532be53fd02c5d/ty-0.0.107-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:bc37c53103d447c8a4d2eba6f746f9ded12c8aea66bd8c03d7039a976069aad4", size = 14401178, upload-time = "2026-11-18T21:07:40.233Z" }, + { url = "https://files.pythonhosted.org/packages/7a/33/b6cad6f43aeaca2988839827f40d6f0a62b062f352be472a2131f35ff0fc/ty-0.0.107-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:fe0aedb5047ac9e5fc2812e4ba36778efd2e5187c9056acf65bd67e85fa83418", size = 14742847, upload-time = "2026-11-18T21:07:43.269Z" }, + { url = "https://files.pythonhosted.org/packages/e0/4e/f467a0b8e151bf2162d9180e824c2dee30092c1284ed123fd787c1572fc9/ty-0.0.107-py3-none-musllinux_1_2_i686.whl", hash = "sha256:2eafaffdeb80484831e2c16e3cec3e1e45176c88cb08a82395138cc6a7695aa9", size = 15103370, upload-time = "2026-11-18T21:07:45.918Z" }, + { url = "https://files.pythonhosted.org/packages/59/76/e0df8db6f22ba0380b0775d7668e3e93cb12b7ab33326a1199f8e88d1d0b/ty-0.0.107-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:2e8fc59467d57762b4b171b597092ba7ebb91071b6dffda8ca3be393cebd437a", size = 15438466, upload-time = "2026-11-18T21:07:48.842Z" }, + { url = "https://files.pythonhosted.org/packages/cd/fe/fc14a66f6a7464a6b7ebd2440f7becd2146aa865f7516b22d44df29c1f3a/ty-0.0.107-py3-none-win32.whl", hash = "sha256:40b4c00666db9bcfe112b320522192ae598c0982f3c7270ce62eb313ffabb373", size = 13966366, upload-time = "2026-11-18T21:07:51.826Z" }, + { url = "https://files.pythonhosted.org/packages/a0/ad/1c992fb038f33a34f32f1ebc57ac4023ab60b4530e2bbf3fdd5e6d97753e/ty-0.0.107-py3-none-win_amd64.whl", hash = "sha256:e9b5e292a0b39105e1068ff176f355eb645b45d9f6aa91765ca739069ed13c12", size = 14895905, upload-time = "2026-11-18T21:07:54.814Z" }, + { url = "https://files.pythonhosted.org/packages/4e/93/83c2fa56dd6ab9f9d1253621ae79a5bbc2f3fc2bb3e562f2e8cd1ad5df5c/ty-0.0.107-py3-none-win_arm64.whl", hash = "sha256:c5f4eb4ea3c84ab755dafb7d09abee8d6fbd582db5371d858443f0c85e72dcd3", size = 14031494, upload-time = "2026-11-18T21:07:57.714Z" }, ] [[package]] From a326aaab5476aec9f6ce2b78d4d22c408348e48e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:53:50 +0000 Subject: [PATCH 44/47] chore(deps): Bump the python group with 2 updates Bumps the python group with 2 updates: [git-changelog](https://github.com/pawamoy/git-changelog) and [mkdocs-material](https://github.com/squidfunk/mkdocs-material). Updates `git-changelog` from 2.11.0 to 2.12.0 - [Release notes](https://github.com/pawamoy/git-changelog/releases) - [Changelog](https://github.com/pawamoy/git-changelog/blob/main/CHANGELOG.md) - [Commits](https://github.com/pawamoy/git-changelog/compare/2.11.0...2.12.0) Updates `mkdocs-material` from 9.8.1 to 9.8.2 - [Release notes](https://github.com/squidfunk/mkdocs-material/releases) - [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG) - [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.8.1...9.8.2) --- updated-dependencies: - dependency-name: git-changelog dependency-version: 2.12.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: python - dependency-name: mkdocs-material dependency-version: 9.8.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: python ... Signed-off-by: dependabot[bot] --- uv.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/uv.lock b/uv.lock index 5697ce4..ec1ab7b 100644 --- a/uv.lock +++ b/uv.lock @@ -274,7 +274,7 @@ wheels = [ [[package]] name = "git-changelog" -version = "2.11.0" +version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jinja2" }, @@ -283,9 +283,9 @@ dependencies = [ { name = "semver" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a3/dd/64cfc980e35e658f769d7282172ac45cdeb75380a0fdecb188cb9ffd5cef/git_changelog-2.11.0.tar.gz", hash = "sha256:67595f2090c0f017faf5cb27feecfe6edb03f02b5f56d63101c2defc004475e6", size = 104544, upload-time = "2026-11-09T14:50:17.812Z" } +sdist = { url = "https://files.pythonhosted.org/packages/af/e1/c6cdc4556848c01bd71bcf0921e84264b5e0f7b1ec7d36d6cf2f71ad3f3e/git_changelog-2.12.0.tar.gz", hash = "sha256:260992739b342329b594fe8a6bd84fcb64630a567eccb5e17af2e4d7a18aa03b", size = 107705, upload-time = "2026-11-19T11:02:08.918Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5b/9c/4c105b6f311a16dbf72859db89be0f9ae05ac4df43e2716a3528eddf9a0a/git_changelog-2.11.0-py3-none-any.whl", hash = "sha256:8a42fd014d24604d1a5c4ce6b2dd88e21915c3bd4582c07754af3745d8859ecb", size = 45221, upload-time = "2026-11-09T14:49:01.54Z" }, + { url = "https://files.pythonhosted.org/packages/f3/ce/811e2d9e83348ce03a88e6041a3346f35f1f8c6239abc9f42c328a673b96/git_changelog-2.12.0-py3-none-any.whl", hash = "sha256:2596081b006b12002193a881be1b673dd27d7d1c9e37f56096ac7d392761b31e", size = 45877, upload-time = "2026-11-19T11:02:07.317Z" }, ] [[package]] @@ -536,7 +536,7 @@ wheels = [ [[package]] name = "mkdocs-material" -version = "9.8.1" +version = "9.8.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "babel" }, @@ -551,9 +551,9 @@ dependencies = [ { name = "pymdown-extensions" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e2/b2/dee93bf227b481e28ba4d800c322dffc41b16d524ae84ca8d85aa7ec3a81/mkdocs_material-9.8.1.tar.gz", hash = "sha256:cddae7d77bb98d1d347aa68ee252ab40926171a1b34ba8777c44e16de9629f00", size = 4160481, upload-time = "2026-11-07T13:05:04.482Z" } +sdist = { url = "https://files.pythonhosted.org/packages/99/bf/c47389fa622b513c2d115eb4c16075ef04a5f4d8156039f46cb26e5c70a9/mkdocs_material-9.8.2.tar.gz", hash = "sha256:005d942bdbfa22efa049f4818c31d42fb36bed6d362adb641dd7a2e948078f9d", size = 4160697, upload-time = "2026-11-19T19:52:25.799Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/70/05/a4011d6a6af86cd03059a5b165cd69a3695ef4bd7bd477c66befe399640a/mkdocs_material-9.8.1-py3-none-any.whl", hash = "sha256:2115af67ee680e1398bdd0ea02e517721e4bba88b342503a93f97ea8eb3de51c", size = 9302217, upload-time = "2026-11-07T13:05:00.747Z" }, + { url = "https://files.pythonhosted.org/packages/18/86/9204441dd9e224f1dc3f1a32edf6a474e84696bfa493c7df067dcde36366/mkdocs_material-9.8.2-py3-none-any.whl", hash = "sha256:ef1414cab33d64fcc13387e972af5ba4620f55f93482d1842933399ed2c69b02", size = 9302480, upload-time = "2026-11-19T19:52:22.436Z" }, ] [[package]] From 3100f3cbf5e003f946f2255a90735c52f2b944db Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Wed, 4 Nov 2026 11:18:12 -0500 Subject: [PATCH 45/47] feat(helpers): sync game data constants with client schema 0.41.2115745 Client 0.41.2115745 adds the Overcharge game data bit (2**52) and folds it into segment 4, so DataItems gains OVERCHARGE (aliases OVERCHARGE_DEFINITION, OVERCHARGE_STAT_GROUP, OVERCHARGE_POINT_MISSION_LOOKUP), Constants.get("Overcharge") resolves it, and SEGMENT4 / Constants.Segment4 move to the game's new 7881024469991424. The stat and enum tables gain UnitStat 62 (Critical Defense, UNIT_STAT_CRITICAL_DAMAGE_NEGATE), ItemType 36 OVERCHARGE_POINT and CurrencyType 51 ARENA_CURRENCY ("Arena Tokens"). Requires Comlink 4.6.0 or later, which accepts items up to 2**53 - 1. Earlier releases reject OVERCHARGE and the new SEGMENT4 with HTTP 400. Closes #216 Co-Authored-By: Claude Opus 5.5 --- docs/api/helpers.md | 8 +++++--- docs/migration.md | 18 ++++++++++++----- src/swgoh_comlink/helpers/_constants.py | 3 ++- src/swgoh_comlink/helpers/_data_items.py | 12 ++++++++---- src/swgoh_comlink/helpers/_stat_data.py | 17 ++++++++++++++-- tests/resources/enums-item-currency.json | 8 +++++--- tests/unit/test_helpers.py | 25 +++++++++++++++++++++--- 7 files changed, 70 insertions(+), 21 deletions(-) diff --git a/docs/api/helpers.md b/docs/api/helpers.md index 7b48679..9fe80b4 100644 --- a/docs/api/helpers.md +++ b/docs/api/helpers.md @@ -64,12 +64,14 @@ in about 2.4 seconds, versus about 147 MB in about 12.5 seconds for `ABILITY_DECISION_TREE`. Bitwise OR (`|`) is always safe. !!! note - Comlink accepts any `items` bitmask from 1 to 252 − 1, or `-1` + Comlink accepts any `items` bitmask from 1 to 253 − 1, or `-1` (`DataItems.ALL`) for everything, and rejects values outside that range with an - HTTP 400. Older Comlink releases had a bug in how CDN URLs were built that could + HTTP 400. `DataItems.OVERCHARGE` (252) and `DataItems.SEGMENT4`, which + includes it, need Comlink 4.6.0 or later; earlier releases accept only up to + 252 − 1. Older Comlink releases had a bug in how CDN URLs were built that could make some single-collection requests fail; upgrade Comlink if you see that. - On Python 3.15 and later, `int(DataItems.ALL)` is 252 − 1 rather than + On Python 3.15 and later, `int(DataItems.ALL)` is 253 − 1 rather than `-1`, because `enum` now turns a negative flag value into the union of every defined bit. The client still sends `-1` for `DataItems.ALL` and `items="ALL"`. diff --git a/docs/migration.md b/docs/migration.md index f059e87..888700a 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -284,7 +284,7 @@ in your own code (rather than referencing the constants by name), update them: | Constant | Old value | New value | |----------|-----------|-----------| | `DataItems.SEGMENT2` / `Constants.Segment2` | `68717379584` | `1125968624222208` | -| `DataItems.SEGMENT4` / `Constants.Segment4` | `281200098803712` | `3377424842620928` | +| `DataItems.SEGMENT4` / `Constants.Segment4` | `281200098803712` | `7881024469991424` | `SEGMENT1` (`2097151`) and `SEGMENT3` (`206158430208`) are unchanged. @@ -292,8 +292,8 @@ Code that references the constant by name (`DataItems.SEGMENT2`, `Constants.Segm `Constants.get("Segment2")`) picks up the new values automatically. **`get_game_data(items=...)` accepts any in-range bitmask.** Comlink accepts any -`items` value from 1 to 252 − 1, or `-1` (`DataItems.ALL`; the client sends -`-1` for it even on Python 3.15+, where `int(DataItems.ALL)` is 252 − 1) for everything, +`items` value from 1 to 253 − 1, or `-1` (`DataItems.ALL`; the client sends +`-1` for it even on Python 3.15+, where `int(DataItems.ALL)` is 253 − 1) for everything, so single collections (e.g. `DataItems.UNITS`), custom combinations and the `SEGMENT1`–`SEGMENT4` aggregates all work. Out-of-range values are rejected with an HTTP 400. Earlier versions of this guide advised against single-collection values; @@ -362,6 +362,14 @@ Upgrading from v2.8 to v2.9. rebuilt table is a copy: call `set_game_data` again after changing it. The same applies to a unit's `skills` list, which `set_game_data` indexes by skill id, and to `gpTables["modRarityLevelTierGP"]`, which it indexes by pips, level and tier. +- **`DataItems.OVERCHARGE` and a wider `SEGMENT4` need Comlink 4.6.0 or later.** Game + client 0.41 added the `Overcharge` bit (252). `DataItems.OVERCHARGE` requests + `overchargeDefinition`, `overchargeStatGroup` and `overchargePointMissionLookup` (each also + available under its own alias, e.g. `DataItems.OVERCHARGE_STAT_GROUP`), and + `Constants.get("Overcharge")` resolves it. The game folded the bit into segment 4, so + `DataItems.SEGMENT4` / `Constants.Segment4` changes from `3377424842620928` to + `7881024469991424`, and `items` accepts 1 to 253 − 1. A Comlink release + older than 4.6.0 rejects both values with an HTTP 400. ## Summary of changes @@ -382,5 +390,5 @@ Upgrading from v2.8 to v2.9. | GAC bracket scanning | Linear O(n) | Exponential probe + binary search O(log n) | | Migration checker | Not available | `swgoh-migrate` CLI / `python -m swgoh_comlink.migrate` | | `DataItems.SEGMENT2` value | `68717379584` | `1125968624222208` (server-aligned) | -| `DataItems.SEGMENT4` value | `281200098803712` | `3377424842620928` (server-aligned) | -| `get_game_data(items=)` values | Any bitmask | Any bitmask from 1 to 252 − 1, or `-1`; out of range → HTTP 400 | +| `DataItems.SEGMENT4` value | `281200098803712` | `7881024469991424` (server-aligned) | +| `get_game_data(items=)` values | Any bitmask | Any bitmask from 1 to 253 − 1, or `-1` | diff --git a/src/swgoh_comlink/helpers/_constants.py b/src/swgoh_comlink/helpers/_constants.py index 4f5b0af..0dd6453 100644 --- a/src/swgoh_comlink/helpers/_constants.py +++ b/src/swgoh_comlink/helpers/_constants.py @@ -84,6 +84,7 @@ "EpisodeDefinition": "EPISODE_DEFINITION", "EpisodeDefinitions": "EPISODE_DEFINITION", "EraDefinitions": "ERA_DEFINITION", + "Overcharge": "OVERCHARGE", "LinkingReward": "LINKING_REWARD", "AccountLinking": "LINKING_REWARD", } @@ -141,7 +142,7 @@ class Constants: Segment1 = 2097151 Segment2 = 1125968624222208 Segment3 = 206158430208 - Segment4 = 3377424842620928 + Segment4 = 7881024469991424 # Proxied stat data from _stat_data (backward compat) STAT_ENUMS = STAT_ENUMS diff --git a/src/swgoh_comlink/helpers/_data_items.py b/src/swgoh_comlink/helpers/_data_items.py index ec0bbb6..05eb9e2 100644 --- a/src/swgoh_comlink/helpers/_data_items.py +++ b/src/swgoh_comlink/helpers/_data_items.py @@ -27,10 +27,10 @@ class DataItems(IntFlag): `DataItems.CONQUEST_DEFINITION + DataItems.ARTIFACT_DEFINITION` requests `ABILITY_DECISION_TREE`, while `DataItems.CONQUEST_DEFINITION | DataItems.ARTIFACT_DEFINITION` correctly requests `CONQUEST`. - Comlink accepts any bitmask from 1 to 2**52 - 1, or -1 (`DataItems.ALL`) for everything. Values outside - that range are rejected with an HTTP 400. + Every collection bit lies below 2**53, so any combination of members is a bitmask from 1 to 2**53 - 1. + Use -1 (`DataItems.ALL`) for everything. - On Python 3.15 and later, `int(DataItems.ALL)` is 2**52 - 1 rather than -1, because `enum` now turns a + On Python 3.15 and later, `int(DataItems.ALL)` is 2**53 - 1 rather than -1, because `enum` now turns a negative flag value into the union of every defined bit. The client still sends -1 for `DataItems.ALL`. Some of the DataItems members are actually aliases for other members. For example, the `TABLE` member is an @@ -133,11 +133,15 @@ class DataItems(IntFlag): LINKING_REWARD = 562949953421312 LIGHTSPEED_TOKEN = 1125899906842624 ERA_DEFINITION = 2251799813685248 + OVERCHARGE = 4503599627370496 + OVERCHARGE_DEFINITION = OVERCHARGE + OVERCHARGE_STAT_GROUP = OVERCHARGE + OVERCHARGE_POINT_MISSION_LOOKUP = OVERCHARGE SEGMENT1 = 2097151 SEGMENT2 = 1125968624222208 SEGMENT3 = RELIC_TIER_DEFINITION + UNITS - SEGMENT4 = 3377424842620928 + SEGMENT4 = 7881024469991424 @classmethod def members(cls) -> KeysView[str]: diff --git a/src/swgoh_comlink/helpers/_stat_data.py b/src/swgoh_comlink/helpers/_stat_data.py index 46f4b3f..d54fcc3 100644 --- a/src/swgoh_comlink/helpers/_stat_data.py +++ b/src/swgoh_comlink/helpers/_stat_data.py @@ -637,6 +637,16 @@ "enum": "UNITSTATMASTERY", "tableKey": "MASTERY", }, + "62": { + "statId": 62, + "nameKey": "UNIT_STAT_CRITICAL_DAMAGE_NEGATE", + "descKey": "UNIT_STAT_DESCRIPTION_CRITICAL_DAMAGE_NEGATE", + "isDecimal": True, + "name": "Critical Defense", + "detailedName": "Critical Damage Negate", + "enum": "UNITSTATCRITICALDAMAGENEGATE", + "tableKey": "CRITICAL_DAMAGE_NEGATE", + }, } # --------------------------------------------------------------------------- @@ -756,10 +766,11 @@ 33: "EPISODE_PASS_PLUS", 34: "LIGHTSPEED_TOKEN", 35: "LOANED_UNIT_ERA_LEVEL_INCREASE", + 36: "OVERCHARGE_POINT", } """``ItemType`` number to enum member name: the ``type`` of a reward, preview or inventory item. -A snapshot of ``get_enums()["ItemType"]`` at game data 0.40.6, without ``ItemType_DEFAULT``. The game adds +A snapshot of ``get_enums()["ItemType"]`` at client schema 0.41.2115745, without ``ItemType_DEFAULT``. The game adds members over time: pass the live ``get_enums()`` response to :class:`ItemNames` to read the current table. """ @@ -811,13 +822,14 @@ 48: "EPISODE_CURRENCY", 49: "ERA_CURRENCY", 50: "ERA_UPGRADE_CURRENCY", + 51: "ARENA_CURRENCY", } """``CurrencyType`` number to enum member name. An inventory's ``currencyItem[].currency`` carries the number; a reward of ``ItemType`` ``CURRENCY`` carries the member name as its ``id``. -A snapshot of ``get_enums()["CurrencyType"]`` at game data 0.40.6, without ``CurrencyType_DEFAULT``. The +A snapshot of ``get_enums()["CurrencyType"]`` at client schema 0.41.2115745, without ``CurrencyType_DEFAULT``. The game adds currencies over time: pass the live ``get_enums()`` response to :class:`ItemNames` to read the current table. """ @@ -875,6 +887,7 @@ "EPISODE_CURRENCY": "Episode Currency", "ERA_CURRENCY": "Era Currency", "ERA_UPGRADE_CURRENCY": "Era Level Currency", + "ARENA_CURRENCY": "Arena Tokens", } """``CurrencyType`` member name to its English display name (see ``CURRENCY_TYPES``). diff --git a/tests/resources/enums-item-currency.json b/tests/resources/enums-item-currency.json index 744d1bf..29d0f15 100644 --- a/tests/resources/enums-item-currency.json +++ b/tests/resources/enums-item-currency.json @@ -1,5 +1,5 @@ { - "_comment": "Excerpt of get_enums() at game data 0.40.6: the groups ITEM_TYPES and CURRENCY_TYPES snapshot.", + "_comment": "Excerpt of get_enums() at client schema 0.41.2115745: the groups ITEM_TYPES and CURRENCY_TYPES snapshot.", "ItemType": { "ItemType_DEFAULT": 0, "EMPTY": 1, @@ -33,7 +33,8 @@ "EPISODE_PASS": 32, "EPISODE_PASS_PLUS": 33, "LIGHTSPEED_TOKEN": 34, - "LOANED_UNIT_ERA_LEVEL_INCREASE": 35 + "LOANED_UNIT_ERA_LEVEL_INCREASE": 35, + "OVERCHARGE_POINT": 36 }, "CurrencyType": { "CurrencyType_DEFAULT": 0, @@ -83,6 +84,7 @@ "GL_EVENT_CURRENCY": 47, "EPISODE_CURRENCY": 48, "ERA_CURRENCY": 49, - "ERA_UPGRADE_CURRENCY": 50 + "ERA_UPGRADE_CURRENCY": 50, + "ARENA_CURRENCY": 51 } } diff --git a/tests/unit/test_helpers.py b/tests/unit/test_helpers.py index 552e899..24dd570 100644 --- a/tests/unit/test_helpers.py +++ b/tests/unit/test_helpers.py @@ -2261,7 +2261,7 @@ def test_invalid_input_raises(self, args: tuple[Any, ...], match: str): def _recorded_enums() -> dict[str, Any]: - """The ItemType and CurrencyType groups of a real get_enums() response (game data 0.40.6).""" + """The ItemType and CurrencyType groups of a real get_enums() response (client schema 0.41.2115745).""" return json.loads((_RESOURCES / "enums-item-currency.json").read_text()) @@ -3321,13 +3321,15 @@ class TestConstants: ("name", "expected"), [ pytest.param("Segment1", str(Constants.Segment1), id="own-attribute"), - # Sent as -1 even on Python 3.15+, where int(DataItems.ALL) is 2**52 - 1. + # Sent as -1 even on Python 3.15+, where int(DataItems.ALL) is 2**53 - 1. pytest.param("ALL", "-1", id="all"), pytest.param("UnitDefinitions", "137438953472", id="legacy-name"), # 2**37, DataItems.UNITS pytest.param("UNITS", "137438953472", id="data-items-name"), # Aligned with the live GameDataItemsEnum from get_enums(). pytest.param("AbilityDecisionTrees", "1099511627776", id="ability-decision-trees"), pytest.param("EraDefinitions", "2251799813685248", id="era-definitions"), + pytest.param("Overcharge", "4503599627370496", id="overcharge"), # 2**52, client 0.41.2115745 + pytest.param("Segment4", "7881024469991424", id="segment4-includes-overcharge"), pytest.param("UBSUpdate", "2150109456", id="ubs-update"), pytest.param("EpisodeDefinitions", "281474976710656", id="episode-definitions-plural"), pytest.param("AccountLinking", "562949953421312", id="account-linking-alias"), @@ -3351,13 +3353,30 @@ def test_segment_values_match_server(self): 2097151, 1125968624222208, 206158430208, - 3377424842620928, + 7881024469991424, ) + assert DataItems.SEGMENT4 == 3377424842620928 | DataItems.OVERCHARGE def test_dataitems_members_present(self): assert DataItems.ABILITY_DECISION_TREE.value == 1099511627776 assert DataItems.ERA_DEFINITION.value == 2251799813685248 assert DataItems.UBS_UPDATE.value == 2150109456 + assert DataItems.OVERCHARGE.value == 4503599627370496 + + @pytest.mark.parametrize( + "alias", ["OVERCHARGE_DEFINITION", "OVERCHARGE_STAT_GROUP", "OVERCHARGE_POINT_MISSION_LOOKUP"] + ) + def test_overcharge_collections_share_one_bit(self, alias): + assert DataItems[alias] is DataItems.OVERCHARGE + + def test_critical_damage_negate_stat(self): + # UnitStat 62 arrived with client schema 0.41.2115745; the keys are the localization bundle's. + assert Constants.UNIT_STAT_ENUMS_MAP["62"] == { + "enum": "UNITSTATCRITICALDAMAGENEGATE", + "nameKey": "UNIT_STAT_CRITICAL_DAMAGE_NEGATE", + "tableKey": "CRITICAL_DAMAGE_NEGATE", + } + assert Constants.STATS["62"]["name"] == "Critical Defense" # ── _decorators ───────────────────────────────────────────────────────── From 7c4f01e7f5a8ebb6358fe16e3962b312a5c74ab1 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 23 Nov 2026 09:14:35 -0500 Subject: [PATCH 46/47] test(hmac): assert the plain-HTTP warning argument exactly The two-URL case checked each host with a substring test on the log message. CodeQL reads `"" in message` as incomplete URL sanitisation (py/incomplete-url-substring-sanitization) and raised two high alerts. Compare the record's formatting argument instead, which is also stricter: it pins both URLs and their order. Use a neutral non-loopback host name in the parametrised cases. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_hmac_plain_http.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_hmac_plain_http.py b/tests/unit/test_hmac_plain_http.py index 2d708e5..c370d54 100644 --- a/tests/unit/test_hmac_plain_http.py +++ b/tests/unit/test_hmac_plain_http.py @@ -41,7 +41,7 @@ def _plain_http_warnings( {"url": "http://[2001:db8::1]:3000"}, {"url": "http://128.0.0.1:3000"}, {"url": "http://localhost.example.com:3000"}, - {"host": "comlink.lab"}, + {"host": "comlink.internal"}, {"url": "https://comlink.example.com", "stats_url": "http://stats.example.com:3223"}, ], ids=lambda kwargs: next(iter(kwargs.values())), @@ -65,8 +65,7 @@ def test_one_warning_when_both_urls_are_remote( 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() + assert records[0].args == ("http://comlink.example.com:3000 and http://stats.example.com:3223",) def test_each_client_warns_once(make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture) -> None: From 11802b5e92a6706097c4552b71a690034308a6e5 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:16:51 +0000 Subject: [PATCH 47/47] chore(changelog): update for v2.9.0 --- .github/release-pr/v2.9.0.md | 78 ++++++++++++++++++++++++++++++++++++ CHANGELOG.md | 52 ++++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 .github/release-pr/v2.9.0.md diff --git a/.github/release-pr/v2.9.0.md b/.github/release-pr/v2.9.0.md new file mode 100644 index 0000000..dc643e3 --- /dev/null +++ b/.github/release-pr/v2.9.0.md @@ -0,0 +1,78 @@ +Automated release prep for **v2.9.0**. CHANGELOG.md regenerated via git-changelog. + +Merging promotes `develop` -> `main` with the changelog already in place. +Afterwards, run the **release** workflow on `main` to build, publish, and tag v2.9.0. + +### Issues resolved by this release + +Merging this PR into `main` closes: + +- Closes #216 (via #273) +- Closes #234 (via #250) +- Closes #235 (via #258) +- Closes #236 (via #258) +- Closes #237 (via #258) +- Closes #238 (via #249) +- Closes #239 (via #249) +- Closes #240 (via #258) +- Closes #241 (via #258) +- Closes #242 (via #257) +- Closes #243 (via #251) +- Closes #244 (via #251) +- Closes #245 (via #252) +- Closes #246 (via #258) +- Closes #248 (via #259) + +--- + + + +## [v2.9.0](https://github.com/swgoh-utils/comlink-python/compare/v2.8.0...v2.9.0) (2026-11-23) + +### Features + +- **client:** add strip_empty option to get_game_data ([3b63a7a](https://github.com/swgoh-utils/comlink-python/commit/3b63a7a73aed527f052c59e1e9f2bd7f14785c58)) +- **helpers:** add get_omicron_breakdown for guild-wide omicron adoption ([ff158cd](https://github.com/swgoh-utils/comlink-python/commit/ff158cd4891acda6823387e4bee925d1c6503c85)) +- **statcalc:** apply a named datacron's stat affixes to characters ([d79193a](https://github.com/swgoh-utils/comlink-python/commit/d79193a90341acfffc9a687b715003726d9d21dd)) +- **client:** add opt-in max_response_bytes and max_game_data_bytes limits ([81623d0](https://github.com/swgoh-utils/comlink-python/commit/81623d0d573e1a0e6f2c0c1463d129e9a2c632b2)) +- **helpers:** sync game data constants with client schema 0.41.2115745 ([3100f3c](https://github.com/swgoh-utils/comlink-python/commit/3100f3cbf5e003f946f2255a90735c52f2b944db)) +- **helpers:** accept type-prefixed enum names in guild roles and item names ([4f7e96e](https://github.com/swgoh-utils/comlink-python/commit/4f7e96e23227d092ab8bdb1118ce227e1bb667f8)) + +### Bug Fixes + +- **helpers:** accept tier 0 in is_omicron_skill ([07bffd6](https://github.com/swgoh-utils/comlink-python/commit/07bffd6a960cf0a1afc6623bbbbf33997a2d553a)) +- **client:** attribute the credential deprecation warning past in-package subclasses ([374541a](https://github.com/swgoh-utils/comlink-python/commit/374541ad5d564a931e3e589973346b107426618c)) +- **async:** give back the pacing slot on any exception while sleeping ([a23b611](https://github.com/swgoh-utils/comlink-python/commit/a23b611f717189780968babc0971b077c5d5cfbe)) +- **examples:** skip comment lines when decoding language bundles ([18bd2ee](https://github.com/swgoh-utils/comlink-python/commit/18bd2ee95d80c9f57e10ae67b1a147b243adaa25)) +- **async:** use httpx default keep-alive and add a limits argument ([8b51989](https://github.com/swgoh-utils/comlink-python/commit/8b51989b02639d8005788be4c71d884eba2ca433)) +- **statcalc:** cap and optionally verify the game data download ([06b0227](https://github.com/swgoh-utils/comlink-python/commit/06b02274e91de2ff09851fad83e7e43e63385324)) +- **hmac:** warn when HMAC is used over plain HTTP to a non-loopback host ([7288a1f](https://github.com/swgoh-utils/comlink-python/commit/7288a1f7ed71500c6040f34e212c89c7a4ae1d75)) +- **client:** read HMAC keys from COMLINK_ACCESS_KEY and COMLINK_SECRET_KEY ([63ed346](https://github.com/swgoh-utils/comlink-python/commit/63ed3460ab1fa88ef861f8088bcad99350e75653)) +- **core:** replace runtime asserts and raw KeyErrors with library errors ([0467afe](https://github.com/swgoh-utils/comlink-python/commit/0467afe9c11329ced8b34483bb7c86314dbb6abc)) +- **core:** validate and URL-encode the get_unit_stats language parameter ([1672812](https://github.com/swgoh-utils/comlink-python/commit/16728120e8a440a2d5b08f33e1c90d345c9b6275)) +- **exceptions:** truncate response bodies in HTTP error messages ([4ec7597](https://github.com/swgoh-utils/comlink-python/commit/4ec7597e5aa32b7e67014349f6c255f3dd721417)) + +### Code Refactoring + +- **core:** generate the sync client from the async client ([921148b](https://github.com/swgoh-utils/comlink-python/commit/921148b6c64ebb836059753df00a9830e2715b25)) +- **core:** move request preparation and retry decisions into a sans-I/O core ([07b3db2](https://github.com/swgoh-utils/comlink-python/commit/07b3db2226b7d0f72d89161369fa25afe3797677)) + +### Performance Improvements + +- **statcalc:** build renamed stat dicts with a comprehension ([ccc3198](https://github.com/swgoh-utils/comlink-python/commit/ccc3198142f361c656274622a25d52e26adfc5dc)) +- **statcalc:** index mod GP by int (pips, level, tier) in set_game_data ([17d35de](https://github.com/swgoh-utils/comlink-python/commit/17d35deb528bafde93e1311ff1acc0f90a5330ae)) +- **statcalc:** key the summed raw mod stats by int stat id ([e02f7fb](https://github.com/swgoh-utils/comlink-python/commit/e02f7fbb9c4006e43f7d7e401d2dd7c3a9b95770)) +- **statcalc:** run all percent conversions in one _convert_percent call ([1f81a80](https://github.com/swgoh-utils/comlink-python/commit/1f81a805f2a8e19ee99152db3a5e7cf03bc674cc)) +- **statcalc:** fold final stat ids by lookup and loop the percent conversions ([d8b5b07](https://github.com/swgoh-utils/comlink-python/commit/d8b5b07b7d902654d7e716cdf12f1efc631f61fa)) +- **statcalc:** map mod stat ids to their target stats with lookup tables ([1a71544](https://github.com/swgoh-utils/comlink-python/commit/1a715447ecfc18ba4774e3dcf7b0d98240447c0c)) +- **statcalc:** drop key-list copies and probing lookups in _format_stats ([ae35c6d](https://github.com/swgoh-utils/comlink-python/commit/ae35c6db0f05c98c61ffdfa672fcdbaa0f33e87e)) +- **statcalc:** index each unit's skills by id in set_game_data ([d228fa1](https://github.com/swgoh-utils/comlink-python/commit/d228fa110e7854cb138f4adba0e752f606ddf16b)) +- **statcalc:** copy normalized units shallowly instead of deep-copying ([0190952](https://github.com/swgoh-utils/comlink-python/commit/0190952e5a5f10ad559109063b8af556367b2359)) +- **statcalc:** normalise game data tables to str keys once ([3648460](https://github.com/swgoh-utils/comlink-python/commit/36484609918590e828f5354e0045df4594f59d63)) +- **statcalc:** run StatCalcAsync calculations off the event loop ([3201dbe](https://github.com/swgoh-utils/comlink-python/commit/3201dbee7322ad981dd334a145d5a105dbd10242)) + +### Docs + +- **examples:** add guild omicron breakdown examples ([0c3bf6a](https://github.com/swgoh-utils/comlink-python/commit/0c3bf6ad5dae0b1f58914d136fade3f74627b966)) +- **examples:** add sync and async datacron calculation examples ([c213f68](https://github.com/swgoh-utils/comlink-python/commit/c213f68a248b9b540b3eaffa545914f4d2dd8f5d)) +- **migration:** note that set_game_data indexes the mod GP table ([24684ea](https://github.com/swgoh-utils/comlink-python/commit/24684ea7a1d90fba62367aadefbae0aace4d3225)) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01186f0..9187de4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,58 @@ # CHANGELOG + + +## [v2.9.0](https://github.com/swgoh-utils/comlink-python/compare/v2.8.0...v2.9.0) (2026-11-23) + +### Features + +- **client:** add strip_empty option to get_game_data ([3b63a7a](https://github.com/swgoh-utils/comlink-python/commit/3b63a7a73aed527f052c59e1e9f2bd7f14785c58)) +- **helpers:** add get_omicron_breakdown for guild-wide omicron adoption ([ff158cd](https://github.com/swgoh-utils/comlink-python/commit/ff158cd4891acda6823387e4bee925d1c6503c85)) +- **statcalc:** apply a named datacron's stat affixes to characters ([d79193a](https://github.com/swgoh-utils/comlink-python/commit/d79193a90341acfffc9a687b715003726d9d21dd)) +- **client:** add opt-in max_response_bytes and max_game_data_bytes limits ([81623d0](https://github.com/swgoh-utils/comlink-python/commit/81623d0d573e1a0e6f2c0c1463d129e9a2c632b2)) +- **helpers:** sync game data constants with client schema 0.41.2115745 ([3100f3c](https://github.com/swgoh-utils/comlink-python/commit/3100f3cbf5e003f946f2255a90735c52f2b944db)) +- **helpers:** accept type-prefixed enum names in guild roles and item names ([4f7e96e](https://github.com/swgoh-utils/comlink-python/commit/4f7e96e23227d092ab8bdb1118ce227e1bb667f8)) + +### Bug Fixes + +- **helpers:** accept tier 0 in is_omicron_skill ([07bffd6](https://github.com/swgoh-utils/comlink-python/commit/07bffd6a960cf0a1afc6623bbbbf33997a2d553a)) +- **client:** attribute the credential deprecation warning past in-package subclasses ([374541a](https://github.com/swgoh-utils/comlink-python/commit/374541ad5d564a931e3e589973346b107426618c)) +- **async:** give back the pacing slot on any exception while sleeping ([a23b611](https://github.com/swgoh-utils/comlink-python/commit/a23b611f717189780968babc0971b077c5d5cfbe)) +- **examples:** skip comment lines when decoding language bundles ([18bd2ee](https://github.com/swgoh-utils/comlink-python/commit/18bd2ee95d80c9f57e10ae67b1a147b243adaa25)) +- **async:** use httpx default keep-alive and add a limits argument ([8b51989](https://github.com/swgoh-utils/comlink-python/commit/8b51989b02639d8005788be4c71d884eba2ca433)) +- **statcalc:** cap and optionally verify the game data download ([06b0227](https://github.com/swgoh-utils/comlink-python/commit/06b02274e91de2ff09851fad83e7e43e63385324)) +- **hmac:** warn when HMAC is used over plain HTTP to a non-loopback host ([7288a1f](https://github.com/swgoh-utils/comlink-python/commit/7288a1f7ed71500c6040f34e212c89c7a4ae1d75)) +- **client:** read HMAC keys from COMLINK_ACCESS_KEY and COMLINK_SECRET_KEY ([63ed346](https://github.com/swgoh-utils/comlink-python/commit/63ed3460ab1fa88ef861f8088bcad99350e75653)) +- **core:** replace runtime asserts and raw KeyErrors with library errors ([0467afe](https://github.com/swgoh-utils/comlink-python/commit/0467afe9c11329ced8b34483bb7c86314dbb6abc)) +- **core:** validate and URL-encode the get_unit_stats language parameter ([1672812](https://github.com/swgoh-utils/comlink-python/commit/16728120e8a440a2d5b08f33e1c90d345c9b6275)) +- **exceptions:** truncate response bodies in HTTP error messages ([4ec7597](https://github.com/swgoh-utils/comlink-python/commit/4ec7597e5aa32b7e67014349f6c255f3dd721417)) + +### Code Refactoring + +- **core:** generate the sync client from the async client ([921148b](https://github.com/swgoh-utils/comlink-python/commit/921148b6c64ebb836059753df00a9830e2715b25)) +- **core:** move request preparation and retry decisions into a sans-I/O core ([07b3db2](https://github.com/swgoh-utils/comlink-python/commit/07b3db2226b7d0f72d89161369fa25afe3797677)) + +### Performance Improvements + +- **statcalc:** build renamed stat dicts with a comprehension ([ccc3198](https://github.com/swgoh-utils/comlink-python/commit/ccc3198142f361c656274622a25d52e26adfc5dc)) +- **statcalc:** index mod GP by int (pips, level, tier) in set_game_data ([17d35de](https://github.com/swgoh-utils/comlink-python/commit/17d35deb528bafde93e1311ff1acc0f90a5330ae)) +- **statcalc:** key the summed raw mod stats by int stat id ([e02f7fb](https://github.com/swgoh-utils/comlink-python/commit/e02f7fbb9c4006e43f7d7e401d2dd7c3a9b95770)) +- **statcalc:** run all percent conversions in one _convert_percent call ([1f81a80](https://github.com/swgoh-utils/comlink-python/commit/1f81a805f2a8e19ee99152db3a5e7cf03bc674cc)) +- **statcalc:** fold final stat ids by lookup and loop the percent conversions ([d8b5b07](https://github.com/swgoh-utils/comlink-python/commit/d8b5b07b7d902654d7e716cdf12f1efc631f61fa)) +- **statcalc:** map mod stat ids to their target stats with lookup tables ([1a71544](https://github.com/swgoh-utils/comlink-python/commit/1a715447ecfc18ba4774e3dcf7b0d98240447c0c)) +- **statcalc:** drop key-list copies and probing lookups in _format_stats ([ae35c6d](https://github.com/swgoh-utils/comlink-python/commit/ae35c6db0f05c98c61ffdfa672fcdbaa0f33e87e)) +- **statcalc:** index each unit's skills by id in set_game_data ([d228fa1](https://github.com/swgoh-utils/comlink-python/commit/d228fa110e7854cb138f4adba0e752f606ddf16b)) +- **statcalc:** copy normalized units shallowly instead of deep-copying ([0190952](https://github.com/swgoh-utils/comlink-python/commit/0190952e5a5f10ad559109063b8af556367b2359)) +- **statcalc:** normalise game data tables to str keys once ([3648460](https://github.com/swgoh-utils/comlink-python/commit/36484609918590e828f5354e0045df4594f59d63)) +- **statcalc:** run StatCalcAsync calculations off the event loop ([3201dbe](https://github.com/swgoh-utils/comlink-python/commit/3201dbee7322ad981dd334a145d5a105dbd10242)) + +### Docs + +- **examples:** add guild omicron breakdown examples ([0c3bf6a](https://github.com/swgoh-utils/comlink-python/commit/0c3bf6ad5dae0b1f58914d136fade3f74627b966)) +- **examples:** add sync and async datacron calculation examples ([c213f68](https://github.com/swgoh-utils/comlink-python/commit/c213f68a248b9b540b3eaffa545914f4d2dd8f5d)) +- **migration:** note that set_game_data indexes the mod GP table ([24684ea](https://github.com/swgoh-utils/comlink-python/commit/24684ea7a1d90fba62367aadefbae0aace4d3225)) + ## [v2.8.0](https://github.com/swgoh-utils/comlink-python/compare/v2.7.0...v2.8.0) (2026-11-05)