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
@@ -255,6 +255,9 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
static const int _errCodeNotFound = 2;
|
||||
int _reactionSendQueueSequence = 0;
|
||||
final Set<String> _loadedConversationKeys = {};
|
||||
int _messageHistoryGeneration = 0;
|
||||
final Map<String, Future<List<Message>>> _conversationPageLoads = {};
|
||||
final Map<String, Future<List<ChannelMessage>>> _channelPageLoads = {};
|
||||
// Self public key of the radio whose messages are held in memory.
|
||||
String? _messageStateOwnerKey;
|
||||
// Self public key whose persisted stores were loaded this link session.
|
||||
@@ -985,63 +988,82 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
Future<void> _loadMessagesForContact(String contactKeyHex) async {
|
||||
if (_loadedConversationKeys.contains(contactKeyHex)) return;
|
||||
_loadedConversationKeys.add(contactKeyHex);
|
||||
|
||||
final allMessages = await _messageStore.loadMessages(contactKeyHex);
|
||||
if (allMessages.isNotEmpty) {
|
||||
// Keep only the most recent N messages in memory to bound memory usage
|
||||
final windowedMessages = allMessages.length > _messageWindowSize
|
||||
? allMessages.sublist(allMessages.length - _messageWindowSize)
|
||||
: allMessages;
|
||||
final archivedMessages = allMessages.sublist(
|
||||
0,
|
||||
allMessages.length - windowedMessages.length,
|
||||
final generation = _messageHistoryGeneration;
|
||||
final scope = _messageStore.publicKeyHex;
|
||||
bool current() =>
|
||||
!_disposed &&
|
||||
generation == _messageHistoryGeneration &&
|
||||
scope == _messageStore.publicKeyHex;
|
||||
final page = await _readSettledPage(
|
||||
current: current,
|
||||
window: () => _conversations[contactKeyHex] ?? const <Message>[],
|
||||
archived: () => _messageStore.archivedCount(contactKeyHex),
|
||||
read: (_, _) => _messageStore.loadMessagePage(
|
||||
contactKeyHex,
|
||||
limit: _messageWindowSize,
|
||||
),
|
||||
);
|
||||
if (page == null) return;
|
||||
final currentMessages = _conversations[contactKeyHex] ?? const <Message>[];
|
||||
final mergedMessages = <Message>[...page.messages];
|
||||
final persistedKeyCounts = <String, int>{};
|
||||
for (final message in page.messages) {
|
||||
final key = _messageMergeKey(message);
|
||||
persistedKeyCounts[key] = (persistedKeyCounts[key] ?? 0) + 1;
|
||||
}
|
||||
final currentKeyCounts = <String, int>{};
|
||||
for (final message in currentMessages) {
|
||||
final key = _messageMergeKey(message);
|
||||
final count = (currentKeyCounts[key] ?? 0) + 1;
|
||||
currentKeyCounts[key] = count;
|
||||
if (count > (persistedKeyCounts[key] ?? 0)) mergedMessages.add(message);
|
||||
}
|
||||
mergedMessages.sort((a, b) => a.receivedAt.compareTo(b.receivedAt));
|
||||
final trimCount = (mergedMessages.length - _messageWindowSize).clamp(
|
||||
0,
|
||||
mergedMessages.length,
|
||||
);
|
||||
_messageStore.setArchivedCount(contactKeyHex, page.start);
|
||||
if (trimCount > 0) {
|
||||
_messageStore.archive(
|
||||
contactKeyHex,
|
||||
mergedMessages.sublist(0, trimCount),
|
||||
);
|
||||
|
||||
final currentMessages =
|
||||
_conversations[contactKeyHex] ?? const <Message>[];
|
||||
final mergedMessages = <Message>[...windowedMessages];
|
||||
final persistedKeyCounts = <String, int>{};
|
||||
for (final message in windowedMessages) {
|
||||
final key = _messageMergeKey(message);
|
||||
persistedKeyCounts[key] = (persistedKeyCounts[key] ?? 0) + 1;
|
||||
}
|
||||
final currentKeyCounts = <String, int>{};
|
||||
|
||||
for (final message in currentMessages) {
|
||||
final key = _messageMergeKey(message);
|
||||
final currentCount = (currentKeyCounts[key] ?? 0) + 1;
|
||||
currentKeyCounts[key] = currentCount;
|
||||
final persistedCount = persistedKeyCounts[key] ?? 0;
|
||||
|
||||
// Preserve distinct duplicates without IDs (for example same text
|
||||
// received multiple times in the same second) by only skipping the
|
||||
// overlapping occurrences that already exist in persisted storage.
|
||||
if (currentCount > persistedCount) {
|
||||
mergedMessages.add(message);
|
||||
}
|
||||
}
|
||||
|
||||
// Re-sort after merging persisted and in-memory messages so the
|
||||
// conversation window remains stable after optimistic inserts.
|
||||
mergedMessages.sort((a, b) => a.receivedAt.compareTo(b.receivedAt));
|
||||
final trimCount = mergedMessages.length > _messageWindowSize
|
||||
? mergedMessages.length - _messageWindowSize
|
||||
: 0;
|
||||
final windowedMergedMessages = mergedMessages.sublist(trimCount);
|
||||
|
||||
// Everything stored ahead of the window stays in storage on the next
|
||||
// save instead of being overwritten by the window.
|
||||
_messageStore.setArchived(contactKeyHex, [
|
||||
...archivedMessages,
|
||||
...mergedMessages.sublist(0, trimCount),
|
||||
]);
|
||||
_conversations[contactKeyHex] = windowedMergedMessages;
|
||||
}
|
||||
if (mergedMessages.isNotEmpty) {
|
||||
_conversations[contactKeyHex] = mergedMessages.sublist(trimCount);
|
||||
notifyListeners();
|
||||
} else {
|
||||
_messageStore.setArchived(contactKeyHex, const []);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a stored page once queued writes have landed, and again whenever
|
||||
/// the in-memory [window] or the [archived] count moved during the read.
|
||||
/// Returns null when [current] turns false, or when [older] history is
|
||||
/// requested and none is archived.
|
||||
Future<P?> _readSettledPage<M, P>({
|
||||
required bool Function() current,
|
||||
required List<M> Function() window,
|
||||
required int? Function() archived,
|
||||
required Future<P> Function(int? archived, List<M> window) read,
|
||||
bool older = false,
|
||||
}) async {
|
||||
while (true) {
|
||||
await _coalescedWrites.flush();
|
||||
if (!current()) return null;
|
||||
final archivedBefore = archived();
|
||||
if (older && archivedBefore == 0) return null;
|
||||
final snapshot = List<M>.of(window());
|
||||
final page = await read(archivedBefore, snapshot);
|
||||
if (!current()) return null;
|
||||
if (listEquals(snapshot, window()) && archivedBefore == archived()) {
|
||||
return page;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int _startOfWindow(int stored, List<Object?> window) =>
|
||||
(stored - window.length).clamp(0, stored);
|
||||
|
||||
String _messageMergeKey(Message message) {
|
||||
final messageId = message.messageId;
|
||||
if (messageId.isNotEmpty) {
|
||||
@@ -1054,58 +1076,126 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
Future<List<Message>> loadOlderMessages(
|
||||
String contactKeyHex, {
|
||||
int count = 50,
|
||||
}) async {
|
||||
final allMessages = await _messageStore.loadMessages(contactKeyHex);
|
||||
final currentMessages = _conversations[contactKeyHex] ?? [];
|
||||
}) {
|
||||
if (count <= 0) return Future.value([]);
|
||||
final loadKey = '${_messageStore.publicKeyHex}:$contactKeyHex';
|
||||
final pending = _conversationPageLoads[loadKey];
|
||||
if (pending != null) return pending;
|
||||
final started = _loadOlderMessages(contactKeyHex, count);
|
||||
_conversationPageLoads[loadKey] = started;
|
||||
return started.whenComplete(() {
|
||||
if (identical(_conversationPageLoads[loadKey], started)) {
|
||||
_conversationPageLoads.remove(loadKey);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Storage holds the archived entries followed by the in-memory window.
|
||||
final currentOffset =
|
||||
(_messageStore.archivedCount(contactKeyHex) ??
|
||||
allMessages.length - currentMessages.length)
|
||||
.clamp(0, allMessages.length);
|
||||
if (currentOffset == 0) {
|
||||
return []; // No more messages to load
|
||||
}
|
||||
|
||||
final fetchCount = count.clamp(0, currentOffset);
|
||||
final startIndex = currentOffset - fetchCount;
|
||||
|
||||
final olderMessages = allMessages.sublist(startIndex, currentOffset);
|
||||
_messageStore.unarchiveNewest(contactKeyHex, olderMessages.length);
|
||||
|
||||
// Prepend to current conversation
|
||||
_conversations[contactKeyHex] = [...olderMessages, ...currentMessages];
|
||||
Future<List<Message>> _loadOlderMessages(
|
||||
String contactKeyHex,
|
||||
int count,
|
||||
) async {
|
||||
final generation = _messageHistoryGeneration;
|
||||
final scope = _messageStore.publicKeyHex;
|
||||
bool current() =>
|
||||
!_disposed &&
|
||||
generation == _messageHistoryGeneration &&
|
||||
scope == _messageStore.publicKeyHex;
|
||||
final page = await _readSettledPage(
|
||||
current: current,
|
||||
window: () => _conversations[contactKeyHex] ?? const <Message>[],
|
||||
archived: () => _messageStore.archivedCount(contactKeyHex),
|
||||
older: true,
|
||||
read: (archived, window) async => _messageStore.loadMessagePage(
|
||||
contactKeyHex,
|
||||
// Unreconciled storage is assumed to end with the loaded window.
|
||||
before:
|
||||
archived ??
|
||||
_startOfWindow(
|
||||
(await _messageStore.loadMessagePage(
|
||||
contactKeyHex,
|
||||
limit: 0,
|
||||
)).total,
|
||||
window,
|
||||
),
|
||||
limit: count,
|
||||
),
|
||||
);
|
||||
if (page == null) return [];
|
||||
_messageStore.setArchivedCount(contactKeyHex, page.start);
|
||||
if (page.messages.isEmpty) return [];
|
||||
final currentMessages = _conversations[contactKeyHex] ?? const <Message>[];
|
||||
_conversations[contactKeyHex] = [...page.messages, ...currentMessages];
|
||||
notifyListeners();
|
||||
|
||||
return olderMessages;
|
||||
return page.messages;
|
||||
}
|
||||
|
||||
/// Full stored history (archived prefix plus the in-memory window) for
|
||||
/// search. Read-only: nothing is unarchived and listeners are not notified.
|
||||
Future<List<Message>> allMessagesForSearch(String contactKeyHex) async {
|
||||
final stored = await _messageStore.loadMessages(contactKeyHex);
|
||||
final generation = _messageHistoryGeneration;
|
||||
final scope = _messageStore.publicKeyHex;
|
||||
await _coalescedWrites.flush();
|
||||
if (_disposed ||
|
||||
generation != _messageHistoryGeneration ||
|
||||
scope != _messageStore.publicKeyHex) {
|
||||
return [];
|
||||
}
|
||||
final archived = _messageStore.archivedCount(contactKeyHex);
|
||||
final stored = await _messageStore.loadMessages(
|
||||
contactKeyHex,
|
||||
limit: archived,
|
||||
);
|
||||
if (_disposed ||
|
||||
generation != _messageHistoryGeneration ||
|
||||
scope != _messageStore.publicKeyHex) {
|
||||
return [];
|
||||
}
|
||||
final window = _conversations[contactKeyHex] ?? const <Message>[];
|
||||
final archived =
|
||||
(_messageStore.archivedCount(contactKeyHex) ??
|
||||
stored.length - window.length)
|
||||
.clamp(0, stored.length);
|
||||
return [...stored.sublist(0, archived), ...window];
|
||||
final prefix = archived == null
|
||||
? stored.sublist(
|
||||
0,
|
||||
(stored.length - window.length).clamp(0, stored.length),
|
||||
)
|
||||
: stored;
|
||||
return [...prefix, ...window];
|
||||
}
|
||||
|
||||
/// Channel counterpart of [allMessagesForSearch]; read-only.
|
||||
Future<List<ChannelMessage>> allChannelMessagesForSearch(
|
||||
int channelIndex,
|
||||
) async {
|
||||
final generation = _messageHistoryGeneration;
|
||||
final scope = _channelMessageStore.publicKeyHex;
|
||||
final slot = _canonicalSlot(channelIndex);
|
||||
final window = _channelMessages[slot] ?? const <ChannelMessage>[];
|
||||
final channelId = _channelIdForSlot(slot);
|
||||
if (channelId == null) return List.of(window);
|
||||
final stored = await _channelMessageStore.loadChannelMessages(channelId);
|
||||
final archived =
|
||||
(_channelMessageStore.archivedCount(channelId) ??
|
||||
stored.length - window.length)
|
||||
.clamp(0, stored.length);
|
||||
return [..._bindToSlot(stored.sublist(0, archived), slot), ...window];
|
||||
if (channelId == null) return List.of(_channelMessages[slot] ?? []);
|
||||
await _coalescedWrites.flush();
|
||||
if (_disposed ||
|
||||
generation != _messageHistoryGeneration ||
|
||||
scope != _channelMessageStore.publicKeyHex ||
|
||||
_slotChannelIds[slot] != channelId) {
|
||||
return [];
|
||||
}
|
||||
final archived = _channelMessageStore.archivedCount(channelId);
|
||||
final stored = await _channelMessageStore.loadChannelMessages(
|
||||
channelId,
|
||||
limit: archived,
|
||||
);
|
||||
if (_disposed ||
|
||||
generation != _messageHistoryGeneration ||
|
||||
scope != _channelMessageStore.publicKeyHex ||
|
||||
_slotChannelIds[slot] != channelId) {
|
||||
return [];
|
||||
}
|
||||
final window = _channelMessages[slot] ?? const <ChannelMessage>[];
|
||||
final rebound = _bindToSlot(stored, slot);
|
||||
final prefix = archived == null
|
||||
? rebound.sublist(
|
||||
0,
|
||||
(rebound.length - window.length).clamp(0, rebound.length),
|
||||
)
|
||||
: rebound;
|
||||
return [...prefix, ...window];
|
||||
}
|
||||
|
||||
List<ChannelMessage> getChannelMessages(Channel channel) {
|
||||
@@ -1492,7 +1582,14 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
|
||||
/// Runs queued persistence now. Called before the app is backgrounded and
|
||||
/// whenever the stores are about to switch to another radio.
|
||||
Future<void> flushPendingWrites() => _coalescedWrites.flush();
|
||||
Future<void> flushPendingWrites() async {
|
||||
await Future.wait([
|
||||
_coalescedWrites.flush(),
|
||||
_unreadStore.flush(),
|
||||
if (_pathHistoryService != null)
|
||||
_pathHistoryService!.flushPendingWrites(),
|
||||
]);
|
||||
}
|
||||
|
||||
int getUnreadCountForContact(Contact contact) {
|
||||
if (contact.type == advTypeRepeater) return 0;
|
||||
@@ -2045,77 +2142,103 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
: message.copyWith(channelIndex: slot),
|
||||
];
|
||||
|
||||
/// Load persisted channel messages for a specific channel
|
||||
/// Load only the newest persisted window of a channel.
|
||||
Future<void> _loadChannelMessages(int channelIndex) async {
|
||||
// The load replaces the in-memory history, so queued writes of it must
|
||||
// reach storage (whose cache updates synchronously) first.
|
||||
unawaited(_coalescedWrites.flush());
|
||||
final generation = _messageHistoryGeneration;
|
||||
final scope = _channelMessageStore.publicKeyHex;
|
||||
final channelId = _slotChannelIds[channelIndex];
|
||||
final allMessages = channelId == null
|
||||
? <ChannelMessage>[]
|
||||
: _bindToSlot(
|
||||
await _channelMessageStore.loadChannelMessages(channelId),
|
||||
channelIndex,
|
||||
);
|
||||
// Keep only the most recent N messages in memory to bound memory usage
|
||||
final windowedMessages = allMessages.length > _messageWindowSize
|
||||
? allMessages.sublist(allMessages.length - _messageWindowSize)
|
||||
: allMessages;
|
||||
if (channelId != null) {
|
||||
_channelMessageStore.setArchived(
|
||||
channelId,
|
||||
allMessages.sublist(0, allMessages.length - windowedMessages.length),
|
||||
bool current() =>
|
||||
!_disposed &&
|
||||
generation == _messageHistoryGeneration &&
|
||||
scope == _channelMessageStore.publicKeyHex &&
|
||||
_slotChannelIds[channelIndex] == channelId;
|
||||
var windowedMessages = <ChannelMessage>[];
|
||||
if (channelId == null) {
|
||||
await _coalescedWrites.flush();
|
||||
if (!current()) return;
|
||||
} else {
|
||||
final page = await _readSettledPage(
|
||||
current: current,
|
||||
window: () =>
|
||||
_channelMessages[channelIndex] ?? const <ChannelMessage>[],
|
||||
archived: () => _channelMessageStore.archivedCount(channelId),
|
||||
read: (_, _) => _channelMessageStore.loadMessagePage(
|
||||
channelId,
|
||||
limit: _messageWindowSize,
|
||||
),
|
||||
);
|
||||
if (page == null) return;
|
||||
windowedMessages = _bindToSlot(page.messages, channelIndex);
|
||||
_channelMessageStore.setArchivedCount(channelId, page.start);
|
||||
}
|
||||
// Replace even when nothing is stored so another radio's messages never
|
||||
// linger under this index.
|
||||
final hadMessages = _channelMessages[channelIndex]?.isNotEmpty ?? false;
|
||||
// Rules may have changed since these were stored.
|
||||
if (_applyFilterRules(channelIndex, windowedMessages)) {
|
||||
_scheduleChannelSave(channelIndex);
|
||||
}
|
||||
final retagged = _applyFilterRules(channelIndex, windowedMessages);
|
||||
_channelMessages[channelIndex] = windowedMessages;
|
||||
if (retagged) _scheduleChannelSave(channelIndex);
|
||||
if (hadMessages || windowedMessages.isNotEmpty) notifyListeners();
|
||||
}
|
||||
|
||||
/// Load older channel messages (pagination)
|
||||
Future<List<ChannelMessage>> loadOlderChannelMessages(
|
||||
int channelIndex, {
|
||||
int count = 50,
|
||||
}) async {
|
||||
}) {
|
||||
if (count <= 0) return Future.value([]);
|
||||
final slot = _canonicalSlot(channelIndex);
|
||||
final channelId = _channelIdForSlot(slot);
|
||||
if (channelId == null) return [];
|
||||
final allMessages = await _channelMessageStore.loadChannelMessages(
|
||||
channelId,
|
||||
if (channelId == null) return Future.value([]);
|
||||
final loadKey = '${_channelMessageStore.publicKeyHex}:$channelId';
|
||||
final pending = _channelPageLoads[loadKey];
|
||||
if (pending != null) return pending;
|
||||
final started = _loadOlderChannelMessages(slot, channelId, count);
|
||||
_channelPageLoads[loadKey] = started;
|
||||
return started.whenComplete(() {
|
||||
if (identical(_channelPageLoads[loadKey], started)) {
|
||||
_channelPageLoads.remove(loadKey);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<List<ChannelMessage>> _loadOlderChannelMessages(
|
||||
int slot,
|
||||
String channelId,
|
||||
int count,
|
||||
) async {
|
||||
final generation = _messageHistoryGeneration;
|
||||
final scope = _channelMessageStore.publicKeyHex;
|
||||
bool current() =>
|
||||
!_disposed &&
|
||||
generation == _messageHistoryGeneration &&
|
||||
scope == _channelMessageStore.publicKeyHex &&
|
||||
_slotChannelIds[slot] == channelId;
|
||||
final page = await _readSettledPage(
|
||||
current: current,
|
||||
window: () => _channelMessages[slot] ?? const <ChannelMessage>[],
|
||||
archived: () => _channelMessageStore.archivedCount(channelId),
|
||||
older: true,
|
||||
read: (archived, window) async => _channelMessageStore.loadMessagePage(
|
||||
channelId,
|
||||
// Unreconciled storage is assumed to end with the loaded window.
|
||||
before:
|
||||
archived ??
|
||||
_startOfWindow(
|
||||
(await _channelMessageStore.loadMessagePage(
|
||||
channelId,
|
||||
limit: 0,
|
||||
)).total,
|
||||
window,
|
||||
),
|
||||
limit: count,
|
||||
),
|
||||
);
|
||||
final currentMessages = _channelMessages[slot] ?? [];
|
||||
|
||||
// Storage holds the archived entries followed by the in-memory window.
|
||||
final currentOffset =
|
||||
(_channelMessageStore.archivedCount(channelId) ??
|
||||
allMessages.length - currentMessages.length)
|
||||
.clamp(0, allMessages.length);
|
||||
if (currentOffset == 0) {
|
||||
return []; // No more messages to load
|
||||
}
|
||||
|
||||
final fetchCount = count.clamp(0, currentOffset);
|
||||
final startIndex = currentOffset - fetchCount;
|
||||
|
||||
final olderMessages = _bindToSlot(
|
||||
allMessages.sublist(startIndex, currentOffset),
|
||||
slot,
|
||||
);
|
||||
_channelMessageStore.unarchiveNewest(channelId, olderMessages.length);
|
||||
|
||||
// Rules may have changed since these were stored.
|
||||
if (page == null) return [];
|
||||
_channelMessageStore.setArchivedCount(channelId, page.start);
|
||||
final olderMessages = _bindToSlot(page.messages, slot);
|
||||
if (olderMessages.isEmpty) return [];
|
||||
final retagged = _applyFilterRules(slot, olderMessages);
|
||||
// Prepend to current conversation
|
||||
final currentMessages = _channelMessages[slot] ?? const <ChannelMessage>[];
|
||||
_channelMessages[slot] = [...olderMessages, ...currentMessages];
|
||||
if (retagged) _scheduleChannelSave(slot);
|
||||
notifyListeners();
|
||||
|
||||
return olderMessages;
|
||||
}
|
||||
|
||||
@@ -4305,6 +4428,7 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
_txCharacteristic = null;
|
||||
_deviceDisplayName = null;
|
||||
_deviceId = null;
|
||||
await _coalescedWrites.flush();
|
||||
_contacts.clear();
|
||||
_discoveredContacts.clear();
|
||||
_clearSessionMessageState();
|
||||
@@ -6333,7 +6457,8 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
}
|
||||
// Queued channel writes find their channel by slot; land them before
|
||||
// the map moves, or a channel whose slot changed would never be saved.
|
||||
unawaited(_coalescedWrites.flush());
|
||||
await _coalescedWrites.flush();
|
||||
if (generation != _channelSessionGeneration) return;
|
||||
_slotChannelIds
|
||||
..clear()
|
||||
..addAll(next);
|
||||
@@ -6455,18 +6580,32 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
/// Runs the one-shot storage migration, then preloads this radio's channel
|
||||
/// state from the saved slot map so it shows before the channel sync ends.
|
||||
Future<void> _prepareChannelStorage() async {
|
||||
final generation = _channelSessionGeneration;
|
||||
final scope = _channelStore.publicKeyHex;
|
||||
bool current() =>
|
||||
!_disposed &&
|
||||
generation == _channelSessionGeneration &&
|
||||
scope == _channelStore.publicKeyHex;
|
||||
try {
|
||||
// First: the channel sync is already running and carries unread counts
|
||||
// over from these. The migration never touches the channel cache.
|
||||
await loadCachedChannels();
|
||||
await ChannelStorageMigration.migrate(
|
||||
_channelStore.publicKeyHex,
|
||||
beforeDone: (slotIds) async =>
|
||||
_receivedImageStore?.stampLegacyChannelIds(slotIds),
|
||||
);
|
||||
try {
|
||||
await ChannelStorageMigration.migrate(
|
||||
scope,
|
||||
beforeDone: (slotIds) async =>
|
||||
_receivedImageStore?.stampLegacyChannelIds(slotIds),
|
||||
);
|
||||
} catch (e) {
|
||||
// It repeats on the next connect; what is already stored under
|
||||
// channel IDs still preloads.
|
||||
appLogger.warn('Channel storage migration failed: $e');
|
||||
}
|
||||
await _loadChannelOrder();
|
||||
final saved = await _channelStore.loadSlotChannelIds();
|
||||
unawaited(_coalescedWrites.flush());
|
||||
await _coalescedWrites.flush();
|
||||
// The radio may have disconnected or changed while writes landed.
|
||||
if (!current()) return;
|
||||
_slotChannelIds
|
||||
..clear()
|
||||
..addAll(saved);
|
||||
@@ -6541,7 +6680,7 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
await sendFrame(buildSetChannelFrame(index, '', Uint8List(16)));
|
||||
// A twin slot with the same PSK keeps this history, so queued writes of
|
||||
// it land before the list is dropped; a full delete clears them below.
|
||||
unawaited(_coalescedWrites.flush());
|
||||
await _coalescedWrites.flush();
|
||||
_channelMessages.remove(index);
|
||||
_processedChannelReactions.remove(index);
|
||||
try {
|
||||
@@ -9441,6 +9580,9 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
/// Drops the conversation and channel history held in memory, so a
|
||||
/// different radio never shows or persists another radio's messages.
|
||||
void _clearSessionMessageState() {
|
||||
_messageHistoryGeneration++;
|
||||
_conversationPageLoads.clear();
|
||||
_channelPageLoads.clear();
|
||||
// Writes start synchronously, so they still read this radio's history and
|
||||
// store keys before both change below.
|
||||
unawaited(_coalescedWrites.flush());
|
||||
@@ -9536,6 +9678,8 @@ class MeshCoreConnector extends ChangeNotifier {
|
||||
generation != _offlineLoadGeneration ||
|
||||
_state != MeshCoreConnectionState.disconnected;
|
||||
|
||||
await _coalescedWrites.flush();
|
||||
if (superseded()) return;
|
||||
_clearSessionMessageState();
|
||||
_bindStorageScope(keyHex);
|
||||
// A connect to this radio keeps what is loaded here; a different radio's
|
||||
|
||||
@@ -41,6 +41,7 @@ import 'services/ui_view_state_service.dart';
|
||||
import 'services/chat_background_service.dart';
|
||||
import 'services/timeout_prediction_service.dart';
|
||||
import 'storage/prefs_manager.dart';
|
||||
import 'storage/history_store.dart';
|
||||
import 'theme/mesh_theme.dart';
|
||||
import 'utils/app_logger.dart';
|
||||
import 'widgets/image_send_codec_binding.dart';
|
||||
@@ -68,6 +69,7 @@ void main() async {
|
||||
|
||||
// Initialize SharedPreferences cache
|
||||
await PrefsManager.initialize();
|
||||
await HistoryStore.initialize();
|
||||
|
||||
// Initialize services
|
||||
final storage = StorageService();
|
||||
|
||||
@@ -6,6 +6,7 @@ import '../services/storage_service.dart';
|
||||
import '../services/timeout_prediction_service.dart';
|
||||
import '../storage/legacy_key_migration.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../storage/history_store.dart';
|
||||
import 'review_radio.dart';
|
||||
|
||||
/// Channel notification modes (JSON map of channel name to mode name) as they
|
||||
@@ -26,9 +27,16 @@ const _savedGlobalKeyPrefix = 'review_mode_saved_global_';
|
||||
Future<void> clearReviewModeData() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final prefix = ReviewRadio.storagePrefix;
|
||||
final keys = prefs.getKeys().where((key) => key.contains(prefix)).toList();
|
||||
final keys = {
|
||||
...prefs.getKeys(),
|
||||
...await HistoryStore.instance.getKeys(),
|
||||
}.where((key) => key.contains(prefix)).toList();
|
||||
for (final key in keys) {
|
||||
await prefs.remove(key);
|
||||
if (HistoryStore.isHistoryKey(key)) {
|
||||
await HistoryStore.instance.remove(key);
|
||||
} else {
|
||||
await prefs.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+64
-18
@@ -75,7 +75,7 @@ class MapScreen extends StatefulWidget {
|
||||
State<MapScreen> createState() => _MapScreenState();
|
||||
}
|
||||
|
||||
class _MapScreenState extends State<MapScreen> {
|
||||
class _MapScreenState extends State<MapScreen> with WidgetsBindingObserver {
|
||||
// Zoom level at which node labels start to appear
|
||||
static const double _labelZoomThreshold = 14.0;
|
||||
// Below this zoom, nearby nodes collapse into clusters.
|
||||
@@ -135,6 +135,9 @@ class _MapScreenState extends State<MapScreen> {
|
||||
({LatLng center, double zoom})? _initialCamera;
|
||||
|
||||
static const String _lastCameraKey = 'map_last_camera';
|
||||
static const Duration _cameraSaveDelay = Duration(milliseconds: 500);
|
||||
Timer? _cameraSaveTimer;
|
||||
List<String>? _pendingCamera;
|
||||
|
||||
({LatLng center, double zoom}) _fallbackCamera(MeshCoreConnector connector) {
|
||||
final lat = connector.selfLatitude;
|
||||
@@ -152,23 +155,58 @@ class _MapScreenState extends State<MapScreen> {
|
||||
return (center: const LatLng(20, 0), zoom: _mapMinZoom);
|
||||
}
|
||||
|
||||
void _saveLastCamera() {
|
||||
void _scheduleCameraSave() {
|
||||
try {
|
||||
final camera = _mapController.camera;
|
||||
PrefsManager.instance.setStringList(_lastCameraKey, [
|
||||
final value = [
|
||||
camera.center.latitude.toString(),
|
||||
camera.center.longitude.toString(),
|
||||
camera.zoom.toString(),
|
||||
]);
|
||||
];
|
||||
_cameraSaveTimer?.cancel();
|
||||
_cameraSaveTimer = null;
|
||||
_pendingCamera =
|
||||
listEquals(value, PrefsManager.instance.getStringList(_lastCameraKey))
|
||||
? null
|
||||
: value;
|
||||
if (_pendingCamera != null) {
|
||||
_cameraSaveTimer = Timer(_cameraSaveDelay, _flushCameraSave);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
void _flushCameraSave() {
|
||||
_cameraSaveTimer?.cancel();
|
||||
_cameraSaveTimer = null;
|
||||
final value = _pendingCamera;
|
||||
_pendingCamera = null;
|
||||
if (value == null) return;
|
||||
final prefs = PrefsManager.instance;
|
||||
if (listEquals(value, prefs.getStringList(_lastCameraKey))) return;
|
||||
unawaited(
|
||||
prefs.setStringList(_lastCameraKey, value).catchError((Object error) {
|
||||
debugPrint('Saving map camera failed: $error');
|
||||
return false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state != AppLifecycleState.resumed) {
|
||||
_scheduleCameraSave();
|
||||
_flushCameraSave();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_ageTimer?.cancel();
|
||||
_online.removeListener(_onOnlineChanged);
|
||||
_online.dispose();
|
||||
_saveLastCamera();
|
||||
_scheduleCameraSave();
|
||||
_flushCameraSave();
|
||||
_searchController.dispose();
|
||||
_searchFocus.dispose();
|
||||
_mapController.dispose();
|
||||
@@ -278,6 +316,7 @@ class _MapScreenState extends State<MapScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_loadRemovedMarkers();
|
||||
_online.addListener(_onOnlineChanged);
|
||||
_ageTimer = Timer.periodic(const Duration(seconds: 60), (_) {
|
||||
@@ -531,7 +570,7 @@ class _MapScreenState extends State<MapScreen> {
|
||||
final tileCache = context.read<MapTileCacheService>();
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final isDesktop = _isDesktopPlatform(defaultTargetPlatform);
|
||||
final allContacts = connector.allContacts;
|
||||
final allContacts = connectorSnapshot.allContacts;
|
||||
|
||||
final contacts = settings.mapShowDiscoveryContacts
|
||||
? allContacts
|
||||
@@ -912,11 +951,12 @@ class _MapScreenState extends State<MapScreen> {
|
||||
event is MapEventFlingAnimationEnd ||
|
||||
event is MapEventScrollWheelZoom ||
|
||||
event is MapEventDoubleTapZoomEnd) {
|
||||
_saveLastCamera();
|
||||
_scheduleCameraSave();
|
||||
if (showOnline) _requestOnlineData();
|
||||
}
|
||||
},
|
||||
onPositionChanged: (camera, hasGesture) {
|
||||
_scheduleCameraSave();
|
||||
// Track zoom in half-step buckets so cluster/marker
|
||||
// detail levels update without rebuilding every frame.
|
||||
final bucket = (camera.zoom * 2).roundToDouble() / 2;
|
||||
@@ -1087,13 +1127,19 @@ class _MapScreenState extends State<MapScreen> {
|
||||
),
|
||||
bottomNavigationBar: SafeArea(
|
||||
top: false,
|
||||
child: QuickSwitchBar(
|
||||
selectedIndex: 2,
|
||||
onDestinationSelected: (index) =>
|
||||
_handleQuickSwitch(index, context),
|
||||
contactsUnreadCount: connector.getTotalContactsUnreadCount(),
|
||||
channelsUnreadCount: connector.getTotalChannelsUnreadCount(),
|
||||
highContrast: _usePaletteOverlay,
|
||||
child: Selector<MeshCoreConnector, (int, int)>(
|
||||
selector: (_, connector) => (
|
||||
connector.getTotalContactsUnreadCount(),
|
||||
connector.getTotalChannelsUnreadCount(),
|
||||
),
|
||||
builder: (context, unread, child) => QuickSwitchBar(
|
||||
selectedIndex: 2,
|
||||
onDestinationSelected: (index) =>
|
||||
_handleQuickSwitch(index, context),
|
||||
contactsUnreadCount: unread.$1,
|
||||
channelsUnreadCount: unread.$2,
|
||||
highContrast: _usePaletteOverlay,
|
||||
),
|
||||
),
|
||||
),
|
||||
floatingActionButton:
|
||||
@@ -1130,8 +1176,7 @@ class _MapScreenState extends State<MapScreen> {
|
||||
}) {
|
||||
final visibleContactsSignature = Object.hashAll(
|
||||
contacts.map(
|
||||
(contact) =>
|
||||
Object.hash(_mapContactSignature(contact), _ageOf(contact)),
|
||||
(contact) => Object.hash(contact.publicKeyHex, _ageOf(contact)),
|
||||
),
|
||||
);
|
||||
final key = _NodeMarkersCacheKey(
|
||||
@@ -4226,6 +4271,7 @@ int _mapContactSignature(Contact contact) {
|
||||
|
||||
class _MapConnectorSnapshot {
|
||||
final MeshCoreConnector connector;
|
||||
final List<Contact> allContacts;
|
||||
final int contactsSignature;
|
||||
final int markerSignature;
|
||||
final int batterySignature;
|
||||
@@ -4233,6 +4279,7 @@ class _MapConnectorSnapshot {
|
||||
|
||||
const _MapConnectorSnapshot({
|
||||
required this.connector,
|
||||
required this.allContacts,
|
||||
required this.contactsSignature,
|
||||
required this.markerSignature,
|
||||
required this.batterySignature,
|
||||
@@ -4285,6 +4332,7 @@ class _MapConnectorSnapshot {
|
||||
|
||||
return _MapConnectorSnapshot(
|
||||
connector: connector,
|
||||
allContacts: allContacts,
|
||||
contactsSignature: contactsSignature,
|
||||
markerSignature: Object.hashAll(markerParts),
|
||||
batterySignature: batterySignature,
|
||||
@@ -4296,8 +4344,6 @@ class _MapConnectorSnapshot {
|
||||
connector.currentBwHz,
|
||||
connector.currentSf,
|
||||
connector.currentTxPower,
|
||||
connector.getTotalContactsUnreadCount(),
|
||||
connector.getTotalChannelsUnreadCount(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import 'app_settings_service.dart';
|
||||
import '../storage/channel_store.dart';
|
||||
import '../storage/contact_store.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../storage/history_store.dart';
|
||||
|
||||
const int _backupVersion = 1;
|
||||
const int _pbkdf2Iterations = 310000;
|
||||
@@ -134,6 +135,7 @@ class BackupService {
|
||||
required String password,
|
||||
}) async {
|
||||
if (items.isEmpty) throw StateError('Select at least one backup item');
|
||||
await connector.flushPendingWrites();
|
||||
final includedItems = Set<BackupItem>.of(items);
|
||||
final customVars = connector.currentCustomVars ?? const <String, String>{};
|
||||
if (includedItems.isEmpty) {
|
||||
@@ -175,7 +177,9 @@ class BackupService {
|
||||
};
|
||||
}
|
||||
if (includedItems.contains(BackupItem.regions)) {
|
||||
node['preferences'] = _snapshotPreferences((key) => key == 'regions');
|
||||
node['preferences'] = await _snapshotPreferences(
|
||||
(key) => key == 'regions',
|
||||
);
|
||||
}
|
||||
sections[BackupSection.nodeSettings.name] = node;
|
||||
}
|
||||
@@ -239,8 +243,8 @@ class BackupService {
|
||||
}
|
||||
sections[section.name] = {
|
||||
'preferences': section == BackupSection.appSettings
|
||||
? _snapshotAppSettingsPreferences(sectionItems)
|
||||
: _snapshotPreferences(
|
||||
? await _snapshotAppSettingsPreferences(sectionItems)
|
||||
: await _snapshotPreferences(
|
||||
(key) =>
|
||||
_preferenceBelongsToItems(key, sectionItems, devicePrefix),
|
||||
),
|
||||
@@ -266,6 +270,7 @@ class BackupService {
|
||||
required AppSettingsService appSettingsService,
|
||||
}) async {
|
||||
if (items.isEmpty) throw StateError('Select at least one item to restore');
|
||||
await connector.flushPendingWrites();
|
||||
final payload = await _decodeImport(contents, password: password);
|
||||
final sectionData = payload['sections'];
|
||||
if (sectionData is! Map) throw const FormatException('Missing backup data');
|
||||
@@ -956,14 +961,19 @@ class BackupService {
|
||||
static int _intOr(Object? value, int fallback) =>
|
||||
value is int ? value : fallback;
|
||||
|
||||
static Map<String, Object?> _snapshotPreferences(
|
||||
static Future<Map<String, Object?>> _snapshotPreferences(
|
||||
bool Function(String) include,
|
||||
) {
|
||||
) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final values = <String, Object?>{};
|
||||
for (final key in prefs.getKeys()) {
|
||||
for (final key in {
|
||||
...prefs.getKeys(),
|
||||
...await HistoryStore.instance.getKeys(),
|
||||
}) {
|
||||
if (!include(key)) continue;
|
||||
final value = prefs.get(key);
|
||||
final value = HistoryStore.isHistoryKey(key)
|
||||
? await HistoryStore.instance.getString(key)
|
||||
: prefs.get(key);
|
||||
if (value is String) {
|
||||
values[key] = _expandJsonPreference(value);
|
||||
} else if (value is bool || value is int || value is double) {
|
||||
@@ -1003,10 +1013,10 @@ class BackupService {
|
||||
return value;
|
||||
}
|
||||
|
||||
static Map<String, Object?> _snapshotAppSettingsPreferences(
|
||||
static Future<Map<String, Object?>> _snapshotAppSettingsPreferences(
|
||||
Set<BackupItem> items,
|
||||
) {
|
||||
final values = _snapshotPreferences(
|
||||
) async {
|
||||
final values = await _snapshotPreferences(
|
||||
(key) => _preferenceBelongsToItems(key, items, ''),
|
||||
);
|
||||
final appSettings = _asMap(values['app_settings']);
|
||||
@@ -1224,30 +1234,37 @@ class BackupService {
|
||||
final existingAppSettings = _asJsonMapPreference(
|
||||
prefs.getString('app_settings'),
|
||||
);
|
||||
final matching = prefs.getKeys().where((key) {
|
||||
if (section == BackupSection.appSettings &&
|
||||
key == 'app_settings' &&
|
||||
!items.contains(BackupItem.appSettings)) {
|
||||
return false;
|
||||
}
|
||||
if (!_preferenceBelongsToSection(
|
||||
key,
|
||||
section,
|
||||
devicePrefix: destinationPrefix,
|
||||
) ||
|
||||
!_preferenceBelongsToItems(key, items, destinationPrefix)) {
|
||||
return false;
|
||||
}
|
||||
if (section == BackupSection.appSettings ||
|
||||
section == BackupSection.nodeSettings) {
|
||||
return true;
|
||||
}
|
||||
return _hasDevicePrefix(key, section, destinationPrefix) ||
|
||||
(section == BackupSection.channels &&
|
||||
key.startsWith('message_filter_'));
|
||||
}).toList();
|
||||
final matching =
|
||||
{...prefs.getKeys(), ...await HistoryStore.instance.getKeys()}.where((
|
||||
key,
|
||||
) {
|
||||
if (section == BackupSection.appSettings &&
|
||||
key == 'app_settings' &&
|
||||
!items.contains(BackupItem.appSettings)) {
|
||||
return false;
|
||||
}
|
||||
if (!_preferenceBelongsToSection(
|
||||
key,
|
||||
section,
|
||||
devicePrefix: destinationPrefix,
|
||||
) ||
|
||||
!_preferenceBelongsToItems(key, items, destinationPrefix)) {
|
||||
return false;
|
||||
}
|
||||
if (section == BackupSection.appSettings ||
|
||||
section == BackupSection.nodeSettings) {
|
||||
return true;
|
||||
}
|
||||
return _hasDevicePrefix(key, section, destinationPrefix) ||
|
||||
(section == BackupSection.channels &&
|
||||
key.startsWith('message_filter_'));
|
||||
}).toList();
|
||||
for (final key in matching) {
|
||||
await prefs.remove(key);
|
||||
if (HistoryStore.isHistoryKey(key)) {
|
||||
await HistoryStore.instance.remove(key);
|
||||
} else {
|
||||
await prefs.remove(key);
|
||||
}
|
||||
}
|
||||
for (final entry in values.entries) {
|
||||
if (!_preferenceBelongsToItems(entry.key, items, sourcePrefix)) {
|
||||
@@ -1260,7 +1277,13 @@ class BackupService {
|
||||
destinationPrefix,
|
||||
);
|
||||
final value = entry.value;
|
||||
if (section == BackupSection.appSettings && key == 'app_settings') {
|
||||
if (HistoryStore.isHistoryKey(key)) {
|
||||
await HistoryStore.instance.setString(
|
||||
key,
|
||||
value is String ? value : jsonEncode(value),
|
||||
);
|
||||
} else if (section == BackupSection.appSettings &&
|
||||
key == 'app_settings') {
|
||||
final storedIncoming = _asJsonMapPreference(value);
|
||||
if (storedIncoming == null) {
|
||||
throw const FormatException('Invalid app settings in backup');
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export 'map_tile_cache_repository_stub.dart'
|
||||
if (dart.library.io) 'map_tile_cache_repository_io.dart';
|
||||
@@ -0,0 +1,312 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
|
||||
CacheInfoRepository createMapTileCacheRepository(String cacheKey) {
|
||||
if (!Platform.isLinux && !Platform.isWindows) {
|
||||
return CacheObjectProvider(databaseName: cacheKey);
|
||||
}
|
||||
sqfliteFfiInit();
|
||||
return SqliteMapTileCacheRepository(databaseName: cacheKey);
|
||||
}
|
||||
|
||||
/// Tile metadata stays in SQLite; only queried rows become Dart objects.
|
||||
class SqliteMapTileCacheRepository implements CacheInfoRepository {
|
||||
SqliteMapTileCacheRepository({
|
||||
required this.databaseName,
|
||||
Future<Directory> Function()? directory,
|
||||
DatabaseFactory? factory,
|
||||
}) : _directory = directory ?? getApplicationSupportDirectory,
|
||||
_factory = factory ?? databaseFactoryFfi;
|
||||
|
||||
static const int schemaVersion = 1;
|
||||
static const int legacyImportVersion = 1;
|
||||
static const String _table = 'cacheObject';
|
||||
static const String _migrationTable = 'cacheMigration';
|
||||
static const String _legacyMigration = 'legacyJson';
|
||||
static const String _unreadableSuffix = '.unreadable';
|
||||
|
||||
final String databaseName;
|
||||
final Future<Directory> Function() _directory;
|
||||
final DatabaseFactory _factory;
|
||||
Future<Directory>? _resolvedDirectory;
|
||||
Future<Database>? _opening;
|
||||
int _connections = 0;
|
||||
|
||||
Future<Directory> _baseDirectory() => _resolvedDirectory ??= _directory();
|
||||
|
||||
Future<String> _databasePath() async =>
|
||||
'${(await _baseDirectory()).path}${Platform.pathSeparator}$databaseName.db';
|
||||
|
||||
Future<File> _legacyFile() async => File(
|
||||
'${(await _baseDirectory()).path}${Platform.pathSeparator}$databaseName.json',
|
||||
);
|
||||
|
||||
Future<Database> _database() async {
|
||||
final pending = _opening;
|
||||
if (pending != null) return pending;
|
||||
final started = _openDatabase();
|
||||
_opening = started;
|
||||
try {
|
||||
return await started;
|
||||
} catch (_) {
|
||||
if (identical(_opening, started)) _opening = null;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<Database> _openDatabase() async {
|
||||
final path = await _databasePath();
|
||||
await File(path).parent.create(recursive: true);
|
||||
final db = await _factory.openDatabase(
|
||||
path,
|
||||
options: OpenDatabaseOptions(
|
||||
version: schemaVersion,
|
||||
onCreate: (db, version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE $_table (
|
||||
_id INTEGER PRIMARY KEY,
|
||||
url TEXT NOT NULL,
|
||||
key TEXT NOT NULL UNIQUE,
|
||||
relativePath TEXT NOT NULL,
|
||||
eTag TEXT,
|
||||
validTill INTEGER NOT NULL,
|
||||
touched INTEGER NOT NULL,
|
||||
length INTEGER
|
||||
)
|
||||
''');
|
||||
await db.execute('CREATE INDEX cacheTouched ON $_table (touched)');
|
||||
await db.execute('''
|
||||
CREATE TABLE $_migrationTable (
|
||||
name TEXT PRIMARY KEY,
|
||||
version INTEGER NOT NULL
|
||||
)
|
||||
''');
|
||||
},
|
||||
),
|
||||
);
|
||||
try {
|
||||
await _importLegacyJson(db);
|
||||
return db;
|
||||
} catch (_) {
|
||||
await db.close();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _importLegacyJson(Database db) async {
|
||||
final versions = await db.query(
|
||||
_migrationTable,
|
||||
where: 'name = ?',
|
||||
whereArgs: [_legacyMigration],
|
||||
);
|
||||
final version = versions.isEmpty ? 0 : versions.single['version'] as int;
|
||||
if (version > legacyImportVersion) return;
|
||||
final legacy = await _legacyFile();
|
||||
var unreadable = false;
|
||||
if (version < legacyImportVersion) {
|
||||
final List<Map<String, Object?>> records;
|
||||
(records, unreadable) = await compute(_readLegacyRecords, legacy.path);
|
||||
await db.transaction((transaction) async {
|
||||
final batch = transaction.batch();
|
||||
for (final record in records) {
|
||||
batch.insert(
|
||||
_table,
|
||||
record,
|
||||
conflictAlgorithm: ConflictAlgorithm.ignore,
|
||||
);
|
||||
}
|
||||
batch.insert(_migrationTable, {
|
||||
'name': _legacyMigration,
|
||||
'version': legacyImportVersion,
|
||||
}, conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
await batch.commit(noResult: true);
|
||||
});
|
||||
}
|
||||
// A committed version marker makes a crash before cleanup safe to retry.
|
||||
try {
|
||||
if (unreadable && await legacy.exists()) {
|
||||
// Kept for inspection rather than deleted; it is never imported again.
|
||||
debugPrint('Map metadata migration skipped unreadable records');
|
||||
await legacy.rename('${legacy.path}$_unreadableSuffix');
|
||||
}
|
||||
for (final file in [legacy, File('${legacy.path}.tmp')]) {
|
||||
if (await file.exists()) await file.delete();
|
||||
}
|
||||
} on FileSystemException catch (error) {
|
||||
debugPrint('Map metadata migration cleanup: $error');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> open() async {
|
||||
_connections++;
|
||||
try {
|
||||
await _database();
|
||||
return true;
|
||||
} catch (_) {
|
||||
_connections--;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> close() async {
|
||||
if (_connections == 0 || --_connections > 0) return false;
|
||||
final pending = _opening;
|
||||
_opening = null;
|
||||
if (pending != null) await (await pending).close();
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> exists() async => File(await _databasePath()).exists();
|
||||
|
||||
@override
|
||||
Future<void> deleteDataFile() async {
|
||||
if (_connections != 0) {
|
||||
throw StateError('Close map metadata connections before deleting it.');
|
||||
}
|
||||
await _factory.deleteDatabase(await _databasePath());
|
||||
final legacy = await _legacyFile();
|
||||
for (final file in [
|
||||
legacy,
|
||||
File('${legacy.path}.tmp'),
|
||||
File('${legacy.path}$_unreadableSuffix'),
|
||||
]) {
|
||||
if (await file.exists()) await file.delete();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<CacheObject?> get(String key) async {
|
||||
final rows = await (await _database()).query(
|
||||
_table,
|
||||
where: 'key = ?',
|
||||
whereArgs: [key],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : CacheObject.fromMap(rows.single);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<CacheObject> insert(
|
||||
CacheObject cacheObject, {
|
||||
bool setTouchedToNow = true,
|
||||
}) async {
|
||||
if (cacheObject.id != null) {
|
||||
throw ArgumentError('Inserted cache objects must not have an ID.');
|
||||
}
|
||||
final map = cacheObject.toMap(setTouchedToNow: setTouchedToNow);
|
||||
final id = await (await _database()).insert(_table, map);
|
||||
return CacheObject.fromMap({...map, CacheObject.columnId: id});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> update(
|
||||
CacheObject cacheObject, {
|
||||
bool setTouchedToNow = true,
|
||||
}) async {
|
||||
if (cacheObject.id == null) {
|
||||
throw ArgumentError('Updated cache objects must have an ID.');
|
||||
}
|
||||
return (await _database()).update(
|
||||
_table,
|
||||
cacheObject.toMap(setTouchedToNow: setTouchedToNow),
|
||||
where: '_id = ?',
|
||||
whereArgs: [cacheObject.id],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<dynamic> updateOrInsert(CacheObject cacheObject) =>
|
||||
cacheObject.id == null ? insert(cacheObject) : update(cacheObject);
|
||||
|
||||
@override
|
||||
Future<int> delete(int id) async =>
|
||||
(await _database()).delete(_table, where: '_id = ?', whereArgs: [id]);
|
||||
|
||||
@override
|
||||
Future<int> deleteAll(Iterable<int> ids) async {
|
||||
final unique = ids.toSet().toList();
|
||||
if (unique.isEmpty) return 0;
|
||||
final db = await _database();
|
||||
return db.transaction((transaction) async {
|
||||
var deleted = 0;
|
||||
for (var start = 0; start < unique.length; start += 500) {
|
||||
final chunk = unique.skip(start).take(500).toList();
|
||||
deleted += await transaction.delete(
|
||||
_table,
|
||||
where: '_id IN (${List.filled(chunk.length, '?').join(',')})',
|
||||
whereArgs: chunk,
|
||||
);
|
||||
}
|
||||
return deleted;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<CacheObject>> getAllObjects() async =>
|
||||
CacheObject.fromMapList(await (await _database()).query(_table));
|
||||
|
||||
@override
|
||||
Future<List<CacheObject>> getObjectsOverCapacity(int capacity) async =>
|
||||
CacheObject.fromMapList(
|
||||
await (await _database()).query(
|
||||
_table,
|
||||
where: 'touched < ?',
|
||||
whereArgs: [
|
||||
DateTime.now()
|
||||
.subtract(const Duration(days: 1))
|
||||
.millisecondsSinceEpoch,
|
||||
],
|
||||
orderBy: 'touched DESC, _id DESC',
|
||||
offset: capacity,
|
||||
limit: 100,
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<List<CacheObject>> getOldObjects(Duration maxAge) async =>
|
||||
CacheObject.fromMapList(
|
||||
await (await _database()).query(
|
||||
_table,
|
||||
where: 'touched < ?',
|
||||
whereArgs: [DateTime.now().subtract(maxAge).millisecondsSinceEpoch],
|
||||
orderBy: 'touched ASC, _id ASC',
|
||||
limit: 100,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns the importable records and whether any part of the file was
|
||||
/// unreadable. A broken file must not keep the tile cache from opening.
|
||||
(List<Map<String, Object?>>, bool) _readLegacyRecords(String path) {
|
||||
final file = File(path);
|
||||
if (!file.existsSync()) return ([], false);
|
||||
final Object? decoded;
|
||||
try {
|
||||
decoded = jsonDecode(file.readAsStringSync());
|
||||
} on Exception {
|
||||
return ([], true);
|
||||
}
|
||||
if (decoded is! List) return ([], true);
|
||||
final records = <Map<String, Object?>>[];
|
||||
var unreadable = false;
|
||||
for (final value in decoded) {
|
||||
try {
|
||||
records.add(
|
||||
CacheObject.fromMap(
|
||||
(value as Map).cast<String, dynamic>(),
|
||||
).toMap(setTouchedToNow: false)..remove(CacheObject.columnId),
|
||||
);
|
||||
} catch (_) {
|
||||
unreadable = true;
|
||||
}
|
||||
}
|
||||
return (records, unreadable);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
|
||||
CacheInfoRepository createMapTileCacheRepository(String cacheKey) =>
|
||||
NonStoringObjectProvider();
|
||||
@@ -8,6 +8,7 @@ import 'package:flutter_map/flutter_map.dart';
|
||||
import '../models/app_settings.dart';
|
||||
import '../theme/mesh_theme.dart';
|
||||
import 'app_settings_service.dart';
|
||||
import 'map_tile_cache_repository.dart';
|
||||
|
||||
enum MapRasterSourcePreset {
|
||||
osmAuto('osm_auto'),
|
||||
@@ -347,6 +348,7 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
cacheKey,
|
||||
stalePeriod: const Duration(days: 365),
|
||||
maxNrOfCacheObjects: 200000,
|
||||
repo: createMapTileCacheRepository(cacheKey),
|
||||
),
|
||||
) {
|
||||
tileProvider = CachedNetworkTileProvider(cacheManager: this.cacheManager);
|
||||
@@ -534,19 +536,23 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
Future<CachedTileInventory> getCachedTileInventory() async {
|
||||
final repo = _concreteCacheManager.config.repo;
|
||||
await repo.open();
|
||||
final objects = await repo.getAllObjects();
|
||||
final tiles = <CachedTileInfo>[];
|
||||
int totalBytes = 0;
|
||||
try {
|
||||
final objects = await repo.getAllObjects();
|
||||
final tiles = <CachedTileInfo>[];
|
||||
int totalBytes = 0;
|
||||
|
||||
for (final object in objects) {
|
||||
totalBytes += object.length ?? 0;
|
||||
final tile = _parseCachedTile(object);
|
||||
if (tile != null) {
|
||||
tiles.add(tile);
|
||||
for (final object in objects) {
|
||||
totalBytes += object.length ?? 0;
|
||||
final tile = _parseCachedTile(object);
|
||||
if (tile != null) {
|
||||
tiles.add(tile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return CachedTileInventory(tiles: tiles, totalBytes: totalBytes);
|
||||
return CachedTileInventory(tiles: tiles, totalBytes: totalBytes);
|
||||
} finally {
|
||||
await repo.close();
|
||||
}
|
||||
}
|
||||
|
||||
List<CachedTileInfo> filterTilesForActiveSource(
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../models/path_history.dart';
|
||||
import '../models/path_selection.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/coalesced_writes.dart';
|
||||
import 'route_chooser.dart';
|
||||
import 'storage_service.dart';
|
||||
@@ -13,7 +14,10 @@ class PathHistoryService extends ChangeNotifier {
|
||||
final StorageService _storage;
|
||||
final Map<String, ContactPathHistory> _cache = {};
|
||||
final Map<String, _FloodStats> _floodStats = {};
|
||||
final Map<String, Future<void>> _pendingLoads = {};
|
||||
final Map<String, Future<bool>> _pendingLoads = {};
|
||||
int _generation = 0;
|
||||
bool _disposed = false;
|
||||
Future<void> _clearing = Future<void>.value();
|
||||
// A path record lands for most received messages, so saves are batched.
|
||||
final CoalescedWrites _writes = CoalescedWrites(
|
||||
delay: const Duration(seconds: 5),
|
||||
@@ -43,9 +47,12 @@ class PathHistoryService extends ChangeNotifier {
|
||||
_now = clock ?? DateTime.now;
|
||||
|
||||
void setDevicePublicKey(String publicKeyHex) {
|
||||
if (_disposed) return;
|
||||
// Queued saves use the storage key on entry, so they still land under
|
||||
// the previous radio's key.
|
||||
unawaited(_writes.flush());
|
||||
_generation++;
|
||||
_pendingLoads.clear();
|
||||
_storage.setPublicKeyHex = publicKeyHex;
|
||||
_cache.clear();
|
||||
_cacheAccessOrder.clear();
|
||||
@@ -59,6 +66,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
void handlePathUpdated(Contact contact, {double initialWeight = 1.0}) {
|
||||
if (_disposed) return;
|
||||
if (contact.pathLength < 0 && contact.path.isEmpty) return;
|
||||
final hopCount = contact.pathLength < 0
|
||||
? contact.path.length
|
||||
@@ -77,6 +85,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
void recordPathAttempt(String contactPubKeyHex, PathSelection selection) {
|
||||
if (_disposed) return;
|
||||
if (selection.useFlood) {
|
||||
_updateFloodStats(contactPubKeyHex);
|
||||
return;
|
||||
@@ -104,11 +113,18 @@ class PathHistoryService extends ChangeNotifier {
|
||||
double successIncrement = 0.5,
|
||||
double maxWeight = 5.0,
|
||||
}) {
|
||||
if (_disposed) return;
|
||||
// A flood answered directly credits the direct (zero-hop) path.
|
||||
if (hopCount < 0 || (pathBytes.isEmpty && hopCount != 0)) return;
|
||||
if (!_cache.containsKey(contactPubKeyHex)) {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
if (!_cache.containsKey(contactPubKeyHex)) return;
|
||||
final generation = _generation;
|
||||
_ensureLoaded(contactPubKeyHex).then((loaded) {
|
||||
if (!loaded ||
|
||||
_disposed ||
|
||||
generation != _generation ||
|
||||
!_cache.containsKey(contactPubKeyHex)) {
|
||||
return;
|
||||
}
|
||||
recordFloodPathAttribution(
|
||||
contactPubKeyHex: contactPubKeyHex,
|
||||
pathBytes: pathBytes,
|
||||
@@ -160,6 +176,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
double failureDecrement = 0.5,
|
||||
double maxWeight = 5.0,
|
||||
}) {
|
||||
if (_disposed) return;
|
||||
if (selection.useFlood) {
|
||||
final stats = _floodStats.putIfAbsent(
|
||||
contactPubKeyHex,
|
||||
@@ -176,8 +193,14 @@ class PathHistoryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
if (!_cache.containsKey(contactPubKeyHex)) {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
if (!_cache.containsKey(contactPubKeyHex)) return;
|
||||
final generation = _generation;
|
||||
_ensureLoaded(contactPubKeyHex).then((loaded) {
|
||||
if (!loaded ||
|
||||
_disposed ||
|
||||
generation != _generation ||
|
||||
!_cache.containsKey(contactPubKeyHex)) {
|
||||
return;
|
||||
}
|
||||
recordPathResult(
|
||||
contactPubKeyHex,
|
||||
selection,
|
||||
@@ -294,6 +317,8 @@ class PathHistoryService extends ChangeNotifier {
|
||||
double? recentFailure,
|
||||
DateTime? statsAt,
|
||||
}) {
|
||||
if (_disposed) return;
|
||||
final generation = _generation;
|
||||
void add() => _addPathRecordInternal(
|
||||
contactPubKeyHex,
|
||||
hopCount,
|
||||
@@ -313,27 +338,43 @@ class PathHistoryService extends ChangeNotifier {
|
||||
if (_cache.containsKey(contactPubKeyHex)) {
|
||||
add();
|
||||
} else {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) => add());
|
||||
_ensureLoaded(contactPubKeyHex).then((loaded) {
|
||||
if (loaded && !_disposed && generation == _generation) add();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _ensureLoaded(String contactPubKeyHex) {
|
||||
if (_cache.containsKey(contactPubKeyHex)) return Future.value();
|
||||
return _pendingLoads[contactPubKeyHex] ??=
|
||||
_loadHistoryFromStorage(contactPubKeyHex)
|
||||
.then((loaded) {
|
||||
_cache[contactPubKeyHex] ??=
|
||||
loaded ??
|
||||
ContactPathHistory(
|
||||
contactPubKeyHex: contactPubKeyHex,
|
||||
recentPaths: [],
|
||||
);
|
||||
_trackAccess(contactPubKeyHex);
|
||||
_evictIfNeeded();
|
||||
})
|
||||
.whenComplete(() {
|
||||
_pendingLoads.remove(contactPubKeyHex);
|
||||
});
|
||||
Future<bool> _ensureLoaded(String contactPubKeyHex) {
|
||||
if (_disposed) return Future.value(false);
|
||||
if (_cache.containsKey(contactPubKeyHex)) return Future.value(true);
|
||||
final existing = _pendingLoads[contactPubKeyHex];
|
||||
if (existing != null) return existing;
|
||||
final generation = _generation;
|
||||
late final Future<bool> pending;
|
||||
pending = _loadHistoryFromStorage(contactPubKeyHex)
|
||||
.then((loaded) {
|
||||
if (_disposed ||
|
||||
generation != _generation ||
|
||||
!identical(_pendingLoads[contactPubKeyHex], pending)) {
|
||||
return false;
|
||||
}
|
||||
_cache[contactPubKeyHex] ??=
|
||||
loaded ??
|
||||
ContactPathHistory(
|
||||
contactPubKeyHex: contactPubKeyHex,
|
||||
recentPaths: [],
|
||||
);
|
||||
_trackAccess(contactPubKeyHex);
|
||||
_evictIfNeeded();
|
||||
return true;
|
||||
})
|
||||
.whenComplete(() {
|
||||
if (identical(_pendingLoads[contactPubKeyHex], pending)) {
|
||||
_pendingLoads.remove(contactPubKeyHex);
|
||||
}
|
||||
});
|
||||
_pendingLoads[contactPubKeyHex] = pending;
|
||||
return pending;
|
||||
}
|
||||
|
||||
void _addPathRecordInternal(
|
||||
@@ -351,6 +392,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
double? recentFailure,
|
||||
DateTime? statsAt,
|
||||
}) {
|
||||
if (_disposed) return;
|
||||
var history = _cache[contactPubKeyHex];
|
||||
if (history == null) return;
|
||||
_version++;
|
||||
@@ -429,6 +471,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
/// Reads saved paths straight from storage without adding them to the
|
||||
/// cache, evicting anything, or notifying listeners.
|
||||
Future<List<PathRecord>> readStoredPaths(String contactPubKeyHex) async {
|
||||
if (_disposed) return [];
|
||||
final cached = _cache[contactPubKeyHex];
|
||||
if (cached != null) return cached.recentPaths;
|
||||
final stored = await _loadHistoryFromStorage(contactPubKeyHex);
|
||||
@@ -436,13 +479,16 @@ class PathHistoryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
List<PathRecord> getRecentPaths(String contactPubKeyHex) {
|
||||
if (_disposed) return [];
|
||||
final history = _cache[contactPubKeyHex];
|
||||
if (history != null) {
|
||||
_trackAccess(contactPubKeyHex);
|
||||
return history.recentPaths;
|
||||
}
|
||||
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
final generation = _generation;
|
||||
_ensureLoaded(contactPubKeyHex).then((loaded) {
|
||||
if (!loaded || _disposed || generation != _generation) return;
|
||||
if (_cache[contactPubKeyHex]?.recentPaths.isNotEmpty ?? false) {
|
||||
_version++;
|
||||
notifyListeners();
|
||||
@@ -455,10 +501,12 @@ class PathHistoryService extends ChangeNotifier {
|
||||
Future<ContactPathHistory?> _loadHistoryFromStorage(
|
||||
String contactPubKeyHex,
|
||||
) async {
|
||||
// An evicted contact may still have a queued save; it reaches the prefs
|
||||
// cache synchronously, so the load below reads it.
|
||||
unawaited(_writes.flush());
|
||||
return await _storage.loadPathHistory(contactPubKeyHex);
|
||||
final generation = _generation;
|
||||
await _clearing;
|
||||
await _writes.flush();
|
||||
if (_disposed || generation != _generation) return null;
|
||||
final history = await _storage.loadPathHistory(contactPubKeyHex);
|
||||
return _disposed || generation != _generation ? null : history;
|
||||
}
|
||||
|
||||
PathRecord? getFastestPath(String contactPubKeyHex) {
|
||||
@@ -494,12 +542,38 @@ class PathHistoryService extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
|
||||
/// Runs [clear] after earlier clears and queued saves. [_clearing] itself
|
||||
/// never fails, so one failed clear cannot break later loads and flushes;
|
||||
/// the returned future still reports the failure to its caller.
|
||||
Future<void> _queueClear(int generation, Future<void> Function() clear) {
|
||||
final previous = _clearing;
|
||||
final run = () async {
|
||||
await previous;
|
||||
await _writes.flush();
|
||||
if (_disposed || generation != _generation) return;
|
||||
await clear();
|
||||
}();
|
||||
_clearing = run.then<void>(
|
||||
(_) {},
|
||||
onError: (Object error, StackTrace _) {
|
||||
appLogger.warn('Clearing path history failed: $error', tag: 'Storage');
|
||||
},
|
||||
);
|
||||
return run;
|
||||
}
|
||||
|
||||
Future<void> clearPathHistory(String contactPubKeyHex) async {
|
||||
if (_disposed) return;
|
||||
final generation = _generation;
|
||||
_pendingLoads.remove(contactPubKeyHex);
|
||||
_cache.remove(contactPubKeyHex);
|
||||
_cacheAccessOrder.remove(contactPubKeyHex);
|
||||
_floodStats.remove(contactPubKeyHex);
|
||||
_writes.cancel(contactPubKeyHex);
|
||||
await _storage.clearPathHistory(contactPubKeyHex);
|
||||
await _queueClear(generation, () {
|
||||
return _storage.clearPathHistory(contactPubKeyHex);
|
||||
});
|
||||
if (_disposed || generation != _generation) return;
|
||||
_version++;
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -508,6 +582,8 @@ class PathHistoryService extends ChangeNotifier {
|
||||
String contactPubKeyHex,
|
||||
List<int> pathBytes,
|
||||
) async {
|
||||
if (_disposed) return;
|
||||
final generation = _generation;
|
||||
final history = _cache[contactPubKeyHex];
|
||||
if (history == null) return;
|
||||
|
||||
@@ -519,8 +595,12 @@ class PathHistoryService extends ChangeNotifier {
|
||||
recentPaths: updatedPaths,
|
||||
);
|
||||
|
||||
final updated = _cache[contactPubKeyHex]!;
|
||||
_writes.cancel(contactPubKeyHex);
|
||||
await _storage.savePathHistory(contactPubKeyHex, _cache[contactPubKeyHex]!);
|
||||
await _writes.flush();
|
||||
if (_disposed || generation != _generation) return;
|
||||
await _storage.savePathHistory(contactPubKeyHex, updated);
|
||||
if (_disposed || generation != _generation) return;
|
||||
_version++;
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -607,20 +687,39 @@ class PathHistoryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
/// Runs queued saves now, e.g. before the app is backgrounded.
|
||||
Future<void> flushPendingWrites() => _writes.flush();
|
||||
Future<void> flushPendingWrites() async {
|
||||
await _clearing;
|
||||
await _writes.flush();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
unawaited(_writes.flush());
|
||||
_disposed = true;
|
||||
_generation++;
|
||||
_pendingLoads.clear();
|
||||
_cache.clear();
|
||||
_cacheAccessOrder.clear();
|
||||
_floodStats.clear();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void clearAllHistories() {
|
||||
if (_disposed) return;
|
||||
final generation = ++_generation;
|
||||
_pendingLoads.clear();
|
||||
_cache.clear();
|
||||
_cacheAccessOrder.clear();
|
||||
_floodStats.clear();
|
||||
_writes.dispose();
|
||||
_storage.clearAllPathHistories();
|
||||
// Nothing awaits this one; _queueClear logs a failure.
|
||||
unawaited(
|
||||
_queueClear(
|
||||
generation,
|
||||
_storage.clearAllPathHistories,
|
||||
).catchError((Object _) {}),
|
||||
);
|
||||
_version = 0;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import '../models/delivery_observation.dart';
|
||||
import '../models/path_history.dart';
|
||||
import '../storage/legacy_key_migration.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../storage/history_store.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
class StorageService {
|
||||
@@ -64,30 +65,32 @@ class StorageService {
|
||||
String contactPubKeyHex,
|
||||
ContactPathHistory history,
|
||||
) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final prefs = HistoryStore.instance;
|
||||
final key = _pathHistoryKey(contactPubKeyHex);
|
||||
final jsonStr = jsonEncode(history.toJson());
|
||||
await prefs.setString(key, jsonStr);
|
||||
}
|
||||
|
||||
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final prefs = HistoryStore.instance;
|
||||
final scope = _publicKeyHex;
|
||||
final allowLegacyMigration =
|
||||
scope.isNotEmpty && canMigrateLegacyKeys(scope);
|
||||
final key = _pathHistoryKey(contactPubKeyHex);
|
||||
var jsonStr = prefs.getString(key);
|
||||
var jsonStr = await prefs.getString(key);
|
||||
final legacyKey = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
if (jsonStr == null &&
|
||||
_publicKeyHex.isNotEmpty &&
|
||||
canMigrateLegacyKeys(_publicKeyHex)) {
|
||||
if (jsonStr == null && allowLegacyMigration) {
|
||||
// Move the pre-scoping history into the first radio that loads it so
|
||||
// learned routes survive the upgrade without leaking into other radios.
|
||||
final legacy = prefs.getString(legacyKey);
|
||||
final legacy = await prefs.getString(legacyKey);
|
||||
if (legacy != null) {
|
||||
await prefs.setString(key, legacy);
|
||||
await prefs.remove(legacyKey);
|
||||
if (await prefs.setString(key, legacy)) {
|
||||
await prefs.remove(legacyKey);
|
||||
}
|
||||
jsonStr = legacy;
|
||||
}
|
||||
} else if (jsonStr == null && _publicKeyHex.isEmpty) {
|
||||
jsonStr = prefs.getString(legacyKey);
|
||||
} else if (jsonStr == null && scope.isEmpty) {
|
||||
jsonStr = await prefs.getString(legacyKey);
|
||||
}
|
||||
|
||||
if (jsonStr == null) return null;
|
||||
@@ -101,7 +104,7 @@ class StorageService {
|
||||
}
|
||||
|
||||
Future<void> clearPathHistory(String contactPubKeyHex) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final prefs = HistoryStore.instance;
|
||||
await prefs.remove(_pathHistoryKey(contactPubKeyHex));
|
||||
await prefs.remove('$_pathHistoryPrefix$contactPubKeyHex');
|
||||
}
|
||||
@@ -109,7 +112,7 @@ class StorageService {
|
||||
/// Clears the path histories of the connected radio only. Histories of other
|
||||
/// radios are left alone; with no radio scope set, everything is cleared.
|
||||
Future<void> clearAllPathHistories() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final prefs = HistoryStore.instance;
|
||||
final scopedPrefix = _publicKeyHex.isEmpty
|
||||
? _pathHistoryPrefix
|
||||
: '$_pathHistoryPrefix${_publicKeyHex}_';
|
||||
@@ -117,7 +120,7 @@ class StorageService {
|
||||
// radio on the next load and bring the cleared routes back.
|
||||
final clearLegacy =
|
||||
_publicKeyHex.isNotEmpty && canMigrateLegacyKeys(_publicKeyHex);
|
||||
final pathHistoryKeys = prefs.getKeys().where((key) {
|
||||
final pathHistoryKeys = (await prefs.getKeys()).where((key) {
|
||||
if (key.startsWith(scopedPrefix)) return true;
|
||||
return clearLegacy &&
|
||||
key.startsWith(_pathHistoryPrefix) &&
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -15,6 +15,7 @@ class CoalescedWrites {
|
||||
|
||||
final Duration delay;
|
||||
final Map<String, Future<void> Function()> _pending = {};
|
||||
final Set<Future<void>> _inFlight = {};
|
||||
Timer? _timer;
|
||||
|
||||
bool get hasPending => _pending.isNotEmpty;
|
||||
@@ -38,20 +39,20 @@ class CoalescedWrites {
|
||||
Future<void> flush() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
if (_pending.isEmpty) return Future<void>.value();
|
||||
final writes = _pending.values.toList();
|
||||
_pending.clear();
|
||||
// Callers fire and forget, so a failed write is logged rather than left
|
||||
// as an unhandled async error, and never stops the other writes.
|
||||
final futures = <Future<void>>[];
|
||||
for (final write in writes) {
|
||||
try {
|
||||
futures.add(write().catchError(_logFailure));
|
||||
final future = write().catchError(_logFailure);
|
||||
_inFlight.add(future);
|
||||
unawaited(future.whenComplete(() => _inFlight.remove(future)));
|
||||
} catch (error) {
|
||||
_logFailure(error);
|
||||
}
|
||||
}
|
||||
return Future.wait(futures).then((_) {});
|
||||
return Future.wait(_inFlight.toList()).then((_) {});
|
||||
}
|
||||
|
||||
static void _logFailure(Object error) {
|
||||
|
||||
Reference in new issue
Block a user