Files
buzz/mobile/lib/shared/relay/relay_http_query_client.dart
Tom Brow 7382130948 feat(mobile): count networking events for diagnostics (#9810)
Implements the networking counts in docs/mobile-diagnostic-reporting.md:
every request through the shared HTTP client and every relay connection
event is counted, with backend (host), endpoint (from a fixed list),
outcome and kind of failure, plus a duration for requests and time to
connect.

## Changes

- **HTTP:** `newAppHttpClient` returns a counting wrapper, and the relay
HTTP query client wraps its own transport the same way. A failure status
is counted at its headers, a transport failure when it happens, and a
success once its body ends or its reader stops (duration is still time
to headers). A caller deadline noted with `noteHttpDeadline` makes a
request still waiting for headers or still reading its body a timeout;
the invite mint now notes its deadline too. Requests the app cancels are
not counted, and a throwing reporter never changes a request's result. A
request counts only for the member who started it, and is dropped if it
finishes while anyone else, or no one, is signed in. Only failed
requests leave a breadcrumb, so successes don't push useful entries out
of the SDK's buffer.
- **Backend names:** only the app's own hosts are named (relays this run
has used, the build's Builderlab origin and hosted relay domains, the
push gateway). Any other host, such as a remote image's, is counted as
`external`.
- **Relay:** the session counts connected (with time to connect),
disconnected or a failed attempt (once per attempt), reconnect attempts,
history queries (EOSE, CLOSED, timeout), publishes (OK true or false,
ack timeout) and live subscriptions closed by the relay. Queries and
publishes still unanswered when the socket drops are counted as
disconnected. A refused protected upgrade is counted before its renewal,
and the relay's authorization denial makes the following close an auth
refusal. Intentional disconnects (background pause, sign-out, community
switch) are not counted. The session's debug hooks moved to
`relay_session_test_hooks.dart` to stay under the file-size limit.
- **Install ID on counts:** metrics carry scope attributes but not scope
tags, so startup also sets `install.id` as an attribute, and the filter
allows it.
- **Spec:** marks counts as implemented and records that the destination
can filter counts by member, so the log-line fallback isn't needed.

### Endpoints

