Skip to content

Commit 0966f3f

Browse files
browstudio
andauthored
feat(mobile): tag escaped relay errors with their call and reason class (#9821)
Makes relay errors that nothing catches readable in diagnostic reports. Today an unhandled relay rejection or timeout arrives with its text removed and a stack that stops at the async error handler, so a report can't say which call failed or why. ## Changes - **Typed call and reason:** relay errors now carry the call (`publish`, `query`, `history`, `subscribe`) and a fixed reason class taken from the relay's reason prefix (`invalid`, `rate-limited`, `restricted`, `auth-required`, `blocked`, `duplicate`, `pow`, `unsupported`, `error`, `timeout`, or `other`). Types: - `RelayEventRejectedException` implements the new `RelayCallError`; - new `RelayTimeoutException` extends `TimeoutException`, and `RelayAckTimeoutError` now extends it; - new `RelayClosedException` replaces the plain `Exception` for a closed history or live subscription, with the same `toString`. - new `RelayQueryException` (a `RelayException` that is also a `RelayCallError`) for a non-2xx `/query` answer, with its reason from the status alone; - a one-shot signed event the relay refuses now fails with a typed rejection, with the same text. Existing `TimeoutException` checks and message helpers behave as before. - **Report tags:** before the filter runs, a report whose error is a `RelayCallError` gets `relay.call` and `relay.reason` tags. The relay's own text is never sent. These reports are also grouped by call and reason on top of the default grouping, so a rate limit and an invalid request from the same code become separate issues. - **Call-site stack:** pending publishes, one-shot signed events, and history and live subscriptions keep the stack where they were created, and errors completed later from timers or socket callbacks use it. A report's stack now reaches the calling code. - **Spec:** one bullet on the tags, the grouping and the stack. ## Validation New tests: - a table of reason prefixes to classes; - error types, fields and the existing message helpers; - relay session cases: a rejected publish's call, reason and calling stack, the timeout types, and closed subscriptions; - reports: tags, the grouping key, no relay text, and non-relay errors untouched. - production refusals through a serialized report: `/query` statuses, snapshot `/query` versus discovery, and one-shot rejections and timeouts with the caller's stack. Full-app run on an iOS simulator (signed in, healthy relay): cold start and session restore, channel list, opening channels and DMs, history back to each channel's start, send, react, edit, thread reply, search, channel details and Add Members, Settings > Send test report, and background then foreground followed by a send and a delete. All passed with no new errors in the device log, and no doubled error names in any logged text. Error paths (timeouts, closed connections, relay rejections) weren't triggered on the healthy relay; the unit tests above cover them. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
1 parent c0932db commit 0966f3f

20 files changed

Lines changed: 1048 additions & 37 deletions

‎docs/mobile-diagnostic-reporting.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat
4242
- **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)).
4343
- **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.
4444
- **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.
45+
- **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.
4546
- **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.
4647
- **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.
4748
- **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.

‎mobile/lib/shared/diagnostics/diagnostic_filter.dart‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import 'package:sentry_flutter/sentry_flutter.dart';
22

33
import 'diagnostic_reporter.dart';
4+
import 'relay_error_tags.dart';
45

