Coverage for src/served_size_ledger.py: 100%
56 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"""Persisted record of photo renditions kept at a non-declared size.
3A complete transfer whose byte count differs from the CloudKit-declared size is
4accepted by the download path. Without a durable note, the next sync's
5``check_photo_exists`` compares only against the declared size, treats the file
6as missing and downloads it again — the loop this issue is about.
8Entries pin the version record, variant, declared size and served size. A
9change to either size invalidates the exception, so an unrelated file of a
10coincidentally matching length is not accepted. The file follows the same
11config-directory convention as the web UI's state and survives container
12recreations with the mounted volume.
13"""
15import json
16import os
17import sys
18import threading
20from src import get_logger
22LOGGER = get_logger()
24_FILENAME = ".served-photo-sizes.json"
25_LOCK = threading.RLock()
26_entries_by_path: dict[str, dict[str, dict]] = {}
29def _path() -> str:
30 """Resolve the ledger path under the config directory.
32 Reads ``DEFAULT_COOKIE_DIRECTORY`` through ``sys.modules`` so the test
33 suite's redirect is honoured, matching ``web_signals``.
34 """
35 cookie_dir = sys.modules["src"].DEFAULT_COOKIE_DIRECTORY
36 return os.path.join(os.path.dirname(cookie_dir) or "/config", _FILENAME)
39def _key(record_id: str, file_size: str) -> str:
40 """Key one rendition by its CloudKit record and version name."""
41 return f"{record_id}|{file_size}"
44def _entries(path: str) -> dict[str, dict]:
45 """Load and cache the ledger stored at ``path``."""
46 with _LOCK:
47 if path not in _entries_by_path:
48 try:
49 with open(path) as f:
50 data = json.load(f)
51 except FileNotFoundError:
52 data = {}
53 except (OSError, json.JSONDecodeError) as e:
54 LOGGER.warning(f"served_size_ledger: failed to load {path}: {e!s} - treating as empty")
55 data = {}
56 _entries_by_path[path] = data if isinstance(data, dict) else {}
57 return _entries_by_path[path]
60def _save(path: str, entries: dict[str, dict]) -> None:
61 """Publish ``entries`` atomically, warning instead of failing a sync."""
62 tmp = f"{path}.{os.getpid()}.{threading.get_ident()}.tmp"
63 try:
64 os.makedirs(os.path.dirname(path), exist_ok=True)
65 with open(tmp, "w") as f:
66 json.dump(entries, f, indent=2)
67 os.replace(tmp, path)
68 except OSError as e:
69 LOGGER.warning(f"served_size_ledger: failed to save {path}: {e!s}")
70 try:
71 os.unlink(tmp)
72 except OSError:
73 pass
76def record(record_id: str, file_size: str, declared: int, served: int) -> None:
77 """Remember that ``served`` bytes were accepted for this rendition."""
78 path = _path()
79 with _LOCK:
80 entries = _entries(path)
81 entries[_key(record_id, file_size)] = {"declared": declared, "served": served}
82 _save(path, entries)
85def matches(record_id: str, file_size: str, declared: int, served: int) -> bool:
86 """Whether this exact rendition was accepted at ``served`` bytes."""
87 with _LOCK:
88 entry = _entries(_path()).get(_key(record_id, file_size))
89 return (
90 isinstance(entry, dict)
91 and entry.get("declared") == declared
92 and entry.get("served") == served
93 )
96def forget(record_id: str, file_size: str) -> None:
97 """Drop an entry once the declared size matches what is on disk again."""
98 path = _path()
99 with _LOCK:
100 entries = _entries(path)
101 if entries.pop(_key(record_id, file_size), None) is not None:
102 _save(path, entries)