Parse notifications event; latch file param

EnforcementView.notifications_off_since(day): today's newest
notifications event when it says off. The latch helpers take an
optional file so the 21:00 ring keeps its own latch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-22 13:52:11 +01:00
parent 0781c42222
commit 35d6d07d8e
4 changed files with 118 additions and 11 deletions

View File

@ -94,6 +94,26 @@ class EnforcementView:
)
return None if dismissed else newest
def notifications_off_since(self, day: str) -> datetime | None:
"""The newest ``notifications`` event of local ``day``, if it says off.
None when ``day`` has none or the newest says on. An entry whose
``enabled`` is not a real bool is skipped, so a malformed event can
neither start the 21:00 ring nor silence it.
"""
seen = [
(at, enabled)
for event in self.phone_events
if event.kind == "notifications"
if isinstance(enabled := event.data.get("enabled"), bool)
if (at := parse_instant(event.at)) is not None
if at.date().isoformat() == day
]
if not seen:
return None
at, enabled = max(seen)
return None if enabled else at
def escaped_dates(self) -> frozenset[str]:
"""Every morning an honoured escape excuses."""
return frozenset(e.date for e in self.honoured_escapes())

View File

@ -5,6 +5,9 @@ contract's shape. It is what makes the 30-minute cap survive the ringing
process dying (a hibernate, a reboot): the cap is measured from the
wall-clock ``started_at``, never a monotonic clock, which does not advance
through S4. An unreadable latch is no latch -- fail toward ringing.
``file`` (default ``FALLBACK_RING_FILE``, resolved per call so the test
redirect holds) lets the 21:00 notifications ring keep its own latch.
"""
from __future__ import annotations
@ -19,6 +22,7 @@ from wake_alarm._enforcement_records import optional_text, parse_instant
if TYPE_CHECKING:
from datetime import datetime
from pathlib import Path
_logger = logging.getLogger(__name__)
@ -38,14 +42,15 @@ class Latch:
return parse_instant(self.started_at) if self.started_at else None
def read_latch(day: str) -> Latch | None:
def read_latch(day: str, file: Path | None = None) -> Latch | None:
"""The latch for ``day``; None when absent, unreadable or another day's."""
path = file or FALLBACK_RING_FILE
try:
raw = json.loads(FALLBACK_RING_FILE.read_text(encoding="utf-8"))
raw = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return None
except (OSError, ValueError) as exc:
_logger.info("Ignoring unreadable %s: %s", FALLBACK_RING_FILE, exc)
_logger.info("Ignoring unreadable %s: %s", path, exc)
return None
if not isinstance(raw, dict) or raw.get("date") != day:
return None
@ -58,31 +63,39 @@ def read_latch(day: str) -> Latch | None:
)
def write_latch(latch: Latch) -> bool:
def write_latch(latch: Latch, file: Path | None = None) -> bool:
"""Persist ``latch``; False when the disk refused."""
path = file or FALLBACK_RING_FILE
try:
FALLBACK_RING_FILE.parent.mkdir(parents=True, exist_ok=True)
FALLBACK_RING_FILE.write_text(json.dumps(asdict(latch), indent=2))
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(asdict(latch), indent=2))
except OSError as exc:
_logger.warning("Could not write %s: %s", FALLBACK_RING_FILE, exc)
_logger.warning("Could not write %s: %s", path, exc)
return False
return True
def mark_started(
previous: Latch | None, *, day: str, now: datetime, reason: str
previous: Latch | None,
*,
day: str,
now: datetime,
reason: str,
file: Path | None = None,
) -> Latch:
"""Record a ring (re)starting; a resumed ring keeps its first start."""
if previous is not None and previous.started_at:
latch = replace(previous, stopped_at=None, stop_reason=None)
else:
latch = Latch(date=day, started_at=now.isoformat(), reason=reason)
write_latch(latch)
write_latch(latch, file)
return latch
def mark_stopped(latch: Latch, *, now: datetime, stop_reason: str) -> Latch:
def mark_stopped(
latch: Latch, *, now: datetime, stop_reason: str, file: Path | None = None
) -> Latch:
"""Record why and when the ring stopped."""
stopped = replace(latch, stopped_at=now.isoformat(), stop_reason=stop_reason)
write_latch(stopped)
write_latch(stopped, file)
return stopped

View File

@ -0,0 +1,64 @@
"""``EnforcementView.notifications_off_since``: the 21:00 check's input."""
from __future__ import annotations
from datetime import datetime
from wake_alarm._enforcement_payload import EnforcementView
from wake_alarm._enforcement_records import PhoneEvent
DAY = "2026-11-22"
def _notif(hour: int, minute: int, enabled: object, day: int = 22) -> PhoneEvent:
at = datetime(2026, 11, day, hour, minute).astimezone().isoformat()
return PhoneEvent(at=at, kind="notifications", data={"enabled": enabled})
def _view(*events: PhoneEvent) -> EnforcementView:
return EnforcementView(phone_events=events)
def test_no_event_today_is_none() -> None:
assert _view().notifications_off_since(DAY) is None
def test_the_newest_event_saying_off_is_returned() -> None:
view = _view(_notif(15, 0, enabled=True), _notif(21, 0, enabled=False))
assert (
view.notifications_off_since(DAY) == datetime(2026, 11, 22, 21, 0).astimezone()
)
def test_a_newer_event_saying_on_clears_it() -> None:
view = _view(_notif(21, 5, enabled=True), _notif(21, 0, enabled=False))
assert view.notifications_off_since(DAY) is None
def test_yesterdays_off_does_not_count_today() -> None:
view = _view(_notif(21, 0, enabled=False, day=21))
assert view.notifications_off_since(DAY) is None
def test_a_malformed_newer_event_neither_starts_nor_silences() -> None:
view = _view(
_notif(21, 0, enabled=False),
_notif(21, 5, enabled="true"),
_notif(21, 6, enabled=None),
)
assert (
view.notifications_off_since(DAY) == datetime(2026, 11, 22, 21, 0).astimezone()
)
assert _view(_notif(21, 6, enabled=0)).notifications_off_since(DAY) is None
def test_other_kinds_and_undatable_events_are_ignored() -> None:
view = _view(
PhoneEvent(at="nope", kind="notifications", data={"enabled": False}),
PhoneEvent(
at=datetime(2026, 11, 22, 21, 0).astimezone().isoformat(),
kind="bypass",
data={"enabled": False},
),
)
assert view.notifications_off_since(DAY) is None

View File

@ -71,3 +71,13 @@ def test_garbage_fields_read_as_none() -> None:
json.dumps({"date": DAY, "started_at": None, "stopped_at": 5, "reason": ""})
)
assert read_latch(DAY) == Latch(date=DAY)
def test_another_file_keeps_its_own_latch(tmp_path: Path) -> None:
other = tmp_path / "evening_ring.json"
latch = mark_started(None, day=DAY, now=NOW, reason="x", file=other)
assert read_latch(DAY, other) == latch
assert read_latch(DAY) is None
stopped = mark_stopped(latch, now=NOW, stop_reason="cap", file=other)
assert read_latch(DAY, other) == stopped
assert not _fallback_latch.FALLBACK_RING_FILE.exists()