diff --git a/lib/const/update_checker.dart b/lib/const/update_checker.dart index ba985f12..ce5d4e11 100644 --- a/lib/const/update_checker.dart +++ b/lib/const/update_checker.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart' show kIsWeb, visibleForTesting; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; +import 'package:icarus/services/app_error_reporter.dart'; import 'package:icarus/const/settings.dart'; import 'package:icarus/l10n/l10n.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; @@ -65,11 +66,20 @@ class UpdateChecker { if (response.statusCode == 200) { return json.decode(response.body) as Map; } else { - debugPrint('Failed to load version info: ${response.statusCode}'); + AppErrorReporter.reportWarning( + 'Checking for updates failed: the server answered ' + '${response.statusCode}.', + source: 'update_checker', + ); return null; } - } catch (e) { - debugPrint('Error fetching version info: $e'); + } catch (error, stackTrace) { + AppErrorReporter.reportWarning( + 'Checking for updates failed.', + source: 'update_checker', + error: error, + stackTrace: stackTrace, + ); return null; } } @@ -155,7 +165,13 @@ class UpdateChecker { source: 'windows_store', message: 'Windows Store checker plugin not available.', ); - } on PlatformException catch (e) { + } on PlatformException catch (e, stackTrace) { + AppErrorReporter.reportWarning( + 'Checking the Windows Store for updates failed.', + source: 'update_checker', + error: e, + stackTrace: stackTrace, + ); return UpdateCheckResult( isSupported: false, isUpdateAvailable: false, @@ -163,7 +179,13 @@ class UpdateChecker { errorCode: e.code.isEmpty ? null : int.tryParse(e.code), message: e.message, ); - } catch (e) { + } catch (e, stackTrace) { + AppErrorReporter.reportWarning( + 'Checking the Windows Store for updates failed.', + source: 'update_checker', + error: e, + stackTrace: stackTrace, + ); return UpdateCheckResult( isSupported: false, isUpdateAvailable: false, diff --git a/lib/main.dart b/lib/main.dart index 3b76dd9a..fb1cc3a3 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -120,9 +120,9 @@ Future _initializeDeepLinkHandling() async { _publishDeepLink(initialLink, source: 'initial'); } } catch (error, stackTrace) { - developer.log( - 'Failed to read initial deep link: $error', - name: 'deep_link', + AppErrorReporter.reportWarning( + 'Failed to read the link the app was opened with.', + source: 'deep_link', error: error, stackTrace: stackTrace, ); @@ -131,9 +131,9 @@ Future _initializeDeepLinkHandling() async { _deepLinkStreamSub ??= _appLinks.uriLinkStream.listen( (uri) => _publishDeepLink(uri, source: 'stream'), onError: (Object error, StackTrace stackTrace) { - developer.log( - 'Deep link stream error: $error', - name: 'deep_link', + AppErrorReporter.reportWarning( + 'A link sent to the running app failed to arrive.', + source: 'deep_link', error: error, stackTrace: stackTrace, ); diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart index 343917ab..bbc7ffdd 100644 --- a/lib/providers/auth_provider.dart +++ b/lib/providers/auth_provider.dart @@ -855,11 +855,13 @@ class AuthProvider extends Notifier { } void _handleSupabaseAuthStreamError(Object error, StackTrace stackTrace) { - log( - 'Supabase auth state stream error: $error', - name: 'auth', - error: error, - stackTrace: stackTrace, + AppErrorReporter.reportWarning( + 'Supabase auth state stream error.', + source: 'auth', + error: redactAuthDiagnosticText(error), + stackTrace: StackTrace.fromString( + redactAuthDiagnosticText(stackTrace), + ), ); // The token refresh couldn't reach Supabase (offline, or Supabase is @@ -907,9 +909,9 @@ class AuthProvider extends Notifier { throw StateError('Discord OAuth browser launch failed'); } } catch (error, stackTrace) { - log( - 'Discord sign-in failed: $error', - name: 'auth', + AppErrorReporter.reportWarning( + 'Discord sign-in failed.', + source: 'auth', error: error, stackTrace: stackTrace, ); @@ -960,9 +962,9 @@ class AuthProvider extends Notifier { state = state.copyWith(isLoading: false); return null; } catch (error, stackTrace) { - log( - 'Email/password sign-in failed: $error', - name: 'auth', + AppErrorReporter.reportWarning( + 'Email/password sign-in failed.', + source: 'auth', error: error, stackTrace: stackTrace, ); @@ -1081,9 +1083,9 @@ class AuthProvider extends Notifier { ProductMetrics.instance.signUp('signed_in'); return null; } catch (error, stackTrace) { - log( - 'Email/password sign-up failed: $error', - name: 'auth', + AppErrorReporter.reportWarning( + 'Email/password sign-up failed.', + source: 'auth', error: error, stackTrace: stackTrace, ); @@ -1156,9 +1158,9 @@ class AuthProvider extends Notifier { sent: true, ); } catch (error, stackTrace) { - log( - 'Password reset request failed: $error', - name: 'auth', + AppErrorReporter.reportWarning( + 'Password reset request failed.', + source: 'auth', error: error, stackTrace: stackTrace, ); @@ -1198,9 +1200,9 @@ class AuthProvider extends Notifier { ref.read(passwordRecoveryProvider.notifier).finish(); return null; } catch (error, stackTrace) { - log( - 'Setting a new password failed: $error', - name: 'auth', + AppErrorReporter.reportWarning( + 'Setting a new password failed.', + source: 'auth', error: error, stackTrace: stackTrace, ); @@ -1273,9 +1275,9 @@ class AuthProvider extends Notifier { convexAuthStatus: ConvexAuthStatus.signedOut, ); } catch (error, stackTrace) { - log( - 'Sign out failed: $error', - name: 'auth', + AppErrorReporter.reportWarning( + 'Sign out failed.', + source: 'auth', error: error, stackTrace: stackTrace, ); @@ -1512,11 +1514,13 @@ class AuthProvider extends Notifier { error is TimeoutException)) { _supabaseUnreachable = true; } - log( - 'Supabase refresh failed while fetching Convex token: $error', - name: 'auth', - error: error, - stackTrace: stackTrace, + AppErrorReporter.reportWarning( + 'Supabase refresh failed while fetching Convex token.', + source: 'auth', + error: redactAuthDiagnosticText(error), + stackTrace: StackTrace.fromString( + redactAuthDiagnosticText(stackTrace), + ), ); } } @@ -1529,11 +1533,13 @@ class AuthProvider extends Notifier { ); return session.accessToken; } catch (error, stackTrace) { - log( - 'Failed fetching Supabase access token for Convex: $error', - name: 'auth', - error: error, - stackTrace: stackTrace, + AppErrorReporter.reportWarning( + 'Failed fetching Supabase access token for Convex.', + source: 'auth', + error: redactAuthDiagnosticText(error), + stackTrace: StackTrace.fromString( + redactAuthDiagnosticText(stackTrace), + ), ); return null; } diff --git a/lib/providers/collab/cloud_media_upload_queue_provider.dart b/lib/providers/collab/cloud_media_upload_queue_provider.dart index 832f94ce..64df9388 100644 --- a/lib/providers/collab/cloud_media_upload_queue_provider.dart +++ b/lib/providers/collab/cloud_media_upload_queue_provider.dart @@ -890,9 +890,9 @@ class CloudMediaUploadQueueNotifier _logMedia( 'upload.pending_attach ${_describeJob(_getJob(job.jobId))}', ); - } catch (error) { + } catch (error, stackTrace) { if (await _dropIfStrategyDeleted(job, error)) return; - _reportMediaFailure('upload', error, job); + _reportMediaFailure('upload', error, stackTrace, job); await _markJobFailed( job, '$error', @@ -1067,9 +1067,9 @@ class CloudMediaUploadQueueNotifier _refreshState(); _logMedia('attach.success image=${job.assetPublicId} ' 'strategy=${job.strategyPublicId}'); - } catch (error) { + } catch (error, stackTrace) { if (await _dropIfStrategyDeleted(job, error)) return; - _reportMediaFailure('attach', error, job); + _reportMediaFailure('attach', error, stackTrace, job); final missingIntent = isMissingImageUploadIntentError(error); await _markJobFailed( missingIntent @@ -1834,12 +1834,14 @@ class CloudMediaUploadQueueNotifier void _reportMediaFailure( String stage, Object error, + StackTrace stackTrace, CloudMediaUploadJob job, ) { AppErrorReporter.reportWarning( redactSyncDiagnosticText('$stage.failed ${_describeJob(job)}'), source: 'cloud_media.upload_queue', error: redactSyncDiagnosticText(error), + stackTrace: StackTrace.fromString(redactSyncDiagnosticText(stackTrace)), ); } diff --git a/lib/providers/collab/remote_library_provider.dart b/lib/providers/collab/remote_library_provider.dart index 276c9f07..3ffcf91f 100644 --- a/lib/providers/collab/remote_library_provider.dart +++ b/lib/providers/collab/remote_library_provider.dart @@ -119,6 +119,12 @@ final cloudFolderTreeProvider = yield const []; return; } + AppErrorReporter.reportWarning( + 'Reading the cloud library folders failed.', + source: 'remote_library:folder_tree', + error: error, + stackTrace: stackTrace, + ); rethrow; } }); @@ -229,6 +235,12 @@ final cloudStrategiesProvider = yield const []; return; } + AppErrorReporter.reportWarning( + 'Reading the cloud library strategies failed.', + source: 'remote_library:strategies', + error: error, + stackTrace: stackTrace, + ); rethrow; } }); diff --git a/lib/providers/collab/remote_strategy_snapshot_provider.dart b/lib/providers/collab/remote_strategy_snapshot_provider.dart index c1a3f698..11dac53f 100644 --- a/lib/providers/collab/remote_strategy_snapshot_provider.dart +++ b/lib/providers/collab/remote_strategy_snapshot_provider.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:developer'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:icarus/services/app_error_reporter.dart'; import 'package:icarus/collab/cloud_library_copy.dart'; import 'package:icarus/collab/cloud_payload_upgrade.dart'; import 'package:icarus/collab/cloud_strategy_copy_box.dart'; @@ -453,8 +454,13 @@ class RemoteEditorSnapshotNotifier if (_keepsCopy && isConvexReadUnanswered(error) && _activeStrategyPublicId == strategyPublicId) { - log('Remote editor read failed, reading the copy: $error', - name: 'remote_editor', error: error, stackTrace: stackTrace); + _reportWarning( + 'Reading the open cloud strategy failed; showing the copy kept ' + 'on this computer.', + source: 'remote_editor', + error: error, + stackTrace: stackTrace, + ); if (_showCopy(strategyPublicId)) return; if (state.valueOrNull == null && state.error is! StrategyAccessLost) { state = AsyncError( @@ -722,9 +728,12 @@ class RemoteEditorSnapshotNotifier /// The copy is a cache: a write that fails is logged and the editor goes /// on. void _keep(Future Function() write) { - void report(Object error, StackTrace stackTrace) => - log('Keeping a cloud answer on this computer failed: $error', - name: 'remote_editor', error: error, stackTrace: stackTrace); + void report(Object error, StackTrace stackTrace) => _reportWarning( + 'Keeping a copy of the cloud strategy on this computer failed.', + source: 'remote_editor', + error: error, + stackTrace: stackTrace, + ); try { unawaited(write().catchError(report)); } catch (error, stackTrace) { @@ -819,14 +828,40 @@ class RemoteEditorSnapshotNotifier return; } ref.read(clientUpgradeRequiredProvider.notifier).noteError(error); - log('Remote editor read failed: $error', - name: 'remote_editor', error: error, stackTrace: stackTrace); + _reportWarning( + 'Reading the open cloud strategy failed.', + source: 'remote_editor:$source', + error: error, + stackTrace: stackTrace, + ); // A read that failed for another reason (offline, say) says nothing // about access already confirmed gone. if (state.error is StrategyAccessLost) return; state = AsyncError(error, stackTrace); } + /// Writes a failed read to the debug report with the share link's code + /// taken out: a viewer reads with it, and a server error can quote the + /// arguments it was sent. + void _reportWarning( + String message, { + required String source, + required Object error, + StackTrace? stackTrace, + }) { + final token = _shareToken; + String redact(Object? text) => token == null || token.isEmpty + ? '$text' + : '$text'.replaceAll(token, ''); + AppErrorReporter.reportWarning( + message, + source: source, + error: redact(error), + stackTrace: + stackTrace == null ? null : StackTrace.fromString(redact(stackTrace)), + ); + } + void _handleSubscriptionError({ required String source, required Object error, @@ -840,8 +875,12 @@ class RemoteEditorSnapshotNotifier )); return; } - log('Remote editor subscription failed: $error', - name: 'remote_editor', error: error, stackTrace: stackTrace); + _reportWarning( + 'Watching the open cloud strategy for changes failed.', + source: 'remote_editor:$source', + error: error, + stackTrace: stackTrace, + ); // A read again would be refused again; the sync button says why. if (ref.read(clientUpgradeRequiredProvider.notifier).noteError(error)) { return; diff --git a/lib/providers/drawing_provider.dart b/lib/providers/drawing_provider.dart index 97f0e874..e1690c3f 100644 --- a/lib/providers/drawing_provider.dart +++ b/lib/providers/drawing_provider.dart @@ -15,6 +15,7 @@ import 'package:icarus/const/settings.dart'; import 'package:icarus/const/traversal_speed.dart'; import 'package:icarus/providers/action_provider.dart'; import 'package:icarus/providers/action_history_models.dart'; +import 'package:icarus/services/app_error_reporter.dart'; import 'package:uuid/uuid.dart'; class DrawingState { @@ -226,18 +227,26 @@ class DrawingProvider extends Notifier { static List fromJson(String jsonString) { final List jsonList = jsonDecode(jsonString); - final result = jsonList - .map((json) { - try { - return _deserializeDrawingElement(json as Map); - } catch (e) { - dev.log(e.toString()); - return null; - } - }) - .whereType() - .toList(); - + final result = []; + for (var i = 0; i < jsonList.length; i++) { + final json = jsonList[i]; + try { + result.add(_deserializeDrawingElement(json as Map)); + } catch (error, stackTrace) { + // The page still opens with the drawings that could be read; this + // says which one it lost, by its kind and place, not its content. + final type = json is Map ? '${json['type'] ?? 'untyped'}' : 'not a map'; + AppErrorReporter.reportError( + "A drawing couldn't be read and was left off the page " + '(drawing ${i + 1} of ${jsonList.length}, type ' + '${type.length > 40 ? '${type.substring(0, 40)}...' : type}).', + source: 'DrawingProvider.fromJson', + error: error, + stackTrace: stackTrace, + promptUser: false, + ); + } + } return result; } diff --git a/lib/providers/replay_library_provider.dart b/lib/providers/replay_library_provider.dart index 96184717..43232ae1 100644 --- a/lib/providers/replay_library_provider.dart +++ b/lib/providers/replay_library_provider.dart @@ -117,9 +117,25 @@ class ReplayLibrary extends AsyncNotifier> { ) async { try { return (probe: await ref.read(replayProbeProvider)(path), error: null); - } on ReplayDecodeException catch (error) { + } on ReplayDecodeException catch (error, stackTrace) { + // A file we can't read is the file's problem; a decoder that can't + // run ('io') is ours. + if (error.code == 'io') { + AppErrorReporter.reportWarning( + 'The replay decoder could not run.', + source: 'replay_library', + error: error, + stackTrace: stackTrace, + ); + } return (probe: null, error: error); - } catch (error) { + } catch (error, stackTrace) { + AppErrorReporter.reportWarning( + 'Reading a replay file failed unexpectedly.', + source: 'replay_library', + error: error, + stackTrace: stackTrace, + ); return ( probe: null, error: const ReplayDecodeException( diff --git a/lib/providers/share_link_provider.dart b/lib/providers/share_link_provider.dart index df721ff3..f70dcbbe 100644 --- a/lib/providers/share_link_provider.dart +++ b/lib/providers/share_link_provider.dart @@ -7,6 +7,7 @@ import 'package:icarus/l10n/l10n.dart'; import 'package:icarus/providers/auth_provider.dart'; import 'package:icarus/providers/folder_provider.dart'; import 'package:icarus/providers/library_workspace_provider.dart'; +import 'package:icarus/services/app_error_reporter.dart'; import 'package:icarus/services/browser_url.dart'; import 'package:icarus/share/current_share_origin.dart'; import 'package:icarus/share/pending_share_code_store.dart'; @@ -154,6 +155,7 @@ class ShareLinkController extends Notifier { ); return false; } + _reportFailure('Adding a shared link failed', token, error, stackTrace); // The user is told (here, or inline by the dialog), so the code is done // with. Keeping it would replay the failure on every web page reload. _release(generation); @@ -167,6 +169,24 @@ class ShareLinkController extends Notifier { } } + /// Writes a failed link to the debug report, with the link's code taken + /// out: the code is what lets anyone open the strategy. + void _reportFailure( + String what, + String token, + Object error, + StackTrace stackTrace, + ) { + String redact(Object text) => + token.isEmpty ? '$text' : '$text'.replaceAll(token, ''); + AppErrorReporter.reportWarning( + '$what.', + source: 'share_link', + error: redact(error), + stackTrace: StackTrace.fromString(redact(stackTrace)), + ); + } + /// Opens a strategy link for a reader with no account, read-only. The code /// stays held, and the page keeps its /share/ URL, so a reload opens /// it again. Signing in joins an edit link; a view link stays read-only @@ -193,8 +213,14 @@ class ShareLinkController extends Notifier { (strategyPublicId: strategyPublicId, token: token); ref.read(sharedStrategyToOpenProvider.notifier).state = strategyPublicId; return true; - } catch (error) { + } catch (error, stackTrace) { if (_superseded(token, generation)) return false; + _reportFailure( + 'Opening a shared link signed out failed', + token, + error, + stackTrace, + ); final revoked = isShareLinkRevokedError(error); if (revoked || isTypedConvexNotFoundError(error)) { _release(generation); @@ -240,6 +266,8 @@ class ShareLinkController extends Notifier { ); return false; } + _reportFailure( + 'Previewing a shared link failed', token, error, stackTrace); final revoked = isShareLinkRevokedError(error); if (revoked || isTypedConvexNotFoundError(error)) { _release(generation); diff --git a/lib/providers/strategy_provider.dart b/lib/providers/strategy_provider.dart index 3ac33db6..033daedf 100644 --- a/lib/providers/strategy_provider.dart +++ b/lib/providers/strategy_provider.dart @@ -3,6 +3,7 @@ import 'dart:developer'; import 'dart:io'; import 'dart:math' show max; import 'package:flutter/foundation.dart' show kIsWeb, visibleForTesting; +import 'package:icarus/services/app_error_reporter.dart'; import 'package:icarus/providers/collab/move_to_cloud_provider.dart'; import 'package:icarus/collab/durable_strategy_outbox.dart'; import 'package:icarus/config/platform_policy.dart'; @@ -1321,8 +1322,13 @@ class StrategyProvider extends Notifier { strategyPublicId: strategyId, pagePublicId: targetPageId, ); - } catch (error) { - log('Could not read page $targetPageId to copy onto it: $error'); + } catch (error, stackTrace) { + AppErrorReporter.reportWarning( + 'Could not read the page to copy onto it.', + source: 'strategy.copyToPage', + error: error, + stackTrace: stackTrace, + ); return PageCopyResult.unreachable; } // Access can drop while the page is read; a reader can still read it. @@ -1538,8 +1544,13 @@ class StrategyProvider extends Notifier { }) async { try { await _syncCurrentPageToHive(); - } catch (error) { - log('Could not save the page before copying lineups: $error'); + } catch (error, stackTrace) { + AppErrorReporter.reportWarning( + 'Could not save the page before copying lineups.', + source: 'strategy.copyLineUps', + error: error, + stackTrace: stackTrace, + ); return PageCopyResult.notSaved; } if (state.strategyId != strategyId) return PageCopyResult.unavailable; @@ -1580,8 +1591,13 @@ class StrategyProvider extends Notifier { ); try { await box.put(updated.id, updated); - } catch (error) { - log('Writing lineups to page ${target.id} failed: $error'); + } catch (error, stackTrace) { + AppErrorReporter.reportWarning( + 'Writing lineups to another page failed.', + source: 'strategy.copyLineUps', + error: error, + stackTrace: stackTrace, + ); // Hive can store a write and then fail tidying its file, so what the // box holds decides whether the lineups are there. final stored = box.get(strategyId)?.pages.where((p) => p.id == target.id); @@ -1632,8 +1648,13 @@ class StrategyProvider extends Notifier { strategyPublicId: strategyId, pagePublicId: pageId, ); - } catch (error) { - log('Could not read page $pageId to copy lineups onto it: $error'); + } catch (error, stackTrace) { + AppErrorReporter.reportWarning( + 'Could not read the page to copy lineups onto it.', + source: 'strategy.copyLineUps', + error: error, + stackTrace: stackTrace, + ); return PageCopyResult.unreachable; } // Access can drop while the page is read; a reader can still read it. @@ -2499,9 +2520,9 @@ class StrategyProvider extends Notifier { ], ); } on FileSystemException catch (error, stackTrace) { - log( - 'Failed to copy the images of $strategyID: $error', - name: 'strategy', + AppErrorReporter.reportWarning( + 'Failed to copy the images of a strategy being duplicated.', + source: 'strategy.duplicate', error: error, stackTrace: stackTrace, ); diff --git a/lib/replay_view.dart b/lib/replay_view.dart index 05f10efe..7f6c5df0 100644 --- a/lib/replay_view.dart +++ b/lib/replay_view.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:icarus/services/app_error_reporter.dart'; import 'package:icarus/const/maps.dart'; import 'package:icarus/const/settings.dart'; import 'package:icarus/const/shortcut_info.dart'; @@ -133,11 +134,14 @@ class _ReplayViewState extends ConsumerState unawaited(_startConeCuts()); claimEditorState(); _ticker.start(); - } on ReplayDecodeException catch (error) { + } on ReplayDecodeException catch (error, stackTrace) { + if (!error.isCancelled) _reportFailure(error, stackTrace); if (mounted && !error.isCancelled) setState(() => _error = error); - } on FormatException catch (error) { + } on FormatException catch (error, stackTrace) { + _reportFailure(error, stackTrace); _fail(ReplayDecodeException('corrupt', error.message)); - } catch (error) { + } catch (error, stackTrace) { + _reportFailure(error, stackTrace); // Whatever else went wrong, the screen must not sit on "Reading". _fail(ReplayDecodeException('io', '$error')); } finally { @@ -197,6 +201,16 @@ class _ReplayViewState extends ConsumerState } } + /// Puts a replay that couldn't open in the debug report. + void _reportFailure(Object error, StackTrace stackTrace) { + AppErrorReporter.reportWarning( + "A replay couldn't be opened.", + source: 'replay_view', + error: error, + stackTrace: stackTrace, + ); + } + void _fail(ReplayDecodeException error) { if (mounted) setState(() => _error = error); } @@ -528,9 +542,7 @@ class _ReplayLoading extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - failure == null - ? l10n.replayReading - : l10n.replayOpenThisFailed, + failure == null ? l10n.replayReading : l10n.replayOpenThisFailed, style: theme.textTheme.p, ), const SizedBox(height: 12), diff --git a/lib/services/app_error_reporter.dart b/lib/services/app_error_reporter.dart index 2a745ac9..01cbbc3b 100644 --- a/lib/services/app_error_reporter.dart +++ b/lib/services/app_error_reporter.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:developer' as developer; import 'dart:io'; +import 'dart:math' as math; import 'dart:ui' show PlatformDispatcher; import 'package:flutter/foundation.dart' @@ -161,6 +162,40 @@ class AppErrorReporter { } } + static final _emailDomain = RegExp(r'[\w-]{1,63}(\.[\w-]{1,63}){1,8}'); + static final _emailLocalChar = RegExp(r"[\w.%+'-]"); + + /// [text] with every email address replaced. Sign-in errors can quote + /// the address the user typed, and a log entry is kept on disk and + /// pasted into chats. + /// + /// It looks outward from each @ rather than matching from every + /// character, so a long entry costs one pass however few @s it has. + @visibleForTesting + static String withoutEmails(String text) { + var at = text.indexOf('@'); + if (at < 0) return text; + final result = StringBuffer(); + var copiedTo = 0; + while (at >= 0) { + var start = at; + while (start > copiedTo && + at - start < 64 && + _emailLocalChar.hasMatch(text[start - 1])) { + start--; + } + final domain = _emailDomain.matchAsPrefix(text, at + 1); + if (start < at && domain != null) { + result + ..write(text.substring(copiedTo, start)) + ..write(''); + copiedTo = domain.end; + } + at = text.indexOf('@', math.max(at + 1, copiedTo)); + } + return (result..write(text.substring(copiedTo))).toString(); + } + static DebugLogEntry addDebugLog( String message, { DebugLogLevel level = DebugLogLevel.info, @@ -169,14 +204,15 @@ class AppErrorReporter { StackTrace? stackTrace, String? recentActivity, }) { - final errorText = error?.toString(); + final errorText = error == null ? null : withoutEmails('$error'); + message = withoutEmails(message); final entry = DebugLogEntry( timestamp: DateTime.now(), level: level, message: message, source: source, errorText: errorText, - stackTrace: stackTrace?.toString(), + stackTrace: stackTrace == null ? null : withoutEmails('$stackTrace'), recentActivity: recentActivity, ); diff --git a/test/services/dropped_drawing_report_test.dart b/test/services/dropped_drawing_report_test.dart new file mode 100644 index 00000000..9cbc43d8 --- /dev/null +++ b/test/services/dropped_drawing_report_test.dart @@ -0,0 +1,55 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:icarus/const/drawing_element.dart'; +import 'package:icarus/providers/drawing_provider.dart'; +import 'package:icarus/services/app_error_reporter.dart'; +import 'package:path/path.dart' as path; + +void main() { + late Directory tempDir; + late String logPath; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('icarus-dropped-drawing-'); + logPath = path.join(tempDir.path, 'icarus_debug.log'); + await AppErrorReporter.initializePersistedLog(logPath); + }); + + tearDown(() async { + await AppErrorReporter.flushPersistedLog(); + await tempDir.delete(recursive: true); + }); + + test('a drawing that cannot be read is reported, not dropped silently', + () async { + final line = Line( + lineStart: const Offset(120, 340), + lineEnd: const Offset(480, 360), + color: Colors.red, + isDotted: false, + hasArrow: true, + id: 'kept-line', + ); + final saved = jsonDecode(DrawingProvider.objectToJson([line])) as List; + final broken = Map.from(saved.single as Map) + ..['id'] = 'broken-line' + ..remove('lineEnd'); + + final decoded = + DrawingProvider.fromJson(jsonEncode([saved.single, broken])); + await AppErrorReporter.flushPersistedLog(); + + expect(decoded.map((drawing) => drawing.id), ['kept-line']); + final log = await File(logPath).readAsString(); + expect(log, contains('ERROR [DrawingProvider.fromJson]')); + expect( + log, + contains("A drawing couldn't be read and was left off the page " + '(drawing 2 of 2, type lineDrawing).'), + ); + expect(log, contains('Stack trace:')); + }); +} diff --git a/test/services/report_without_emails_test.dart b/test/services/report_without_emails_test.dart new file mode 100644 index 00000000..5d44514b --- /dev/null +++ b/test/services/report_without_emails_test.dart @@ -0,0 +1,33 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:icarus/providers/in_app_debug_provider.dart'; +import 'package:icarus/services/app_error_reporter.dart'; + +void main() { + test('an email in a failure never reaches the log', () { + final entry = AppErrorReporter.addDebugLog( + 'Email/password sign-up failed.', + level: DebugLogLevel.warning, + source: 'auth', + // Supabase quotes the address it refused. + error: 'AuthApiException(message: Unable to send email to ' + 'sam.o-neil+icarus@mail.example.co.uk, statusCode: 500)', + stackTrace: StackTrace.fromString("#0 resetFor(sam.o'neil@example.com)"), + ); + + final text = entry.toClipboardText(); + expect(text, isNot(contains('@'))); + expect( + text, + contains('Unable to send email to , statusCode: 500'), + ); + expect(text, contains('#0 resetFor()')); + }); + + test('a long entry is checked quickly, with or without an @', () { + final long = '${'x' * 1000000}@${'y' * 1000000}'; + final watch = Stopwatch()..start(); + AppErrorReporter.withoutEmails(long); + AppErrorReporter.withoutEmails('x' * 2000000); + expect(watch.elapsed, lessThan(const Duration(seconds: 2))); + }); +}