56
/// The one filter every Dart report, breadcrumb and count passes through
67
/// before it leaves the device. Reports the native SDKs capture themselves
@@ -141,11 +142,14 @@ abstract final class DiagnosticFilter {
141142
key == installIdTag ||
142143
_sdkAttributePrefixes.any(key.startsWith);
143144

144-
/// The app tags a report with where it came from and which installation
145-
/// sent it; the SDK tags it with its origin and environment.
145+
/// The app tags a report with where it came from, which installation sent
146+
/// it and, for a relay error, the call and reason class; the SDK tags it
147+
/// with its origin and environment.
146148
static bool _allowsTag(String key) =>
147149
key == 'operation' ||
148150
key == installIdTag ||
151+
key == RelayErrorTags.callTag ||
152+
key == RelayErrorTags.reasonTag ||
149153
key.startsWith('event.') ||
150154
allowsAttribute(key);
151155

‎mobile/lib/shared/diagnostics/diagnostic_startup.dart‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import 'package:uuid/uuid.dart';
1111
import '../http/app_http_client.dart';
1212
import 'diagnostic_filter.dart';
1313
import 'diagnostic_reporter.dart';
14+
import 'relay_error_tags.dart';
1415
import 'sentry_diagnostic_reporter.dart';
1516

1617
/// The build's reporting destination, a Sentry DSN supplied at build time.
@@ -151,7 +152,8 @@ void configureDiagnostics(SentryFlutterOptions options, String destination) {
151152
..enableAppHangTracking = true
152153
..anrEnabled = true
153154
..enableWatchdogTerminationTracking = true
154-
..beforeSend = ((event, hint) => DiagnosticFilter.filterEvent(event))
155+
..beforeSend = ((event, hint) =>
156+
DiagnosticFilter.filterEvent(RelayErrorTags.apply(event)))
155157
..beforeBreadcrumb = ((crumb, hint) =>
156158
DiagnosticFilter.filterBreadcrumb(crumb))
157159
..beforeSendMetric = ((metric, hint) =>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import 'package:sentry_flutter/sentry_flutter.dart';
2+
3+
import '../relay/relay_call_error.dart';
4+
5+
/// Says which relay call an error came from and why it failed, on a report
6+
/// whose error is a [RelayCallError].
7+
///
8+
/// An error that escapes uncaught reaches the SDK from the zone's handler,
9+
/// not through the reporter, and the filter replaces its text, so without
10+
/// this a report of one says only that some relay call failed. The reason is
11+
/// the relay's reason prefix or a timeout, never the relay's own text.
12+
abstract final class RelayErrorTags {
13+
/// Tag naming the relay call: publish, query, history or subscribe.
14+
static const callTag = 'relay.call';
15+
16+
/// Tag naming the reason class, such as invalid or rate-limited.
17+
static const reasonTag = 'relay.reason';
18+
19+
/// Adds the tags to [event], and splits its issue by call and reason on top
20+
/// of the usual grouping by stack, so a rate limit and an invalid request
21+
/// from the same call site are not one issue. Other events pass unchanged.
22+
static SentryEvent apply(SentryEvent event) {
23+
final error = event.throwable;
24+
if (error is! RelayCallError) return event;
25+
final call = error.call.name;
26+
final reason = error.reason.tag;
27+
event.tags = {...?event.tags, callTag: call, reasonTag: reason};
28+
event.fingerprint = [
29+
SentryEvent.defaultFingerprint,
30+
'relay.call:$call',
31+
'relay.reason:$reason',
32+
];
33+
return event;
34+
}
35+
}

‎mobile/lib/shared/relay/relay.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export 'media_image.dart';
66
export 'media_upload.dart';
77
export 'nostr_filters.dart';
88
export 'nostr_models.dart';
9+
export 'relay_call_error.dart';
910
export 'relay_closed_policy.dart';
1011
export 'relay_error_text.dart';
1112
export 'relay_client.dart';
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import 'dart:async';
2+
3+
/// The relay call an error came from.
4+
enum RelayCall {
5+
/// An EVENT sent over the socket and acknowledged with OK.
6+
publish,
7+
8+
/// A one-shot query over the relay's HTTP bridge.
9+
query,
10+
11+
/// A one-shot REQ over the socket, read until EOSE.
12+
history,
13+
14+
/// A live REQ, up to its first EOSE.
15+
subscribe,
16+
}
17+
18+
/// The reason class of a failed relay call: the relay's own reason prefix, or
19+
/// a timeout. Never the reason text, which is free-form and can quote what
20+
/// the app sent.
21+
enum RelayReason {
22+
invalid('invalid'),
23+
rateLimited('rate-limited'),
24+
restricted('restricted'),
25+
authRequired('auth-required'),
26+
blocked('blocked'),
27+
duplicate('duplicate'),
28+
pow('pow'),
29+
unsupported('unsupported'),
30+
error('error'),
31+
32+
/// The call timed out here, before the relay answered.
33+
timeout('timeout'),
34+
35+
/// A reason with no known prefix.
36+
other('other');
37+
38+
const RelayReason(this.tag);
39+
40+
/// The wording that leaves the device.
41+
final String tag;
42+
43+
static final _prefixes = {
44+
for (final reason in values)
45+
if (reason != timeout && reason != other) reason.tag: reason,
46+
};
47+
48+
/// The class of a relay `OK` or `CLOSED` [message]: its prefix, up to the
49+
/// first colon, when that is one of the relay's.
50+
static RelayReason fromMessage(String message) {
51+
final colon = message.indexOf(':');
52+
if (colon < 0) return other;
53+
return _prefixes[message.substring(0, colon).trim().toLowerCase()] ?? other;
54+
}
55+
56+
/// The class of an HTTP error [status] from the relay's `/query`. Its body
57+
/// is not read: the status alone says rate limit, refusal or server error.
58+
static RelayReason fromHttpStatus(int status) => switch (status) {
59+
429 => rateLimited,
60+
401 => authRequired,
61+
403 => restricted,
62+
>= 500 && < 600 => error,
63+
_ => other,
64+
};
65+
}
66+
67+
/// An error from a relay call that says which call and why.
68+
///
69+
/// Diagnostic reports of these carry [call] and [reason] as tags, because the
70+
/// error's own text is removed before a report leaves the device.
71+
abstract interface class RelayCallError implements Exception {
72+
RelayCall get call;
73+
RelayReason get reason;
74+
}
75+
76+
/// A relay call timed out before the relay answered.
77+
class RelayTimeoutException extends TimeoutException implements RelayCallError {
78+
RelayTimeoutException(this.call, String message, [Duration? duration])
79+
: super(message, duration);
80+
81+
@override
82+
final RelayCall call;
83+
84+
@override
85+
RelayReason get reason => RelayReason.timeout;
86+
87+
/// The text without the duration, which [message] already states. Screens
88+
/// show this text.
89+
@override
90+
String toString() => 'TimeoutException: $message';
91+
}
92+
93+
/// The relay closed a history or live subscription with [message].
94+
class RelayClosedException implements RelayCallError {
95+
RelayClosedException(this.call, this.message);
96+
97+
@override
98+
final RelayCall call;
99+
100+
/// The relay's `CLOSED` reason. Callers read its text.
101+
final String message;
102+
103+
@override
104+
RelayReason get reason => RelayReason.fromMessage(message);
105+
106+
@override
107+
String toString() => 'Exception: $message';
108+
}

‎mobile/lib/shared/relay/relay_client.dart‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'package:http/http.dart' as http;
22
import 'package:buzz/shared/http/app_http_client.dart';
3+
import 'relay_call_error.dart';
34

45
/// Lightweight HTTP context for talking to the Buzz relay.
56
///
@@ -46,3 +47,18 @@ class RelayException implements Exception {
4647
return 'RelayException($statusCode): $trimmedBody';
4748
}
4849
}
50+
51+
/// The relay's `/query` answered with a non-2xx status.
52+
///
53+
/// Callers that retry, fall back or give up read the [RelayException] status
54+
/// and body as before. A diagnostic report of one is tagged with the call and
55+
/// a reason class taken from the status alone, never the body.
56+
class RelayQueryException extends RelayException implements RelayCallError {
57+
RelayQueryException(super.statusCode, super.body);
58+
59+
@override
60+
RelayCall get call => RelayCall.query;
61+
62+
@override
63+
RelayReason get reason => RelayReason.fromHttpStatus(statusCode);
64+
}

‎mobile/lib/shared/relay/relay_http_query_client.dart‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import 'dart:io';
44
import 'package:http/http.dart' as http;
55
import 'package:http/io_client.dart';
66
import 'package:buzz/shared/http/app_http_client.dart';
7+
import 'relay_call_error.dart';
78

89
import 'relay_query_response.dart' show RelayResponseTooLarge;
910

@@ -38,13 +39,26 @@ class RelayHttpQueryClient {
3839
_ClientGeneration? _currentGeneration;
3940
final Set<_ClientGeneration> _generations = {};
4041

42+
/// The error for a request that outlived [timeout]: a [call] when the
43+
/// request is one, otherwise a plain [TimeoutException]. Its stack is the
44+
/// caller's, since the timer that raises it has no frames from the app.
45+
static TimeoutException _timedOut(Duration timeout, RelayCall? call) =>
46+
call == null
47+
? TimeoutException('Relay request timed out after $timeout', timeout)
48+
: RelayTimeoutException(
49+
call,
50+
'Relay query timed out after $timeout',
51+
timeout,
52+
);
53+
4154
Future<http.Response> post(
4255
Uri url, {
4356
required Map<String, String> headers,
4457
required List<int> body,
4558
required Duration timeout,
4659
http.Client Function(http.Client, bool Function())? decorate,
4760
}) async {
61+
final callSite = StackTrace.current;
4862
final generation = _injectedClient == null
4963
? (_currentGeneration ??= _createGeneration())
5064
: null;
@@ -73,21 +87,24 @@ class RelayHttpQueryClient {
7387
_currentGeneration = null;
7488
}
7589
generation?.retire();
76-
rethrow;
90+
Error.throwWithStackTrace(_timedOut(timeout, RelayCall.query), callSite);
7791
} finally {
7892
active = false;
7993
generation?.release();
8094
}
8195
}
8296

8397
/// Sends a non-redirecting request, bounding bytes before buffering or parsing.
84-
/// The deadline includes headers and the entire response body.
98+
/// The deadline includes headers and the entire response body. A timeout is
99+
/// a [RelayTimeoutException] for [call], or untyped when [call] is null.
85100
Future<http.Response> sendBounded(
86101
http.Request request, {
87102
required int maxBytes,
88103
required Duration timeout,
104+
required RelayCall? call,
89105
http.Client Function(http.Client, bool Function())? decorate,
90106
}) async {
107+
final callSite = StackTrace.current;
91108
// As in [post], a timed-out request on a shared session is aborted.
92109
final abort = Completer<void>();
93110
final sent =
@@ -145,7 +162,7 @@ class RelayHttpQueryClient {
145162
_currentGeneration = null;
146163
}
147164
generation?.retire();
148-
rethrow;
165+
Error.throwWithStackTrace(_timedOut(timeout, call), callSite);
149166
} finally {
150167
finished = true;
151168
// Cancelling an iterator that never listened leaves the body

‎mobile/lib/shared/relay/relay_session.dart‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import '../hosted/hosted_relay_auth.dart';
1919
import '../hosted/builderlab_account.dart';
2020
import 'nostr_filters.dart';
2121
import 'nostr_models.dart';
22+
import 'relay_call_error.dart';
2223
import 'relay_client.dart';
2324
import 'relay_closed_policy.dart';
2425
import 'relay_http_query_client.dart';
@@ -297,7 +298,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
297298
response.headers['content-type'],
298299
);
299300
_activateRateLimitGateFromHttpError(body);
300-
throw RelayException(response.statusCode, body);
301+
throw RelayQueryException(response.statusCode, body);
301302
}
302303
// Decoding runs off the UI isolate, so the session can retire meanwhile.
303304
// A retired session reports that, not whatever its bytes decoded to.
@@ -343,9 +344,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
343344
failure: NetworkFailure.timeout,
344345
since: sub.startedAt,
345346
);
346-
sub.completer.completeError(
347-
TimeoutException('Relay history request timed out after $timeout'),
348-
);
347+
sub.timedOut(timeout);
349348
}
350349
if (sub?.heldFilter == null) _sendClose(subId);
351350
});
@@ -476,11 +475,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
476475
failure: NetworkFailure.timeout,
477476
since: pending.startedAt,
478477
);
479-
pending.completer.completeError(
480-
RelayAckTimeoutError(
481-
'Event ${event.id} not acknowledged within $timeout',
482-
),
483-
);
478+
pending.timedOut(event.id, timeout);
484479
}
485480
});
486481

