diff --git a/lib/features/earthquake/data/earthquake_api.dart b/lib/features/earthquake/data/earthquake_api.dart index 289e58314..3f79672f7 100644 --- a/lib/features/earthquake/data/earthquake_api.dart +++ b/lib/features/earthquake/data/earthquake_api.dart @@ -1,3 +1,4 @@ +import 'package:dio/dio.dart'; import 'package:dpip/core/error/result.dart'; import 'package:dpip/core/network/api_client.dart'; import 'package:dpip/core/network/api_paths.dart'; @@ -38,6 +39,47 @@ class EarthquakeApi { (await _client.get(ApiTier.coreApi, '${ApiPaths.rtsArchive}/$seconds')) as Map; + /// Whether the replay archives still hold the moment at [seconds]. + /// + /// Two feeds make a replay: the EEW alerts around the event and the RTS + /// frames from its start. They are pruned on different schedules, and the + /// EEW history is the longer-lived of the two (an old event can still have + /// alerts to replay and no shaking left to draw), so an EEW hit is enough. + /// + /// EEW alerts trail the origin by a few seconds, so the EEW probe looks + /// just past it rather than at the replay's lead-in second. A 404 from the + /// RTS archive is a "no such second", not a fault — what it retains moves + /// with time, which is exactly why this asks instead of comparing against + /// a fixed date. Every other failure is rethrown. + Future hasReplayAt(int seconds) async { + if (await _hasEewAt(seconds + 60)) return true; + try { + await getRtsAt(seconds); + return true; + } on DioException catch (error) { + if (_isMissing(error)) return false; + rethrow; + } + } + + /// An EEW point query, with the archive's two "nothing there" answers — + /// 404, and 400 for a timestamp too old to be ten digits — folded to empty. + Future _hasEewAt(int seconds) async { + try { + return (await getEewAt(seconds)).isNotEmpty; + } on DioException catch (error) { + if (_isMissing(error)) return false; + rethrow; + } + } + + /// Whether [error] is the archive saying it has nothing for that second, + /// rather than a transport/server fault. + static bool _isMissing(DioException error) { + final code = error.response?.statusCode; + return code == 404 || code == 400; + } + /// Latest EEW list (one-shot snapshot) — what the live feed polls while /// its stream is down. /// diff --git a/lib/features/earthquake/data/report_repository_impl.dart b/lib/features/earthquake/data/report_repository_impl.dart index f0c0997fd..b0b46f976 100644 --- a/lib/features/earthquake/data/report_repository_impl.dart +++ b/lib/features/earthquake/data/report_repository_impl.dart @@ -47,6 +47,10 @@ class ReportRepositoryImpl implements ReportRepository { return EarthquakeReport.fromJson((raw as Map).cast()); }); + @override + Future> hasReplayAt(int timestamp) => + guardResult(() => _api.hasReplayAt(timestamp ~/ 1000)); + /// Skips malformed rows so one bad record cannot blank the catalogue. static List parseReportList(List raw) { return [ diff --git a/lib/features/earthquake/domain/report_repository.dart b/lib/features/earthquake/domain/report_repository.dart index 2a17ece9f..7535b83e8 100644 --- a/lib/features/earthquake/domain/report_repository.dart +++ b/lib/features/earthquake/domain/report_repository.dart @@ -18,4 +18,12 @@ abstract interface class ReportRepository { /// The full report — including the per-area/town intensity breakdown — by /// [id], for the detail page behind a catalogue row. Future> get(String id); + + /// Whether the replay archive still holds [timestamp] (Unix ms). + /// + /// The retained window moves, so the detail page asks on every visit rather + /// than comparing against a fixed date. A 404 is `Ok(false)`; other + /// failures stay `Err` so a transient probe failure does not read as "never + /// replayable". + Future> hasReplayAt(int timestamp); } diff --git a/lib/features/earthquake/presentation/pages/report_detail_page.dart b/lib/features/earthquake/presentation/pages/report_detail_page.dart index 731bee9d2..7ed6c57f6 100644 --- a/lib/features/earthquake/presentation/pages/report_detail_page.dart +++ b/lib/features/earthquake/presentation/pages/report_detail_page.dart @@ -10,6 +10,7 @@ import 'package:dpip/app/theme/app_motion.dart'; import 'package:dpip/app/theme/app_radius.dart'; import 'package:dpip/app/theme/app_spacing.dart'; import 'package:dpip/core/error/failure.dart'; +import 'package:dpip/core/error/result.dart'; import 'package:dpip/core/geo/town.dart'; import 'package:dpip/core/geo/town_directory.dart'; import 'package:dpip/core/logging/log.dart'; @@ -303,6 +304,13 @@ class _ReportMapDetailState extends State<_ReportMapDetail> { MapLibreMapController? _controller; bool _styleLoaded = false; + /// Whether the replay archive still holds this report's moment. + /// + /// Probed once on every visit rather than compared against a fixed date: + /// the archive's retained window moves as data is added and pruned. A 404 + /// hides the chip; the check ends there, no polling. + bool _replayAvailable = false; + /// Feeds the Flutter [MapCompass] needle — camera heading, ° clockwise from /// north. Kept in sync from [BaseMap.onCameraMove] so the needle tracks /// rotation live, matching the map tab's compass. @@ -339,6 +347,24 @@ class _ReportMapDetailState extends State<_ReportMapDetail> { mutuallyExclusiveTerrain: _showTerrain, ); _gsi.addListener(_onGsiChanged); + unawaited(_probeReplay()); + } + + /// One request per page visit: the archive answers 404 once the report is + /// older than what it still keeps, and that window is not fixed. A probe + /// that fails for any other reason keeps the chip — a timeout does not mean + /// the event was never replayable. + Future _probeReplay() async { + final repository = context.read(); + final timestamp = widget.report.originTimeUtc.millisecondsSinceEpoch - 2000; + final result = await repository.hasReplayAt(timestamp); + if (!mounted) return; + setState(() { + _replayAvailable = switch (result) { + Ok(:final value) => value, + Err() => true, + }; + }); } @override @@ -548,6 +574,7 @@ class _ReportMapDetailState extends State<_ReportMapDetail> { report: widget.report, expandedNotifier: widget.sheetExpanded, saver: widget.imageSaver, + replayAvailable: _replayAvailable, ), ), // Base-map options (OSM detailed map / terrain relief / township @@ -600,10 +627,14 @@ class _ReportSheet extends StatefulWidget { required this.report, required this.expandedNotifier, required this.saver, + required this.replayAvailable, }); final EarthquakeReport report; + /// Whether the archive probe found this report still replayable. + final bool replayAvailable; + /// Mirrors this sheet's collapsed/expanded state up to the page, so it can /// hide its floating back button while the sheet's own header has one. final ValueNotifier expandedNotifier; @@ -778,7 +809,10 @@ class _ReportSheetState extends State<_ReportSheet> { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - _ReportHeader(report: report), + _ReportHeader( + report: report, + replayAvailable: widget.replayAvailable, + ), const SizedBox(height: AppSpacing.lg), SectionHeader(l10n.reportDetailInfo), _ReportInfoCard(report: report), @@ -971,10 +1005,13 @@ class _PeekStat extends StatelessWidget { /// Intensity badge + numbered/local-felt eyebrow + location — the expanded /// sheet's header, with a filled chip opening the official CWA report page. class _ReportHeader extends StatelessWidget { - const _ReportHeader({required this.report}); + const _ReportHeader({required this.report, required this.replayAvailable}); final EarthquakeReport report; + /// Whether the page's archive probe found this report still replayable. + final bool replayAvailable; + @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context); @@ -1038,11 +1075,12 @@ class _ReportHeader extends StatelessWidget { side: BorderSide(color: colors.primary), onPressed: () => _openReportPage(context), ), - ActionChip( - avatar: const Icon(Icons.replay, size: 16), - label: Text(l10n.reportDetailReplay), - onPressed: () => _openReplay(context), - ), + if (replayAvailable) + ActionChip( + avatar: const Icon(Icons.replay, size: 16), + label: Text(l10n.reportDetailReplay), + onPressed: () => _openReplay(context), + ), ], ), ], diff --git a/test/features/earthquake/data/earthquake_api_test.dart b/test/features/earthquake/data/earthquake_api_test.dart index 78eec817d..e501d8f73 100644 --- a/test/features/earthquake/data/earthquake_api_test.dart +++ b/test/features/earthquake/data/earthquake_api_test.dart @@ -138,6 +138,46 @@ void main() { expect(result, {'ts': 1700000000000}); }, ); + + test( + 'hasReplayAt accepts EEW alerts without asking the RTS archive', + () async { + client.nextGetResult = [ + {'id': '1130465'}, + ]; + expect(await api.hasReplayAt(1), isTrue); + expect(client.getCalls.single.$2, '${ApiPaths.eew}/61'); + }, + ); + + test('hasReplayAt turns the RTS archive 404 into false', () async { + client.nextGetResult = []; + final options = RequestOptions(path: '/api/v3/trem/rts/1'); + client.getError = DioException( + requestOptions: options, + response: Response(requestOptions: options, statusCode: 404), + ); + expect(await api.hasReplayAt(1), isFalse); + expect(client.getCalls.map((call) => call.$2), [ + '${ApiPaths.eew}/61', + '${ApiPaths.rtsArchive}/1', + ]); + + client.getError = DioException( + requestOptions: options, + response: Response(requestOptions: options, statusCode: 500), + ); + await expectLater(api.hasReplayAt(1), throwsA(isA())); + }); + + test('hasReplayAt reads a 400 as a timestamp too old to archive', () async { + final options = RequestOptions(path: '/api/v2/eq/eew/1'); + client.getError = DioException( + requestOptions: options, + response: Response(requestOptions: options, statusCode: 400), + ); + expect(await api.hasReplayAt(1), isFalse); + }); }); group('getEewAt', () { diff --git a/test/features/earthquake/data/eew_replay_source_test.dart b/test/features/earthquake/data/eew_replay_source_test.dart index 9dcb9beae..50cd64bdc 100644 --- a/test/features/earthquake/data/eew_replay_source_test.dart +++ b/test/features/earthquake/data/eew_replay_source_test.dart @@ -34,6 +34,12 @@ class _FakeEarthquakeApi implements EarthquakeApi { return nextEewAt as List; } + @override + Future hasReplayAt(int seconds) async { + await getRtsAt(seconds); + return true; + } + @override Future> getRtsAt(int seconds) => throw UnimplementedError(); diff --git a/test/features/earthquake/data/eew_repository_impl_test.dart b/test/features/earthquake/data/eew_repository_impl_test.dart index 2585c5200..31c3cbaf5 100644 --- a/test/features/earthquake/data/eew_repository_impl_test.dart +++ b/test/features/earthquake/data/eew_repository_impl_test.dart @@ -22,6 +22,12 @@ class _FakeEarthquakeApi implements EarthquakeApi { return nextEewRealtime as List; } + @override + Future hasReplayAt(int seconds) async { + await getRtsAt(seconds); + return true; + } + @override Future> getRtsAt(int seconds) => throw UnimplementedError(); diff --git a/test/features/earthquake/data/monitor_demo_test.dart b/test/features/earthquake/data/monitor_demo_test.dart index 6b0130118..d764e2c57 100644 --- a/test/features/earthquake/data/monitor_demo_test.dart +++ b/test/features/earthquake/data/monitor_demo_test.dart @@ -48,6 +48,9 @@ class _Reports implements ReportRepository { Future> get(String id) async => const Err(NoDataFailure('unused')); + @override + Future> hasReplayAt(int timestamp) => throw UnimplementedError(); + @override Future>> list({ int limit = 30, diff --git a/test/features/earthquake/data/report_repository_impl_test.dart b/test/features/earthquake/data/report_repository_impl_test.dart index b79911752..52e00fa8f 100644 --- a/test/features/earthquake/data/report_repository_impl_test.dart +++ b/test/features/earthquake/data/report_repository_impl_test.dart @@ -69,6 +69,12 @@ class _Api implements EarthquakeApi { @override Future> getEewAt(int seconds) => throw UnimplementedError(); + @override + Future hasReplayAt(int seconds) async { + await getRtsAt(seconds); + return true; + } + @override Future> getRtsAt(int seconds) => throw UnimplementedError(); diff --git a/test/features/earthquake/data/rts_replay_source_test.dart b/test/features/earthquake/data/rts_replay_source_test.dart index 18ddc5805..402adadc5 100644 --- a/test/features/earthquake/data/rts_replay_source_test.dart +++ b/test/features/earthquake/data/rts_replay_source_test.dart @@ -28,6 +28,12 @@ class _FakeEarthquakeApi implements EarthquakeApi { Object? error; int? lastSeconds; + @override + Future hasReplayAt(int seconds) async { + await getRtsAt(seconds); + return true; + } + @override Future> getRtsAt(int seconds) async { lastSeconds = seconds; diff --git a/test/features/earthquake/monitor_demo_test.dart b/test/features/earthquake/monitor_demo_test.dart index 86d750388..e8b9fa68c 100644 --- a/test/features/earthquake/monitor_demo_test.dart +++ b/test/features/earthquake/monitor_demo_test.dart @@ -26,6 +26,9 @@ class _FakeReports implements ReportRepository { @override Future> get(String id) => throw UnimplementedError(); + + @override + Future> hasReplayAt(int timestamp) => throw UnimplementedError(); } PartialEarthquakeReport _report({ diff --git a/test/features/earthquake/presentation/pages/report_detail_page_test.dart b/test/features/earthquake/presentation/pages/report_detail_page_test.dart index 652d7605b..d7448210f 100644 --- a/test/features/earthquake/presentation/pages/report_detail_page_test.dart +++ b/test/features/earthquake/presentation/pages/report_detail_page_test.dart @@ -175,6 +175,10 @@ class _Reports implements ReportRepository { Completer>? pending; int gets = 0; + /// What the archive probe answers; tests flip it between visits. + Result replay = const Ok(true); + final List replayProbes = []; + @override Future> get(String id) async { gets++; @@ -192,6 +196,12 @@ class _Reports implements ReportRepository { int page = 1, ReportListQuery query = ReportListQuery.empty, }) => throw UnimplementedError(); + + @override + Future> hasReplayAt(int timestamp) async { + replayProbes.add(timestamp); + return replay; + } } class _BytesClient extends ApiClient { @@ -405,6 +415,83 @@ void main() { ], ); + testWidgets('a 404 from the archive probe hides replay', (tester) async { + final report = _report(origin: DateTime.utc(2024, 2, 19, 15, 59, 59)); + final reports = _Reports() + ..next = Ok(report) + ..replay = const Ok(false); + final settings = SettingsStore.inMemory(); + await pumpPage( + tester, + reports: reports, + client: _BytesClient(RegionSelection(settings)), + settings: settings, + regions: RegionStore(settings), + towns: const TownDirectory({}), + router: nestedRouter(reports), + ); + await tester.pump(); + expect(reports.replayProbes, [report.time - 2000]); + await _expandSheet(tester); + expect(find.text('Report page'), findsOneWidget); + expect(find.byIcon(Icons.replay), findsNothing); + expect(find.text('Replay'), findsNothing); + }); + + testWidgets('a transient probe failure keeps replay', (tester) async { + final report = _report(); + final reports = _Reports() + ..next = Ok(report) + ..replay = const Err(NetworkFailure('offline')); + final settings = SettingsStore.inMemory(); + await pumpPage( + tester, + reports: reports, + client: _BytesClient(RegionSelection(settings)), + settings: settings, + regions: RegionStore(settings), + towns: const TownDirectory({}), + router: nestedRouter(reports), + ); + await tester.pump(); + await _expandSheet(tester); + expect(find.text('Replay'), findsOneWidget); + await tester.tap(find.text('Replay')); + await tester.pump(); + await tester.pump(); + expect(find.text('replay ${report.time - 2000}'), findsOneWidget); + }); + + testWidgets('every visit probes the archive again', (tester) async { + final report = _report(); + final reports = _Reports()..next = Ok(report); + final settings = SettingsStore.inMemory(); + final router = nestedRouter(reports); + await pumpPage( + tester, + reports: reports, + client: _BytesClient(RegionSelection(settings)), + settings: settings, + regions: RegionStore(settings), + towns: const TownDirectory({}), + router: router, + ); + await tester.pump(); + expect(reports.replayProbes, [report.time - 2000]); + + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('catalogue'), findsOneWidget); + + reports.replay = const Ok(false); + router.push('/earthquake/${report.id}'); + await tester.pump(); + await tester.pump(); + expect(reports.replayProbes, [report.time - 2000, report.time - 2000]); + await _expandSheet(tester); + expect(find.text('Replay'), findsNothing); + }); + testWidgets('a pending report stays on the loading view', (tester) async { final reports = _Reports()..pending = Completer>(); final settings = SettingsStore.inMemory(); diff --git a/test/features/earthquake/presentation/pages/report_list_page_test.dart b/test/features/earthquake/presentation/pages/report_list_page_test.dart index 8466aea0e..74d8da473 100644 --- a/test/features/earthquake/presentation/pages/report_list_page_test.dart +++ b/test/features/earthquake/presentation/pages/report_list_page_test.dart @@ -88,6 +88,9 @@ class _FakeReportRepository implements ReportRepository { @override Future> get(String id) => throw UnimplementedError(); + + @override + Future> hasReplayAt(int timestamp) => throw UnimplementedError(); } PartialEarthquakeReport _report( diff --git a/test/features/earthquake/presentation/report_list_controller_test.dart b/test/features/earthquake/presentation/report_list_controller_test.dart index ba0c38ff1..25fc723a8 100644 --- a/test/features/earthquake/presentation/report_list_controller_test.dart +++ b/test/features/earthquake/presentation/report_list_controller_test.dart @@ -36,6 +36,9 @@ class _FakeReportRepository implements ReportRepository { @override Future> get(String id) => throw UnimplementedError(); + + @override + Future> hasReplayAt(int timestamp) => throw UnimplementedError(); } PartialEarthquakeReport _report(String id) => PartialEarthquakeReport(