Skip to content

refactor(core): move request preparation and retry decisions into a sans-I/O core - #258

Merged
MarTrepodi merged 9 commits into
developfrom
refactor/sans-io-retry
Nov 7, 2026
Merged

MarTrepodi merged 9 commits into
developfrom
refactor/sans-io-retry

Conversation

@MarTrepodi

@MarTrepodi MarTrepodi commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Merge note. #253, #254, #255 and #256 conflict with develop on their own once #249 merged, because they don't contain it. This PR already merges #249 into that stack and passed CI as a whole, so it lands all of them together, and GitHub marks those four PRs as merged. Their closing keywords are repeated here so the issue bookkeeping (.github/tools/closing_issues.py) still sees them:

Closes #235
Closes #236
Closes #237
Closes #240
Closes #241

Stacked PR. Depends on #256 (fix/keepalive-parity), #249 (fix/error-body-truncation); merge those first. Until then this diff also shows the parent commits. To review only this PR's changes: fix/keepalive-parity...refactor/sans-io-retry.

Task: REF-1 phase 1 (v2.9 hardening plan, PR 10)
Branch: refactor/sans-io-retry
Stacked on: fix/keepalive-parity (PRs 2, 3, 5, 6), with fix/error-body-truncation (PR 4) merged in. Review after those land, or retarget once they are on develop.

Closes #246

Design note

Problem. SwgohComlink._request and SwgohComlinkAsync._request each held the whole retry and pacing loop: reserving a pacing slot, adding the carried retry wait, sleeping, re-checking a rate hold that was extended during the sleep, requeueing, sending, asking the policy for a delay, logging, holding the endpoint, adding jitter, and counting attempts. _send duplicated request building and response decoding as well. These are the parts most likely to drift between the two copies, and they already had (keep-alive limits, docstrings).

Split. Everything that decides what happens moves out of the clients and does no I/O. Only sending, sleeping and cancellation stay in each client.

Piece Where What it does I/O
_retry_step(policy, error, attempt) retry.py Returns _RetryStep(delay, hold) or None to give up. hold is set for rate refusals. none
_Admission retry.py Admits one attempt. Reserves the slot and adds the carried wait to the first slot only. next_wait() returns each wait to sleep, re-checks the hold after every wait, and requeues if the hold now ends later. Returns None once the caller may send. abandon() gives the slot back. none (reads retry._clock)
_prepare_request(...) _base.py Uppercases the method, serializes the body once, builds HMAC headers for each attempt, sets the timeout and picks the size limit. Returns a _PreparedRequest, whose stats field chooses stats_client or client. none
_interpret_response(response, content) _base.py Turns a response into the decoded dict/list, or raises the typed SwgohComlinkHTTPError (cause HTTPStatusError) or SwgohComlinkDecodeError (cause JSONDecodeError/UnicodeDecodeError). none
_admission(...), _retry_wait(...) _base.py Bind the pacer to an endpoint. _retry_wait logs, applies the hold, adds jitter and returns the wait to carry into the next attempt, or None to re-raise. none

What each client keeps (identical apart from await and the cancellation rule):

attempt, extra = 1, 0.0
while True:
    self._admit(endpoint, stats, extra)          # sleep loop over _Admission.next_wait()
    try:
        return self._send(method, endpoint, payload, stats, timeout)   # prepare → transport → interpret
    except SwgohComlinkHTTPError as exc:
        extra = self._retry_wait(exc, attempt, endpoint, stats)
        if extra is None:
            raise
        attempt += 1

_request is 28 lines in both clients, including its signature and docstring. _send and _receive_limited keep only the transport call and the streaming read.

Cancellation is unchanged and now documented in each client's _admit:

  • Sync: any exception raised while sleeping in the pacing loop gives the reserved slot back before it propagates. This uses except BaseException, so it includes KeyboardInterrupt. A new test covers it.
  • Async: only asyncio.CancelledError gives the slot back, as before. test_rate_hold_admission.py covers it.

Things kept on purpose:

  • Order of side effects: reserve, then sleep, then hold check, then send. On failure: policy, then log, then hold, then jitter draw.
  • Clock, sleep and random still go through retry._clock, _sleep, _async_sleep and _random, read at call time, so the existing monkeypatch seams still work.
  • Log records keep the client module logger names (swgoh_comlink.swgoh_comlink / swgoh_comlink.swgoh_comlink_async). A private _log class attribute does this.
  • __cause__ chains are unchanged.
  • The private names _post, _get_game_version, _send, _pace_delay, _pace_slot, _hold_changed and _hold_endpoint are unchanged.

