mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
Reading, mark read, whole-channel mark unread and thread follow choices now sync across a person's installations. This PR specifies the rules in NIP-RS and implements them in the mobile app. ## Spec (`docs/nips/NIP-RS.md`) - Defines *catch-up* and *displayed*. - A catch-up advances the channel's own frontier (top-level messages) or `thread:<root>`. `activity:` and `thread-activity:` become read-only legacy keys. - Explicit mark read is synchronized state. A first explicit read of a message with no override group writes only its `msg:` frontier. Display, dwell, scroll, catch-up and mention visibility create no `msg:` entries. - Only whole-channel override groups are published, merged and cleared with the counter. Readers ignore peer `msg:` and `thread:` groups. - Single-message and thread mark unread stay on the device. They end once the merged frontier covering them passes their baseline, from any installation, or on display, catch-up or explicit read. The section also states clearing scope, the accepted concurrency limitation and capacity. - When the merged override union no longer fits the primary, the client rewrites the primary compactly from the groups its last published primary carried, each canonical against current frontiers. It never omits merged groups or tombstone floors that primary carried, and override actions fail visibly. - Adds Buzz Thread Follow Choices: `thread-follows:<32hex>` coordinates, validation, three-state verdict, last-writer merge with ties going to unfollow, publication and recovery, legacy import at `at = 0`, and capacity. ## Mobile - Catch-up writes the main frontier. A flat timeline reads up to the newest top-level message it reached. - Explicit mark read publishes. Passive `msg:` marks stay on the device. - Whole-channel mark unread publishes an override group and merges peer groups. An explicit read or catch-up clears it, even when no frontier moves. The action fails visibly at the uint32 limit or when the primary is full. A synced clear the primary can't carry is rolled back, and the channel view reports it once while the failure stands. - Device-local message and Inbox unread overrides record a baseline and clear when a covering frontier passes it, including one merged from a peer. - Thread follows move from local storage to the synced `thread-follows:` slots. They share the read-state `client_id`, journal, `created_at` sequence, snapshot and live subscription, and spill across up to 16 slots with stable placement. An unreadable coordinate marks follow state incomplete and blocks this installation's follow publication. - Follow and unfollow are refused on every cold start of the writer until its first complete recovery of its own state succeeds and every owned follow head is readable. Cached follows show at once. A refused tap changes nothing and shows "Follow choices are not ready. Connect and try again." Reads, catch-up and both kinds of mark unread are not gated. - A follow tap is accepted only once journaled. The accepted own head, pending edits and the exact in-flight packet are kept apart, so a retry or restore never drops or re-attributes an edit. - Pre-sync local follows are imported at `at = 0` after a complete merge, once their channel is known from a relay event. An imported key is settled, and its legacy copy retired, only when the journal write the import awaited covered it and that entry is still current. - An explicit unfollow suppresses ordinary replies at live and catch-up admission. A change in follow choices drops the unread replies already counted for an unfollowed thread. A newly followed thread re-runs catch-up only for its own channel. - A reading clear refused because the view hasn't completely loaded is retried after the next complete snapshot, including when publishing was shut off at the time. The view also counts as not completely loaded while the live subscription is reconnecting, so a read made while the phone is offline can't erase a newer unread mark set on another device. Offline, whole-channel mark unread is still refused, with a message. - Read-state events, including live ones, are verified with native libsecp256k1 before they are used. - A pending unread packet is counted as published only when no newer own head outranks it. When a newer head supersedes it, a successor is built above that head from the saved intent, and a late echo of a replaced packet doesn't overwrite what was published. - When the merged unread state overfills the primary and the compact fallback can't carry a pending mark, the packet stays pending and the "read state full" error shows. Other queued reads and follows in the same flush still publish. - When this installation's own unread record can't be decoded, only the unread step is held: that record isn't overwritten, its pending marks stay queued and the sync error shows. Other queued reads and follows in the same flush still publish. - The sync notice stays up after an unsupported refusal until a new session. Offline, it can't be tapped and says it will retry when back online. - Two-device fixtures against an in-memory relay cover channel round-trips and clears, stray message groups, the first explicit message read, the primary cap, follow propagation, same-second and backward-clock follow publication, legacy import, retry after a failed publish, unreadable coordinates and slot packing. Recovery fixtures cover the startup gate, journal failures during flush, interleaved legacy imports, and restore of an older journal. ## Relay - Conforming `thread-follows:<32 hex>` records get the NIP-RS treatment: a replaced record is purged, and a stale resend of an older one is refused. Records with a mismatched `t` tag keep ordinary replaceable-event behavior. ## Known gap - An unread packet held for capacity can age past the relay's timestamp window. The relay then refuses it, and the refusal path retires it without the capacity check, so the error clears and other installations don't get that mark. The mark stays on the device. Related: [block/buzz-app#3552](https://github.com/block/buzz-app/pull/3552) --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Will Pfleger <wpfleger@squareup.com> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz>
218 lines
8.3 KiB
Dart
218 lines
8.3 KiB
Dart
part of 'read_state_manager.dart';
|
|
|
|
/// The local journal: this installation's durable read-state copy.
|
|
extension ReadStateJournal on ReadStateManager {
|
|
void _hydrateFromLocalStorage() {
|
|
final journal = _storage.readJournal(_journalKey);
|
|
Map<String, int> contexts(Object? value) => (value as Map).map(
|
|
(key, value) => MapEntry(key as String, value as int),
|
|
);
|
|
if (journal != null) {
|
|
// An existing journal, even empty, means this is not a first landing.
|
|
_initialSeedComplete = true;
|
|
_clientId = journal['clientId'] as String;
|
|
_effectiveState.addAll(contexts(journal['observed']));
|
|
_localContexts.addAll(contexts(journal['local']));
|
|
_expiryWatermark = _savedExpiryWatermark =
|
|
(journal['expiryWatermark'] as int?) ?? 0;
|
|
// Overrides from before the unread record are not v2 intent (no
|
|
// import): only a journal that has the record loads them.
|
|
if (journal['unreadSlot'] case final String slot) {
|
|
_unreadSlot = slot;
|
|
_unreadPublished = contexts(journal['unreadPublished']);
|
|
_hydrateOverrides(
|
|
channelOverrideRegisters({
|
|
...contexts(journal['observed']),
|
|
...contexts(journal['overrides']),
|
|
}),
|
|
);
|
|
for (final held
|
|
in (journal['deferredOverrides'] as List?) ?? const []) {
|
|
final [String id, int s, int c, int b, int local] = held as List;
|
|
_mergeRegister(id, (s: s, c: c, b: b), local: local == 1);
|
|
}
|
|
}
|
|
_followSlots.addAll(
|
|
((journal['followSlots'] as List?) ?? const []).cast<String>(),
|
|
);
|
|
_followPlacement = [
|
|
for (final keys in (journal['followPlacement'] as List?) ?? const [])
|
|
(keys as List).cast<String>().toSet(),
|
|
];
|
|
for (final entry
|
|
in ((journal['ownFollows'] as Map?) ?? const {}).entries) {
|
|
_ownFollows[entry.key as String] = Map<String, Object?>.from(
|
|
entry.value as Map,
|
|
);
|
|
}
|
|
for (final entry
|
|
in ((journal['followExtra'] as Map?) ?? const {}).entries) {
|
|
_followExtra[entry.key as String] = Map.from(entry.value as Map);
|
|
}
|
|
_hydrateFollowHeads(journal['followHeads']);
|
|
for (final entry
|
|
in ((journal['followEdits'] as Map?) ?? const {}).entries) {
|
|
_followEdits[entry.key as String] = entry.value as int;
|
|
}
|
|
for (final entry
|
|
in ((journal['followCaptured'] as Map?) ?? const {}).entries) {
|
|
_followCaptured[entry.key as String] = (entry.value as Map).map(
|
|
(key, value) => MapEntry(key as String, value as int),
|
|
);
|
|
}
|
|
for (final entry
|
|
in ((journal['followPublished'] as Map?) ?? const {}).entries) {
|
|
_followPublished[entry.key as String] = entry.value as String;
|
|
}
|
|
_slots
|
|
..clear()
|
|
..addAll((journal['slots'] as List).cast<String>());
|
|
if (_slots.isEmpty) {
|
|
throw const FormatException('Empty read-state slot list');
|
|
}
|
|
_slotId = _slots.first;
|
|
_placement = (journal['placement'] as List).map(contexts).toList();
|
|
for (final entry in (journal['published'] as Map).entries) {
|
|
_published[entry.key as String] = contexts(entry.value);
|
|
}
|
|
// Follow and v2 unread events have their own fields, which older
|
|
// builds ignore; v2 entries an earlier build wrote to `pending` load
|
|
// here too and move to `unreadPending` on the next save.
|
|
for (final entry in {
|
|
...journal['pending'] as Map,
|
|
...?journal['unreadPending'] as Map?,
|
|
...?journal['followPending'] as Map?,
|
|
}.entries) {
|
|
_pending[entry.key as String] = NostrEvent.fromJson(
|
|
Map<String, dynamic>.from(entry.value as Map),
|
|
);
|
|
}
|
|
_maxFetchedCreatedAt = journal['createdAt'] as int;
|
|
// Never below anything already reserved, even if the journal's own
|
|
// counter is older than a retained edit or packet.
|
|
_lastReserved = [
|
|
(journal['reserved'] as int?) ?? 0,
|
|
..._followEdits.values,
|
|
for (final event in _pending.values) event.createdAt,
|
|
for (final slot in _followSlots) ?_followHeads[slot]?.createdAt,
|
|
].reduce(max);
|
|
} else {
|
|
final stored = _storage.read(pubkey, relayUrl);
|
|
_effectiveState.addEntries(
|
|
stored.contexts.entries.where((entry) => !isOverrideContext(entry.key)),
|
|
);
|
|
// Legacy storage did not preserve provenance. Carry its existing
|
|
// publishable values once; subsequent peer merges never enter this map.
|
|
_localContexts.addEntries(
|
|
stored.contexts.entries.where(
|
|
(entry) =>
|
|
stored.publishableContextIds.contains(entry.key) &&
|
|
!isOverrideContext(entry.key) &&
|
|
!entry.key.startsWith(msgContextPrefix),
|
|
),
|
|
);
|
|
}
|
|
_persistLocalState();
|
|
}
|
|
|
|
/// The journal field that keeps a retained packet for coordinate [key].
|
|
String _pendingField(String key) => key.startsWith(threadFollowsDTagPrefix)
|
|
? 'followPending'
|
|
: key.startsWith(readStateUnreadDTagPrefix)
|
|
? 'unreadPending'
|
|
: 'pending';
|
|
|
|
/// Saves like [_persistLocalState], resolving with the follow keys the
|
|
/// write it awaited actually covered; see [_savedFollows].
|
|
Future<Map<String, int>> _persistFollowKeys() {
|
|
_persistLocalState();
|
|
return _savedFollows;
|
|
}
|
|
|
|
Future<void> _persistLocalState() {
|
|
if (_saveScheduled) return _saved;
|
|
_saveScheduled = true;
|
|
Future<Map<String, int>> save() async {
|
|
_saveScheduled = false;
|
|
if (!_ownsJournal) {
|
|
throw StateError('Read-state journal writer retired');
|
|
}
|
|
_discardOverrides();
|
|
final observed = pruneStaleContexts(
|
|
_effectiveState,
|
|
nowUnixSeconds: _now(),
|
|
);
|
|
// Every retained register keeps its frontier, an explicit 0 included.
|
|
for (final channelId in {
|
|
..._overrides.keys,
|
|
for (final held in _deferredOverrides) held.channelId,
|
|
}) {
|
|
observed[overrideFrontierKey(channelId)] = _frontierOf(channelId);
|
|
}
|
|
final watermark = _expiryNow;
|
|
final encoded = jsonEncode({
|
|
'v': 1,
|
|
'clientId': _clientId,
|
|
'observed': observed,
|
|
'local': _localContexts,
|
|
'overrides': canonicalOverrideEntries(
|
|
_overrides,
|
|
_frontierOf,
|
|
now: _expiryNow,
|
|
),
|
|
'unreadSlot': _unreadSlot,
|
|
'unreadPublished': _unreadPublished,
|
|
'expiryWatermark': watermark,
|
|
'deferredOverrides': [
|
|
for (final (:channelId, register: r, :local) in _deferredOverrides)
|
|
[channelId, r.s, r.c, r.b, if (local) 1 else 0],
|
|
],
|
|
'followSlots': _followSlots,
|
|
'followPlacement': [
|
|
for (final keys in _followPlacement) keys.toList()..sort(),
|
|
],
|
|
'ownFollows': _ownFollows,
|
|
'followExtra': _followExtra,
|
|
'followHeads': _followHeadsJson(),
|
|
'followPublished': _followPublished,
|
|
'followEdits': _followEdits,
|
|
'followCaptured': _followCaptured,
|
|
'reserved': _lastReserved,
|
|
'slots': _slots,
|
|
'placement': _placement,
|
|
'published': _published,
|
|
// `pending` stays v1-only, so an older build can replay it.
|
|
for (final field in ['pending', 'unreadPending', 'followPending'])
|
|
field: {
|
|
for (final MapEntry(:key, :value) in _pending.entries)
|
|
if (_pendingField(key) == field) key: value.toJson(),
|
|
},
|
|
'createdAt': _maxFetchedCreatedAt,
|
|
});
|
|
final follows = {
|
|
for (final key in threadFollows.keys) key: _followEdits[key] ?? 0,
|
|
};
|
|
await _storage.writeJournal(_journalKey, encoded, owner: _journalOwner);
|
|
// Only a saved watermark is safe to compare against; a failed save
|
|
// leaves the next expiry check asking again.
|
|
_savedExpiryWatermark = max(_savedExpiryWatermark, watermark);
|
|
return follows;
|
|
}
|
|
|
|
// Coalesce synchronous batches without allowing a later write to race an
|
|
// earlier write. A sender awaits this entire chain before network I/O.
|
|
_savedFollows = _saved.then(
|
|
(_) => save(),
|
|
onError: (Object _, StackTrace _) => save(),
|
|
);
|
|
_saved = _savedFollows.then((_) {});
|
|
unawaited(
|
|
_saved.catchError((Object error) {
|
|
syncError = error;
|
|
debugPrint('[ReadStateManager] journal save failed: $error');
|
|
}),
|
|
);
|
|
return _saved;
|
|
}
|
|
}
|