mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +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>
181 lines
6.0 KiB
Dart
181 lines
6.0 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:collection';
|
|
import 'dart:isolate';
|
|
import 'dart:typed_data';
|
|
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import '../crypto/event_signing.dart';
|
|
import '../profile/profile_event_parser.dart';
|
|
import '../profile/user_profile.dart';
|
|
import '../../features/age_gate/age_signal_provider.dart';
|
|
import '../relay/relay_query_response.dart';
|
|
import '../relay/relay_session.dart';
|
|
import 'device_identity_source.dart';
|
|
import 'hosted_relay_auth.dart';
|
|
import '../http/app_http_client.dart';
|
|
|
|
final savedIdentityProfileClientProvider = Provider<http.Client Function()>(
|
|
(ref) => newAppHttpClient,
|
|
);
|
|
|
|
final _profileQueueProvider = Provider((ref) => _ProfileQueue());
|
|
|
|
/// Fetches the saved identity's own profile without changing the active session.
|
|
final savedIdentityProfileProvider = FutureProvider.autoDispose
|
|
.family<UserProfile?, String>((ref, pubkey) async {
|
|
if (ref.watch(ageSignalProvider) == AgeSignalState.restricted) {
|
|
return null;
|
|
}
|
|
final auth = ref.read(hostedRelayAuthProvider);
|
|
final createTransport = ref.read(savedIdentityProfileClientProvider);
|
|
final slot = ref.read(_profileQueueProvider).request();
|
|
http.Client? transport;
|
|
StreamIterator<List<int>>? chunks;
|
|
var active = true;
|
|
ref.onDispose(() {
|
|
active = false;
|
|
slot.cancelQueued();
|
|
if (chunks != null) unawaited(chunks!.cancel());
|
|
transport?.close();
|
|
});
|
|
if (!await slot.ready.future) return null;
|
|
try {
|
|
if (!active) return null;
|
|
return await DeviceIdentitySource().loadProfile(pubkey, (config) async {
|
|
if (!active) return null;
|
|
// Passive cards must never queue account restore/identity/assertion
|
|
// work ahead of reconnect or admission, even while still visible.
|
|
final headers = auth.cachedHeaders(config);
|
|
if (headers == null) return null;
|
|
final uri = Uri.parse(config.baseUrl).resolve('/query');
|
|
final body = utf8.encode(
|
|
jsonEncode([
|
|
{
|
|
'kinds': [0],
|
|
'authors': [pubkey],
|
|
'limit': 1,
|
|
},
|
|
]),
|
|
);
|
|
final attemptTransport = createTransport();
|
|
transport = attemptTransport;
|
|
var requesting = true;
|
|
chunks = null;
|
|
final client = attemptTransport;
|
|
final request = http.Request('POST', uri)
|
|
..followRedirects = false
|
|
..bodyBytes = body
|
|
..headers.addAll({
|
|
...headers,
|
|
'Content-Type': 'application/json',
|
|
'Authorization': buildNip98AuthHeader(
|
|
method: 'POST',
|
|
url: uri.toString(),
|
|
bodyBytes: body,
|
|
nsec: config.nsec,
|
|
pubkey: pubkey,
|
|
),
|
|
});
|
|
try {
|
|
final response = await (() async {
|
|
final response = await client.send(request);
|
|
if (!active || !requesting) return null;
|
|
chunks = StreamIterator(response.stream);
|
|
// One kind-0 event should fit comfortably within 256 KiB.
|
|
const maxBytes = 256 * 1024;
|
|
if (response.statusCode != 200 ||
|
|
(response.contentLength ?? 0) > maxBytes) {
|
|
return null;
|
|
}
|
|
final bytes = BytesBuilder(copy: false);
|
|
while (await chunks!.moveNext()) {
|
|
if (!active || !requesting) return null;
|
|
final chunk = chunks!.current;
|
|
if (chunk.length > maxBytes - bytes.length) return null;
|
|
bytes.add(chunk);
|
|
}
|
|
if (!active || !requesting) return null;
|
|
return (bytes.takeBytes(), response.headers['content-type']);
|
|
})().timeout(const Duration(seconds: 5));
|
|
if (!active || response == null) return null;
|
|
// Retain the queue slot until bounded decoding actually finishes.
|
|
return await _decodeProfile(response.$1, response.$2, pubkey);
|
|
} on TimeoutException {
|
|
noteHttpDeadline(request);
|
|
rethrow;
|
|
} finally {
|
|
// Retire this attempt before another relay can be tried.
|
|
requesting = false;
|
|
if (chunks != null) unawaited(chunks!.cancel());
|
|
client.close();
|
|
transport = null;
|
|
}
|
|
});
|
|
} finally {
|
|
slot.release();
|
|
}
|
|
});
|
|
|
|
Future<UserProfile?> _decodeProfile(
|
|
Uint8List bytes,
|
|
String? contentType,
|
|
String pubkey,
|
|
) => Isolate.run(() {
|
|
// The transport normally inflates HTTP gzip before the byte cap. Reject
|
|
// raw gzip here so the shared parser cannot expand a second, uncapped body.
|
|
if (bytes.length > 2 && bytes[0] == 0x1f && bytes[1] == 0x8b) return null;
|
|
final events = parseRelayQueryEvents(bytes, contentType);
|
|
for (final event in events) {
|
|
if (event.kind != 0 || event.pubkey != pubkey) continue;
|
|
verifiedNostrEventFromJson(jsonEncode(event.toJson()));
|
|
return parseProfileEvent(event).profile;
|
|
}
|
|
return null;
|
|
});
|
|
|
|
// Shared across identities in one provider container. Cancelled queued cards
|
|
// never reach secure storage, HTTP, or decoding.
|
|
class _ProfileQueue {
|
|
final _waiting = Queue<_ProfileSlot>();
|
|
int _running = 0;
|
|
|
|
_ProfileSlot request() {
|
|
final slot = _ProfileSlot(this);
|
|
_waiting.add(slot);
|
|
_drain();
|
|
return slot;
|
|
}
|
|
|
|
void _drain() {
|
|
while (_running < 3 && _waiting.isNotEmpty) {
|
|
final slot = _waiting.removeFirst();
|
|
_running++;
|
|
slot.ready.complete(true);
|
|
}
|
|
}
|
|
}
|
|
|
|
class _ProfileSlot {
|
|
_ProfileSlot(this.queue);
|
|
final _ProfileQueue queue;
|
|
final ready = Completer<bool>();
|
|
bool _released = false;
|
|
|
|
void cancelQueued() {
|
|
if (ready.isCompleted) return;
|
|
queue._waiting.remove(this);
|
|
ready.complete(false);
|
|
_released = true;
|
|
}
|
|
|
|
void release() {
|
|
if (_released) return;
|
|
_released = true;
|
|
queue._running--;
|
|
queue._drain();
|
|
}
|
|
}
|