diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 06860b5..528e064 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -108,7 +108,7 @@ repos: # direct URLs for one distribution, so any pin that drifts from # the manifest becomes an unresolvable hook environment rather # than merely an old one. - - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock + - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock - crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync - kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit - freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays diff --git a/phone_app/lib/screens/home_body.dart b/phone_app/lib/screens/home_body.dart index fce078c..2fc6e49 100644 --- a/phone_app/lib/screens/home_body.dart +++ b/phone_app/lib/screens/home_body.dart @@ -55,8 +55,10 @@ class HomeBody extends StatelessWidget { final VoidCallback? onEscaped; IconData? _statusIcon(String status) { - if (status.startsWith('Connect a sync backend')) return Icons.cloud_off; - if (status.startsWith('Sync store unavailable')) return Icons.sync_problem; + if (status.contains('Connect a sync backend')) return Icons.cloud_off; + if (status.contains('Sync store unavailable')) return Icons.sync_problem; + // Saved and armed offline; the push rides the next sync. + if (status.contains('Saved locally')) return Icons.cloud_upload; if (status.contains('✓')) return Icons.cloud_done; return null; } diff --git a/phone_app/lib/services/alarm_publisher.dart b/phone_app/lib/services/alarm_publisher.dart index da2125f..92db078 100644 --- a/phone_app/lib/services/alarm_publisher.dart +++ b/phone_app/lib/services/alarm_publisher.dart @@ -1,3 +1,4 @@ +import 'package:http/http.dart' as http; import 'package:wake_alarm_sync/services/alarm_arming.dart'; import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; @@ -10,6 +11,10 @@ import 'package:wake_alarm_sync/services/sync_settings.dart'; /// Split out of `home_screen.dart` for the 250-line gate, and because none of /// this is UI: it returns a message for the screen to render rather than /// calling `setState` itself, which also makes it testable without a widget. +/// +/// Offline-first: the local half — storing the time and arming the phone — +/// always runs. The sync half degrades to a status line, and the next +/// publish (app start, settings return, an earlier tap) retries it. class AlarmPublisher { /// Creates a publisher; [arming] is injectable for tests. AlarmPublisher({AlarmArming? arming}) @@ -21,53 +26,88 @@ class AlarmPublisher { /// Publishes [hour]:[minute] and arms the alarm, returning a status line. /// /// Never throws: this runs unattended from the app's init seam, so a sync - /// failure must degrade to a message rather than take the screen down. The - /// alarm itself is already armed by `main()` regardless of what happens - /// here — publishing is how the PC learns the time, not how the phone rings. + /// failure must degrade to a message rather than take the screen down. Future publish({ required AlarmSyncService? service, required int hour, required int minute, + http.Client? httpClient, }) async { - final settings = await SyncSettings.load(); - // syncBackend() falls back to GitHub alone, or pushes to Firebase alone - // via the mirror, so either credential is enough to proceed. - final hasFirebase = await loadAccount() != null; - if (!settings.isConfigured && !hasFirebase) { - return 'Connect a sync backend in Settings first.'; - } - // Distinct from the above on purpose. Both used to report "connect a - // backend", so a store that failed to open looked like a configuration - // the user had never done -- and the advice was to fix something that - // was not broken. - if (service == null) { - return 'Sync store unavailable — reopen the app.'; + // The local half first: store the time (when a store exists) and arm the + // phone. Neither depends on a backend or the network, so the alarm is set + // even on a plane — the sync status below is the only thing that cannot + // complete offline. + String? armProblem; + var inClock = false; + Exception? saveError; + if (service != null) { + try { + await service.setLocal(hour, minute); + } on Exception catch (e) { + // The log could not be written, so the PC must not be told + // "synced": pushing now would publish the previous time. + saveError = e; + } } try { - await service.setLocal(hour, minute); - // Tags and home ride on the same record: stage local edits, sync - // (pull, merge, push), then take whatever won back into prefs. That - // last step is how a fresh install gets its tags back. - await stageLocalSettings(service); - await service.push(settings.token); - await applySyncedSettings(service); - final problem = await arming.arm(hour, minute); - if (problem != null) return problem; - final inClock = await arming.registerWithClockApp(hour, minute); - return syncedStatus(hour, minute, inClock: inClock); + armProblem = await arming.arm(hour, minute); + if (armProblem == null) { + inClock = await arming.registerWithClockApp(hour, minute); + } } on Exception catch (e) { - return 'Error: $e'; + armProblem ??= 'Error: $e'; } + + if (saveError != null) { + return armProblem ?? '${armedFor(hour, minute)}Error: $saveError'; + } + + // The sync half: stage the settings that ride on the record, push, take + // the winners back into prefs (how a fresh install gets its tags). + if (service != null) { + final settings = await SyncSettings.load(); + // syncBackend() falls back to GitHub alone, or pushes to Firebase alone + // via the mirror, so either credential is enough to proceed. + final configured = settings.isConfigured || await loadAccount() != null; + if (configured) { + try { + await stageLocalSettings(service); + await service.push(settings.token, httpClient: httpClient); + await applySyncedSettings(service); + } on Exception catch (e) { + // The local save and the arming are already done; only the push + // failed. Say so — the time is not lost, it rides the next publish. + return armProblem ?? + '${armedFor(hour, minute)}Saved locally — will sync to PC. ' + 'Error: $e'; + } + } else { + return armProblem ?? + '${armedFor(hour, minute)}' + 'Connect a sync backend in Settings first.'; + } + } else { + // Distinct from the "connect a backend" line on purpose. Both used to + // report the same thing, so a store that failed to open looked like a + // configuration the user had never done. + return armProblem ?? + '${armedFor(hour, minute)}Sync store unavailable — reopen the app.'; + } + return armProblem ?? syncedStatus(hour, minute, inClock: inClock); } } +/// The "Armed for HH:MM." prefix every status line shares: the local arm is +/// what succeeded, whatever the sync half reports. +String armedFor(int hour, int minute) => + 'Armed for ' + '${hour.toString().padLeft(2, '0')}:' + '${minute.toString().padLeft(2, '0')}. '; + /// The success line, naming the armed time; names the Clock app only when /// the handoff to it completed before its timeout, so a silent timeout -/// never claims it. Only reached after `arm()` succeeded. +/// never claims it. String syncedStatus(int hour, int minute, {required bool inClock}) { - final time = - '${hour.toString().padLeft(2, '0')}:' - '${minute.toString().padLeft(2, '0')}'; - final synced = 'Armed for $time. Synced to PC ✓'; + final synced = '${armedFor(hour, minute)}Synced to PC ✓'; return inClock ? '$synced Clock app set ✓' : synced; } diff --git a/phone_app/lib/ui/cues.dart b/phone_app/lib/ui/cues.dart index 981d4c0..1d81c75 100644 --- a/phone_app/lib/ui/cues.dart +++ b/phone_app/lib/ui/cues.dart @@ -37,6 +37,15 @@ enum CueKind { CueKind? cueKindOf(String status) { if (status.isEmpty) return null; if (status.endsWith('…') || status.endsWith('...')) return CueKind.busy; + // Checked before the error/ok keywords: an offline-first publish prefixes + // every line with "Armed for HH:MM." (the local half succeeded), so a + // pending sync must not read as a plain success, nor a dead network as a + // failure — the time is saved and rides the next sync. + if (status.contains('Saved locally') || + status.contains('Connect a sync backend') || + status.contains('Open Settings')) { + return CueKind.warning; + } const errorKeywords = [ 'Error', @@ -72,10 +81,6 @@ CueKind? cueKindOf(String status) { if (status.contains(kw)) return CueKind.ok; } - if (status.contains('Connect a sync backend') || - status.contains('Open Settings')) { - return CueKind.warning; - } return CueKind.info; } diff --git a/phone_app/test/services/alarm_publisher_test.dart b/phone_app/test/services/alarm_publisher_test.dart index 6c021d6..5fd8d7c 100644 --- a/phone_app/test/services/alarm_publisher_test.dart +++ b/phone_app/test/services/alarm_publisher_test.dart @@ -1,9 +1,65 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'package:wake_alarm_sync/services/alarm_publisher.dart'; +import 'dart:io'; +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/alarm_arming.dart'; +import 'package:wake_alarm_sync/services/alarm_publisher.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; + +import '../e2e_support.dart'; +import '../fake_day_pool_store.dart'; import '../fake_secure_storage.dart'; +/// Persistence whose writes start failing once [failing] is set. +class _FailingWrites extends MemPersistence { + bool failing = false; + + @override + Future write(String value) async { + if (failing) throw const FileSystemException('disk gone'); + await super.write(value); + } +} + +/// Records the platform arms instead of touching the real channel. +class _RecordingScheduler extends AlarmScheduler { + _RecordingScheduler() : super(channel: const MethodChannel('test/alarm')); + + final List calls = []; + + @override + Future canUseFullScreenIntent() async => true; + + @override + Future schedule(int hour, int minute) async { + calls.add('schedule $hour:$minute'); + } +} + +/// Completes the Clock handoff without launching an intent. +class _RecordingArming extends AlarmArming { + _RecordingArming(super.scheduler); + + @override + Future registerWithClockApp(int hour, int minute) async => true; +} + +class _OfflineClient extends http.BaseClient { + @override + Future send(http.BaseRequest request) => + throw http.ClientException('offline'); +} + +Future _service({LogPersistence? persistence}) => + AlarmSyncService.open( + persistence: persistence ?? MemPersistence(), + deviceId: 'test-device', + ); + void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -13,12 +69,17 @@ void main() { }); test('an unconfigured install is told to connect a backend', () async { - final message = await AlarmPublisher().publish( - service: null, - hour: 8, - minute: 0, - ); + final scheduler = _RecordingScheduler(); + final service = await _service(); + final message = await AlarmPublisher( + arming: _RecordingArming(scheduler), + ).publish(service: service, hour: 8, minute: 0); + // Offline-first: the time is stored locally and the phone is armed even + // though nothing can be pushed yet. + expect(service.currentAlarm, (hour: 8, minute: 0)); + expect(message, contains('Armed for 08:00')); expect(message, contains('Connect a sync backend')); + expect(scheduler.calls, ['schedule 8:0']); }); test('a missing store is not reported as a missing backend', () async { @@ -30,13 +91,78 @@ void main() { SharedPreferences.setMockInitialValues({ 'github_token': 'ghp_configured', }); - final message = await AlarmPublisher().publish( - service: null, - hour: 8, - minute: 0, - ); + final scheduler = _RecordingScheduler(); + final message = await AlarmPublisher( + arming: _RecordingArming(scheduler), + ).publish(service: null, hour: 8, minute: 0); + expect(message, contains('Armed for 08:00')); expect(message, isNot(contains('Connect a sync backend'))); expect(message, contains('Sync store unavailable')); + expect(scheduler.calls, ['schedule 8:0']); + }); + + test('a failed push keeps the phone armed and says it will sync', () async { + installE2eTestStorage(); + SharedPreferences.setMockInitialValues({ + 'github_token': 'ghp_configured', + }); + final scheduler = _RecordingScheduler(); + final service = await _service(); + final message = await AlarmPublisher(arming: _RecordingArming(scheduler)) + .publish( + service: service, + hour: 7, + minute: 30, + httpClient: _OfflineClient(), + ); + expect(service.currentAlarm, (hour: 7, minute: 30)); + expect(message, contains('Armed for 07:30')); + expect(message, contains('Saved locally')); + expect(message, contains('Error')); + expect(scheduler.calls, ['schedule 7:30']); + }); + + test('a failed local save is reported, never "synced"', () async { + installE2eTestStorage(); + SharedPreferences.setMockInitialValues({ + 'github_token': 'ghp_configured', + }); + final github = MemGitHub(); + final persistence = _FailingWrites(); + final service = await _service(persistence: persistence); + persistence.failing = true; + final message = + await AlarmPublisher( + arming: _RecordingArming(_RecordingScheduler()), + ).publish( + service: service, + hour: 6, + minute: 45, + httpClient: github.httpClient, + ); + expect(message, contains('Armed for 06:45')); + expect(message, contains('Error')); + expect(message, isNot(contains('Synced'))); + expect(github.putPaths, isEmpty); + }); + + test('a push on a live mirror ends with the synced line', () async { + installE2eTestStorage(); + SharedPreferences.setMockInitialValues({ + 'github_token': 'ghp_configured', + }); + final github = MemGitHub(); + final scheduler = _RecordingScheduler(); + final message = await AlarmPublisher(arming: _RecordingArming(scheduler)) + .publish( + service: await _service(), + hour: 7, + minute: 15, + httpClient: github.httpClient, + ); + expect(message, 'Armed for 07:15. Synced to PC ✓ Clock app set ✓'); + expect(scheduler.calls, ['schedule 7:15']); + expect(github.putPaths, isNotEmpty); }); test('the Clock line names the time only when the handoff completed', () { diff --git a/phone_app/test/ui/cues_test.dart b/phone_app/test/ui/cues_test.dart index 333f87c..efa424e 100644 --- a/phone_app/test/ui/cues_test.dart +++ b/phone_app/test/ui/cues_test.dart @@ -3,6 +3,7 @@ library; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:wake_alarm_sync/services/alarm_publisher.dart'; import 'package:wake_alarm_sync/ui/cues.dart'; void main() { @@ -60,6 +61,24 @@ void main() { expect(cueKindOf('Open Settings to connect'), equals(CueKind.warning)); }); + test('every offline-first publish line keeps its own cue', () { + // Each line is built by AlarmPublisher, so a reworded prefix that + // flips a pending sync to "ok" (or a dead network to "error") fails. + expect( + cueKindOf('${armedFor(8, 0)}Connect a sync backend in Settings first.'), + equals(CueKind.warning), + ); + expect( + cueKindOf('${armedFor(8, 0)}Saved locally — will sync to PC. Error: x'), + equals(CueKind.warning), + ); + expect( + cueKindOf('${armedFor(8, 0)}Sync store unavailable — reopen the app.'), + equals(CueKind.error), + ); + expect(cueKindOf(syncedStatus(8, 0, inClock: false)), equals(CueKind.ok)); + }); + test('default info', () { expect(cueKindOf('hello'), equals(CueKind.info)); expect(cueKindOf('Syncing now'), equals(CueKind.info)); diff --git a/pyproject.toml b/pyproject.toml index 01c95ac..124f24d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ version = "1.0.0" description = "Trigger that starts the morning routine at the phone's alarm time" requires-python = ">=3.14" dependencies = [ - "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock", + "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock", # Firebase transport for the alarm read. _sync.py imports it lazily and # falls back to its stdlib GitHub path if the import fails, so a broken # install degrades the read instead of killing the per-minute trigger. diff --git a/requirements.txt b/requirements.txt index 06929fa..14fa9c2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,7 +7,7 @@ codespell==2.4.3 coverage==7.17.5 crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays -gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.1#subdirectory=gatelock +gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.16.2#subdirectory=gatelock kuhy-credit @ git+https://github.com/kuhyx/utils@kuhy-credit-v0.3.2#subdirectory=kuhy_credit mypy==2.4.1 pre-commit==4.7.0 diff --git a/wake_alarm/_constants.py b/wake_alarm/_constants.py index c71817a..f2e7050 100644 --- a/wake_alarm/_constants.py +++ b/wake_alarm/_constants.py @@ -49,6 +49,11 @@ SYNC_TOKEN_FALLBACK_FILES: tuple[Path, ...] = ( # Where a successful read is cached, so a network blip can't cost a wake-up. ALARM_CACHE_FILE: Path = Path.home() / ".config" / "wake_alarm" / "alarm_cache.json" +# The last successful Firebase fetch of every device's log, served offline. +SYNC_LOGS_CACHE_FILE: Path = ( + Path.home() / ".config" / "wake_alarm" / "synced_logs_cache.json" +) + # Structured logs live under XDG state, not .config: they are churning runtime # data, not configuration. The JSONL file is additive -- the journal keeps diff --git a/wake_alarm/_field_reader.py b/wake_alarm/_field_reader.py index 495dbb9..3db036e 100644 --- a/wake_alarm/_field_reader.py +++ b/wake_alarm/_field_reader.py @@ -64,7 +64,8 @@ def latest_field[T]( field: str, parse: Callable[[object, str], T | None], *, what: str ) -> T | None: """``newest_field`` over a live Firebase read; None when unreadable.""" - published = fetch_firebase_logs() + # Offline-first: a dead network serves the last synced logs. + published = fetch_firebase_logs(offline_cache=True) if published is None: return None value = newest_field(published, field, parse) diff --git a/wake_alarm/_sync_log_cache.py b/wake_alarm/_sync_log_cache.py new file mode 100644 index 0000000..8f974bf --- /dev/null +++ b/wake_alarm/_sync_log_cache.py @@ -0,0 +1,65 @@ +"""The last successfully-fetched Firebase logs, read back when offline. + +``fetch_firebase_logs`` writes the cache after every success and, for the +display readers that ask for it (``_weight``, ``_energy`` via +``_field_reader``), serves it when a fetch fails, so they still answer with +the newest known data while the network is down. The alarm path and the +enforcement checks do not ask: they must see a failed read as a failure. +The alarm time keeps its own ``ALARM_CACHE_FILE``; this is the *details* +half of offline-first: the raw per-device logs, not just the hour and +minute. +""" + +from __future__ import annotations + +import json +import logging + +from wake_alarm._constants import SYNC_LOGS_CACHE_FILE + +_logger = logging.getLogger(__name__) + +#: The arity of one cached ``(device_id, raw_log_json)`` pair. +_PAIR_ARITY = 2 + + +def write_synced_logs_cache(published: list[tuple[str, str]]) -> None: + """Persist [published] ``(device_id, raw_log_json)`` pairs. + + A failed write is logged and swallowed: the fetch already succeeded, and + losing the cache must not crash the per-minute trigger or a reader. + """ + entry = {"logs": [[device_id, raw] for device_id, raw in published]} + try: + SYNC_LOGS_CACHE_FILE.parent.mkdir(parents=True, exist_ok=True) + SYNC_LOGS_CACHE_FILE.write_text(json.dumps(entry, indent=2)) + except OSError as exc: + _logger.warning("Cannot write synced-logs cache: %s", exc) + + +def read_synced_logs_cache() -> list[tuple[str, str]] | None: + """The cached pairs, or None when absent, unreadable or malformed. + + A corrupt cache degrades to "nothing cached" — the fetch then degrades + further to its own fallbacks — never to a crash. + """ + try: + cached = json.loads(SYNC_LOGS_CACHE_FILE.read_text()) + except OSError, json.JSONDecodeError: + return None + if not isinstance(cached, dict): + return None + logs = cached.get("logs") + if not isinstance(logs, list) or not logs: + return None + pairs = [ + (pair[0], pair[1]) + for pair in logs + if ( + isinstance(pair, list) + and len(pair) == _PAIR_ARITY + and isinstance(pair[0], str) + and isinstance(pair[1], str) + ) + ] + return pairs or None diff --git a/wake_alarm/_sync_transport.py b/wake_alarm/_sync_transport.py index e2497f9..f3a78e2 100644 --- a/wake_alarm/_sync_transport.py +++ b/wake_alarm/_sync_transport.py @@ -36,6 +36,7 @@ from wake_alarm._constants import ( SYNC_REPO_NAME, SYNC_REPO_OWNER, ) +from wake_alarm._sync_log_cache import read_synced_logs_cache, write_synced_logs_cache if TYPE_CHECKING: from crdt_sync import Argon2Params, RemoteStore @@ -122,7 +123,7 @@ def _read_published(client: RemoteStore) -> list[tuple[str, str]]: return published -def fetch_firebase_logs() -> list[tuple[str, str]] | None: +def fetch_firebase_logs(*, offline_cache: bool = False) -> list[tuple[str, str]] | None: """Fetch every device's decrypted ``alarm.json`` from Firebase. Shared by the alarm reader and ``_weight``: the morning session's @@ -133,6 +134,15 @@ def fetch_firebase_logs() -> list[tuple[str, str]] | None: (no or wrong passphrase) store, so the caller can fall back to GitHub and then to the cache. + Every successful fetch rewrites the synced-logs cache. Only a caller that + passes *offline_cache* gets that cache back when the fetch fails: the + display readers (``_weight``, ``_energy``) want the newest known value + offline, while the alarm path (which has its own cache *after* the + GitHub fallback) and the enforcement checks must still see the failure. + + Args: + offline_cache: Serve the last cached logs when the fetch fails. + Returns: ``(device_id, raw_json)`` per device, or None if unconfigured, locked or unreadable. @@ -156,10 +166,11 @@ def fetch_firebase_logs() -> list[tuple[str, str]] | None: E2eLockedError, ) as exc: _logger.info("Cannot fetch the alarm from Firebase: %s", exc) - return None + return read_synced_logs_cache() if offline_cache else None if not published: _logger.info("No alarm published to Firebase yet") return None + write_synced_logs_cache(published) return published diff --git a/wake_alarm/tests/conftest.py b/wake_alarm/tests/conftest.py index eb73b80..268d6a4 100644 --- a/wake_alarm/tests/conftest.py +++ b/wake_alarm/tests/conftest.py @@ -186,6 +186,12 @@ def _hermetic(tmp_path: Path) -> Generator[None]: # the trigger's cache. A missing Firebase config keeps fetches # off the network unless a test patches the fetch itself. patch("wake_alarm._sync.ALARM_CACHE_FILE", tmp_path / "alarm_cache.json"), + # The raw per-device logs (weigh-in, energy, ...) are the *details* + # half of offline-first; keep that cache off the live file too. + patch( + "wake_alarm._sync_log_cache.SYNC_LOGS_CACHE_FILE", + tmp_path / "synced_logs_cache.json", + ), patch( "wake_alarm._sync_transport.FIREBASE_CONFIG_FILE", tmp_path / "no-firebase.json", diff --git a/wake_alarm/tests/test_sync_log_cache.py b/wake_alarm/tests/test_sync_log_cache.py new file mode 100644 index 0000000..7dee219 --- /dev/null +++ b/wake_alarm/tests/test_sync_log_cache.py @@ -0,0 +1,200 @@ +"""The offline-first fallback of every Firebase-log reader. + +``fetch_firebase_logs`` caches its last success (``_sync_log_cache``) and +serves it when a fetch fails, so the field readers (``_weight``, +``_energy``, ...) answer with the newest known data while the network is +down. These tests pin that contract. +""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +from crdt_sync import RemoteSyncError +import pytest + +from wake_alarm import _sync_log_cache +from wake_alarm._sync_log_cache import ( + read_synced_logs_cache, + write_synced_logs_cache, +) +from wake_alarm._sync_transport import fetch_firebase_logs, fetch_remote_alarm + +if TYPE_CHECKING: + from pathlib import Path + from typing import NoReturn + +_LOGS = [("device-a", '{"alarm": {}}')] + + +@pytest.fixture(autouse=True) +def _cache_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Point the cache at tmp for every test here; the autouse conftest + redirect covers the rest of the suite.""" + monkeypatch.setattr( + _sync_log_cache, "SYNC_LOGS_CACHE_FILE", tmp_path / "logs_cache.json" + ) + + +def test_write_then_read_roundtrip() -> None: + write_synced_logs_cache(_LOGS) + assert read_synced_logs_cache() == _LOGS + + +def test_read_missing_file_is_none() -> None: + assert read_synced_logs_cache() is None + + +def test_read_corrupt_file_is_none() -> None: + file = _sync_log_cache.SYNC_LOGS_CACHE_FILE + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text("not json") + assert read_synced_logs_cache() is None + + +def test_read_wrong_shape_is_none() -> None: + file = _sync_log_cache.SYNC_LOGS_CACHE_FILE + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text(json.dumps({"logs": [{"wrong": "shape"}]})) + assert read_synced_logs_cache() is None + + +def test_read_cache_not_a_dict_is_none() -> None: + file = _sync_log_cache.SYNC_LOGS_CACHE_FILE + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text(json.dumps(["logs"])) + assert read_synced_logs_cache() is None + + +def test_read_logs_not_a_list_is_none() -> None: + file = _sync_log_cache.SYNC_LOGS_CACHE_FILE + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text(json.dumps({"logs": 5})) + assert read_synced_logs_cache() is None + + +def test_read_empty_logs_is_none() -> None: + file = _sync_log_cache.SYNC_LOGS_CACHE_FILE + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text(json.dumps({"logs": []})) + assert read_synced_logs_cache() is None + + +def test_write_failure_is_swallowed() -> None: + # The cache path is a directory, so write_text raises; the failure must + # be swallowed, not crash the reader it protects. + blocker = _sync_log_cache.SYNC_LOGS_CACHE_FILE + blocker.parent.mkdir(parents=True, exist_ok=True) + blocker.mkdir() + write_synced_logs_cache(_LOGS) # must not raise + + +def _configured_transport(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """A transport that *is* configured: the fetch reaches the backend.""" + config = tmp_path / "firebase-config.json" + config.write_text("{}") + monkeypatch.setattr("wake_alarm._sync_transport.FIREBASE_CONFIG_FILE", config) + monkeypatch.setattr( + "wake_alarm._sync_transport.firebase_client_for", lambda _app: object() + ) + + +def test_failed_fetch_serves_the_cache( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _configured_transport(monkeypatch, tmp_path) + write_synced_logs_cache(_LOGS) + + def _fail(_client: object) -> NoReturn: + msg = "offline" + raise RemoteSyncError(msg) + + monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail) + assert fetch_firebase_logs(offline_cache=True) == _LOGS + # Callers that did not ask (alarm path, audit, fallback ring) still see + # the failure: stale logs must not pass for a live read there. + assert fetch_firebase_logs() is None + + +def test_a_log_cache_does_not_skip_the_github_alarm_fallback( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _configured_transport(monkeypatch, tmp_path) + write_synced_logs_cache(_LOGS) + + def _fail(_client: object) -> NoReturn: + msg = "offline" + raise RemoteSyncError(msg) + + monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail) + monkeypatch.setattr( + "wake_alarm._sync_transport._fetch_github_alarm", lambda: (6, 30, None) + ) + assert fetch_remote_alarm() == (6, 30, None) + + +def test_unconfigured_fetch_without_cache_is_none( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # Conftest default: the config file does not exist, no cache written. + assert fetch_firebase_logs() is None + + +def test_success_writes_the_cache( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _configured_transport(monkeypatch, tmp_path) + monkeypatch.setattr( + "wake_alarm._sync_transport._read_published", lambda _client: _LOGS + ) + assert fetch_firebase_logs() == _LOGS + assert read_synced_logs_cache() == _LOGS + + +def test_an_empty_fetch_returns_none_and_keeps_the_cache( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # An empty *successful* fetch (no devices, no exception) means "nothing + # is published right now", not "the last value is still live". Serving + # the old cache here would resurrect a phone that deliberately cleared + # its alarm, so the fetch returns None and leaves the cache untouched. + _configured_transport(monkeypatch, tmp_path) + write_synced_logs_cache(_LOGS) + monkeypatch.setattr( + "wake_alarm._sync_transport._read_published", lambda _client: [] + ) + assert fetch_firebase_logs() is None + assert read_synced_logs_cache() == _LOGS + + +def test_weight_offline_comes_from_the_cache( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # The reader half of offline-first: with the network down, the newest + # known weigh-in is still the one last synced, not "none". + _configured_transport(monkeypatch, tmp_path) + log = json.dumps( + { + "alarm": { + "fields": { + "latest_weight_kg": [ + {"date": "2026-11-26", "kg": 81.5}, + "2026-11-26T07:00:00.000Z-0-device-a", + ] + } + } + } + ) + write_synced_logs_cache([("device-a", log)]) + + def _fail(_client: object) -> NoReturn: + msg = "offline" + raise RemoteSyncError(msg) + + monkeypatch.setattr("wake_alarm._sync_transport._read_published", _fail) + from wake_alarm._weight import latest_weight + + weight = latest_weight() + assert weight is not None + assert (weight.date, weight.kg) == ("2026-11-26", 81.5)