fix: address final review findings for service clients plan

Fixes 9 numbered findings + 7 minor fixes from the whole-plan review of
the MyWhoosh/Garmin service clients (Plan 3):

Garmin uploader (app/garmin/uploader.py):
- Detect Garmin-rejected imports (failures without successes) and raise
  new GarminImportRejected instead of reporting them as successful.
- Reclassify 429/rate-limit/500 login failures as transient instead of
  falling through to permanent auth errors; unrecognized login failures
  are now treated as transient (retryable) rather than GarminAuthError.
- Mirror the auth-token check from the login branch into the import
  branch so 401-at-import-time raises GarminAuthError instead of
  propagating raw.
- Add common GarminError base class, hoist transient-token tuple to a
  shared module constant, check response.status_code==409 before the
  duplicate substring fallback, and create the tokenstore dir 0o700.

MyWhoosh client (app/mywhoosh/client.py):
- Add optional max_pages bound to list_activities pagination.
- Add aclose()/__aenter__/__aexit__ so the client's own httpx.AsyncClient
  gets closed, while never closing an injected client.
- Guard the two remaining unguarded JSON-decode paths (login body,
  download-fit metadata) so malformed bodies raise
  MyWhooshIntegrationError instead of raw ValueError/AttributeError.
- Row-level malformation (missing id/activityFileId, unparseable
  startDatetime) is now skipped rather than aborting the whole page;
  envelope-shape failures still raise. id/activityFileId checks use
  explicit None/"" comparisons instead of Python falsiness.
- Replace asserts in _authenticated_post with explicit exceptions;
  restrict the reauth retry to 401 only, treat 403 as immediately
  terminal; naive startDatetime values are now treated as already-UTC
  instead of host-local.

MyWhoosh tokenstore (app/mywhoosh/tokenstore.py):
- load() now treats any corrupt/malformed token file (bad JSON, missing
  keys, OS errors) as "absent" instead of raising, so a bad cache no
  longer permanently wedges a user.

pyproject.toml:
- Tighten garminconnect pin to >=0.3.10,<1 (import_activity requires
  0.3.10+).

Adds/updates tests across tests/mywhoosh/ and tests/garmin/ covering
all of the above, including a fake client that wraps GarminUploadBlocked
in a plain RuntimeError to mirror the real garminconnect library's MFA
error wrapping.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Bastian Wagner
2026-08-15 15:23:14 +02:00
parent b48008c16e
commit 2f65c0178c
8 changed files with 426 additions and 33 deletions

View File

