Repository navigation
refactor(core): move request preparation and retry decisions into a sans-I/O core - #258
Merged
Merged
Conversation
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>
This was referenced Nov 7, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Task: REF-1 phase 1 (v2.9 hardening plan, PR 10)
Branch:
refactor/sans-io-retryStacked on:
fix/keepalive-parity(PRs 2, 3, 5, 6), withfix/error-body-truncation(PR 4) merged in. Review after those land, or retarget once they are ondevelop.Closes #246
Design note
Problem.
SwgohComlink._requestandSwgohComlinkAsync._requesteach 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._sendduplicated 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.
_retry_step(policy, error, attempt)retry.py_RetryStep(delay, hold)orNoneto give up.holdis set for rate refusals._Admissionretry.pynext_wait()returns each wait to sleep, re-checks the hold after every wait, and requeues if the hold now ends later. ReturnsNoneonce the caller may send.abandon()gives the slot back.retry._clock)_prepare_request(...)_base.py_PreparedRequest, whosestatsfield choosesstats_clientorclient._interpret_response(response, content)_base.pydict/list, or raises the typedSwgohComlinkHTTPError(causeHTTPStatusError) orSwgohComlinkDecodeError(causeJSONDecodeError/UnicodeDecodeError)._admission(...),_retry_wait(...)_base.py_retry_waitlogs, applies the hold, adds jitter and returns the wait to carry into the next attempt, orNoneto re-raise.What each client keeps (identical apart from
awaitand the cancellation rule):_requestis 28 lines in both clients, including its signature and docstring._sendand_receive_limitedkeep only the transport call and the streaming read.Cancellation is unchanged and now documented in each client's
_admit:except BaseException, so it includesKeyboardInterrupt. A new test covers it.asyncio.CancelledErrorgives the slot back, as before.test_rate_hold_admission.pycovers it.Things kept on purpose:
retry._clock,_sleep,_async_sleepand_random, read at call time, so the existing monkeypatch seams still work.swgoh_comlink.swgoh_comlink/swgoh_comlink.swgoh_comlink_async). A private_logclass attribute does this.__cause__chains are unchanged._post,_get_game_version,_send,_pace_delay,_pace_slot,_hold_changedand_hold_endpointare unchanged.Not done here: generating the sync client (phase 2,
unasyncor 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-retryadds only import-line conflicts on top of the conflicts the stacked PRs 2–6 already cause:json/typingimports in both clients and in_base.py. Auth has no_requestchanges and no name collisions with the new private names.What changed
src/swgoh_comlink/retry.py: adds_RetryStep,_retry_stepand_Admission.src/swgoh_comlink/_base.py: adds_PreparedRequest,_prepare_request,_interpret_response,_admission,_retry_waitand the_logclass attribute.src/swgoh_comlink/swgoh_comlink.pyandswgoh_comlink_async.py:_requestis now the short loop above. The new_admitholds the runtime's sleep and cancellation handling._sendis now prepare, then transport, then interpret._receive_limitedtakes the_PreparedRequestand 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.tests/unit/test_client_parity.py: API parity and the_requestguard.tests/unit/test_retry_core.py: 22 tests of the core with no network, plus the sync interrupt test.fix/error-body-truncation. There were conflicts indocs/migration.md,_base.pyand 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_namefollows_bounded_error_response.Acceptance
_requestin 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 withinspect.getsource. It also checks that the source mentions none ofretry_policy,retry_delay,jitter,_hold_endpoint,_hold_changedor_pace_slot. Both cases failed before the refactor.test_retry.py,test_retry_mocked.py,test_rate_hold_admission.pyandtest_pacer_scaling.pypass unchanged.git diff 9cc3760 -- <those four files>is empty, and all four pass.The method-signature parity test passes.
test_client_parity.pychecks three things for every public callable onSwgohComlinkAsync, aliases included (40 names):SwgohComlink. The only mapping isaclose→close.inspect.signature.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/: passeduv run ruff format --check src/ tests/ examples/ parity/: passeduv run ty check src/swgoh_comlink/: passeduv run pytest tests/unit -q: 1887 passeduv run pytest -q: 1902 passed, 31 skipped. The integration suite is hard-wired tolocalhost:3000/3001, and neither was reachable.comlink.lab:3200, read-only, both clients:/metadatacalls withmin_interval=0.4took about 0.87 s./enumswas a GET./playerrequest raisedSwgohComlinkClientError400.max_response_bytes=100raised the size error.Sync/get_latest_game_data_version.py,Sync/get_events.py,Async/get_events.pyandAsync/concurrent_requests.py. All completed.Migration notes
None. This is a behaviour-preserving internal refactor, so there is no
docs/migration.mdentry. Code that subclassed a client and overrode the private_receive_limitedmust follow its new signature,(client, request, endpoint, limit) -> (response, body).🤖 Generated with Claude Code