Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions lib/features/earthquake/data/earthquake_api.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -38,6 +39,47 @@ class EarthquakeApi {
(await _client.get(ApiTier.coreApi, '${ApiPaths.rtsArchive}/$seconds'))
as Map<String, dynamic>;

/// 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<bool> 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<bool> _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.
///
Expand Down
4 changes: 4 additions & 0 deletions lib/features/earthquake/data/report_repository_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ class ReportRepositoryImpl implements ReportRepository {
return EarthquakeReport.fromJson((raw as Map).cast<String, dynamic>());
});

@override
Future<Result<bool>> hasReplayAt(int timestamp) =>
guardResult(() => _api.hasReplayAt(timestamp ~/ 1000));

/// Skips malformed rows so one bad record cannot blank the catalogue.
static List<PartialEarthquakeReport> parseReportList(List<dynamic> raw) {
return [
Expand Down
8 changes: 8 additions & 0 deletions lib/features/earthquake/domain/report_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<Result<EarthquakeReport>> 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<Result<bool>> hasReplayAt(int timestamp);
}
52 changes: 45 additions & 7 deletions lib/features/earthquake/presentation/pages/report_detail_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<void> _probeReplay() async {
final repository = context.read<ReportRepository>();
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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<bool> expandedNotifier;
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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),
),
],
),
],
Expand Down
40 changes: 40 additions & 0 deletions test/features/earthquake/data/earthquake_api_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <dynamic>[];
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<DioException>()));
});

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', () {
Expand Down
6 changes: 6 additions & 0 deletions test/features/earthquake/data/eew_replay_source_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ class _FakeEarthquakeApi implements EarthquakeApi {
return nextEewAt as List<dynamic>;
}

@override
Future<bool> hasReplayAt(int seconds) async {
await getRtsAt(seconds);
return true;
}

@override
Future<Map<String, dynamic>> getRtsAt(int seconds) =>
throw UnimplementedError();
Expand Down
6 changes: 6 additions & 0 deletions test/features/earthquake/data/eew_repository_impl_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ class _FakeEarthquakeApi implements EarthquakeApi {
return nextEewRealtime as List<dynamic>;
}

@override
Future<bool> hasReplayAt(int seconds) async {
await getRtsAt(seconds);
return true;
}

@override
Future<Map<String, dynamic>> getRtsAt(int seconds) =>
throw UnimplementedError();
Expand Down
3 changes: 3 additions & 0 deletions test/features/earthquake/data/monitor_demo_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ class _Reports implements ReportRepository {
Future<Result<EarthquakeReport>> get(String id) async =>
const Err(NoDataFailure('unused'));

@override
Future<Result<bool>> hasReplayAt(int timestamp) => throw UnimplementedError();

@override
Future<Result<List<PartialEarthquakeReport>>> list({
int limit = 30,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ class _Api implements EarthquakeApi {
@override
Future<List<dynamic>> getEewAt(int seconds) => throw UnimplementedError();

@override
Future<bool> hasReplayAt(int seconds) async {
await getRtsAt(seconds);
return true;
}

@override
Future<Map<String, dynamic>> getRtsAt(int seconds) =>
throw UnimplementedError();
Expand Down
6 changes: 6 additions & 0 deletions test/features/earthquake/data/rts_replay_source_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ class _FakeEarthquakeApi implements EarthquakeApi {
Object? error;
int? lastSeconds;

@override
Future<bool> hasReplayAt(int seconds) async {
await getRtsAt(seconds);
return true;
}

@override
Future<Map<String, dynamic>> getRtsAt(int seconds) async {
lastSeconds = seconds;
Expand Down
3 changes: 3 additions & 0 deletions test/features/earthquake/monitor_demo_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ class _FakeReports implements ReportRepository {

@override
Future<Result<EarthquakeReport>> get(String id) => throw UnimplementedError();

@override
Future<Result<bool>> hasReplayAt(int timestamp) => throw UnimplementedError();
}

PartialEarthquakeReport _report({
Expand Down
Loading
Loading