Coverage for src/web_signals.py: 100%
242 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"""Cross-thread signalling for the embedded web UI.
3The web UI (``src.web``) runs in a daemon thread alongside the sync
4loop (``src.sync``). Two things need to flow between them:
61. **Force-sync sentinels** — when the user taps "Sync now" on the
7 dashboard, the web thread touches ``$CONFIG_DIR/.force-sync-<svc>``
8 and the sync loop deletes the sentinel + zeroes the countdown on
9 its next iteration.
112. **Last-sync state** — after each per-service sync run, the sync
12 loop writes a small JSON file the dashboard reads on every
13 refresh (last completion time, file counts, error count).
15Files are chosen over a shared module-level singleton so the same
16mechanism keeps working if a future refactor splits sync + web into
17two processes. They live in ``ICLOUD_DOCKER_CONFIG_DIR`` (default
18``/config``) — same place the keyring and session cookies live, so
19they're persisted across container recreations.
20"""
22__author__ = "Mandar Patil (mandarons@pm.me)"
24import functools
25import json
26import os
27import threading
28import time
29from typing import Any
31from src import get_logger
33LOGGER = get_logger()
36def _config_dir() -> str:
37 """Resolve the directory force-sync sentinels + state JSON live in.
39 Mirrors the ICLOUD_DOCKER_CONFIG_DIR / DEFAULT_COOKIE_DIRECTORY
40 setup: same logic the keyring redirect uses, so dev hosts without
41 ``/config`` still work via a tempdir. Reads
42 ``DEFAULT_COOKIE_DIRECTORY`` via ``sys.modules`` so the test
43 fixture's monkeypatch is honoured -- a ``from src import
44 DEFAULT_COOKIE_DIRECTORY`` at module top would bind the value once
45 at import time and miss the redirect.
46 """
47 import sys
49 # DEFAULT_COOKIE_DIRECTORY is "<config_dir>/session_data"; strip the
50 # trailing component to recover the config dir.
51 cookie_dir = sys.modules["src"].DEFAULT_COOKIE_DIRECTORY
52 return os.path.dirname(cookie_dir) or "/config"
55_VALID_SERVICES = ("drive", "photos")
57# The sync loop and the web UI are threads of one process, and every writer
58# below reads the whole file, changes one key and writes it back. Unlocked,
59# two of them interleave and one update is lost. Re-entrant so a locked
60# writer may call another.
61_STATE_LOCK = threading.RLock()
64def _locked(func):
65 """Hold the state lock across a writer's read-modify-write."""
67 @functools.wraps(func)
68 def wrapper(*args, **kwargs):
69 with _STATE_LOCK:
70 return func(*args, **kwargs)
72 return wrapper
75def _sentinel_path(service: str) -> str:
76 return os.path.join(_config_dir(), f".force-sync-{service}")
79def _state_path() -> str:
80 return os.path.join(_config_dir(), ".last-sync-state.json")
83def _reauth_sentinel_path() -> str:
84 return os.path.join(_config_dir(), ".reauth-completed")
87def record_reauth_completed() -> bool:
88 """Signal that a re-auth just succeeded in the web UI.
90 Deliberately not the force-sync sentinel. That one is a button meaning
91 "sync everything now"; borrowing it would queue a full photo
92 re-enumeration -- hours on a large library -- that nobody asked for.
93 This one means only "the wait you are serving is over".
94 """
95 path = _reauth_sentinel_path()
96 try:
97 os.makedirs(os.path.dirname(path), exist_ok=True)
98 with open(path, "w") as f:
99 f.write(str(time.time()))
100 return True
101 except OSError as e:
102 LOGGER.warning(f"web_signals: failed to write {path}: {e!s}")
103 return False
106def consume_reauth_completed() -> bool:
107 """Atomically check + clear the re-auth signal."""
108 path = _reauth_sentinel_path()
109 try:
110 os.unlink(path)
111 return True
112 except FileNotFoundError:
113 return False
114 except OSError as e:
115 LOGGER.warning(f"web_signals: failed to clear {path}: {e!s}")
116 return False
119def request_force_sync(service: str) -> bool:
120 """Touch the sentinel for ``service``.
122 Returns True on success, False on validation/IO failure. Idempotent —
123 re-tapping while a previous request is still queued is a no-op.
124 """
125 if service not in _VALID_SERVICES:
126 return False
127 path = _sentinel_path(service)
128 try:
129 os.makedirs(os.path.dirname(path), exist_ok=True)
130 with open(path, "w") as f:
131 f.write(str(time.time()))
132 return True
133 except OSError as e:
134 LOGGER.warning(f"web_signals: failed to write {path}: {e!s}")
135 return False
138def pending_force_syncs() -> list[str]:
139 """Return services currently queued for an immediate sync.
141 Used by the dashboard to render "Queued ✓" instead of "Sync now".
142 """
143 return [
144 service
145 for service in _VALID_SERVICES
146 if os.path.isfile(_sentinel_path(service))
147 ]
150def consume_force_sync(service: str) -> bool:
151 """Atomically check + delete the sentinel. Sync loop calls this on
152 each iteration; True means "user requested an immediate run."
154 ``os.unlink`` raises ``FileNotFoundError`` if another caller beat us
155 to it — treated as "no request" rather than an error.
156 """
157 if service not in _VALID_SERVICES:
158 return False
159 try:
160 os.unlink(_sentinel_path(service))
161 return True
162 except FileNotFoundError:
163 return False
164 except OSError as e:
165 LOGGER.warning(f"web_signals: failed to consume {service} sentinel: {e!s}")
166 return False
169@_locked
170def record_sync_completion(
171 service: str,
172 *,
173 files_downloaded: int | None = None,
174 files_skipped: int | None = None,
175 files_removed: int | None = None,
176 errors: int | None = None,
177 duration_seconds: float | None = None,
178) -> None:
179 """Persist per-service stats after a sync run completes.
181 All counters are optional — passing ``None`` leaves the previous
182 value alone. Writes atomically (temp + rename) so a partial write
183 can't corrupt the file.
184 """
185 if service not in _VALID_SERVICES:
186 return
187 state = _load_state()
188 entry = state.get(service, {})
189 entry["completed_at"] = time.time()
190 if files_downloaded is not None:
191 entry["files_downloaded"] = int(files_downloaded)
192 if files_skipped is not None:
193 entry["files_skipped"] = int(files_skipped)
194 if files_removed is not None:
195 entry["files_removed"] = int(files_removed)
196 if errors is not None:
197 entry["errors"] = int(errors)
198 if duration_seconds is not None:
199 entry["duration_seconds"] = float(duration_seconds)
200 state[service] = entry
201 _save_state(state)
204@_locked
205def record_service_running(service: str, *, running: bool) -> None:
206 """Mark ``service`` as syncing right now, or as no longer syncing.
208 A pass can take an hour, and the per-service record is only written
209 when it completes, so until then the dashboard showed nothing but
210 when the previous one finished.
211 """
212 if service not in _VALID_SERVICES:
213 return
214 state = _load_state()
215 entry = state.get(service, {})
216 if running:
217 entry["running_since"] = time.time()
218 elif entry.pop("running_since", None) is None:
219 return
220 state[service] = entry
221 _save_state(state)
224def get_sync_state(service: str) -> dict[str, Any]:
225 """Return the persisted last-sync state for ``service``.
227 Empty dict on missing/corrupt file — the dashboard renders absence
228 gracefully.
229 """
230 if service not in _VALID_SERVICES:
231 return {}
232 return _load_state().get(service, {})
235def _load_state() -> dict[str, dict[str, Any]]:
236 path = _state_path()
237 if not os.path.isfile(path):
238 return {}
239 try:
240 with open(path) as f:
241 data = json.load(f)
242 if isinstance(data, dict):
243 return data
244 except (OSError, json.JSONDecodeError) as e:
245 LOGGER.warning(f"web_signals: failed to load {path}: {e!s} — treating as empty")
246 return {}
249def _save_state(state: dict[str, dict[str, Any]]) -> None:
250 path = _state_path()
251 # Named per process and thread: a shared name let one writer truncate the
252 # file while another renamed it into place, publishing torn JSON that the
253 # next load reads as empty.
254 tmp = f"{path}.{os.getpid()}.{threading.get_ident()}.tmp"
255 try:
256 os.makedirs(os.path.dirname(path), exist_ok=True)
257 with open(tmp, "w") as f:
258 json.dump(state, f, indent=2)
259 os.rename(tmp, path)
260 except OSError as e:
261 LOGGER.warning(f"web_signals: failed to save {path}: {e!s}")
262 try:
263 os.unlink(tmp)
264 except OSError:
265 pass
268_TRUST_STATE_KEY = "_trust"
269_AUTH_BLOCKED_STATE_KEY = "_auth_blocked"
270_AUTH_METHOD_STATE_KEY = "_auth_method"
273@_locked
274def record_trust_state(
275 *,
276 expires_at_iso: str | None,
277 warned_for_expires_at: str | None = None,
278) -> None:
279 """Persist Apple trust-cookie expiry + whether we've warned for it.
281 Stored under a reserved ``_trust`` key in the same JSON file as
282 per-service sync state. ``warned_for_expires_at`` carries the iso
283 timestamp the most recent threshold-cross warning was fired for, so
284 a cookie refresh (new expires_at) automatically rearms warning
285 eligibility -- compare ``warned_for_expires_at`` against the live
286 ``expires_at_iso`` to decide whether to fire again.
287 """
288 state = _load_state()
289 entry = state.get(_TRUST_STATE_KEY, {})
290 entry["expires_at"] = expires_at_iso
291 entry["last_updated"] = time.time()
292 if warned_for_expires_at is not None:
293 entry["warned_for_expires_at"] = warned_for_expires_at
294 state[_TRUST_STATE_KEY] = entry
295 _save_state(state)
298def get_trust_state() -> dict[str, Any]:
299 """Return persisted trust state. Empty dict if never recorded."""
300 return _load_state().get(_TRUST_STATE_KEY, {})
303@_locked
304def record_auth_blocked(*, blocked: bool, reason: str | None = None) -> None:
305 """Record whether the sync loop is currently unable to authenticate.
307 ``_detect_auth_state`` can only see on-disk signals -- a username in
308 the config and a password in the keyring -- so it reports "ready" for
309 an account that is in fact stuck on a second factor. Only the sync
310 loop knows it is failing, so it publishes that here and the dashboard
311 stops claiming everything is healthy while nothing is syncing.
312 """
313 state = _load_state()
314 state[_AUTH_BLOCKED_STATE_KEY] = {
315 "blocked": bool(blocked),
316 "reason": reason,
317 "last_updated": time.time(),
318 }
319 _save_state(state)
322def get_auth_blocked() -> dict[str, Any]:
323 """Return the recorded auth-blocked state. Empty dict if never recorded."""
324 entry = _load_state().get(_AUTH_BLOCKED_STATE_KEY)
325 return entry if isinstance(entry, dict) else {}
328@_locked
329def record_auth_method(*, username: str, method: str) -> None:
330 """Remember which second factor Apple demands for this Apple ID.
332 Keyed by username because the factor is an account property, not a
333 container property -- an operator who repoints the container at a
334 different Apple ID must not inherit the previous account's mode.
336 ``method`` is "security_key" once Apple has answered with an
337 ``fsaChallenge`` (hardware key or passkey enrolled, which disables
338 6-digit codes entirely), otherwise "code".
339 """
340 state = _load_state()
341 entry = state.get(_AUTH_METHOD_STATE_KEY, {})
342 entry[username] = {"method": method, "last_seen": time.time()}
343 state[_AUTH_METHOD_STATE_KEY] = entry
344 _save_state(state)
347def get_auth_method(username: str) -> str | None:
348 """Return the recorded second factor for ``username``, or None if unknown."""
349 entry = _load_state().get(_AUTH_METHOD_STATE_KEY, {}).get(username)
350 if not isinstance(entry, dict):
351 return None
352 method = entry.get("method")
353 return method if isinstance(method, str) else None
356def format_relative_time(epoch_seconds: float, *, now: float | None = None) -> str:
357 """Human-friendly relative time for dashboard display.
359 "Just now" / "5 min ago" / "2 h ago" / "3 d ago". Avoids
360 "1 hour ago" pluralisation gymnastics by sticking to compact
361 unit suffixes.
362 """
363 if not epoch_seconds:
364 return ""
365 if now is None:
366 now = time.time()
367 delta = max(0, now - epoch_seconds)
368 if delta < 30:
369 return "Just now"
370 if delta < 120:
371 return f"{int(delta)} sec ago"
372 if delta < 3600:
373 return f"{int(delta // 60)} min ago"
374 if delta < 86400:
375 return f"{int(delta // 3600)} h ago"
376 return f"{int(delta // 86400)} d ago"
379_LIBRARY_STATE_KEY = "_libraries"
382@_locked
383def record_library_started(library: str) -> None:
384 """Mark ``library`` as syncing right now.
386 A photo library can take an hour, and until it finishes there was
387 nothing anywhere saying which one was being worked on -- the
388 per-service record is only written once the whole pass completes, so
389 a library that never got its turn was indistinguishable from one
390 that had nothing to do.
391 """
392 state = _load_state()
393 libraries = state.get(_LIBRARY_STATE_KEY, {})
394 entry = libraries.get(library, {})
395 entry["state"] = "syncing"
396 entry["started_at"] = time.time()
397 entry.pop("error", None)
398 libraries[library] = entry
399 state[_LIBRARY_STATE_KEY] = libraries
400 _save_state(state)
403@_locked
404def record_library_finished(
405 library: str,
406 *,
407 ok: bool,
408 error: str | None = None,
409 downloaded: int | None = None,
410 skipped: int | None = None,
411) -> None:
412 """Record how ``library`` ended.
414 ``ok=False`` keeps the previous ``completed_at`` untouched, so the
415 dashboard can still show when the library last succeeded alongside
416 the fact that it is failing now.
417 """
418 state = _load_state()
419 libraries = state.get(_LIBRARY_STATE_KEY, {})
420 entry = libraries.get(library, {})
421 entry["state"] = "ok" if ok else "failed"
422 entry["finished_at"] = time.time()
423 if ok:
424 entry["completed_at"] = entry["finished_at"]
425 entry.pop("error", None)
426 else:
427 entry["error"] = error
428 if downloaded is not None:
429 entry["downloaded"] = downloaded
430 if skipped is not None:
431 entry["skipped"] = skipped
432 libraries[library] = entry
433 state[_LIBRARY_STATE_KEY] = libraries
434 _save_state(state)
437@_locked
438def record_library_indexing(library: str, *, state: str | None) -> None:
439 """Record whether Apple is still indexing ``library`` (None: finished).
441 Such a library is synced but kept out of obsolete-file cleanup, and
442 nothing else on the dashboard would say why its deletions never land.
443 """
444 states = _load_state()
445 libraries = states.get(_LIBRARY_STATE_KEY, {})
446 entry = libraries.get(library, {})
447 if state is None:
448 entry.pop("indexing", None)
449 else:
450 entry["indexing"] = state
451 libraries[library] = entry
452 states[_LIBRARY_STATE_KEY] = libraries
453 _save_state(states)
456def get_library_states() -> dict[str, Any]:
457 """Return per-library sync state. Empty dict if never recorded."""
458 return _load_state().get(_LIBRARY_STATE_KEY, {})
461@_locked
462def clear_stale_library_states() -> None:
463 """Demote any library, or service, left mid-sync with no process still on it.
465 The state file outlives the container, so a restart during a library
466 would otherwise leave it reading "syncing" forever. Called at
467 sync-loop startup, when nothing can legitimately be in flight, and
468 whenever a photos pass is abandoned part-way through a library.
469 """
470 state = _load_state()
471 libraries = state.get(_LIBRARY_STATE_KEY, {})
472 changed = False
473 for service in _VALID_SERVICES:
474 if state.get(service, {}).pop("running_since", None) is not None:
475 changed = True
476 for entry in libraries.values():
477 if entry.get("state") == "syncing":
478 entry["state"] = "interrupted"
479 changed = True
480 if changed:
481 state[_LIBRARY_STATE_KEY] = libraries
482 _save_state(state)