`relayConnection`, `relayReconnect`, `relayQuery`, `relayPublish`,
`relaySubscription`, `relayHttpQuery` (`/query`, `/count`,
`/profiles/search`), `relayInfo` (GET of a server's root),
`mediaDownload`, `mediaUpload`, `communityAdmission`,
`builderlabAccount`, `otherHttp`.

### Failure kinds

| Source | Kind |
|---|---|
| 401, 403 | `authRefused` |
| 408, abort before headers, timeouts | `timeout` |
| 429 | `rateLimited` |
| 5xx | `serverError` |
| Other 4xx | `clientError` (new) |
| No network | `offline` |
| Host unreachable | `unreachable` |
| TLS failure | `insecure` |
| Connection closed or reset (including ECONNRESET) | `disconnected` |
| Relay `rate-limited:` / `query timed out` | `rateLimited` / `timeout`
|
| Other relay refusal prefixes (`restricted:`, `auth-required:`,
`invalid:`, ...) | `relayRefused` |
| Anything else | `relayError` or `other` (new) |

## Validation

New tests:
- `counted_http_client_test.dart`: status and endpoint tables, transport
failure kinds (the error still reaches the caller and nothing is
reported as an error), a closed client, a throwing reporter, success
settled at body end, deadlines before headers and mid-body, requests
held across a member switch and a sign-out, and remote media hosts
counted as external.
- `relay_network_counts_test.dart`: connect, disconnect, reconnect, auth
refusal, queries, publishes, CLOSED, operations lost with the socket, a
refused protected upgrade before renewal, the relay's authorization
denial, and another member's session counting nothing.


Full-app run on an iOS simulator at b7c03702d (signed in, healthy
relay): cold start and session restore, channel list and avatars,
history scrolled back to a channel's start, image viewer, image and
video upload with thumbnail and playback, search, channel details, DMs,
sending, Settings, and backgrounding for about 30 s then a send after
resume. No new app errors, and no stream errors in the device log. Not
covered: invite creation (the test community offers no invite tools) and
a request that actually hits a deadline, which the unit tests above
cover.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-21 09:42:22 -08:00

210 lines
6.5 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import 'package:buzz/shared/http/app_http_client.dart';
/// The default transport. On iOS and Android, the app-wide native session
/// inflates gzip natively, off the Dart isolate. `dart:io` would inflate on
/// the calling isolate, so leave its responses compressed for the response
/// decoder.
///
/// A non-`dart:io` client supplied through `http.runWithClient`, such as a
/// `MockClient`, is used as is. An `IOClient` is replaced, not closed, since
/// it may be shared.
http.Client _defaultTransport() {
if (hasNativeHttpSession) return newAppHttpClient();
final client = http.Client();
if (client is! IOClient) return countedAppHttpClient(client);
return countedAppHttpClient(IOClient(HttpClient()..autoUncompress = false));
}
/// Owns the reusable HTTP transport used for relay `/query` requests.
///
/// Requests advertise gzip. A response body may therefore come back
/// compressed; decode it with `relayResponseText` or `decodeRelayQueryResponse`.
class RelayHttpQueryClient {
RelayHttpQueryClient({
http.Client? client,
http.Client Function()? clientFactory,
}) : _injectedClient = client,
_clientFactory = clientFactory ?? _defaultTransport;
final http.Client? _injectedClient;
final http.Client Function() _clientFactory;
_ClientGeneration? _currentGeneration;
final Set<_ClientGeneration> _generations = {};
Future<http.Response> post(
Uri url, {
required Map<String, String> headers,
required List<int> body,
required Duration timeout,
http.Client Function(http.Client, bool Function())? decorate,
}) async {
final generation = _injectedClient == null
? (_currentGeneration ??= _createGeneration())
: null;
generation?.acquire();
var active = true;
// Retiring a generation cannot stop a request on a shared session, so a
// timed-out request is aborted rather than left holding bandwidth.
final abort = Completer<void>();
final request =
http.AbortableRequest('POST', url, abortTrigger: abort.future)
..followRedirects = false
..headers['Accept-Encoding'] = 'gzip'
..headers.addAll(headers)
..bodyBytes = body;
try {
final transport = _injectedClient ?? generation!.client;
final client = decorate?.call(transport, () => active) ?? transport;
return await client
.send(request)
.then(http.Response.fromStream)
.timeout(timeout);
} on TimeoutException {
noteHttpDeadline(request);
if (!abort.isCompleted) abort.complete();
if (identical(_currentGeneration, generation)) {
_currentGeneration = null;
}
generation?.retire();
rethrow;
} finally {
active = false;
generation?.release();
}
}
/// Sends a non-redirecting request, bounding bytes before buffering or parsing.
/// The deadline includes headers and the entire response body.
Future<http.Response> sendBounded(
http.Request request, {
required int maxBytes,
required Duration timeout,
http.Client Function(http.Client, bool Function())? decorate,
}) async {
// As in [post], a timed-out request on a shared session is aborted.
final abort = Completer<void>();
final sent =
http.AbortableRequest(
request.method,
request.url,
abortTrigger: abort.future,
)
..followRedirects = false
..headers.addAll(request.headers)
..bodyBytes = request.bodyBytes;
final generation = _injectedClient == null
? (_currentGeneration ??= _createGeneration())
: null;
generation?.acquire();
StreamIterator<List<int>>? iterator;
var finished = false;
Future<http.Response> receive() async {
final transport = _injectedClient ?? generation!.client;
final client = decorate?.call(transport, () => !finished) ?? transport;
final response = await client.send(sent);
if (finished) {
await response.stream.listen(null).cancel();
throw StateError('Relay request already timed out');
}
iterator = StreamIterator(response.stream);
if ((response.contentLength ?? 0) > maxBytes) {
throw const FormatException('Relay response exceeds byte limit');
}
final bytes = <int>[];
while (await iterator!.moveNext()) {
final chunk = iterator!.current;
if (bytes.length + chunk.length > maxBytes) {
throw const FormatException('Relay response exceeds byte limit');
}
bytes.addAll(chunk);
}
iterator = null; // An exhausted stream needs no cancellation.
return http.Response.bytes(
bytes,
response.statusCode,
headers: response.headers,
request: request,
);
}
try {
return await receive().timeout(timeout);
} on TimeoutException {
noteHttpDeadline(sent);
if (!abort.isCompleted) abort.complete();
if (identical(_currentGeneration, generation)) {
_currentGeneration = null;
}
generation?.retire();
rethrow;
} finally {
finished = true;
// Cancelling an iterator that never listened leaves the body
// downloading on a shared session, so abort on every exit.
if (!abort.isCompleted) abort.complete();
if (iterator != null) await iterator!.cancel();
generation?.release();
}
}
void close() {
for (final generation in _generations.toList()) {
generation.close();
}
_currentGeneration = null;
_injectedClient?.close();
}
_ClientGeneration _createGeneration() {
late final _ClientGeneration generation;
generation = _ClientGeneration(
_clientFactory(),
onClosed: () => _generations.remove(generation),
);
_generations.add(generation);
return generation;
}
}
class _ClientGeneration {
_ClientGeneration(this.client, {required this.onClosed});
final http.Client client;
final void Function() onClosed;
int _activeRequests = 0;
bool _retired = false;
bool _closed = false;
void acquire() {
assert(!_closed);
_activeRequests++;
}
void release() {
assert(_activeRequests > 0);
_activeRequests--;
_closeIfIdle();
}
void retire() {
_retired = true;
_closeIfIdle();
}
void close() {
if (_closed) return;
_closed = true;
client.close();
onClosed();
}
void _closeIfIdle() {
if (_retired && _activeRequests == 0) close();
}
}