import 'dart:async'; import 'dart:convert'; import '../utils/app_logger.dart'; import 'history_store.dart'; typedef HistoryPage = ({List messages, int start, int end, int total}); /// Archive bookkeeping, ordered writes and paging shared by the direct and /// channel message stores. Entries are JSON-encoded messages; the stored /// prefix older than the in-memory window stays in the [HistoryStore]. class HistoryArchive { HistoryArchive({required this.mergeKey, required this.maxEntries}); /// Identifies a stored entry so an unreconciled save can drop overlaps. final String Function(Map json) mergeKey; final int maxEntries; final Expando> _archives = Expando(); final Expando>> _writes = Expando(); _ArchiveState _stateFor(HistoryStore store, String key) => (_archives[store] ??= {}).putIfAbsent(key, () => _ArchiveState()); Future _serialize( HistoryStore store, String key, Future Function() operation, ) { final writes = _writes[store] ??= {}; final previous = writes[key] ?? Future.value(); final result = previous.then((_) => operation()); final completion = result.then( (_) {}, onError: (Object _, StackTrace _) {}, ); writes[key] = completion; unawaited( completion.whenComplete(() { if (identical(writes[key], completion)) writes.remove(key); }), ); return result; } /// Saves the [visible] window after the archived prefix. [readStored] /// supplies the stored JSON when the prefix is not reconciled yet; it /// defaults to the value under [key]. Future save( String key, List visible, { Future Function(HistoryStore store)? readStored, }) { final store = HistoryStore.instance; final state = _stateFor(store, key); final pendingBefore = state.nextId; return _serialize(store, key, () async { final pending = state.pending .where((entry) => entry.$1 < pendingBefore) .toList(); final tail = [...pending.map((entry) => entry.$2), ...visible]; final room = (maxEntries - visible.length).clamp(0, maxEntries); var preserved = state.persistedCount; if (preserved == null) { final raw = await (readStored?.call(store) ?? store.getString(key)); final prefix = _unreconciledPrefix(key, raw, tail); await store.replaceTail(key, 0, [ ...prefix, ...tail, ], maxEntries: maxEntries); preserved = (prefix.length + pending.length).clamp(0, room); } else { final remaining = await store.replaceTail( key, preserved, tail, maxEntries: maxEntries, ); preserved = remaining + pending.length.clamp(0, room); } state.persistedCount = preserved; state.pending.removeWhere((entry) => entry.$1 < pendingBefore); }); } /// Stored entries not repeated in [tail]. Unreadable stored history counts /// as empty, so it cannot block every later save. List _unreconciledPrefix(String key, String? raw, List tail) { if (raw == null || raw.isEmpty) return []; final Object? stored; try { stored = jsonDecode(raw); } on FormatException catch (error) { appLogger.warn('Saving over unreadable history $key: $error'); return []; } if (stored is! List) { appLogger.warn('Saving over history $key that is not a list'); return []; } final overlaps = {}; for (final entry in tail) { final id = mergeKey(jsonDecode(entry) as Map); overlaps[id] = (overlaps[id] ?? 0) + 1; } final kept = []; for (final entry in stored.reversed) { final id = entry is Map ? mergeKey(entry) : null; final remaining = id == null ? 0 : overlaps[id] ?? 0; if (remaining > 0) { overlaps[id!] = remaining - 1; } else { kept.add(jsonEncode(entry)); } } return kept.reversed.toList(); } void setArchivedCount(String key, int count) { RangeError.checkNotNegative(count, 'count'); (_archives[HistoryStore.instance] ??= {})[key] = _ArchiveState(count); } Future updateBookmarkFlag( String key, String messageId, bool isBookmarked, ) { final store = HistoryStore.instance; final state = _stateFor(store, key); return _serialize(store, key, () async { String? update(String raw) { try { final decoded = jsonDecode(raw); if (decoded is! Map || mergeKey(decoded) != 'id:$messageId') { return null; } decoded['isBookmarked'] = isBookmarked; return jsonEncode(decoded); } on FormatException { return null; } } for (var i = 0; i < state.pending.length; i++) { final entry = state.pending[i]; final replacement = update(entry.$2); if (replacement != null) state.pending[i] = (entry.$1, replacement); } final entries = await store.readEntries(key); var changed = false; final updated = []; for (final entry in entries) { final replacement = update(entry); updated.add(replacement ?? entry); changed = changed || replacement != null; } if (changed && !await store.setString( key, jsonEncode(updated.map(jsonDecode).toList()), )) { throw StateError('Could not update message bookmark flag'); } }); } /// Only entries trimmed since the last successful save need buffering. void archive(String key, Iterable entries) { final state = _stateFor(HistoryStore.instance, key); for (final entry in entries) { state.pending.add((state.nextId++, entry)); } } int? archivedCount(String key) { final state = _archives[HistoryStore.instance]?[key]; final count = state?.persistedCount; return count == null ? null : count + state!.pending.length; } void forget([String? key]) { final states = _archives[HistoryStore.instance]; if (key == null) { states?.clear(); } else { states?.remove(key); } } Future clear(HistoryStore store, String key) { final state = _ArchiveState(0); (_archives[store] ??= {})[key] = state; return _serialize(store, key, () async { if (!await store.remove(key)) { state.persistedCount = null; throw StateError('Could not clear message history'); } }); } /// Reads a page backwards using physical stored-row offsets, so entries /// [decode] skips do not make earlier valid history unreachable. Future> readPage( String key, int total, List Function(List entries) decode, { int? before, required int limit, }) async { final store = HistoryStore.instance; final end = (before ?? total).clamp(0, total); var start = end; var messages = []; while (start > 0 && messages.length < limit) { final batchSize = (limit - messages.length).clamp(0, start); final next = start - batchSize; final entries = await store.readEntries( key, offset: next, limit: batchSize, ); messages = [...decode(entries), ...messages]; start = next; } return (messages: messages, start: start, end: end, total: total); } } class _ArchiveState { _ArchiveState([this.persistedCount]); int? persistedCount; int nextId = 0; final List<(int, String)> pending = []; }