feat(#1213): notice a run that ended badly
A run marker records whether the app is on screen and whether an unhandled Dart error happened; a clean exit removes it (awaited before a desktop window closes). At the next start, a marker left on screen is an unexpected exit, one left in the background is the OS reclaiming memory and is not offered, and an unreadable one is asked about. New Android ANR and crash exit records (not backfill) name the failure. Failed image loads do not count. On web only an unhandled error counts, since closing a tab is not an exit Flutter sees. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>pull/1237/head
parent
0ba22af276
commit
547d399399
@ -0,0 +1,178 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// Why the last run is worth sending logs about.
|
||||
enum FailureKind {
|
||||
/// Android says the process crashed (Java or native).
|
||||
crash,
|
||||
|
||||
/// Android says the process stopped responding.
|
||||
anr,
|
||||
|
||||
/// An error reached the top of the Dart code.
|
||||
dartError,
|
||||
|
||||
/// The run ended while the app was on screen, with no clean exit.
|
||||
foregroundExit,
|
||||
|
||||
/// The run ended and whether it was on screen is not known.
|
||||
unknownExit,
|
||||
}
|
||||
|
||||
/// Notices a run that ended badly so the next launch can offer to send the
|
||||
/// logs (#1213).
|
||||
///
|
||||
/// A run marker is written at start and kept up to date with whether the app
|
||||
/// is on screen. A clean exit removes it. So at the next start, a marker that
|
||||
/// says "on screen" means the app died while the user was looking at it; one
|
||||
/// that says "in the background" means the OS reclaimed memory, which is not a
|
||||
/// failure. Android exit records and unhandled Dart errors are recorded too.
|
||||
class FailureMonitor extends ChangeNotifier {
|
||||
FailureMonitor({SharedPreferences? prefs, this.isWeb = kIsWeb})
|
||||
: _prefsOverride = prefs;
|
||||
|
||||
final bool isWeb;
|
||||
|
||||
static final FailureMonitor instance = FailureMonitor();
|
||||
|
||||
static const String markerKey = 'run_marker_v1';
|
||||
|
||||
final SharedPreferences? _prefsOverride;
|
||||
SharedPreferences get _prefs => _prefsOverride ?? PrefsManager.instance;
|
||||
|
||||
FailureKind? _pending;
|
||||
AppLifecycleListener? _lifecycle;
|
||||
bool _dartError = false;
|
||||
bool _foreground = true;
|
||||
|
||||
/// The previous run's failure, until the user answers the offer.
|
||||
FailureKind? get pending => _pending;
|
||||
|
||||
/// Read what the previous run left, then start this run's marker. Call once,
|
||||
/// after prefs are ready and before `runApp`.
|
||||
void start({bool installHandlers = true}) {
|
||||
_pending = _readPrevious();
|
||||
if (_pending != null) {
|
||||
appLogger.warn(
|
||||
'Previous run ended badly: ${_pending!.name}',
|
||||
tag: 'FailureMonitor',
|
||||
);
|
||||
}
|
||||
_foreground = true;
|
||||
_dartError = false;
|
||||
_writeMarker();
|
||||
if (installHandlers) _installHandlers();
|
||||
}
|
||||
|
||||
FailureKind? _readPrevious() {
|
||||
final raw = _prefs.getString(markerKey);
|
||||
if (raw == null) return null;
|
||||
try {
|
||||
final marker = jsonDecode(raw) as Map<String, dynamic>;
|
||||
if (marker['dartError'] == true) return FailureKind.dartError;
|
||||
// Closing a browser tab is not an exit Flutter can see, so on web only
|
||||
// an unhandled error counts: a marker left on screen means nothing.
|
||||
if (isWeb) return null;
|
||||
return switch (marker['foreground']) {
|
||||
true => FailureKind.foregroundExit,
|
||||
false => null,
|
||||
_ => FailureKind.unknownExit,
|
||||
};
|
||||
} catch (_) {
|
||||
return FailureKind.unknownExit;
|
||||
}
|
||||
}
|
||||
|
||||
void _writeMarker() {
|
||||
_prefs.setString(
|
||||
markerKey,
|
||||
jsonEncode({'foreground': _foreground, 'dartError': _dartError}),
|
||||
);
|
||||
}
|
||||
|
||||
void _installHandlers() {
|
||||
final priorFlutter = FlutterError.onError;
|
||||
FlutterError.onError = (details) {
|
||||
if (countsAsFailure(details)) recordDartError();
|
||||
priorFlutter?.call(details);
|
||||
};
|
||||
final dispatcher = PlatformDispatcher.instance;
|
||||
final priorDispatcher = dispatcher.onError;
|
||||
dispatcher.onError = (error, stack) {
|
||||
recordDartError();
|
||||
appLogger.error('Unhandled error: $error\n$stack', tag: 'FailureMonitor');
|
||||
return priorDispatcher?.call(error, stack) ?? false;
|
||||
};
|
||||
_lifecycle = AppLifecycleListener(
|
||||
onStateChange: onLifecycle,
|
||||
onExitRequested: () async {
|
||||
await markCleanExit();
|
||||
return AppExitResponse.exit;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Image loads that fail (a missing map tile) are reported as Flutter
|
||||
/// errors but are not the app breaking.
|
||||
static bool countsAsFailure(FlutterErrorDetails details) =>
|
||||
!details.silent && details.library != 'image resource service';
|
||||
|
||||
@visibleForTesting
|
||||
void onLifecycle(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.detached) {
|
||||
markCleanExit();
|
||||
return;
|
||||
}
|
||||
final foreground =
|
||||
state == AppLifecycleState.resumed ||
|
||||
state == AppLifecycleState.inactive;
|
||||
if (foreground == _foreground) return;
|
||||
_foreground = foreground;
|
||||
_writeMarker();
|
||||
}
|
||||
|
||||
void recordDartError() {
|
||||
if (_dartError) return;
|
||||
_dartError = true;
|
||||
_writeMarker();
|
||||
}
|
||||
|
||||
/// Awaited before a desktop window is allowed to close, so the removal
|
||||
/// lands before the process ends.
|
||||
Future<void> markCleanExit() => _prefs.remove(markerKey);
|
||||
|
||||
/// Android exit records read at this start (#906). Backfilled records,
|
||||
/// read on the first launch with the reader, are old news and not offered.
|
||||
void recordExitReasons(Iterable<String> reasons, {required bool backfill}) {
|
||||
if (backfill) return;
|
||||
final set = reasons.toSet();
|
||||
final kind = set.contains('ANR')
|
||||
? FailureKind.anr
|
||||
: (set.contains('CRASH') || set.contains('CRASH_NATIVE'))
|
||||
? FailureKind.crash
|
||||
: null;
|
||||
if (kind == null) return;
|
||||
_pending = kind;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// The user answered the offer, whichever way.
|
||||
void resolve() {
|
||||
if (_pending == null) return;
|
||||
_pending = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_lifecycle?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,145 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/services/failure_monitor.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Future<SharedPreferences> _prefs([Map<String, Object> values = const {}]) {
|
||||
SharedPreferences.setMockInitialValues(values);
|
||||
return SharedPreferences.getInstance();
|
||||
}
|
||||
|
||||
Map<String, Object> _marker(Object? foreground, {bool dartError = false}) => {
|
||||
FailureMonitor.markerKey: jsonEncode({
|
||||
'foreground': foreground,
|
||||
'dartError': dartError,
|
||||
}),
|
||||
};
|
||||
|
||||
Future<FailureKind?> _startAfter(Map<String, Object> previous) async {
|
||||
final m = FailureMonitor(prefs: await _prefs(previous));
|
||||
m.start(installHandlers: false);
|
||||
return m.pending;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('how the last run ended', () {
|
||||
test('a first run, or a clean exit, leaves nothing to offer', () async {
|
||||
expect(await _startAfter({}), isNull);
|
||||
});
|
||||
|
||||
test('dying on screen is an unexpected exit', () async {
|
||||
expect(await _startAfter(_marker(true)), FailureKind.foregroundExit);
|
||||
});
|
||||
|
||||
test('dying in the background is the OS reclaiming memory', () async {
|
||||
expect(await _startAfter(_marker(false)), isNull);
|
||||
});
|
||||
|
||||
test('a marker that cannot say where the app was is asked about', () async {
|
||||
expect(await _startAfter(_marker(null)), FailureKind.unknownExit);
|
||||
expect(
|
||||
await _startAfter({FailureMonitor.markerKey: 'not json'}),
|
||||
FailureKind.unknownExit,
|
||||
);
|
||||
});
|
||||
|
||||
test('on web only an unhandled error counts', () async {
|
||||
Future<FailureKind?> onWeb(Map<String, Object> previous) async {
|
||||
final m = FailureMonitor(prefs: await _prefs(previous), isWeb: true);
|
||||
m.start(installHandlers: false);
|
||||
return m.pending;
|
||||
}
|
||||
|
||||
expect(await onWeb(_marker(true)), isNull);
|
||||
expect(await onWeb(_marker(null)), isNull);
|
||||
expect(
|
||||
await onWeb(_marker(true, dartError: true)),
|
||||
FailureKind.dartError,
|
||||
);
|
||||
});
|
||||
|
||||
test('an unhandled Dart error wins over where the app was', () async {
|
||||
expect(
|
||||
await _startAfter(_marker(false, dartError: true)),
|
||||
FailureKind.dartError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('this run', () {
|
||||
late SharedPreferences prefs;
|
||||
late FailureMonitor m;
|
||||
Map<String, dynamic> marker() =>
|
||||
jsonDecode(prefs.getString(FailureMonitor.markerKey)!)
|
||||
as Map<String, dynamic>;
|
||||
|
||||
setUp(() async {
|
||||
prefs = await _prefs();
|
||||
m = FailureMonitor(prefs: prefs)..start(installHandlers: false);
|
||||
});
|
||||
|
||||
test('the marker follows the app on and off screen', () {
|
||||
expect(marker()['foreground'], isTrue);
|
||||
m.onLifecycle(AppLifecycleState.paused);
|
||||
expect(marker()['foreground'], isFalse);
|
||||
m.onLifecycle(AppLifecycleState.resumed);
|
||||
expect(marker()['foreground'], isTrue);
|
||||
m.onLifecycle(AppLifecycleState.hidden);
|
||||
expect(marker()['foreground'], isFalse);
|
||||
});
|
||||
|
||||
test('a clean exit removes the marker', () {
|
||||
m.onLifecycle(AppLifecycleState.detached);
|
||||
expect(prefs.containsKey(FailureMonitor.markerKey), isFalse);
|
||||
});
|
||||
|
||||
test('a Dart error is kept for the next launch', () async {
|
||||
m.recordDartError();
|
||||
expect(marker()['dartError'], isTrue);
|
||||
final next = FailureMonitor(prefs: prefs)..start(installHandlers: false);
|
||||
expect(next.pending, FailureKind.dartError);
|
||||
expect(marker()['dartError'], isFalse, reason: 'a new run starts clean');
|
||||
});
|
||||
|
||||
test('Android exit records name the failure, backfill does not', () {
|
||||
m.recordExitReasons(['LOW_MEMORY', 'USER_REQUESTED'], backfill: false);
|
||||
expect(m.pending, isNull);
|
||||
m.recordExitReasons(['ANR'], backfill: true);
|
||||
expect(m.pending, isNull);
|
||||
m.recordExitReasons(['CRASH_NATIVE'], backfill: false);
|
||||
expect(m.pending, FailureKind.crash);
|
||||
m.recordExitReasons(['CRASH', 'ANR'], backfill: false);
|
||||
expect(m.pending, FailureKind.anr);
|
||||
m.resolve();
|
||||
expect(m.pending, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
test('a failed map tile is not the app breaking', () {
|
||||
expect(
|
||||
FailureMonitor.countsAsFailure(
|
||||
FlutterErrorDetails(
|
||||
exception: Exception('404'),
|
||||
library: 'image resource service',
|
||||
),
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
FailureMonitor.countsAsFailure(
|
||||
FlutterErrorDetails(exception: Exception('x'), silent: true),
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
FailureMonitor.countsAsFailure(
|
||||
FlutterErrorDetails(exception: StateError('bad'), library: 'widgets'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
}
|
||||
Loading…
Reference in new issue