mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-10 21:07:14 +01:00
_workout_sync.py (332) -> _sync_client.py token, Firebase/GitHub client
_sync_records.py payload predicates + log decoding
_sick_tracker.py (317) -> _sick_budget.py SickHistory + rolling budget
This one was not a pure move until the fixtures followed it. Three autouse
test guards patch names by module, and all three pointed at _workout_sync:
isolate_sync_token SYNC_TOKEN_FILE -> now also on _sync_client
_no_real_firebase_config CONFIG_FILE -> now on _sync_client
_firebase_config helper (7 call sites) -> now passed _sync_client
With them stale, sync_client built a REAL client: the suite went from 14s to
over 120s and test_workout_sync_part5 asserted against live workout data
pulled from the actual backend. Fixed, the same tests run in 0.7s. Both
modules keep SYNC_TOKEN_FILE so either patch point works, and every relocated
guard target is asserted to exist.
977 tests pass at 100% branch coverage; pylint back to 8.70 after fixing the
findings the split introduced (a dropped `return None` in _parse_iso and
leftover dead imports). `screen_lock --status` unchanged.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EveB813BQ8abAP68VSqZ5Y
92 lines
3.3 KiB
Python
92 lines
3.3 KiB
Python
"""Decoding sync-log blobs into records, and telling record kinds apart.
|
|
|
|
Split out of :mod:`screen_locker._workout_sync` to keep every file under the
|
|
250-line cap. Re-exported from there, so callers are unchanged.
|
|
|
|
Everything here is pure: it parses JSON that a caller already fetched. Talking
|
|
to GitHub or Firebase stays in ``_workout_sync``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
from typing import TYPE_CHECKING
|
|
|
|
from crdt_sync import Hlc, Record
|
|
|
|
from screen_locker._manual_workout import MANUAL_WORKOUT_SYNC_KIND
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Callable
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
_PAYLOAD_FIELD = "payload"
|
|
|
|
|
|
def _is_manual_payload(payload: object) -> bool:
|
|
"""True if a decoded sync payload is a manual-workout record."""
|
|
return isinstance(payload, dict) and payload.get("kind") == MANUAL_WORKOUT_SYNC_KIND
|
|
|
|
|
|
def _is_session_payload(payload: object) -> bool:
|
|
"""True if a decoded sync payload is a completed StrongLifts session.
|
|
|
|
Identified by SHAPE -- the presence of ``exercises`` -- not by a ``kind``
|
|
field, because the phone app's ``WorkoutSession.toJson()`` emits no ``kind``
|
|
at all. Keying session detection on ``kind`` is what made real sessions
|
|
invisible to the only reader that walks every device directory.
|
|
|
|
Shape-matching also excludes the PC-origin ``runnerup_verified`` /
|
|
``phone_verified`` records that share these device logs: they are non-manual
|
|
too, so "not manual" alone would hand a caller expecting ``exercises`` and
|
|
``duration_seconds`` a record that has neither.
|
|
"""
|
|
return isinstance(payload, dict) and isinstance(payload.get("exercises"), list)
|
|
|
|
|
|
def _session_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
|
|
"""Return ``{record_id: (payload, hlc)}`` for session records in a log blob.
|
|
|
|
Raises the same decode errors as :func:`_manual_records`; callers treat a
|
|
corrupt device log as "no sessions from that device".
|
|
"""
|
|
return _records_matching(log_json, _is_session_payload)
|
|
|
|
|
|
def _records_matching(
|
|
log_json: str, predicate: Callable[[object], bool]
|
|
) -> dict[str, tuple[dict, Hlc]]:
|
|
"""Return ``{record_id: (payload, hlc)}`` for payloads passing ``predicate``.
|
|
|
|
Raises:
|
|
TypeError: If the top-level JSON isn't an object or a record's shape
|
|
doesn't match what :meth:`Record.from_dict` expects.
|
|
KeyError: If a record is missing an expected key.
|
|
ValueError: Via ``json.loads`` or :meth:`crdt_sync.Hlc.from_str`.
|
|
"""
|
|
raw = json.loads(log_json)
|
|
if not isinstance(raw, dict):
|
|
msg = f"top-level sync payload is not a JSON object: {raw!r}"
|
|
raise TypeError(msg)
|
|
result: dict[str, tuple[dict, Hlc]] = {}
|
|
for data in raw.values():
|
|
record = Record.from_dict(data)
|
|
field = record.fields.get(_PAYLOAD_FIELD)
|
|
if field is None:
|
|
continue
|
|
payload, hlc = field
|
|
if predicate(payload):
|
|
result[record.id] = (payload, hlc)
|
|
return result
|
|
|
|
|
|
def _manual_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
|
|
"""Return ``{record_id: (payload, hlc)}`` for manual records in a log blob.
|
|
|
|
Raises the same decode errors as :func:`_records_matching`; callers treat a
|
|
corrupt device log as "no manual records from that device".
|
|
"""
|
|
return _records_matching(log_json, _is_manual_payload)
|