refactor(social): one shared relay connection per identity

Every feature (offers, messaging, trust, profile, the inbox listener) used
to open its OWN RelayPool via social.openSession — several sockets to the
same relays, more battery, and reconnection logic living only in the inbox
listener.

Add SocialConnection: ONE shared session per identity, lazily connected and
reused by all. It watches connectivity — dropping the session when the
network goes and reconnecting when it returns, announcing each change on a
sessions stream so the inbox listener re-subscribes automatically. Callers
get the session via connection.session() and never close it (the connection
owns its lifecycle); recreated/disposed on an identity switch.

- InboxService now consumes the shared connection (subscribes on its
  sessions stream) instead of owning its own socket + connectivity code.
- createOffersCubit + the chat/market/profile screens use the shared
  connection; dead createMessagesCubit/createTrustCubit factories removed.
- DI registers SocialConnection per identity; Bootstrap starts it (after
  the inbox subscribes); switchSocialAccount disposes + recreates it.

Tests: SocialConnection lifecycle (reuse, concurrent connect, offline drop +
reconnect, unreachable retry) with a fake opener + online stream; inbox test
updated. nostr added as a dev_dependency for the channel fake.
This commit is contained in:
vjrj 2026-07-10 21:41:17 +02:00
parent e2b88b4f26
commit bb4ee2fd89
19 changed files with 431 additions and 280 deletions

View file

@ -1,110 +1,89 @@
import 'dart:async';
import 'package:commons_core/commons_core.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import '../i18n/strings.g.dart';
import 'message_store.dart';
import 'notification_service.dart';
import 'profile_cache.dart';
import 'social_service.dart';
import 'social_settings.dart';
import 'social_connection.dart';
import 'social_service.dart' show SocialSession;
import 'unread_service.dart';
/// App-wide inbox listener for private messages (NIP-17).
///
/// Without this, a message only arrived while its specific chat screen was
/// open so a first message from a new peer was invisible (nothing in local
/// storage, so nothing in the inbox list, so you never opened the chat, so you
/// never subscribed). This keeps ONE long-lived subscription for the whole app
/// while online: it persists every incoming message to the [MessageStore] and
/// fires [changes] so the inbox list refreshes. Reconnects when the network
/// returns; degrades to nothing offline (local-first).
/// Without this, a message only arrived while its specific chat screen was open
/// so a first message from a new peer was invisible. This keeps one inbox
/// subscription over the SHARED [SocialConnection] for the whole app while
/// online: it persists every incoming message to the [MessageStore], updates
/// unread counts, fires an OS notification, and fires [changes] so the inbox
/// list refreshes. It re-subscribes automatically each time the connection
/// reconnects (and stops when it drops), because it listens to the connection's
/// session stream rather than owning a socket itself.
///
/// Foreground only background/push delivery is a later concern.
class InboxService {
InboxService({
required SocialService social,
required SocialSettings settings,
required SocialConnection connection,
required String selfPubkey,
required MessageStore store,
ProfileCache? profileCache,
UnreadService? unread,
NotificationService? notifications,
}) : _social = social,
_settings = settings,
}) : _connection = connection,
_selfPubkey = selfPubkey,
_store = store,
_profileCache = profileCache,
_unread = unread,
_notifications = notifications;
final SocialService _social;
final SocialSettings _settings;
final SocialConnection _connection;
final String _selfPubkey;
final MessageStore _store;
final ProfileCache? _profileCache;
final UnreadService? _unread;
final NotificationService? _notifications;
final _changes = StreamController<void>.broadcast();
SocialSession? _session;
StreamSubscription<SocialSession?>? _sessionsSub;
StreamSubscription<PrivateMessage>? _inboxSub;
StreamSubscription<List<ConnectivityResult>>? _connSub;
SocialSession? _session;
bool _started = false;
bool _connecting = false;
/// Fires (with no payload) after a NEW message is persisted the inbox list
/// listens to this to reload. Broadcast, so several screens can listen.
/// Fires (no payload) after a NEW message is persisted the inbox list
/// listens to reload. Broadcast, so several screens can listen.
Stream<void> get changes => _changes.stream;
/// Begins listening. Idempotent. Connects now if online, and (re)connects
/// whenever the network returns. Safe to call once at app start.
Future<void> start() async {
/// Begins listening. Subscribe to the connection's sessions BEFORE the
/// connection starts connecting, so the first session is caught too.
void start() {
if (_started) return;
_started = true;
try {
_connSub = Connectivity().onConnectivityChanged.listen((results) {
final offline =
results.isEmpty || results.every((r) => r == ConnectivityResult.none);
if (offline) {
_dropSession();
} else {
unawaited(_connect());
}
});
} catch (_) {
// Platform without connectivity support just try once below.
}
await _connect();
_sessionsSub = _connection.sessions.listen(_onSession);
// In case the connection is already up (a screen connected first).
final current = _connection.current;
if (current != null) _onSession(current);
}
/// Opens a session and subscribes to the inbox, if not already connected.
/// Guarded so overlapping connectivity events can't open two sessions.
Future<void> _connect() async {
if (_session != null || _connecting) return; // already (being) connected
_connecting = true;
try {
final relays = await _settings.relayUrls();
if (relays.isEmpty) return; // offline / unconfigured
final session = await _social.openSession(relays);
if (!_started) {
await session.close(); // stopped while connecting
return;
}
_session = session;
/// (Re)binds the inbox subscription to [session] the connection handing us a
/// fresh session (reconnect) or null (dropped).
void _onSession(SocialSession? session) {
if (identical(session, _session) && _inboxSub != null) return;
unawaited(_inboxSub?.cancel());
_inboxSub = null;
_session = session;
if (session != null) {
_inboxSub = session.messages.inbox().listen(
ingest,
onError: (_) => _dropSession(), // relay dropped retry on next change
);
} catch (_) {
// No relay reachable a later connectivity change retries.
} finally {
_connecting = false;
ingest,
onError: (_) {}, // drop handled by the connection's reconnect
);
}
}
/// Persists one incoming [message] (deduped) and, when it's new, fires
/// [changes] and best-effort caches the sender's display name. Separated from
/// the transport so it can be unit-tested without a relay.
/// Persists one incoming [message] (deduped) and, when new, fires [changes],
/// updates unread, notifies, and best-effort caches the sender's name. A
/// testable seam (no relay).
@visibleForTesting
Future<void> ingest(PrivateMessage message) async {
final stored = await _store.append(message.fromPubkey, message);
@ -113,9 +92,8 @@ class InboxService {
final peer = message.fromPubkey;
// Defensive: never badge or notify for your own message. NIP-17 doesn't
// loop a sent gift wrap back to its author, so this shouldn't happen — the
// guard just keeps the seam honest.
if (peer != _social.publicKeyHex) {
// loop a sent gift wrap back to its author; the guard keeps the seam honest.
if (peer != _selfPubkey) {
await _unread?.onMessageReceived(peer, message);
await _maybeNotify(peer);
}
@ -151,20 +129,12 @@ class InboxService {
}
}
void _dropSession() {
unawaited(_inboxSub?.cancel());
_inboxSub = null;
unawaited(_session?.close());
_session = null;
}
Future<void> stop() async {
_started = false;
await _connSub?.cancel();
_connSub = null;
await _sessionsSub?.cancel();
_sessionsSub = null;
await _inboxSub?.cancel();
_inboxSub = null;
await _session?.close();
_session = null;
if (!_changes.isClosed) await _changes.close();
}