@@ -31,9 +31,20 @@ class MyWhooshIntegrationError(MyWhooshError):
class MyWhooshClient:
def __init__(self, token_store: MyWhooshTokenStore, http_client: httpx.AsyncClient | None = None) -> None:
self.token_store = token_store
self._owns_http = http_client is None
self.http = http_client or httpx.AsyncClient(timeout=30.0)
self.token = token_store.load()
async def aclose(self) -> None:
if self._owns_http:
await self.http.aclose()
async def __aenter__(self) -> "MyWhooshClient":
return self
async def __aexit__(self, *exc_info: object) -> None:
await self.aclose()
async def login(self, email: str, password: str) -> None:
payload = {
"Username": email,
@@ -56,6 +67,8 @@ class MyWhooshClient:
body = response.json()
except ValueError as exc:
raise MyWhooshIntegrationError("MyWhoosh login returned invalid JSON") from exc
if not isinstance(body, dict):
raise MyWhooshIntegrationError("MyWhoosh login response is not a JSON object")
if body.get("Success") is not True or not body.get("AccessToken"):
raise MyWhooshAuthError(str(body.get("Message") or "MyWhoosh login failed"))
self.token = MyWhooshToken(
@@ -72,7 +85,8 @@ class MyWhooshClient:
async def _authenticated_post(self, url: str, payload: dict, email: str, password: str) -> httpx.Response:
await self.ensure_authenticated(email, password)
for attempt in range(2):
assert self.token is not None
if self.token is None:
raise MyWhooshIntegrationError("no token after ensure_authenticated")
try:
response = await self.http.post(
url,
@@ -81,7 +95,9 @@ class MyWhooshClient:
)
except httpx.TransportError as exc:
raise MyWhooshTransientError("MyWhoosh request failed") from exc
if response.status_code not in {401, 403}:
if response.status_code == 403:
raise MyWhooshAuthError(f"MyWhoosh returned HTTP {response.status_code}")
if response.status_code != 401:
if response.status_code >= 500:
raise MyWhooshTransientError(f"MyWhoosh returned HTTP {response.status_code}")
return response
@@ -91,13 +107,15 @@ class MyWhooshClient:
await self.login(email, password)
continue
raise MyWhooshAuthError("MyWhoosh session rejected after reauthentication")
raise AssertionError("unreachable")
raise MyWhooshIntegrationError("unreachable state in _authenticated_post")
async def list_activities(self, email: str, password: str) -> list[MyWhooshActivity]:
async def list_activities(
self, email: str, password: str, max_pages: int | None = None
) -> list[MyWhooshActivity]:
activities: list[MyWhooshActivity] = []
page = 1
total_pages = 1
while page <= total_pages:
while page <= total_pages and (max_pages is None or page <= max_pages):
response = await self._authenticated_post(
ACTIVITIES_BASE + "rider/profile/activities",
{"sortDate": "DESC", "page": page},
@@ -119,26 +137,30 @@ class MyWhooshClient:
if not isinstance(results, list):
raise MyWhooshIntegrationError("MyWhoosh activities response has unexpected shape")
for row in results:
activities.append(self._normalize_activity(row))
activity = self._normalize_activity(row)
if activity is not None:
activities.append(activity)
page += 1
return activities
def _normalize_activity(self, row: object) -> MyWhooshActivity:
def _normalize_activity(self, row: object) -> MyWhooshActivity | None:
if not isinstance(row, dict):
raise MyWhooshIntegrationError("MyWhoosh activity row is not an object")
activity_id = row.get("id")
activity_file_id = row.get("activityFileId")
if not activity_id or not activity_file_id:
raise MyWhooshIntegrationError("MyWhoosh activity row missing stable id or activityFileId")
if activity_id is None or activity_id == "" or activity_file_id is None or activity_file_id == "":
return None
raw_started = row.get("startDatetime")
started_at: datetime | None = None
if raw_started:
try:
started_at = datetime.fromisoformat(str(raw_started).replace("Z", "+00:00")).astimezone(
timezone.utc
)
except ValueError as exc:
raise MyWhooshIntegrationError("MyWhoosh activity row has invalid startDatetime") from exc
parsed = datetime.fromisoformat(str(raw_started).replace("Z", "+00:00"))
except ValueError:
return None
if parsed.tzinfo is None:
started_at = parsed.replace(tzinfo=timezone.utc)
else:
started_at = parsed.astimezone(timezone.utc)
return MyWhooshActivity(
id=str(activity_id),
title=str(row.get("title") or ""),
@@ -155,7 +177,13 @@ class MyWhooshClient:
)
if response.status_code >= 400:
raise MyWhooshIntegrationError(f"download metadata returned HTTP {response.status_code}")
url = response.json().get("data")
try:
body = response.json()
except ValueError as exc:
raise MyWhooshIntegrationError("MyWhoosh download response returned invalid JSON") from exc
if not isinstance(body, dict):
raise MyWhooshIntegrationError("MyWhoosh download response is not a JSON object")
url = body.get("data")
if not isinstance(url, str) or not url:
raise MyWhooshIntegrationError("MyWhoosh download response has no URL")
try:

View File

@@ -12,13 +12,13 @@ class MyWhooshTokenStore:
def load(self) -> MyWhooshToken | None:
try:
raw = json.loads(self.path.read_text("utf-8"))
except FileNotFoundError:
return MyWhooshToken(
access_token=raw["access_token"],
refresh_token=raw.get("refresh_token"),
whoosh_id=raw.get("whoosh_id"),
)
except (FileNotFoundError, OSError, ValueError, KeyError, TypeError):
return None
return MyWhooshToken(
access_token=raw["access_token"],
refresh_token=raw.get("refresh_token"),
whoosh_id=raw.get("whoosh_id"),
)
def save(self, token: MyWhooshToken) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)