Store histories and the tile index in SQLite
Message, channel and route histories move from whole-blob preferences to indexed SQLite rows on native platforms, so chats page from storage instead of loading a full conversation. Web keeps the preferences store. Existing histories are imported once on the first launch. Linux and Windows keep the map tile index in SQLite and import the old JSON index on first use. Unreadable legacy data no longer blocks saves, migrations or startup: it is left in place and skipped. If the database cannot be opened, the run keeps histories in preferences and the next launch merges them in. Also adds a performance profiling reference and a script that clears the Dart HTTP profile.
This commit is contained in:
1 parent
0106569e7d
commit
2d56d5e349
47 files changed
+4465
-614
No files matched your search
@@ -6,7 +6,8 @@ import '../models/channel_message.dart';
|
||||
import '../models/message.dart' show legacyAwareReceivedAt;
|
||||
import '../models/translation_support.dart';
|
||||
import '../helpers/smaz.dart';
|
||||
import 'prefs_manager.dart';
|
||||
import 'history_archive.dart';
|
||||
import 'history_store.dart';
|
||||
|
||||
class ChannelMessageStore {
|
||||
static const String _keyPrefix = 'channel_messages_';
|
||||
@@ -21,153 +22,117 @@ class ChannelMessageStore {
|
||||
/// beyond it are dropped on save.
|
||||
static const int maxStoredMessages = 1000;
|
||||
|
||||
/// Encoded entries persisted ahead of the connector's in-memory window,
|
||||
/// keyed by scoped storage key. A missing entry means the window has not
|
||||
/// been reconciled with storage yet, so the next save keeps what is already
|
||||
/// stored instead of replacing it. Shared across instances so a store
|
||||
/// created by a screen to clear a key also resets the connector's view.
|
||||
static final Map<String, List<String>> _archived = {};
|
||||
static final HistoryArchive _archive = HistoryArchive(
|
||||
mergeKey: _storedMergeKey,
|
||||
maxEntries: maxStoredMessages,
|
||||
);
|
||||
|
||||
String _keyForChannel(String channelId) => '${keyFor}_$channelId';
|
||||
|
||||
/// Save messages for a specific channel: [messages] is the in-memory
|
||||
/// window (oldest first) and is written after the archived entries that
|
||||
/// sit ahead of it in storage.
|
||||
Future<void> saveChannelMessages(
|
||||
String channelId,
|
||||
List<ChannelMessage> messages,
|
||||
) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot save channel messages.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = _keyForChannel(channelId);
|
||||
final visibleJson = messages.map(_messageToJson).toList();
|
||||
final archived =
|
||||
_archived[key] ??
|
||||
_unreconciledArchive(prefs.getString(key), visibleJson);
|
||||
final overflow = archived.length + visibleJson.length - maxStoredMessages;
|
||||
if (overflow > 0) {
|
||||
archived.removeRange(0, overflow.clamp(0, archived.length));
|
||||
}
|
||||
_archived[key] = archived;
|
||||
final entries = [...archived, ...visibleJson.map(jsonEncode)];
|
||||
await prefs.setString(key, '[${entries.join(',')}]');
|
||||
}
|
||||
|
||||
/// Records [olderMessages] as the stored entries that precede the
|
||||
/// in-memory window for [channelId].
|
||||
void setArchived(String channelId, List<ChannelMessage> olderMessages) {
|
||||
_archived[_keyForChannel(channelId)] = olderMessages
|
||||
.map((message) => jsonEncode(_messageToJson(message)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Number of stored entries ahead of the in-memory window, or null when
|
||||
/// the window has not been reconciled with storage.
|
||||
int? archivedCount(String channelId) =>
|
||||
_archived[_keyForChannel(channelId)]?.length;
|
||||
|
||||
/// Removes the newest [count] archived entries after they were paged back
|
||||
/// into the in-memory window.
|
||||
void unarchiveNewest(String channelId, int count) {
|
||||
final archived = _archived[_keyForChannel(channelId)];
|
||||
if (archived == null || count <= 0) return;
|
||||
archived.removeRange(
|
||||
(archived.length - count).clamp(0, archived.length),
|
||||
archived.length,
|
||||
);
|
||||
}
|
||||
|
||||
/// Drops the archive bookkeeping, for one channel or all of them, when the
|
||||
/// matching in-memory window is discarded.
|
||||
void forgetArchive([String? channelId]) {
|
||||
if (channelId == null) {
|
||||
_archived.clear();
|
||||
} else {
|
||||
_archived.remove(_keyForChannel(channelId));
|
||||
}
|
||||
}
|
||||
|
||||
List<String> _unreconciledArchive(
|
||||
String? storedJson,
|
||||
List<Map<String, dynamic>> visibleJson,
|
||||
) {
|
||||
if (storedJson == null || storedJson.isEmpty) return [];
|
||||
final List<dynamic> stored;
|
||||
try {
|
||||
stored = jsonDecode(storedJson) as List<dynamic>;
|
||||
} catch (_) {
|
||||
return [];
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn('Public key hex is not set. Cannot save messages.');
|
||||
return Future<void>.value();
|
||||
}
|
||||
final visibleKeys = visibleJson.map(_storedMergeKey).toSet();
|
||||
return [
|
||||
for (final entry in stored)
|
||||
if (entry is Map<String, dynamic> &&
|
||||
!visibleKeys.contains(_storedMergeKey(entry)))
|
||||
jsonEncode(entry),
|
||||
];
|
||||
return _archive.save(_keyForChannel(channelId), [
|
||||
for (final message in messages) jsonEncode(_messageToJson(message)),
|
||||
]);
|
||||
}
|
||||
|
||||
/// The stored prefix stays in the database, rather than another JSON cache.
|
||||
void setArchivedCount(String channelId, int count) =>
|
||||
_archive.setArchivedCount(_keyForChannel(channelId), count);
|
||||
|
||||
void archive(String channelId, List<ChannelMessage> messages) =>
|
||||
_archive.archive(
|
||||
_keyForChannel(channelId),
|
||||
messages.map((message) => jsonEncode(_messageToJson(message))),
|
||||
);
|
||||
|
||||
int? archivedCount(String channelId) =>
|
||||
_archive.archivedCount(_keyForChannel(channelId));
|
||||
|
||||
void forgetArchive([String? channelId]) =>
|
||||
_archive.forget(channelId == null ? null : _keyForChannel(channelId));
|
||||
|
||||
static String _storedMergeKey(Map<String, dynamic> json) {
|
||||
final messageId = json['messageId'];
|
||||
if (messageId is String && messageId.isNotEmpty) return 'id:$messageId';
|
||||
return 'fallback:${json['timestamp']}:${json['senderName']}:${json['text']}';
|
||||
}
|
||||
|
||||
/// Load messages for a specific channel
|
||||
Future<List<ChannelMessage>> loadChannelMessages(String channelId) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn(
|
||||
'Public key hex is not set. Cannot load channel messages.',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
final jsonString = PrefsManager.instance.getString(
|
||||
_keyForChannel(channelId),
|
||||
);
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
return [];
|
||||
}
|
||||
final List<dynamic> jsonList;
|
||||
Future<List<ChannelMessage>> loadChannelMessages(
|
||||
String channelId, {
|
||||
int offset = 0,
|
||||
int? limit,
|
||||
}) async {
|
||||
if (publicKeyHex.isEmpty) return [];
|
||||
final key = _keyForChannel(channelId);
|
||||
try {
|
||||
jsonList = jsonDecode(jsonString) as List<dynamic>;
|
||||
} catch (e) {
|
||||
final entries = await HistoryStore.instance.readEntries(
|
||||
key,
|
||||
offset: offset,
|
||||
limit: limit,
|
||||
);
|
||||
return _decodeMessages(entries);
|
||||
} catch (error) {
|
||||
appLogger.warn(
|
||||
'Stored messages for channel $channelId are unreadable: $e',
|
||||
'Stored messages for channel $channelId are unreadable: $error',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<({List<ChannelMessage> messages, int start, int end, int total})>
|
||||
loadMessagePage(String channelId, {int? before, int limit = 50}) async {
|
||||
RangeError.checkNotNegative(limit, 'limit');
|
||||
if (publicKeyHex.isEmpty) {
|
||||
return (messages: <ChannelMessage>[], start: 0, end: 0, total: 0);
|
||||
}
|
||||
final key = _keyForChannel(channelId);
|
||||
try {
|
||||
return await _archive.readPage(
|
||||
key,
|
||||
await HistoryStore.instance.entryCount(key),
|
||||
_decodeMessages,
|
||||
before: before,
|
||||
limit: limit,
|
||||
);
|
||||
} on FormatException catch (error) {
|
||||
appLogger.warn(
|
||||
'Stored messages for channel $channelId are unreadable: $error',
|
||||
);
|
||||
return (messages: <ChannelMessage>[], start: 0, end: 0, total: 0);
|
||||
}
|
||||
}
|
||||
|
||||
List<ChannelMessage> _decodeMessages(List<String> entries) {
|
||||
final messages = <ChannelMessage>[];
|
||||
for (final json in jsonList) {
|
||||
for (final entry in entries) {
|
||||
try {
|
||||
messages.add(_messageFromJson(json as Map<String, dynamic>));
|
||||
} catch (e) {
|
||||
appLogger.warn('Skipping malformed stored channel message: $e');
|
||||
messages.add(
|
||||
_messageFromJson(jsonDecode(entry) as Map<String, dynamic>),
|
||||
);
|
||||
} catch (error) {
|
||||
appLogger.warn('Skipping malformed stored channel message: $error');
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
/// Clear messages for a specific channel
|
||||
Future<void> clearChannelMessages(String channelId) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = _keyForChannel(channelId);
|
||||
_archived[key] = [];
|
||||
await prefs.remove(key);
|
||||
}
|
||||
Future<void> clearChannelMessages(String channelId) =>
|
||||
_archive.clear(HistoryStore.instance, _keyForChannel(channelId));
|
||||
|
||||
/// Clear all channel messages
|
||||
Future<void> clearAllChannelMessages() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final keys = prefs.getKeys().where((k) => k.startsWith(keyFor)).toList();
|
||||
_archived.clear();
|
||||
for (var key in keys) {
|
||||
await prefs.remove(key);
|
||||
}
|
||||
final store = HistoryStore.instance;
|
||||
final prefix = keyFor;
|
||||
final keys = (await store.getKeys())
|
||||
.where((key) => key.startsWith(prefix))
|
||||
.toList();
|
||||
await Future.wait(keys.map((key) => _archive.clear(store, key)));
|
||||
}
|
||||
|
||||
/// Convert ChannelMessage to JSON map
|
||||
|
||||
@@ -5,13 +5,15 @@ import 'channel_message_store.dart';
|
||||
import 'channel_store.dart';
|
||||
import 'legacy_key_migration.dart';
|
||||
import 'prefs_manager.dart';
|
||||
import 'history_store.dart';
|
||||
|
||||
/// One-shot move of a radio's per-channel data from slot-index keys
|
||||
/// (`<prefix><scope><slot>`) to channel-ID keys (`<prefix><scope>_<id>`).
|
||||
///
|
||||
/// The slot -> PSK mapping comes from the radio's cached channel list, which is
|
||||
/// the mapping the legacy data was written under. Legacy keys of slots with no
|
||||
/// cached PSK are left alone and never read again.
|
||||
/// cached PSK are left alone and never read again, and so is a legacy history
|
||||
/// that cannot be parsed.
|
||||
class ChannelStorageMigration {
|
||||
static const String _doneKeyPrefix = 'channel_storage_v2_';
|
||||
|
||||
@@ -70,8 +72,8 @@ class ChannelStorageMigration {
|
||||
await _migrateOrder(scope, slotIds);
|
||||
if (slotIds.isNotEmpty) await beforeDone?.call(slotIds);
|
||||
|
||||
await prefs.setBool(doneKey, true);
|
||||
await channelStore.saveSlotChannelIds(slotIds);
|
||||
await _requireWrite(prefs.setBool(doneKey, true));
|
||||
if (slotIds.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Moved channel data for ${slotIds.length} slots of $scope to channel IDs',
|
||||
@@ -81,38 +83,60 @@ class ChannelStorageMigration {
|
||||
}
|
||||
|
||||
static Future<void> _moveMessages(String scope, int slot, String id) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final prefs = HistoryStore.instance;
|
||||
final oldKey = '$_messagesPrefix$scope$slot';
|
||||
final legacyKey = '$_messagesPrefix$slot';
|
||||
final newKey = '$_messagesPrefix${scope}_$id';
|
||||
var json = prefs.getString(oldKey);
|
||||
if (json == null || json.isEmpty) json = prefs.getString(legacyKey);
|
||||
var json = await prefs.getString(oldKey);
|
||||
if (json == null || json.isEmpty) json = await prefs.getString(legacyKey);
|
||||
if (json != null && json.isNotEmpty) {
|
||||
final existing = prefs.getString(newKey);
|
||||
// Two slots holding the same PSK now share one history.
|
||||
await prefs.setString(
|
||||
newKey,
|
||||
existing == null || existing.isEmpty
|
||||
final String moved;
|
||||
try {
|
||||
if (jsonDecode(json) is! List) {
|
||||
throw const FormatException('Channel history is not an array');
|
||||
}
|
||||
final existing = await prefs.getString(newKey);
|
||||
// Two slots holding the same PSK now share one history.
|
||||
moved = existing == null || existing.isEmpty
|
||||
? json
|
||||
: _mergeMessages(existing, json),
|
||||
);
|
||||
: _mergeMessages(existing, json);
|
||||
} on FormatException catch (error) {
|
||||
// One unreadable history must not hold back the other slots. It
|
||||
// stays under its old key, which nothing reads again.
|
||||
appLogger.warn(
|
||||
'Leaving unreadable channel history of slot $slot in place: $error',
|
||||
);
|
||||
return;
|
||||
}
|
||||
await _requireWrite(prefs.setString(newKey, moved));
|
||||
}
|
||||
// Old keys go only after the new one is written, so an interrupted run
|
||||
// loses nothing; the next launch repeats it.
|
||||
await prefs.remove(oldKey);
|
||||
await prefs.remove(legacyKey);
|
||||
await _requireWrite(prefs.remove(oldKey));
|
||||
await _requireWrite(prefs.remove(legacyKey));
|
||||
}
|
||||
|
||||
static String _mergeMessages(String a, String b) {
|
||||
try {
|
||||
// A rerun after an interrupted migration merges a history into
|
||||
// itself, so drop entries already present.
|
||||
final existing = jsonDecode(a);
|
||||
final incoming = jsonDecode(b);
|
||||
if (existing is! List ||
|
||||
incoming is! List ||
|
||||
![
|
||||
...existing,
|
||||
...incoming,
|
||||
].every((entry) => entry is Map<String, dynamic>)) {
|
||||
throw const FormatException(
|
||||
'Cannot merge unreadable channel histories',
|
||||
);
|
||||
}
|
||||
final seen = <String>{};
|
||||
final merged =
|
||||
[...jsonDecode(a) as List<dynamic>, ...jsonDecode(b) as List<dynamic>]
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.where((m) => seen.add(_mergeKey(m)))
|
||||
.toList();
|
||||
final merged = [...existing, ...incoming]
|
||||
.cast<Map<String, dynamic>>()
|
||||
.where((m) => seen.add(_mergeKey(m)))
|
||||
.toList();
|
||||
merged.sort(
|
||||
(x, y) => ((x['timestamp'] as int?) ?? 0).compareTo(
|
||||
(y['timestamp'] as int?) ?? 0,
|
||||
@@ -122,7 +146,7 @@ class ChannelStorageMigration {
|
||||
if (overflow > 0) merged.removeRange(0, overflow);
|
||||
return jsonEncode(merged);
|
||||
} catch (_) {
|
||||
return a;
|
||||
throw const FormatException('Cannot merge unreadable channel histories');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,19 +169,19 @@ class ChannelStorageMigration {
|
||||
var value = prefs.get(oldKey);
|
||||
if (value == null && legacyKey != null) value = prefs.get(legacyKey);
|
||||
if (value is bool && !prefs.containsKey(newKey)) {
|
||||
await prefs.setBool(newKey, value);
|
||||
await _requireWrite(prefs.setBool(newKey, value));
|
||||
}
|
||||
await prefs.remove(oldKey);
|
||||
if (legacyKey != null) await prefs.remove(legacyKey);
|
||||
await _removeIfPresent(oldKey);
|
||||
if (legacyKey != null) await _removeIfPresent(legacyKey);
|
||||
}
|
||||
|
||||
static Future<void> _moveString(String oldKey, String newKey) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final value = prefs.get(oldKey);
|
||||
if (value is String && !prefs.containsKey(newKey)) {
|
||||
await prefs.setString(newKey, value);
|
||||
await _requireWrite(prefs.setString(newKey, value));
|
||||
}
|
||||
await prefs.remove(oldKey);
|
||||
await _removeIfPresent(oldKey);
|
||||
}
|
||||
|
||||
static Future<void> _migrateOrder(
|
||||
@@ -188,7 +212,18 @@ class ChannelStorageMigration {
|
||||
final id = slotIds[slot];
|
||||
if (id != null && !ids.contains(id)) ids.add(id);
|
||||
}
|
||||
await prefs.setString(key, jsonEncode(ids));
|
||||
await prefs.remove(_orderPrefix);
|
||||
await _requireWrite(prefs.setString(key, jsonEncode(ids)));
|
||||
await _removeIfPresent(_orderPrefix);
|
||||
}
|
||||
|
||||
static Future<void> _removeIfPresent(String key) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
if (prefs.containsKey(key)) await prefs.remove(key);
|
||||
}
|
||||
|
||||
static Future<void> _requireWrite(Future<bool> write) async {
|
||||
if (!await write) {
|
||||
throw StateError('Could not persist channel storage migration');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,16 +24,7 @@ class ChannelStore {
|
||||
String? jsonString = prefs.getString(keyFor);
|
||||
if ((jsonString == null || jsonString.isEmpty) &&
|
||||
canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
final legacyJsonString = prefs.getString(_keyPrefix);
|
||||
prefs.remove(_keyPrefix);
|
||||
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Migrating channel messages from legacy key $_keyPrefix to scoped key $keyFor',
|
||||
);
|
||||
await prefs.setString(keyFor, legacyJsonString);
|
||||
jsonString = legacyJsonString;
|
||||
}
|
||||
jsonString = await migrateLegacyStringPreference(_keyPrefix, keyFor);
|
||||
}
|
||||
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
@@ -97,10 +88,11 @@ class ChannelStore {
|
||||
|
||||
Future<void> saveSlotChannelIds(Map<int, String> ids) async {
|
||||
if (publicKeyHex.isEmpty) return;
|
||||
await PrefsManager.instance.setString(
|
||||
final saved = await PrefsManager.instance.setString(
|
||||
_slotIdsKey,
|
||||
jsonEncode({for (final e in ids.entries) '${e.key}': e.value}),
|
||||
);
|
||||
if (!saved) throw StateError('Could not persist channel slot map');
|
||||
}
|
||||
|
||||
Map<String, dynamic> _toJson(Channel channel) {
|
||||
|
||||
@@ -29,16 +29,7 @@ class CommunityStore {
|
||||
String? jsonString = prefs.getString(keyFor);
|
||||
if ((jsonString == null || jsonString.isEmpty) &&
|
||||
canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
final legacyJsonString = prefs.getString(_keyPrefix);
|
||||
prefs.remove(_keyPrefix);
|
||||
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Migrating communities from legacy key $_keyPrefix to scoped key $keyFor',
|
||||
);
|
||||
await prefs.setString(keyFor, legacyJsonString);
|
||||
jsonString = legacyJsonString;
|
||||
}
|
||||
jsonString = await migrateLegacyStringPreference(_keyPrefix, keyFor);
|
||||
}
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
jsonString = prefs.getString(keyFor);
|
||||
|
||||
@@ -20,11 +20,7 @@ class ContactDiscoveryStore {
|
||||
final prefs = PrefsManager.instance;
|
||||
var jsonStr = prefs.getString(keyFor);
|
||||
if (jsonStr == null && canMigrateLegacyKeys(publicKeyHex)) {
|
||||
jsonStr = prefs.getString(_keyPrefix);
|
||||
if (jsonStr != null) {
|
||||
await prefs.setString(keyFor, jsonStr);
|
||||
await prefs.remove(_keyPrefix);
|
||||
}
|
||||
jsonStr = await migrateLegacyStringPreference(_keyPrefix, keyFor);
|
||||
}
|
||||
if (jsonStr == null) return [];
|
||||
|
||||
|
||||
@@ -22,16 +22,7 @@ class ContactGroupStore {
|
||||
String? jsonString = prefs.getString(keyFor);
|
||||
if ((jsonString == null || jsonString.isEmpty) &&
|
||||
canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
final legacyJsonString = prefs.getString(_keyPrefix);
|
||||
prefs.remove(_keyPrefix);
|
||||
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Migrating channel messages from legacy key $_keyPrefix to scoped key $keyFor',
|
||||
);
|
||||
await prefs.setString(keyFor, legacyJsonString);
|
||||
jsonString = legacyJsonString;
|
||||
}
|
||||
jsonString = await migrateLegacyStringPreference(_keyPrefix, keyFor);
|
||||
}
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
jsonString = prefs.getString(keyFor);
|
||||
|
||||
@@ -29,15 +29,16 @@ class ContactSettingsStore {
|
||||
if (enabled == null && canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
enabled = prefs.getBool(oldKey);
|
||||
prefs.remove(oldKey);
|
||||
if (enabled != null) {
|
||||
appLogger.info(
|
||||
'Migrating contact settings from legacy key $oldKey to scoped key $key',
|
||||
);
|
||||
await prefs.setBool(key, enabled);
|
||||
if (await prefs.setBool(key, enabled)) {
|
||||
await prefs.remove(oldKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
return prefs.getBool(key) ?? false;
|
||||
return enabled ?? false;
|
||||
}
|
||||
|
||||
Future<void> saveSmazEnabled(String contactKeyHex, bool enabled) async {
|
||||
|
||||
@@ -24,16 +24,7 @@ class ContactStore {
|
||||
String? jsonString = prefs.getString(keyFor);
|
||||
if ((jsonString == null || jsonString.isEmpty) &&
|
||||
canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
final legacyJsonString = prefs.getString(_keyPrefix);
|
||||
prefs.remove(_keyPrefix);
|
||||
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Migrating contacts from legacy key $_keyPrefix to scoped key $keyFor',
|
||||
);
|
||||
await prefs.setString(keyFor, legacyJsonString);
|
||||
jsonString = legacyJsonString;
|
||||
}
|
||||
jsonString = await migrateLegacyStringPreference(_keyPrefix, keyFor);
|
||||
}
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
jsonString = prefs.getString(keyFor);
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import '../utils/app_logger.dart';
|
||||
import 'history_store.dart';
|
||||
|
||||
typedef HistoryPage<T> = ({List<T> 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<String, dynamic> json) mergeKey;
|
||||
final int maxEntries;
|
||||
|
||||
final Expando<Map<String, _ArchiveState>> _archives = Expando();
|
||||
final Expando<Map<String, Future<void>>> _writes = Expando();
|
||||
|
||||
_ArchiveState _stateFor(HistoryStore store, String key) =>
|
||||
(_archives[store] ??= {}).putIfAbsent(key, () => _ArchiveState());
|
||||
|
||||
Future<void> _serialize(
|
||||
HistoryStore store,
|
||||
String key,
|
||||
Future<void> Function() operation,
|
||||
) {
|
||||
final writes = _writes[store] ??= {};
|
||||
final previous = writes[key] ?? Future<void>.value();
|
||||
final result = previous.then((_) => operation());
|
||||
final completion = result.then<void>(
|
||||
(_) {},
|
||||
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<void> save(
|
||||
String key,
|
||||
List<String> visible, {
|
||||
Future<String?> 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<String> _unreconciledPrefix(String key, String? raw, List<String> 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 = <String, int>{};
|
||||
for (final entry in tail) {
|
||||
final id = mergeKey(jsonDecode(entry) as Map<String, dynamic>);
|
||||
overlaps[id] = (overlaps[id] ?? 0) + 1;
|
||||
}
|
||||
final kept = <String>[];
|
||||
for (final entry in stored.reversed) {
|
||||
final id = entry is Map<String, dynamic> ? 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);
|
||||
}
|
||||
|
||||
/// Only entries trimmed since the last successful save need buffering.
|
||||
void archive(String key, Iterable<String> 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<void> 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<HistoryPage<T>> readPage<T>(
|
||||
String key,
|
||||
int total,
|
||||
List<T> Function(List<String> entries) decode, {
|
||||
int? before,
|
||||
required int limit,
|
||||
}) async {
|
||||
final store = HistoryStore.instance;
|
||||
final end = (before ?? total).clamp(0, total);
|
||||
var start = end;
|
||||
var messages = <T>[];
|
||||
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 = [];
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../utils/app_logger.dart';
|
||||
import 'history_store_stub.dart'
|
||||
if (dart.library.io) 'history_store_io.dart'
|
||||
as platform;
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
/// Histories use an indexed native store; preferences remain the web backend.
|
||||
abstract class HistoryStore {
|
||||
static HistoryStore _instance = PreferencesHistoryStore();
|
||||
static HistoryStore get instance => _instance;
|
||||
|
||||
static bool isHistoryKey(String key) =>
|
||||
key.startsWith('messages_') ||
|
||||
key.startsWith('channel_messages_') ||
|
||||
key.startsWith('path_history_');
|
||||
|
||||
static bool isSequenceKey(String key) =>
|
||||
key.startsWith('messages_') || key.startsWith('channel_messages_');
|
||||
|
||||
/// Set while a run had to keep histories in preferences because the
|
||||
/// database could not be opened; the next launch that opens it merges them.
|
||||
static const String fallbackRunKey = 'history_fallback_run';
|
||||
|
||||
/// Never throws: a database that cannot be opened must not keep the app
|
||||
/// from starting, so this run keeps histories in preferences instead.
|
||||
static Future<void> initialize() async {
|
||||
try {
|
||||
_instance = await platform.createHistoryStore();
|
||||
} catch (error) {
|
||||
// The app logger is not set up this early.
|
||||
debugPrint('History database unavailable: $error');
|
||||
_instance = PreferencesHistoryStore();
|
||||
await PrefsManager.instance.setBool(fallbackRunKey, true);
|
||||
}
|
||||
}
|
||||
|
||||
static void use(HistoryStore store) => _instance = store;
|
||||
static void reset() => _instance = PreferencesHistoryStore();
|
||||
|
||||
Future<String?> getString(String key);
|
||||
Future<bool> setString(String key, String value);
|
||||
Future<bool> remove(String key);
|
||||
Future<Set<String>> getKeys();
|
||||
Future<int> entryCount(String key);
|
||||
Future<List<String>> readEntries(String key, {int offset = 0, int? limit});
|
||||
|
||||
/// Replaces the visible tail, preserving the first [preservedCount] entries.
|
||||
/// Returns the number of preserved entries remaining after the storage cap.
|
||||
Future<int> replaceTail(
|
||||
String key,
|
||||
int preservedCount,
|
||||
List<String> entries, {
|
||||
int maxEntries = 1000,
|
||||
});
|
||||
|
||||
Future<void> close() async {}
|
||||
}
|
||||
|
||||
class PreferencesHistoryStore extends HistoryStore {
|
||||
SharedPreferences? _preferences;
|
||||
SharedPreferences get _prefs => _preferences ??= PrefsManager.instance;
|
||||
@override
|
||||
Future<String?> getString(String key) async => _prefs.getString(key);
|
||||
|
||||
@override
|
||||
Future<bool> setString(String key, String value) =>
|
||||
_prefs.setString(key, value);
|
||||
|
||||
@override
|
||||
Future<bool> remove(String key) async {
|
||||
final prefs = _prefs;
|
||||
return !prefs.containsKey(key) || await prefs.remove(key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Set<String>> getKeys() async =>
|
||||
_prefs.getKeys().where(HistoryStore.isHistoryKey).toSet();
|
||||
|
||||
/// Encoded entries of recently used histories, so paging and saves do not
|
||||
/// re-parse the blob or re-encode the preserved prefix each time. An entry
|
||||
/// is used only while the stored string is the one it was split from.
|
||||
static const int _maxDecoded = 8;
|
||||
final Map<String, (String, List<String>)> _decoded = {};
|
||||
|
||||
Future<List<String>> _entries(String key) async {
|
||||
final raw = await getString(key);
|
||||
if (raw == null || raw.isEmpty) return const [];
|
||||
final cached = _decoded[key];
|
||||
if (cached != null && cached.$1 == raw) return cached.$2;
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! List) throw const FormatException('Expected message array');
|
||||
return _remember(key, raw, decoded.map(jsonEncode).toList());
|
||||
}
|
||||
|
||||
List<String> _remember(String key, String raw, List<String> entries) {
|
||||
_decoded.remove(key);
|
||||
_decoded[key] = (raw, entries);
|
||||
if (_decoded.length > _maxDecoded) _decoded.remove(_decoded.keys.first);
|
||||
return entries;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<String>> readEntries(
|
||||
String key, {
|
||||
int offset = 0,
|
||||
int? limit,
|
||||
}) async {
|
||||
RangeError.checkNotNegative(offset, 'offset');
|
||||
if (limit != null) RangeError.checkNotNegative(limit, 'limit');
|
||||
final selected = (await _entries(key)).skip(offset);
|
||||
return (limit == null ? selected : selected.take(limit)).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> entryCount(String key) async => (await _entries(key)).length;
|
||||
|
||||
@override
|
||||
Future<int> replaceTail(
|
||||
String key,
|
||||
int preservedCount,
|
||||
List<String> entries, {
|
||||
int maxEntries = 1000,
|
||||
}) async {
|
||||
RangeError.checkNotNegative(preservedCount, 'preservedCount');
|
||||
RangeError.checkNotNegative(maxEntries, 'maxEntries');
|
||||
List<String> previous;
|
||||
try {
|
||||
previous = (await _entries(key)).take(preservedCount).toList();
|
||||
} on FormatException catch (error) {
|
||||
// Preferences hold one value per key, so the save replaces it.
|
||||
appLogger.warn('Replacing unreadable history $key: $error');
|
||||
previous = [];
|
||||
}
|
||||
final combined = [...previous, ...entries];
|
||||
final overflow = (combined.length - maxEntries).clamp(0, combined.length);
|
||||
final kept = combined.sublist(overflow);
|
||||
final raw = '[${kept.join(',')}]';
|
||||
if (!await setString(key, raw)) {
|
||||
throw StateError('Could not save message history');
|
||||
}
|
||||
_remember(key, raw, kept);
|
||||
return (previous.length - overflow).clamp(0, previous.length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
|
||||
import 'package:shared_preferences_platform_interface/types.dart';
|
||||
import 'package:sqflite/sqflite.dart' as sqlite;
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart' as ffi;
|
||||
|
||||
import '../utils/app_logger.dart';
|
||||
import 'history_store.dart';
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
Future<HistoryStore> createHistoryStore() async {
|
||||
final directory = await getApplicationSupportDirectory();
|
||||
if (Platform.isLinux || Platform.isWindows) ffi.sqfliteFfiInit();
|
||||
final store = await SqliteHistoryStore.open(
|
||||
'${directory.path}${Platform.pathSeparator}history_v1.db',
|
||||
factory: Platform.isLinux || Platform.isWindows
|
||||
? ffi.databaseFactoryFfi
|
||||
: sqlite.databaseFactory,
|
||||
);
|
||||
// The database is usable even when an import step fails: reads fall back
|
||||
// to preferences for keys it does not hold, and the step repeats next launch.
|
||||
try {
|
||||
final prefs = PrefsManager.instance;
|
||||
if (prefs.getBool(HistoryStore.fallbackRunKey) == true) {
|
||||
await store.adoptFallbackHistories();
|
||||
await prefs.remove(HistoryStore.fallbackRunKey);
|
||||
}
|
||||
await store.migratePreferences();
|
||||
} catch (error) {
|
||||
// The app logger is not set up this early.
|
||||
debugPrint('History import incomplete: $error');
|
||||
}
|
||||
return store;
|
||||
}
|
||||
|
||||
class SqliteHistoryStore extends HistoryStore {
|
||||
SqliteHistoryStore._(this.database);
|
||||
|
||||
static const schemaVersion = 1;
|
||||
final sqlite.Database database;
|
||||
|
||||
static Future<SqliteHistoryStore> open(
|
||||
String path, {
|
||||
required sqlite.DatabaseFactory factory,
|
||||
}) async {
|
||||
final database = await factory.openDatabase(
|
||||
path,
|
||||
options: sqlite.OpenDatabaseOptions(
|
||||
version: schemaVersion,
|
||||
onConfigure: (db) => db.execute('PRAGMA foreign_keys = ON'),
|
||||
onCreate: (db, version) async {
|
||||
await db.execute(
|
||||
'CREATE TABLE history_keys (key TEXT PRIMARY KEY, value TEXT)',
|
||||
);
|
||||
await db.execute(
|
||||
'CREATE TABLE history_entries ('
|
||||
'key TEXT NOT NULL REFERENCES history_keys(key) ON DELETE CASCADE, '
|
||||
'position INTEGER NOT NULL, value TEXT NOT NULL, '
|
||||
'PRIMARY KEY (key, position))',
|
||||
);
|
||||
await db.execute(
|
||||
'CREATE TABLE history_metadata (key TEXT PRIMARY KEY, value INTEGER NOT NULL)',
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
return SqliteHistoryStore._(database);
|
||||
}
|
||||
|
||||
Future<void> migratePreferences() async {
|
||||
final versions = await database.query(
|
||||
'history_metadata',
|
||||
where: 'key = ?',
|
||||
whereArgs: ['preferences_import_version'],
|
||||
);
|
||||
final version = versions.isEmpty ? null : versions.first['value'] as int;
|
||||
if (version != null && version >= schemaVersion) return;
|
||||
|
||||
final prefs = PrefsManager.instance;
|
||||
final imported = <String>{};
|
||||
for (final key in prefs.getKeys().where(HistoryStore.isHistoryKey)) {
|
||||
final value = prefs.get(key);
|
||||
if (value is! String || value.isEmpty) continue;
|
||||
try {
|
||||
final decoded = jsonDecode(value);
|
||||
if (HistoryStore.isSequenceKey(key)
|
||||
? decoded is! List
|
||||
: decoded is! Map) {
|
||||
continue;
|
||||
}
|
||||
} on FormatException {
|
||||
appLogger.warn('Leaving unreadable history $key in preferences');
|
||||
continue;
|
||||
}
|
||||
// Rows from an interrupted earlier import may have been saved to since.
|
||||
if ((await _header(key)).isEmpty) await setString(key, value);
|
||||
imported.add(key);
|
||||
}
|
||||
if (imported.isNotEmpty) {
|
||||
final removed = await SharedPreferencesStorePlatform.instance
|
||||
.clearWithParameters(
|
||||
ClearParameters(
|
||||
filter: PreferencesFilter(
|
||||
prefix: 'flutter.',
|
||||
allowList: imported.map((key) => 'flutter.$key').toSet(),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!removed) throw StateError('Could not finish history migration');
|
||||
await prefs.reload();
|
||||
}
|
||||
await database.insert('history_metadata', {
|
||||
'key': 'preferences_import_version',
|
||||
'value': schemaVersion,
|
||||
}, conflictAlgorithm: sqlite.ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
/// Merges histories that a run without the database saved to preferences.
|
||||
/// That run could not see the database rows, so its message lists hold
|
||||
/// what it saved itself and are appended; a message it rewrote replaces the
|
||||
/// stored copy. Route histories already in the database are kept.
|
||||
Future<void> adoptFallbackHistories() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final keys = prefs.getKeys().where(HistoryStore.isHistoryKey).toList();
|
||||
for (final key in keys) {
|
||||
final value = prefs.get(key);
|
||||
if (value is! String || value.isEmpty) continue;
|
||||
final sequence = HistoryStore.isSequenceKey(key);
|
||||
final Object? decoded;
|
||||
try {
|
||||
decoded = jsonDecode(value);
|
||||
} on FormatException {
|
||||
continue;
|
||||
}
|
||||
if (sequence ? decoded is! List : decoded is! Map) continue;
|
||||
if ((await _header(key)).isEmpty) {
|
||||
await setString(key, value);
|
||||
} else if (sequence) {
|
||||
final merged = await readEntries(key);
|
||||
final positions = {
|
||||
for (var i = 0; i < merged.length; i++) _entryId(merged[i]): i,
|
||||
};
|
||||
for (final entry in (decoded as List).map(jsonEncode)) {
|
||||
final id = _entryId(entry);
|
||||
final position = positions[id];
|
||||
if (position == null) {
|
||||
positions[id] = merged.length;
|
||||
merged.add(entry);
|
||||
} else {
|
||||
merged[position] = entry;
|
||||
}
|
||||
}
|
||||
await replaceTail(key, 0, merged);
|
||||
}
|
||||
if (!await prefs.remove(key)) {
|
||||
throw StateError('Could not finish merging fallback histories');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String _entryId(String entry) {
|
||||
final decoded = jsonDecode(entry);
|
||||
final id = decoded is Map ? decoded['messageId'] : null;
|
||||
return id is String && id.isNotEmpty ? 'id:$id' : entry;
|
||||
}
|
||||
|
||||
Future<List<Map<String, Object?>>> _header(String key) => database.query(
|
||||
'history_keys',
|
||||
columns: ['value'],
|
||||
where: 'key = ?',
|
||||
whereArgs: [key],
|
||||
);
|
||||
|
||||
@override
|
||||
Future<String?> getString(String key) async {
|
||||
final header = await _header(key);
|
||||
if (header.isEmpty) return PrefsManager.instance.getString(key);
|
||||
final scalar = header.first['value'];
|
||||
if (scalar is String) return scalar;
|
||||
return '[${(await readEntries(key)).join(',')}]';
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> setString(String key, String value) async {
|
||||
final entries = HistoryStore.isSequenceKey(key)
|
||||
? (jsonDecode(value) as List).map(jsonEncode).toList()
|
||||
: null;
|
||||
await database.transaction((txn) async {
|
||||
await txn.insert('history_keys', {
|
||||
'key': key,
|
||||
'value': entries == null ? value : null,
|
||||
}, conflictAlgorithm: sqlite.ConflictAlgorithm.replace);
|
||||
if (entries != null) {
|
||||
final batch = txn.batch();
|
||||
for (var index = 0; index < entries.length; index++) {
|
||||
batch.insert('history_entries', {
|
||||
'key': key,
|
||||
'position': index,
|
||||
'value': entries[index],
|
||||
});
|
||||
}
|
||||
await batch.commit(noResult: true);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> remove(String key) async {
|
||||
await database.delete('history_keys', where: 'key = ?', whereArgs: [key]);
|
||||
final prefs = PrefsManager.instance;
|
||||
return !prefs.containsKey(key) || await prefs.remove(key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Set<String>> getKeys() async => {
|
||||
for (final row in await database.query('history_keys', columns: ['key']))
|
||||
row['key'] as String,
|
||||
...PrefsManager.instance.getKeys().where(HistoryStore.isHistoryKey),
|
||||
};
|
||||
|
||||
@override
|
||||
Future<int> entryCount(String key) async {
|
||||
if ((await _header(key)).isEmpty) {
|
||||
return PreferencesHistoryStore().entryCount(key);
|
||||
}
|
||||
return sqlite.Sqflite.firstIntValue(
|
||||
await database.rawQuery(
|
||||
'SELECT COUNT(*) FROM history_entries WHERE key = ?',
|
||||
[key],
|
||||
),
|
||||
) ??
|
||||
0;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<String>> readEntries(
|
||||
String key, {
|
||||
int offset = 0,
|
||||
int? limit,
|
||||
}) async {
|
||||
RangeError.checkNotNegative(offset, 'offset');
|
||||
if (limit != null) RangeError.checkNotNegative(limit, 'limit');
|
||||
if ((await _header(key)).isEmpty) {
|
||||
return PreferencesHistoryStore().readEntries(
|
||||
key,
|
||||
offset: offset,
|
||||
limit: limit,
|
||||
);
|
||||
}
|
||||
final rows = await database.rawQuery(
|
||||
'SELECT value FROM history_entries WHERE key = ? ORDER BY position '
|
||||
'LIMIT ? OFFSET ?',
|
||||
[key, limit ?? -1, offset],
|
||||
);
|
||||
return [for (final row in rows) row['value'] as String];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> replaceTail(
|
||||
String key,
|
||||
int preservedCount,
|
||||
List<String> entries, {
|
||||
int maxEntries = 1000,
|
||||
}) async {
|
||||
RangeError.checkNotNegative(preservedCount, 'preservedCount');
|
||||
RangeError.checkNotNegative(maxEntries, 'maxEntries');
|
||||
// A readable preference left by the import is adopted first. An
|
||||
// unreadable one stays in preferences, where a save never erases it; the
|
||||
// database rows written below are what later reads return.
|
||||
if ((await _header(key)).isEmpty) {
|
||||
final legacy = PrefsManager.instance.getString(key);
|
||||
if (legacy != null && legacy.isNotEmpty) {
|
||||
if (_isJsonList(legacy)) {
|
||||
await setString(key, legacy);
|
||||
} else {
|
||||
appLogger.warn('Saving $key beside its unreadable preference');
|
||||
}
|
||||
}
|
||||
}
|
||||
return database.transaction((txn) async {
|
||||
await txn.rawInsert(
|
||||
'INSERT OR IGNORE INTO history_keys (key, value) VALUES (?, NULL)',
|
||||
[key],
|
||||
);
|
||||
final prefix = preservedCount == 0
|
||||
? <Map<String, Object?>>[]
|
||||
: await txn.rawQuery(
|
||||
'SELECT position FROM history_entries WHERE key = ? '
|
||||
'ORDER BY position LIMIT 1 OFFSET ?',
|
||||
[key, preservedCount - 1],
|
||||
);
|
||||
final count =
|
||||
sqlite.Sqflite.firstIntValue(
|
||||
await txn.rawQuery(
|
||||
'SELECT COUNT(*) FROM history_entries WHERE key = ?',
|
||||
[key],
|
||||
),
|
||||
) ??
|
||||
0;
|
||||
final preserved = preservedCount.clamp(0, count);
|
||||
final lastPosition = prefix.isNotEmpty
|
||||
? prefix.first['position'] as int
|
||||
: preserved == 0
|
||||
? -1
|
||||
: sqlite.Sqflite.firstIntValue(
|
||||
await txn.rawQuery(
|
||||
'SELECT MAX(position) FROM history_entries WHERE key = ?',
|
||||
[key],
|
||||
),
|
||||
)!;
|
||||
await txn.delete(
|
||||
'history_entries',
|
||||
where: 'key = ? AND position > ?',
|
||||
whereArgs: [key, lastPosition],
|
||||
);
|
||||
final batch = txn.batch();
|
||||
for (var index = 0; index < entries.length; index++) {
|
||||
batch.insert('history_entries', {
|
||||
'key': key,
|
||||
'position': lastPosition + index + 1,
|
||||
'value': entries[index],
|
||||
});
|
||||
}
|
||||
await batch.commit(noResult: true);
|
||||
final overflow = (preserved + entries.length - maxEntries).clamp(
|
||||
0,
|
||||
preserved + entries.length,
|
||||
);
|
||||
if (overflow > 0) {
|
||||
await txn.rawDelete(
|
||||
'DELETE FROM history_entries WHERE key = ? AND position IN '
|
||||
'(SELECT position FROM history_entries WHERE key = ? '
|
||||
'ORDER BY position LIMIT ?)',
|
||||
[key, key, overflow],
|
||||
);
|
||||
}
|
||||
return (preserved - overflow).clamp(0, preserved);
|
||||
});
|
||||
}
|
||||
|
||||
static bool _isJsonList(String value) {
|
||||
try {
|
||||
return jsonDecode(value) is List;
|
||||
} on FormatException {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() => database.close();
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'history_store.dart';
|
||||
|
||||
Future<HistoryStore> createHistoryStore() async => PreferencesHistoryStore();
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'prefs_manager.dart';
|
||||
|
||||
/// Storage scopes (first 10 hex chars of a radio's public key) that must
|
||||
/// never adopt data from the legacy unscoped keys.
|
||||
///
|
||||
@@ -8,3 +10,16 @@ final Set<String> scopesWithoutLegacyMigration = {};
|
||||
|
||||
bool canMigrateLegacyKeys(String scopeHex) =>
|
||||
!scopesWithoutLegacyMigration.contains(scopeHex);
|
||||
|
||||
Future<String?> migrateLegacyStringPreference(
|
||||
String oldKey,
|
||||
String newKey,
|
||||
) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final value = prefs.getString(oldKey);
|
||||
if (value == null || value.isEmpty) return value;
|
||||
if (await prefs.setString(newKey, value)) {
|
||||
await prefs.remove(oldKey);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
+124
-135
@@ -1,14 +1,13 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../models/message.dart';
|
||||
import '../models/translation_support.dart';
|
||||
import '../helpers/smaz.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'legacy_key_migration.dart';
|
||||
import 'prefs_manager.dart';
|
||||
import 'history_archive.dart';
|
||||
import 'history_store.dart';
|
||||
|
||||
class MessageStore {
|
||||
static const String _keyPrefix = 'messages_';
|
||||
@@ -23,102 +22,41 @@ class MessageStore {
|
||||
/// beyond it are dropped on save.
|
||||
static const int maxStoredMessages = 1000;
|
||||
|
||||
/// Encoded entries persisted ahead of the connector's in-memory window,
|
||||
/// keyed by scoped storage key. A missing entry means the window has not
|
||||
/// been reconciled with storage yet, so the next save keeps what is already
|
||||
/// stored instead of replacing it. Shared across instances so a store
|
||||
/// created by a screen to clear a key also resets the connector's view.
|
||||
static final Map<String, List<String>> _archived = {};
|
||||
static final HistoryArchive _archive = HistoryArchive(
|
||||
mergeKey: _storedMergeKey,
|
||||
maxEntries: maxStoredMessages,
|
||||
);
|
||||
|
||||
/// Persists [messages] (the in-memory window, oldest first) after the
|
||||
/// archived entries that sit ahead of it in storage.
|
||||
Future<void> saveMessages(
|
||||
String contactKeyHex,
|
||||
List<Message> messages,
|
||||
) async {
|
||||
Future<void> saveMessages(String contactKeyHex, List<Message> messages) {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn('Public key hex is not set. Cannot save messages.');
|
||||
return;
|
||||
return Future<void>.value();
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyFor$contactKeyHex';
|
||||
final visibleJson = messages.map(_messageToJson).toList();
|
||||
final archived =
|
||||
_archived[key] ??
|
||||
_unreconciledArchive(_readStored(prefs, contactKeyHex), visibleJson);
|
||||
final overflow = archived.length + visibleJson.length - maxStoredMessages;
|
||||
if (overflow > 0) {
|
||||
archived.removeRange(0, overflow.clamp(0, archived.length));
|
||||
}
|
||||
_archived[key] = archived;
|
||||
final entries = [...archived, ...visibleJson.map(jsonEncode)];
|
||||
await prefs.setString(key, '[${entries.join(',')}]');
|
||||
}
|
||||
|
||||
/// Records [olderMessages] as the stored entries that precede the
|
||||
/// in-memory window for [contactKeyHex].
|
||||
void setArchived(String contactKeyHex, List<Message> olderMessages) {
|
||||
_archived['$keyFor$contactKeyHex'] = olderMessages
|
||||
.map((message) => jsonEncode(_messageToJson(message)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Moves [messages], just trimmed from the front of the in-memory window,
|
||||
/// into the archive so the next save keeps them.
|
||||
void archive(String contactKeyHex, List<Message> messages) {
|
||||
final archived = _archived['$keyFor$contactKeyHex'];
|
||||
// Unreconciled saves keep everything already stored anyway.
|
||||
if (archived == null) return;
|
||||
archived.addAll(
|
||||
messages.map((message) => jsonEncode(_messageToJson(message))),
|
||||
final scope = publicKeyHex;
|
||||
return _archive.save(
|
||||
key,
|
||||
[for (final message in messages) jsonEncode(_messageToJson(message))],
|
||||
readStored: (store) =>
|
||||
_readStored(store, key, '$_keyPrefix$contactKeyHex', scope),
|
||||
);
|
||||
}
|
||||
|
||||
/// Number of stored entries ahead of the in-memory window, or null when
|
||||
/// the window has not been reconciled with storage.
|
||||
/// The stored prefix stays in the database, rather than another JSON cache.
|
||||
void setArchivedCount(String contactKeyHex, int count) =>
|
||||
_archive.setArchivedCount('$keyFor$contactKeyHex', count);
|
||||
|
||||
void archive(String contactKeyHex, List<Message> messages) =>
|
||||
_archive.archive(
|
||||
'$keyFor$contactKeyHex',
|
||||
messages.map((message) => jsonEncode(_messageToJson(message))),
|
||||
);
|
||||
|
||||
int? archivedCount(String contactKeyHex) =>
|
||||
_archived['$keyFor$contactKeyHex']?.length;
|
||||
_archive.archivedCount('$keyFor$contactKeyHex');
|
||||
|
||||
/// Removes the newest [count] archived entries after they were paged back
|
||||
/// into the in-memory window.
|
||||
void unarchiveNewest(String contactKeyHex, int count) {
|
||||
final archived = _archived['$keyFor$contactKeyHex'];
|
||||
if (archived == null || count <= 0) return;
|
||||
archived.removeRange(
|
||||
(archived.length - count).clamp(0, archived.length),
|
||||
archived.length,
|
||||
);
|
||||
}
|
||||
|
||||
/// Drops the archive bookkeeping, for one conversation or all of them,
|
||||
/// when the matching in-memory window is discarded.
|
||||
void forgetArchive([String? contactKeyHex]) {
|
||||
if (contactKeyHex == null) {
|
||||
_archived.clear();
|
||||
} else {
|
||||
_archived.remove('$keyFor$contactKeyHex');
|
||||
}
|
||||
}
|
||||
|
||||
List<String> _unreconciledArchive(
|
||||
String? storedJson,
|
||||
List<Map<String, dynamic>> visibleJson,
|
||||
) {
|
||||
if (storedJson == null || storedJson.isEmpty) return [];
|
||||
final List<dynamic> stored;
|
||||
try {
|
||||
stored = jsonDecode(storedJson) as List<dynamic>;
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
final visibleKeys = visibleJson.map(_storedMergeKey).toSet();
|
||||
return [
|
||||
for (final entry in stored)
|
||||
if (entry is Map<String, dynamic> &&
|
||||
!visibleKeys.contains(_storedMergeKey(entry)))
|
||||
jsonEncode(entry),
|
||||
];
|
||||
}
|
||||
void forgetArchive([String? contactKeyHex]) =>
|
||||
_archive.forget(contactKeyHex == null ? null : '$keyFor$contactKeyHex');
|
||||
|
||||
static String _storedMergeKey(Map<String, dynamic> json) {
|
||||
final messageId = json['messageId'];
|
||||
@@ -126,69 +64,120 @@ class MessageStore {
|
||||
return 'fallback:${json['timestamp']}:${json['isOutgoing']}:${json['text']}';
|
||||
}
|
||||
|
||||
/// Reads the stored JSON for [contactKeyHex], migrating the legacy unscoped
|
||||
/// key on first access.
|
||||
String? _readStored(SharedPreferences prefs, String contactKeyHex) {
|
||||
final key = '$keyFor$contactKeyHex';
|
||||
final oldKey = '$_keyPrefix$contactKeyHex';
|
||||
final jsonString = prefs.getString(key);
|
||||
if ((jsonString == null || jsonString.isEmpty) &&
|
||||
canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
final legacyJsonString = prefs.getString(oldKey);
|
||||
prefs.remove(oldKey);
|
||||
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Migrating messages from legacy key $oldKey to scoped key $key',
|
||||
);
|
||||
prefs.setString(key, legacyJsonString);
|
||||
return legacyJsonString;
|
||||
Future<String?> _readStored(
|
||||
HistoryStore store,
|
||||
String key,
|
||||
String oldKey,
|
||||
String scope,
|
||||
) async {
|
||||
final raw = await store.getString(key);
|
||||
if ((raw == null || raw.isEmpty) && canMigrateLegacyKeys(scope)) {
|
||||
final legacy = await store.getString(oldKey);
|
||||
if (legacy != null && legacy.isNotEmpty) {
|
||||
if (await store.setString(key, legacy)) await store.remove(oldKey);
|
||||
}
|
||||
return legacy;
|
||||
}
|
||||
return jsonString;
|
||||
return raw;
|
||||
}
|
||||
|
||||
Future<List<Message>> loadMessages(String contactKeyHex) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn('Public key hex is not set. Cannot load messages.');
|
||||
return [];
|
||||
Future<({String key, int count})> _storedHistory(String contactKeyHex) async {
|
||||
final store = HistoryStore.instance;
|
||||
final scope = publicKeyHex;
|
||||
final key = '$keyFor$contactKeyHex';
|
||||
var count = await store.entryCount(key);
|
||||
if (count > 0) return (key: key, count: count);
|
||||
final raw = await store.getString(key);
|
||||
if ((raw == null || raw.isEmpty) && canMigrateLegacyKeys(scope)) {
|
||||
final oldKey = '$_keyPrefix$contactKeyHex';
|
||||
final legacy = await store.getString(oldKey);
|
||||
if (legacy != null && legacy.isNotEmpty) {
|
||||
if (await store.setString(key, legacy)) {
|
||||
await store.remove(oldKey);
|
||||
count = await store.entryCount(key);
|
||||
} else {
|
||||
throw StateError('Could not migrate stored message history');
|
||||
}
|
||||
}
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
String? jsonString = _readStored(prefs, contactKeyHex);
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
jsonString = prefs.getString(keyFor);
|
||||
}
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
return [];
|
||||
if (raw == null && count == 0) {
|
||||
final fallback = '$_keyPrefix$scope';
|
||||
final fallbackCount = await store.entryCount(fallback);
|
||||
if (fallbackCount > 0) {
|
||||
final fallbackJson = await store.getString(fallback);
|
||||
if (fallbackJson == null || !await store.setString(key, fallbackJson)) {
|
||||
throw StateError('Could not migrate fallback message history');
|
||||
}
|
||||
return (key: key, count: fallbackCount);
|
||||
}
|
||||
}
|
||||
return (key: key, count: count);
|
||||
}
|
||||
|
||||
final List<dynamic> jsonList;
|
||||
Future<List<Message>> loadMessages(
|
||||
String contactKeyHex, {
|
||||
int offset = 0,
|
||||
int? limit,
|
||||
}) async {
|
||||
if (publicKeyHex.isEmpty) return [];
|
||||
try {
|
||||
jsonList = jsonDecode(jsonString) as List<dynamic>;
|
||||
} catch (e) {
|
||||
appLogger.warn('Stored messages for $contactKeyHex are unreadable: $e');
|
||||
final history = await _storedHistory(contactKeyHex);
|
||||
final entries = await HistoryStore.instance.readEntries(
|
||||
history.key,
|
||||
offset: offset,
|
||||
limit: limit,
|
||||
);
|
||||
return _decodeMessages(entries);
|
||||
} catch (error) {
|
||||
appLogger.warn(
|
||||
'Stored messages for $contactKeyHex are unreadable: $error',
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a page backwards using physical stored-row offsets. Malformed
|
||||
/// records are skipped without making earlier valid history unreachable.
|
||||
Future<({List<Message> messages, int start, int end, int total})>
|
||||
loadMessagePage(String contactKeyHex, {int? before, int limit = 50}) async {
|
||||
RangeError.checkNotNegative(limit, 'limit');
|
||||
if (publicKeyHex.isEmpty) {
|
||||
return (messages: <Message>[], start: 0, end: 0, total: 0);
|
||||
}
|
||||
try {
|
||||
final history = await _storedHistory(contactKeyHex);
|
||||
return await _archive.readPage(
|
||||
history.key,
|
||||
history.count,
|
||||
_decodeMessages,
|
||||
before: before,
|
||||
limit: limit,
|
||||
);
|
||||
} on FormatException catch (error) {
|
||||
appLogger.warn(
|
||||
'Stored messages for $contactKeyHex are unreadable: $error',
|
||||
);
|
||||
return (messages: <Message>[], start: 0, end: 0, total: 0);
|
||||
}
|
||||
}
|
||||
|
||||
List<Message> _decodeMessages(List<String> entries) {
|
||||
final messages = <Message>[];
|
||||
for (final json in jsonList) {
|
||||
for (final entry in entries) {
|
||||
try {
|
||||
messages.add(_messageFromJson(json as Map<String, dynamic>));
|
||||
} catch (e) {
|
||||
appLogger.warn('Skipping malformed stored message: $e');
|
||||
messages.add(
|
||||
_messageFromJson(jsonDecode(entry) as Map<String, dynamic>),
|
||||
);
|
||||
} catch (error) {
|
||||
appLogger.warn('Skipping malformed stored message: $error');
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
Future<void> clearMessages(String contactKeyHex) async {
|
||||
if (publicKeyHex.isEmpty) {
|
||||
appLogger.warn('Public key hex is not set. Cannot clear messages.');
|
||||
return;
|
||||
}
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$keyFor$contactKeyHex';
|
||||
_archived[key] = [];
|
||||
await prefs.remove(key);
|
||||
Future<void> clearMessages(String contactKeyHex) {
|
||||
if (publicKeyHex.isEmpty) return Future<void>.value();
|
||||
return _archive.clear(HistoryStore.instance, '$keyFor$contactKeyHex');
|
||||
}
|
||||
|
||||
Map<String, dynamic> _messageToJson(Message msg) {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'history_store.dart';
|
||||
|
||||
/// Singleton wrapper for SharedPreferences to avoid redundant getInstance() calls.
|
||||
///
|
||||
/// BEFORE: Every storage operation called SharedPreferences.getInstance()
|
||||
@@ -30,5 +32,6 @@ class PrefsManager {
|
||||
/// For testing: reset the instance
|
||||
static void reset() {
|
||||
_instance = null;
|
||||
HistoryStore.reset();
|
||||
}
|
||||
}
|
||||
@@ -36,16 +36,7 @@ class UnreadStore {
|
||||
String? jsonString = prefs.getString(keyFor);
|
||||
if ((jsonString == null || jsonString.isEmpty) &&
|
||||
canMigrateLegacyKeys(publicKeyHex)) {
|
||||
// Attempt migration from legacy unscoped key on first load
|
||||
final legacyJsonString = prefs.getString(_keyPrefix);
|
||||
prefs.remove(_keyPrefix);
|
||||
if (legacyJsonString != null && legacyJsonString.isNotEmpty) {
|
||||
appLogger.info(
|
||||
'Migrating channel messages from legacy key $_keyPrefix to scoped key $keyFor',
|
||||
);
|
||||
await prefs.setString(keyFor, legacyJsonString);
|
||||
jsonString = legacyJsonString;
|
||||
}
|
||||
jsonString = await migrateLegacyStringPreference(_keyPrefix, keyFor);
|
||||
}
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
jsonString = prefs.getString(keyFor);
|
||||
|
||||
Reference in new issue
Block a user