mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
## Summary
The relay is starting to refuse a new open channel when another channel
in the community already has that name
(https://github.com/block/buzz/pull/8782). Mobile handled that refusal
badly in two places:
- **Creating a channel with a taken name** showed raw error text:
`Exception: invalid: an open channel named "Launch" already exists`. The
create sheet now shows `An open channel named "Launch" already exists`
and stays open, so the user can pick another name.
- **Joining a community by invite could fail.** After an invite join,
the app joins two starter channels, `#general` and `#welcome-everyone`,
and creates either one if it can't find it. If an archived channel or a
forum already holds one of those names, the relay now refuses the
create, and the whole join failed. Now the app skips a starter whose
name is held by a channel it can't use, and the join succeeds. If the
holder is a live channel the app didn't see at first, the app joins that
channel.
Screenshots from an Android emulator against a local relay built from
https://github.com/block/buzz/pull/8782 are in the Testing section.
## Details
- **Error text.** A new `relayErrorMessage` helper
(`lib/shared/relay/relay_closed_policy.dart`) removes the `Exception: `
wrapper and the relay's machine prefix (`invalid:`, `blocked:`,
`duplicate:` and the other standard prefixes), then capitalizes the
first letter. Only the create sheet uses it. The other error paths are
unchanged.
- **Starter channels** (`ensureStarterChannels` in `lib/app.dart`).
After a taken-name refusal, the app reloads the channel list and looks
for the channel that holds the name:
- A live open stream with that name: join it.
- An archived channel or a forum: skip that starter. An archived channel
can't be joined, and a forum is the wrong type for a starter.
- No visible holder: fail as before. The setup stays retryable, because
the holder may not be visible yet.
- **Which channel counts as the holder.** Only a channel that can hold
the name under the relay's rule counts: open, not unlisted, a stream or
forum. Channels now carry the relay's "unlisted" flag for this. An
unlisted channel with the same name (for example, an unlisted forum the
user is in) doesn't hold the name, so the app doesn't skip the starter
because of it.
- **A starter that was archived.** Desktop and mobile create each
starter at the same fixed id. When the starter at that id is archived,
the relay refuses a new create there with `invalid: channel is
archived`. The app treats that as an archived starter and skips it,
unless a live channel with the name exists. When the relay answers
`duplicate` and the reload doesn't show the channel, the app reads the
channel at the fixed id and skips the starter only if that channel is
archived.
- If `#welcome-everyone` is skipped, the join opens no particular
channel. Both callers already handle that.
### Related issue
None found. Client side of https://github.com/block/buzz/pull/8782.
### Testing
Android emulator, debug build of 778a4cada, local relay built from
https://github.com/block/buzz/pull/8782 at 0df245e3c, fresh database:
**Invite join while an archived `general` holds the name.** The app
skipped `general`, created `#welcome-everyone` at its starter id and
joined it. The archived `general` did not change, and no new `general`
was created.

**Create a channel with a taken name.** `ops` is live. Creating `OPS`
shows the relay's refusal as plain text, and the sheet stays open.

Automated tests: `invite_join_provider_test.dart` has a table row for
each holder case above (archived, forum, unlisted, appears late,
archived at the fixed id for both relay answers), plus the scope fences.
`channels_page_test.dart` covers the sheet text, and
`relay_closed_policy_test.dart` covers the helper. Each new skip fails
its row when it is removed. `just mobile-check` and `just mobile-test`
pass.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
132 lines
5.1 KiB
Dart
132 lines
5.1 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);
|
|
}
|
|
|
|
/// 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`.
|
|
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);
|
|
}
|