Files
buzz/mobile/lib/shared/relay/relay_session_subscriptions.dart
Tom Brow 0966f3fad6 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>
2026-11-24 16:29:14 -08:00

126 lines
3.5 KiB
Dart

part of 'relay_session.dart';
class _HistorySubscription {
final List<NostrEvent> events = [];
final Completer<List<NostrEvent>> completer;
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;
_HistorySubscription({
required this.completer,
required this.timeout,
required this.startedAt,
});
}
class _LiveSubscription {
final NostrFilter filter;
final void Function(NostrEvent) onEvent;
final void Function(String message)? onClosed;
final void Function(RelaySubscriptionStatus status)? onStatusChanged;
/// 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<void>? readyCompleter;
int? lastSeenCreatedAt;
/// Whether EOSE arrived on the current connection and no CLOSED has
/// interrupted the stream since.
bool liveOnConnection = false;
/// Client clock (seconds) when the last connection this subscription was
/// live on closed. Kept across later connections that never reach EOSE.
int? liveUntil;
/// The connection generation of this subscription's latest REQ, and the
/// one on which it sent a second REQ, leaving its EOSE ambiguous.
int? reqGeneration;
int? ambiguousGeneration;
int closedRetryAttempt = 0;
Timer? closedRetryTimer;
_LiveSubscription({
required this.filter,
required this.onEvent,
this.onClosed,
this.onStatusChanged,
this.resumeSince = true,
this.readyCompleter,
});
/// The REQ filter for a replay, resumed from what this subscription saw.
NostrFilter get replayFilter {
if (!resumeSince) return filter;
final since = relayResumeSince(
originalSince: filter.since,
until: filter.until,
lastSeenCreatedAt: lastSeenCreatedAt,
liveUntil: liveUntil,
);
return since == null || since == filter.since
? filter
: filter.copyWithSince(since);
}
}
class _ClosedRetry {
final _LiveSubscription subscription;
final int generation;
_ClosedRetry({required this.subscription, required this.generation});
}
class _PendingEvent {
final Completer<NostrEvent> completer;
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,
required this.startedAt,
});
}
class _BufferedEvent {
final String subId;
final NostrEvent event;
_BufferedEvent(this.subId, this.event);
}