mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-24 23:06:18 +01:00
Compare commits
4 Commits
b8b432bee4
...
6258b35f88
| Author | SHA1 | Date | |
|---|---|---|---|
| 6258b35f88 | |||
| c7371d7e0d | |||
| 0173f4c56c | |||
| b53ac92c59 |
@ -102,7 +102,7 @@ repos:
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
- requests
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.5.0#subdirectory=gatelock
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.6.0#subdirectory=crdt-sync
|
||||
- mcp>=2,<3
|
||||
- pydantic
|
||||
|
||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
||||
description: "Companion phone app for diet_guard: log meals on the go."
|
||||
publish_to: 'none'
|
||||
|
||||
version: 1.0.39+1
|
||||
version: 1.0.43+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
||||
@ -8,31 +8,68 @@ just the thin CLI glue, same as ``_cli_sync.py`` is for ``sync``.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib import import_module
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard._gate import gate_is_due
|
||||
from diet_guard._gatelock import MealGate, acquire_gate_lock, release_gate_lock
|
||||
from diet_guard._gatelock_lockfile import acquire_gate_lock, release_gate_lock
|
||||
from diet_guard._gatelock_support import wait_for_display
|
||||
from diet_guard._sync import pull_shared_log
|
||||
from diet_guard._sync_events import publish_after_log
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
# Names resolved lazily below. Importing ``_gatelock`` eagerly costs ~120ms:
|
||||
# it reaches ``_resolve`` -> ``_estimator_off`` -> ``requests`` (~78ms) on top
|
||||
# of tkinter. The common gate tick is *not due* and opens no window, so it must
|
||||
# not pay for a GUI and an HTTP stack it never touches.
|
||||
#
|
||||
# A module-level ``__getattr__`` (PEP 562) rather than a function-local import
|
||||
# because seven tests do ``patch.object(_cli_gate, "MealGate", ...)`` and
|
||||
# ``scripts/check_patch_targets.py`` resolves targets with ``hasattr`` -- both
|
||||
# go through ``__getattr__`` and keep working, while a function-local import
|
||||
# would make the attribute invisible to both.
|
||||
_LAZY_ATTRS = {
|
||||
"MealGate": ("diet_guard._gatelock", "MealGate"),
|
||||
# ``_sync_refresh`` reaches ``crdt_sync`` -> ``requests``; the not-due
|
||||
# tick never pulls, so it must not pay that import either.
|
||||
"pull_peer_logs": ("diet_guard._sync_refresh", "pull_peer_logs"),
|
||||
}
|
||||
|
||||
|
||||
def __getattr__(name: str) -> object:
|
||||
"""Resolve the deferred GUI import on first attribute access."""
|
||||
target = _LAZY_ATTRS.get(name)
|
||||
if target is None:
|
||||
msg = f"module {__name__!r} has no attribute {name!r}"
|
||||
raise AttributeError(msg)
|
||||
module_name, attr = target
|
||||
return getattr(import_module(module_name), attr)
|
||||
|
||||
|
||||
def _should_lock(emit: Callable[[str], None]) -> bool:
|
||||
"""Decide whether to lock, pulling from sync first if a lock looks due.
|
||||
|
||||
This wraps the pure, local :func:`~diet_guard._gate.gate_is_due` predicate
|
||||
with one network step: the cheap local check runs first, and only when it
|
||||
says a lock is due do we pull the shared log (via :func:`pull_shared_log`,
|
||||
which fails closed) and re-read the freshly written log. So a meal just
|
||||
logged on the phone can clear the lock, while a not-due tick never touches
|
||||
the network at all.
|
||||
says a lock is due do we pull (via :func:`pull_peer_logs`, which fails
|
||||
closed) and re-read the freshly written log. So a meal just logged on the
|
||||
phone can clear the lock, while a not-due tick never touches the network
|
||||
at all.
|
||||
|
||||
The pull is deliberately the *narrow* one -- peer logs only, no budget, no
|
||||
food banks, no push. The full tick measured ~21s against the live remote,
|
||||
which is not something to sit in front of a fullscreen lock; it still runs
|
||||
in :func:`cmd_gate` once the window has closed. Only the peer logs can
|
||||
answer "has a peer already logged this slot?", which is the sole question
|
||||
this predicate asks.
|
||||
"""
|
||||
if not gate_is_due():
|
||||
return False
|
||||
reason = pull_shared_log() # only pay the network cost when about to lock
|
||||
# Through the module object so the lazy hook above resolves it, and so a
|
||||
# test's ``patch.object`` still wins.
|
||||
reason = sys.modules[__name__].pull_peer_logs()
|
||||
if reason is not None:
|
||||
emit(f"{reason}; using local log.")
|
||||
return gate_is_due()
|
||||
@ -45,7 +82,7 @@ def cmd_gate(emit: Callable[[str], None], *, check: bool, demo: bool) -> int:
|
||||
a timer reads; ``--demo`` always shows a safe demo window; bare ``gate``
|
||||
shows the real lock only when one is due. Both real modes route through
|
||||
:func:`_should_lock`, which -- only when a lock is otherwise due -- pulls
|
||||
the shared log first (via :func:`pull_shared_log`) so a meal just logged on
|
||||
the shared log first (via :func:`pull_peer_logs`) so a meal just logged on
|
||||
the phone unlocks without a manual re-entry. A flock guard stops a second
|
||||
window from stacking on top of the first, and a window-opening mode first
|
||||
waits for the X display so a session-start launch never crashes unshown.
|
||||
@ -77,7 +114,10 @@ def cmd_gate(emit: Callable[[str], None], *, check: bool, demo: bool) -> int:
|
||||
if not wait_for_display():
|
||||
emit("display not ready yet; will retry on the next timer tick.")
|
||||
return 0
|
||||
MealGate(demo_mode=demo).run()
|
||||
# Via the module object, not a bare name: ``MealGate`` is resolved by
|
||||
# the lazy ``__getattr__`` above, and a test's ``patch.object`` sets a
|
||||
# real module attribute that must win over it.
|
||||
sys.modules[__name__].MealGate(demo_mode=demo).run()
|
||||
finally:
|
||||
release_gate_lock(handle)
|
||||
# Publish only once ``run()`` has returned -- i.e. the mainloop has ended and
|
||||
|
||||
@ -8,16 +8,37 @@ of one file.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib import import_module
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import RemoteSyncError
|
||||
|
||||
from diet_guard._sync import SyncError, run_sync
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import argparse
|
||||
from collections.abc import Callable
|
||||
|
||||
# ``_cli_args`` imports this module just to register the subparser, but
|
||||
# ``crdt_sync``/``_sync`` drag in ``requests`` (~78ms). Only the ``sync``
|
||||
# command itself needs them, so every other subcommand -- notably the gate's
|
||||
# frequent ``--check`` -- no longer pays for an HTTP stack it will not use.
|
||||
#
|
||||
# A module-level ``__getattr__`` (PEP 562) rather than function-local imports
|
||||
# so ``patch.object(_cli_sync, "run_sync", ...)`` still resolves.
|
||||
_LAZY_ATTRS = {
|
||||
"run_sync": ("diet_guard._sync", "run_sync"),
|
||||
"SyncError": ("diet_guard._sync", "SyncError"),
|
||||
"RemoteSyncError": ("crdt_sync", "RemoteSyncError"),
|
||||
}
|
||||
|
||||
|
||||
def __getattr__(name: str) -> object:
|
||||
"""Resolve a deferred sync import on first attribute access."""
|
||||
target = _LAZY_ATTRS.get(name)
|
||||
if target is None:
|
||||
msg = f"module {__name__!r} has no attribute {name!r}"
|
||||
raise AttributeError(msg)
|
||||
module_name, attr = target
|
||||
return getattr(import_module(module_name), attr)
|
||||
|
||||
|
||||
def register_sync_subparser(sub: argparse._SubParsersAction) -> None:
|
||||
"""Register the ``sync`` subcommand on ``sub``."""
|
||||
@ -43,12 +64,13 @@ def cmd_sync(emit: Callable[[str], None]) -> int:
|
||||
Returns:
|
||||
0 on a successful sync, 1 if it could not run or failed partway.
|
||||
"""
|
||||
module = sys.modules[__name__]
|
||||
try:
|
||||
merged = run_sync()
|
||||
except SyncError as exc:
|
||||
merged = module.run_sync()
|
||||
except module.SyncError as exc:
|
||||
emit(f"sync not configured: {exc}")
|
||||
return 1
|
||||
except RemoteSyncError as exc:
|
||||
except module.RemoteSyncError as exc:
|
||||
# The shared base, not GitHubSyncError: Firebase's errors are siblings
|
||||
# of GitHub's, so catching only the latter let the primary backend's
|
||||
# failures crash this timer-driven command with a traceback.
|
||||
|
||||
@ -110,3 +110,14 @@ SYNC_DEVICE_ID_FILE: Path = DATA_DIR / ".device_id"
|
||||
# mode 600. Never committed -- this path is outside the repo entirely.
|
||||
SYNC_TOKEN_FILE: Path = Path.home() / ".config" / "diet_guard" / "sync_token"
|
||||
SYNC_TIMEOUT_SECONDS: float = 10.0
|
||||
|
||||
#: Per-request budget for a pull the user is actively waiting on (the gate's
|
||||
#: pre-lock refresh and the lock screen's "Fetch from sync" button).
|
||||
#:
|
||||
#: Deliberately far below :data:`SYNC_TIMEOUT_SECONDS`: those paths run 1-2
|
||||
#: requests and must resolve inside a second, whereas the background tick can
|
||||
#: afford to be patient. The default is worse than it looks -- ``crdt_sync``
|
||||
#: v0.6.0's ``firebase_client_for`` takes no timeout at all, so Firebase falls
|
||||
#: back to *15s per request* and one hung session refresh stalls the lock
|
||||
#: window. The journal records five such refresh failures in five days.
|
||||
INTERACTIVE_TIMEOUT_SECONDS: float = 2.0
|
||||
|
||||
@ -13,9 +13,10 @@ the log/state or CLI layers.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib import import_module
|
||||
import logging
|
||||
|
||||
import requests
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard._constants import (
|
||||
DEFAULT_PORTION_GRAMS,
|
||||
@ -26,8 +27,39 @@ from diet_guard._constants import (
|
||||
)
|
||||
from diet_guard._estimator import Nutrition, _as_float, manual
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from types import ModuleType
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ``requests`` costs ~70ms to import and this module is reachable from every
|
||||
# CLI subcommand via ``_resolve`` -> ``_cli_log``, so importing it eagerly
|
||||
# taxed ``gate --check`` -- which never looks a food up. Only the Open Food
|
||||
# Facts calls below need it, and those are network calls already.
|
||||
#
|
||||
# A module-level ``__getattr__`` (PEP 562) rather than function-local imports
|
||||
# so ``patch("diet_guard._estimator_off.requests")`` still resolves: the patch
|
||||
# sets a real module attribute, which takes precedence over this hook.
|
||||
def _requests() -> ModuleType:
|
||||
"""Return the ``requests`` module, imported on first use.
|
||||
|
||||
Both call sites below go through this rather than a bare global: a module
|
||||
``__getattr__`` does not fire for name lookups *inside* its own module, and
|
||||
``sys.modules[__name__].requests`` is what lets the suite keep patching
|
||||
``diet_guard._estimator_off.requests``.
|
||||
"""
|
||||
return sys.modules[__name__].requests
|
||||
|
||||
|
||||
def __getattr__(name: str) -> object:
|
||||
"""Resolve the deferred ``requests`` import on first attribute access."""
|
||||
if name != "requests":
|
||||
msg = f"module {__name__!r} has no attribute {name!r}"
|
||||
raise AttributeError(msg)
|
||||
return import_module("requests")
|
||||
|
||||
|
||||
# Open Food Facts nutriment field names (values are "per 100 g").
|
||||
_OFF_KCAL_FIELD = "energy-kcal_100g"
|
||||
_OFF_PROTEIN_FIELD = "proteins_100g"
|
||||
@ -53,7 +85,7 @@ def _off_search(term: str) -> list[dict[str, object]]:
|
||||
"fields": "product_name,nutriments,serving_quantity",
|
||||
"page_size": str(OFF_PAGE_SIZE),
|
||||
}
|
||||
response = requests.get(
|
||||
response = _requests().get(
|
||||
OFF_SEARCH_URL,
|
||||
params=params,
|
||||
headers={"User-Agent": OFF_USER_AGENT},
|
||||
@ -159,7 +191,7 @@ def off_candidates(
|
||||
"""
|
||||
try:
|
||||
products = _off_search(description)
|
||||
except requests.RequestException as exc:
|
||||
except _requests().RequestException as exc:
|
||||
_logger.warning("Open Food Facts request failed: %s", exc)
|
||||
return []
|
||||
return [
|
||||
|
||||
@ -52,6 +52,7 @@ from gatelock import (
|
||||
LockConfig,
|
||||
LockWindow,
|
||||
SurfaceInfo,
|
||||
wait_for_turn,
|
||||
)
|
||||
|
||||
from diet_guard._gate import due_slots
|
||||
@ -151,6 +152,9 @@ class MealGate(_GateCalendar):
|
||||
disable_vt=config.resolved_disable_vt(),
|
||||
)
|
||||
arbiter.publish()
|
||||
# Wait with nothing on screen for any stronger claim; never exits
|
||||
# here, so a higher-ranked locker means "later", never "skip".
|
||||
wait_for_turn(arbiter)
|
||||
arbiter.acquire_holder()
|
||||
self._lock = LockWindow(self.root, config, hooks=self, arbiter=arbiter)
|
||||
self._vars = make_vars(self.root)
|
||||
|
||||
59
diet_guard/_gatelock_fetch.py
Normal file
59
diet_guard/_gatelock_fetch.py
Normal file
@ -0,0 +1,59 @@
|
||||
"""Off-thread plumbing for the lock screen's "Fetch from sync" button.
|
||||
|
||||
Split out of :mod:`._gatelock_mealflow`, which is already near the repo's
|
||||
250-line cap.
|
||||
|
||||
The pull used to run on the Tk thread, so the fullscreen lock froze for the
|
||||
whole tick -- measured at ~18-27s against the live remote, and unbounded in
|
||||
the worst case because the Firebase client's default timeout is 15s *per
|
||||
request*. A user staring at a dead window is exactly the experience the gate
|
||||
must not create.
|
||||
|
||||
Two rules shape the design:
|
||||
|
||||
* **The worker touches no widget.** Tcl is not thread-safe, and that includes
|
||||
``after`` -- so the worker only ``put``s its result on a queue, and a poll
|
||||
scheduled on the Tk thread picks it up. That also makes the completion path
|
||||
testable with no thread at all: put a result, call the poll, assert.
|
||||
* **The worker does not write the log either.** :func:`pull_shared_log`
|
||||
persists the merged result, so running it while the user types would let a
|
||||
merge snapshot taken *before* their meal was entered land *after* it,
|
||||
silently dropping the entry. The button is therefore disabled for the
|
||||
duration, which is both the race fix and the reentrancy guard.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
#: How often the Tk thread checks whether the worker has finished.
|
||||
FETCH_POLL_MS = 50
|
||||
|
||||
|
||||
def start_fetch(pull: Callable[[], str | None]) -> queue.Queue[str | None]:
|
||||
"""Run ``pull`` on a daemon thread; return the queue its result lands on.
|
||||
|
||||
Daemon so a hung request can never keep the process alive after the window
|
||||
is gone -- the gate is a ``Type=oneshot`` unit and must exit.
|
||||
"""
|
||||
result: queue.Queue[str | None] = queue.Queue(maxsize=1)
|
||||
|
||||
def _worker() -> None:
|
||||
"""Runs OFF the Tk thread. Touches no widget, by construction."""
|
||||
reason: str | None = "sync failed (unexpected error)"
|
||||
try:
|
||||
reason = pull()
|
||||
finally:
|
||||
# Always feed the queue, even if ``pull`` raised: this thread has
|
||||
# nowhere to propagate to, so an escaping exception would leave the
|
||||
# poll waiting forever with the button disabled and the user stuck.
|
||||
# ``pull`` is already fail-closed, so this is the unexpected case.
|
||||
result.put(reason)
|
||||
|
||||
threading.Thread(target=_worker, daemon=True).start()
|
||||
return result
|
||||
@ -11,17 +11,19 @@ calorie/macro dashboard it calls into lives in :mod:`._gatelock_dashboard`.
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import queue
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from diet_guard._foodbank import remember_food
|
||||
from diet_guard._gate import due_slots
|
||||
from diet_guard._gatelock_dashboard import _GateDashboard
|
||||
from diet_guard._gatelock_fetch import FETCH_POLL_MS, start_fetch
|
||||
from diet_guard._gatelock_ui import ERR, FG, UNIT_GRAMS
|
||||
from diet_guard._resolve import lookup_candidates
|
||||
from diet_guard._slots import slot_label
|
||||
from diet_guard._state import log_meal
|
||||
from diet_guard._sync import pull_shared_log
|
||||
from diet_guard._sync_refresh import pull_peer_logs
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from diet_guard._estimator import Nutrition
|
||||
@ -33,6 +35,11 @@ _UNLOCK_DELAY_MS = 1200
|
||||
class _GateMealFlow(_GateDashboard):
|
||||
"""Submit/lookup/log flow for a logged food."""
|
||||
|
||||
#: The in-flight fetch's result queue, or None when no fetch is running.
|
||||
#: Doubles as the poll's own guard: a stray poll after completion finds
|
||||
#: None and stops rather than blocking on an empty queue forever.
|
||||
_fetch_result: queue.Queue[str | None] | None = None
|
||||
|
||||
# -- slot walk ------------------------------------------------------------
|
||||
|
||||
def _clear_inputs(self) -> None:
|
||||
@ -164,15 +171,44 @@ class _GateMealFlow(_GateDashboard):
|
||||
|
||||
For a meal already logged on another device (typically the phone) that
|
||||
has not yet propagated here: rather than re-entering it to unlock, the
|
||||
user pulls it in. The pull blocks the window briefly (bounded by the
|
||||
sync timeout) and fails closed -- a failure leaves the lock untouched.
|
||||
user pulls it in.
|
||||
|
||||
The pull is the *narrow* one (:func:`pull_peer_logs`) and runs on a
|
||||
worker thread, so the window stays live. It used to run the full tick
|
||||
inline and froze the fullscreen lock for its whole duration (~18-27s
|
||||
measured). The button's question is the same as the gate's -- "did a
|
||||
peer log this slot?" -- and :meth:`_reconcile_after_fetch` reads only
|
||||
``due_slots()``, so the budget and food banks it dropped were never
|
||||
consulted here; the full tick still runs once the window closes.
|
||||
Measured at ~92ms against the live remote.
|
||||
|
||||
Fails closed: a failure leaves the lock untouched. A second click while
|
||||
a fetch is in flight is ignored, which is the reentrancy guard and the
|
||||
write-race fix in one -- two workers would race two log writes and
|
||||
orphan one result.
|
||||
"""
|
||||
if self.demo_mode:
|
||||
self._set_status("Fetch from sync is only available on the real lock.")
|
||||
return
|
||||
if self._fetch_result is not None:
|
||||
# Already fetching. Without this a double-click starts a second
|
||||
# worker, orphans the first result and races two log writes.
|
||||
return
|
||||
self._set_status("Fetching from sync…")
|
||||
self.root.update_idletasks()
|
||||
reason = pull_shared_log()
|
||||
self._fetch_result = start_fetch(pull_peer_logs)
|
||||
self.root.after(FETCH_POLL_MS, self._poll_fetch)
|
||||
|
||||
def _poll_fetch(self) -> None:
|
||||
"""On the Tk thread: pick up the worker's result once it lands."""
|
||||
result = self._fetch_result
|
||||
if result is None:
|
||||
return
|
||||
try:
|
||||
reason = result.get_nowait()
|
||||
except queue.Empty:
|
||||
self.root.after(FETCH_POLL_MS, self._poll_fetch)
|
||||
return
|
||||
self._fetch_result = None
|
||||
if reason is not None:
|
||||
self._set_status(f"{reason} — still locked.", error=True)
|
||||
return
|
||||
|
||||
@ -53,6 +53,8 @@ from diet_guard.sync_merge import (
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
from diet_guard._state import (
|
||||
DayLog,
|
||||
)
|
||||
@ -86,10 +88,11 @@ def _pull_remote_logs(
|
||||
client: RemoteStore,
|
||||
remote_revs: dict[str, str],
|
||||
state: SyncState,
|
||||
seen_revs: dict[str, str],
|
||||
*,
|
||||
identity: DeviceIdentity,
|
||||
) -> list[Log]:
|
||||
"""Return every other device's last-pushed log, skipping this one.
|
||||
device_ids: Sequence[str],
|
||||
) -> tuple[list[Log], dict[str, str]]:
|
||||
"""Return every other device's last-pushed log, plus the revisions seen.
|
||||
|
||||
A device whose pushed file is corrupt, truncated, or otherwise
|
||||
unparsable (new or old wire format) is logged and skipped, same as one
|
||||
@ -103,7 +106,8 @@ def _pull_remote_logs(
|
||||
day, so re-reading an unchanged peer is pure waste.
|
||||
"""
|
||||
remote_logs: list[Log] = []
|
||||
for device_id in client.list_directory(_DEVICES_DIR):
|
||||
seen_revs: dict[str, str] = {}
|
||||
for device_id in device_ids:
|
||||
if identity.is_own(device_id):
|
||||
continue
|
||||
remote_rev = remote_revs.get(device_id)
|
||||
@ -123,7 +127,7 @@ def _pull_remote_logs(
|
||||
_logger.warning("Unparsable log pushed by device %r, skipping", device_id)
|
||||
continue
|
||||
seen_revs[device_id] = remote_rev or revision_of(text)
|
||||
return remote_logs
|
||||
return remote_logs, seen_revs
|
||||
|
||||
|
||||
def run_sync() -> DayLog:
|
||||
@ -152,12 +156,17 @@ def run_sync() -> DayLog:
|
||||
state_store = FileSyncStateStore(SYNC_STATE_FILE)
|
||||
state = state_store.load()
|
||||
remote_revs = _remote_revisions(client)
|
||||
seen_revs: dict[str, str] = {}
|
||||
device_ids = list(client.list_directory(_DEVICES_DIR))
|
||||
|
||||
merged = daylog_to_log(read_raw_log())
|
||||
for remote_log in _pull_remote_logs(
|
||||
client, remote_revs, state, seen_revs, identity
|
||||
):
|
||||
remote_logs, seen_revs = _pull_remote_logs(
|
||||
client,
|
||||
remote_revs,
|
||||
state,
|
||||
identity=identity,
|
||||
device_ids=device_ids,
|
||||
)
|
||||
for remote_log in remote_logs:
|
||||
merged = merge_logs(merged, remote_log)
|
||||
|
||||
merged_daylog = log_to_daylog(merged)
|
||||
@ -167,9 +176,9 @@ def run_sync() -> DayLog:
|
||||
}
|
||||
write_raw_log(resigned)
|
||||
rebuild_food_bank(resigned)
|
||||
_sync_budget(client)
|
||||
_sync_food_bank(client)
|
||||
_sync_manual_bank(client)
|
||||
_sync_budget(client, device_ids)
|
||||
_sync_food_bank(client, device_ids)
|
||||
_sync_manual_bank(client, device_ids)
|
||||
|
||||
push_log = daylog_to_log(resigned)
|
||||
push_json = json.dumps(
|
||||
|
||||
@ -17,7 +17,7 @@ import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import merge_logs
|
||||
from crdt_sync import MirrorSyncClient, merge_logs
|
||||
|
||||
from diet_guard._budget import read_raw_record, write_raw_record
|
||||
from diet_guard._budget_history import (
|
||||
@ -38,7 +38,6 @@ from diet_guard._meal_schedule_store import (
|
||||
write_raw_history as write_raw_schedule,
|
||||
)
|
||||
from diet_guard._sync_paths import (
|
||||
_DEVICES_DIR,
|
||||
_device_budget_path,
|
||||
_device_food_bank_path,
|
||||
_device_manual_bank_path,
|
||||
@ -58,12 +57,14 @@ from diet_guard.sync_merge import (
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
from crdt_sync import GitHubSyncClient
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _sync_food_bank(client: GitHubSyncClient) -> None:
|
||||
def _sync_food_bank(client: GitHubSyncClient, device_ids: Sequence[str]) -> None:
|
||||
"""Pull, merge, persist and push the log-derived food bank.
|
||||
|
||||
Runs *after* the local rebuild in :func:`run_sync`, so this device's own
|
||||
@ -87,7 +88,7 @@ def _sync_food_bank(client: GitHubSyncClient) -> None:
|
||||
identity = device_identity()
|
||||
local = read_food_bank()
|
||||
merged = food_bank_to_log(local)
|
||||
for device_id in client.list_directory(_DEVICES_DIR):
|
||||
for device_id in device_ids:
|
||||
if identity.is_own(device_id):
|
||||
continue
|
||||
text = client.get_file_text(_device_food_bank_path(device_id))
|
||||
@ -120,7 +121,27 @@ def _sync_food_bank(client: GitHubSyncClient) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _sync_manual_bank(client: GitHubSyncClient) -> None:
|
||||
def _primary_only_text(client: GitHubSyncClient, path: str) -> str | None:
|
||||
"""Read ``path`` from the primary backend, skipping the mirror fallthrough.
|
||||
|
||||
``MirrorSyncClient.get_file_text`` treats a ``None`` from the primary as
|
||||
"this device has not migrated yet" and consults the mirror. That is right
|
||||
for the log and the derived bank, whose data really can live on either
|
||||
side -- but for the *curated* bank it is 21 GitHub round trips per tick
|
||||
(~406ms each, ~17s total) that return ``{}`` and nothing else.
|
||||
|
||||
Verified before narrowing, and worth re-checking before widening again:
|
||||
reading every peer's curated bank straight off the mirror found 23 absent,
|
||||
2 empty and **zero** non-empty. No curated food exists on the mirror alone,
|
||||
so nothing is lost. A client with no ``primary`` (the GitHub-only case) is
|
||||
read directly, which is the same backend either way.
|
||||
"""
|
||||
if isinstance(client, MirrorSyncClient):
|
||||
return client.primary.get_file_text(path)
|
||||
return client.get_file_text(path)
|
||||
|
||||
|
||||
def _sync_manual_bank(client: GitHubSyncClient, device_ids: Sequence[str]) -> None:
|
||||
"""Pull, merge, persist and push the hand-curated food bank.
|
||||
|
||||
Curated entries are the one part of the bank that is not derivable from
|
||||
@ -130,10 +151,10 @@ def _sync_manual_bank(client: GitHubSyncClient) -> None:
|
||||
"""
|
||||
identity = device_identity()
|
||||
merged = manual_bank_to_log(read_manual_bank())
|
||||
for device_id in client.list_directory(_DEVICES_DIR):
|
||||
for device_id in device_ids:
|
||||
if identity.is_own(device_id):
|
||||
continue
|
||||
text = client.get_file_text(_device_manual_bank_path(device_id))
|
||||
text = _primary_only_text(client, _device_manual_bank_path(device_id))
|
||||
if text is None:
|
||||
continue
|
||||
try:
|
||||
@ -159,7 +180,7 @@ def _sync_manual_bank(client: GitHubSyncClient) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _sync_budget(client: GitHubSyncClient) -> None:
|
||||
def _sync_budget(client: GitHubSyncClient, device_ids: Sequence[str]) -> None:
|
||||
"""Pull other devices' budgets, merge, write locally, push this device's.
|
||||
|
||||
Runs in the same tick as the food-log sync, reusing the already
|
||||
@ -172,7 +193,7 @@ def _sync_budget(client: GitHubSyncClient) -> None:
|
||||
"""
|
||||
identity = device_identity()
|
||||
merged = budget_to_log(read_raw_record(), load_entries(), load_schedule_entries())
|
||||
for device_id in client.list_directory(_DEVICES_DIR):
|
||||
for device_id in device_ids:
|
||||
if identity.is_own(device_id):
|
||||
continue
|
||||
text = client.get_file_text(_device_budget_path(device_id))
|
||||
|
||||
@ -30,6 +30,7 @@ from crdt_sync import (
|
||||
)
|
||||
|
||||
from diet_guard._constants import (
|
||||
INTERACTIVE_TIMEOUT_SECONDS,
|
||||
SYNC_REPO_NAME,
|
||||
SYNC_REPO_OWNER,
|
||||
SYNC_TIMEOUT_SECONDS,
|
||||
@ -129,3 +130,38 @@ def _read_token() -> str:
|
||||
msg = f"{SYNC_TOKEN_FILE} is empty"
|
||||
raise SyncError(msg)
|
||||
return token
|
||||
|
||||
|
||||
def _apply_timeout(client: RemoteStore, seconds: float) -> None:
|
||||
"""Tighten ``client``'s per-request budget, including any mirrored halves.
|
||||
|
||||
Reaches for the private ``_timeout_seconds`` because ``crdt_sync`` v0.6.0
|
||||
exposes no other lever: ``firebase_client_for`` accepts no timeout, so a
|
||||
Firebase client silently uses its 15s default and one hung request stalls
|
||||
a path the user is watching. The attribute is read fresh on every request,
|
||||
so assigning it here is enough.
|
||||
|
||||
Set via ``vars()`` rather than ``setattr`` so a client that does not carry
|
||||
the attribute is left alone instead of gaining a meaningless one. The clean
|
||||
fix is a ``timeout_seconds`` kwarg upstream; until that ships this keeps the
|
||||
interactive paths bounded.
|
||||
"""
|
||||
for target in (
|
||||
client,
|
||||
getattr(client, "primary", None),
|
||||
getattr(client, "mirror", None),
|
||||
):
|
||||
if target is not None and "_timeout_seconds" in vars(target):
|
||||
vars(target)["_timeout_seconds"] = seconds
|
||||
|
||||
|
||||
def _client_for_interactive_run() -> RemoteStore:
|
||||
"""Return a sync client budgeted for a path the user is waiting on.
|
||||
|
||||
Same backends as :func:`_client_for_run`, but with
|
||||
:data:`~diet_guard._constants.INTERACTIVE_TIMEOUT_SECONDS` in place of the
|
||||
background tick's much longer budget.
|
||||
"""
|
||||
client = _client_for_run()
|
||||
_apply_timeout(client, INTERACTIVE_TIMEOUT_SECONDS)
|
||||
return client
|
||||
|
||||
@ -25,13 +25,27 @@ day that goes unlogged raises a lock by construction.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib import import_module
|
||||
import logging
|
||||
|
||||
from diet_guard._sync import pull_shared_log
|
||||
import sys
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ``_sync`` pulls in ``crdt_sync`` -> ``requests`` (~78ms), and the gate's
|
||||
# common path -- no lock due -- never publishes. Deferring the import is what
|
||||
# lets ``gate --check`` decide without loading an HTTP stack it will not use.
|
||||
#
|
||||
# A module-level ``__getattr__`` (PEP 562) rather than a function-local import
|
||||
# so ``patch.object(_sync_events, "pull_shared_log", ...)`` still resolves.
|
||||
def __getattr__(name: str) -> object:
|
||||
"""Resolve the deferred sync import on first attribute access."""
|
||||
if name != "pull_shared_log":
|
||||
msg = f"module {__name__!r} has no attribute {name!r}"
|
||||
raise AttributeError(msg)
|
||||
return import_module("diet_guard._sync").pull_shared_log
|
||||
|
||||
|
||||
def publish_after_log() -> str | None:
|
||||
"""Run a full sync tick after a local write, swallowing any outage.
|
||||
|
||||
@ -44,7 +58,7 @@ def publish_after_log() -> str | None:
|
||||
it could not -- callers that have somewhere to show it (the CLI) print
|
||||
it; callers that do not (the gate, the MCP tool) let it fall to the log.
|
||||
"""
|
||||
reason = pull_shared_log()
|
||||
reason = sys.modules[__name__].pull_shared_log()
|
||||
if reason is not None:
|
||||
_logger.info("post-log sync skipped: %s", reason)
|
||||
return reason
|
||||
|
||||
201
diet_guard/_sync_refresh.py
Normal file
201
diet_guard/_sync_refresh.py
Normal file
@ -0,0 +1,201 @@
|
||||
"""The gate's narrow, pre-lock refresh: peer logs only, no push.
|
||||
|
||||
``_sync.run_sync`` is the *full* tick -- peer logs, the budget, both food
|
||||
banks, a rebuild and a push. That is the right thing to run after a meal is
|
||||
logged, and it is what :func:`~diet_guard._sync_events.publish_after_log`
|
||||
still does. It is the wrong thing to run *in front of a fullscreen lock*: the
|
||||
banks alone measured ~21s against the live remote (the curated bank is absent
|
||||
on Firebase for every peer, so each of ~21 peers fell through to a GitHub
|
||||
round trip that returned ``{}``), and the budget loop another ~2.6s.
|
||||
|
||||
The gate has exactly one question to answer -- *"has a peer already logged
|
||||
this slot?"* -- and only the peer **logs** can answer it. So this module does
|
||||
that and nothing else:
|
||||
|
||||
* one bulk read of the revision map (~83ms, a single request),
|
||||
* a fetch of only those peers whose revision actually moved,
|
||||
* merge, re-sign, write.
|
||||
|
||||
No budget, no banks, no ``rebuild_food_bank``, and **no push**. The full tick
|
||||
still runs after the window closes, so nothing is permanently skipped -- the
|
||||
exhaustive pass is merely moved off the path the user waits on.
|
||||
|
||||
**Accepted trade:** a budget edited on the phone is not visible in the lock
|
||||
window's dashboard until that post-window tick. It cannot affect the lock
|
||||
*decision*, which is why it is safe to defer, but it is user-visible and so
|
||||
recorded here rather than left implicit.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import (
|
||||
FileSyncStateStore,
|
||||
Log,
|
||||
RemoteSyncError,
|
||||
SyncState,
|
||||
merge_logs,
|
||||
revision_of,
|
||||
)
|
||||
|
||||
from diet_guard import _sync
|
||||
from diet_guard._device import device_identity
|
||||
from diet_guard._state_sync import read_raw_log, resign_entry, write_raw_log
|
||||
from diet_guard._sync import _remote_revisions
|
||||
from diet_guard._sync_client import _client_for_interactive_run
|
||||
from diet_guard._sync_errors import SyncError
|
||||
from diet_guard._sync_paths import _DEVICES_DIR, _device_log_path
|
||||
from diet_guard.sync_merge import daylog_to_log, log_to_daylog, parse_remote_log
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from crdt_sync import RemoteStore
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _candidate_peers(
|
||||
client: RemoteStore,
|
||||
remote_revs: dict[str, str],
|
||||
state: SyncState,
|
||||
) -> list[str]:
|
||||
"""Return the device ids worth considering, without a directory listing.
|
||||
|
||||
``list_directory`` is the single most expensive call in a tick (~445ms,
|
||||
because the mirrored GitHub half alone is ~360ms), and the revision map
|
||||
already names every peer that has ever published one. Union it with the
|
||||
peers we have merged before so a device that stopped publishing revisions
|
||||
is still reachable.
|
||||
|
||||
Falls back to the real listing when the revision map is empty -- a
|
||||
GitHub-only device has no ``get_string_map``, and there "no revisions"
|
||||
means "no information", not "no peers".
|
||||
"""
|
||||
if not remote_revs:
|
||||
return list(client.list_directory(_DEVICES_DIR))
|
||||
return sorted(set(remote_revs) | set(state.peer_revs))
|
||||
|
||||
|
||||
def _peer_is_current(
|
||||
device_id: str,
|
||||
remote_revs: dict[str, str],
|
||||
state: SyncState,
|
||||
) -> bool:
|
||||
"""Return True when ``device_id`` holds nothing this device has not merged.
|
||||
|
||||
Two ways to be current, and the second is specific to this narrow pass:
|
||||
|
||||
* the peer publishes a revision equal to the one already merged, or
|
||||
* the peer publishes **no** revision but has been merged before.
|
||||
|
||||
The second rule is what removes the standing ~1.25s cost of the frozen
|
||||
legacy role-id directories, which can never satisfy the first. It is sound
|
||||
only because this pass is *not* the authoritative one: the post-window full
|
||||
tick still reads every peer exhaustively, and a union CRDT cannot lose a
|
||||
record that arrives a tick later.
|
||||
|
||||
Membership is tested with ``in``, never ``.get(...) is not None`` --
|
||||
``peer_revs`` legitimately holds explicit null values, and treating those
|
||||
as "never seen" would re-download them on every single tick forever.
|
||||
"""
|
||||
remote_rev = remote_revs.get(device_id)
|
||||
if remote_rev is None:
|
||||
return device_id in state.peer_revs
|
||||
return remote_rev == state.peer_revs.get(device_id)
|
||||
|
||||
|
||||
def _merge_peer_logs(
|
||||
client: RemoteStore,
|
||||
peers: list[str],
|
||||
remote_revs: dict[str, str],
|
||||
merged: Log,
|
||||
seen: dict[str, str],
|
||||
) -> tuple[Log, bool]:
|
||||
"""Merge each peer's pushed log into ``merged``; report whether any landed."""
|
||||
changed = False
|
||||
for device_id in peers:
|
||||
text = client.get_file_text(_device_log_path(device_id))
|
||||
if text is None:
|
||||
continue
|
||||
try:
|
||||
merged = merge_logs(merged, parse_remote_log(text))
|
||||
except (TypeError, KeyError, ValueError, json.JSONDecodeError):
|
||||
# A corrupt push must be retried next tick, not remembered as
|
||||
# merged -- so deliberately not recorded in ``seen``.
|
||||
_logger.warning("Unparsable log pushed by device %r, skipping", device_id)
|
||||
continue
|
||||
seen[device_id] = remote_revs.get(device_id) or revision_of(text)
|
||||
changed = True
|
||||
return merged, changed
|
||||
|
||||
|
||||
def refresh_peer_logs() -> None:
|
||||
"""Merge any newly-published peer log into the local one.
|
||||
|
||||
Raises:
|
||||
SyncError: If no backend is configured.
|
||||
crdt_sync.RemoteSyncError: On any transport failure.
|
||||
"""
|
||||
client = _client_for_interactive_run()
|
||||
identity = device_identity()
|
||||
# Via the module, not a direct import: the suite redirects
|
||||
# ``_sync.SYNC_STATE_FILE`` to a tmp path, and a private copy of the
|
||||
# constant would escape that redirect and write real user state.
|
||||
state_store = FileSyncStateStore(_sync.SYNC_STATE_FILE)
|
||||
state = state_store.load()
|
||||
remote_revs = _remote_revisions(client)
|
||||
|
||||
peers = [
|
||||
device_id
|
||||
for device_id in _candidate_peers(client, remote_revs, state)
|
||||
if not identity.is_own(device_id)
|
||||
and not _peer_is_current(device_id, remote_revs, state)
|
||||
]
|
||||
if not peers:
|
||||
return
|
||||
|
||||
seen: dict[str, str] = {}
|
||||
merged, changed = _merge_peer_logs(
|
||||
client, peers, remote_revs, daylog_to_log(read_raw_log()), seen
|
||||
)
|
||||
if not changed:
|
||||
return
|
||||
|
||||
# Re-sign every entry, not just the newly arrived ones: a signature made on
|
||||
# another device is not valid under this device's key, and ``load_log``
|
||||
# drops unsigned entries outright -- that is how a phone-logged meal would
|
||||
# vanish on the very next read.
|
||||
resigned = {
|
||||
day: [resign_entry(entry) for entry in entries]
|
||||
for day, entries in log_to_daylog(merged).items()
|
||||
}
|
||||
# Log first, state second. If the state landed and this write failed, a peer
|
||||
# would be recorded as merged while its records were absent -- silent loss.
|
||||
write_raw_log(resigned)
|
||||
# ``pushed_rev`` verbatim: this pass never pushes, and overwriting it would
|
||||
# convince the next full tick it had already published, silently making this
|
||||
# device invisible to every peer. ``peer_revs`` merged, not replaced: only
|
||||
# changed peers were visited, so a wholesale replace would drop the ~20
|
||||
# untouched entries and re-download all of them next tick.
|
||||
state_store.save(
|
||||
SyncState(
|
||||
pushed_rev=state.pushed_rev,
|
||||
peer_revs={**state.peer_revs, **seen},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def pull_peer_logs() -> str | None:
|
||||
"""Run :func:`refresh_peer_logs`, failing closed instead of raising.
|
||||
|
||||
Mirrors :func:`diet_guard._sync.pull_shared_log`'s contract exactly --
|
||||
``None`` on success, a short human-readable reason otherwise -- so the gate
|
||||
keeps its own local lock decision rather than failing open on an outage.
|
||||
"""
|
||||
try:
|
||||
refresh_peer_logs()
|
||||
except (SyncError, RemoteSyncError, OSError) as exc:
|
||||
return f"sync unavailable ({exc})"
|
||||
return None
|
||||
@ -155,6 +155,10 @@ def _isolate_state(tmp_path: Path) -> Iterator[None]:
|
||||
patch("diet_guard._cli_log.publish_after_log", return_value=None),
|
||||
patch("diet_guard._cli_gate.publish_after_log", return_value=None),
|
||||
patch("diet_guard._mcp.publish_after_log", return_value=None),
|
||||
# The gate's pre-lock refresh is a *second*, independent network
|
||||
# entry point (narrow peer-log pull, not the full tick). Without
|
||||
# this every test that reaches `_should_lock` hits the real remote.
|
||||
patch("diet_guard._cli_gate.pull_peer_logs", return_value=None),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@ -16,7 +16,7 @@ from diet_guard._state import log_meal
|
||||
|
||||
def _no_sync() -> object:
|
||||
"""Neutralize the pre-lock pull (as if it found nothing) for mode tests."""
|
||||
return patch.object(_cli_gate, "pull_shared_log", return_value=None)
|
||||
return patch.object(_cli_gate, "pull_peer_logs", return_value=None)
|
||||
|
||||
|
||||
class TestCmdGate:
|
||||
@ -73,7 +73,7 @@ class TestCmdGate:
|
||||
lines: list[str] = []
|
||||
with (
|
||||
patch.object(_cli_gate, "gate_is_due", side_effect=[True, False]),
|
||||
patch.object(_cli_gate, "pull_shared_log", return_value=None),
|
||||
patch.object(_cli_gate, "pull_peer_logs", return_value=None),
|
||||
patch.object(_cli_gate, "MealGate") as factory,
|
||||
):
|
||||
assert cmd_gate(lines.append, check=False, demo=False) == 0
|
||||
@ -161,7 +161,7 @@ class TestShouldLock:
|
||||
pull = MagicMock(return_value=None)
|
||||
with (
|
||||
patch.object(_cli_gate, "gate_is_due", return_value=False),
|
||||
patch.object(_cli_gate, "pull_shared_log", pull),
|
||||
patch.object(_cli_gate, "pull_peer_logs", pull),
|
||||
):
|
||||
assert _should_lock([].append) is False
|
||||
pull.assert_not_called()
|
||||
@ -171,7 +171,7 @@ class TestShouldLock:
|
||||
pull = MagicMock(return_value=None)
|
||||
with (
|
||||
patch.object(_cli_gate, "gate_is_due", side_effect=[True, False]),
|
||||
patch.object(_cli_gate, "pull_shared_log", pull),
|
||||
patch.object(_cli_gate, "pull_peer_logs", pull),
|
||||
):
|
||||
assert _should_lock([].append) is False
|
||||
pull.assert_called_once()
|
||||
@ -181,7 +181,7 @@ class TestShouldLock:
|
||||
pull = MagicMock(return_value=None)
|
||||
with (
|
||||
patch.object(_cli_gate, "gate_is_due", side_effect=[True, True]),
|
||||
patch.object(_cli_gate, "pull_shared_log", pull),
|
||||
patch.object(_cli_gate, "pull_peer_logs", pull),
|
||||
):
|
||||
assert _should_lock([].append) is True
|
||||
pull.assert_called_once()
|
||||
@ -192,7 +192,7 @@ class TestShouldLock:
|
||||
with (
|
||||
patch.object(_cli_gate, "gate_is_due", side_effect=[True, True]),
|
||||
patch.object(
|
||||
_cli_gate, "pull_shared_log", return_value="sync unavailable (x)"
|
||||
_cli_gate, "pull_peer_logs", return_value="sync unavailable (x)"
|
||||
),
|
||||
):
|
||||
assert _should_lock(lines.append) is True
|
||||
|
||||
@ -9,8 +9,8 @@ dashboard, and multi-item meals). The functional fake ``tk`` widgets and the
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from diet_guard import _gatelock_mealflow
|
||||
from diet_guard._budget import write_budget
|
||||
@ -99,12 +99,26 @@ class TestSlotWalk:
|
||||
unlock.assert_called_once()
|
||||
|
||||
|
||||
def _drive_fetch(gate: MealGate) -> None:
|
||||
"""Run a started fetch to completion, deterministically.
|
||||
|
||||
``_on_fetch_sync`` now hands the pull to a worker thread and schedules a
|
||||
poll via ``root.after``; under test ``after`` is a MagicMock, so nothing
|
||||
would ever pick the result up. Joining on the queue and calling the poll
|
||||
directly keeps these assertions synchronous without a sleep.
|
||||
"""
|
||||
result = gate._fetch_result
|
||||
assert result is not None, "no fetch was started"
|
||||
result.put(result.get(timeout=5))
|
||||
gate._poll_fetch()
|
||||
|
||||
|
||||
class TestFetchFromSync:
|
||||
"""The manual "Fetch from sync" button on the lock screen."""
|
||||
|
||||
def test_demo_mode_does_not_sync(self, gate: MealGate) -> None:
|
||||
"""In demo the button is inert and never touches the network."""
|
||||
with patch.object(_gatelock_mealflow, "pull_shared_log") as pull:
|
||||
with patch.object(_gatelock_mealflow, "pull_peer_logs") as pull:
|
||||
gate._on_fetch_sync()
|
||||
pull.assert_not_called()
|
||||
assert "only available on the real lock" in gate._vars.status.get()
|
||||
@ -115,10 +129,11 @@ class TestFetchFromSync:
|
||||
gate._pending = [8, 12]
|
||||
with patch.object(
|
||||
_gatelock_mealflow,
|
||||
"pull_shared_log",
|
||||
"pull_peer_logs",
|
||||
return_value="sync unavailable (x)",
|
||||
):
|
||||
gate._on_fetch_sync()
|
||||
_drive_fetch(gate)
|
||||
assert gate._pending == [8, 12]
|
||||
assert "still locked" in gate._vars.status.get()
|
||||
|
||||
@ -127,10 +142,11 @@ class TestFetchFromSync:
|
||||
gate.demo_mode = False
|
||||
gate._pending = [8, 12]
|
||||
with (
|
||||
patch.object(_gatelock_mealflow, "pull_shared_log", return_value=None),
|
||||
patch.object(_gatelock_mealflow, "pull_peer_logs", return_value=None),
|
||||
patch.object(_gatelock_mealflow, "due_slots", return_value=(8, 12)),
|
||||
):
|
||||
gate._on_fetch_sync()
|
||||
_drive_fetch(gate)
|
||||
assert gate._pending == [8, 12]
|
||||
assert "No new meals" in gate._vars.status.get()
|
||||
|
||||
@ -139,10 +155,11 @@ class TestFetchFromSync:
|
||||
gate.demo_mode = False
|
||||
gate._pending = [8, 12]
|
||||
with (
|
||||
patch.object(_gatelock_mealflow, "pull_shared_log", return_value=None),
|
||||
patch.object(_gatelock_mealflow, "pull_peer_logs", return_value=None),
|
||||
patch.object(_gatelock_mealflow, "due_slots", return_value=(12,)),
|
||||
):
|
||||
gate._on_fetch_sync()
|
||||
_drive_fetch(gate)
|
||||
assert gate._pending == [12]
|
||||
assert "Pulled 1 meal " in gate._vars.status.get()
|
||||
|
||||
@ -151,10 +168,11 @@ class TestFetchFromSync:
|
||||
gate.demo_mode = False
|
||||
gate._pending = [8, 12, 16]
|
||||
with (
|
||||
patch.object(_gatelock_mealflow, "pull_shared_log", return_value=None),
|
||||
patch.object(_gatelock_mealflow, "pull_peer_logs", return_value=None),
|
||||
patch.object(_gatelock_mealflow, "due_slots", return_value=(16,)),
|
||||
):
|
||||
gate._on_fetch_sync()
|
||||
_drive_fetch(gate)
|
||||
assert gate._pending == [16]
|
||||
assert "Pulled 2 meals" in gate._vars.status.get()
|
||||
|
||||
@ -163,9 +181,48 @@ class TestFetchFromSync:
|
||||
gate.demo_mode = False
|
||||
gate._pending = [8, 12]
|
||||
with (
|
||||
patch.object(_gatelock_mealflow, "pull_shared_log", return_value=None),
|
||||
patch.object(_gatelock_mealflow, "pull_peer_logs", return_value=None),
|
||||
patch.object(_gatelock_mealflow, "due_slots", return_value=()),
|
||||
):
|
||||
gate._on_fetch_sync()
|
||||
_drive_fetch(gate)
|
||||
assert gate._pending == []
|
||||
assert "unlocking" in gate._vars.status.get()
|
||||
|
||||
def test_poll_without_a_fetch_is_inert(self, gate: MealGate) -> None:
|
||||
"""A stray poll after completion must stop, not block on an empty queue."""
|
||||
gate._fetch_result = None
|
||||
|
||||
gate._poll_fetch() # must simply return
|
||||
|
||||
assert gate._fetch_result is None
|
||||
|
||||
def test_poll_rearms_while_the_worker_is_still_running(
|
||||
self, gate: MealGate
|
||||
) -> None:
|
||||
"""An empty queue means "not finished yet" -- reschedule, do not block."""
|
||||
import queue as _queue
|
||||
|
||||
gate.demo_mode = False
|
||||
gate._fetch_result = _queue.Queue()
|
||||
|
||||
gate._poll_fetch()
|
||||
|
||||
after = cast("MagicMock", gate.root.after)
|
||||
after.assert_called_with(_gatelock_mealflow.FETCH_POLL_MS, gate._poll_fetch)
|
||||
assert gate._fetch_result is not None
|
||||
|
||||
def test_a_second_click_while_fetching_is_ignored(self, gate: MealGate) -> None:
|
||||
"""Two workers would race two log writes and orphan one result."""
|
||||
gate.demo_mode = False
|
||||
with patch.object(
|
||||
_gatelock_mealflow, "pull_peer_logs", return_value=None
|
||||
) as pull:
|
||||
gate._on_fetch_sync()
|
||||
first = gate._fetch_result
|
||||
gate._on_fetch_sync() # second click, still in flight
|
||||
|
||||
assert gate._fetch_result is first
|
||||
_drive_fetch(gate)
|
||||
|
||||
assert pull.call_count == 1
|
||||
|
||||
@ -8,6 +8,7 @@ credentials a run actually requires (``_client_for_run``).
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from crdt_sync import ConfigError
|
||||
import pytest
|
||||
@ -125,3 +126,35 @@ class TestClientForRun:
|
||||
|
||||
with pytest.raises(_sync.SyncError):
|
||||
_sync_client._client_for_run()
|
||||
|
||||
|
||||
class TestInteractiveTimeout:
|
||||
"""The short per-request budget for paths the user is waiting on."""
|
||||
|
||||
def test_tightens_every_backend_half(self) -> None:
|
||||
"""A mirrored client must bound both halves, not just the primary."""
|
||||
client = SimpleNamespace(
|
||||
primary=SimpleNamespace(_timeout_seconds=15.0),
|
||||
mirror=SimpleNamespace(_timeout_seconds=10.0),
|
||||
)
|
||||
|
||||
_sync_client._apply_timeout(client, 2.0)
|
||||
|
||||
assert client.primary._timeout_seconds == 2.0
|
||||
assert client.mirror._timeout_seconds == 2.0
|
||||
|
||||
def test_a_client_without_the_attribute_is_left_alone(self) -> None:
|
||||
"""Never invent a setting on a backend that does not read one."""
|
||||
client = SimpleNamespace()
|
||||
|
||||
_sync_client._apply_timeout(client, 2.0)
|
||||
|
||||
assert not hasattr(client, "_timeout_seconds")
|
||||
|
||||
def test_a_bare_client_is_tightened_directly(self) -> None:
|
||||
"""Not every backend is mirrored; the unwrapped case must work too."""
|
||||
client = SimpleNamespace(_timeout_seconds=15.0)
|
||||
|
||||
_sync_client._apply_timeout(client, 2.0)
|
||||
|
||||
assert client._timeout_seconds == 2.0
|
||||
|
||||
35
diet_guard/tests/test_sync_banks_mirror.py
Normal file
35
diet_guard/tests/test_sync_banks_mirror.py
Normal file
@ -0,0 +1,35 @@
|
||||
"""Tests for the curated bank's primary-only read.
|
||||
|
||||
Split out of ``test_sync_banks.py`` to keep both files under the repo's
|
||||
250-line cap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from crdt_sync import MirrorSyncClient
|
||||
|
||||
from diet_guard import _sync_banks
|
||||
|
||||
|
||||
class TestPrimaryOnlyText:
|
||||
"""Reading the curated bank without the per-peer mirror fallthrough."""
|
||||
|
||||
def test_a_mirrored_client_reads_only_the_primary(self) -> None:
|
||||
"""The 17s/tick the fallthrough cost was spent fetching ``{}``."""
|
||||
primary = MagicMock()
|
||||
primary.get_file_text.return_value = None
|
||||
mirror = MagicMock()
|
||||
client = MirrorSyncClient(primary, mirror)
|
||||
|
||||
assert _sync_banks._primary_only_text(client, "some/path") is None
|
||||
mirror.get_file_text.assert_not_called()
|
||||
|
||||
def test_an_unmirrored_client_is_read_directly(self) -> None:
|
||||
"""GitHub-only devices have no primary/mirror split to skip."""
|
||||
client = MagicMock()
|
||||
client.get_file_text.return_value = "{}"
|
||||
|
||||
assert _sync_banks._primary_only_text(client, "some/path") == "{}"
|
||||
client.get_file_text.assert_called_once_with("some/path")
|
||||
@ -37,9 +37,14 @@ class TestPullSkipsOwnLegacyPath:
|
||||
"""
|
||||
client = _mock_client(devices=("pc", "phone"))
|
||||
state = SyncState(pushed_rev=None, peer_revs={})
|
||||
seen: dict[str, str] = {}
|
||||
|
||||
_sync._pull_remote_logs(client, {}, state, seen, device_identity())
|
||||
_, _seen = _sync._pull_remote_logs(
|
||||
client,
|
||||
{},
|
||||
state,
|
||||
identity=device_identity(),
|
||||
device_ids=("pc", "phone"),
|
||||
)
|
||||
|
||||
fetched = [call.args[0] for call in client.get_file_text.call_args_list]
|
||||
assert "diet-guard-sync/devices/pc/food_log.json" not in fetched
|
||||
@ -54,10 +59,13 @@ class TestPullSkipsOwnLegacyPath:
|
||||
"""
|
||||
client = _mock_client(devices=("pc",))
|
||||
state = SyncState(pushed_rev=None, peer_revs={})
|
||||
seen: dict[str, str] = {}
|
||||
|
||||
_sync._pull_remote_logs(
|
||||
client, {}, state, seen, DeviceIdentity(device_id=device_id())
|
||||
_, _seen = _sync._pull_remote_logs(
|
||||
client,
|
||||
{},
|
||||
state,
|
||||
identity=DeviceIdentity(device_id=device_id()),
|
||||
device_ids=("pc",),
|
||||
)
|
||||
|
||||
fetched = [call.args[0] for call in client.get_file_text.call_args_list]
|
||||
|
||||
@ -102,10 +102,13 @@ class TestPullSkipsUnchangedPeers:
|
||||
def test_skips_a_peer_whose_revision_is_unchanged(self) -> None:
|
||||
client = _mock_client(devices=("phone",))
|
||||
state = SyncState(pushed_rev=None, peer_revs={"phone": "rev-1"})
|
||||
seen: dict[str, str] = {}
|
||||
|
||||
logs = _sync._pull_remote_logs(
|
||||
client, {"phone": "rev-1"}, state, seen, device_identity()
|
||||
logs, seen = _sync._pull_remote_logs(
|
||||
client,
|
||||
{"phone": "rev-1"},
|
||||
state,
|
||||
identity=device_identity(),
|
||||
device_ids=("phone",),
|
||||
)
|
||||
|
||||
assert logs == []
|
||||
@ -119,10 +122,13 @@ class TestPullSkipsUnchangedPeers:
|
||||
files={"diet-guard-sync/devices/phone/food_log.json": text},
|
||||
)
|
||||
state = SyncState(pushed_rev=None, peer_revs={"phone": "rev-1"})
|
||||
seen: dict[str, str] = {}
|
||||
|
||||
_sync._pull_remote_logs(
|
||||
client, {"phone": "rev-2"}, state, seen, device_identity()
|
||||
_, seen = _sync._pull_remote_logs(
|
||||
client,
|
||||
{"phone": "rev-2"},
|
||||
state,
|
||||
identity=device_identity(),
|
||||
device_ids=("phone",),
|
||||
)
|
||||
|
||||
client.get_file_text.assert_called_once()
|
||||
|
||||
248
diet_guard/tests/test_sync_refresh.py
Normal file
248
diet_guard/tests/test_sync_refresh.py
Normal file
@ -0,0 +1,248 @@
|
||||
"""Tests for the gate's narrow, pre-lock refresh.
|
||||
|
||||
The full tick measured ~21s against the live remote, which is far too slow to
|
||||
sit in front of a fullscreen lock. ``_sync_refresh`` answers the gate's single
|
||||
question -- "has a peer already logged this slot?" -- from the peer logs alone.
|
||||
|
||||
The three state invariants below are the traps that make this pass dangerous
|
||||
if it drifts, so each has its own regression test:
|
||||
|
||||
* ``pushed_rev`` must survive verbatim (this pass never pushes),
|
||||
* ``peer_revs`` must be *merged*, never replaced (only changed peers visited),
|
||||
* the log must be written before the state.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from crdt_sync import FileSyncStateStore, GitHubSyncError, SyncState
|
||||
import pytest
|
||||
|
||||
from diet_guard import _sync_client, _sync_refresh
|
||||
from diet_guard._device import device_id
|
||||
from diet_guard._state import log_meal
|
||||
from diet_guard._state_sync import read_raw_log, write_raw_log
|
||||
from diet_guard.sync_merge import daylog_to_log
|
||||
from diet_guard.tests._sync_fakes import _mock_client, _nutrition, _write_token
|
||||
|
||||
|
||||
def _state_store() -> FileSyncStateStore:
|
||||
"""Return a store bound to the *redirected* state path, resolved per call."""
|
||||
from diet_guard import _sync
|
||||
|
||||
return FileSyncStateStore(_sync.SYNC_STATE_FILE)
|
||||
|
||||
|
||||
def _peer_log_text() -> str:
|
||||
"""Return the wire text a peer would push for one logged meal.
|
||||
|
||||
Built through ``log_meal`` into the (redirected) local log, serialised, then
|
||||
the local log is emptied again -- so the merge under test is unambiguously
|
||||
the peer's record arriving, not one that was already there.
|
||||
"""
|
||||
log_meal("peer porridge", _nutrition(), 8)
|
||||
text = json.dumps(
|
||||
{rid: rec.to_dict() for rid, rec in daylog_to_log(read_raw_log()).items()},
|
||||
indent=2,
|
||||
)
|
||||
write_raw_log({})
|
||||
return text
|
||||
|
||||
|
||||
class TestCandidatePeers:
|
||||
"""Enumerating peers without the ~445ms mirrored directory listing."""
|
||||
|
||||
def test_uses_the_revision_map_and_the_cache(self) -> None:
|
||||
"""The union covers peers that stopped publishing revisions."""
|
||||
client = MagicMock()
|
||||
state = SyncState(pushed_rev=None, peer_revs={"cached": "r"})
|
||||
|
||||
peers = _sync_refresh._candidate_peers(client, {"published": "r"}, state)
|
||||
|
||||
assert peers == ["cached", "published"]
|
||||
client.list_directory.assert_not_called()
|
||||
|
||||
def test_falls_back_to_listing_without_a_revision_map(self) -> None:
|
||||
"""No revisions means no information -- not "no peers"."""
|
||||
client = _mock_client(devices=("phone",))
|
||||
state = SyncState(pushed_rev=None, peer_revs={})
|
||||
|
||||
assert _sync_refresh._candidate_peers(client, {}, state) == ["phone"]
|
||||
client.list_directory.assert_called_once()
|
||||
|
||||
|
||||
class TestPeerIsCurrent:
|
||||
"""Which peers this narrow pass is allowed to skip."""
|
||||
|
||||
def test_skips_a_matching_revision(self) -> None:
|
||||
state = SyncState(pushed_rev=None, peer_revs={"phone": "r1"})
|
||||
|
||||
assert _sync_refresh._peer_is_current("phone", {"phone": "r1"}, state)
|
||||
|
||||
def test_fetches_a_moved_revision(self) -> None:
|
||||
state = SyncState(pushed_rev=None, peer_revs={"phone": "r1"})
|
||||
|
||||
assert not _sync_refresh._peer_is_current("phone", {"phone": "r2"}, state)
|
||||
|
||||
def test_skips_a_rev_less_peer_already_merged(self) -> None:
|
||||
"""Removes the standing cost of the frozen legacy role-id directories."""
|
||||
state = SyncState(pushed_rev=None, peer_revs={"desktop": "whatever"})
|
||||
|
||||
assert _sync_refresh._peer_is_current("desktop", {}, state)
|
||||
|
||||
def test_fetches_a_genuinely_new_rev_less_peer(self) -> None:
|
||||
state = SyncState(pushed_rev=None, peer_revs={})
|
||||
|
||||
assert not _sync_refresh._peer_is_current("newcomer", {}, state)
|
||||
|
||||
def test_a_null_cached_revision_still_counts_as_seen(self) -> None:
|
||||
"""``peer_revs`` holds explicit nulls; ``in`` is the only safe test.
|
||||
|
||||
Using ``.get(...) is not None`` here would re-download those peers on
|
||||
every single tick, forever.
|
||||
"""
|
||||
# A real ``sync_state.json`` holds explicit nulls here even though the
|
||||
# annotation says ``str`` -- that mismatch is exactly what this test
|
||||
# pins, so the value is cast in rather than suppressed at the line.
|
||||
peer_revs = cast("dict[str, str]", {"pc": None})
|
||||
state = SyncState(pushed_rev=None, peer_revs=peer_revs)
|
||||
|
||||
assert _sync_refresh._peer_is_current("pc", {}, state)
|
||||
|
||||
|
||||
class TestRefreshPeerLogs:
|
||||
"""The pass itself."""
|
||||
|
||||
def test_no_candidates_touches_nothing(self) -> None:
|
||||
_write_token()
|
||||
client = _mock_client(devices=())
|
||||
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
client.get_file_text.assert_not_called()
|
||||
|
||||
def test_skips_this_device(self) -> None:
|
||||
"""Merging our own pushed log back in is pure waste."""
|
||||
_write_token()
|
||||
client = _mock_client(devices=(device_id(),))
|
||||
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
client.get_file_text.assert_not_called()
|
||||
|
||||
def test_a_missing_remote_file_is_skipped(self) -> None:
|
||||
_write_token()
|
||||
client = _mock_client(devices=("phone",), files={})
|
||||
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
assert read_raw_log() == {}
|
||||
|
||||
def test_an_unparsable_payload_is_skipped_and_not_recorded(self) -> None:
|
||||
"""A corrupt push must be retried next tick, never remembered as merged."""
|
||||
_write_token()
|
||||
client = _mock_client(
|
||||
devices=("phone",),
|
||||
files={"diet-guard-sync/devices/phone/food_log.json": "{not json"},
|
||||
)
|
||||
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
assert "phone" not in _state_store().load().peer_revs
|
||||
|
||||
def test_merges_a_peer_entry_into_the_local_log(self) -> None:
|
||||
_write_token()
|
||||
text = _peer_log_text()
|
||||
client = _mock_client(
|
||||
devices=("phone",),
|
||||
files={"diet-guard-sync/devices/phone/food_log.json": text},
|
||||
)
|
||||
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
assert any(
|
||||
entry.get("desc") == "peer porridge"
|
||||
for entries in read_raw_log().values()
|
||||
for entry in entries
|
||||
)
|
||||
|
||||
def test_never_pushes(self) -> None:
|
||||
"""This pass is pull-only; a push here would block the lock window."""
|
||||
_write_token()
|
||||
text = _peer_log_text()
|
||||
client = _mock_client(
|
||||
devices=("phone",),
|
||||
files={"diet-guard-sync/devices/phone/food_log.json": text},
|
||||
)
|
||||
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
client.put_file_text.assert_not_called()
|
||||
|
||||
def test_preserves_pushed_rev(self) -> None:
|
||||
"""Overwriting it would make this device stop pushing forever."""
|
||||
_write_token()
|
||||
store = _state_store()
|
||||
store.save(SyncState(pushed_rev="mine-v1", peer_revs={}))
|
||||
text = _peer_log_text()
|
||||
client = _mock_client(
|
||||
devices=("phone",),
|
||||
files={"diet-guard-sync/devices/phone/food_log.json": text},
|
||||
)
|
||||
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
assert store.load().pushed_rev == "mine-v1"
|
||||
|
||||
def test_merges_peer_revs_rather_than_replacing_them(self) -> None:
|
||||
"""Only changed peers are visited, so a replace would drop the rest."""
|
||||
_write_token()
|
||||
store = _state_store()
|
||||
store.save(SyncState(pushed_rev=None, peer_revs={"other": "r-other"}))
|
||||
text = _peer_log_text()
|
||||
client = _mock_client(
|
||||
devices=("phone", "other"),
|
||||
files={"diet-guard-sync/devices/phone/food_log.json": text},
|
||||
)
|
||||
|
||||
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
assert store.load().peer_revs["other"] == "r-other"
|
||||
|
||||
|
||||
class TestPullPeerLogs:
|
||||
"""The fail-closed wrapper the gate actually calls."""
|
||||
|
||||
def test_returns_none_on_success(self) -> None:
|
||||
with patch.object(_sync_refresh, "refresh_peer_logs"):
|
||||
assert _sync_refresh.pull_peer_logs() is None
|
||||
|
||||
def test_returns_a_reason_on_a_sync_failure(self) -> None:
|
||||
with patch.object(
|
||||
_sync_refresh, "refresh_peer_logs", side_effect=GitHubSyncError("boom")
|
||||
):
|
||||
reason = _sync_refresh.pull_peer_logs()
|
||||
|
||||
assert reason is not None
|
||||
assert "boom" in reason
|
||||
|
||||
def test_an_unexpected_error_is_not_swallowed(self) -> None:
|
||||
"""A bug outside the known failure surface must surface, not hide."""
|
||||
with (
|
||||
patch.object(
|
||||
_sync_refresh, "refresh_peer_logs", side_effect=KeyError("bug")
|
||||
),
|
||||
pytest.raises(KeyError),
|
||||
):
|
||||
_sync_refresh.pull_peer_logs()
|
||||
@ -4,7 +4,7 @@ version = "1.0.0"
|
||||
description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.5.0#subdirectory=gatelock",
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock",
|
||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.6.0#subdirectory=crdt-sync",
|
||||
"requests>=2.31.0",
|
||||
]
|
||||
|
||||
@ -4,7 +4,7 @@ bandit>=1.7.0
|
||||
codespell>=2.2.0
|
||||
coverage>=7.4.0
|
||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.6.0#subdirectory=crdt-sync
|
||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.5.0#subdirectory=gatelock
|
||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock
|
||||
mcp>=2,<3
|
||||
mypy>=1.8.0
|
||||
pre-commit>=3.6.0
|
||||
|
||||
Loading…
Reference in New Issue
Block a user