Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
7 changes: 6 additions & 1 deletion docs/api/async.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
59 changes: 57 additions & 2 deletions docs/api/comlink.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -52,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
Expand Down
4 changes: 3 additions & 1 deletion docs/api/exceptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|---|---|
Expand Down
6 changes: 6 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
38 changes: 38 additions & 0 deletions docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,44 @@ 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.
- **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.
- **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).
- **`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.
- **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.
- **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

| Area | Before (v1.x) | After |
Expand Down
54 changes: 31 additions & 23 deletions src/swgoh_comlink/StatCalc/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import urllib.request
from typing import Any

from ..exceptions import SwgohComlinkValueError
from ..helpers._stat_data import STATS as _CANONICAL_STATS


Expand All @@ -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.

Expand All @@ -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),
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"])
Expand Down Expand Up @@ -499,29 +507,29 @@ 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"])
+ self._get_crewless_skills_crew_rating(ship.get("skills", []))
)

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
cr += mult * self._table_get(self._cr_tables["abilityLevelCR"], skill["tier"])
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"]

Expand Down Expand Up @@ -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"])
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand All @@ -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 = []

Expand Down Expand Up @@ -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

Expand Down
Loading
Loading