import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:uuid/uuid.dart'; import '../community/community.dart'; import '../storage/secure_storage.dart'; import '../storage/serial_queue.dart'; import 'builderlab_account.dart'; import 'known_community_address.dart'; /// Retained account for a local add or removal only. extension LocalEditSubject on BuilderlabAccountClient { /// An unreadable session record makes a local add or removal behave as /// signed out: no owner stamp and no tombstone, so the device edit still /// succeeds as it did before account sync. Account sync itself stays strict: /// it requires a verified session and never reads this fallback. Future localEditSubject() async { try { return await retainedSubject(); } on AccountFailure catch (failure) { if (failure == AccountFailure.storage) return null; rethrow; } } } /// Durable account-list edits. Community credentials and relay membership never /// enter this queue. Each account keeps its own snapshot and latest URL intents. class KnownCommunitySync extends ChangeNotifier { /// Reconciles committed, explicitly owned additions and queued removals. KnownCommunitySync({ required this.account, required this.localCommunities, this.acknowledgeRemoval, FlutterSecureStorage? storage, this.retryDelay = const Duration(seconds: 2), }) : _storage = storage ?? accountSecureStorage { account.subjectChanges.addListener(_sessionChanged); account.sessionChanges.addListener(_sessionChanged); } /// Account API whose verified session authorizes each destination edit. final BuilderlabAccountClient account; /// Durable device records, including their explicit account ownership. final Future> Function() localCommunities; /// Removes a credential-free local tombstone only after server acknowledgment. final Future Function(String revision)? acknowledgeRemoval; final FlutterSecureStorage _storage; /// Initial transient retry delay; subsequent failures back off up to 32x. final Duration retryDelay; /// Latest failure for the current account; pending work remains durable. Object? get failure => _failure; Object? _failure; final _queue = SerialQueue(); Timer? _retry; bool _disposed = false; bool _active = true; Future? _work; bool _again = false; String? _blockedSubject; int _failures = 0; String _key(String subject) => 'buzz_known_communities_v1_${base64Url.encode(utf8.encode('${account.accountOrigin.origin}\n$subject'))}'; Future<_SyncState> _read(String subject) async { final raw = await _storage.read(key: _key(subject)); return raw == null ? _SyncState() : _SyncState.decode(raw); } Future _write(String subject, _SyncState state) => _storage.write(key: _key(subject), value: state.encode()); bool _current(String subject) => !_disposed && account.account?.subject == subject; void _sessionChanged() { _failure = null; _blockedSubject = null; _failures = 0; _retry?.cancel(); notifyListeners(); trigger(); } /// Stop retries immediately when the app leaves the foreground. void setActive(bool active) { _active = active; _retry?.cancel(); if (active) trigger(); } /// Persist removal before deleting the local record. The drain sends it only /// once the local record is absent, so failed local deletion cannot forget it /// remotely. Signed-out edits never borrow another account's credentials. Future remove(String relay, {String? expectedSubject}) async { final subject = expectedSubject ?? await account.localEditSubject(); if (await account.localEditSubject() != subject) { throw AccountFailure.differentAccount; } final url = knownCommunityAddress(relay); if (subject == null || url == null) return; await _queue.run(() async { final state = await _read(subject); if (!_current(subject)) throw AccountFailure.differentAccount; final local = await localCommunities(); if (!_current(subject)) throw AccountFailure.differentAccount; for (final item in local) { if (knownCommunityAddress(item.relayUrl) == url && item.accountSyncOwner == _owner(subject) && item.accountSyncRevision != null) { state.observed[url] = item.accountSyncRevision!; } } state.pending[url] = true; await _write(subject, state); }); if (!_disposed) notifyListeners(); } String _owner(String subject) => '${account.accountOrigin.origin}\n$subject'; /// Stamp only explicit additions. Saving this returned record atomically with /// credentials is the durable add intent; a later journal failure cannot turn /// a completed join into an authentication failure. Unclaimed legacy records /// and another account's retained records are never automatically uploaded. Future prepareAddition(Community community) async { final subject = await account.localEditSubject(); if (subject == null && community.accountSyncOwner == null && community.accountSyncRevision == null) { return community; } return community.copyWith( accountSyncRemoved: false, accountSyncOwner: subject == null ? null : _owner(subject), accountSyncRevision: subject == null ? null : const Uuid().v4(), ); } /// An explicit retry clears a refused request without dropping its intent. void retry() { _blockedSubject = null; _failure = null; _failures = 0; notifyListeners(); trigger(); } /// Pending removals for visible status, including across app restarts. Future> pendingRemovals(String subject) => _queue.run(() async { final records = await localCommunities(); final removed = records .where( (c) => c.accountSyncRemoved && c.accountSyncOwner == _owner(subject), ) .map((c) => c.relayUrl) .toSet(); try { final state = await _read(subject); removed.addAll( state.pending.entries.where((e) => e.value).map((e) => e.key), ); } catch (_) { // A separate journal failure must not conceal a committed local removal. if (removed.isEmpty) rethrow; } return removed; }); /// Run after startup, a saved-community change, sign-in, or app resume. void trigger() => unawaited(synchronize()); /// Coalesce concurrent refreshes and complete after their queued work drains. Future synchronize() { if (_disposed || !_active) return Future.value(); _retry?.cancel(); final work = _work; if (work != null) { _again = true; return work; } return _work = _drain().whenComplete(() => _work = null); } Future _drain() async { do { _again = false; await _run(); } while (_again && !_disposed && _active); } Future _run() async { String? attemptSubject; try { final session = account.account ?? await account.restore(); if (session == null || !_current(session.subject) || !_active) return; final subject = session.subject; attemptSubject = subject; if (_blockedSubject == subject) return; // Local deletion and this intent share a single storage commit. Drain it // independently of the older account-only journal, even if that is broken. final committed = await localCommunities(); for (final item in committed.where( (c) => c.accountSyncRemoved && c.accountSyncOwner == _owner(subject), )) { if (!_current(subject)) return; await account.updateKnownCommunity( item.relayUrl, removed: true, expectedSubject: subject, ); if (!_current(subject)) return; await acknowledgeRemoval?.call(item.accountSyncRevision!); if (!_disposed) notifyListeners(); } var local = {}; await _queue.run(() async { final records = (await localCommunities()) .where((c) => !c.accountSyncRemoved) .toList(); local = records .where((c) => c.accountSyncOwner == _owner(subject)) .map((c) => knownCommunityAddress(c.relayUrl)) .whereType() .toSet(); final state = await _read(subject); if (!_current(subject)) return; final owned = records .where( (item) => item.accountSyncOwner == _owner(subject) && item.accountSyncRevision != null, ) .map((item) => knownCommunityAddress(item.relayUrl)) .whereType() .toSet(); // Older preview journals had no ownership evidence for inferred adds. state.pending.removeWhere( (url, removed) => !removed && !owned.contains(url), ); final revisions = >{}; for (final item in records) { final url = knownCommunityAddress(item.relayUrl); final revision = item.accountSyncRevision; if (url == null || revision == null || item.accountSyncOwner != _owner(subject)) { continue; } (revisions[url] ??= []).add(revision); } for (final entry in revisions.entries) { final url = entry.key; final revision = (entry.value..sort()).join(','); if (state.observed[url] != revision) { // A committed re-add wins over an older removal, even if the app // stopped before it could update this separate retry journal. state.pending[url] = false; state.observed[url] = revision; } } await _write(subject, state); }); while (_current(subject) && _active) { final pending = await _queue.run(() => _read(subject)); final entries = pending.pending.entries.where( (entry) => !entry.value || !local.contains(entry.key), ); if (entries.isEmpty) break; final op = entries.first; if (!_current(subject)) return; await account.updateKnownCommunity( op.key, removed: op.value, expectedSubject: subject, ); if (!_current(subject)) return; await _queue.run(() async { final latest = await _read(subject); // An edit made while the request was in flight wins over its ack. if (latest.pending[op.key] == op.value) { latest.pending.remove(op.key); await _write(subject, latest); } }); if (!_disposed) notifyListeners(); } _failures = 0; if (_failure != null) { _failure = null; notifyListeners(); } } catch (error) { if (_disposed || (attemptSubject != null && !_current(attemptSubject))) { return; } _failure = error; notifyListeners(); if (error == AccountFailure.denied || error == AccountFailure.rejected || error == AccountFailure.invalidResponse || error == AccountFailure.accountSetupRequired) { // Preserve intent but do not hammer a refused API until a new sign-in. _blockedSubject = account.account?.subject; } else if (_active && error != AccountFailure.signedOut) { final multiplier = 1 << (_failures++).clamp(0, 5); _retry = Timer(retryDelay * multiplier, trigger); } debugPrint('Account community sync deferred: $error'); } } @override void dispose() { _disposed = true; _retry?.cancel(); account.subjectChanges.removeListener(_sessionChanged); account.sessionChanges.removeListener(_sessionChanged); super.dispose(); } } class _SyncState { _SyncState({Map? observed, Map? pending}) : observed = observed ?? {}, pending = pending ?? {}; final Map observed; final Map pending; factory _SyncState.decode(String raw) { final value = jsonDecode(raw) as Map; return _SyncState( observed: (value['observed'] as Map?)?.cast() ?? {}, pending: (value['pending'] as Map).cast(), ); } String encode() => jsonEncode({'observed': observed, 'pending': pending}); }