From a23b611f717189780968babc0971b077c5d5cfbe Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Sat, 7 Nov 2026 15:10:48 -0500 Subject: [PATCH 1/4] 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 2/4] 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 3/4] 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 4/4] 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