diff --git a/docs/mobile-diagnostic-reporting.md b/docs/mobile-diagnostic-reporting.md index a0d8f797db..ed61f10dbb 100644 --- a/docs/mobile-diagnostic-reporting.md +++ b/docs/mobile-diagnostic-reporting.md @@ -42,6 +42,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - **The reporting destination is a build-time setting**, named with the implementation to match the existing `BUZZ_` build settings. When it is absent, the app uses the do-nothing implementation and never initializes the SDK. There is no check on the kind of build, no in-app switch and no notice ([ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md)). - **Crashes and uncaught errors** are captured by the SDK's own handlers for native crashes, Flutter framework errors and uncaught asynchronous Dart errors, installed at startup around the app. - **Explicit error reports** are added at the places where the app meets something that should never happen: a relay frame or query response that cannot be decoded, a relay rejection whose reason says the app sent something invalid (except a refusal the app already handles as an expected outcome, such as an archived channel, an Unarchive of a channel that is no longer archived, a channel name that is taken, an agent whose policy refuses the addition, a guest adding people, a sole owner leaving or an event whose timestamp is outside the relay's window, which is counted; that last one is left out for every event, so a device with a wrong clock does not report every publish, at the cost of hiding a signed event retried after the window has passed), an account or push gateway response that cannot be understood, saved data that cannot be read back, and an event subscriber that throws while handling an event. +- **Escaped relay errors say which call failed and why.** An error from a relay call that nothing catches reaches the SDK on its own, not through the reporting module, and its text is removed, so on its own it would say only that some call failed. The relay's errors therefore carry the call (publish, query, history or subscribe) and a reason class as fixed values, and a report of one is tagged `relay.call` and `relay.reason`. The reason class is the relay's reason prefix (invalid, rate-limited, restricted, auth-required, blocked, duplicate, pow, unsupported or error), `timeout` when the call timed out in the app before the relay answered, and `other` for any other prefix. Never the relay's own text. The report is also grouped by call and reason, on top of the usual grouping by stack, so a rate limit and an invalid request from one place are separate issues. A publish, history request or live subscription keeps the stack of the code that made the call and gives it to the errors it completes later from a timer or socket callback, so the report's stack reaches app code instead of stopping in the SDK's error handler. Queries do the same for their timeouts. - **Routine failures are counted, never reported.** Timeouts, disconnects, unreachable or insecure hosts, rate limits, refused or expired sign-ins and server errors increment a count. That includes the relay's own errors, such as a query that timed out or too many subscriptions. Of the reasons a relay gives for a rejection, only the one that marks the request as invalid is reported, with the exception above; every other reason is counted. - **Networking measurements.** Every request through the app's shared HTTP client and every relay connection event (connected, disconnected, reconnect attempt, request timed out, subscription closed by the relay) is counted with four attributes: backend, endpoint, outcome and kind of failure. The backend is the host name of the server the app was talking to when it is one of the app's own (a relay the app has used this run, the build's Builderlab and push gateway); any other host, such as a remote image's, is counted as `external`, so a host that names a person never leaves the phone. Endpoints are names from a fixed list, never raw paths. Durations are recorded for requests (to response headers), for time to connect, for opening a channel (from asking for its newest history to showing it, first load only, including any wait for a reconnect in between; one that spans a move to the background or starts in the background is not counted, since it measured the time away, and the load after the return is a new open; one that started for another member or community is not counted; one the member backed out of still is, since the load took that long, unless they left while a lost connection was still reconnecting, before the history was asked for again; after a failed open, a retry counts as a new open; a refusal before the history was asked for counts as a failed open with no duration) and for recovering a lost relay connection (from the last frame the lost connection delivered to the next authenticated one, so time spent not noticing a dead socket counts; a quiet connection is taken to have been alive until two ping intervals before the loss, since pongs are not visible to the app, so an idle connection that closes cleanly can read up to a minute long; a loss in the background, or one followed by a move to the background, is not counted; a loss within the first seconds after a return from a brief stay in the background can reach back to before the stay, by at most the same minute). These two durations run on a monotonic clock, so a correction of the device's clock does not move them. A request the app gives up on at its own deadline is a timeout, including one whose successful response body is still arriving; one the app cancels (a view closing, an image scrolled away) is not counted. A request still in flight when the member signs out or switches is not counted for anyone. HTTP is measured where the app's shared HTTP client already classifies transport failures; relay connections are measured by hand in the relay session, since the SDK documents no WebSocket instrumentation. - **Counts are handed to the SDK as they happen**, including while the network is down. The app does no buffering of its own, and the SDK's default limit on unsent data is kept. Accepted consequence: in a long outage the oldest unsent reports can be dropped. diff --git a/mobile/lib/shared/diagnostics/diagnostic_filter.dart b/mobile/lib/shared/diagnostics/diagnostic_filter.dart index 0feac9949e..aa31465c21 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_filter.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_filter.dart @@ -1,6 +1,7 @@ import 'package:sentry_flutter/sentry_flutter.dart'; import 'diagnostic_reporter.dart'; +import 'relay_error_tags.dart'; /// The one filter every Dart report, breadcrumb and count passes through /// before it leaves the device. Reports the native SDKs capture themselves @@ -141,11 +142,14 @@ abstract final class DiagnosticFilter { key == installIdTag || _sdkAttributePrefixes.any(key.startsWith); - /// The app tags a report with where it came from and which installation - /// sent it; the SDK tags it with its origin and environment. + /// The app tags a report with where it came from, which installation sent + /// it and, for a relay error, the call and reason class; the SDK tags it + /// with its origin and environment. static bool _allowsTag(String key) => key == 'operation' || key == installIdTag || + key == RelayErrorTags.callTag || + key == RelayErrorTags.reasonTag || key.startsWith('event.') || allowsAttribute(key); diff --git a/mobile/lib/shared/diagnostics/diagnostic_startup.dart b/mobile/lib/shared/diagnostics/diagnostic_startup.dart index f45473f028..aeb36e01e8 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_startup.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_startup.dart @@ -11,6 +11,7 @@ import 'package:uuid/uuid.dart'; import '../http/app_http_client.dart'; import 'diagnostic_filter.dart'; import 'diagnostic_reporter.dart'; +import 'relay_error_tags.dart'; import 'sentry_diagnostic_reporter.dart'; /// The build's reporting destination, a Sentry DSN supplied at build time. @@ -151,7 +152,8 @@ void configureDiagnostics(SentryFlutterOptions options, String destination) { ..enableAppHangTracking = true ..anrEnabled = true ..enableWatchdogTerminationTracking = true - ..beforeSend = ((event, hint) => DiagnosticFilter.filterEvent(event)) + ..beforeSend = ((event, hint) => + DiagnosticFilter.filterEvent(RelayErrorTags.apply(event))) ..beforeBreadcrumb = ((crumb, hint) => DiagnosticFilter.filterBreadcrumb(crumb)) ..beforeSendMetric = ((metric, hint) => diff --git a/mobile/lib/shared/diagnostics/relay_error_tags.dart b/mobile/lib/shared/diagnostics/relay_error_tags.dart new file mode 100644 index 0000000000..dde0e849b5 --- /dev/null +++ b/mobile/lib/shared/diagnostics/relay_error_tags.dart @@ -0,0 +1,35 @@ +import 'package:sentry_flutter/sentry_flutter.dart'; + +import '../relay/relay_call_error.dart'; + +/// Says which relay call an error came from and why it failed, on a report +/// whose error is a [RelayCallError]. +/// +/// An error that escapes uncaught reaches the SDK from the zone's handler, +/// not through the reporter, and the filter replaces its text, so without +/// this a report of one says only that some relay call failed. The reason is +/// the relay's reason prefix or a timeout, never the relay's own text. +abstract final class RelayErrorTags { + /// Tag naming the relay call: publish, query, history or subscribe. + static const callTag = 'relay.call'; + + /// Tag naming the reason class, such as invalid or rate-limited. + static const reasonTag = 'relay.reason'; + + /// Adds the tags to [event], and splits its issue by call and reason on top + /// of the usual grouping by stack, so a rate limit and an invalid request + /// from the same call site are not one issue. Other events pass unchanged. + static SentryEvent apply(SentryEvent event) { + final error = event.throwable; + if (error is! RelayCallError) return event; + final call = error.call.name; + final reason = error.reason.tag; + event.tags = {...?event.tags, callTag: call, reasonTag: reason}; + event.fingerprint = [ + SentryEvent.defaultFingerprint, + 'relay.call:$call', + 'relay.reason:$reason', + ]; + return event; + } +} diff --git a/mobile/lib/shared/relay/relay.dart b/mobile/lib/shared/relay/relay.dart index 9ef42d2080..64e4b22f84 100644 --- a/mobile/lib/shared/relay/relay.dart +++ b/mobile/lib/shared/relay/relay.dart @@ -6,6 +6,7 @@ export 'media_image.dart'; export 'media_upload.dart'; export 'nostr_filters.dart'; export 'nostr_models.dart'; +export 'relay_call_error.dart'; export 'relay_closed_policy.dart'; export 'relay_error_text.dart'; export 'relay_client.dart'; diff --git a/mobile/lib/shared/relay/relay_call_error.dart b/mobile/lib/shared/relay/relay_call_error.dart new file mode 100644 index 0000000000..a8b48c35c3 --- /dev/null +++ b/mobile/lib/shared/relay/relay_call_error.dart @@ -0,0 +1,108 @@ +import 'dart:async'; + +/// The relay call an error came from. +enum RelayCall { + /// An EVENT sent over the socket and acknowledged with OK. + publish, + + /// A one-shot query over the relay's HTTP bridge. + query, + + /// A one-shot REQ over the socket, read until EOSE. + history, + + /// A live REQ, up to its first EOSE. + subscribe, +} + +/// The reason class of a failed relay call: the relay's own reason prefix, or +/// a timeout. Never the reason text, which is free-form and can quote what +/// the app sent. +enum RelayReason { + invalid('invalid'), + rateLimited('rate-limited'), + restricted('restricted'), + authRequired('auth-required'), + blocked('blocked'), + duplicate('duplicate'), + pow('pow'), + unsupported('unsupported'), + error('error'), + + /// The call timed out here, before the relay answered. + timeout('timeout'), + + /// A reason with no known prefix. + other('other'); + + const RelayReason(this.tag); + + /// The wording that leaves the device. + final String tag; + + static final _prefixes = { + for (final reason in values) + if (reason != timeout && reason != other) reason.tag: reason, + }; + + /// The class of a relay `OK` or `CLOSED` [message]: its prefix, up to the + /// first colon, when that is one of the relay's. + static RelayReason fromMessage(String message) { + final colon = message.indexOf(':'); + if (colon < 0) return other; + return _prefixes[message.substring(0, colon).trim().toLowerCase()] ?? other; + } + + /// The class of an HTTP error [status] from the relay's `/query`. Its body + /// is not read: the status alone says rate limit, refusal or server error. + static RelayReason fromHttpStatus(int status) => switch (status) { + 429 => rateLimited, + 401 => authRequired, + 403 => restricted, + >= 500 && < 600 => error, + _ => other, + }; +} + +/// An error from a relay call that says which call and why. +/// +/// Diagnostic reports of these carry [call] and [reason] as tags, because the +/// error's own text is removed before a report leaves the device. +abstract interface class RelayCallError implements Exception { + RelayCall get call; + RelayReason get reason; +} + +/// A relay call timed out before the relay answered. +class RelayTimeoutException extends TimeoutException implements RelayCallError { + RelayTimeoutException(this.call, String message, [Duration? duration]) + : super(message, duration); + + @override + final RelayCall call; + + @override + RelayReason get reason => RelayReason.timeout; + + /// The text without the duration, which [message] already states. Screens + /// show this text. + @override + String toString() => 'TimeoutException: $message'; +} + +/// The relay closed a history or live subscription with [message]. +class RelayClosedException implements RelayCallError { + RelayClosedException(this.call, this.message); + + @override + final RelayCall call; + + /// The relay's `CLOSED` reason. Callers read its text. + final String message; + + @override + RelayReason get reason => RelayReason.fromMessage(message); + + @override + String toString() => 'Exception: $message'; +} diff --git a/mobile/lib/shared/relay/relay_client.dart b/mobile/lib/shared/relay/relay_client.dart index 894aeb2f84..b2a7611afc 100644 --- a/mobile/lib/shared/relay/relay_client.dart +++ b/mobile/lib/shared/relay/relay_client.dart @@ -1,5 +1,6 @@ import 'package:http/http.dart' as http; import 'package:buzz/shared/http/app_http_client.dart'; +import 'relay_call_error.dart'; /// Lightweight HTTP context for talking to the Buzz relay. /// @@ -46,3 +47,18 @@ class RelayException implements Exception { return 'RelayException($statusCode): $trimmedBody'; } } + +/// The relay's `/query` answered with a non-2xx status. +/// +/// Callers that retry, fall back or give up read the [RelayException] status +/// and body as before. A diagnostic report of one is tagged with the call and +/// a reason class taken from the status alone, never the body. +class RelayQueryException extends RelayException implements RelayCallError { + RelayQueryException(super.statusCode, super.body); + + @override + RelayCall get call => RelayCall.query; + + @override + RelayReason get reason => RelayReason.fromHttpStatus(statusCode); +} diff --git a/mobile/lib/shared/relay/relay_http_query_client.dart b/mobile/lib/shared/relay/relay_http_query_client.dart index b42aafab29..9a58f2f7c0 100644 --- a/mobile/lib/shared/relay/relay_http_query_client.dart +++ b/mobile/lib/shared/relay/relay_http_query_client.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:http/http.dart' as http; import 'package:http/io_client.dart'; import 'package:buzz/shared/http/app_http_client.dart'; +import 'relay_call_error.dart'; import 'relay_query_response.dart' show RelayResponseTooLarge; @@ -38,6 +39,18 @@ class RelayHttpQueryClient { _ClientGeneration? _currentGeneration; final Set<_ClientGeneration> _generations = {}; + /// The error for a request that outlived [timeout]: a [call] when the + /// request is one, otherwise a plain [TimeoutException]. Its stack is the + /// caller's, since the timer that raises it has no frames from the app. + static TimeoutException _timedOut(Duration timeout, RelayCall? call) => + call == null + ? TimeoutException('Relay request timed out after $timeout', timeout) + : RelayTimeoutException( + call, + 'Relay query timed out after $timeout', + timeout, + ); + Future post( Uri url, { required Map headers, @@ -45,6 +58,7 @@ class RelayHttpQueryClient { required Duration timeout, http.Client Function(http.Client, bool Function())? decorate, }) async { + final callSite = StackTrace.current; final generation = _injectedClient == null ? (_currentGeneration ??= _createGeneration()) : null; @@ -73,7 +87,7 @@ class RelayHttpQueryClient { _currentGeneration = null; } generation?.retire(); - rethrow; + Error.throwWithStackTrace(_timedOut(timeout, RelayCall.query), callSite); } finally { active = false; generation?.release(); @@ -81,13 +95,16 @@ class RelayHttpQueryClient { } /// Sends a non-redirecting request, bounding bytes before buffering or parsing. - /// The deadline includes headers and the entire response body. + /// The deadline includes headers and the entire response body. A timeout is + /// a [RelayTimeoutException] for [call], or untyped when [call] is null. Future sendBounded( http.Request request, { required int maxBytes, required Duration timeout, + required RelayCall? call, http.Client Function(http.Client, bool Function())? decorate, }) async { + final callSite = StackTrace.current; // As in [post], a timed-out request on a shared session is aborted. final abort = Completer(); final sent = @@ -145,7 +162,7 @@ class RelayHttpQueryClient { _currentGeneration = null; } generation?.retire(); - rethrow; + Error.throwWithStackTrace(_timedOut(timeout, call), callSite); } finally { finished = true; // Cancelling an iterator that never listened leaves the body diff --git a/mobile/lib/shared/relay/relay_session.dart b/mobile/lib/shared/relay/relay_session.dart index 2fec7cd39f..d5da7cf379 100644 --- a/mobile/lib/shared/relay/relay_session.dart +++ b/mobile/lib/shared/relay/relay_session.dart @@ -19,6 +19,7 @@ import '../hosted/hosted_relay_auth.dart'; import '../hosted/builderlab_account.dart'; import 'nostr_filters.dart'; import 'nostr_models.dart'; +import 'relay_call_error.dart'; import 'relay_client.dart'; import 'relay_closed_policy.dart'; import 'relay_http_query_client.dart'; @@ -297,7 +298,7 @@ class RelaySessionNotifier extends Notifier { response.headers['content-type'], ); _activateRateLimitGateFromHttpError(body); - throw RelayException(response.statusCode, body); + throw RelayQueryException(response.statusCode, body); } // Decoding runs off the UI isolate, so the session can retire meanwhile. // A retired session reports that, not whatever its bytes decoded to. @@ -343,9 +344,7 @@ class RelaySessionNotifier extends Notifier { failure: NetworkFailure.timeout, since: sub.startedAt, ); - sub.completer.completeError( - TimeoutException('Relay history request timed out after $timeout'), - ); + sub.timedOut(timeout); } if (sub?.heldFilter == null) _sendClose(subId); }); @@ -476,11 +475,7 @@ class RelaySessionNotifier extends Notifier { failure: NetworkFailure.timeout, since: pending.startedAt, ); - pending.completer.completeError( - RelayAckTimeoutError( - 'Event ${event.id} not acknowledged within $timeout', - ), - ); + pending.timedOut(event.id, timeout); } }); @@ -922,7 +917,7 @@ class RelaySessionNotifier extends Notifier { failure: _relayMessageFailure(message), since: historySub.startedAt, ); - historySub.completer.completeError(Exception(message)); + historySub.fail(RelayClosedException(RelayCall.history, message)); } return; } @@ -943,7 +938,10 @@ class RelaySessionNotifier extends Notifier { if (closedClass == RelayClosedClass.terminal && !isRelayDeadlineError(message)) { if (readyCompleter != null && !readyCompleter.isCompleted) { - readyCompleter.completeError(Exception(message)); + readyCompleter.completeError( + RelayClosedException(RelayCall.subscribe, message), + liveSub.callSite, + ); } liveSub.onClosed?.call(message); _removeLiveSubscription(subId, liveSub); @@ -1066,7 +1064,7 @@ class RelaySessionNotifier extends Notifier { _rateLimitGate.activate(parseRateLimitRetrySeconds(message)); } if (!pending.completer.isCompleted) { - pending.completer.completeError( + pending.fail( RelayEventRejectedException( message.isNotEmpty ? message : 'Event rejected', ), @@ -1148,7 +1146,7 @@ class RelaySessionNotifier extends Notifier { for (final entry in _historySubscriptions.values) { entry.timeout.cancel(); if (!entry.completer.isCompleted) { - entry.completer.completeError(error ?? Exception('Connection lost')); + entry.fail(error ?? Exception('Connection lost')); } } _historySubscriptions.clear(); @@ -1158,7 +1156,7 @@ class RelaySessionNotifier extends Notifier { for (final entry in _pendingEvents.values) { entry.timeout.cancel(); if (!entry.completer.isCompleted) { - entry.completer.completeError(RelayAckLostError(error)); + entry.fail(RelayAckLostError(error)); } } _pendingEvents.clear(); diff --git a/mobile/lib/shared/relay/relay_session_snapshot.dart b/mobile/lib/shared/relay/relay_session_snapshot.dart index 6cb3b92240..58a1e8ae90 100644 --- a/mobile/lib/shared/relay/relay_session_snapshot.dart +++ b/mobile/lib/shared/relay/relay_session_snapshot.dart @@ -24,11 +24,17 @@ extension on RelaySessionNotifier { } } - Future send(http.Request request, int maxBytes) async { + // Only the `/query` POST is a [RelayCall.query]; the discovery GET is not. + Future send( + http.Request request, + int maxBytes, { + bool query = false, + }) async { final response = await _httpQueryClient.sendBounded( request, maxBytes: maxBytes, timeout: timeout, + call: query ? RelayCall.query : null, decorate: (client, active) => HostedRelayHttpClient( _snapshotAuth, config, @@ -45,7 +51,9 @@ extension on RelaySessionNotifier { maxInflatedBytes: maxBytes, ); _activateRateLimitGateFromHttpError(text); - throw RelayException(response.statusCode, text); + throw query + ? RelayQueryException(response.statusCode, text) + : RelayException(response.statusCode, text); } return response; } @@ -91,7 +99,11 @@ extension on RelaySessionNotifier { nsec: nsec, ), }); - final response = await send(request, readStateSnapshotMaxEnvelopeBytes); + final response = await send( + request, + readStateSnapshotMaxEnvelopeBytes, + query: true, + ); // Inflating, parsing and Schnorr verification must not block Flutter's // UI isolate. final List events; diff --git a/mobile/lib/shared/relay/relay_session_subscriptions.dart b/mobile/lib/shared/relay/relay_session_subscriptions.dart index 2c3543ae3e..6d7b73bcd2 100644 --- a/mobile/lib/shared/relay/relay_session_subscriptions.dart +++ b/mobile/lib/shared/relay/relay_session_subscriptions.dart @@ -6,6 +6,20 @@ class _HistorySubscription { final Timer timeout; final DateTime startedAt; + /// Where the call was made. Errors completed later, from a timer or a + /// socket callback, carry it, so an escaped error's stack reaches the caller. + final StackTrace callSite = StackTrace.current; + + void fail(Object error) => completer.completeError(error, callSite); + + void timedOut(Duration timeout) => fail( + RelayTimeoutException( + RelayCall.history, + 'Relay history request timed out after $timeout', + timeout, + ), + ); + /// The filter of a request held until the socket authenticates. NostrFilter? heldFilter; @@ -25,6 +39,11 @@ class _LiveSubscription { /// Whether a replay narrows [filter] with a `since` from what this /// subscription last saw. final bool resumeSince; + + /// Where the call was made. Errors completed later, from a timer or a + /// socket callback, carry it, so an escaped error's stack reaches the caller. + final StackTrace callSite = StackTrace.current; + Completer? readyCompleter; int? lastSeenCreatedAt; @@ -78,6 +97,19 @@ class _PendingEvent { final Timer timeout; final DateTime startedAt; + /// Where the call was made. Errors completed later, from a timer or a + /// socket callback, carry it, so an escaped error's stack reaches the caller. + final StackTrace callSite = StackTrace.current; + + void fail(Object error) => completer.completeError(error, callSite); + + void timedOut(String eventId, Duration timeout) => fail( + RelayAckTimeoutError( + 'Event $eventId not acknowledged within $timeout', + timeout, + ), + ); + _PendingEvent({ required this.completer, required this.timeout, diff --git a/mobile/lib/shared/relay/relay_session_types.dart b/mobile/lib/shared/relay/relay_session_types.dart index 33aa59496d..481e0722b0 100644 --- a/mobile/lib/shared/relay/relay_session_types.dart +++ b/mobile/lib/shared/relay/relay_session_types.dart @@ -1,7 +1,6 @@ -import 'dart:async'; - import 'package:flutter/foundation.dart'; +import 'relay_call_error.dart'; import 'relay_socket.dart'; enum SessionStatus { disconnected, connecting, connected, reconnecting } @@ -40,9 +39,10 @@ class RelayNotConnectedError extends StateError { /// The relay did not acknowledge a published EVENT in time, so it may or may /// not have accepted it. Other relay timeouts (history, queries) happen before -/// anything is published and stay plain [TimeoutException]s. -class RelayAckTimeoutError extends TimeoutException { - RelayAckTimeoutError(super.message, [super.duration]); +/// anything is published and are plain [RelayTimeoutException]s. +class RelayAckTimeoutError extends RelayTimeoutException { + RelayAckTimeoutError(String message, [Duration? duration]) + : super(RelayCall.publish, message, duration); } /// The connection ended after an EVENT was sent but before the relay diff --git a/mobile/lib/shared/relay/relay_socket.dart b/mobile/lib/shared/relay/relay_socket.dart index 84e4e4b42f..4dd6316b4a 100644 --- a/mobile/lib/shared/relay/relay_socket.dart +++ b/mobile/lib/shared/relay/relay_socket.dart @@ -9,6 +9,7 @@ import 'package:web_socket_channel/web_socket_channel.dart'; import '../diagnostics/diagnostic_reporter.dart'; import 'nostr_models.dart'; +import 'relay_call_error.dart'; import 'relay_websocket.dart'; import 'package:buzz/shared/crypto/event_signing.dart'; @@ -30,11 +31,17 @@ class RelayAuthRejectedException implements Exception { } /// The relay answered an EVENT with OK false, so it wasn't stored. -class RelayEventRejectedException implements Exception { +class RelayEventRejectedException implements RelayCallError { final String message; const RelayEventRejectedException(this.message); + @override + RelayCall get call => RelayCall.publish; + + @override + RelayReason get reason => RelayReason.fromMessage(message); + @override String toString() => 'Exception: $message'; } diff --git a/mobile/lib/shared/relay/signed_event_relay.dart b/mobile/lib/shared/relay/signed_event_relay.dart index 30b158ecf4..efb91c0b2c 100644 --- a/mobile/lib/shared/relay/signed_event_relay.dart +++ b/mobile/lib/shared/relay/signed_event_relay.dart @@ -4,6 +4,7 @@ import 'package:nostr/nostr.dart' as nostr; import '../diagnostics/diagnostic_reporter.dart'; import 'nostr_models.dart'; +import 'relay_call_error.dart'; import 'relay_closed_policy.dart'; import 'relay_session.dart'; import 'relay_socket.dart'; @@ -96,6 +97,9 @@ Future submitSignedEventOnce({ // push tombstone; its reports must not name the active member. final reporter = SignerDiagnosticReporter(diagnostics, signer: event.pubkey); final result = Completer(); + // Errors completed later, from a socket callback or timer, carry the stack + // of the caller, so an escaped error's report reaches app code. + final callSite = StackTrace.current; late final RelaySocket socket; socket = RelaySocket( wsUrl: wsUrl, @@ -128,24 +132,70 @@ Future submitSignedEventOnce({ operation: DiagnosticOperation.relayRejection, ); } - result.completeError(Exception('Relay rejected event: $detail')); + result.completeError(_SignedEventRejection(detail), callSite); } } }, - onConnected: () => socket.send(['EVENT', event.toJson()]), + onConnected: () { + if (!result.isCompleted) socket.send(['EVENT', event.toJson()]); + }, onDisconnected: (error) { - if (!result.isCompleted) { - result.completeError(error ?? Exception('Relay disconnected')); + if (result.isCompleted) return; + // The socket's own authentication deadline is shorter than [timeout], + // so its plain timeout is typed here as this call's. + if (error is TimeoutException && error is! RelayCallError) { + result.completeError( + RelayTimeoutException( + RelayCall.publish, + error.message ?? 'Relay did not answer', + error.duration, + ), + callSite, + ); + return; } + result.completeError(error ?? Exception('Relay disconnected'), callSite); }, ); socket.headers = headers; socket.diagnostics = reporter; - final resultFuture = result.future.timeout(timeout); + // The deadline covers connecting and authenticating too. Once it passes the + // event is never sent, and its timeout goes to the caller, never to the + // zone as an uncaught error. + final deadline = Timer(timeout, () { + if (result.isCompleted) return; + result.completeError( + RelayTimeoutException( + RelayCall.publish, + 'Relay did not answer within $timeout', + timeout, + ), + callSite, + ); + }); try { - await socket.connect(); - return await resultFuture; + // Whichever settles first: a failed connect, or the result (which the + // deadline settles if nothing else does). Future.any listens to both, so + // the other one's later error is not uncaught. + return await Future.any([ + socket.connect().then((_) => result.future), + result.future, + ]); } finally { + deadline.cancel(); await socket.disconnect(); } } + +/// The relay answered a one-shot EVENT with OK false and [detail]. Its text +/// names the refusal for callers; its reason class is the prefix of [detail]. +class _SignedEventRejection extends RelayEventRejectedException { + _SignedEventRejection(String detail) + : _reason = RelayReason.fromMessage(detail), + super('Relay rejected event: $detail'); + + final RelayReason _reason; + + @override + RelayReason get reason => _reason; +} diff --git a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart index 3c052b7f3f..9ea1abfc54 100644 --- a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart +++ b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart @@ -8,7 +8,7 @@ import 'package:buzz/shared/diagnostics/diagnostic_member_binding.dart'; import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/diagnostics/diagnostic_startup.dart'; import 'package:buzz/shared/diagnostics/sentry_diagnostic_reporter.dart'; -import 'package:buzz/shared/relay/relay_provider.dart'; +import 'package:buzz/shared/relay/relay.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -318,6 +318,89 @@ void main() { expect(transport.events, hasLength(2)); }); + group('an error that escapes from a relay call', () { + Future> escaped(Object error) async { + // As an uncaught asynchronous error reaches the SDK: straight to the + // hub, not through the app's reporter. + await hub.captureException(error, stackTrace: StackTrace.current); + return transport.events.single; + } + + test( + 'is tagged with the call and the reason class, not the text', + () async { + final sent = await escaped( + const RelayEventRejectedException('rate-limited: private-marker'), + ); + + expect(sent['tags']['relay.call'], 'publish'); + expect(sent['tags']['relay.reason'], 'rate-limited'); + expect(jsonEncode(sent), isNot(contains('private-marker'))); + final exception = (sent['exception']['values'] as List).last as Map; + expect(exception['type'], 'RelayEventRejectedException'); + expect(exception['value'], DiagnosticFilter.removedText); + }, + ); + + test('is grouped by call and reason on top of its stack', () async { + final sent = await escaped( + RelayClosedException(RelayCall.history, 'error: private-marker'), + ); + + expect(sent['tags']['relay.call'], 'history'); + expect(sent['tags']['relay.reason'], 'error'); + expect(sent['fingerprint'], [ + '{{ default }}', + 'relay.call:history', + 'relay.reason:error', + ]); + }); + + test('names a timeout as one', () async { + final sent = await escaped( + RelayTimeoutException(RelayCall.query, 'private-marker'), + ); + + expect(sent['tags']['relay.call'], 'query'); + expect(sent['tags']['relay.reason'], 'timeout'); + expect(jsonEncode(sent), isNot(contains('private-marker'))); + }); + + test('with an unknown prefix has the reason other', () async { + final sent = await escaped( + const RelayEventRejectedException('teapot: private-marker'), + ); + + expect(sent['tags']['relay.reason'], 'other'); + expect(jsonEncode(sent), isNot(contains('private-marker'))); + }); + + test('is tagged when reported through the reporter too', () async { + SentryDiagnosticReporter(hub: hub).reportError( + const RelayEventRejectedException('invalid: private-marker'), + StackTrace.current, + operation: DiagnosticOperation.relayRejection, + ); + await transport.first(); + + final sent = transport.events.single; + expect(sent['tags']['operation'], 'relayRejection'); + expect(sent['tags']['relay.call'], 'publish'); + expect(sent['tags']['relay.reason'], 'invalid'); + }); + + test( + 'is the only kind of error that gets the tags or the grouping', + () async { + final sent = await escaped(StateError('private-marker')); + + expect(sent['tags'], isNot(contains('relay.call'))); + expect(sent['tags'], isNot(contains('relay.reason'))); + expect(sent, isNot(contains('fingerprint'))); + }, + ); + }); + testWidgets('sends only the allowed contexts', (tester) async { tester.platformDispatcher.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(accessibleNavigation: true); diff --git a/mobile/test/shared/diagnostics/relay_refusal_report_test.dart b/mobile/test/shared/diagnostics/relay_refusal_report_test.dart new file mode 100644 index 0000000000..e622d5c1f0 --- /dev/null +++ b/mobile/test/shared/diagnostics/relay_refusal_report_test.dart @@ -0,0 +1,315 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:buzz/shared/auth/auth_provider.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_startup.dart'; +import 'package:buzz/shared/relay/relay.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:sentry_flutter/sentry_flutter.dart'; + +/// Refusals produced by the relay code itself, reported the way an uncaught +/// error reaches the SDK, and read back as the serialized event. +void main() { + late _MemoryTransport transport; + late Hub hub; + + setUp(() { + transport = _MemoryTransport(); + final options = SentryFlutterOptions(); + configureDiagnostics(options, 'https://key@example.org/1'); + options + ..transport = transport + ..sendClientReports = false; + hub = Hub(options); + }); + tearDown(() => hub.close()); + + Future> escaped(Object error, StackTrace stack) async { + await hub.captureException(error, stackTrace: stack); + return transport.events.single; + } + + Future<(Object, StackTrace)> failure(Future call) async { + try { + await call; + } catch (error, stack) { + return (error, stack); + } + fail('the call succeeded'); + } + + group('a refused /query', () { + final keys = nostr.Keys.generate(); + const marker = 'private-marker'; + + RelaySessionNotifier session(http.Client client) { + final session = RelaySessionNotifier(httpClient: client); + final container = ProviderContainer( + overrides: [ + authProvider.overrideWith(_PendingAuth.new), + relayConfigProvider.overrideWith(() => _Config(keys.nsec)), + relaySessionProvider.overrideWith(() => session), + ], + ); + addTearDown(container.dispose); + container.read(relaySessionProvider); + return session; + } + + for (final (status, reason) in [ + (429, 'rate-limited'), + (401, 'auth-required'), + (403, 'restricted'), + (503, 'error'), + (400, 'other'), + ]) { + test('$status is tagged query and $reason, without its body', () async { + final relay = session( + MockClient((_) async => http.Response('{"error":"$marker"}', status)), + ); + + final (error, stack) = await failure(relay.queryRelay(const [])); + final sent = await escaped(error, stack); + + expect(error, isA()); + expect((error as RelayException).statusCode, status); + expect(error.body, contains(marker)); + expect(sent['tags']['relay.call'], 'query'); + expect(sent['tags']['relay.reason'], reason); + expect(sent['fingerprint'], [ + '{{ default }}', + 'relay.call:query', + 'relay.reason:$reason', + ]); + expect(jsonEncode(sent), isNot(contains(marker))); + }); + } + + group('of the read state snapshot', () { + final discovery = jsonEncode({ + 'read_state_snapshot': { + 'version': 1, + 'community_id': 'abcdabcd-eeee-abcd-abcd-abcdefabcdef', + 'max_events': 4096, + 'max_event_array_bytes': 8 * 1024 * 1024, + }, + }); + + test('is tagged query and its reason, without its body', () async { + final relay = session( + MockClient( + (request) async => request.method == 'GET' + ? http.Response(discovery, 200) + : http.Response('{"error":"$marker"}', 429), + ), + ); + + final (error, stack) = await failure(relay.fetchReadStateSnapshot()); + final sent = await escaped(error, stack); + + expect((error as RelayException).statusCode, 429); + expect(sent['tags']['relay.call'], 'query'); + expect(sent['tags']['relay.reason'], 'rate-limited'); + expect(jsonEncode(sent), isNot(contains(marker))); + }); + + test('discovery is not a query and is not tagged', () async { + final relay = session( + MockClient((_) async => http.Response('{"error":"$marker"}', 429)), + ); + + final (error, stack) = await failure(relay.fetchReadStateSnapshot()); + final sent = await escaped(error, stack); + + expect(error, isA()); + expect(error, isNot(isA())); + expect(sent['tags'], isNot(contains('relay.call'))); + expect(jsonEncode(sent), isNot(contains(marker))); + }); + + test('a stalled discovery is an untyped timeout, not tagged', () async { + final relay = session( + MockClient((_) => Completer().future), + ); + + final (error, stack) = await failure( + relay.fetchReadStateSnapshot( + timeout: const Duration(milliseconds: 50), + ), + ); + final sent = await escaped(error, stack); + + expect(error, isA()); + expect(error, isNot(isA())); + expect(sent['tags'], isNot(contains('relay.call'))); + expect(sent['tags'], isNot(contains('relay.reason'))); + }); + + test('a stalled snapshot POST is a query timeout', () async { + final relay = session( + MockClient( + (request) => request.method == 'GET' + ? Future.value(http.Response(discovery, 200)) + : Completer().future, + ), + ); + + final (error, stack) = await failure( + relay.fetchReadStateSnapshot( + timeout: const Duration(milliseconds: 50), + ), + ); + final sent = await escaped(error, stack); + + expect(error, isA()); + expect(sent['tags']['relay.call'], 'query'); + expect(sent['tags']['relay.reason'], 'timeout'); + }); + }); + }); + + group('a one-shot signed event', () { + const marker = 'private-marker'; + + var eventsReceived = 0; + + Future relayAnswering( + String? reason, { + bool acknowledgeAuth = true, + }) async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + server.listen((request) async { + final ws = await WebSocketTransformer.upgrade(request); + ws.add(jsonEncode(['AUTH', 'challenge'])); + ws.listen((raw) { + final frame = jsonDecode(raw as String) as List; + final id = (frame[1] as Map)['id']; + if (frame[0] == 'AUTH' && acknowledgeAuth) { + ws.add(jsonEncode(['OK', id, true, ''])); + } + if (frame[0] == 'EVENT') eventsReceived++; + if (frame[0] == 'EVENT' && reason != null) { + ws.add(jsonEncode(['OK', id, false, reason])); + } + }); + }); + return server; + } + + Future submit(HttpServer server, {Duration? timeout}) => + _submitFromTheCaller(server, timeout: timeout); + + test('refused is tagged publish and the relay prefix, ' + 'with the caller\'s stack and without the relay text', () async { + final server = await relayAnswering('rate-limited: $marker'); + + final (error, stack) = await failure(submit(server)); + final sent = await escaped(error, stack); + + expect(error, isA()); + expect( + error.toString(), + 'Exception: Relay rejected event: rate-limited: $marker', + ); + expect((error as RelayCallError).call, RelayCall.publish); + expect(error.reason, RelayReason.rateLimited); + expect(stack.toString(), contains('_submitFromTheCaller')); + expect(sent['tags']['relay.call'], 'publish'); + expect(sent['tags']['relay.reason'], 'rate-limited'); + expect(jsonEncode(sent), isNot(contains(marker))); + expect(jsonEncode(sent), contains('_submitFromTheCaller')); + }); + + test('refused with an unknown prefix has the reason other', () async { + final server = await relayAnswering('teapot: $marker'); + + final (error, stack) = await failure(submit(server)); + final sent = await escaped(error, stack); + + expect(sent['tags']['relay.reason'], 'other'); + expect(jsonEncode(sent), isNot(contains(marker))); + }); + + test('unanswered is a publish timeout from the caller', () async { + final server = await relayAnswering(null); + + final (error, stack) = await failure( + submit(server, timeout: const Duration(milliseconds: 200)), + ); + final sent = await escaped(error, stack); + + expect(error, isA()); + expect(stack.toString(), contains('_submitFromTheCaller')); + expect(sent['tags']['relay.call'], 'publish'); + expect(sent['tags']['relay.reason'], 'timeout'); + }); + + test('an authentication the relay never acknowledges is a publish ' + 'timeout from the caller, and the event is never sent', () async { + eventsReceived = 0; + final server = await relayAnswering( + 'rate-limited: $marker', + acknowledgeAuth: false, + ); + + // The socket's 8 s authentication deadline passes first. + final (error, stack) = await failure(submit(server)); + final sent = await escaped(error, stack); + + expect(error, isA()); + expect(error, isA()); + expect(stack.toString(), contains('_submitFromTheCaller')); + expect(sent['tags']['relay.call'], 'publish'); + expect(sent['tags']['relay.reason'], 'timeout'); + expect(jsonEncode(sent), isNot(contains(marker))); + expect(eventsReceived, 0); + }, timeout: const Timeout(Duration(seconds: 30))); + }); +} + +Future _submitFromTheCaller( + HttpServer server, { + Duration? timeout, +}) => submitSignedEventOnce( + wsUrl: 'ws://127.0.0.1:${server.port}', + nsec: nostr.Keys.generate().nsec, + kind: 1, + content: '', + tags: const [], + timeout: timeout ?? const Duration(seconds: 12), +); + +class _PendingAuth extends AuthNotifier { + @override + Future build() => Completer().future; +} + +class _Config extends RelayConfigNotifier { + _Config(this.nsec); + + final String nsec; + + @override + RelayConfig build() => + RelayConfig(baseUrl: 'https://relay.example', nsec: nsec); +} + +class _MemoryTransport implements Transport { + final events = >[]; + + @override + Future send(SentryEnvelope envelope) async { + for (final item in envelope.items) { + if (item.header.type != 'event') continue; + final bytes = await item.dataFactory(); + events.add(jsonDecode(utf8.decode(bytes)) as Map); + } + return envelope.header.eventId; + } +} diff --git a/mobile/test/shared/relay/relay_call_error_test.dart b/mobile/test/shared/relay/relay_call_error_test.dart new file mode 100644 index 0000000000..2f7663f818 --- /dev/null +++ b/mobile/test/shared/relay/relay_call_error_test.dart @@ -0,0 +1,133 @@ +import 'dart:async'; + +import 'package:buzz/shared/relay/relay.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('the reason class of a relay message', () { + const cases = { + 'invalid: bad signature': RelayReason.invalid, + 'rate-limited: quota exceeded; retry in 4s': RelayReason.rateLimited, + 'restricted: access revoked': RelayReason.restricted, + 'auth-required: verification failed': RelayReason.authRequired, + 'blocked: community policy': RelayReason.blocked, + 'duplicate: already have this event': RelayReason.duplicate, + 'pow: insufficient work': RelayReason.pow, + 'unsupported: filter extension': RelayReason.unsupported, + 'error: query timed out': RelayReason.error, + 'INVALID: shouted': RelayReason.invalid, + ' invalid : padded': RelayReason.invalid, + 'invalid:': RelayReason.invalid, + 'timeout: not a relay prefix': RelayReason.other, + 'other: not a relay prefix': RelayReason.other, + 'teapot: unknown prefix': RelayReason.other, + 'no prefix at all': RelayReason.other, + 'a sentence, then invalid: later': RelayReason.other, + '': RelayReason.other, + }; + for (final entry in cases.entries) { + test('"${entry.key}" is ${entry.value.name}', () { + expect(RelayReason.fromMessage(entry.key), entry.value); + }); + } + + test('the wording that leaves the device is the relay prefix', () { + expect( + {for (final reason in RelayReason.values) reason.tag}, + { + 'invalid', + 'rate-limited', + 'restricted', + 'auth-required', + 'blocked', + 'duplicate', + 'pow', + 'unsupported', + 'error', + 'timeout', + 'other', + }, + ); + }); + }); + + group('the reason class of a /query status', () { + const cases = { + 429: RelayReason.rateLimited, + 401: RelayReason.authRequired, + 403: RelayReason.restricted, + 500: RelayReason.error, + 503: RelayReason.error, + 599: RelayReason.error, + 400: RelayReason.other, + 404: RelayReason.other, + 302: RelayReason.other, + 600: RelayReason.other, + }; + for (final entry in cases.entries) { + test('${entry.key} is ${entry.value.name}', () { + expect(RelayReason.fromHttpStatus(entry.key), entry.value); + }); + } + }); + + group('what a relay error says about itself', () { + test('a refused query is a relay exception that names the query', () { + final error = RelayQueryException(429, '{"error":"slow down"}'); + + expect(error, isA()); + expect(error.call, RelayCall.query); + expect(error.reason, RelayReason.rateLimited); + expect(error.statusCode, 429); + expect(error.toString(), 'RelayException(429): {"error":"slow down"}'); + }); + + test('a rejected publish names the publish and the relay prefix', () { + const error = RelayEventRejectedException('blocked: secret reason'); + + expect(error.call, RelayCall.publish); + expect(error.reason, RelayReason.blocked); + expect(error.toString(), 'Exception: blocked: secret reason'); + }); + + test('a closed subscription names its call and keeps its text', () { + final error = RelayClosedException( + RelayCall.history, + 'error: query timed out', + ); + + expect(error.call, RelayCall.history); + expect(error.reason, RelayReason.error); + expect(error.toString(), 'Exception: error: query timed out'); + expect(isRelayDeadlineError(error), isTrue); + expect(relayErrorMessage(error), 'Query timed out'); + }); + + test('an access refusal is still recognized as one', () { + final error = RelayClosedException( + RelayCall.subscribe, + 'restricted: not a member', + ); + + expect(isRelayAccessDenied(error), isTrue); + }); + + test('a relay timeout is a timeout of its call', () { + final error = RelayTimeoutException(RelayCall.query, 'slow'); + + expect(error, isA()); + expect(error.call, RelayCall.query); + expect(error.reason, RelayReason.timeout); + }); + + test('an unacknowledged publish is still a timeout, of the publish', () { + final error = RelayAckTimeoutError('no OK', const Duration(seconds: 8)); + + expect(error, isA()); + expect(error, isA()); + expect(error.call, RelayCall.publish); + expect(error.reason, RelayReason.timeout); + expect(error.duration, const Duration(seconds: 8)); + }); + }); +} diff --git a/mobile/test/shared/relay/relay_http_query_client_test.dart b/mobile/test/shared/relay/relay_http_query_client_test.dart index f57cc6a2be..0a7a5fdebc 100644 --- a/mobile/test/shared/relay/relay_http_query_client_test.dart +++ b/mobile/test/shared/relay/relay_http_query_client_test.dart @@ -85,6 +85,7 @@ void main() { http.Request('GET', Uri.parse('https://relay.example/')), maxBytes: 1024, timeout: const Duration(milliseconds: 10), + call: null, ), throwsA(isA()), ); @@ -109,6 +110,7 @@ void main() { http.Request('GET', Uri.parse('https://relay.example/')), maxBytes: 1024, timeout: const Duration(seconds: 5), + call: null, ), throwsA(isA()), ); diff --git a/mobile/test/shared/relay/relay_session_test.dart b/mobile/test/shared/relay/relay_session_test.dart index 08062adb23..5a2cfb165e 100644 --- a/mobile/test/shared/relay/relay_session_test.dart +++ b/mobile/test/shared/relay/relay_session_test.dart @@ -2380,6 +2380,151 @@ void main() { (RelayInvalidRequest, DiagnosticOperation.relayRejection), ]); }); + + group('errors from relay calls say which call and why', () { + test('a rejected publish carries the call and reason class', () async { + final session = RelaySessionNotifier(); + session.debugAttachSocketForTest(_RecordingRelaySocket()); + + final publish = session.publish(_event()); + session.debugHandleMessage([ + 'OK', + 'event-1', + false, + 'rate-limited: slow down', + ]); + + await expectLater( + publish, + throwsA( + isA() + .having((error) => error.call, 'call', RelayCall.publish) + .having( + (error) => error.reason, + 'reason', + RelayReason.rateLimited, + ), + ), + ); + }); + + test('an escaped error keeps the stack of the call', () async { + final session = RelaySessionNotifier(); + session.debugAttachSocketForTest(_RecordingRelaySocket()); + + final publish = _publishFromTheCaller(session); + session.debugHandleMessage(['OK', 'event-1', false, 'invalid: bad']); + + StackTrace? stack; + try { + await publish; + } on RelayEventRejectedException catch (_, trace) { + stack = trace; + } + expect(stack.toString(), contains('_publishFromTheCaller')); + }); + + test('an unacknowledged publish is a timeout of the publish', () async { + final session = RelaySessionNotifier(); + session.debugAttachSocketForTest(_RecordingRelaySocket()); + + await expectLater( + session.publish(_event(), timeout: Duration.zero), + throwsA( + isA() + .having((error) => error.call, 'call', RelayCall.publish) + .having((error) => error.duration, 'duration', Duration.zero) + .having( + (error) => error.toString(), + 'text', + 'TimeoutException: Event event-1 not acknowledged ' + 'within 0:00:00.000000', + ), + ), + ); + }); + + test('a history timeout is a timeout of the history call', () async { + final session = RelaySessionNotifier(); + + await expectLater( + session.fetchHistory( + const NostrFilter(kinds: [39002]), + timeout: const Duration(milliseconds: 1), + ), + throwsA( + isA() + .having((error) => error.call, 'call', RelayCall.history) + .having((error) => error.reason, 'reason', RelayReason.timeout) + .having( + (error) => error.toString(), + 'text', + 'TimeoutException: Relay history request timed out after ' + '0:00:00.001000', + ), + ), + ); + }); + + test('a query timeout is a timeout of the query', () async { + final harness = _queryHarness(client: _ControlledHttpClient()); + addTearDown(harness.container.dispose); + + await expectLater( + harness.session.queryRelay(const [], timeout: Duration.zero), + throwsA( + isA().having( + (error) => error.call, + 'call', + RelayCall.query, + ), + ), + ); + }); + + test('a history CLOSED carries the call and the relay prefix', () async { + final socket = _RecordingRelaySocket(); + final session = RelaySessionNotifier(); + session.debugAttachSocketForTest(socket); + + final history = session.fetchHistory(_channelFilter); + session.debugHandleMessage([ + 'CLOSED', + _reqs(socket).last[1] as String, + 'restricted: not a member', + ]); + + await expectLater( + history, + throwsA( + isA() + .having((error) => error.call, 'call', RelayCall.history) + .having((error) => error.reason, 'reason', RelayReason.restricted) + .having( + (error) => error.toString(), + 'text', + 'Exception: restricted: not a member', + ), + ), + ); + }); + + test('a live subscribe CLOSED carries the call', () async { + final session = RelaySessionNotifier(); + + final subscribe = session.subscribe(_channelFilter, (_) {}); + session.debugHandleMessage(['CLOSED', 'l-1', 'blocked: no']); + + await expectLater( + subscribe, + throwsA( + isA() + .having((error) => error.call, 'call', RelayCall.subscribe) + .having((error) => error.reason, 'reason', RelayReason.blocked), + ), + ); + }); + }); } class _ControlledHttpClient extends http.BaseClient { @@ -2562,6 +2707,9 @@ class _FakeRelayConfigNotifier extends RelayConfigNotifier { RelayConfig build() => RelayConfig(baseUrl: _baseUrl, nsec: _nsec); } +Future _publishFromTheCaller(RelaySessionNotifier session) => + session.publish(_event()); + NostrEvent _event({int createdAt = 20, String id = 'event-1'}) { return NostrEvent( id: id, diff --git a/mobile/test/shared/relay/submit_signed_event_once_test.dart b/mobile/test/shared/relay/submit_signed_event_once_test.dart index b24bf1be75..d0496d2690 100644 --- a/mobile/test/shared/relay/submit_signed_event_once_test.dart +++ b/mobile/test/shared/relay/submit_signed_event_once_test.dart @@ -1,7 +1,9 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; +import 'package:buzz/shared/relay/relay_call_error.dart'; import 'package:buzz/shared/relay/relay_closed_policy.dart'; import 'package:buzz/shared/relay/signed_event_relay.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -87,6 +89,51 @@ void main() { ]); }); } + test('a deadline that passes while authenticating reaches the caller, ' + 'and the event is never sent', () async { + final events = []; + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + server.listen((request) async { + final ws = await WebSocketTransformer.upgrade(request); + ws.add(jsonEncode(['AUTH', 'challenge'])); + ws.listen((raw) { + final frame = jsonDecode(raw as String) as List; + final id = (frame[1] as Map)['id']; + if (frame[0] == 'EVENT') events.add(id); + if (frame[0] == 'AUTH') { + // Authentication answers only after the caller's deadline. + Timer(const Duration(milliseconds: 600), () { + ws.add(jsonEncode(['OK', id, true, ''])); + }); + } + }); + }); + final watch = Stopwatch()..start(); + + await expectLater( + submitSignedEventOnce( + wsUrl: 'ws://127.0.0.1:${server.port}', + nsec: nostr.Keys.generate().nsec, + kind: 1, + content: '', + tags: const [], + timeout: const Duration(milliseconds: 200), + ), + throwsA( + isA().having( + (error) => error.call, + 'call', + RelayCall.publish, + ), + ), + ); + expect(watch.elapsed, lessThan(const Duration(milliseconds: 550))); + // Outlive the late authentication: an uncaught error would fail the test. + await Future.delayed(const Duration(milliseconds: 800)); + + expect(events, isEmpty); + }); } class _RecordingDiagnostics extends NoopDiagnosticReporter {