Not done here: generating the sync client (phase 2, unasync or a script). That is deferred. No codegen and no new dependency. Transport errors are still not retried.

Auth branch impact (dry run). git merge-tree auth refactor/sans-io-retry adds only import-line conflicts on top of the conflicts the stacked PRs 2–6 already cause: json/typing imports in both clients and in _base.py. Auth has no _request changes and no name collisions with the new private names.

What changed

  • src/swgoh_comlink/retry.py: adds _RetryStep, _retry_step and _Admission.
  • src/swgoh_comlink/_base.py: adds _PreparedRequest, _prepare_request, _interpret_response, _admission, _retry_wait and the _log class attribute.
  • src/swgoh_comlink/swgoh_comlink.py and swgoh_comlink_async.py: _request is now the short loop above. The new _admit holds the runtime's sleep and cancellation handling. _send is now prepare, then transport, then interpret. _receive_limited takes the _PreparedRequest and returns (response, body) instead of raising from inside the stream (it is private and no tests used it). Unused imports are removed.
  • CONTRIBUTING.md: the module table describes the sans-I/O core.
  • New tests:
    • tests/unit/test_client_parity.py: API parity and the _request guard.
    • tests/unit/test_retry_core.py: 22 tests of the core with no network, plus the sync interrupt test.
  • Merge of fix/error-body-truncation. There were conflicts in docs/migration.md, _base.py and both clients' imports. Both sides were purely additive, so both were kept: PR 4's v2.9 migration entries follow PRs 2–6's, and _lookup_name follows _bounded_error_response.

Acceptance

  • _request in each client is under 40 lines and makes no retry decisions. Both are 28 lines. test_request_is_a_short_loop_without_retry_decisions[sync|async] checks the line count with inspect.getsource. It also checks that the source mentions none of retry_policy, retry_delay, jitter, _hold_endpoint, _hold_changed or _pace_slot. Both cases failed before the refactor.

  • test_retry.py, test_retry_mocked.py, test_rate_hold_admission.py and test_pacer_scaling.py pass unchanged. git diff 9cc3760 -- <those four files> is empty, and all four pass.

  • The method-signature parity test passes. test_client_parity.py checks three things for every public callable on SwgohComlinkAsync, aliases included (40 names):

    • The same name exists on SwgohComlink. The only mapping is aclose → close.
    • It has the same inspect.signature.
    • An alias points at the same function name.

    It also checks that the two sets of public names are equal and that client-defined methods are coroutines only in the async client (looking through param_alias).

Verification:

  • uv run ruff check src/ tests/ examples/ parity/: passed
  • uv run ruff format --check src/ tests/ examples/ parity/: passed
  • uv run ty check src/swgoh_comlink/: passed
  • uv run pytest tests/unit -q: 1887 passed
  • uv run pytest -q: 1902 passed, 31 skipped. The integration suite is hard-wired to localhost:3000/3001, and neither was reachable.
  • Live check against the public Comlink at comlink.lab:3200, read-only, both clients:
    • Three paced /metadata calls with min_interval=0.4 took about 0.87 s.
    • /enums was a GET.
    • A bad /player request raised SwgohComlinkClientError 400.
    • max_response_bytes=100 raised the size error.
  • Examples run against the same Comlink: Sync/get_latest_game_data_version.py, Sync/get_events.py, Async/get_events.py and Async/concurrent_requests.py. All completed.

Migration notes

None. This is a behaviour-preserving internal refactor, so there is no docs/migration.md entry. Code that subclassed a client and overrode the private _receive_limited must follow its new signature, (client, request, endpoint, limit) -> (response, body).

🤖 Generated with Claude Code

MarTrepodi and others added 9 commits November 7, 2026 08:24
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 <noreply@anthropic.com>
_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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…T_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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…imits

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
# Conflicts:
#	docs/migration.md
#	src/swgoh_comlink/_base.py
#	src/swgoh_comlink/swgoh_comlink.py
#	src/swgoh_comlink/swgoh_comlink_async.py
…ans-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 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

code documentation Improvements or additions to documentation testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant