Coverage for src/download_report.py: 100%
36 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
1"""Per-run record of photo transfers that could not be verified.
3A failed transfer is still retried on the next sync, but it is now visible:
4the asset is recorded once per run with its declared and received byte counts,
5and a single summary line closes the run. The report is process-local; the
6sync loop is the only writer.
7"""
9from threading import Lock
11from src import get_logger
13LOGGER = get_logger()
15# Paths named in the summary line before it switches to a count.
16_SUMMARY_PATH_LIMIT = 5
19class DownloadReport:
20 """Unverified transfers for one photo-sync run, keyed by path and variant."""
22 def __init__(self) -> None:
23 """Initialize an empty report."""
24 self._failures: dict[tuple[str, str], dict] = {}
25 self._lock = Lock()
27 def record(self, failure: dict) -> bool:
28 """Record one failure, logging it once per path and version.
30 Args:
31 failure: Fields describing the failed transfer (``path``,
32 ``file_size``, ``asset_id``, ``reason``, ``declared_bytes``,
33 ``received_bytes``).
35 Returns:
36 True when this failure was not already recorded, False otherwise.
37 """
38 key = (failure["path"], failure["file_size"])
39 with self._lock:
40 if key in self._failures:
41 return False
42 self._failures[key] = failure
44 LOGGER.error(
45 f"Could not verify photo {failure['path']} "
46 f"(asset {failure.get('asset_id') or '<unknown>'}, {failure['file_size']}): "
47 f"{failure['reason']} - declared {failure.get('declared_bytes')} bytes, "
48 f"received {failure.get('received_bytes')} bytes. Will retry on the next sync.",
49 )
50 return True
52 def unverified(self) -> list[dict]:
53 """Return a snapshot of the recorded failures."""
54 with self._lock:
55 return list(self._failures.values())
57 def __len__(self) -> int:
58 """Return how many distinct transfers are unverified."""
59 with self._lock:
60 return len(self._failures)
63_report = DownloadReport()
66def reset_download_report() -> None:
67 """Start a fresh report for a new photo-sync run."""
68 global _report # noqa: PLW0603 - one report per process, swapped per run
69 _report = DownloadReport()
72def get_download_report() -> DownloadReport:
73 """Return the report for the current run."""
74 return _report
77def log_download_summary() -> int:
78 """Log the run's unverified count, if any, and return it."""
79 failures = _report.unverified()
80 if not failures:
81 return 0
83 paths = ", ".join(failure["path"] for failure in failures[:_SUMMARY_PATH_LIMIT])
84 remaining = len(failures) - _SUMMARY_PATH_LIMIT
85 suffix = f" (+{remaining} more)" if remaining > 0 else ""
86 LOGGER.error(f"{len(failures)} photo(s) could not be verified this run: {paths}{suffix}")
87 return len(failures)