mirror of
https://github.com/block/buzz.git
synced 2026-11-28 20:22:39 +00:00
feat(mobile): time channel opens and relay connection recovery (#9858)
Adds two durations to the mobile networking diagnostics, so work on channel opening and reconnecting has a before and after number from real use: - **Channel open** (`channelOpen`): from asking for a channel's newest history to the messages being shown, or to the failure that stopped it (including a refusal on the live subscription, or one a thread screen reports, which counts as a failed open with no duration when it comes before the history was asked for). Only a channel's first load counts; a catch-up after a reconnect is not an open. An open cut short by a lost connection keeps its clock, so the wait for the reconnect counts. An open that spans a move to the background, or starts there, is not counted, since it measured the time away, and a return after leaving the channel or after the background is a new open. An open the member backed out of still counts, since the load took that long, unless they left while a lost connection was still reconnecting, before its history was asked for again; after a failed open a retry counts as a new one. A refusal that arrives after a move to the background is not counted either: whether a refusal can count is fixed when the load starts. An open is filed under the member whose relay it ran on, and not counted when the app has since moved to another member. - **Relay recovery** (`relayRecovery`): from the last frame a lost connection delivered to the next authenticated connection. Starting at the last frame means the time it took to notice a dead socket counts too, which the existing connect duration misses. The app cannot see pongs, so a quiet connection is taken to have been alive until two ping intervals (60 s) before the loss, and idle time does not inflate the number by more than that: an idle connection that closes cleanly can read up to a minute, since a clean close and a missed ping look the same to the app. Failed attempts in between are part of one recovery. A loss in the background or followed by a move to the background, and a loss carried across a community switch, are not counted. A loss in the first seconds after a return from a brief stay in the background can reach back to before the stay, by at most that same minute. Both durations run on a monotonic clock, so a correction of the device's clock during an open or an outage does not inflate a sample or make it negative. Both go through the existing `network.event` count and `network.duration` distribution with their endpoint name, like the other networking events. ### Regressions None expected. These add no requests: each is one counted event per channel open or per recovered connection, recorded where the app already counts connection events. ### Validation Read from a profile build on an iPhone 12 mini against a hosted relay, with a local log of each event: - Seven channel opens after a cold start: `channelOpen` read 0.36 to 1.48 s per open, each matching the time from the history request to its response in the request log. - Three Wi-Fi drops of about 22 s with a channel open: `relayRecovery` read 30.1, 47.0 and 30.4 s, each spanning the drop, the time until the dead socket was noticed, and the reconnect. `relayConnection` alone read 0.28 to 0.36 s for the same reconnects, so the new duration is what shows the time lost to the dead socket. That run also covered the flows this touches: cold start, opening channels with back navigation, and losing and regaining the network with a channel open. Every open and every reconnect completed. Added tests: - [relay_network_counts_test.dart](mobile/test/shared/relay/relay_network_counts_test.dart): recovery is timed from the last frame, at most two ping intervals back, spans failed attempts, is not moved by a device clock set forward or back during the outage, and is not counted for the background or a community switch; existing journeys now expect a recovery after each loss. - [channel_open_timing_test.dart](mobile/test/features/channels/channel_open_timing_test.dart): an open is timed once, to its history being shown; a reconnect catch-up is not an open; an open spanning a reconnect keeps its start; a member change during the open, or an open started after the app moved to another member, records nothing; backing out still records it; a return after leaving starts a new clock; an open spanning a stay in the background, or started there, records nothing; a live refusal records a failed open, once, with its time when the member already backed out and with no duration when it comes before the history request; a refused retry after a failed open is a new open; a refusal on reconnect ends an open cut short by the lost connection with its full wait, or with no duration if the app was in the background meanwhile; a refusal that arrives before the history is asked for counts in the foreground and records nothing after a move to the background; a refusal reported by a thread screen ends a first open as one refused open, timed once the history was asked for, records nothing after a move to the background, and is not another open once the channel has loaded; a device clock set forward or back during an open does not move its time; a relay deadline is a timeout. Known limits: - The device run predates the final review commits, which changed which opens are counted (background, member switch, refusals) and moved both durations to a monotonic clock, not where an open or recovery starts or ends. - iOS Siri Quick Send tells the relay session the app is back in the foreground while it sends. A Quick Send to a DM whose messages were never loaded this run can count one open, and a connection lost during the send can count a recovery. Both are true first-load and recovery times, at most one open per DM per run. Moving Quick Send onto the background-work hold would remove both, which changes Quick Send and is left out of this PR. - When a saved page of a channel is already on screen, `channelOpen` measures how long fresh history took rather than how long the member waited to see anything, and it ends when the messages are handed to the screen, not at the first frame that draws them. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -43,7 +43,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat
|
||||
- **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.
|
||||
- **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) and for time to connect. 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.
|
||||
- **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.
|
||||
- **No log lines in step one.** The counts carry the member and the time, and the destination can filter them by member (see Further notes), so the fallback of one log line per outage is not needed.
|
||||
- **Breadcrumbs come from a fixed list:** networking events and screen names, written by the app, and the app moving to the foreground or background, written by the SDK. A screen name comes from the app's own list of screens (such as the channel list, a channel, a thread or settings), with any other page called "other". A screen whose name alone would say something about the person, such as the age restriction, is also called "other". It is never a channel or community name, an ID, a route's settings or anything a screen shows, so a report shows which screens the person was on and not what they were looking at. A breadcrumb is left when the person moves to a page or back to one, unless it names the same screen as the one before. Dialogs, sheets and menus leave none. The SDK's other automatic breadcrumbs, which could carry content or addresses, are turned off or filtered. Leaving a member (switching or signing out) clears the trail, so one member's networking events never reach another member's reports.
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import '../../shared/channels/saved_message_store.dart';
|
||||
import '../../shared/relay/relay.dart';
|
||||
import 'channel_event_order.dart';
|
||||
import 'channel_open_timing.dart';
|
||||
import 'pending_local_messages_provider.dart';
|
||||
import 'saved_channel_page.dart';
|
||||
import 'channel_window.dart';
|
||||
@@ -93,6 +94,9 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
ref.read(relaySessionProvider).status == SessionStatus.connected,
|
||||
);
|
||||
bool _hasListeners = true;
|
||||
ChannelOpenTimer? _openTimer;
|
||||
// The first load's untimed refusal, for a refusal that comes via a thread.
|
||||
ChannelOpenTimer? _openRefusal;
|
||||
Timer? _liveDetachTimer;
|
||||
bool _liveDetached = false;
|
||||
late final _summaryRefreshes = ThreadSummaryRefreshQueue(
|
||||
@@ -174,6 +178,8 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
_liveDetached = false;
|
||||
ref.onCancel(() {
|
||||
_hasListeners = false;
|
||||
_openTimer = null;
|
||||
_openRefusal = null;
|
||||
_deletionOwnerQueue.pause();
|
||||
_summaryRefreshes.pause();
|
||||
_liveDetachTimer?.cancel();
|
||||
@@ -253,6 +259,9 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
final ticket = cacheScope == null
|
||||
? null
|
||||
: cache.capture(cacheScope, (channelId: channelId, rootId: ''));
|
||||
ChannelOpenTimer? openTimer;
|
||||
final refusal = ChannelOpenTimer.refusal(ref, loaded: _hasLoadedHistory);
|
||||
_openRefusal = refusal;
|
||||
try {
|
||||
final session = ref.read(relaySessionProvider.notifier);
|
||||
|
||||
@@ -297,6 +306,7 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
StackTrace.current,
|
||||
cache,
|
||||
cacheScope,
|
||||
openTimer ?? _openTimer?.running ?? refusal,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -312,6 +322,11 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
);
|
||||
}
|
||||
|
||||
openTimer = _hasLoadedHistory
|
||||
? null
|
||||
: ChannelOpenTimer.resume(_openTimer, ref);
|
||||
// Shared only while the chat is open: a return later is a new open.
|
||||
if (_hasListeners) _openTimer = openTimer;
|
||||
final historyVersion = ++_threadQuerySerial;
|
||||
final (history, wireEvents) = await _fetchNewestHistory(
|
||||
session,
|
||||
@@ -345,6 +360,10 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
// catching up.
|
||||
_initInFlight = false;
|
||||
state = AsyncData(merged);
|
||||
// An open the member left before it finished still took this long.
|
||||
openTimer?.finish();
|
||||
_openTimer = null;
|
||||
_openRefusal = null;
|
||||
if (ticket != null && _hasListeners) {
|
||||
unawaited(
|
||||
saveMessagePage(
|
||||
@@ -361,9 +380,12 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
} catch (e, st) {
|
||||
if (!_isCurrentInit(initVersion)) return;
|
||||
if (isRelayChannelAccessDenied(e)) {
|
||||
_denyAccess(e, st, cache, cacheScope);
|
||||
_denyAccess(e, st, cache, cacheScope, openTimer ?? refusal);
|
||||
return;
|
||||
}
|
||||
openTimer?.finish(error: e);
|
||||
_openTimer = null;
|
||||
_openRefusal = null;
|
||||
if (_accessDenial != null) return;
|
||||
_historyRefreshFailed = true;
|
||||
final fallbackMessages = state.value ?? _lastKnownMessages;
|
||||
@@ -395,15 +417,20 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
stackTrace,
|
||||
ref.read(savedMessageStoreProvider),
|
||||
ref.read(savedMessageScopeProvider),
|
||||
_openTimer?.running ?? _openRefusal,
|
||||
);
|
||||
|
||||
void _denyAccess(
|
||||
Object error,
|
||||
StackTrace stackTrace,
|
||||
SavedMessageStore cache,
|
||||
SavedMessageScope? scope,
|
||||
) {
|
||||
SavedMessageScope? scope, [
|
||||
ChannelOpenTimer? openTimer,
|
||||
]) {
|
||||
_detachLive();
|
||||
_openTimer = null;
|
||||
_openRefusal = null;
|
||||
openTimer?.finish(error: error);
|
||||
_lastKnownMessages = null;
|
||||
_hasLoadedHistory = false;
|
||||
_windowStore = const ChannelWindowStore.empty();
|
||||
@@ -479,29 +506,6 @@ class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<ChannelWindowPage> _fetchWindowPage(
|
||||
RelaySessionNotifier session,
|
||||
ChannelPageCursor? cursor,
|
||||
) async {
|
||||
final events = await session.queryRelay([_channelWindowFilter(cursor)]);
|
||||
return parseChannelWindowResponse(events, channelId, cursor);
|
||||
}
|
||||
|
||||
NostrFilter _channelWindowFilter(ChannelPageCursor? cursor) => NostrFilter(
|
||||
kinds: EventKind.channelWindowPageKinds,
|
||||
tags: {
|
||||
'#h': [channelId],
|
||||
},
|
||||
limit: 50,
|
||||
until: cursor?.createdAt,
|
||||
extensions: {
|
||||
'top_level': true,
|
||||
'include_summaries': true,
|
||||
'include_aux': true,
|
||||
if (cursor != null) 'before_id': cursor.eventId,
|
||||
},
|
||||
);
|
||||
|
||||
void _handleLiveEvent(
|
||||
NostrEvent event, {
|
||||
bool authoritative = true,
|
||||
|
||||
@@ -1,6 +1,29 @@
|
||||
part of '../channel_messages_provider.dart';
|
||||
|
||||
extension _ChannelHistoryPagination on ChannelMessagesNotifier {
|
||||
Future<ChannelWindowPage> _fetchWindowPage(
|
||||
RelaySessionNotifier session,
|
||||
ChannelPageCursor? cursor,
|
||||
) async {
|
||||
final events = await session.queryRelay([_channelWindowFilter(cursor)]);
|
||||
return parseChannelWindowResponse(events, channelId, cursor);
|
||||
}
|
||||
|
||||
NostrFilter _channelWindowFilter(ChannelPageCursor? cursor) => NostrFilter(
|
||||
kinds: EventKind.channelWindowPageKinds,
|
||||
tags: {
|
||||
'#h': [channelId],
|
||||
},
|
||||
limit: 50,
|
||||
until: cursor?.createdAt,
|
||||
extensions: {
|
||||
'top_level': true,
|
||||
'include_summaries': true,
|
||||
'include_aux': true,
|
||||
if (cursor != null) 'before_id': cursor.eventId,
|
||||
},
|
||||
);
|
||||
|
||||
Future<bool> _fetchOlder() async {
|
||||
if (_reachedOldest || _initInFlight || _accessDenial != null) return false;
|
||||
final initVersion = _initVersion;
|
||||
|
||||
108
mobile/lib/features/channels/channel_open_timing.dart
Normal file
108
mobile/lib/features/channels/channel_open_timing.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
|
||||
import '../../shared/diagnostics/diagnostic_reporter.dart';
|
||||
import '../../shared/diagnostics/network_event_reporting.dart';
|
||||
import '../../shared/http/app_http_client.dart';
|
||||
import '../../shared/relay/relay.dart';
|
||||
|
||||
/// Times a channel opening: from asking for its newest history to showing
|
||||
/// it, or to the failure that stopped it. A catch-up after a reconnect is not
|
||||
/// an open, so callers time only a channel's first load.
|
||||
///
|
||||
/// The relay and its member are fixed when the request starts. An open that
|
||||
/// finishes after the reporter moved to another member belonged to someone
|
||||
/// else, and one that spanned a move to the background measured the time
|
||||
/// away, so neither is counted. Nor is one started in the background.
|
||||
class ChannelOpenTimer {
|
||||
factory ChannelOpenTimer(Ref ref, {bool timed = true}) {
|
||||
final config = ref.read(relayConfigProvider);
|
||||
final reporter = ref.read(diagnosticReporterProvider);
|
||||
return ChannelOpenTimer._(
|
||||
SignerDiagnosticReporter(reporter, signer: pubkeyFromNsec(config.nsec)),
|
||||
Uri.tryParse(config.baseUrl)?.host,
|
||||
ref.read(relaySessionProvider.notifier),
|
||||
timed,
|
||||
);
|
||||
}
|
||||
|
||||
ChannelOpenTimer._(this._reporter, this._host, this._session, this._timed)
|
||||
: _memberChanges = _reporter.memberChanges,
|
||||
_pauses = _session.pauses,
|
||||
_startedAt = _session.elapsed,
|
||||
_done = _session.backgrounded;
|
||||
|
||||
/// Continues [pending] if it is still running, since an open cut short by
|
||||
/// a reconnect keeps its clock and the wait counts; otherwise starts one.
|
||||
static ChannelOpenTimer resume(ChannelOpenTimer? pending, Ref ref) =>
|
||||
pending != null && !pending.isDone ? pending : ChannelOpenTimer(ref);
|
||||
|
||||
/// An untimed open for a load's refusal, which can end a first open before
|
||||
/// its history was asked for and then counts with no duration. It is fixed
|
||||
/// when the load starts, so a refusal that arrives after a move to the
|
||||
/// background or another member is not counted. Null once the channel
|
||||
/// has loaded, since a later refusal is not an open.
|
||||
static ChannelOpenTimer? refusal(Ref ref, {required bool loaded}) =>
|
||||
loaded ? null : ChannelOpenTimer(ref, timed: false);
|
||||
|
||||
final DiagnosticReporter _reporter;
|
||||
final String? _host;
|
||||
final RelaySessionNotifier _session;
|
||||
final int _memberChanges;
|
||||
final int _pauses;
|
||||
final Duration _startedAt;
|
||||
final bool _timed;
|
||||
bool _done;
|
||||
|
||||
/// Whether the open was already counted or dropped, or spanned a move to
|
||||
/// the background, so a later load starts a new one.
|
||||
bool get isDone => _done || _session.pauses != _pauses;
|
||||
|
||||
/// This timer while it still runs, so a carried open ends on it.
|
||||
ChannelOpenTimer? get running => isDone ? null : this;
|
||||
|
||||
/// Counts the open once, as a failure when [error] is set. Later calls do
|
||||
/// nothing.
|
||||
void finish({Object? error}) {
|
||||
if (isDone) return;
|
||||
_done = true;
|
||||
_count(error);
|
||||
}
|
||||
|
||||
void _count(Object? error) {
|
||||
final host = _host;
|
||||
if (host == null || host.isEmpty) return;
|
||||
if (_reporter.memberChanges != _memberChanges) return;
|
||||
final failure = error == null ? null : _failure(error);
|
||||
_reporter.noteNetworkEvent(
|
||||
NetworkEvent(
|
||||
backend: host,
|
||||
endpoint: NetworkEndpoint.channelOpen,
|
||||
outcome: failure == null
|
||||
? NetworkOutcome.success
|
||||
: NetworkOutcome.failure,
|
||||
failure: failure,
|
||||
duration: _timed ? _session.elapsed - _startedAt : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of failure that ended an open: the relay's own answers first,
|
||||
/// then the transport's.
|
||||
NetworkFailure _failure(Object error) {
|
||||
if (isRelayChannelAccessDenied(error)) return NetworkFailure.relayRefused;
|
||||
if (isRelayDeadlineError(error)) return NetworkFailure.timeout;
|
||||
if (error is RelayException) {
|
||||
return switch (error.statusCode) {
|
||||
429 => NetworkFailure.rateLimited,
|
||||
>= 500 => NetworkFailure.serverError,
|
||||
>= 400 => NetworkFailure.relayRefused,
|
||||
_ => NetworkFailure.other,
|
||||
};
|
||||
}
|
||||
final closed = error.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
if (classifyRelayClosed(closed) == RelayClosedClass.rateLimited) {
|
||||
return NetworkFailure.rateLimited;
|
||||
}
|
||||
return classifyTransportError(error) ?? NetworkFailure.other;
|
||||
}
|
||||
@@ -84,6 +84,15 @@ enum NetworkEndpoint {
|
||||
/// A live subscription the relay closed.
|
||||
relaySubscription,
|
||||
|
||||
/// An open relay connection coming back after it was lost, timed from the
|
||||
/// last frame the lost connection delivered, so the time it took to notice
|
||||
/// the loss counts too.
|
||||
relayRecovery,
|
||||
|
||||
/// Opening a channel: its newest history, timed from the request to the
|
||||
/// messages being shown.
|
||||
channelOpen,
|
||||
|
||||
/// The relay's HTTP query bridge: `/query`, `/count` and `/profiles/search`.
|
||||
relayHttpQuery,
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
http.Client Function()? httpClientFactory,
|
||||
RelaySocketFactory socketFactory = RelaySocket.new,
|
||||
DateTime Function()? now,
|
||||
Duration Function()? elapsed,
|
||||
RelayRateLimitGate? rateLimitGate,
|
||||
RelayTimerFactory retryTimerFactory = Timer.new,
|
||||
Future<void> Function(Duration) replayDelay = Future.delayed,
|
||||
@@ -61,6 +62,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
),
|
||||
_socketFactory = socketFactory,
|
||||
_now = now ?? DateTime.now,
|
||||
_elapsed = elapsed ?? _monotonic,
|
||||
_rateLimitGate = rateLimitGate ?? RelayRateLimitGate(),
|
||||
_retryTimerFactory = retryTimerFactory,
|
||||
_replayDelay = replayDelay,
|
||||
@@ -72,6 +74,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
final RelayHttpQueryClient _httpQueryClient;
|
||||
final RelaySocketFactory _socketFactory;
|
||||
final DateTime Function() _now;
|
||||
final Duration Function() _elapsed;
|
||||
final RelayRateLimitGate _rateLimitGate;
|
||||
final RelayTimerFactory _retryTimerFactory;
|
||||
final Future<void> Function(Duration) _replayDelay;
|
||||
@@ -99,11 +102,14 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
Timer? _flushTimer;
|
||||
Timer? _backgroundGraceTimer;
|
||||
DateTime? _backgroundedAt;
|
||||
int _pauses = 0;
|
||||
DateTime? _connectedAt;
|
||||
DateTime? _connectStartedAt;
|
||||
// The relay sent its terminal authorization denial on this connection.
|
||||
bool _authorizationDenied = false;
|
||||
DateTime? _lastInboundAt;
|
||||
Duration? _lastFrameElapsed;
|
||||
({Duration at, int context, int pauses})? _connectionLost;
|
||||
int _reconnectDelayMs = _baseReconnectDelayMs;
|
||||
int _subIdCounter = 0;
|
||||
bool _disposed = false;
|
||||
@@ -315,22 +321,6 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
return events;
|
||||
}
|
||||
|
||||
void _activateRateLimitGateFromHttpError(String body) {
|
||||
final dynamic decoded;
|
||||
try {
|
||||
decoded = jsonDecode(body);
|
||||
} on FormatException {
|
||||
return;
|
||||
}
|
||||
if (decoded is! Map<String, dynamic>) return;
|
||||
final message = decoded['error'];
|
||||
if (message is! String ||
|
||||
classifyRelayClosed(message) != RelayClosedClass.rateLimited) {
|
||||
return;
|
||||
}
|
||||
_rateLimitGate.activate(parseRateLimitRetrySeconds(message));
|
||||
}
|
||||
|
||||
/// Fetch historical events matching [filter]. Sends REQ, collects events
|
||||
/// until EOSE, then resolves. One-shot subscription.
|
||||
Future<List<NostrEvent>> fetchHistory(
|
||||
@@ -532,9 +522,19 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
return () => _beforePauseCallbacks.remove(owner);
|
||||
}
|
||||
|
||||
/// Counts moves to the background, so work can tell it spanned one.
|
||||
int get pauses => _pauses;
|
||||
|
||||
/// Time on a clock that device clock corrections don't move, for durations.
|
||||
Duration get elapsed => _elapsed();
|
||||
|
||||
/// Whether the app is in the background now.
|
||||
bool get backgrounded => _backgroundedAt != null;
|
||||
|
||||
/// Called by the app lifecycle provider when the app goes to background.
|
||||
void onAppPaused() {
|
||||
_backgroundedAt = _now();
|
||||
_pauses++;
|
||||
_backgroundGraceTimer?.cancel();
|
||||
_backgroundGraceTimer = Timer(_backgroundGraceDuration, () {
|
||||
unawaited(_pauseAfterCallbacks());
|
||||
@@ -669,10 +669,11 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
_connectedRelay = ref.read(relayConfigProvider).baseUrl;
|
||||
// The backoff is not reset here: a client bounced repeatedly must keep
|
||||
// backing off. [_handleDisconnected] resets it after a stable connection.
|
||||
_noteNetwork(NetworkEndpoint.relayConnection, since: _connectStartedAt);
|
||||
_noteConnected();
|
||||
_connectStartedAt = null;
|
||||
_connectedAt = _now();
|
||||
_lastInboundAt = _connectedAt;
|
||||
_lastFrameElapsed = _elapsed();
|
||||
state = const SessionState(status: SessionStatus.connected);
|
||||
await _replayLiveSubscriptions(generation);
|
||||
}
|
||||
@@ -817,6 +818,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
|
||||
void _handleMessage(List<dynamic> data) {
|
||||
_lastInboundAt = _now();
|
||||
_lastFrameElapsed = _elapsed();
|
||||
if (data.isEmpty) return;
|
||||
final type = data[0] as String;
|
||||
|
||||
|
||||
@@ -27,6 +27,24 @@ extension _RelaySessionDiagnostics on RelaySessionNotifier {
|
||||
);
|
||||
}
|
||||
|
||||
/// Counts a connection completing AUTH, and the recovery it ends when an
|
||||
/// open connection was lost before it.
|
||||
void _noteConnected() {
|
||||
_noteNetwork(NetworkEndpoint.relayConnection, since: _connectStartedAt);
|
||||
final lost = _connectionLost;
|
||||
_connectionLost = null;
|
||||
// A loss in another community's connection, or before a move to the
|
||||
// background, is not this one's recovery.
|
||||
if (lost != null &&
|
||||
lost.context == _contextGeneration &&
|
||||
lost.pauses == _pauses) {
|
||||
_noteNetwork(
|
||||
NetworkEndpoint.relayRecovery,
|
||||
duration: _elapsed() - lost.at,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts the end of a connect attempt or of an open connection, once: a
|
||||
/// socket that fails while authenticating reports it twice.
|
||||
///
|
||||
@@ -35,6 +53,19 @@ extension _RelaySessionDiagnostics on RelaySessionNotifier {
|
||||
void _noteDisconnected(Object? error, {bool denied = false}) {
|
||||
final since = _connectStartedAt;
|
||||
if (since == null && _connectedAt == null) return;
|
||||
// Recovery runs from the last frame, since a dead socket can look open
|
||||
// for a while. Pongs never reach here, but one is due every ping
|
||||
// interval, so a quiet socket was alive until at most two intervals
|
||||
// before the loss. Failed attempts after the loss keep the first time.
|
||||
if (_connectedAt != null && _backgroundedAt == null) {
|
||||
final provenAlive = _elapsed() - RelaySocket.pingInterval * 2;
|
||||
final inbound = _lastFrameElapsed;
|
||||
_connectionLost ??= (
|
||||
at: inbound != null && inbound > provenAlive ? inbound : provenAlive,
|
||||
context: _contextGeneration,
|
||||
pauses: _pauses,
|
||||
);
|
||||
}
|
||||
_connectStartedAt = null;
|
||||
_noteNetwork(
|
||||
NetworkEndpoint.relayConnection,
|
||||
@@ -98,6 +129,11 @@ extension _RelaySessionDiagnostics on RelaySessionNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// The session's default clock for durations. Unlike the wall clock, a device
|
||||
/// clock correction does not move it.
|
||||
Duration _monotonic() => _uptime.elapsed;
|
||||
final _uptime = Stopwatch()..start();
|
||||
|
||||
/// The relay's NOTICE for a refused or expired authorization, sent just before
|
||||
/// it closes the connection with 1008.
|
||||
const _authorizationDeniedNotice = 'restricted: authorization denied';
|
||||
|
||||
@@ -115,4 +115,20 @@ extension on RelaySessionNotifier {
|
||||
checkContext();
|
||||
return events;
|
||||
}
|
||||
|
||||
void _activateRateLimitGateFromHttpError(String body) {
|
||||
final dynamic decoded;
|
||||
try {
|
||||
decoded = jsonDecode(body);
|
||||
} on FormatException {
|
||||
return;
|
||||
}
|
||||
if (decoded is! Map<String, dynamic>) return;
|
||||
final message = decoded['error'];
|
||||
if (message is! String ||
|
||||
classifyRelayClosed(message) != RelayClosedClass.rateLimited) {
|
||||
return;
|
||||
}
|
||||
_rateLimitGate.activate(parseRateLimitRetrySeconds(message));
|
||||
}
|
||||
}
|
||||
|
||||
524
mobile/test/features/channels/channel_open_timing_test.dart
Normal file
524
mobile/test/features/channels/channel_open_timing_test.dart
Normal file
@@ -0,0 +1,524 @@
|
||||
import 'package:buzz/features/channels/channel_messages_provider.dart';
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/relay/relay.dart';
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:fake_async/fake_async.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
|
||||
import '../../helpers/fake_relay.dart';
|
||||
import '../../helpers/recording_diagnostics.dart';
|
||||
|
||||
const _channel = '11111111-1111-4111-8111-111111111111';
|
||||
|
||||
({
|
||||
FakeRelay relay,
|
||||
RecordingDiagnostics counts,
|
||||
ProviderContainer container,
|
||||
Iterable<NetworkEvent> Function() opens,
|
||||
})
|
||||
_start(FakeAsync async) {
|
||||
final relay = FakeRelay();
|
||||
final counts = RecordingDiagnostics();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
...relay.overrides,
|
||||
diagnosticReporterProvider.overrideWithValue(counts),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
container.listen(relaySessionProvider, (_, _) {});
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
counts.clear();
|
||||
return (
|
||||
relay: relay,
|
||||
counts: counts,
|
||||
container: container,
|
||||
opens: () => counts.events.where(
|
||||
(event) => event.endpoint == NetworkEndpoint.channelOpen,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('opening a channel is timed once, to its history being shown', () {
|
||||
fakeAsync((async) {
|
||||
final relay = FakeRelay();
|
||||
final counts = RecordingDiagnostics();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
...relay.overrides,
|
||||
diagnosticReporterProvider.overrideWithValue(counts),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
container.listen(relaySessionProvider, (_, _) {});
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
counts.clear();
|
||||
Iterable<NetworkEvent> opens() => counts.events.where(
|
||||
(event) => event.endpoint == NetworkEndpoint.channelOpen,
|
||||
);
|
||||
|
||||
final held = relay.holdQuery();
|
||||
final messages = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 2));
|
||||
expect(opens(), isEmpty, reason: 'nothing is shown yet');
|
||||
held.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
expect(messages.read().hasValue, isTrue);
|
||||
final open = opens().single;
|
||||
expect(open.backend, 'relay.test');
|
||||
expect(open.outcome, NetworkOutcome.success);
|
||||
expect(open.duration, greaterThanOrEqualTo(const Duration(seconds: 2)));
|
||||
|
||||
// A catch-up after a reconnect is not an open.
|
||||
relay.drop();
|
||||
async.elapse(const Duration(seconds: 40));
|
||||
expect(opens(), hasLength(1));
|
||||
});
|
||||
});
|
||||
|
||||
for (final correction in [
|
||||
const Duration(hours: 1),
|
||||
-const Duration(hours: 1),
|
||||
]) {
|
||||
test('a device clock set ${correction.isNegative ? 'back' : 'forward'} '
|
||||
'during an open does not move its time', () {
|
||||
fakeAsync((async) {
|
||||
var shift = Duration.zero;
|
||||
final fake = async.getClock(DateTime.utc(2026));
|
||||
final wall = Clock(() => fake.now().add(shift));
|
||||
withClock(wall, () {
|
||||
// Fake time is the monotonic clock; only the wall clock moves.
|
||||
final relay = FakeRelay(elapsed: () => async.elapsed);
|
||||
final counts = RecordingDiagnostics();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
...relay.overrides,
|
||||
diagnosticReporterProvider.overrideWithValue(counts),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
container.listen(relaySessionProvider, (_, _) {});
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
final held = relay.holdQuery();
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
shift = correction;
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
held.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
final open = counts.events.singleWhere(
|
||||
(event) => event.endpoint == NetworkEndpoint.channelOpen,
|
||||
);
|
||||
expect(
|
||||
open.duration,
|
||||
greaterThanOrEqualTo(const Duration(seconds: 2)),
|
||||
);
|
||||
expect(open.duration, lessThan(const Duration(seconds: 3)));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('an open that spans a reconnect is timed from its start', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final held = relay.holdQuery();
|
||||
final messages = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 3));
|
||||
final auth = relay.holdAuth();
|
||||
relay.drop();
|
||||
async.elapse(const Duration(seconds: 30));
|
||||
auth.complete();
|
||||
async.elapse(const Duration(milliseconds: 100));
|
||||
held.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
expect(messages.read().hasValue, isTrue);
|
||||
final open = opens().single;
|
||||
expect(open.outcome, NetworkOutcome.success);
|
||||
expect(open.duration, greaterThanOrEqualTo(const Duration(seconds: 33)));
|
||||
});
|
||||
});
|
||||
|
||||
test('an open is not counted for a member who signed in during it', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final held = relay.holdQuery();
|
||||
final messages = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
counts.setMember('someone else');
|
||||
held.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
expect(messages.read().hasValue, isTrue);
|
||||
expect(opens(), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
test('an open started after the reporter moved to another member '
|
||||
'is not counted for them', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
// A switch names the next member before the old relay is replaced.
|
||||
counts.setMember('someone else');
|
||||
final messages = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(messages.read().hasValue, isTrue);
|
||||
expect(opens(), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
test('an open spanning a brief stay in the background is not counted', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final held = relay.holdQuery();
|
||||
final messages = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
final session = container.read(relaySessionProvider.notifier);
|
||||
session.onAppPaused();
|
||||
async.elapse(const Duration(seconds: 2));
|
||||
session.onAppResumed();
|
||||
held.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
expect(messages.read().hasValue, isTrue);
|
||||
expect(opens(), isEmpty, reason: 'it measured the time away');
|
||||
});
|
||||
});
|
||||
|
||||
test('an open the member left still counts', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final held = relay.holdQuery();
|
||||
final page = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
page.close();
|
||||
held.complete();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(opens().single.outcome, NetworkOutcome.success);
|
||||
});
|
||||
});
|
||||
|
||||
test('a return after leaving a cut-short open is a new open', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
var held = relay.holdQuery();
|
||||
final page = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
page.close();
|
||||
relay.drop();
|
||||
async.elapse(const Duration(minutes: 10));
|
||||
held.complete();
|
||||
held = relay.holdQuery();
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 2));
|
||||
held.complete();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
final open = opens().single;
|
||||
expect(open.duration, lessThan(const Duration(minutes: 1)));
|
||||
});
|
||||
});
|
||||
|
||||
test('an open cut short by the background is not carried past it', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final held = relay.holdQuery();
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
final session = container.read(relaySessionProvider.notifier);
|
||||
session.onAppPaused();
|
||||
async.elapse(const Duration(minutes: 1));
|
||||
session.onAppResumed();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
held.complete();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(
|
||||
opens().single.duration,
|
||||
lessThan(const Duration(minutes: 1)),
|
||||
reason: 'the open after the return is a new one',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('a refusal on the live subscription counts as a failed open', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final held = relay.holdQuery();
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
relay.closeLive(
|
||||
(filter) => filter.containsKey('#h'),
|
||||
'restricted: not a channel member',
|
||||
);
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
held.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
final open = opens().single;
|
||||
expect(open.outcome, NetworkOutcome.failure);
|
||||
expect(open.failure, NetworkFailure.relayRefused);
|
||||
});
|
||||
});
|
||||
|
||||
test('a refusal before the history was asked for counts once', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
relay.refuseReq(
|
||||
(filter) => filter.containsKey('#h'),
|
||||
'restricted: not a channel member',
|
||||
);
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
final open = opens().single;
|
||||
expect(open.failure, NetworkFailure.relayRefused);
|
||||
expect(open.duration, isNull, reason: 'nothing timed it');
|
||||
});
|
||||
});
|
||||
|
||||
for (final away in [false, true]) {
|
||||
test(
|
||||
'a refusal that arrives before the history asks '
|
||||
'${away ? 'after a move to the background is not counted' : 'in the foreground counts'}',
|
||||
() {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final req = relay.holdReq();
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
expect(relay.reqs, isNotEmpty);
|
||||
if (away) {
|
||||
container.read(relaySessionProvider.notifier).onAppPaused();
|
||||
}
|
||||
relay.refuseReq(
|
||||
(filter) => filter.containsKey('#h'),
|
||||
'restricted: not a channel member',
|
||||
);
|
||||
req.complete();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(relay.queries, isEmpty, reason: 'refused before the history');
|
||||
if (away) {
|
||||
expect(
|
||||
opens(),
|
||||
isEmpty,
|
||||
reason: 'it spanned a move to the background',
|
||||
);
|
||||
} else {
|
||||
expect(opens().single.failure, NetworkFailure.relayRefused);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
for (final asked in [false, true]) {
|
||||
for (final away in [false, true]) {
|
||||
test(
|
||||
'a thread refusal ${asked ? 'during' : 'before'} the first history '
|
||||
'${away ? 'after a move to the background is not counted' : 'counts one refused open'}',
|
||||
() {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final req = asked ? null : relay.holdReq();
|
||||
final held = asked ? relay.holdQuery() : null;
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
expect(relay.queries, asked ? isNotEmpty : isEmpty);
|
||||
final session = container.read(relaySessionProvider.notifier);
|
||||
if (away) {
|
||||
session.onAppPaused();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
session.onAppResumed();
|
||||
}
|
||||
container
|
||||
.read(channelMessagesProvider(_channel).notifier)
|
||||
.denyAccessFromThread(
|
||||
Exception('restricted: not a channel member'),
|
||||
StackTrace.current,
|
||||
);
|
||||
req?.complete();
|
||||
held?.complete();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
if (away) {
|
||||
expect(opens(), isEmpty, reason: 'it spanned the background');
|
||||
} else {
|
||||
final open = opens().single;
|
||||
expect(open.failure, NetworkFailure.relayRefused);
|
||||
expect(open.duration, asked ? isNotNull : isNull);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
test('a thread refusal after the channel loaded is not another open', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(opens().single.outcome, NetworkOutcome.success);
|
||||
container
|
||||
.read(channelMessagesProvider(_channel).notifier)
|
||||
.denyAccessFromThread(
|
||||
Exception('restricted: not a channel member'),
|
||||
StackTrace.current,
|
||||
);
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(opens(), hasLength(1));
|
||||
});
|
||||
});
|
||||
|
||||
test('a relay that runs out of time on the history fails the open', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
relay.failQuery((_) => true, body: '{"error":"query timed out"}');
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
final open = opens().first;
|
||||
expect(open.outcome, NetworkOutcome.failure);
|
||||
expect(open.failure, NetworkFailure.timeout);
|
||||
});
|
||||
});
|
||||
|
||||
test('an open started in the background is not counted', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final session = container.read(relaySessionProvider.notifier);
|
||||
session.onAppPaused();
|
||||
final held = relay.holdQuery();
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 2));
|
||||
session.onAppResumed();
|
||||
held.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
expect(opens(), isEmpty, reason: 'it measured the time away');
|
||||
});
|
||||
});
|
||||
|
||||
test('a return after leaving before the history, once live detached, '
|
||||
'is a new open', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final req = relay.holdReq();
|
||||
final held = relay.holdQuery();
|
||||
final page = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(milliseconds: 10));
|
||||
page.close();
|
||||
req.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
expect(relay.queries, isNotEmpty);
|
||||
relay.drop();
|
||||
async.elapse(const Duration(minutes: 10));
|
||||
held.complete();
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(opens().single.duration, lessThan(const Duration(seconds: 1)));
|
||||
});
|
||||
});
|
||||
|
||||
test('a refused retry after a failed open counts as a new open', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
relay.failQuery((_) => true, body: '{"error":"query timed out"}');
|
||||
final page = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(opens().single.failure, NetworkFailure.timeout);
|
||||
counts.clear();
|
||||
relay.refuseReq((_) => true, 'restricted: not a channel member');
|
||||
container
|
||||
.read(channelMessagesProvider(_channel).notifier)
|
||||
.retryHistoryRefresh();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
expect(page.read().hasError, isTrue);
|
||||
final open = opens().single;
|
||||
expect(open.failure, NetworkFailure.relayRefused);
|
||||
expect(open.duration, isNull, reason: 'nothing timed it');
|
||||
});
|
||||
});
|
||||
|
||||
test('a refusal after the member backed out ends the open with its time', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
final held = relay.holdQuery();
|
||||
final page = container.listen(
|
||||
channelMessagesProvider(_channel),
|
||||
(_, _) {},
|
||||
);
|
||||
async.elapse(const Duration(seconds: 2));
|
||||
expect(relay.queries, isNotEmpty);
|
||||
page.close();
|
||||
relay.closeLive(
|
||||
(filter) => filter.containsKey('#h'),
|
||||
'restricted: not a channel member',
|
||||
);
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
held.complete();
|
||||
async.elapse(const Duration(milliseconds: 50));
|
||||
final open = opens().single;
|
||||
expect(open.failure, NetworkFailure.relayRefused);
|
||||
expect(open.duration, greaterThanOrEqualTo(const Duration(seconds: 2)));
|
||||
});
|
||||
});
|
||||
|
||||
for (final away in [false, true]) {
|
||||
test('a refusal on reconnect before the history ends the carried open'
|
||||
'${away ? ', untimed after a stay in the background' : ''}', () {
|
||||
fakeAsync((async) {
|
||||
final (:relay, :counts, :container, :opens) = _start(async);
|
||||
relay.holdQuery();
|
||||
container.listen(channelMessagesProvider(_channel), (_, _) {});
|
||||
async.elapse(const Duration(seconds: 2));
|
||||
final auth = relay.holdAuth();
|
||||
relay.drop();
|
||||
relay.refuseReq(
|
||||
(filter) => filter.containsKey('#h'),
|
||||
'restricted: not a channel member',
|
||||
);
|
||||
if (away) {
|
||||
final session = container.read(relaySessionProvider.notifier);
|
||||
session.onAppPaused();
|
||||
async.elapse(const Duration(seconds: 1));
|
||||
session.onAppResumed();
|
||||
}
|
||||
async.elapse(const Duration(seconds: 20));
|
||||
auth.complete();
|
||||
async.elapse(const Duration(milliseconds: 100));
|
||||
final open = opens().single;
|
||||
expect(open.failure, NetworkFailure.relayRefused);
|
||||
if (away) {
|
||||
expect(open.duration, isNull, reason: 'it measured the time away');
|
||||
} else {
|
||||
expect(
|
||||
open.duration,
|
||||
greaterThanOrEqualTo(const Duration(seconds: 22)),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,7 @@ class _Relay extends RelaySessionNotifier {
|
||||
void connect() => state = const SessionState(status: SessionStatus.connected);
|
||||
|
||||
/// Background pauses started; the real session closes the socket after one.
|
||||
@override
|
||||
var pauses = 0;
|
||||
|
||||
@override
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:buzz/shared/auth/auth_provider.dart';
|
||||
import 'package:buzz/shared/relay/relay.dart';
|
||||
import 'package:buzz/shared/relay/read_state_snapshot.dart';
|
||||
import 'package:buzz/shared/relay/relay_query_response.dart';
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hooks_riverpod/misc.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
@@ -26,8 +27,11 @@ import 'package:nostr/nostr.dart' as nostr;
|
||||
/// relay errors and falls back.
|
||||
class FakeRelay {
|
||||
/// [now] is the session's wall clock, so a test can model OS suspension:
|
||||
/// time passes while no timer runs.
|
||||
FakeRelay({DateTime Function()? now}) : _now = now {
|
||||
/// time passes while no timer runs. [elapsed] is its monotonic clock for
|
||||
/// durations, by default the test's fake time, which [now] does not move.
|
||||
FakeRelay({DateTime Function()? now, Duration Function()? elapsed})
|
||||
: _now = now,
|
||||
_elapsed = elapsed {
|
||||
addTearDown(() {
|
||||
expect(unanswerable, isEmpty, reason: 'requests FakeRelay cannot answer');
|
||||
});
|
||||
@@ -51,6 +55,7 @@ class FakeRelay {
|
||||
Completer<void>? _authHold;
|
||||
Completer<void>? _queryHold;
|
||||
final DateTime Function()? _now;
|
||||
final Duration Function()? _elapsed;
|
||||
|
||||
String get pubkey => keys.public;
|
||||
|
||||
@@ -65,6 +70,9 @@ class FakeRelay {
|
||||
),
|
||||
snapshotDecoder: (input) async => validateReadStateSnapshot(input),
|
||||
now: _now,
|
||||
elapsed:
|
||||
_elapsed ??
|
||||
() => Duration(microseconds: clock.now().microsecondsSinceEpoch),
|
||||
random: _MidpointRandom(),
|
||||
);
|
||||
|
||||
@@ -200,13 +208,13 @@ class FakeRelay {
|
||||
}
|
||||
reqs.add(message);
|
||||
final filters = message.skip(2).cast<Map<String, dynamic>>().toList();
|
||||
final refusal = _refusals.indexWhere((r) => filters.any(r.match));
|
||||
if (refusal >= 0) {
|
||||
final reason = _refusals.removeAt(refusal).message;
|
||||
scheduleMicrotask(() => socket._reply(['CLOSED', subId, reason]));
|
||||
return;
|
||||
}
|
||||
void admit() {
|
||||
final refusal = _refusals.indexWhere((r) => filters.any(r.match));
|
||||
if (refusal >= 0) {
|
||||
final reason = _refusals.removeAt(refusal).message;
|
||||
scheduleMicrotask(() => socket._reply(['CLOSED', subId, reason]));
|
||||
return;
|
||||
}
|
||||
if (!socket._authenticated) return;
|
||||
final history = _query(filters);
|
||||
if (history == null) return;
|
||||
|
||||
@@ -16,6 +16,7 @@ import '../../helpers/recording_diagnostics.dart';
|
||||
const _connection = NetworkEndpoint.relayConnection;
|
||||
const _query = NetworkEndpoint.relayQuery;
|
||||
const _publish = NetworkEndpoint.relayPublish;
|
||||
const _recovery = NetworkEndpoint.relayRecovery;
|
||||
|
||||
/// What the session counts for what the network and the relay do, with only
|
||||
/// the socket and HTTP boundary fake. None of it is an error report.
|
||||
@@ -63,6 +64,7 @@ void main() {
|
||||
(_connection, failure),
|
||||
(NetworkEndpoint.relayReconnect, null),
|
||||
(_connection, null),
|
||||
(_recovery, null),
|
||||
],
|
||||
]);
|
||||
// Everything on the trail too, and nothing was reported as an error.
|
||||
@@ -72,7 +74,7 @@ void main() {
|
||||
// A relay that refuses the member ends it for good, with no reconnect.
|
||||
s.relay.drop(const RelayAuthRejectedException('restricted: not a member'));
|
||||
s.settle(const Duration(seconds: 40));
|
||||
expect(s.counts.outcomes.skip(1 + losses.length * 3), [
|
||||
expect(s.counts.outcomes.skip(1 + losses.length * 4), [
|
||||
(_connection, NetworkFailure.authRefused),
|
||||
]);
|
||||
});
|
||||
@@ -171,6 +173,7 @@ void main() {
|
||||
(_publish, NetworkFailure.disconnected),
|
||||
(NetworkEndpoint.relayReconnect, null),
|
||||
(_connection, null),
|
||||
(_recovery, null),
|
||||
]);
|
||||
expect(s.counts.errors, isEmpty);
|
||||
|
||||
@@ -262,17 +265,128 @@ void main() {
|
||||
(_connection, NetworkFailure.disconnected),
|
||||
(NetworkEndpoint.relayReconnect, null),
|
||||
(_connection, null),
|
||||
(_recovery, null),
|
||||
(_connection, NetworkFailure.authRefused),
|
||||
(NetworkEndpoint.relayReconnect, null),
|
||||
(_connection, null),
|
||||
(_recovery, null),
|
||||
(_connection, NetworkFailure.disconnected),
|
||||
(NetworkEndpoint.relayReconnect, null),
|
||||
(_connection, null),
|
||||
(_recovery, null),
|
||||
]);
|
||||
});
|
||||
|
||||
journey('recovery is timed from the last frame the lost socket delivered', (
|
||||
async,
|
||||
s,
|
||||
) {
|
||||
s.settle();
|
||||
// The socket goes quiet for 20 s before the loss is noticed.
|
||||
s.session.debugHandleMessage(['NOTICE', 'still here']);
|
||||
s.settle(const Duration(seconds: 20));
|
||||
s.counts.clear();
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(seconds: 40));
|
||||
final recovery = s.counts.events.singleWhere(
|
||||
(e) => e.endpoint == _recovery,
|
||||
);
|
||||
final reconnected = s.counts.events.lastWhere(
|
||||
(e) => e.endpoint == _connection,
|
||||
);
|
||||
expect(recovery.duration, greaterThan(const Duration(seconds: 20)));
|
||||
expect(recovery.duration, lessThan(const Duration(seconds: 25)));
|
||||
expect(recovery.duration, greaterThan(reconnected.duration!));
|
||||
|
||||
// Failed attempts in between are part of the same recovery.
|
||||
s.settle(const Duration(minutes: 1));
|
||||
s.counts.clear();
|
||||
s.relay.holdAuth();
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(seconds: 10));
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(minutes: 1));
|
||||
expect(s.counts.outcomes, [
|
||||
(_connection, NetworkFailure.disconnected),
|
||||
(NetworkEndpoint.relayReconnect, null),
|
||||
(_connection, NetworkFailure.disconnected),
|
||||
(NetworkEndpoint.relayReconnect, null),
|
||||
(_connection, null),
|
||||
(_recovery, null),
|
||||
]);
|
||||
|
||||
// Time in the background is not recovery: a loss just before it is
|
||||
// forgotten.
|
||||
s.counts.clear();
|
||||
s.relay.holdAuth();
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(seconds: 5));
|
||||
s.session.onAppPaused();
|
||||
s.settle(const Duration(seconds: 40));
|
||||
s.session.onAppResumed();
|
||||
s.settle(const Duration(seconds: 40));
|
||||
expect(s.counts.outcomes, isNot(contains((_recovery, null))));
|
||||
expect(s.counts.outcomes.last, (_connection, null));
|
||||
});
|
||||
|
||||
for (final correction in [
|
||||
const Duration(hours: 1),
|
||||
-const Duration(hours: 1),
|
||||
]) {
|
||||
journey('a device clock set ${correction.isNegative ? 'back' : 'forward'} '
|
||||
'during an outage does not move its recovery time', (async, s) {
|
||||
s.settle();
|
||||
s.session.debugHandleMessage(['NOTICE', 'still here']);
|
||||
s.counts.clear();
|
||||
s.relay.holdAuth();
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(seconds: 5));
|
||||
s.clockCorrection = correction;
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(seconds: 40));
|
||||
final recovery = s.counts.events.singleWhere(
|
||||
(e) => e.endpoint == _recovery,
|
||||
);
|
||||
expect(recovery.duration, greaterThan(const Duration(seconds: 5)));
|
||||
expect(recovery.duration, lessThan(const Duration(seconds: 45)));
|
||||
});
|
||||
}
|
||||
|
||||
journey('an idle socket was alive until at most two pings before its loss', (
|
||||
async,
|
||||
s,
|
||||
) {
|
||||
s.settle();
|
||||
s.session.debugHandleMessage(['NOTICE', 'still here']);
|
||||
s.settle(const Duration(minutes: 5));
|
||||
s.counts.clear();
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(seconds: 40));
|
||||
final recovery = s.counts.events.singleWhere(
|
||||
(e) => e.endpoint == _recovery,
|
||||
);
|
||||
expect(recovery.duration, lessThan(const Duration(seconds: 65)));
|
||||
|
||||
// A loss while in the background, before the pause, is not recovery.
|
||||
s.counts.clear();
|
||||
s.session.onAppPaused();
|
||||
final auth = s.relay.holdAuth();
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(seconds: 2));
|
||||
s.session.onAppResumed();
|
||||
s.settle(const Duration(seconds: 1));
|
||||
auth.complete();
|
||||
s.settle(const Duration(seconds: 40));
|
||||
expect(s.counts.outcomes.last, (_connection, null));
|
||||
expect(s.counts.outcomes, isNot(contains((_recovery, null))));
|
||||
});
|
||||
|
||||
journey('a community switch\'s first connect is not a reconnect', (async, s) {
|
||||
s.settle();
|
||||
// Nor a recovery, though the old connection was lost and not yet back.
|
||||
s.relay.holdAuth();
|
||||
s.relay.drop();
|
||||
s.settle(const Duration(seconds: 5));
|
||||
s.counts.clear();
|
||||
|
||||
s.container
|
||||
@@ -311,7 +425,11 @@ class _Session {
|
||||
|
||||
final FakeAsync async;
|
||||
// On the fake clock, so durations are the time that passed in the test.
|
||||
late final relay = FakeRelay(now: async.getClock(DateTime.utc(2026)).now);
|
||||
// [clockCorrection] moves only the device's wall clock.
|
||||
late final relay = FakeRelay(
|
||||
now: () => async.getClock(DateTime.utc(2026)).now().add(clockCorrection),
|
||||
);
|
||||
Duration clockCorrection = Duration.zero;
|
||||
final counts = RecordingDiagnostics();
|
||||
late final ProviderContainer container;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user