Files
buzz/mobile/lib/shared/push/shown_message_store.dart
Tom Brow 298543f555 fix(mobile): report a push wake claim it stopped waiting for (#9931)
## What

An Android push wake that runs out of time can leave a claim still
running. If that claim then wins, the message is recorded as shown but
was never returned. No later wake finds it, so the user is never told.
This makes the wake report that case, and the native handler shows its
generic notification for it.

- `resolvePushWake` tracks the message each community is claiming. After
the claim grace it sets `PushWakeResult.unreported` when a claim is
still running for a message with something to show (a message whose body
is empty would not be returned anyway). It is read in the same
synchronous step as the claimed-message snapshot, so a claim that
finishes before the snapshot is returned, and one that finishes after it
is counted.
- `PushWakeRunner` reports `unreported` when any pass does, because a
message lost in one pass stays lost.
- The channel payload carries `unreported`. The native handler posts the
named notifications, and the generic notification beside them, silently
when something already alerted. If the user already cleared the generic
card this wake posted at 2 seconds, it stays cleared. The generic is
marked as standing in for a lost message, so later wakes, which clear an
unmarked generic as before, leave it until the user clears it. A later
wake that re-posts the generic keeps the mark.
- It stays separate from `incomplete`, which means a later wake retries.
Folding the two would show the generic beside named notifications on
every retryable partial wake.
- `ShownMessageStore.claim` documents that a caller that stops waiting
for a claim must report it. A claim that later returns false still costs
one unnecessary generic notification, which is accepted.

The realistic trigger is storage that stalls after the claim marker is
created, during the watermark and prune I/O in
`DirectoryShownMessageStore.claim` (a pre-existing finding from the
review of the Android wake handler). The store's order is unchanged. The
marker has to come first for atomicity, and this signal turns the stall
into a generic notification instead of silence.

## Validation

- The push-wake journey test's stalled-storage step now asserts
`unreported`, and a stalled claim for a message with an empty body
asserts it is not set. A wake cut short in the name lookup, outside any
claim, asserts it is not set and still returns its messages. The runner
step asserts that a message lost in one pass is still reported after a
clean rerun. The channel payload test covers both values.
- Forcing the signal off fails the stalled-storage step.
- `WakeNotifierGenericTest` (instrumented) drives the generic
notification against the real notification manager on a Pixel 9a: an
unmarked card clears on a clean wake, a kept card survives clean wakes
and a later 2-second re-post, and a card the user cleared before the
result is not posted again. Each step waits for the state it expects, a
re-post check waits for a newer post, and checks that nothing changed
run after a barrier notification. Its two updates wait 700 ms first, so
Android's update rate limit can't drop them on quick reruns (12
back-to-back runs passed). Removing the cleared-card check, or dropping
the mark on re-post, fails it.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-25 06:27:18 +00:00

160 lines
6.5 KiB
Dart

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<DateTime?> 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. For the same reason, a caller that stops waiting for a
/// claim must report it as lost (`PushWakeResult.unreported`), even though
/// the claim may yet return false and cost only a needless fallback.
Future<bool> 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<List<({bool claim, int seconds, File file})>> _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<DateTime?> 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<bool> 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;