Files
buzz/mobile/lib/shared/http/app_http_client.dart
Tom Brow 5825a7a81f feat(mobile): handle Android push wakes (#9804)
Ticket 6 of the [Android push
design](https://github.com/block/buzz/pull/9555), building on [#9558
resolve push wakes](https://github.com/block/buzz/pull/9558). Enrollment
(FCM token registration, ticket 7) landed separately in [#9811 enroll
Android push](https://github.com/block/buzz/pull/9811), which also
carries the Firebase build config, `POST_NOTIFICATIONS` and the
auto-init switch.

## What it does

A data-only FCM message wakes the app with no content. This PR turns
that wake into notifications natively, with no UI:

- `PushWakeService` (a `FirebaseMessagingService`) treats both a message
and the deleted-messages callback as "sync now".
- If the app is in the foreground it does nothing. Otherwise it starts a
headless Flutter engine on `androidPushWakeMain`, which runs ticket 5's
`resolvePushWake` and hands the notifications back to native code to
post.
- If nothing has been posted after 2 s, a generic "New activity"
notification appears in the "Other" channel. The real result replaces it
silently, or removes it when there is nothing to show. An 8 s native
watchdog ends a run whose Dart side hangs.
- One run per process. A wake that arrives mid-run joins it and sets the
rerun flag from ticket 5.
- Channels: Direct messages, Mentions, Other. Each conversation is one
`MessagingStyle` notification, grouped under the app. Existing messages
in a conversation are recovered from the active notification so a new
wake appends instead of replacing.
- Tapping opens the conversation through the existing push deep-link
path (`pendingPushNotificationLink`), for a cold start and for a running
app. This also turns on the cold-start tap handoff for Android, which
was iOS-only.
- The headless path sends the NIP-FI header that org-protected relays
need, using the same `HostedRelayAuth` as the foreground app (background
mode: a fresh assertion per wake that never records foreground
failures). `resolvePushWake` gets one optional `relayHeaders` hook for
it.

## Decisions

- **Firebase config is build-time and never committed.**
`BUZZ_FIREBASE_APP_ID`, `BUZZ_FIREBASE_API_KEY`,
`BUZZ_FIREBASE_PROJECT_ID` and `BUZZ_FIREBASE_SENDER_ID` become string
resources (no google-services plugin or JSON file). All four or none: a
partial set fails the build, and a build with none works but has no push
wake. Documented in `mobile/README.md`.
- **The wake only reads the saved account session.** Its account clients
share the foreground app's record, so they never save, replace or delete
it. A rejected credential is dropped from the wake's memory only, which
keeps a sign-in that finished mid-wake.
- **No FCM token before enrollment.** Firebase Messaging's auto-init is
off, so a configured build does not register with Firebase at launch.
Ticket 7 requests the token when the app enrolls.
- **Notifications disabled means the wake is skipped entirely**, so
nothing is claimed as shown and the next wake after the user re-enables
them still delivers.
- **Debug hook.** Debug builds include an exported receiver that runs
the same code path as the FCM service, for testing without Firebase.

## Known gaps

- The foreground app does not yet write the shown-message record, so a
message already read in the app can notify again after the app is
backgrounded. This needs its own ticket.
- `PushWakeService` is now the app's only messaging service, so it
should hand `onNewToken` to the registration plugin from [#9811 enroll
Android push](https://github.com/block/buzz/pull/9811). It doesn't yet.
- Follow-ups now that enrollment is on main: real FCM wakes run one at a
time and never join a run; a blocked or silent "Other" channel mutes a
slow DM; a stale generic can make one message alert twice; NIP-FI
issuance can use the whole wake budget; a consumed tap replays after
process death; cold engine start registers every plugin.
- Follow-ups from review:
- A confirmed age restriction isn't applied to Android wakes, and the
Android purge doesn't cancel posted notifications.
- One unreadable entry, or a throw from `notify`, sends the whole batch,
already recorded as shown, to the generic notification.
- The foreground check can lag about 700 ms behind the app becoming
visible.
- There is no group summary, so below Android 16 several conversations
show as separate cards.
- On API 24 and 25 the notifications have no priority or defaults, so
they don't sound.
- A stall delivering the result over the channel can still use up the 1
s reserve before the watchdog.
- A shown-message claim writes its marker before its watermark and prune
I/O, so a stall past the 250 ms claim grace loses the message (from
[#9558 Dart
wake-to-notifications](https://github.com/block/buzz/pull/9558)).
- A live tap during cold start can be handled before the startup tap,
and the tap's target is carried in extras any app can send.
- The native side has no JVM tests yet, although `app/src/test/kotlin`
exists and CI runs it. A payload-contract test for
`WakeNotification.fromDart` and a test of the production
`_headlessRelayHeaders` wiring are follow-ups. The device runs below
cover the native side, and the Dart side (payload shape, joined runs,
header hook, cold-start tap) has tests.

### Validation

Run on a Pixel 9a (Android 17) against a local fake relay with test data
only, using a profile (AOT) build with the debug hook, since debug (JIT)
builds start the Dart engine in 4 to 5 s and say little about real
latency. Timings come from the `BuzzPushWake` log tags, measured from
the start of the wake.

| Scenario | Result |
| --- | --- |
| Cold wake, process killed, one DM | Notification posted at 2.0 s
(engine 0.9 s, Dart ready 1.8 s), three runs within 0.1 s of each other
|
| Wake while the process is warm | Posted at 0.4 s |
| Two conversations in one wake | One grouped notification card, each
conversation its own `MessagingStyle`, posted at 2.1 s |
| Relay answers in 2.4 s | Generic "New activity" at 2.0 s, replaced by
the real notification at 5.8 s, generic removed, replacement did not
beep (the system's `notification_alert` event shows no sound for it,
while the generic did beep) |
| Relay answers in 3.5 s (over the 3 s request limit) | Generic stays at
5.0 s, nothing is claimed |
| Next wake after that, relay healthy | Real notification at 0.4 s and
the stale generic is gone (the case fixed in `c786957`) |
| Relay accepts the connection and never answers | Dart's own 3 s
request timeout ends the wake at 5.0 s as incomplete, generic stays |
| App in the foreground | Wake ignored, no notification; after
backgrounding, the next wake delivers |
| Tap, app running in background | The existing deep-link provider
receives the right community, channel and message; notification
dismisses |
| Tap, process killed | Same |
| 10 wakes in a row, debug build, app process kept alive | Network
threads stay at 3 and total threads flat (53 to 58). Before the switch
to dart:io, each wake left about 2 Cronet threads behind (3 to 11 over 5
wakes) |

An earlier run on an Android 36 emulator gave the same behavior.

Not exercised: the FCM service itself (it is not exported and there is
no Firebase config), so the deleted-messages callback was not triggered,
though it calls the same entry as the debug hook. The 8 s native
watchdog was not reached: a hung relay is always ended earlier by Dart's
request timeout, and only a hung Dart isolate would trigger it. NIP-FI
against an org-protected relay is covered only by unit tests. The tap
was checked up to the deep-link provider, not to the chat screen,
because the fake relay does not serve the channel list the app needs to
open it.

On a debug (JIT) build the main thread is busy for several seconds
starting the engine, so the 2 s generic timer, which runs on that
thread, fired at 5.3 s.

Added tests:
[`android_push_wake_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/android_push_wake_test.dart)
covers the native payload, joined and sequential wakes, the relay header
hook, and a community whose headers fail.
[`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/push_bridge_test.dart)
covers the Android cold-start tap.

### Screenshots

Before: no notification (nothing handles wakes). After, with test data,
on the Pixel 9a (two conversations grouped) and on the emulator (one
conversation after a cold wake):

<img
src="https://github.com/user-attachments/assets/d3d98784-fecc-4757-a867-0a93d5a210a5"
width="300" alt="Two conversations grouped on a Pixel"> <img
src="https://github.com/user-attachments/assets/1e7fea3c-7f72-4f8d-90d1-8c289cf1b740"
width="300" alt="One conversation after a cold wake on an emulator">

## Regressions

- Adds the `POST_NOTIFICATIONS` permission and the Firebase Messaging
and `lifecycle-process` dependencies, so the Android build and APK grow.
The runtime permission prompt is not part of this PR.
- Debug builds ship an exported broadcast receiver that can trigger a
wake. Release builds do not include it.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost:3000>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 16:43:08 -07:00

331 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,
);
}
/// Makes [newAppHttpClient] use `dart:io` in this isolate from now on, for an
/// engine that lives only briefly. A native session belongs to the process,
/// not the isolate: a Cronet engine keeps its threads after the Flutter engine
/// that opened it is destroyed, so one opened per push wake would leak them.
/// Call it before anything opens a client.
void useDartIoHttpOnly() {
assert(_sessions.isEmpty, 'A native session is already open');
for (final traffic in HttpTraffic.values) {
_sessions[traffic] = null;
}
}
/// 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,
};