mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-28 21:09:14 +01:00
Plant phone logs in fallback dry runs
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,free-days-interop,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / free-days-interop (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,free-days-interop,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / free-days-interop (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
_fallback --dry-run --published FILE reads the phone's logs from a JSON list of [device_id, alarm.json] pairs instead of Firebase, morning and evening alike, so the bypass answers (live check C8) can be seen from the CLI without a backend. Refused (exit 2) without --dry-run or for a malformed file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8253836612
commit
1df4f64393
@ -77,6 +77,9 @@ a minute is recorded once (both activities run the launch check).
|
|||||||
than the bypass, which the phone also pushes at once. Free and sick days
|
than the bypass, which the phone also pushes at once. Free and sick days
|
||||||
and an escape stand it down. The tick reads the phone until `A + 4 h`
|
and an escape stand it down. The tick reads the phone until `A + 4 h`
|
||||||
(`BYPASS_WATCH`); the fallback timer ticks 04:00-11:59 (and 21:xx, below).
|
(`BYPASS_WATCH`); the fallback timer ticks 04:00-11:59 (and 21:xx, below).
|
||||||
|
To see these answers without a backend, `_fallback --dry-run --at <instant>
|
||||||
|
--published <file>` reads the phone's logs from a JSON list of
|
||||||
|
`[device_id, alarm.json]` pairs instead of Firebase (`_published_file`).
|
||||||
|
|
||||||
## The 21:00 notifications check
|
## The 21:00 notifications check
|
||||||
|
|
||||||
|
|||||||
@ -15,6 +15,7 @@ no session, no escape": fail toward ringing.
|
|||||||
python -m wake_alarm._fallback --tick # what the timer runs
|
python -m wake_alarm._fallback --tick # what the timer runs
|
||||||
python -m wake_alarm._fallback --dry-run # decide now, change nothing
|
python -m wake_alarm._fallback --dry-run # decide now, change nothing
|
||||||
python -m wake_alarm._fallback --show # latch + last decision, offline
|
python -m wake_alarm._fallback --show # latch + last decision, offline
|
||||||
|
python -m wake_alarm._fallback --dry-run --published F # F replaces Firebase
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@ -50,6 +51,7 @@ from wake_alarm._fallback_policy import (
|
|||||||
)
|
)
|
||||||
from wake_alarm._fallback_ring import ring
|
from wake_alarm._fallback_ring import ring
|
||||||
from wake_alarm._logging_setup import configure_logging
|
from wake_alarm._logging_setup import configure_logging
|
||||||
|
from wake_alarm._published_file import load_published
|
||||||
from wake_alarm._ring_probe import maybe_probe
|
from wake_alarm._ring_probe import maybe_probe
|
||||||
from wake_alarm._ring_wav import SYSTEM_WAV_DIR, USER_WAV_DIR, ensure_pair
|
from wake_alarm._ring_wav import SYSTEM_WAV_DIR, USER_WAV_DIR, ensure_pair
|
||||||
from wake_alarm._sick import alarm_stands_down
|
from wake_alarm._sick import alarm_stands_down
|
||||||
@ -215,13 +217,22 @@ def _terminate(signum: int, _frame: FrameType | None) -> None:
|
|||||||
def main(argv: list[str] | None = None) -> int:
|
def main(argv: list[str] | None = None) -> int:
|
||||||
"""Entry point."""
|
"""Entry point."""
|
||||||
parser = mode_parser("PC fallback alarm tick", "tick", "decide and act")
|
parser = mode_parser("PC fallback alarm tick", "tick", "decide and act")
|
||||||
|
parser.add_argument("--published", help="with --dry-run: phone logs file")
|
||||||
args, now = parse_with_now(parser, argv, _now)
|
args, now = parse_with_now(parser, argv, _now)
|
||||||
|
planted = None
|
||||||
|
if args.published is not None:
|
||||||
|
if not args.dry_run:
|
||||||
|
parser.error("--published only goes with --dry-run")
|
||||||
|
try:
|
||||||
|
planted = load_published(args.published)
|
||||||
|
except (OSError, TypeError, ValueError) as exc:
|
||||||
|
parser.error(f"--published {args.published}: {exc}")
|
||||||
if args.show:
|
if args.show:
|
||||||
sys.stdout.write(show(now))
|
sys.stdout.write(show(now))
|
||||||
elif args.dry_run and in_evening(now):
|
elif args.dry_run and in_evening(now):
|
||||||
sys.stdout.write(evening_dry_run(now))
|
sys.stdout.write(evening_dry_run(now, planted))
|
||||||
elif args.dry_run:
|
elif args.dry_run:
|
||||||
seen = observe(now, sync=False)
|
seen = observe(now, sync=False, planted=planted)
|
||||||
sys.stdout.write(describe(seen, decide(seen.facts)))
|
sys.stdout.write(describe(seen, decide(seen.facts)))
|
||||||
else:
|
else:
|
||||||
configure_logging(component="fallback")
|
configure_logging(component="fallback")
|
||||||
|
|||||||
@ -57,8 +57,10 @@ def _tomorrow_off(now: datetime, *, sync: bool) -> str | None:
|
|||||||
return SICK_TOMORROW if sick(tomorrow) else None
|
return SICK_TOMORROW if sick(tomorrow) else None
|
||||||
|
|
||||||
|
|
||||||
def observe_evening(now: datetime, *, sync: bool) -> EveningFacts:
|
def observe_evening(
|
||||||
"""Gather the evening's facts; Firebase only when it can change them."""
|
now: datetime, *, sync: bool, planted: list[tuple[str, str]] | None = None
|
||||||
|
) -> EveningFacts:
|
||||||
|
"""Gather the evening's facts; Firebase (or ``planted``) only when needed."""
|
||||||
day = now.date().isoformat()
|
day = now.date().isoformat()
|
||||||
facts = EveningFacts(
|
facts = EveningFacts(
|
||||||
now=now,
|
now=now,
|
||||||
@ -67,7 +69,7 @@ def observe_evening(now: datetime, *, sync: bool) -> EveningFacts:
|
|||||||
)
|
)
|
||||||
if not needs_fetch(facts):
|
if not needs_fetch(facts):
|
||||||
return facts
|
return facts
|
||||||
published = fetch_firebase_logs()
|
published = fetch_firebase_logs() if planted is None else planted
|
||||||
if published is None:
|
if published is None:
|
||||||
return replace(facts, reachable=False)
|
return replace(facts, reachable=False)
|
||||||
return replace(
|
return replace(
|
||||||
@ -152,9 +154,9 @@ def evening_tick(now: datetime) -> Decision:
|
|||||||
return decision
|
return decision
|
||||||
|
|
||||||
|
|
||||||
def evening_dry_run(now: datetime) -> str:
|
def evening_dry_run(now: datetime, planted: list[tuple[str, str]] | None = None) -> str:
|
||||||
"""The ``--dry-run`` report for a 21:xx instant; writes nothing."""
|
"""The ``--dry-run`` report for a 21:xx instant; writes nothing."""
|
||||||
facts = observe_evening(now, sync=False)
|
facts = observe_evening(now, sync=False, planted=planted)
|
||||||
decision = decide(facts)
|
decision = decide(facts)
|
||||||
verdict = "WOULD RING" if decision.ring else "quiet"
|
verdict = "WOULD RING" if decision.ring else "quiet"
|
||||||
return (
|
return (
|
||||||
|
|||||||
@ -62,11 +62,14 @@ def _sick_today(now: datetime, *, online: bool, sync: bool) -> bool:
|
|||||||
return alarm_stands_down(now.date())
|
return alarm_stands_down(now.date())
|
||||||
|
|
||||||
|
|
||||||
def observe(now: datetime, *, sync: bool) -> Observation:
|
def observe(
|
||||||
|
now: datetime, *, sync: bool, planted: list[tuple[str, str]] | None = None
|
||||||
|
) -> Observation:
|
||||||
"""Gather the facts; the network only when the decision needs it.
|
"""Gather the facts; the network only when the decision needs it.
|
||||||
|
|
||||||
``sync`` is False for ``--dry-run``: pulling the sick-day pool rewrites
|
``sync`` is False for ``--dry-run``: pulling the sick-day pool rewrites
|
||||||
its local file, and a dry run writes nothing.
|
its local file, and a dry run writes nothing. ``planted`` (``--dry-run
|
||||||
|
--published``) stands in for the Firebase fetch.
|
||||||
"""
|
"""
|
||||||
day = now.date().isoformat()
|
day = now.date().isoformat()
|
||||||
latch = read_latch(day)
|
latch = read_latch(day)
|
||||||
@ -82,7 +85,7 @@ def observe(now: datetime, *, sync: bool) -> Observation:
|
|||||||
)
|
)
|
||||||
if facts.free_day or facts.sick_day or not online:
|
if facts.free_day or facts.sick_day or not online:
|
||||||
return Observation(facts)
|
return Observation(facts)
|
||||||
published = fetch_firebase_logs()
|
published = fetch_firebase_logs() if planted is None else planted
|
||||||
if published is None:
|
if published is None:
|
||||||
return Observation(facts, reachable=False)
|
return Observation(facts, reachable=False)
|
||||||
view = enforcement_view(published)
|
view = enforcement_view(published)
|
||||||
|
|||||||
42
wake_alarm/_published_file.py
Normal file
42
wake_alarm/_published_file.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
"""A planted stand-in for ``fetch_firebase_logs()``: ``--published FILE``.
|
||||||
|
|
||||||
|
Only for ``_fallback --dry-run``: the live check of the bypass ring needs
|
||||||
|
``bypass`` / ``dismissed`` events the PC can read, and there is no test
|
||||||
|
backend to put them in. The file is a JSON list of ``[device_id, alarm]``
|
||||||
|
pairs, the shape ``fetch_firebase_logs()`` returns. ``alarm`` is the
|
||||||
|
decrypted ``alarm.json`` -- an object (re-serialised here) or its raw text,
|
||||||
|
passed through as-is.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_PAIR_LEN = 2
|
||||||
|
|
||||||
|
|
||||||
|
def _pair(entry: object) -> tuple[str, str]:
|
||||||
|
"""One ``[device_id, alarm]`` entry as ``(device_id, raw_json)``."""
|
||||||
|
if not isinstance(entry, list) or len(entry) != _PAIR_LEN:
|
||||||
|
msg = f"expected [device_id, alarm], got {entry!r}"
|
||||||
|
raise TypeError(msg)
|
||||||
|
device, alarm = entry
|
||||||
|
if not isinstance(device, str):
|
||||||
|
msg = f"device id must be a string, got {device!r}"
|
||||||
|
raise TypeError(msg)
|
||||||
|
if isinstance(alarm, str):
|
||||||
|
return device, alarm
|
||||||
|
if isinstance(alarm, dict):
|
||||||
|
return device, json.dumps(alarm)
|
||||||
|
msg = f"alarm for {device!r} must be an object or its JSON text"
|
||||||
|
raise TypeError(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def load_published(path: str) -> list[tuple[str, str]]:
|
||||||
|
"""The planted logs; OSError/ValueError/TypeError when the file is unusable."""
|
||||||
|
raw = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
msg = "expected a JSON list of [device_id, alarm] pairs"
|
||||||
|
raise TypeError(msg)
|
||||||
|
return [_pair(entry) for entry in raw]
|
||||||
119
wake_alarm/tests/test_fallback_published.py
Normal file
119
wake_alarm/tests/test_fallback_published.py
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
"""``--dry-run --published FILE``: plant the phone's logs without a backend.
|
||||||
|
|
||||||
|
The live check of the bypass ring (C8, 2026-11-22) could not see ``ring:
|
||||||
|
bypass`` from the CLI: there is no test backend to plant a ``bypass`` event
|
||||||
|
in. The file stands in for ``fetch_firebase_logs()`` -- a dry run only, so
|
||||||
|
a planted world never rings or writes a latch.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from wake_alarm import _fallback, _fallback_evening, _fallback_observe
|
||||||
|
from wake_alarm._fallback_latch import read_latch
|
||||||
|
from wake_alarm._published_file import load_published
|
||||||
|
from wake_alarm._sync import Alarm
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Generator
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
DAY = "2026-11-22"
|
||||||
|
|
||||||
|
|
||||||
|
def _alarm_json(*events: dict[str, object]) -> dict[str, object]:
|
||||||
|
return {"alarm": {"fields": {"phone_events": [list(events), "h"]}}}
|
||||||
|
|
||||||
|
|
||||||
|
def _bypass(at: str) -> dict[str, object]:
|
||||||
|
return {"at": f"{DAY}T{at}+01:00", "kind": "bypass", "data": {"date": DAY}}
|
||||||
|
|
||||||
|
|
||||||
|
def _write(tmp_path: Path, content: object) -> str:
|
||||||
|
path = tmp_path / "published.json"
|
||||||
|
path.write_text(json.dumps(content), encoding="utf-8")
|
||||||
|
return str(path)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def no_backend() -> Generator[MagicMock]:
|
||||||
|
"""Alarm 08:00 and a Firebase fetch that must never run."""
|
||||||
|
fetch = MagicMock(side_effect=AssertionError("fetched Firebase"))
|
||||||
|
with (
|
||||||
|
patch.object(_fallback_observe, "get_alarm", return_value=Alarm(8, 0, "c")),
|
||||||
|
patch.object(_fallback_observe, "fetch_firebase_logs", fetch),
|
||||||
|
patch.object(_fallback_evening, "fetch_firebase_logs", fetch),
|
||||||
|
):
|
||||||
|
yield fetch
|
||||||
|
|
||||||
|
|
||||||
|
def _dry_run(path: str, at: str) -> int:
|
||||||
|
return _fallback.main(["--dry-run", "--at", f"{DAY}T{at}", "--published", path])
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_planted_bypass_rings_in_a_dry_run(
|
||||||
|
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
path = _write(tmp_path, [["phone", _alarm_json(_bypass("10:15:00"))]])
|
||||||
|
assert _dry_run(path, "10:30") == 0
|
||||||
|
assert "WOULD RING: bypass" in capsys.readouterr().out
|
||||||
|
assert read_latch(DAY) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_raw_text_is_passed_through_as_is(tmp_path: Path) -> None:
|
||||||
|
raw = json.dumps(_alarm_json(_bypass("08:05:00")))
|
||||||
|
path = _write(tmp_path, [["phone", raw], ["tablet", {"alarm": {}}]])
|
||||||
|
assert load_published(path) == [
|
||||||
|
("phone", raw),
|
||||||
|
("tablet", '{"alarm": {}}'),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_evening_dry_run_reads_the_file_too(
|
||||||
|
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
event = {
|
||||||
|
"at": f"{DAY}T21:00:00+01:00",
|
||||||
|
"kind": "notifications",
|
||||||
|
"data": {"enabled": False},
|
||||||
|
}
|
||||||
|
path = _write(tmp_path, [["phone", _alarm_json(event)]])
|
||||||
|
assert _dry_run(path, "21:05") == 0
|
||||||
|
assert "firebase=ok" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", ["--tick", "--show"])
|
||||||
|
def test_published_needs_dry_run(tmp_path: Path, mode: str) -> None:
|
||||||
|
path = _write(tmp_path, [])
|
||||||
|
with pytest.raises(SystemExit) as exc:
|
||||||
|
_fallback.main([mode, "--published", path])
|
||||||
|
assert exc.value.code == 2
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"content",
|
||||||
|
[
|
||||||
|
{"phone": {}},
|
||||||
|
[["phone"]],
|
||||||
|
[[1, "{}"]],
|
||||||
|
[["phone", 3]],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_a_malformed_file_is_refused(tmp_path: Path, content: object) -> None:
|
||||||
|
with pytest.raises(SystemExit) as exc:
|
||||||
|
_dry_run(_write(tmp_path, content), "08:10")
|
||||||
|
assert exc.value.code == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_missing_or_unparsable_file_is_refused(tmp_path: Path) -> None:
|
||||||
|
bad = tmp_path / "bad.json"
|
||||||
|
bad.write_text("{", encoding="utf-8")
|
||||||
|
for path in (str(bad), str(tmp_path / "absent.json")):
|
||||||
|
with pytest.raises(SystemExit) as exc:
|
||||||
|
_dry_run(path, "08:10")
|
||||||
|
assert exc.value.code == 2
|
||||||
Loading…
Reference in New Issue
Block a user