@@ -922,7 +917,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
922917
failure: _relayMessageFailure(message),
923918
since: historySub.startedAt,
924919
);
925-
historySub.completer.completeError(Exception(message));
920+
historySub.fail(RelayClosedException(RelayCall.history, message));
926921
}
927922
return;
928923
}
@@ -943,7 +938,10 @@ class RelaySessionNotifier extends Notifier<SessionState> {
943938
if (closedClass == RelayClosedClass.terminal &&
944939
!isRelayDeadlineError(message)) {
945940
if (readyCompleter != null && !readyCompleter.isCompleted) {
946-
readyCompleter.completeError(Exception(message));
941+
readyCompleter.completeError(
942+
RelayClosedException(RelayCall.subscribe, message),
943+
liveSub.callSite,
944+
);
947945
}
948946
liveSub.onClosed?.call(message);
949947
_removeLiveSubscription(subId, liveSub);
@@ -1066,7 +1064,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
10661064
_rateLimitGate.activate(parseRateLimitRetrySeconds(message));
10671065
}
10681066
if (!pending.completer.isCompleted) {
1069-
pending.completer.completeError(
1067+
pending.fail(
10701068
RelayEventRejectedException(
10711069
message.isNotEmpty ? message : 'Event rejected',
10721070
),
@@ -1148,7 +1146,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
11481146
for (final entry in _historySubscriptions.values) {
11491147
entry.timeout.cancel();
11501148
if (!entry.completer.isCompleted) {
1151-
entry.completer.completeError(error ?? Exception('Connection lost'));
1149+
entry.fail(error ?? Exception('Connection lost'));
11521150
}
11531151
}
11541152
_historySubscriptions.clear();
@@ -1158,7 +1156,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
11581156
for (final entry in _pendingEvents.values) {
11591157
entry.timeout.cancel();
11601158
if (!entry.completer.isCompleted) {
1161-
entry.completer.completeError(RelayAckLostError(error));
1159+
entry.fail(RelayAckLostError(error));
11621160
}
11631161
}
11641162
_pendingEvents.clear();

0 commit comments

Comments
 (0)