From 9a9d579460142ca4cf348136b1e11d26ba2e60dd Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Mon, 23 Nov 2026 14:04:45 -0800 Subject: [PATCH] feat(mobile): resolve push wakes into notifications in Dart (#9558) Ticket 5 of the [Android push design](https://github.com/block/buzz/pull/9555). It builds on [#9556 Dart body formatter](https://github.com/block/buzz/pull/9556), now merged. Native posting, the 2 s generic notification, the foreground check and FCM are ticket 6 and are not here. ## What it does `resolvePushWake` is the Dart half of an Android push wake. A wake carries no content, so it means "sync now": the function reads the saved communities, signs a `/query` to each relay (the same NIP-98 request the app uses), fetches what is newer than the last shown message, applies the same eligibility rules as the iOS resolver, and returns every eligible unshown message with title, body (ticket 4's formatter), conversation id, navigation target and category (direct message or mention). It is plain Dart: no Flutter UI and no Riverpod app state, so a headless engine can run it. - Eligibility is a port of the iOS `PushLeaseMatcher`, applied to the same subscriptions the app already syncs: self-authored messages and muted DMs are ignored (mutes reach the subscriptions for DMs only, as on iOS), and a message tagging more than 20 people is dropped. Only joined DMs and `#p` mentions notify. - Results are bounded: newest 20 overall, newest 8 per conversation. Messages cut by the caps are still recorded as shown, so a later wake does not bring them back. - `PushWakeRunner` runs one wake at a time per process. A wake that arrives mid-run sets a rerun flag, and every waiting caller gets one result with the notifications of every pass. ## Decisions - **Shown record.** One empty marker file per message, created exclusively. That is atomic across isolates and processes with no lock, and the foreground app can write the same record through the same `claim`. The newest time is the maximum of the marker names, so it can never move backwards (a separate cursor file would lose updates between concurrent writers). Markers older than 15 minutes before the newest are deleted. The app's other stores don't fit: `shared_preferences` has no atomic read-modify-write across isolates, and secure storage has none either. File locks were avoided because POSIX locks are per process, and the app and the background engine share a process. - **Claim before post.** `claim` is the post decision, so a message is returned at most once. If native posting then fails, the message is not offered again, as on iOS. - **Claim oldest first.** Each claim can advance the newest time, and claim rejects anything more than 15 minutes older, so messages are claimed oldest first. A wake cut short leaves only messages newer than everything it claimed, which the next fetch still covers. - **Fetch window.** Fetches start 15 minutes before the newest shown message, the same reorder window the iOS cache uses, and claim rejects anything older. With no record yet, the fetch looks back 15 minutes only, so a new install or community doesn't dump history. - **Timeouts.** 3 s per fetch request, 1.5 s for the sender and channel name lookup (which runs after messages are claimed, so a slow lookup costs only names), 5 s overall from entry, well under the ~8 s native watchdog. On expiry it returns what it has. `PushWakeResult.incomplete` lists communities that couldn't be read; with no notifications it tells the caller to use its generic fallback. Communities that failed record nothing, so the next wake retries them. - **Paging.** A relay answers each filter's newest `limit` events, so a page filled by messages that can't notify could hide an eligible one. A subscription whose 50-event page comes back full is read again below its oldest event, up to 5 pages per community; a community that stops at the cap, or whose later page fails, is reported incomplete and keeps what it read. A page over the 4 MiB cap is asked for again with half the events. - **Fresh reads.** Message filters ask for `"consistency": "strong"`, so a wake for a message that has just arrived isn't answered by a replica that lacks it. That costs one writer read per community per wake. - **Deadline.** The 5 s budget runs from entry, reading the community list included, and no request may outlast it. Claims already running get 250 ms to finish, and what a community claimed before the deadline is still returned. - **Thread target.** A reply opens its direct parent's thread, as the in-app inbox does; a broadcast reply opens the channel. - **Transport.** HTTP `/query` rather than a WebSocket: one round trip per community, no connection to keep, and the same request the iOS resolver sends. ## Regressions Nothing existing changes: the new files are not referenced by app code yet, so there is no runtime effect until ticket 6 wires them in. Bugs stay inside the new wake path. ## Open questions - Organization-protected relays need a federated-identity header, which the iOS extension gets from a shared session. The headless path sends none yet, so such a community is reported as failed. Wiring it belongs with ticket 6 or 7. - Before ticket 6 calls this: the notifications setting is read only at entry, where iOS rechecks before posting; and Solo chat titles get a `#` where iOS and the app show none. A wake the deadline cuts short claims oldest first, so it can show older messages and leave the newest for another wake that nothing prompts (each winning claim lists the store directory again, so a long offline backlog on slow storage is where this bites). Ticket 6 can rerun when a wake is incomplete but returned notifications, or batch the claims: oldest first, all markers created before one listing that checks and prunes, cap overflow still recorded. A claim that storage never answers can still be lost after the 250 ms grace. - First-wake baseline: with no shown record yet, a wake looks back only 15 minutes, so a phone's first wake after a longer outage (still inside the relay's delivery window) can miss the message that caused it and report complete. Ticket 7 owns the fix: write a bounded baseline at enrollment, before wakes are turned on. - A wake reads the community snapshot at entry; rechecking the saved community, identity and push preference just before posting is on ticket 6's list, before ticket 7 turns wakes on. - Sender names come only from profiles their authors signed. Channel titles come from kind 39000 events whose id and signature check out, but nothing yet checks that the signing key is the relay's, because the community record has no relay key. That check belongs with ticket 7's enrollment work, which learns the relay key. Until then a relay could only mislabel a notification the user is already entitled to. ### Validation Added tests: - `push_wake_journey_test.dart`: journeys against a fake relay (only `/query` over HTTP is fake): DM and mention notify; self-authored, muted, hellthread, unrelated and text-less messages don't; already shown doesn't repeat; several messages across two conversations after one wake; a missed wake recovered by the next; a catch-up after a quiet spell returns messages more than 15 minutes apart; several communities, including a wake stopped partway by a failed claim whose leftover message is far newer than the one claimed; per-conversation and overall caps without resurfacing; slow, silent and unreachable relays return inside the budget and recover on the next wake; two wakes in different "isolates" never notify twice; the app recording a message during a run is respected; a wake mid-run reruns once and loses or repeats nothing, and is reported incomplete when no budget is left to rerun. - The journeys now also cover: an eligible DM and mention behind a page of messages that can't notify; an oversized page retried at half size; a relay past the page cap, and a later page failing, both leaving the community unfinished; message reads pinned to the writer; reply and broadcast-reply tap targets; unsigned or forged names falling back to short keys; a community list that never loads, and storage that stalls one community's claim, both ending at the budget. - `shown_message_store_test.dart`: concurrent claims, the reorder window, future-dated messages, pruning. Break checks: removing the hellthread rule fails the first journey; making marker creation non-exclusive fails the concurrent-claim test and the two-isolate journey; claiming newest first fails the catch-up and partial-wake steps; dropping the skipped-rerun flag fails the rerun journey. --------- Signed-off-by: Tom Brow Signed-off-by: Tom Brow Co-authored-by: studio --- mobile/lib/features/activity/inbox_item.dart | 8 - .../shared/push/push_wake_eligibility.dart | 64 ++ .../lib/shared/push/push_wake_resolver.dart | 655 +++++++++++++ mobile/lib/shared/push/push_wake_runner.dart | 81 ++ .../lib/shared/push/shown_message_store.dart | 157 +++ .../shared/relay/relay_http_query_client.dart | 8 +- .../shared/relay/relay_query_response.dart | 20 +- mobile/lib/shared/relay/thread_reference.dart | 8 + mobile/test/helpers/push_wake_fixture.dart | 357 +++++++ .../shared/push/push_wake_journey_test.dart | 898 ++++++++++++++++++ .../shared/push/shown_message_store_test.dart | 106 +++ 11 files changed, 2349 insertions(+), 13 deletions(-) create mode 100644 mobile/lib/shared/push/push_wake_eligibility.dart create mode 100644 mobile/lib/shared/push/push_wake_resolver.dart create mode 100644 mobile/lib/shared/push/push_wake_runner.dart create mode 100644 mobile/lib/shared/push/shown_message_store.dart create mode 100644 mobile/test/helpers/push_wake_fixture.dart create mode 100644 mobile/test/shared/push/push_wake_journey_test.dart create mode 100644 mobile/test/shared/push/shown_message_store_test.dart diff --git a/mobile/lib/features/activity/inbox_item.dart b/mobile/lib/features/activity/inbox_item.dart index 08ff5da8ea..641da39c5d 100644 --- a/mobile/lib/features/activity/inbox_item.dart +++ b/mobile/lib/features/activity/inbox_item.dart @@ -33,14 +33,6 @@ int categoryPriority(String category) { List> tags, ) => parseThreadReference(tags); -/// Broadcast replies surface at the channel top level — desktop's -/// `isBroadcastReply`. -bool isBroadcastReply(List> tags) { - return tags.any( - (tag) => tag.length >= 2 && tag[0] == 'broadcast' && tag[1] == '1', - ); -} - /// A thread reply also sent to the channel: it has a parent and the /// broadcast tag. [isThreadReply] excludes it. bool isChannelSentReply(List> tags) => diff --git a/mobile/lib/shared/push/push_wake_eligibility.dart b/mobile/lib/shared/push/push_wake_eligibility.dart new file mode 100644 index 0000000000..29d2858a43 --- /dev/null +++ b/mobile/lib/shared/push/push_wake_eligibility.dart @@ -0,0 +1,64 @@ +import '../relay/nostr_models.dart'; +import 'push_subscription.dart'; + +/// Whether a subscription filter matches [event]. This is a port of +/// `PushLeaseFilter.matches` in `BuzzPushKit`: change the two together. +bool pushFilterMatches(BuzzPushFilter filter, NostrEvent event) { + if (!filter.kinds.contains(event.kind)) return false; + final authors = filter.authors; + if (authors != null && !authors.contains(event.pubkey.toLowerCase())) { + return false; + } + final pTags = filter.pTags; + if (pTags != null && !_hasAnyTag(event, 'p', pTags)) return false; + final hTags = filter.hTags; + if (hTags != null && !_hasAnyTag(event, 'h', hTags)) return false; + final eTags = filter.eTags; + if (eTags != null && !_hasAnyTag(event, 'e', eTags)) return false; + return true; +} + +/// Whether a subscription, with its ignore filters and hellthread +/// suppression, selects [event]. This is a port of +/// `PushLeaseMatcher.matches` in `BuzzPushKit`. +bool pushSubscriptionMatches( + BuzzPushSubscription subscription, + NostrEvent event, +) { + if (!pushFilterMatches(subscription.filter, event)) return false; + if (subscription.ignore.any((ignore) => pushFilterMatches(ignore, event))) { + return false; + } + final maximum = subscription.suppress?.pTagsMax; + if (maximum != null && _tagCount(event, 'p') > maximum) return false; + return true; +} + +/// A relay-signed workflow message names its owner in +/// `["p", owner, "", "owner"]` for attribution, not as a mention. Like the +/// relay, `p` matching and counting skip that tag on workflow messages. +bool _countsAsTag(List tag, String name, {required bool workflow}) { + if (tag.length < 2 || tag[0] != name) return false; + return !(workflow && name == 'p' && tag.length >= 4 && tag[3] == 'owner'); +} + +bool _isWorkflow(NostrEvent event) => event.tags.any( + (tag) => tag.length >= 2 && tag[0] == 'buzz:workflow' && tag[1] == 'true', +); + +int _tagCount(NostrEvent event, String name) { + final workflow = _isWorkflow(event); + return event.tags + .where((tag) => _countsAsTag(tag, name, workflow: workflow)) + .length; +} + +bool _hasAnyTag(NostrEvent event, String name, List values) { + final expected = {for (final value in values) value.toLowerCase()}; + final workflow = _isWorkflow(event); + return event.tags.any( + (tag) => + _countsAsTag(tag, name, workflow: workflow) && + expected.contains(tag[1].toLowerCase()), + ); +} diff --git a/mobile/lib/shared/push/push_wake_resolver.dart b/mobile/lib/shared/push/push_wake_resolver.dart new file mode 100644 index 0000000000..aa20b5c25e --- /dev/null +++ b/mobile/lib/shared/push/push_wake_resolver.dart @@ -0,0 +1,655 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:nostr/nostr.dart' as nostr; + +import '../community/community.dart'; +import '../community/community_storage.dart'; +import '../crypto/event_signing.dart' show verifySchnorrHex; +import '../relay/nostr_models.dart'; +import '../relay/relay_client.dart' show RelayException; +import '../relay/relay_http_query_client.dart'; +import '../relay/relay_provider.dart'; +import '../relay/relay_query_response.dart'; +import '../relay/relay_session.dart' show buildNip98AuthHeader; +import '../relay/thread_reference.dart' show isBroadcastReply; +import '../utils/string_utils.dart'; +import 'notification_body.dart'; +import 'push_wake_eligibility.dart'; +import 'shown_message_store.dart'; + +/// Most notifications one wake returns. The newest are kept, so a phone that +/// was offline for a day gets a screenful, not hundreds. +const pushWakeMaxNotifications = 20; + +/// Most notifications one conversation gets from one wake. Android's +/// `MessagingStyle` keeps at most 25 messages and the shade is unreadable well +/// before that, so a busy conversation shows its newest 8 and the rest are +/// older than anything the user can see. Messages beyond the cap are still +/// recorded as shown, so a later wake does not bring them back. +const pushWakeMaxPerConversation = 8; + +/// Most bytes a relay answer may have, as received and again once inflated. +/// Fifty events of the 64 KiB content limit fit with room to spare. +const pushWakeMaxResponseBytes = 4 * 1024 * 1024; + +/// Events one page of a wake's message fetch asks for, per subscription. +const pushWakeMessagePageSize = 50; + +/// Most pages one community's message fetch may take, however many events a +/// relay holds. A fetch that stops there leaves the community unfinished. +const pushWakeMaxMessagePages = 5; + +/// How a notification is categorized, which is the Android channel the user +/// may have silenced. A message in a direct-message channel is a +/// [directMessage] even when it also mentions the user. +enum PushWakeCategory { directMessage, mention } + +/// Where tapping a notification goes. These are the fields of the app's +/// message deep link. +class PushWakeTarget { + const PushWakeTarget({ + required this.communityId, + required this.channelId, + required this.eventId, + this.threadRootId, + }); + + final String communityId; + final String channelId; + final String eventId; + final String? threadRootId; + + Map toMap() => { + 'communityId': communityId, + 'channelId': channelId, + 'eventId': eventId, + 'threadRootId': ?threadRootId, + }; + + @override + bool operator ==(Object other) => + other is PushWakeTarget && + other.communityId == communityId && + other.channelId == channelId && + other.eventId == eventId && + other.threadRootId == threadRootId; + + @override + int get hashCode => + Object.hash(communityId, channelId, eventId, threadRootId); +} + +/// One message to notify about. +class PushWakeNotification { + const PushWakeNotification({ + required this.eventId, + required this.createdAt, + required this.title, + required this.body, + required this.conversationId, + this.conversationTitle, + required this.category, + required this.target, + }); + + final String eventId; + final DateTime createdAt; + + /// The sender's name. + final String title; + + /// Plain text from [notificationBody]. + final String body; + + /// Stable per conversation and community, for grouping. + final String conversationId; + + /// `#name` for a channel, null for a direct message. + final String? conversationTitle; + final PushWakeCategory category; + final PushWakeTarget target; + + PushWakeNotification named({String? title, String? conversationTitle}) => + PushWakeNotification( + eventId: eventId, + createdAt: createdAt, + title: title ?? this.title, + body: body, + conversationId: conversationId, + conversationTitle: conversationTitle, + category: category, + target: target, + ); +} + +/// What a wake found. +class PushWakeResult { + const PushWakeResult({ + required this.notifications, + this.failedCommunityIds = const [], + this.interrupted = false, + }); + + /// Every eligible unshown message, newest first, within the caps. + final List notifications; + + /// Communities whose messages could not be read in time. Their messages are + /// not recorded as shown, so the next wake retries them. + final List failedCommunityIds; + + /// Whether a pass failed before it could look anywhere, so the wake can't + /// say which communities it missed. + final bool interrupted; + + /// Whether the wake could not look everywhere. With no [notifications] the + /// caller shows its generic notification, so the wake is never silent. + bool get incomplete => interrupted || failedCommunityIds.isNotEmpty; +} + +/// Sorts newest first and applies [pushWakeMaxPerConversation] and +/// [pushWakeMaxNotifications]. +List capPushWakeNotifications( + Iterable notifications, +) { + final newestFirst = notifications.toList() + ..sort( + (a, b) => a.createdAt != b.createdAt + ? b.createdAt.compareTo(a.createdAt) + : a.eventId.compareTo(b.eventId), + ); + final perConversation = {}; + final kept = []; + for (final notification in newestFirst) { + final count = perConversation.update( + notification.conversationId, + (count) => count + 1, + ifAbsent: () => 1, + ); + if (count > pushWakeMaxPerConversation) continue; + kept.add(notification); + if (kept.length == pushWakeMaxNotifications) break; + } + return kept; +} + +/// Time limits of a wake. The native watchdog ends the work at about 8 s +/// whatever Dart does, so the whole wake stays well inside that, and one slow +/// relay can't use the budget the others need. +class PushWakeTimeouts { + const PushWakeTimeouts({ + this.request = const Duration(seconds: 3), + this.metadata = const Duration(milliseconds: 1500), + this.total = const Duration(seconds: 5), + }); + + /// Longest one HTTP request to a relay may take, including its body. + final Duration request; + + /// Longest the lookup of sender and channel names may take. It comes after + /// the messages are fetched and recorded, so [request] plus this stays + /// inside [total], and a slow lookup costs only the names. + final Duration metadata; + + /// Longest the whole wake may take, from the moment it starts, reading the + /// community list included. At this point it returns what it has, after a + /// short grace for claims already running. + final Duration total; +} + +/// Reads the configured communities and returns every eligible message not +/// yet shown, claiming each in [store] before returning it. +/// +/// It does what the iOS notification extension's resolver does, for a wake +/// that carries no content: sign in to each relay, fetch what is newer than +/// the last shown message, apply the subscription's eligibility rules +/// (self-authored, muted channels, hellthreads) and build title, body and +/// target for each message. +/// +/// It runs headless, with no UI and no Riverpod state, so it is safe to run +/// in a background engine. Callers run it one at a time per process; see +/// `PushWakeRunner`. +Future resolvePushWake({ + required ShownMessageStore store, + Future> Function()? loadCommunities, + http.Client? httpClient, + PushWakeTimeouts timeouts = const PushWakeTimeouts(), + DateTime Function()? now, +}) async { + final clock = now ?? DateTime.now; + // The budget starts here, so reading the community list spends it too. + final run = _WakeRun(); + final deadline = Completer(); + final timer = Timer(timeouts.total, deadline.complete); + final client = RelayHttpQueryClient(client: httpClient); + try { + final communities = await Future.any?>([ + (loadCommunities ?? CommunityStorage().loadAll)(), + deadline.future.then((_) => null), + ]); + // Not even the list could be read, so no community was looked at. + if (communities == null) { + return const PushWakeResult(notifications: [], interrupted: true); + } + final eligible = [ + for (final community in communities) + if (community.pushNotificationsEnabled && + (community.nsec?.isNotEmpty ?? false) && + community.pushSubscriptionState.authoritative.isNotEmpty) + community, + ]; + final tasks = [ + for (final community in eligible) + _resolveCommunity( + community, + run: run, + store: store, + client: client, + timeouts: timeouts, + clock: clock, + ).catchError((Object _) { + run.failed.add(community.id); + }), + ]; + await Future.any([Future.wait(tasks), deadline.future]); + // From here no task may start claiming. A claim already running gets a + // short grace to finish, so its message is returned, but a stalled one + // (storage that never answers) can't hold back the other communities. + run.closed = true; + await Future.wait( + run.claims, + ).timeout(_claimGrace, onTimeout: () => const []); + for (final community in eligible) { + if (!run.done.contains(community.id)) run.failed.add(community.id); + } + // A community still working was cut short. What it claimed is already + // recorded as shown, so it is returned, with short keys for titles. + for (final claimed in run.claimed.values) { + run.notifications.addAll(claimed); + } + return PushWakeResult( + notifications: capPushWakeNotifications(run.notifications), + failedCommunityIds: run.failed.toSet().toList()..sort(), + ); + } finally { + timer.cancel(); + // The caller may be in a long-lived process, and a request that outlived + // the budget must not keep holding the connection. + client.close(); + } +} + +/// How long claims already running get to finish once the wake's budget is +/// spent. Bounded, so a claim that never answers can't hold the wake. +const _claimGrace = Duration(milliseconds: 250); + +class _WakeRun { + final notifications = []; + final failed = []; + final done = {}; + final claims = >[]; + + /// What each community running now has claimed so far, which is returned if + /// the wake ends before the community does. + final claimed = >{}; + bool closed = false; + final _clock = Stopwatch()..start(); + + /// Whether the wake's budget is spent, by [PushWakeTimeouts.total] or + /// because the wake already stopped waiting for its tasks. + bool expired(PushWakeTimeouts timeouts) => + closed || _clock.elapsed >= timeouts.total; + + /// What is left of the budget, never negative. + Duration remaining(PushWakeTimeouts timeouts) { + final left = timeouts.total - _clock.elapsed; + return left.isNegative ? Duration.zero : left; + } +} + +Future _resolveCommunity( + Community community, { + required _WakeRun run, + required ShownMessageStore store, + required RelayHttpQueryClient client, + required PushWakeTimeouts timeouts, + required DateTime Function() clock, +}) async { + final nsec = community.nsec!; + final mine = (community.pubkey ?? pubkeyFromNsec(nsec))?.toLowerCase(); + if (mine == null) throw StateError('Community has no usable key'); + final subscriptions = community.pushSubscriptionState.authoritative; + final config = RelayConfig(baseUrl: community.relayUrl, nsec: nsec); + final url = Uri.parse(config.baseUrl).resolve('/query'); + + Future> query( + List> filters, { + required Duration timeout, + }) async { + // Whatever a request is allowed, it ends with the wake: once the budget + // is spent nothing is sent. + final left = run.remaining(timeouts); + if (run.expired(timeouts) || left == Duration.zero) { + throw TimeoutException('The wake has no time left'); + } + final body = utf8.encode(jsonEncode(filters)); + final request = http.Request('POST', url) + ..headers.addAll({ + 'Authorization': buildNip98AuthHeader( + method: 'POST', + url: url.toString(), + bodyBytes: body, + nsec: nsec, + pubkey: mine, + ), + 'Content-Type': 'application/json', + 'Accept-Encoding': 'gzip', + }) + ..bodyBytes = body; + // An untrusted relay can't make the wake buffer or inflate more than the + // cap, however small its compressed answer is. + final response = await client.sendBounded( + request, + maxBytes: pushWakeMaxResponseBytes, + timeout: timeout < left ? timeout : left, + ); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw RelayException(response.statusCode, ''); + } + final events = parseRelayQueryEvents( + response.bodyBytes, + response.headers['content-type'], + maxInflatedBytes: pushWakeMaxResponseBytes, + ); + // A relay answers each filter's `limit` at most. More is not a relay to + // spend signature checks on. + if (events.length > filters.fold(0, (n, f) => n + (f['limit'] as int))) { + throw const FormatException('Relay returned more events than asked'); + } + return events; + } + + final newest = await store.newestShown(community.id); + // Without a record there is no history to bound the fetch, and the message + // that caused this wake is recent, so look back one reorder window only. + final since = + (newest ?? clock()).millisecondsSinceEpoch ~/ 1000 - + shownMessageReorderWindow.inSeconds; + // Reads every subscription's messages since [since], newest first, a page + // at a time. A relay answers a filter's newest `limit` events, so when + // messages that can't notify (already shown, muted, or my own) fill a page, + // an eligible one may sit behind them: a subscription whose page came back + // full is read again below the oldest event it returned. + Future<({List events, bool complete})> fetchMessages() async { + final found = {}; + // The newest second each subscription still has to read, once a page of + // it has filled. Subscriptions that came back short are done. + final until = { + for (var i = 0; i < subscriptions.length; i++) i: null, + }; + var limit = pushWakeMessagePageSize; + var pages = 0; + var complete = true; + while (until.isNotEmpty) { + if (pages == pushWakeMaxMessagePages) { + return (events: found.values.toList(), complete: false); + } + final List page; + try { + page = await query([ + for (final MapEntry(key: i, value: latest) in until.entries) + { + ...subscriptions[i].filter.toJson(), + 'since': since, + 'until': ?latest, + 'limit': limit, + // A wake is for a message that has just arrived, which a lagging + // replica may not have yet. + 'consistency': 'strong', + }, + ], timeout: timeouts.request); + } on Object catch (error) { + // A page too big to take is asked for again with half the events. + if (error is RelayResponseTooLarge && limit > 1) { + limit ~/= 2; + continue; + } + // The first page failing is the community failing. A later one only + // leaves it unfinished, and the newest messages it did read still + // show. + if (pages == 0) rethrow; + return (events: found.values.toList(), complete: false); + } + pages++; + for (final event in page) { + found[event.id] = event; + } + for (final i in until.keys.toList()) { + // A subscription's page is what the relay answered for its filter: + // the events at or below its `until` that match it. Events another + // filter brought back can match it too (a DM that mentions me), but + // they say nothing about where its own page ended. + final latest = until[i]; + final filter = subscriptions[i].filter; + final times = { + for (final event in page) + if (pushFilterMatches(filter, event) && + (latest == null || event.createdAt <= latest)) + event.id: event.createdAt, + }.values.toList()..sort((a, b) => b.compareTo(a)); + if (times.length < limit) { + until.remove(i); + continue; + } + // `until` includes its second, so the next page starts at the oldest + // second this one reached, and events found twice are kept once. + final next = times[limit - 1]; + // A whole page inside one second: the next would repeat it, so the + // subscription stops here, unfinished. + if (next == latest) { + until.remove(i); + complete = false; + continue; + } + until[i] = next; + } + } + return (events: found.values.toList(), complete: complete); + } + + final fetch = await fetchMessages(); + final selected = <({NostrEvent event, PushWakeCategory category})>[]; + for (final event in fetch.events) { + if (event.pubkey.toLowerCase() == mine) continue; + final matching = [ + for (final subscription in subscriptions) + if (pushSubscriptionMatches(subscription, event)) subscription, + ]; + // Verify last, so events this wake discards cost no signature check. + if (matching.isEmpty || + event.channelId == null || + !_hasValidIdAndSignature(event)) { + continue; + } + selected.add(( + event: event, + category: matching.any((s) => s.filter.hTags != null) + ? PushWakeCategory.directMessage + : PushWakeCategory.mention, + )); + } + // Claim oldest first. Each claim can advance the store's watermark, and a + // claim below the watermark's reorder window is rejected, so claiming a + // newer message first would reject older unshown ones fetched in the same + // wake. + selected.sort( + (a, b) => a.event.createdAt != b.event.createdAt + ? a.event.createdAt.compareTo(b.event.createdAt) + : a.event.id.compareTo(b.event.id), + ); + + if (run.closed) return; + final work = () async { + // Claim first, so a message already shown costs no further requests: the + // fetch overlaps the last shown messages by the reorder window, so most + // wakes see messages they have already shown. + final claimed = run.claimed[community.id] = []; + final senders = {}; + var complete = fetch.complete; + for (final (:event, :category) in selected) { + // Stop at the deadline. Messages not yet claimed stay unclaimed, so the + // next wake gets them, and the ones already claimed are still returned. + if (run.expired(timeouts)) { + complete = false; + break; + } + final createdAt = DateTime.fromMillisecondsSinceEpoch( + event.createdAt * 1000, + isUtc: true, + ); + // A claim that fails (storage full, say) ends this community's run. + // The messages claimed before it are returned, since they are already + // recorded as shown, and the community is reported as incomplete. + try { + if (!await store.claim(community.id, event.id, createdAt)) continue; + } on Object { + complete = false; + break; + } + final body = notificationBody(event.content); + // A message with no text (only markup) has nothing to show, but it is + // recorded so it is not looked at again. + if (body.isEmpty) continue; + final channelId = event.channelId!; + senders[event.id] = event.pubkey.toLowerCase(); + claimed.add( + PushWakeNotification( + eventId: event.id, + createdAt: createdAt, + title: shortPubkey(event.pubkey), + body: body, + conversationId: '${community.id}:$channelId', + category: category, + target: PushWakeTarget( + communityId: community.id, + channelId: channelId, + eventId: event.id, + // A reply opens its direct parent's thread, as the in-app inbox + // does, and a broadcast reply is a top-level message. + threadRootId: isBroadcastReply(event.tags) + ? null + : event.threadReference.parentId, + ), + ), + ); + } + // Names are presentation, and only the messages that will show need + // them. A failed or slow lookup leaves a short key as the title instead of + // hiding a message that is already recorded as shown. + final kept = capPushWakeNotifications(claimed); + var names = {}; + var channels = {}; + final metadataBudget = timeouts.metadata < run.remaining(timeouts) + ? timeouts.metadata + : run.remaining(timeouts); + if (kept.isNotEmpty && metadataBudget > Duration.zero) { + try { + final people = {for (final n in kept) senders[n.eventId]!}.toList(); + final channelIds = {for (final n in kept) n.target.channelId}.toList(); + final metadata = await query([ + { + 'kinds': [EventKind.profile], + 'authors': people, + 'limit': people.length, + }, + { + 'kinds': [39000], + '#d': channelIds, + 'limit': channelIds.length, + }, + ], timeout: metadataBudget); + // A relay can't put words in a person's mouth: a profile must be + // signed by its author. A channel's kind 39000 is signed by the relay, + // and only its id and signature are checked here, not that the key is + // the relay's own. That check comes with the enrollment work (ticket 7 + // in PLANS/ANDROID_PUSH.md), which knows the relay key. + final verified = metadata.where(_hasValidIdAndSignature).toList(); + names = _profileNames(verified); + channels = _channelNames(verified); + } on Object { + // Keep the fallback labels. + } + } + run.notifications.addAll([ + for (final n in kept) + n.named( + title: names[senders[n.eventId]], + conversationTitle: n.category == PushWakeCategory.directMessage + ? null + : channels[n.target.channelId], + ), + ]); + run.claimed.remove(community.id); + // A wake cut short leaves the community unfinished, so it is reported as + // incomplete and the next wake looks again. + if (complete) run.done.add(community.id); + }(); + // The wake waits for this without its error, which reaches the community's + // own handler through the await below, so one community can't discard the + // others' notifications. + run.claims.add(work.then((_) {}, onError: (Object _) {})); + await work; +} + +bool _hasValidIdAndSignature(NostrEvent event) { + try { + final signed = nostr.Event.fromMap(event.toJson(), verify: false); + return signed.getEventId() == event.id && + verifySchnorrHex( + publicKey: event.pubkey, + messageHex: event.id, + signature: event.sig, + ); + } on Object { + return false; + } +} + +Map _profileNames(List events) { + final newest = {}; + for (final event in events) { + if (event.kind != EventKind.profile) continue; + final existing = newest[event.pubkey.toLowerCase()]; + if (existing == null || event.createdAt > existing.createdAt) { + newest[event.pubkey.toLowerCase()] = event; + } + } + final names = {}; + for (final MapEntry(:key, :value) in newest.entries) { + try { + final meta = jsonDecode(value.content); + if (meta is! Map) continue; + final name = (meta['display_name'] ?? meta['name'])?.toString().trim(); + if (name != null && name.isNotEmpty) { + names[key] = name.length > 100 ? name.substring(0, 100) : name; + } + } on FormatException { + continue; + } + } + return names; +} + +Map _channelNames(List events) { + final names = {}; + for (final event in events) { + if (event.kind != 39000) continue; + final id = event.getTagValue('d'); + final name = event.getTagValue('name')?.trim(); + if (id == null || name == null || name.isEmpty) continue; + final label = name.length > 100 ? name.substring(0, 100) : name; + names[id] = label.startsWith('#') ? label : '#$label'; + } + return names; +} diff --git a/mobile/lib/shared/push/push_wake_runner.dart b/mobile/lib/shared/push/push_wake_runner.dart new file mode 100644 index 0000000000..b13b37fecd --- /dev/null +++ b/mobile/lib/shared/push/push_wake_runner.dart @@ -0,0 +1,81 @@ +import 'dart:async'; + +import 'push_wake_resolver.dart'; + +/// Runs wakes one at a time in this process. A wake that arrives while one is +/// running does not start a second run: it sets a rerun flag, and the running +/// wake looks again when it finishes, so a message that arrived after its +/// fetch is still found. Every caller waiting gets one result, with the +/// notifications of every pass. +/// +/// All passes of a run share one [budget], which stays inside the native +/// watchdog, so wakes that keep arriving can't extend a run past it. A rerun +/// starts only when at least [minimumPass] of the budget is left; otherwise the +/// run returns what it has, and a message it skipped is found by the next +/// wake, which fetches from before the newest shown message. +class PushWakeRunner { + PushWakeRunner( + this._resolve, { + this.budget = const Duration(seconds: 5), + this.minimumPass = const Duration(seconds: 1), + }); + + /// Runs one pass within the time it is given. + final Future Function(Duration budget) _resolve; + + /// The longest a run may take, over all its passes. + final Duration budget; + + /// The least time worth starting a rerun with. + final Duration minimumPass; + + Future? _running; + bool _rerun = false; + + Future wake() { + final running = _running; + if (running != null) { + _rerun = true; + return running; + } + return _running = _loop().whenComplete(() => _running = null); + } + + Future _loop() async { + final elapsed = Stopwatch()..start(); + final notifications = []; + final failed = {}; + var first = true; + var interrupted = false; + do { + _rerun = false; + final PushWakeResult result; + try { + result = await _resolve(budget - elapsed.elapsed); + } on Object { + // A rerun that fails must not discard what earlier passes claimed, + // since those messages are already recorded as shown. The run is + // still incomplete: the rerun was for a message it never looked for, + // so the caller falls back to its generic notification when nothing + // else was found. + if (first) rethrow; + interrupted = true; + break; + } + first = false; + notifications.addAll(result.notifications); + // Only the last pass says what is still unread, because a community + // that failed once may have been read by the next. + failed + ..clear() + ..addAll(result.failedCommunityIds); + } while (_rerun && budget - elapsed.elapsed >= minimumPass); + return PushWakeResult( + notifications: capPushWakeNotifications(notifications), + failedCommunityIds: failed.toList()..sort(), + // A wake that arrived during the last pass and got no rerun for lack of + // budget was never looked up, so the caller must fall back for it. + interrupted: interrupted || _rerun, + ); + } +} diff --git a/mobile/lib/shared/push/shown_message_store.dart b/mobile/lib/shared/push/shown_message_store.dart new file mode 100644 index 0000000000..acc43fd3fc --- /dev/null +++ b/mobile/lib/shared/push/shown_message_store.dart @@ -0,0 +1,157 @@ +import 'dart:io'; + +import 'package:crypto/crypto.dart'; + +/// How far before the newest shown message a message may be and still be +/// shown. Wakes can be handled out of order, and the relay accepts a +/// `created_at` up to 15 minutes off, so a new message can carry an earlier +/// time than one already shown. Anything older is history. This is the same +/// window the iOS notification cache uses (`presentationReorderWindow`). +const shownMessageReorderWindow = Duration(minutes: 15); + +/// The record of messages already shown in a notification, or seen in the +/// app, so later wakes and the app don't notify for them again. +/// +/// The background wake handler and the foreground app both write it, from +/// different isolates and possibly different processes, so [claim] must be +/// atomic: of any number of concurrent claims for one message, exactly one +/// returns true. +abstract interface class ShownMessageStore { + /// The newest time among the messages recorded for [community], or null + /// when none is. Fetches start [shownMessageReorderWindow] before it. + Future newestShown(String community); + + /// Records [eventId] as shown and returns true, unless it is already + /// recorded or is older than [shownMessageReorderWindow] before the newest + /// recorded message, in which case it returns false and the caller must not + /// notify. + /// + /// Callers claim before they post, so a message is posted at most once. If + /// posting then fails, the message is not offered again, which is better + /// than repeating it. + Future claim(String community, String eventId, DateTime createdAt); +} + +/// A [ShownMessageStore] kept as two empty marker files per message. +/// +/// The claim marker's name holds only the message's own time and id, which +/// never change, so every claim for one message names the same file, and +/// creating it exclusively is atomic across isolates and processes with no +/// lock to take. The claim that creates it wins. +/// +/// The winner then writes a watermark marker: the message's time capped at the +/// present, so a future-dated message can't hold back later ones. +/// [newestShown] is the newest watermark, so it needs no shared cursor file +/// whose concurrent read-modify-write could move it backwards. If the process +/// dies between the two files, the fetch only starts earlier, and the claim +/// markers drop what was already shown. +/// +/// Markers whose message is older than the reorder window before the newest +/// watermark can never be claimed again, so they are deleted. Retention +/// follows the message's own time, not the capped watermark: a future-dated +/// message still matches the fetch window after its watermark has aged out, so +/// its claim marker must outlive that. +class DirectoryShownMessageStore implements ShownMessageStore { + DirectoryShownMessageStore(this._root, {DateTime Function()? now}) + : _now = now ?? DateTime.now; + + final Directory _root; + final DateTime Function() _now; + + Directory _directory(String community) => Directory( + '${_root.path}/${sha256.convert(community.codeUnits).toString()}', + ); + + static const _maxMarkerSeconds = 999999999999; + + static int _seconds(DateTime time) => + (time.millisecondsSinceEpoch ~/ 1000).clamp(0, _maxMarkerSeconds); + + static String _digits(int seconds) => seconds.toString().padLeft(12, '0'); + + static final _marker = RegExp(r'^([cw])-([0-9]{12})-([0-9a-f]{64})$'); + + Future> _markers( + Directory directory, + ) async { + if (!await directory.exists()) return const []; + return [ + await for (final entry in directory.list()) + if (entry is File) + if (_marker.firstMatch(entry.uri.pathSegments.last) case final match?) + ( + claim: match.group(1) == 'c', + seconds: int.parse(match.group(2)!), + file: entry, + ), + ]; + } + + static int? _newest(Iterable<({bool claim, int seconds, File file})> all) { + final watermarks = [ + for (final marker in all) + if (!marker.claim) marker.seconds, + ]; + return watermarks.isEmpty ? null : watermarks.reduce(_max); + } + + @override + Future newestShown(String community) async { + final newest = _newest(await _markers(_directory(community))); + if (newest == null) return null; + return DateTime.fromMillisecondsSinceEpoch(newest * 1000, isUtc: true); + } + + @override + Future claim( + String community, + String eventId, + DateTime createdAt, + ) async { + if (!RegExp(r'^[0-9a-f]{64}$').hasMatch(eventId)) { + throw ArgumentError.value(eventId, 'eventId', 'must be 64 hex digits'); + } + final directory = _directory(community); + await directory.create(recursive: true); + final created = _seconds(createdAt); + try { + await File( + '${directory.path}/c-${_digits(created)}-$eventId', + ).create(exclusive: true); + } on PathExistsException { + return false; + } + // The claim is won and can't be undone, so nothing after this may throw: + // a throw would leave a claim that no later wake can win, for a message + // never shown. If the bookkeeping fails, the message is shown. A missing + // watermark only makes later fetches start earlier, and a skipped prune + // runs again on the next claim. + try { + final now = _seconds(_now()); + final watermark = created < now ? created : now; + await File('${directory.path}/w-${_digits(watermark)}-$eventId').create(); + // Check the window only after the markers exist. A concurrent claim that + // advances the newest watermark may delete markers below its cutoff, and + // the newest watermark never moves backwards because it is the maximum + // of marker names and is never itself below a cutoff, so a message that + // was shown and then pruned is rejected here instead of being claimed + // again. + final all = await _markers(directory); + final cutoff = _newest(all)! - shownMessageReorderWindow.inSeconds; + for (final marker in all) { + if (marker.seconds < cutoff) { + try { + await marker.file.delete(); + } on PathNotFoundException { + // Another claim pruned it first. + } + } + } + return created >= cutoff; + } on Object { + return true; + } + } +} + +int _max(int a, int b) => a > b ? a : b; diff --git a/mobile/lib/shared/relay/relay_http_query_client.dart b/mobile/lib/shared/relay/relay_http_query_client.dart index 00bd55ee96..b42aafab29 100644 --- a/mobile/lib/shared/relay/relay_http_query_client.dart +++ b/mobile/lib/shared/relay/relay_http_query_client.dart @@ -5,6 +5,8 @@ import 'package:http/http.dart' as http; import 'package:http/io_client.dart'; import 'package:buzz/shared/http/app_http_client.dart'; +import 'relay_query_response.dart' show RelayResponseTooLarge; + /// 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 @@ -113,13 +115,15 @@ class RelayHttpQueryClient { } iterator = StreamIterator(response.stream); if ((response.contentLength ?? 0) > maxBytes) { - throw const FormatException('Relay response exceeds byte limit'); + throw const RelayResponseTooLarge('Relay response exceeds byte limit'); } final bytes = []; while (await iterator!.moveNext()) { final chunk = iterator!.current; if (bytes.length + chunk.length > maxBytes) { - throw const FormatException('Relay response exceeds byte limit'); + throw const RelayResponseTooLarge( + 'Relay response exceeds byte limit', + ); } bytes.addAll(chunk); } diff --git a/mobile/lib/shared/relay/relay_query_response.dart b/mobile/lib/shared/relay/relay_query_response.dart index 7e6aa7180d..0b61ffac17 100644 --- a/mobile/lib/shared/relay/relay_query_response.dart +++ b/mobile/lib/shared/relay/relay_query_response.dart @@ -29,12 +29,26 @@ Future> _decodeInIsolate( String? contentType, ) => Isolate.run(() => parseRelayQueryEvents(bytes, contentType)); +/// A relay response that went past the byte cap given for it, as received or +/// once inflated. +class RelayResponseTooLarge extends FormatException { + const RelayResponseTooLarge(super.message); +} + /// Parses the event array a relay `/query` or `/profiles/search` answers. /// /// Throws a [FormatException] for a body that is not JSON, is not an array, /// or holds an element that is not a well-formed event. -List parseRelayQueryEvents(Uint8List bytes, String? contentType) { - final decoded = jsonDecode(relayResponseText(bytes, contentType)); +/// +/// With [maxInflatedBytes], see [relayResponseText]. +List parseRelayQueryEvents( + Uint8List bytes, + String? contentType, { + int? maxInflatedBytes, +}) { + final decoded = jsonDecode( + relayResponseText(bytes, contentType, maxInflatedBytes: maxInflatedBytes), + ); if (decoded is! List) { throw const FormatException('relay returned malformed query response'); } @@ -101,7 +115,7 @@ class _CappedByteSink implements Sink> { @override void add(List data) { if (_output.length + data.length > _maxBytes) { - throw FormatException( + throw RelayResponseTooLarge( 'relay response exceeds $_maxBytes bytes after inflating', ); } diff --git a/mobile/lib/shared/relay/thread_reference.dart b/mobile/lib/shared/relay/thread_reference.dart index 7931887f51..7bdfbe431e 100644 --- a/mobile/lib/shared/relay/thread_reference.dart +++ b/mobile/lib/shared/relay/thread_reference.dart @@ -30,3 +30,11 @@ final _threadReferences = Expando<({String? parentId, String? rootId})>(); } final _threadEventId = RegExp(r'^[0-9a-fA-F]{64}$'); + +/// Broadcast replies surface at the channel top level — desktop's +/// `isBroadcastReply`. +bool isBroadcastReply(List> tags) { + return tags.any( + (tag) => tag.length >= 2 && tag[0] == 'broadcast' && tag[1] == '1', + ); +} diff --git a/mobile/test/helpers/push_wake_fixture.dart b/mobile/test/helpers/push_wake_fixture.dart new file mode 100644 index 0000000000..938d9f3b3e --- /dev/null +++ b/mobile/test/helpers/push_wake_fixture.dart @@ -0,0 +1,357 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/push/push_subscription.dart'; +import 'package:buzz/shared/push/push_wake_resolver.dart'; +import 'package:buzz/shared/push/shown_message_store.dart'; +import 'package:buzz/shared/relay/nostr_models.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:uuid/uuid.dart'; + +/// The present, as every part of a wake journey sees it. +final pushWakeClock = DateTime.utc(2026, 11, 15, 12); + +/// Communities on fake relays, and a wake that reads them as the headless +/// handler does. Only the network boundary is fake: the relays answer +/// `POST /query` over a [MockClient]. The resolver, its shown-message store +/// (real files in [directory]) and the eligibility rules are the real ones. +class PushWakeFixture { + PushWakeFixture(this.directory); + + final Directory directory; + final relays = []; + + late final http.Client client = MockClient( + (request) => relays + .firstWhere((relay) => relay.host == request.url.host) + .handle(request), + ); + + FakePushRelay addCommunity() { + final relay = FakePushRelay._(relays.length); + relays.add(relay); + return relay; + } + + /// A store as another isolate or process would open it: its own instance + /// over the same files. + ShownMessageStore openStore() => + DirectoryShownMessageStore(directory, now: () => pushWakeClock); + + Future wake({ + ShownMessageStore? store, + PushWakeTimeouts timeouts = const PushWakeTimeouts(), + Future> Function()? loadCommunities, + }) => resolvePushWake( + store: store ?? openStore(), + loadCommunities: + loadCommunities ?? () async => [for (final r in relays) r.community], + httpClient: client, + timeouts: timeouts, + now: () => pushWakeClock, + ); +} + +class FakeChannel { + FakeChannel(this.id, this.name, {required this.isDm}); + final String id; + final String name; + final bool isDm; +} + +class FakePerson { + FakePerson(this.name) : keys = nostr.Keys.generate(); + final String name; + final nostr.Keys keys; + String get pubkey => keys.public; +} + +class FakePushRelay { + FakePushRelay._(this.index) : me = FakePerson('Me'); + + final int index; + final FakePerson me; + final events = []; + final queries = >>[]; + final _channels = []; + final _muted = {}; + var _sequence = 0; + + /// Withholds answers until completed, as a slow relay would. + Completer? hold; + + /// Never answers. + bool silent = false; + + /// Refuses connections. + bool unreachable = false; + + /// Refuses connections once it has answered this many queries. + int? unreachableAfter; + + /// Answers every query with this body instead of the stored events, as a + /// hostile relay would. + http.Response Function()? hostileResponse; + + /// Never answers queries for profiles, as a metadata lookup slower than + /// any budget. + bool slowProfiles = false; + + String get host => 'relay-$index.example.org'; + String get communityId => 'community-$index'; + + Community get community => Community( + id: communityId, + name: 'Community $index', + relayUrl: 'https://$host', + pubkey: me.pubkey, + nsec: me.keys.nsec, + pushSubscriptionState: BuzzPushLeaseSubscriptionState.desired( + desired: buildDesiredBuzzPushSubscriptions( + myPubkey: me.pubkey, + channelIds: [ + for (final channel in _channels) + if (channel.isDm) channel.id, + ], + mutedChannelIds: _muted, + ), + ), + addedAt: pushWakeClock, + ); + + FakeChannel dmChannel() => _addChannel(isDm: true); + FakeChannel channel({bool forged = false}) => + _addChannel(isDm: false, forged: forged); + + FakeChannel _addChannel({required bool isDm, bool forged = false}) { + final id = const Uuid().v4(); + final channel = FakeChannel(id, 'room-${id.substring(0, 4)}', isDm: isDm); + _channels.add(channel); + final metadata = _sign( + kind: 39000, + tags: [ + ['d', id], + ['name', channel.name], + ], + content: '', + author: nostr.Keys.generate(), + ); + events.add(forged ? _forge(metadata) : metadata); + return channel; + } + + void mute(FakeChannel channel) => _muted.add(channel.id); + + /// A person with a profile. A [forged] profile carries a signature that + /// isn't its author's, as an untrusted relay could serve. + FakePerson person(String name, {bool forged = false}) { + final person = FakePerson(name); + final profile = _sign( + kind: 0, + tags: const [], + content: jsonEncode({'display_name': name}), + author: person.keys, + ); + events.add(forged ? _forge(profile) : profile); + return person; + } + + NostrEvent _forge(NostrEvent event) => NostrEvent.fromJson({ + ...event.toJson(), + 'sig': nostr.Event.from( + kind: 1, + tags: const [], + content: 'someone else', + secretKey: nostr.Keys.generate().secret, + verify: false, + ).sig, + }); + + /// Stores a message that arrived `age` before now (default: each message a + /// second after the previous one, ending a few minutes ago). + NostrEvent message( + FakeChannel channel, + FakePerson author, + String content, { + FakePerson? mention, + List extraMentions = const [], + List> extraTags = const [], + Duration? age, + DateTime? at, + }) { + final createdAt = + at ?? + pushWakeClock + .subtract(age ?? const Duration(minutes: 5)) + .add(Duration(seconds: _sequence++)); + final event = _sign( + kind: EventKind.streamMessage, + tags: [ + ['h', channel.id], + if (mention != null) ['p', mention.pubkey], + for (final pubkey in extraMentions) ['p', pubkey], + ...extraTags, + ], + content: content, + author: author.keys, + createdAt: createdAt.millisecondsSinceEpoch ~/ 1000, + ); + events.add(event); + return event; + } + + NostrEvent _sign({ + required int kind, + required List> tags, + required String content, + required nostr.Keys author, + int? createdAt, + }) => NostrEvent.fromJson( + nostr.Event.from( + kind: kind, + tags: tags, + content: content, + createdAt: createdAt, + secretKey: author.secret, + verify: false, + ).toMap(), + ); + + Future handle(http.Request request) async { + if (unreachable || queries.length >= (unreachableAfter ?? 1 << 30)) { + throw const SocketException('connection refused'); + } + if (request.method != 'POST' || + request.url.path != '/query' || + request.headers['Authorization'] == null) { + return http.Response('unanswerable', 501); + } + final filters = (jsonDecode(request.body) as List) + .cast>(); + queries.add(filters); + if (silent) await Completer().future; + await hold?.future; + final hostile = hostileResponse; + if (hostile != null) return hostile(); + if (slowProfiles && + filters.any((f) => (f['kinds'] as List?)?.contains(0) ?? false)) { + await Completer().future; + } + final result = {}; + for (final filter in filters) { + final matches = events.where((e) => _matches(filter, e)).toList() + ..sort( + (a, b) => a.createdAt != b.createdAt + ? b.createdAt.compareTo(a.createdAt) + : a.id.compareTo(b.id), + ); + for (final event in matches.take(filter['limit'] as int)) { + result[event.id] = event; + } + } + return http.Response( + jsonEncode([for (final e in result.values) e.toJson()]), + 200, + headers: {'content-type': 'application/json'}, + ); + } + + bool _matches(Map filter, NostrEvent event) { + bool allows(String key, Object value) => + (filter[key] as List?)?.contains(value) ?? true; + if (!allows('authors', event.pubkey) || !allows('kinds', event.kind)) { + return false; + } + final since = filter['since'] as int?; + if (since != null && event.createdAt < since) return false; + final until = filter['until'] as int?; + if (until != null && event.createdAt > until) return false; + for (final MapEntry(:key, :value) in filter.entries) { + if (!key.startsWith('#')) continue; + final wanted = (value as List).cast(); + if (!event.tags.any( + (tag) => + tag.length > 1 && + tag[0] == key.substring(1) && + wanted.contains(tag[1]), + )) { + return false; + } + } + return true; + } +} + +/// A store whose claims take [delay], as slow storage would, and whose +/// [newestShown] waits for [newestGate]. +class SlowShownMessageStore implements ShownMessageStore { + SlowShownMessageStore(this._inner, this.delay, {this.newestGate}); + + final ShownMessageStore _inner; + final Duration delay; + final Future? newestGate; + + @override + Future newestShown(String community) async { + await newestGate; + return _inner.newestShown(community); + } + + @override + Future claim( + String community, + String eventId, + DateTime createdAt, + ) async { + await Future.delayed(delay); + return _inner.claim(community, eventId, createdAt); + } +} + +/// A store whose claims for [community] fail after [succeed] of them, as when +/// storage fills midway through a wake. +class FailingShownMessageStore implements ShownMessageStore { + FailingShownMessageStore(this._inner, this.community, {this.succeed = 0}); + + final ShownMessageStore _inner; + final String community; + int succeed; + + @override + Future newestShown(String community) => + _inner.newestShown(community); + + @override + Future claim(String community, String eventId, DateTime createdAt) { + if (community == this.community && succeed-- <= 0) { + throw const FileSystemException('No space left on device'); + } + return _inner.claim(community, eventId, createdAt); + } +} + +/// A store whose claims for [community] never answer after [succeed] of them, +/// as storage that hangs midway through a wake. +class StalledShownMessageStore implements ShownMessageStore { + StalledShownMessageStore(this._inner, this.community, {this.succeed = 0}); + + final ShownMessageStore _inner; + final String community; + int succeed; + + @override + Future newestShown(String community) => + _inner.newestShown(community); + + @override + Future claim(String community, String eventId, DateTime createdAt) { + if (community == this.community && succeed-- <= 0) { + return Completer().future; + } + return _inner.claim(community, eventId, createdAt); + } +} diff --git a/mobile/test/shared/push/push_wake_journey_test.dart b/mobile/test/shared/push/push_wake_journey_test.dart new file mode 100644 index 0000000000..2e94494a0e --- /dev/null +++ b/mobile/test/shared/push/push_wake_journey_test.dart @@ -0,0 +1,898 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/push/push_wake_resolver.dart'; + +import 'package:buzz/shared/push/push_wake_runner.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:buzz/shared/relay/nostr_models.dart'; +import 'package:buzz/shared/utils/string_utils.dart'; +import 'package:nostr/nostr.dart' as nostr; + +import '../../helpers/push_wake_fixture.dart'; + +void main() { + late Directory directory; + late PushWakeFixture fixture; + + setUp(() { + directory = Directory.systemTemp.createTempSync('push-wake-'); + fixture = PushWakeFixture(directory); + }); + tearDown(() => directory.deleteSync(recursive: true)); + + // The message fetches a relay saw, without the name lookups after them. + Iterable>> messageQueries(FakePushRelay relay) => + relay.queries.where((query) => query.first.containsKey('since')); + + // Records a message as shown [age] ago, as an earlier wake would have. + Future shownAgo(FakePushRelay relay, Duration age) async { + expect( + await fixture.openStore().claim( + relay.communityId, + age.inSeconds.toRadixString(16).padLeft(64, '0'), + pushWakeClock.subtract(age), + ), + isTrue, + ); + } + + test('a DM and a mention notify, and nothing else does', () async { + final relay = fixture.addCommunity(); + final dm = relay.dmChannel(); + final muted = relay.dmChannel(); + final room = relay.channel(); + final friend = relay.person('Friend'); + final bystander = relay.person('Bystander'); + relay.mute(muted); + + final direct = relay.message(dm, friend, 'hello **there**'); + final mention = relay.message( + room, + friend, + 'look at this', + mention: relay.me, + ); + // Not notifying: my own message from another device, a muted DM, a + // hellthread tagging more people than the limit, chatter that doesn't + // mention me, and a message with no text. + relay.message(dm, relay.me, 'sent from my laptop'); + relay.message(muted, friend, 'muted'); + relay.message( + room, + friend, + 'everyone!', + mention: relay.me, + extraMentions: List.generate(20, (_) => nostr.Keys.generate().public), + ); + relay.message(room, bystander, 'unrelated'); + relay.message(dm, friend, '`` ``'); + + final result = await fixture.wake(); + + expect(result.incomplete, isFalse); + expect(result.notifications.map((n) => n.eventId), [mention.id, direct.id]); + + // Messages are read from the writer, so one that just arrived is not + // missed to a lagging replica. Names can come from any replica. + for (final filter in relay.queries.expand((query) => query)) { + expect( + filter['consistency'], + filter.containsKey('since') ? 'strong' : isNull, + reason: '$filter', + ); + } + final [first, second] = result.notifications; + expect(first.category, PushWakeCategory.mention); + expect(first.title, 'Friend'); + expect(first.body, 'look at this'); + expect(first.conversationTitle, '#${room.name}'); + expect(first.target.channelId, room.id); + expect(first.target.eventId, mention.id); + expect(second.category, PushWakeCategory.directMessage); + expect(second.body, 'hello there'); + expect(second.conversationTitle, isNull); + expect(second.conversationId, isNot(first.conversationId)); + + // Tapping a reply opens the thread of the message it answers, as in the + // inbox: a reply to a reply opens its direct parent's thread, and a + // broadcast reply is a top-level message with no thread. + List> replyTo(NostrEvent root, [NostrEvent? parent]) => [ + ['e', root.id, '', 'root'], + ['e', (parent ?? root).id, '', 'reply'], + ]; + final start = relay.message(dm, friend, 'thread start'); + final reply = relay.message( + dm, + friend, + 'first reply', + extraTags: replyTo(start), + ); + final nested = relay.message( + dm, + friend, + 'reply to the reply', + extraTags: replyTo(start, reply), + ); + final broadcast = relay.message( + dm, + friend, + 'also for the channel', + extraTags: [ + ...replyTo(start, reply), + ['broadcast', '1'], + ], + ); + expect( + { + for (final n in (await fixture.wake()).notifications) + n.eventId: n.target.threadRootId, + }, + { + start.id: null, + reply.id: start.id, + nested.id: reply.id, + broadcast.id: null, + }, + ); + + // Names come from signed events only. A profile or channel name that + // fails verification leaves the short key and no channel name, and the + // message still shows. + final stranger = relay.person('Impostor', forged: true); + final lookalike = relay.channel(forged: true); + final forged = relay.message( + lookalike, + stranger, + 'trust me', + mention: relay.me, + ); + final unnamed = (await fixture.wake()).notifications.single; + expect(unnamed.eventId, forged.id); + expect(unnamed.title, shortPubkey(stranger.pubkey)); + expect(unnamed.conversationTitle, isNull); + }); + + test('shown messages stay shown, and a missed wake is recovered', () async { + final relay = fixture.addCommunity(); + final first = relay.dmChannel(); + final second = relay.dmChannel(); + final friend = relay.person('Friend'); + // History from before this install knew about the community. + relay.message(first, friend, 'ancient', age: const Duration(hours: 2)); + final arrived = relay.message(first, friend, 'one'); + + expect((await fixture.wake()).notifications.map((n) => n.eventId), [ + arrived.id, + ]); + expect((await fixture.wake()).notifications, isEmpty); + + // Several messages arrive across two conversations while no wake does. + final b = relay.message(second, friend, 'two'); + final c = relay.message(first, friend, 'three'); + final d = relay.message(second, friend, 'four'); + final recovered = await fixture.wake(); + expect(recovered.notifications.map((n) => n.eventId), [d.id, c.id, b.id]); + expect( + recovered.notifications.map((n) => n.conversationId).toSet(), + hasLength(2), + ); + expect((await fixture.wake()).notifications, isEmpty); + + // Later wakes fetch from the last shown message, not from the start. + final since = relay.queries.last.first['since'] as int; + expect( + since, + greaterThan( + pushWakeClock + .subtract(const Duration(hours: 1)) + .millisecondsSinceEpoch ~/ + 1000, + ), + ); + + // A message stamped earlier than one already shown (clock skew or + // delivery order) still notifies, once. + final older = relay.message( + first, + friend, + 'five', + age: const Duration(minutes: 10), + ); + expect(older.createdAt, lessThan(d.createdAt)); + expect((await fixture.wake()).notifications.map((n) => n.eventId), [ + older.id, + ]); + expect((await fixture.wake()).notifications, isEmpty); + + // After a long quiet spell, every message since the last shown one + // notifies, however far apart they arrived. + final quiet = fixture.addCommunity(); + await shownAgo(quiet, const Duration(hours: 2)); + final quietDm = quiet.dmChannel(); + final quietFriend = quiet.person('Friend'); + final earlier = quiet.message( + quietDm, + quietFriend, + 'while you were away', + age: const Duration(minutes: 50), + ); + final latest = quiet.message(quietDm, quietFriend, 'and now'); + final caughtUp = await fixture.wake(); + expect(caughtUp.incomplete, isFalse); + expect( + caughtUp.notifications + .where((n) => n.target.communityId == quiet.communityId) + .map((n) => n.eventId), + [latest.id, earlier.id], + ); + + // Messages that can't notify can fill a page of the fetch, and an + // eligible one behind them must still show: here a DM behind messages + // already shown, and a mention behind mentions in a muted channel. + final crowded = fixture.addCommunity(); + final crowdedDm = crowded.dmChannel(); + final mutedDm = crowded.dmChannel(); + final crowdedRoom = crowded.channel(); + crowded.mute(mutedDm); + final chatty = crowded.person('Chatty'); + const buriedAge = Duration(minutes: 12); + final buriedDm = crowded.message( + crowdedDm, + chatty, + 'buried', + age: buriedAge, + ); + final buriedMention = crowded.message( + crowdedRoom, + chatty, + 'buried mention', + mention: crowded.me, + age: buriedAge, + ); + for (var i = 0; i < pushWakeMessagePageSize + 5; i++) { + final seen = crowded.message(crowdedDm, chatty, 'seen $i'); + expect( + await fixture.openStore().claim( + crowded.communityId, + seen.id, + DateTime.fromMillisecondsSinceEpoch( + seen.createdAt * 1000, + isUtc: true, + ), + ), + isTrue, + ); + crowded.message(mutedDm, chatty, 'muted $i', mention: crowded.me); + } + final dug = await fixture.wake(); + expect(dug.incomplete, isFalse); + expect( + dug.notifications + .where((n) => n.target.communityId == crowded.communityId) + .map((n) => n.eventId), + unorderedEquals([buriedDm.id, buriedMention.id]), + ); + expect(crowded.queries.first.every((f) => f['until'] == null), isTrue); + expect(crowded.queries[1].every((f) => f['until'] != null), isTrue); + expect((await fixture.wake()).notifications, isEmpty); + + // Subscriptions overlap: a DM that mentions me answers the DM filter and + // also matches the mention filter. Being older than the room's mentions, + // it must not move the mention filter's next page past them. + final overlap = fixture.addCommunity(); + final palDm = overlap.dmChannel(); + final noisyDm = overlap.dmChannel(); + final room = overlap.channel(); + overlap.mute(noisyDm); + final pal = overlap.person('Pal'); + final expected = [ + overlap + .message( + palDm, + pal, + 'dm mention', + mention: overlap.me, + age: const Duration(minutes: 13), + ) + .id, + for (final minutes in [12, 11, 10]) + overlap + .message( + room, + pal, + 'mention $minutes', + mention: overlap.me, + age: Duration(minutes: minutes), + ) + .id, + ]; + for (var i = 0; i < pushWakeMessagePageSize + 5; i++) { + overlap.message(noisyDm, pal, 'muted $i', mention: overlap.me); + } + final untangled = await fixture.wake(); + expect(untangled.incomplete, isFalse); + expect( + untangled.notifications + .where((n) => n.target.communityId == overlap.communityId) + .map((n) => n.eventId), + unorderedEquals(expected), + ); + }); + + test('every community notifies, each from its own relay', () async { + final relays = [fixture.addCommunity(), fixture.addCommunity()]; + final events = []; + for (final relay in relays) { + final dm = relay.dmChannel(); + events.add(relay.message(dm, relay.person('Friend'), 'hi').id); + } + + final result = await fixture.wake(); + + expect(result.notifications.map((n) => n.eventId).toSet(), events.toSet()); + expect( + result.notifications.map((n) => n.target.communityId).toSet(), + relays.map((r) => r.communityId).toSet(), + ); + + // Storage fails midway through one community. The other community's + // message and the one claimed before the failure still show, and the + // failing community is reported so the next wake finishes it, even + // when the message left over arrived long after the one claimed. + final [healthy, _] = relays; + // A community whose last shown message is old, so the one left over is + // also far from the one claimed. + final failing = fixture.addCommunity(); + final newer = healthy.message( + healthy.dmChannel(), + healthy.person('A'), + 'a', + ); + await shownAgo(failing, const Duration(hours: 2)); + final failingDm = failing.dmChannel(); + final friend = failing.person('B'); + final claimed = failing.message( + failingDm, + friend, + 'older', + age: const Duration(minutes: 40), + ); + final skipped = failing.message(failingDm, friend, 'newer'); + final partial = await fixture.wake( + store: FailingShownMessageStore( + fixture.openStore(), + failing.communityId, + succeed: 1, + ), + ); + expect(partial.notifications.map((n) => n.eventId).toSet(), { + newer.id, + claimed.id, + }); + expect(partial.failedCommunityIds, [failing.communityId]); + expect((await fixture.wake()).notifications.map((n) => n.eventId), [ + skipped.id, + ]); + }); + + test( + 'a burst is bounded per conversation and overall, and not repeated', + () async { + final relay = fixture.addCommunity(); + final friend = relay.person('Friend'); + final channels = List.generate(4, (_) => relay.dmChannel()); + for (final channel in channels) { + for (var i = 0; i < 12; i++) { + relay.message(channel, friend, 'message $i'); + } + } + + final result = await fixture.wake(); + + expect(result.notifications, hasLength(pushWakeMaxNotifications)); + final counts = {}; + for (final n in result.notifications) { + counts.update(n.conversationId, (c) => c + 1, ifAbsent: () => 1); + } + expect( + counts.values.every((c) => c <= pushWakeMaxPerConversation), + isTrue, + ); + // The messages left out are recorded as shown, so they don't resurface. + expect((await fixture.wake()).notifications, isEmpty); + }, + ); + + group('slow and unreachable relays', () { + const timeouts = PushWakeTimeouts( + request: Duration(milliseconds: 150), + metadata: Duration(milliseconds: 100), + total: Duration(milliseconds: 600), + ); + + test('return what they have inside the budget, and recover', () async { + final slow = fixture.addCommunity(); + final healthy = fixture.addCommunity(); + final dead = fixture.addCommunity(); + final slowMessage = slow.message( + slow.dmChannel(), + slow.person('Friend'), + 'slow', + ); + final healthyMessage = healthy.message( + healthy.dmChannel(), + healthy.person('Friend'), + 'fast', + ); + slow.silent = true; + dead.unreachable = true; + + final watch = Stopwatch()..start(); + final result = await fixture.wake(timeouts: timeouts); + + expect(watch.elapsed, lessThan(const Duration(seconds: 2))); + expect(result.notifications.map((n) => n.eventId), [healthyMessage.id]); + expect(result.incomplete, isTrue); + expect( + result.failedCommunityIds, + [dead.communityId, slow.communityId]..sort(), + ); + + // Nothing was recorded for the communities that failed, so the next + // wake finds their messages once they answer. + slow.silent = false; + dead.unreachable = false; + final next = await fixture.wake(timeouts: timeouts); + expect(next.incomplete, isFalse); + expect(next.notifications.map((n) => n.eventId), [slowMessage.id]); + + // A relay that answers with more than a wake will buffer, inflate or + // verify costs only its own community, and its messages are still + // there once it behaves. + final hostile = fixture.addCommunity(); + final hostileMessage = hostile.message( + hostile.dmChannel(), + hostile.person('Friend'), + 'hostile', + ); + final signed = jsonEncode(hostileMessage.toJson()); + final hostileAnswers = { + // Tiny on the wire, huge once inflated. + 'a gzip bomb': () => http.Response.bytes( + gzip.encode(utf8.encode('[${' ' * (pushWakeMaxResponseBytes + 1)}]')), + 200, + headers: {'content-type': 'application/json'}, + ), + 'an oversized body': () => http.Response( + '[${' ' * (pushWakeMaxResponseBytes + 1)}]', + 200, + headers: {'content-type': 'application/json'}, + ), + 'more events than asked for': () => http.Response( + '[${List.filled(1000, signed).join(',')}]', + 200, + headers: {'content-type': 'application/json'}, + ), + }; + for (final MapEntry(:key, :value) in hostileAnswers.entries) { + hostile.hostileResponse = value; + final attempt = await fixture.wake(timeouts: timeouts); + expect(attempt.failedCommunityIds, [hostile.communityId], reason: key); + expect(attempt.notifications, isEmpty, reason: key); + } + hostile.hostileResponse = null; + final recovered = await fixture.wake(timeouts: timeouts); + expect(recovered.notifications.map((n) => n.eventId), [ + hostileMessage.id, + ]); + + // A page too big to take is asked for again with half the events, and + // the fetch carries on at that size. + final heavy = fixture.addCommunity(); + final heavyDm = heavy.dmChannel(); + heavy.mute(heavyDm); + final bulky = heavy.person('Friend'); + final small = heavy.message( + heavy.channel(), + bulky, + 'small', + mention: heavy.me, + age: const Duration(minutes: 12), + ); + final bulk = 'x' * 90000; + for (var i = 0; i < 60; i++) { + heavy.message(heavyDm, bulky, bulk, mention: heavy.me); + } + final halved = await fixture.wake(); + expect(halved.incomplete, isFalse); + expect(halved.notifications.map((n) => n.eventId), [small.id]); + expect( + [for (final query in messageQueries(heavy)) query.first['limit']], + [pushWakeMessagePageSize, 25, 25, 25], + ); + + // A relay with more history than the page cap allows still shows the + // newest messages, and leaves its community unfinished. + final endless = fixture.addCommunity(); + final endlessDm = endless.dmChannel(); + endless.mute(endlessDm); + final noisy = endless.person('Friend'); + for ( + var i = 0; + i < pushWakeMessagePageSize * pushWakeMaxMessagePages; + i++ + ) { + endless.message(endlessDm, noisy, 'noise $i', mention: endless.me); + } + final newest = endless.message( + endless.channel(), + noisy, + 'newest', + mention: endless.me, + ); + final capped = await fixture.wake(); + expect(capped.failedCommunityIds, [endless.communityId]); + expect( + capped.notifications + .where((n) => n.target.communityId == endless.communityId) + .map((n) => n.eventId), + [newest.id], + ); + expect(messageQueries(endless), hasLength(pushWakeMaxMessagePages)); + + // A later page failing leaves the community unfinished too, and the + // next wake reads on from what was shown. + final flaky = fixture.addCommunity(); + final flakyDm = flaky.dmChannel(); + flaky.mute(flakyDm); + final flakyFriend = flaky.person('Friend'); + final older = flaky.message( + flaky.channel(), + flakyFriend, + 'older', + mention: flaky.me, + age: const Duration(minutes: 12), + ); + for (var i = 0; i < pushWakeMessagePageSize + 5; i++) { + flaky.message(flakyDm, flakyFriend, 'noise $i', mention: flaky.me); + } + final latest = flaky.message( + flaky.channel(), + flakyFriend, + 'latest', + mention: flaky.me, + ); + flaky.unreachableAfter = 1; + final cut = await fixture.wake(); + expect(cut.failedCommunityIds, contains(flaky.communityId)); + expect( + cut.notifications + .where((n) => n.target.communityId == flaky.communityId) + .map((n) => n.eventId), + [latest.id], + ); + flaky.unreachableAfter = null; + final resumed = await fixture.wake(); + expect( + resumed.notifications + .where((n) => n.target.communityId == flaky.communityId) + .map((n) => n.eventId), + [older.id], + ); + + // A full page inside one second can't be paged by time: the next + // request would answer the same page. The fetch stops there, leaving + // the community unfinished, rather than spending its pages on repeats. + final stuck = fixture.addCommunity(); + final stuckDm = stuck.dmChannel(); + stuck.mute(stuckDm); + final stuckFriend = stuck.person('Friend'); + stuck.message( + stuck.channel(), + stuckFriend, + 'behind', + mention: stuck.me, + age: const Duration(minutes: 12), + ); + final second = pushWakeClock.subtract(const Duration(minutes: 1)); + for (var i = 0; i < pushWakeMessagePageSize + 5; i++) { + stuck.message( + stuckDm, + stuckFriend, + 'same second $i', + mention: stuck.me, + at: second, + ); + } + final repeated = await fixture.wake(); + expect(repeated.failedCommunityIds, contains(stuck.communityId)); + expect(messageQueries(stuck), hasLength(2)); + }); + + test('with nothing found say so, so the caller can fall back', () async { + final relay = fixture.addCommunity()..unreachable = true; + relay.message(relay.dmChannel(), relay.person('Friend'), 'hi'); + + final result = await fixture.wake(timeouts: timeouts); + + expect(result.notifications, isEmpty); + expect(result.incomplete, isTrue); + + // The budget starts with the wake, so a community list that never + // loads can't hold it past that either. + final unloaded = await fixture + .wake( + timeouts: timeouts, + loadCommunities: () => Completer>().future, + ) + .timeout(const Duration(seconds: 2)); + expect(unloaded.notifications, isEmpty); + expect(unloaded.interrupted, isTrue); + }); + + test('the whole wake stops at its total budget, claims included', () async { + final relay = fixture.addCommunity()..silent = true; + final first = relay + .message(relay.dmChannel(), relay.person('Friend'), 'hi') + .id; + const patient = PushWakeTimeouts( + request: Duration(seconds: 30), + total: Duration(milliseconds: 300), + ); + + final watch = Stopwatch()..start(); + final result = await fixture.wake(timeouts: patient); + + expect(watch.elapsed, lessThan(const Duration(seconds: 2))); + expect(result.failedCommunityIds, [relay.communityId]); + + // Slow storage and a slow name lookup spend the budget too. Messages + // not yet claimed stay unclaimed for the next wake, and those already + // claimed are returned, not lost. + relay.silent = false; + final friend = relay.person('Friend'); + final sent = [ + first, + for (var i = 0; i < 3; i++) + for (final channel in [relay.dmChannel()]) + for (var j = 0; j < 6; j++) + relay.message(channel, friend, 'message $i $j').id, + ]; + const tight = PushWakeTimeouts( + request: Duration(seconds: 30), + metadata: Duration(seconds: 30), + total: Duration(milliseconds: 700), + ); + final slowStore = SlowShownMessageStore( + fixture.openStore(), + const Duration(milliseconds: 100), + ); + final stopped = Stopwatch()..start(); + final partial = await fixture.wake(store: slowStore, timeouts: tight); + expect(stopped.elapsed, lessThan(const Duration(seconds: 2))); + expect(partial.incomplete, isTrue); + expect(partial.notifications, isNotEmpty); + expect(partial.notifications.length, lessThan(sent.length)); + final rest = await fixture.wake(); + expect(rest.incomplete, isFalse); + expect( + [...partial.notifications, ...rest.notifications].map((n) => n.eventId), + unorderedEquals(sent), + ); + + relay.slowProfiles = true; + final late = relay.message(relay.dmChannel(), friend, 'late names'); + final lookup = Stopwatch()..start(); + final unnamed = await fixture.wake(timeouts: tight); + expect(lookup.elapsed, lessThan(const Duration(seconds: 2))); + expect(unnamed.notifications.map((n) => n.eventId), [late.id]); + + // Storage that never answers for one community holds back neither the + // others nor what it claimed before it stalled, and the community is + // left for the next wake. + final healthy = fixture.addCommunity(); + final stalled = fixture.addCommunity(); + final healthyFriend = healthy.person('Friend'); + final stalledFriend = stalled.person('Friend'); + final healthyDm = healthy.dmChannel(); + final stalledDm = stalled.dmChannel(); + final fine = healthy.message(healthyDm, healthyFriend, 'fine'); + final claimedFirst = stalled.message(stalledDm, stalledFriend, 'first'); + stalled.message(stalledDm, stalledFriend, 'second'); + final hung = Stopwatch()..start(); + final cutShort = await fixture + .wake( + store: StalledShownMessageStore( + fixture.openStore(), + stalled.communityId, + succeed: 1, + ), + timeouts: tight, + ) + .timeout(const Duration(seconds: 3)); + expect(hung.elapsed, lessThan(const Duration(seconds: 2))); + expect(cutShort.failedCommunityIds, [stalled.communityId]); + expect(cutShort.notifications.map((n) => n.eventId).toSet(), { + fine.id, + claimedFirst.id, + }); + + // Once the budget is spent, nothing more is sent to a relay. + final gate = Completer(); + int queried() => fixture.relays.fold(0, (n, r) => n + r.queries.length); + final before = queried(); + final gated = await fixture.wake( + store: SlowShownMessageStore( + fixture.openStore(), + Duration.zero, + newestGate: gate.future, + ), + timeouts: const PushWakeTimeouts(total: Duration(milliseconds: 300)), + ); + expect(gated.notifications, isEmpty); + gate.complete(); + await Future.delayed(const Duration(milliseconds: 100)); + expect(queried(), before); + }); + }); + + group('overlapping writers', () { + Future untilQueries(FakePushRelay relay, int count) async { + while (relay.queries.length < count) { + await Future.delayed(Duration.zero); + } + } + + test('two wakes in different isolates never notify twice', () async { + final relay = fixture.addCommunity(); + final dm = relay.dmChannel(); + final friend = relay.person('Friend'); + final sent = [ + for (var i = 0; i < 5; i++) relay.message(dm, friend, 'message $i').id, + ]; + final release = relay.hold = Completer(); + + // Each opens its own store over the same files. + final wakes = [ + fixture.wake(store: fixture.openStore()), + fixture.wake(store: fixture.openStore()), + ]; + await untilQueries(relay, 2); + release.complete(); + final results = await Future.wait(wakes); + + final shown = [ + for (final result in results) + ...result.notifications.map((n) => n.eventId), + ]; + expect(shown, unorderedEquals(sent)); + }); + + test('the app marking a message seen during a run is respected', () async { + final relay = fixture.addCommunity(); + final dm = relay.dmChannel(); + final friend = relay.person('Friend'); + final seen = relay.message(dm, friend, 'already on screen'); + final unseen = relay.message(dm, friend, 'not yet'); + final release = relay.hold = Completer(); + + final wake = fixture.wake(); + await untilQueries(relay, 1); + // The foreground app shows the message and records it. + expect( + await fixture.openStore().claim( + relay.communityId, + seen.id, + DateTime.fromMillisecondsSinceEpoch( + seen.createdAt * 1000, + isUtc: true, + ), + ), + isTrue, + ); + release.complete(); + + expect((await wake).notifications.map((n) => n.eventId), [unseen.id]); + }); + + test('a wake mid-run reruns once, and loses and repeats nothing', () async { + final relay = fixture.addCommunity(); + final dm = relay.dmChannel(); + final friend = relay.person('Friend'); + final before = relay.message(dm, friend, 'before the fetch'); + final release = relay.hold = Completer(); + var passes = 0; + final runner = PushWakeRunner((budget) { + passes++; + return fixture.wake(timeouts: PushWakeTimeouts(total: budget)); + }); + + final first = runner.wake(); + await untilQueries(relay, 1); + // A message arrives after the fetch started, and its wake finds a run + // already going. + final after = relay.message(dm, friend, 'after the fetch'); + final second = runner.wake(); + final third = runner.wake(); + release.complete(); + relay.hold = null; + + final results = await Future.wait([first, second, third]); + + expect(passes, 2); + for (final result in results) { + expect(result.notifications.map((n) => n.eventId), [ + after.id, + before.id, + ]); + } + + // All passes share one budget: when the first pass leaves too little + // of it, a wake mid-run does not start another pass. The run returns + // what it found, and is incomplete, since the later wake's message was + // never looked for and the caller must fall back for it. + final short = PushWakeRunner( + (budget) { + passes++; + return fixture.wake(timeouts: PushWakeTimeouts(total: budget)); + }, + budget: const Duration(seconds: 5), + minimumPass: const Duration(seconds: 10), + ); + final late = relay.message(dm, friend, 'during a slow pass'); + final slow = relay.hold = Completer(); + final queries = relay.queries.length; + final fourth = short.wake(); + await untilQueries(relay, queries + 1); + final fifth = short.wake(); + slow.complete(); + relay.hold = null; + + for (final result in await Future.wait([fourth, fifth])) { + expect(result.notifications.map((n) => n.eventId), [late.id]); + expect(result.incomplete, isTrue); + } + expect(passes, 3); + + // A rerun that fails keeps what the first pass already claimed, and + // reports the run incomplete, so an empty first pass still ends in the + // generic notification. + var failingPasses = 0; + final failing = PushWakeRunner((budget) { + if (++failingPasses > 1) throw StateError('storage unreadable'); + return fixture.wake(timeouts: PushWakeTimeouts(total: budget)); + }); + final kept = relay.message(dm, friend, 'before a failed rerun'); + final held = relay.hold = Completer(); + final queriesBefore = relay.queries.length; + final sixth = failing.wake(); + await untilQueries(relay, queriesBefore + 1); + final seventh = failing.wake(); + held.complete(); + relay.hold = null; + for (final result in await Future.wait([sixth, seventh])) { + expect(result.notifications.map((n) => n.eventId), [kept.id]); + expect(result.incomplete, isTrue); + } + expect(failingPasses, 2); + + failingPasses = 0; + final emptyHeld = relay.hold = Completer(); + final emptyBefore = relay.queries.length; + final eighth = failing.wake(); + await untilQueries(relay, emptyBefore + 1); + final ninth = failing.wake(); + emptyHeld.complete(); + relay.hold = null; + for (final result in await Future.wait([eighth, ninth])) { + expect(result.notifications, isEmpty); + expect(result.incomplete, isTrue); + } + expect(failingPasses, 2); + }); + }); +} diff --git a/mobile/test/shared/push/shown_message_store_test.dart b/mobile/test/shared/push/shown_message_store_test.dart new file mode 100644 index 0000000000..742ed45f39 --- /dev/null +++ b/mobile/test/shared/push/shown_message_store_test.dart @@ -0,0 +1,106 @@ +import 'dart:io'; + +import 'package:buzz/shared/push/shown_message_store.dart'; +import 'package:crypto/crypto.dart'; +import 'package:flutter_test/flutter_test.dart'; + +String _id(int n) => n.toRadixString(16).padLeft(64, '0'); + +void main() { + late Directory directory; + final now = DateTime.utc(2026, 11, 15, 12); + ShownMessageStore open() => + DirectoryShownMessageStore(directory, now: () => now); + + setUp(() => directory = Directory.systemTemp.createTempSync('shown-')); + tearDown(() => directory.deleteSync(recursive: true)); + + test('of concurrent claims for one message exactly one wins', () async { + final at = now.subtract(const Duration(minutes: 1)); + final results = await Future.wait([ + for (var i = 0; i < 20; i++) open().claim('community', _id(1), at), + ]); + expect(results.where((won) => won), hasLength(1)); + }); + + test('claims for a future-dated message from clocks a second apart race ' + 'to one winner', () async { + final future = now.add(const Duration(hours: 1)); + final results = await Future.wait([ + for (var i = 0; i < 20; i++) + DirectoryShownMessageStore( + directory, + now: () => now.add(Duration(seconds: i)), + ).claim('community', _id(1), future), + ]); + expect(results.where((won) => won), hasLength(1)); + }); + + test('a won claim whose bookkeeping fails is still shown, once', () async { + // A directory where the watermark file belongs makes writing it fail, as + // a full disk would, after the claim itself is won. + final at = now.subtract(const Duration(minutes: 1)); + final seconds = (at.millisecondsSinceEpoch ~/ 1000).toString(); + final community = sha256.convert('community'.codeUnits).toString(); + Directory( + '${directory.path}/$community/w-${seconds.padLeft(12, '0')}-${_id(1)}', + ).createSync(recursive: true); + + expect(await open().claim('community', _id(1), at), isTrue); + expect(await open().claim('community', _id(1), at), isFalse); + }); + + test('history is rejected, reordering and future dates are not', () async { + final store = open(); + Future claim(int n, Duration age) => + store.claim('community', _id(n), now.subtract(age)); + + expect(await claim(1, const Duration(minutes: 1)), isTrue); + expect(await claim(1, const Duration(minutes: 1)), isFalse); + // Handled out of order, within the window. + expect(await claim(2, const Duration(minutes: 10)), isTrue); + // Older than the window before the newest shown message. + expect(await claim(3, const Duration(minutes: 30)), isFalse); + // A message dated in the future is recorded as of now, so it can't hold + // back later ones. + expect(await claim(4, const Duration(days: -365)), isTrue); + expect(await claim(5, const Duration(minutes: 1)), isTrue); + expect(await store.newestShown('community'), now); + // Communities don't share a record. + expect(await store.newestShown('another'), isNull); + expect(await open().claim('another', _id(1), now), isTrue); + }); + + test('a message pruned from the record is not claimed again', () async { + final store = open(); + Future claim(int n, Duration age) => + store.claim('community', _id(n), now.subtract(age)); + + expect(await claim(1, const Duration(minutes: 20)), isTrue); + expect(await claim(2, const Duration(minutes: 1)), isTrue); + // The first marker is now older than the window and has been deleted. + expect(await claim(1, const Duration(minutes: 20)), isFalse); + + // A message dated in the future is kept as long as the fetch window can + // still return it, not only as long as the present it was capped to. + expect(await claim(6, const Duration(minutes: -10)), isTrue); + final later = now.add(const Duration(minutes: 20)); + final afterwards = DirectoryShownMessageStore(directory, now: () => later); + expect( + await afterwards.claim( + 'community', + _id(7), + later.subtract(const Duration(minutes: 1)), + ), + isTrue, + ); + expect( + await afterwards.claim( + 'community', + _id(6), + now.add(const Duration(minutes: 10)), + ), + isFalse, + ); + }); +}