mirror of
https://github.com/block/buzz.git
synced 2026-11-25 02:31:36 +00:00
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>
319 lines
12 KiB
Dart
319 lines
12 KiB
Dart
import 'dart:async';
|
|
import 'dart:io'
|
|
show Platform, SocketException, TlsException, WebSocketException;
|
|
|
|
import 'package:cronet_http/cronet_http.dart';
|
|
import 'package:cupertino_http/cupertino_http.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:jni/jni.dart' show JThrowable;
|
|
import 'package:objective_c/objective_c.dart';
|
|
import 'package:web_socket_channel/web_socket_channel.dart';
|
|
import 'package:flutter/foundation.dart' show debugPrint, visibleForTesting;
|
|
|
|
import '../diagnostics/diagnostic_reporter.dart';
|
|
import '../diagnostics/network_event_reporting.dart';
|
|
|
|
part 'counted_http_client.dart';
|
|
|
|
/// Which app-wide connection pool a request belongs to.
|
|
enum HttpTraffic {
|
|
/// Relay queries, NIP-11 documents, account and admission calls.
|
|
api,
|
|
|
|
/// Image, video and voice-note downloads and media uploads.
|
|
media,
|
|
}
|
|
|
|
/// The app-wide session for each traffic class, or null where the platform
|
|
/// has none.
|
|
final _sessions = <HttpTraffic, http.Client?>{};
|
|
|
|
/// An HTTP client for [traffic]. Callers own it and close it as usual.
|
|
///
|
|
/// On iOS and Android, every client for the same [traffic] shares one native
|
|
/// session (`NSURLSession` or a Cronet engine), so requests to a host
|
|
/// multiplex over one HTTP/2 connection instead of opening an HTTP/1.1
|
|
/// connection each, and gzip is inflated natively, off the Dart isolate.
|
|
/// Media has its own session, and so its own connection, so image bytes
|
|
/// cannot starve queries queued behind them on a shared connection.
|
|
///
|
|
/// Elsewhere this is `http.Client()`, which also honors `http.runWithClient`.
|
|
///
|
|
/// Every request through the returned client is counted for diagnostics
|
|
/// ([appHttpDiagnostics]).
|
|
http.Client newAppHttpClient([HttpTraffic traffic = HttpTraffic.api]) {
|
|
final session = _sessions.putIfAbsent(traffic, _openNativeSession);
|
|
if (session == null) return _CountedClient(http.Client(), traffic);
|
|
return _CountedClient(
|
|
SharedSessionClient(session, streamsUploads: !Platform.isAndroid),
|
|
traffic,
|
|
);
|
|
}
|
|
|
|
/// Whether [newAppHttpClient] uses a native session on this device.
|
|
bool get hasNativeHttpSession =>
|
|
_sessions.putIfAbsent(HttpTraffic.api, _openNativeSession) != null;
|
|
|
|
http.Client? _openNativeSession() {
|
|
if (Platform.isIOS) return _openUrlSession();
|
|
if (Platform.isAndroid) return _openCronetSession();
|
|
return null;
|
|
}
|
|
|
|
/// Matches the `dart:io` transport apart from the protocol: no HTTP cache and
|
|
/// no cookies.
|
|
http.Client _openUrlSession() {
|
|
final config = URLSessionConfiguration.ephemeralSessionConfiguration()
|
|
..cache = null
|
|
..httpShouldSetCookies = false
|
|
..httpCookieAcceptPolicy =
|
|
NSHTTPCookieAcceptPolicy.NSHTTPCookieAcceptPolicyNever;
|
|
return CupertinoClient.fromSessionConfiguration(config);
|
|
}
|
|
|
|
/// Matches the `dart:io` transport apart from the protocol: no HTTP cache,
|
|
/// and Cronet keeps no cookies. QUIC stays off, so this changes only the
|
|
/// HTTP version.
|
|
///
|
|
/// Null when no Cronet provider is available: Cronet comes from Google Play
|
|
/// services, which some Android devices don't have. Those keep `dart:io`.
|
|
http.Client? _openCronetSession() {
|
|
final CronetEngine engine;
|
|
try {
|
|
engine = CronetEngine.build(
|
|
cacheMode: CacheMode.disabled,
|
|
enableHttp2: true,
|
|
enableQuic: false,
|
|
);
|
|
} on JThrowable catch (error) {
|
|
debugPrint('Cronet is unavailable, using dart:io: ${error.message}');
|
|
return null;
|
|
}
|
|
return CronetClient.fromCronetEngine(engine);
|
|
}
|
|
|
|
/// A caller's handle on an app-wide session. Like closing a `dart:io` client,
|
|
/// [close] cancels the handle's requests still in flight and refuses later
|
|
/// ones, but leaves the session open for other handles. Closing a
|
|
/// `CupertinoClient` while any of its requests run would also throw, and
|
|
/// closing a `CronetClient` would stop the shared engine.
|
|
///
|
|
/// App Transport Security blocks cleartext `URLSession` loads from public
|
|
/// hosts, while saved community icons and remote media may still use
|
|
/// `http://`. Those keep the handle's own `dart:io` client, as before.
|
|
///
|
|
/// Unless [streamsUploads], a streamed request with a body (media and voice
|
|
/// note uploads) also keeps `dart:io`: `CronetClient` reads the whole body
|
|
/// into memory before sending it, so progress would reach 100% before any
|
|
/// byte left and a large attachment would be copied in full.
|
|
@visibleForTesting
|
|
class SharedSessionClient extends http.BaseClient {
|
|
SharedSessionClient(
|
|
this._session, {
|
|
http.Client Function()? cleartext,
|
|
this.streamsUploads = true,
|
|
}) : _newCleartext = cleartext ?? http.Client.new;
|
|
|
|
final http.Client _session;
|
|
final http.Client Function() _newCleartext;
|
|
|
|
/// Whether the session streams request bodies instead of buffering them.
|
|
final bool streamsUploads;
|
|
|
|
/// One abort trigger per request still running, so [close] can cancel it.
|
|
/// A request leaves the set once its response body is done, failed or
|
|
/// cancelled, or once the caller's own abort trigger fires. A body nobody
|
|
/// listens to stays until then: the session keeps downloading it, so
|
|
/// callers that drop a response unread must abort it.
|
|
final _inFlight = <Completer<void>>{};
|
|
var _closed = false;
|
|
http.Client? _cleartext;
|
|
|
|
@override
|
|
Future<http.StreamedResponse> send(http.BaseRequest request) async {
|
|
if (_closed) {
|
|
throw http.ClientException(
|
|
'HTTP request failed. Client is already closed.',
|
|
request.url,
|
|
);
|
|
}
|
|
if (request.url.scheme != 'https' ||
|
|
(!streamsUploads && _isStreamedUpload(request))) {
|
|
return (_cleartext ??= _newCleartext()).send(request);
|
|
}
|
|
final abort = Completer<void>();
|
|
void fire() {
|
|
_inFlight.remove(abort);
|
|
if (!abort.isCompleted) abort.complete();
|
|
}
|
|
|
|
_inFlight.add(abort);
|
|
if (request case http.Abortable(:final abortTrigger?)) {
|
|
abortTrigger.then<void>((_) => fire(), onError: (_) => fire());
|
|
}
|
|
final http.StreamedResponse response;
|
|
try {
|
|
response = await _session.send(_withAbortTrigger(request, abort.future));
|
|
} catch (_) {
|
|
_inFlight.remove(abort);
|
|
rethrow;
|
|
}
|
|
// A controller, not an async* wrapper: async* never listens to the
|
|
// session's stream when cancelled before its first event, so the
|
|
// session would keep downloading a body nobody reads.
|
|
late final StreamSubscription<List<int>> inner;
|
|
final body = StreamController<List<int>>(sync: true);
|
|
body
|
|
..onListen = () {
|
|
inner = response.stream.listen(
|
|
body.add,
|
|
onError: body.addError,
|
|
onDone: () {
|
|
_inFlight.remove(abort);
|
|
body.close();
|
|
},
|
|
);
|
|
}
|
|
..onPause = (() => inner.pause())
|
|
..onResume = (() => inner.resume())
|
|
..onCancel = () {
|
|
_inFlight.remove(abort);
|
|
return inner.cancel();
|
|
};
|
|
|
|
return http.StreamedResponse(
|
|
http.ByteStream(body.stream),
|
|
response.statusCode,
|
|
contentLength: response.contentLength,
|
|
request: response.request,
|
|
headers: response.headers,
|
|
isRedirect: response.isRedirect,
|
|
persistentConnection: response.persistentConnection,
|
|
reasonPhrase: response.reasonPhrase,
|
|
);
|
|
}
|
|
|
|
static bool _isStreamedUpload(http.BaseRequest request) =>
|
|
request is! http.Request &&
|
|
request.method != 'GET' &&
|
|
request.method != 'HEAD';
|
|
|
|
/// A copy of [request] that the session cancels when [trigger] completes.
|
|
http.BaseRequest _withAbortTrigger(
|
|
http.BaseRequest request,
|
|
Future<void> trigger,
|
|
) {
|
|
if (request is http.Request) {
|
|
return http.AbortableRequest(
|
|
request.method,
|
|
request.url,
|
|
abortTrigger: trigger,
|
|
)
|
|
..bodyBytes = request.bodyBytes
|
|
..headers.addAll(request.headers)
|
|
..followRedirects = request.followRedirects
|
|
..maxRedirects = request.maxRedirects
|
|
..persistentConnection = request.persistentConnection;
|
|
}
|
|
// Finalizing first lets a multipart request set its content type.
|
|
final body = request.finalize();
|
|
final copy =
|
|
http.AbortableStreamedRequest(
|
|
request.method,
|
|
request.url,
|
|
abortTrigger: trigger,
|
|
)
|
|
..headers.addAll(request.headers)
|
|
..contentLength = request.contentLength
|
|
..followRedirects = request.followRedirects
|
|
..maxRedirects = request.maxRedirects
|
|
..persistentConnection = request.persistentConnection;
|
|
// addStream keeps backpressure: the body is read only as the session
|
|
// reads the copy, so upload progress tracks bytes the session has taken
|
|
// (including its read-ahead buffers), as with plain cupertino_http.
|
|
unawaited(copy.sink.addStream(body).whenComplete(copy.sink.close));
|
|
return copy;
|
|
}
|
|
|
|
@override
|
|
void close() {
|
|
_closed = true;
|
|
for (final abort in _inFlight.toList()) {
|
|
if (!abort.isCompleted) abort.complete();
|
|
}
|
|
_inFlight.clear();
|
|
_cleartext?.close();
|
|
}
|
|
}
|
|
|
|
/// How a native transport request failed, for user-facing messages.
|
|
/// `dart:io` failures are recognized by their messages instead.
|
|
enum TransportFailure { unreachable, insecure, timedOut }
|
|
|
|
/// The [TransportFailure] for a `URLSession` or Cronet error, or null for
|
|
/// any other error.
|
|
TransportFailure? transportFailure(Object error) => switch (error) {
|
|
NSErrorClientException(:final error)
|
|
when error.domain.toDartString() == 'NSURLErrorDomain' =>
|
|
urlErrorFailure(error.code),
|
|
NetworkException(:final errorCode, :final cronetInternalErrorCode) =>
|
|
cronetErrorFailure(errorCode, cronetInternalErrorCode),
|
|
_ => null,
|
|
};
|
|
|
|
/// Whether a native transport [error] says the device has no connection, as
|
|
/// opposed to a host that cannot be reached: `URLSession`'s not connected to
|
|
/// the internet, or Cronet's internet disconnected.
|
|
bool isOfflineTransportError(Object error) => switch (error) {
|
|
NSErrorClientException(:final error) =>
|
|
error.domain.toDartString() == 'NSURLErrorDomain' && error.code == -1009,
|
|
NetworkException(:final errorCode) => errorCode == 2,
|
|
_ => false,
|
|
};
|
|
|
|
/// Whether a native transport [error] says an open connection was lost:
|
|
/// `URLSession`'s network connection lost, or Cronet's connection closed or
|
|
/// reset.
|
|
bool isConnectionLostTransportError(Object error) => switch (error) {
|
|
NSErrorClientException(:final error) =>
|
|
error.domain.toDartString() == 'NSURLErrorDomain' && error.code == -1005,
|
|
NetworkException(:final errorCode) => errorCode == 5 || errorCode == 8,
|
|
_ => false,
|
|
};
|
|
|
|
/// Classifies an `NSURLErrorDomain` code.
|
|
@visibleForTesting
|
|
TransportFailure? urlErrorFailure(int code) => switch (code) {
|
|
-1001 => TransportFailure.timedOut,
|
|
// Cannot find host, cannot connect, connection lost, DNS lookup failed,
|
|
// international roaming off, cellular data not allowed, offline.
|
|
-1003 ||
|
|
-1004 ||
|
|
-1005 ||
|
|
-1006 ||
|
|
-1018 ||
|
|
-1020 ||
|
|
-1009 => TransportFailure.unreachable,
|
|
// Secure connection failed and the server certificate errors.
|
|
>= -1206 && <= -1200 => TransportFailure.insecure,
|
|
_ => null,
|
|
};
|
|
|
|
/// Classifies a Cronet `NetworkException` by its `ERROR_*` code and, for
|
|
/// `ERROR_OTHER`, Chromium's internal net error code.
|
|
@visibleForTesting
|
|
TransportFailure? cronetErrorFailure(int errorCode, int internalCode) =>
|
|
switch (errorCode) {
|
|
4 || 6 => TransportFailure.timedOut,
|
|
// Host not resolved, offline, network changed, connection closed,
|
|
// refused or reset, address unreachable.
|
|
1 || 2 || 3 || 5 || 7 || 8 || 9 => TransportFailure.unreachable,
|
|
// SSL protocol error, cipher mismatch, and the certificate errors.
|
|
11
|
|
when internalCode == -107 ||
|
|
internalCode == -113 ||
|
|
(internalCode <= -200 && internalCode >= -299) =>
|
|
TransportFailure.insecure,
|
|
_ => null,
|
|
};
|