mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
## Summary The compose bar's send error, the upload error and the invite page's error removed the first `Exception: ` anywhere in an error's text, not just a leading one. A `TimeoutException` read "Timeout..." and a wrapped error lost part of its text. They now share the helper Add Members already uses: only a plain `Exception`'s leading prefix is removed, a relay rejection shows its message verbatim, a lost acknowledgement drops the prefix only from its cause, and named types such as `TimeoutException` keep their whole name. The helper moves to `shared/relay/relay_error_text.dart`; Add Members behaves as before. ## Validation - New `relay_error_text_test.dart` covers a plain `Exception`, a `TimeoutException`, a named error whose message contains `Exception: `, a relay rejection and a lost acknowledgement. The `TimeoutException` and named-error rows fail with the old `replaceFirst`. No screenshots: the change only affects text after a failed send, upload or invite, which can't be triggered on demand against a real relay. Full-app run on an iOS simulator (signed in, healthy relay): cold start and session restore, channel list, opening a channel, sending a message, the attachment button, Settings, and background then foreground. All passed with no new errors in the device log. The invite page isn't offered to the test account. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
220 lines
8.9 KiB
Dart
220 lines
8.9 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
import 'relay_client.dart';
|
|
|
|
// Shared constant so [isRelayDeadlineError] and [classifyRelayClosed] cannot
|
|
// drift apart.
|
|
const _queryTimedOutPrefix = 'error: query timed out';
|
|
|
|
/// Returns true when [error] is a relay server-side statement deadline that
|
|
/// cannot be resolved by retrying the same query.
|
|
///
|
|
/// Two surfaces carry the same deadline signal:
|
|
/// - HTTP `/query` or `/count`: [RelayException] with status 503 and a JSON
|
|
/// body containing `"error": "query timed out"`.
|
|
/// - WebSocket CLOSED: a plain [Exception] whose message is
|
|
/// `"error: query timed out"` (the relay's stable CLOSED reason string).
|
|
///
|
|
/// Both surfaces are checked so the caller (e.g. a Riverpod retry hook) does
|
|
/// not need to distinguish which transport produced the error.
|
|
bool isRelayDeadlineError(Object error) {
|
|
if (error is RelayException && error.statusCode == 503) {
|
|
try {
|
|
final decoded = jsonDecode(error.body);
|
|
if (decoded is Map<String, dynamic>) {
|
|
final message = decoded['error'];
|
|
if (message is String &&
|
|
message.trim().toLowerCase() == 'query timed out') {
|
|
return true;
|
|
}
|
|
}
|
|
} on FormatException {
|
|
// Non-JSON 503 — not a deadline.
|
|
}
|
|
return false;
|
|
}
|
|
// WebSocket history CLOSED: Exception("error: query timed out")
|
|
// Strip the "Exception: " prefix Flutter adds to Exception.toString(), then
|
|
// check via classifyRelayClosed so this path shares the same source of truth.
|
|
var message = error.toString().trim().toLowerCase();
|
|
const prefix = 'exception: ';
|
|
if (message.startsWith(prefix)) message = message.substring(prefix.length);
|
|
return classifyRelayClosed(message) == RelayClosedClass.terminal &&
|
|
message.startsWith(_queryTimedOutPrefix);
|
|
}
|
|
|
|
/// Reported when the relay says a request the app sent is invalid. It never
|
|
/// reaches callers, and it carries no relay text: the reason is free text.
|
|
/// Not const: Sentry drops a repeat of the last error object.
|
|
class RelayInvalidRequest implements Exception {
|
|
RelayInvalidRequest();
|
|
|
|
@override
|
|
String toString() => 'RelayInvalidRequest';
|
|
}
|
|
|
|
/// How the relay begins a refusal for a timestamp outside its clock window.
|
|
/// It has one wording per kind of event: ordinary events, canvas events,
|
|
/// relay-admin, moderation and identity archive commands (followed by the
|
|
/// timing details), leave requests (likewise) and observer frames. Matched from
|
|
/// the start of the reason, so a reason about something else that mentions a
|
|
/// timestamp, or echoes a value that does, is still reported.
|
|
const _clockWindowRefusals = [
|
|
'invalid: event timestamp too far from server time',
|
|
'invalid: canvas event timestamp too far in the future',
|
|
'invalid: event timestamp out of range',
|
|
'invalid: leave request timestamp out of range',
|
|
'invalid: observer frame timestamp outside',
|
|
];
|
|
|
|
/// Whether [message], a relay `OK` or `CLOSED` reason, says the app sent
|
|
/// something invalid. Refusals the app handles as expected outcomes, an
|
|
/// archived channel, an Unarchive of a channel that is no longer archived, an
|
|
/// open 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, are not. The timestamp refusal is
|
|
/// left out for every event, not only read-state updates: a device clock that
|
|
/// is off would otherwise report every publish, though this also hides a
|
|
/// signed event retried after the window has passed.
|
|
bool isInvalidRequestRejection(String message) {
|
|
final normalized = message.trim().toLowerCase();
|
|
return normalized.startsWith('invalid:') &&
|
|
!normalized.startsWith('invalid: channel is archived') &&
|
|
!normalized.startsWith('invalid: channel is not archived') &&
|
|
!normalized.startsWith('invalid: an open channel named') &&
|
|
!normalized.startsWith('invalid: policy:') &&
|
|
!normalized.startsWith(
|
|
'invalid: only members can add people in this channel',
|
|
) &&
|
|
!normalized.startsWith('invalid: cannot remove the last owner') &&
|
|
!_clockWindowRefusals.any(normalized.startsWith);
|
|
}
|
|
|
|
/// Explicit access refusal; cached private history must not mask this error.
|
|
bool isRelayAccessDenied(Object error) {
|
|
if (error is RelayException && error.statusCode == 403) return true;
|
|
final message = error.toString().toLowerCase().replaceFirst(
|
|
RegExp(r'^exception:\s*'),
|
|
'',
|
|
);
|
|
return message.startsWith('restricted:') || message.startsWith('blocked:');
|
|
}
|
|
|
|
/// A channel-level refusal, distinct from a session authorization failure.
|
|
bool isRelayChannelAccessDenied(Object error) {
|
|
var reason = error.toString();
|
|
if (error is RelayException) {
|
|
if (error.statusCode != 403) return false;
|
|
reason = error.body;
|
|
try {
|
|
final decoded = jsonDecode(reason);
|
|
if (decoded is Map<String, dynamic> && decoded['error'] is String) {
|
|
reason = decoded['error'] as String;
|
|
}
|
|
} on FormatException {
|
|
// Relay admission can return plain text.
|
|
}
|
|
}
|
|
final message = reason.trim().toLowerCase().replaceFirst(
|
|
RegExp(r'^exception:\s*'),
|
|
'',
|
|
);
|
|
return message == 'restricted: not a channel member' ||
|
|
isRelayChannelSubscriptionRevoked(message);
|
|
}
|
|
|
|
/// The relay ends live delivery on archive as well as on membership loss.
|
|
bool isRelayChannelSubscriptionRevoked(String message) =>
|
|
message.trim().toLowerCase() == 'restricted: channel access revoked';
|
|
|
|
/// Recovery policy for a relay `CLOSED` subscription message.
|
|
enum RelayClosedClass {
|
|
/// A transient failure that may recover when the same REQ is retried.
|
|
retryable,
|
|
|
|
/// Relay back-pressure that must also arm the shared request gate.
|
|
rateLimited,
|
|
|
|
/// An authorization, access, or filter failure that cannot recover unchanged.
|
|
terminal,
|
|
}
|
|
|
|
/// Classifies whether a relay `CLOSED` message should be retried.
|
|
RelayClosedClass classifyRelayClosed(String message) {
|
|
final normalized = message.trim().toLowerCase();
|
|
if (normalized.startsWith('rate-limited:')) {
|
|
return RelayClosedClass.rateLimited;
|
|
}
|
|
if (normalized.startsWith('restricted:') ||
|
|
normalized.startsWith('auth-required:') ||
|
|
normalized.startsWith('blocked:') ||
|
|
normalized.startsWith('invalid:') ||
|
|
normalized.startsWith('pow:') ||
|
|
normalized.startsWith('duplicate:') ||
|
|
normalized.startsWith('unsupported:') ||
|
|
normalized.startsWith('error: mixed search') ||
|
|
normalized.startsWith('error: too many subscriptions') ||
|
|
// Server statement deadline: re-sending the same REQ re-runs the same
|
|
// slow query.
|
|
normalized.startsWith(_queryTimedOutPrefix)) {
|
|
return RelayClosedClass.terminal;
|
|
}
|
|
return RelayClosedClass.retryable;
|
|
}
|
|
|
|
final _relayErrorPrefixPattern = RegExp(
|
|
r'^(?:exception:\s*)?(?:(?:invalid|blocked|restricted|duplicate|pow|unsupported|error|rate-limited|auth-required):\s*)?',
|
|
caseSensitive: false,
|
|
);
|
|
|
|
/// User-facing text for a failed relay publish or request.
|
|
///
|
|
/// Drops the Dart `Exception: ` wrapper and a leading NIP-01 machine prefix
|
|
/// (`invalid: `, `blocked: `, `error: `, ...) so a relay refusal such as
|
|
/// `invalid: an open channel named "Launch" already exists` reads as
|
|
/// `An open channel named "Launch" already exists`.
|
|
///
|
|
/// Use this for a relay publish or request whose refusal is the message.
|
|
/// To keep any error's text whole, minus only a plain [Exception]'s
|
|
/// `Exception: `, use `relayErrorText` instead.
|
|
String relayErrorMessage(Object error) {
|
|
final text = error.toString().trim().replaceFirst(
|
|
_relayErrorPrefixPattern,
|
|
'',
|
|
);
|
|
if (text.isEmpty) return error.toString().trim();
|
|
return text[0].toUpperCase() + text.substring(1);
|
|
}
|
|
|
|
final _rateLimitRetryPattern = RegExp(r'retry in (\d+)s', caseSensitive: false);
|
|
|
|
/// Parses the relay's canonical `retry in Ns` hint, when present.
|
|
int? parseRateLimitRetrySeconds(String message) {
|
|
final match = _rateLimitRetryPattern.firstMatch(message);
|
|
return match == null ? null : int.tryParse(match.group(1)!);
|
|
}
|
|
|
|
/// Whether [value] has settled on a relay deadline.
|
|
///
|
|
/// The forum periodic poll timers pause while a query is in this state;
|
|
/// reopening the view is the explicit retry. Other refresh paths (reconnect,
|
|
/// resume, live events, unread backstop) still re-send, each bounded by the
|
|
/// relay's 20s statement deadline.
|
|
bool isSettledRelayDeadline(AsyncValue<Object?> value) =>
|
|
value.hasError && !value.isLoading && isRelayDeadlineError(value.error!);
|
|
|
|
/// Production Riverpod retry policy for relay providers.
|
|
///
|
|
/// A relay statement deadline cannot resolve on retry — the same expensive
|
|
/// query would re-run and hit the same limit. Returns `null` (no retry) for
|
|
/// deadline errors and falls through to [ProviderContainer.defaultRetry] for
|
|
/// everything else.
|
|
///
|
|
/// Pass this to [ProviderScope.retry] at the root of the widget tree.
|
|
Duration? relayProviderRetry(int retryCount, Object error) {
|
|
if (isRelayDeadlineError(error)) return null;
|
|
return ProviderContainer.defaultRetry(retryCount, error);
|
|
}
|