mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +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>
307 lines
12 KiB
Dart
307 lines
12 KiB
Dart
part of 'read_state_manager.dart';
|
|
|
|
/// Synced whole-channel override actions and the version-2 unread record
|
|
/// that carries them (NIP-RS, Expiring unread state).
|
|
extension ReadStateOverrides on ReadStateManager {
|
|
/// The channels whose synced manual unread is live.
|
|
Set<String> get activeChannelOverrides => {
|
|
for (final MapEntry(key: channelId, value: register) in _overrides.entries)
|
|
if (_isLive(channelId, register)) channelId,
|
|
};
|
|
|
|
/// Channels whose synced clear failed and still stands.
|
|
Set<String> get failedClears =>
|
|
Set.unmodifiable(_failedClears.intersection(activeChannelOverrides));
|
|
|
|
/// The expiry clock: the local clock, never behind any time this
|
|
/// installation already used, so a rollback cannot revive a mark.
|
|
int get _expiryNow => _expiryWatermark = max(_expiryWatermark, _now());
|
|
|
|
String get _unreadCoordinate => '$readStateUnreadDTagPrefix$_unreadSlot';
|
|
|
|
bool _isLive(String channelId, OverrideRegister register) {
|
|
final frontier = _frontierOf(channelId);
|
|
final live = isOverrideActive(register, frontier, now: _expiryNow);
|
|
// An expiry seen here must survive a crash and a clock rollback.
|
|
if (!live &&
|
|
isOverrideActive(register, frontier, now: _savedExpiryWatermark)) {
|
|
_persistLocalState();
|
|
}
|
|
return live;
|
|
}
|
|
|
|
/// A fresh action stamp above [register], or null when it would pass
|
|
/// uint32 or run more than a minute ahead of the local clock.
|
|
int? _allocateStamp(OverrideRegister register) =>
|
|
allocateOverrideStamp(register, now: _now());
|
|
|
|
/// Synchronized whole-channel mark unread (NIP-RS Actions). Returns false,
|
|
/// leaving state unchanged, when the action must fail visibly: no complete
|
|
/// load, no stamp to allocate, or a record that cannot fit the group.
|
|
bool markChannelUnread(String channelId) {
|
|
if (_disposed || !_hasFullState || !isChannelOverrideTarget(channelId)) {
|
|
return false;
|
|
}
|
|
final previous = _overrides[channelId];
|
|
final register = previous ?? (s: 0, c: 0, b: 0);
|
|
final stamp = _allocateStamp(register);
|
|
if (stamp == null) return false;
|
|
// Baseline is the stored frontier, never the moving retention floor.
|
|
_overrides[channelId] = (
|
|
s: stamp,
|
|
c: register.c,
|
|
b: _frontierOf(channelId),
|
|
);
|
|
if (!_primaryFits()) {
|
|
if (previous == null) {
|
|
_overrides.remove(channelId);
|
|
} else {
|
|
_overrides[channelId] = previous;
|
|
}
|
|
return false;
|
|
}
|
|
_persistLocalState();
|
|
_onChanged();
|
|
_schedulePublish();
|
|
return true;
|
|
}
|
|
|
|
/// Ends a live channel override without moving its frontier: reaching the
|
|
/// bottom of a channel with nothing new to read. Returns false when the
|
|
/// clear failed and [syncError] says so. A [reading] clear refused only
|
|
/// because the view is incomplete is retried after the next usable
|
|
/// snapshot, if the register is still the one the reader saw.
|
|
bool clearChannelOverride(String channelId, {bool reading = false}) {
|
|
if (_disposed) return false;
|
|
final cleared = _clearChannelOverride(channelId, reading: reading);
|
|
if (cleared != true) return cleared == null;
|
|
_persistLocalState();
|
|
_onChanged();
|
|
_schedulePublish();
|
|
return true;
|
|
}
|
|
|
|
/// Ends a live channel override with a fresh clear stamp, even when no
|
|
/// frontier moved. Returns null when no live override needs a clear, and
|
|
/// false, setting [syncError], when no stamp can be allocated or the
|
|
/// record cannot carry the clear.
|
|
bool? _clearChannelOverride(String channelId, {bool reading = false}) {
|
|
// Resolve held-back groups first: one may be this channel's.
|
|
final complete = _hasFullState;
|
|
final register = _overrides[channelId];
|
|
if (register == null || !_isLive(channelId, register)) return null;
|
|
if (reading && !complete) _refusedReadingClears[channelId] = register;
|
|
// An incomplete view refuses the clear, visibly.
|
|
final stamp = complete ? _allocateStamp(register) : null;
|
|
if (stamp != null) {
|
|
_overrides[channelId] = (s: register.s, c: stamp, b: register.b);
|
|
if (_primaryFits()) {
|
|
_failedClears.remove(channelId);
|
|
return true;
|
|
}
|
|
_overrides[channelId] = register;
|
|
}
|
|
_failedClears.add(channelId);
|
|
syncError = _standingError;
|
|
_onChanged();
|
|
return false;
|
|
}
|
|
|
|
/// Retries each refused reading clear once the view is complete, after a
|
|
/// whole snapshot merged. Only a register still live and exactly as the
|
|
/// reader saw it is cleared: a newer or different mark stays. A failure
|
|
/// here is reported as any clear's is, and not retried again. A publisher
|
|
/// shut off for good keeps the refusal standing: the clear could not sync.
|
|
void _retryRefusedReadingClears() {
|
|
if (_disposed ||
|
|
_remoteUnsupported ||
|
|
_refusedReadingClears.isEmpty ||
|
|
!_hasFullState) {
|
|
return;
|
|
}
|
|
final refused = Map.of(_refusedReadingClears);
|
|
_refusedReadingClears.clear();
|
|
var cleared = false;
|
|
for (final MapEntry(key: channelId, value: seen) in refused.entries) {
|
|
if (_overrides[channelId] != seen) continue;
|
|
if (_clearChannelOverride(channelId) == true) cleared = true;
|
|
}
|
|
if (!cleared) return;
|
|
syncError = _standingError;
|
|
_persistLocalState();
|
|
_onChanged();
|
|
_schedulePublish();
|
|
}
|
|
|
|
/// Merges received version-2 groups. An expired replay is dropped before
|
|
/// its baseline can enter a register; a group stamped too far ahead is
|
|
/// deferred until the clock reaches it.
|
|
void _mergeOverrides(Map<String, int> contexts) {
|
|
for (final MapEntry(key: channelId, value: register)
|
|
in channelOverrideRegisters(contexts).entries) {
|
|
_mergeRegister(channelId, register);
|
|
}
|
|
}
|
|
|
|
/// Restores journaled groups. Local state keeps a dead group until the
|
|
/// discard guard passes, unlike an incoming replay.
|
|
void _hydrateOverrides(Map<String, OverrideRegister> registers) =>
|
|
registers.forEach(
|
|
(channelId, register) =>
|
|
_mergeRegister(channelId, register, local: true),
|
|
);
|
|
|
|
void _mergeRegister(
|
|
String channelId,
|
|
OverrideRegister register, {
|
|
bool local = false,
|
|
}) {
|
|
final now = _expiryNow;
|
|
if (local
|
|
? isOverrideDiscardable(register, now: now)
|
|
: isOverrideExpired(register, now: now)) {
|
|
return;
|
|
}
|
|
if (isOverrideDeferred(register, now: _now())) {
|
|
final held = (channelId: channelId, register: register, local: local);
|
|
// A repeated delivery holds nothing new.
|
|
if (!_deferredOverrides.contains(held)) _deferredOverrides.add(held);
|
|
return;
|
|
}
|
|
final current = _overrides[channelId];
|
|
_overrides[channelId] = current == null
|
|
? register
|
|
: mergeOverrideRegisters(current, register);
|
|
}
|
|
|
|
/// Merges the deferred groups the clock has reached. Returns whether none
|
|
/// remain: until then the override view is incomplete.
|
|
bool _resolveDeferred() {
|
|
if (_deferredOverrides.isEmpty) return true;
|
|
final waiting = List.of(_deferredOverrides);
|
|
_deferredOverrides.clear();
|
|
// Each contribution meets its own rule: an incoming one the replay
|
|
// cutoff, before its baseline can merge; accepted local state the guard.
|
|
for (final held in waiting) {
|
|
_mergeRegister(held.channelId, held.register, local: held.local);
|
|
}
|
|
if (_deferredOverrides.length == waiting.length) return false;
|
|
_persistLocalState();
|
|
_onChanged();
|
|
_schedulePublish();
|
|
return _deferredOverrides.isEmpty;
|
|
}
|
|
|
|
/// Clock upkeep, on the display tick and on resume: merges held-back
|
|
/// groups the clock has reached and saves any expiry the tick shows.
|
|
void maintainOverrideClock() {
|
|
if (_disposed) return;
|
|
_resolveDeferred();
|
|
activeChannelOverrides;
|
|
}
|
|
|
|
/// Whether an unread candidate may be planned: held-back groups the clock
|
|
/// has reached merge first, so the save before sending covers them.
|
|
bool get _unreadPublishable => _resolveDeferred();
|
|
|
|
/// Whether the candidate planned as [planned] may still be sent. Changes
|
|
/// nothing: anything held back, or admitted since planning, refuses it,
|
|
/// and the next pass saves and rebuilds, so an older record never
|
|
/// replaces the only carrier of a mark the journal does not cover.
|
|
bool _unreadStillCurrent(Map<String, int> planned) {
|
|
if (_deferredOverrides.isEmpty && mapEquals(_planUnread(), planned)) {
|
|
return true;
|
|
}
|
|
_schedulePublish();
|
|
return false;
|
|
}
|
|
|
|
/// Drops dead groups past the discard guard, with their ceilings.
|
|
void _discardOverrides() {
|
|
final now = _expiryNow;
|
|
_overrides.removeWhere(
|
|
(_, register) => isOverrideDiscardable(register, now: now),
|
|
);
|
|
}
|
|
|
|
/// The record's canonical groups and their paired frontiers, 0 included.
|
|
Map<String, int> _unreadEntries(Map<String, OverrideRegister> registers) {
|
|
final now = _expiryNow;
|
|
final kept = {
|
|
for (final MapEntry(:key, :value) in registers.entries)
|
|
if (!isOverrideDiscardable(value, now: now)) key: value,
|
|
};
|
|
return {
|
|
...canonicalOverrideEntries(kept, _frontierOf, now: now),
|
|
for (final channelId in kept.keys)
|
|
overrideFrontierKey(channelId): _frontierOf(channelId),
|
|
};
|
|
}
|
|
|
|
Map<String, int> _primaryOverrides() => _unreadEntries(_overrides);
|
|
|
|
bool _unreadFits(Map<String, int> contexts) =>
|
|
contexts.length <= 10000 &&
|
|
utf8
|
|
.encode(
|
|
jsonEncode(
|
|
ReadStateBlob(
|
|
clientId: _clientId,
|
|
contexts: contexts,
|
|
version: 2,
|
|
).toJson(),
|
|
),
|
|
)
|
|
.length <=
|
|
readStatePlaintextBytes;
|
|
|
|
bool _primaryFits() => _unreadFits(_primaryOverrides());
|
|
|
|
/// The unread record to publish. When the merged groups overfill it, it
|
|
/// keeps the last published groups, canonical and expired against the
|
|
/// current clock and frontiers, so it can only shrink; only override
|
|
/// actions fail ([_primaryFits]).
|
|
Map<String, int> _planUnread() {
|
|
final merged = _primaryOverrides();
|
|
if (_unreadFits(merged)) return merged;
|
|
return _unreadEntries(channelOverrideRegisters(_unreadPublished));
|
|
}
|
|
|
|
/// Takes in one decoded unread record. A foreign record at this
|
|
/// installation's coordinate moves it to a fresh slot.
|
|
void _mergeUnreadRecord(String slot, ReadStateBlob blob, NostrEvent event) {
|
|
if (slot == _unreadSlot) {
|
|
if (blob.clientId == _clientId) {
|
|
// Our own head raises the reservation floor whatever its clock, so
|
|
// the next version can replace it (the peer filter doesn't apply).
|
|
_lastReserved = max(_lastReserved, event.createdAt);
|
|
final head = _unreadHead;
|
|
// A superseded own packet, such as a late echo, is not what the
|
|
// relay holds.
|
|
if (head == null || !_outranks(head, event)) {
|
|
_unreadHead = event;
|
|
_unreadPublished = Map.of(blob.contexts);
|
|
}
|
|
} else {
|
|
_pending.remove(_unreadCoordinate);
|
|
_unreadSlot = generateReadStateSlotId();
|
|
_unreadPublished = const {};
|
|
_unreadHead = null;
|
|
}
|
|
}
|
|
_mergeOverrides(blob.contexts);
|
|
for (final MapEntry(:key, :value) in blob.contexts.entries) {
|
|
if (isOverrideContext(key)) continue;
|
|
if (_applyRemoteContextTimestamp(contextId: key, timestamp: value) ==
|
|
_ApplyRemoteContextResult.advanced) {
|
|
_pendingSyncedAdvances.add(key);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Replaceable-event order: the later `created_at`, then the lower id.
|
|
bool _outranks(NostrEvent a, NostrEvent b) =>
|
|
a.createdAt > b.createdAt ||
|
|
(a.createdAt == b.createdAt && a.id.compareTo(b.id) < 0);
|