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:
zjs81 committed 2026-11-09 22:32:40 -07:00
1 parent 0106569e7d
commit 2d56d5e349
47 files changed
+4465 -614

No files matched your search

+2 -1
View File
@@ -119,7 +119,8 @@ void main() {
test('the archive follows the channel ID', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _deviceA;
store.setArchived(_idOne, [_ch('old', 1), _ch('older', 2)]);
await store.saveChannelMessages(_idOne, [_ch('old', 1), _ch('older', 2)]);
store.setArchivedCount(_idOne, 2);
expect(store.archivedCount(_idOne), 2);
expect(store.archivedCount(_idTwo), isNull);
+511
View File
@@ -0,0 +1,511 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'dart:typed_data';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/storage/channel_storage_migration.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/backup_service.dart';
import 'package:meshcore_open/review_mode/review_mode_storage.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/models/path_history.dart';
import 'package:meshcore_open/storage/history_store.dart';
import 'package:meshcore_open/storage/legacy_key_migration.dart';
import 'package:meshcore_open/storage/history_store_io.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:shared_preferences_platform_interface/types.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
class _DelayedHistoryStore extends PreferencesHistoryStore {
_DelayedHistoryStore(this.delayedKey, this.gate);
final String delayedKey;
final Completer<void> gate;
@override
Future<String?> getString(String key) async {
if (key == delayedKey) await gate.future;
return super.getString(key);
}
}
class _FailingCleanupPreferences extends InMemorySharedPreferencesStore {
_FailingCleanupPreferences() : super.withData({'flutter.messages_a': '[1]'});
bool fail = true;
@override
Future<bool> clearWithParameters(ClearParameters parameters) async =>
fail ? false : super.clearWithParameters(parameters);
}
class _BackupConnector extends MeshCoreConnector {
_BackupConnector(this.radioKey);
final String radioKey;
@override
bool get isConnected => true;
@override
String get selfPublicKeyHex => radioKey;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late SqliteHistoryStore store;
setUp(() async {
sqfliteFfiInit();
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
store = await SqliteHistoryStore.open(
inMemoryDatabasePath,
factory: databaseFactoryFfiNoIsolate,
);
HistoryStore.use(store);
});
tearDown(() async {
await store.close();
PrefsManager.reset();
});
test('native history writes leave small preferences untouched', () async {
await PrefsManager.instance.setString('theme', 'dark');
await store.setString('messages_a', '[{"text":"hello"}]');
await store.setString('path_history_a', '{"recentPaths":[]}');
expect(PrefsManager.instance.getKeys(), {'theme'});
expect(await store.getString('messages_a'), '[{"text":"hello"}]');
expect(await store.getString('path_history_a'), '{"recentPaths":[]}');
});
test('sequence reads return only the requested ordered page', () async {
await store.setString(
'channel_messages_a',
jsonEncode([
for (var i = 0; i < 1000; i++) {'id': i},
]),
);
expect(await store.entryCount('channel_messages_a'), 1000);
expect(
await store.readEntries('channel_messages_a', offset: 950, limit: 3),
['{"id":950}', '{"id":951}', '{"id":952}'],
);
expect(
await store.readEntries('channel_messages_a', offset: 1000, limit: 3),
isEmpty,
);
expect(await store.readEntries('channel_messages_a', limit: 0), isEmpty);
});
test(
'tail replacement preserves history, deletes and storage limits',
() async {
await store.setString('messages_a', '[0,1,2,3,4]');
expect(
await store.replaceTail('messages_a', 3, ['4', '5'], maxEntries: 4),
2,
);
expect(await store.readEntries('messages_a'), ['1', '2', '4', '5']);
expect(await store.replaceTail('messages_a', 2, ['6'], maxEntries: 4), 2);
expect(await store.readEntries('messages_a'), ['1', '2', '6']);
expect(
await store.replaceTail('messages_a', 50, ['7'], maxEntries: 4),
3,
);
expect(await store.readEntries('messages_a'), ['1', '2', '6', '7']);
expect(await store.replaceTail('messages_a', 0, [], maxEntries: 4), 0);
expect(await store.getString('messages_a'), '[]');
},
);
test('history data survives database reopen', () async {
final dir = await Directory.systemTemp.createTemp('meshcore-history-test-');
addTearDown(() => dir.delete(recursive: true));
final path = '${dir.path}/history_v1.db';
final disk = await SqliteHistoryStore.open(
path,
factory: databaseFactoryFfiNoIsolate,
);
await disk.setString('messages_a', '[1,2,3]');
await disk.setString('path_history_a', '{"sample":true}');
await disk.close();
final reopened = await SqliteHistoryStore.open(
path,
factory: databaseFactoryFfiNoIsolate,
);
addTearDown(reopened.close);
expect(await reopened.getString('messages_a'), '[1,2,3]');
expect(await reopened.getString('path_history_a'), '{"sample":true}');
});
test('versioned import removes only committed valid histories', () async {
final prefs = PrefsManager.instance;
await prefs.setString('messages_a', '[{"text":"hello"},42]');
await prefs.setString('path_history_a', '{"recentPaths":[]}');
await prefs.setString('messages_unreadable', '{broken');
await prefs.setString('path_history_wrong_shape', '[]');
await prefs.setBool('notification', true);
await store.migratePreferences();
expect(prefs.getKeys(), {
'messages_unreadable',
'path_history_wrong_shape',
'notification',
});
expect(await store.readEntries('messages_a'), ['{"text":"hello"}', '42']);
expect(await store.getString('messages_unreadable'), '{broken');
expect(
await store.getKeys(),
containsAll(['messages_a', 'path_history_a', 'messages_unreadable']),
);
final metadata = await store.database.query('history_metadata');
expect(metadata.single['value'], SqliteHistoryStore.schemaVersion);
// Current versions skip another scan/import.
await prefs.setString('messages_added_later', '[1]');
await store.migratePreferences();
expect(prefs.containsKey('messages_added_later'), isTrue);
expect(
await store.database.query(
'history_keys',
where: 'key = ?',
whereArgs: ['messages_added_later'],
),
isEmpty,
);
});
test(
'interrupted import does not replace committed newer database values',
() async {
await store.setString('messages_a', '[2]');
await PrefsManager.instance.setString('messages_a', '[1]');
await store.migratePreferences();
expect(await store.getString('messages_a'), '[2]');
expect(PrefsManager.instance.containsKey('messages_a'), isFalse);
},
);
test('histories saved by a run without the database are merged', () async {
final prefs = PrefsManager.instance;
await store.migratePreferences();
await store.setString(
'messages_a',
'[{"messageId":"1","text":"old"},{"messageId":"2","text":"sent"}]',
);
await store.setString('path_history_a', '{"stored":true}');
// What the fallback run saved: it started from an empty history.
await prefs.setString(
'messages_a',
'[{"messageId":"2","text":"delivered"},{"messageId":"3","text":"new"}]',
);
await prefs.setString('messages_b', '[{"messageId":"4"}]');
await prefs.setString('path_history_a', '{"stored":false}');
await prefs.setString('messages_unreadable', '{broken');
await store.adoptFallbackHistories();
expect(await store.readEntries('messages_a'), [
'{"messageId":"1","text":"old"}',
'{"messageId":"2","text":"delivered"}',
'{"messageId":"3","text":"new"}',
]);
expect(await store.readEntries('messages_b'), ['{"messageId":"4"}']);
expect(await store.getString('path_history_a'), '{"stored":true}');
expect(prefs.getKeys(), {'messages_unreadable'});
});
test('initialize falls back to preferences and flags the run', () async {
// No path provider is registered here, so the database cannot be opened.
await HistoryStore.initialize();
addTearDown(HistoryStore.reset);
expect(HistoryStore.instance, isA<PreferencesHistoryStore>());
expect(PrefsManager.instance.getBool(HistoryStore.fallbackRunKey), isTrue);
});
test('a save lands beside an unreadable preference', () async {
await PrefsManager.instance.setString('messages_a', '{broken');
await store.migratePreferences();
expect(await store.replaceTail('messages_a', 0, ['1', '2']), 0);
expect(await store.readEntries('messages_a'), ['1', '2']);
expect(await store.replaceTail('messages_a', 2, ['3']), 2);
expect(await store.getString('messages_a'), '[1,2,3]');
expect(PrefsManager.instance.getString('messages_a'), '{broken');
});
test('the preferences store replaces an unreadable history', () async {
final prefs = PreferencesHistoryStore();
await PrefsManager.instance.setString('messages_a', '{broken');
expect(await prefs.replaceTail('messages_a', 3, ['1', '2']), 0);
expect(
await prefs.replaceTail('messages_a', 2, ['3', '4'], maxEntries: 3),
1,
);
expect(await prefs.getString('messages_a'), '[2,3,4]');
// A value written behind the store's back is read fresh.
await PrefsManager.instance.setString('messages_a', '[9]');
expect(await prefs.readEntries('messages_a'), ['9']);
expect(await prefs.entryCount('messages_a'), 1);
});
test('future import versions are left untouched', () async {
await store.database.insert('history_metadata', {
'key': 'preferences_import_version',
'value': 99,
});
await PrefsManager.instance.setString('messages_a', '[1]');
await store.migratePreferences();
expect(PrefsManager.instance.containsKey('messages_a'), isTrue);
expect(
(await store.database.query('history_metadata')).single['value'],
99,
);
});
test('review cleanup removes only its database histories', () async {
final prefix = ReviewRadio.storagePrefix;
await store.setString('messages_${prefix}c1', '[1]');
await store.setString('channel_messages_${prefix}_id', '[2]');
await store.setString('messages_real_c1', '[3]');
await clearReviewModeData();
expect(await store.getKeys(), {'messages_real_c1'});
});
test(
'path history scoping and clearing work through database storage',
() async {
final a = StorageService()..setPublicKeyHex = 'aaaaaaaaaaaa';
final b = StorageService()..setPublicKeyHex = 'bbbbbbbbbbbb';
await store.setString(
'path_history_c1',
jsonEncode(
ContactPathHistory(contactPubKeyHex: 'c1', recentPaths: []).toJson(),
),
);
expect(await a.loadPathHistory('c1'), isNotNull);
expect(await b.loadPathHistory('c1'), isNull);
await b.savePathHistory(
'c1',
ContactPathHistory(contactPubKeyHex: 'c1', recentPaths: []),
);
await a.clearAllPathHistories();
expect(await store.getKeys(), {'path_history_bbbbbbbbbb_c1'});
},
);
test(
'backup exports native histories and restores into the destination scope',
() async {
final source = _BackupConnector('a' * 64);
final destination = _BackupConnector('b' * 64);
final settings = AppSettingsService();
addTearDown(source.dispose);
addTearDown(destination.dispose);
addTearDown(settings.dispose);
await store.setString('messages_aaaaaaaaaac1', '[{"text":"original"}]');
await store.setString(
'channel_messages_aaaaaaaaaa_0123456789abcdef',
'[{"text":"channel"}]',
);
const service = BackupService();
final backup = await service.createBackup(
items: {BackupItem.contactHistory, BackupItem.channelHistory},
connector: source,
settings: AppSettings(),
password: '',
);
final decoded = jsonDecode(backup) as Map<String, dynamic>;
final contacts = decoded['sections']['contacts']['preferences'] as Map;
expect(contacts['messages_aaaaaaaaaac1'], [
{'text': 'original'},
]);
await store.setString('messages_bbbbbbbbbbc1', '[{"text":"old"}]');
await service.restoreBackup(
contents: backup,
password: '',
items: {BackupItem.contactHistory, BackupItem.channelHistory},
connector: destination,
appSettingsService: settings,
);
expect(
await store.getString('messages_bbbbbbbbbbc1'),
'[{"text":"original"}]',
);
expect(
await store.getString('channel_messages_bbbbbbbbbb_0123456789abcdef'),
'[{"text":"channel"}]',
);
expect(
await store.getString('messages_aaaaaaaaaac1'),
'[{"text":"original"}]',
);
expect(
PrefsManager.instance.getKeys().where(HistoryStore.isHistoryKey),
isEmpty,
);
},
);
test(
'failed preference cleanup leaves source and import version available for retry',
() async {
SharedPreferences.setMockInitialValues({});
final platform = _FailingCleanupPreferences();
SharedPreferencesStorePlatform.instance = platform;
PrefsManager.reset();
await PrefsManager.initialize();
HistoryStore.use(store);
await expectLater(store.migratePreferences(), throwsStateError);
expect(PrefsManager.instance.getString('messages_a'), '[1]');
expect(await store.getString('messages_a'), '[1]');
expect(await store.database.query('history_metadata'), isEmpty);
platform.fail = false;
await store.migratePreferences();
expect(PrefsManager.instance.containsKey('messages_a'), isFalse);
expect(
(await store.database.query('history_metadata')).single['value'],
1,
);
},
);
test(
'failed database import preserves original preferences and can retry',
() async {
await PrefsManager.instance.setString('messages_a', '[1]');
await PrefsManager.instance.setString('messages_b', '[2]');
await store.database.execute(
"CREATE TRIGGER fail_history BEFORE INSERT ON history_entries WHEN NEW.key = 'messages_b' BEGIN SELECT RAISE(ABORT, 'test failure'); END",
);
await expectLater(
store.migratePreferences(),
throwsA(isA<DatabaseException>()),
);
expect(PrefsManager.instance.getString('messages_a'), '[1]');
expect(PrefsManager.instance.getString('messages_b'), '[2]');
expect(await store.database.query('history_metadata'), isEmpty);
await store.database.execute('DROP TRIGGER fail_history');
await store.migratePreferences();
expect(await store.readEntries('messages_a'), ['1']);
expect(await store.readEntries('messages_b'), ['2']);
expect(PrefsManager.instance.getKeys(), isEmpty);
},
);
test(
'channel migration removes old database keys after committing the new ID',
() async {
const scope = 'aaaaaaaaaa';
final channel = Channel(
index: 0,
name: 'Public',
psk: Uint8List.fromList(List.filled(16, 1)),
);
await (ChannelStore()..setPublicKeyHex = '${scope}xx').saveChannels([
channel,
]);
final oldKey = 'channel_messages_${scope}0';
final newKey = 'channel_messages_${scope}_${channel.storageId}';
await store.setString(oldKey, '[{"messageId":"legacy","text":"keep"}]');
await ChannelStorageMigration.migrate(scope);
expect(await store.getKeys(), {newKey});
expect(
await store.getString(newKey),
'[{"messageId":"legacy","text":"keep"}]',
);
expect(
PrefsManager.instance.getBool('channel_storage_v2_$scope'),
isTrue,
);
},
);
test(
'channel migration leaves malformed sources in place and still completes',
() async {
const scope = 'aaaaaaaaaa';
final psk = Uint8List.fromList(List.filled(16, 1));
final id = Channel.storageIdForPsk(psk)!;
await PrefsManager.instance.setString(
'channels$scope',
jsonEncode([
{
'index': 0,
'name': 'Public',
'psk': base64Encode(psk),
'unreadCount': 0,
},
]),
);
await PrefsManager.instance.setString(
'channel_messages_${scope}0',
'{broken',
);
await store.setString(
'channel_messages_${scope}_$id',
'[{"messageId":"existing","text":"keep"}]',
);
await ChannelStorageMigration.migrate(scope);
expect(
PrefsManager.instance.getString('channel_messages_${scope}0'),
'{broken',
);
expect(
await store.getString('channel_messages_${scope}_$id'),
'[{"messageId":"existing","text":"keep"}]',
);
expect(
PrefsManager.instance.getBool('channel_storage_v2_$scope'),
isTrue,
);
// An array that cannot be merged safely is left alone as well.
await PrefsManager.instance.remove('channel_storage_v2_$scope');
await PrefsManager.instance.setString(
'channel_messages_${scope}0',
'[42]',
);
await ChannelStorageMigration.migrate(scope);
expect(
PrefsManager.instance.getString('channel_messages_${scope}0'),
'[42]',
);
expect(
await store.getString('channel_messages_${scope}_$id'),
'[{"messageId":"existing","text":"keep"}]',
);
expect(
PrefsManager.instance.getBool('channel_storage_v2_$scope'),
isTrue,
);
},
);
test(
'path migration keeps the original scope policy while reading asynchronously',
() async {
final reviewScope = ReviewRadio.storagePrefix;
scopesWithoutLegacyMigration.add(reviewScope);
addTearDown(() => scopesWithoutLegacyMigration.remove(reviewScope));
await PrefsManager.instance.setString(
'path_history_c1',
jsonEncode(
ContactPathHistory(contactPubKeyHex: 'c1', recentPaths: []).toJson(),
),
);
final gate = Completer<void>();
HistoryStore.use(
_DelayedHistoryStore('path_history_${reviewScope}_c1', gate),
);
final service = StorageService()..setPublicKeyHex = '${reviewScope}xx';
final pending = service.loadPathHistory('c1');
service.setPublicKeyHex = 'bbbbbbbbbbbb';
gate.complete();
expect(await pending, isNull);
expect(PrefsManager.instance.containsKey('path_history_c1'), isTrue);
expect(
PrefsManager.instance.containsKey('path_history_${reviewScope}_c1'),
isFalse,
);
},
);
}
@@ -0,0 +1,218 @@
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/storage/channel_storage_migration.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/community_store.dart';
import 'package:meshcore_open/storage/contact_discovery_store.dart';
import 'package:meshcore_open/storage/contact_group_store.dart';
import 'package:meshcore_open/storage/contact_settings_store.dart';
import 'package:meshcore_open/storage/contact_store.dart';
import 'package:meshcore_open/storage/legacy_key_migration.dart';
import 'package:meshcore_open/storage/message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/storage/unread_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
const _device = 'aaaaaaaaaa012345';
const _scope = 'aaaaaaaaaa';
class _RecordingPreferences extends InMemorySharedPreferencesStore {
_RecordingPreferences(Map<String, Object> values)
: super.withData({
for (final e in values.entries) 'flutter.${e.key}': e.value,
});
final calls = <(String, String)>[];
final failedKeys = <String>{};
Completer<void>? writeGate;
@override
Future<bool> setValue(String valueType, String key, Object value) async {
calls.add(('set', key));
if (failedKeys.contains(key)) return false;
await writeGate?.future;
return super.setValue(valueType, key, value);
}
@override
Future<bool> remove(String key) async {
calls.add(('remove', key));
return super.remove(key);
}
}
Future<_RecordingPreferences> _init([
Map<String, Object> values = const {},
]) async {
SharedPreferences.setMockInitialValues({});
final platform = _RecordingPreferences(values);
SharedPreferencesStorePlatform.instance = platform;
PrefsManager.reset();
await PrefsManager.initialize();
return platform;
}
String _cachedChannel(Uint8List psk) => jsonEncode([
{'index': 0, 'name': 'Public', 'psk': base64Encode(psk), 'unreadCount': 0},
]);
void main() {
tearDown(() {
scopesWithoutLegacyMigration.clear();
PrefsManager.reset();
SharedPreferences.setMockInitialValues({});
});
test('loading absent legacy data performs no platform writes', () async {
final platform = await _init();
await (MessageStore()..setPublicKeyHex = _device).loadMessages('c1');
await (ContactSettingsStore()..setPublicKeyHex = _device).loadSmazEnabled(
'c1',
);
await (ContactStore()..setPublicKeyHex = _device).loadContacts();
await (ChannelStore()..setPublicKeyHex = _device).loadChannels();
await (CommunityStore()..setPublicKeyHex = _device).loadCommunities();
await (ContactGroupStore()..setPublicKeyHex = _device).loadGroups();
await (UnreadStore()..setPublicKeyHex = _device).loadContactUnreadCount();
await (ContactDiscoveryStore()..setPublicKeyHex = _device).loadContacts();
expect(platform.calls, isEmpty);
});
test(
'string migration waits for persistence before deleting the source',
() async {
final platform = await _init({'messages_c1': '[]'});
final gate = Completer<void>();
platform.writeGate = gate;
final pending = (MessageStore()..setPublicKeyHex = _device).loadMessages(
'c1',
);
await Future<void>.delayed(Duration.zero);
expect(platform.calls, [('set', 'flutter.messages_${_scope}c1')]);
expect((await platform.getAll())['flutter.messages_c1'], '[]');
gate.complete();
await pending;
expect(platform.calls, [
('set', 'flutter.messages_${_scope}c1'),
('remove', 'flutter.messages_c1'),
]);
await (MessageStore()..setPublicKeyHex = _device).loadMessages('c1');
expect(platform.calls, hasLength(2));
},
);
test('a failed string migration retains persisted legacy data', () async {
final platform = await _init({'messages_c1': '[]'});
platform.failedKeys.add('flutter.messages_${_scope}c1');
await (MessageStore()..setPublicKeyHex = _device).loadMessages('c1');
expect(platform.calls, [('set', 'flutter.messages_${_scope}c1')]);
final persisted = await platform.getAll();
expect(persisted['flutter.messages_c1'], '[]');
expect(persisted, isNot(contains('flutter.messages_${_scope}c1')));
});
test(
'false legacy settings migrate, but stay persisted when writing fails',
() async {
final platform = await _init({'contact_smaz_c1': false});
platform.failedKeys.add('flutter.contact_smaz_${_scope}c1');
expect(
await (ContactSettingsStore()..setPublicKeyHex = _device)
.loadSmazEnabled('c1'),
isFalse,
);
expect(platform.calls, [('set', 'flutter.contact_smaz_${_scope}c1')]);
expect((await platform.getAll())['flutter.contact_smaz_c1'], isFalse);
},
);
test('review scopes never adopt legacy strings or settings', () async {
final platform = await _init({
'messages_c1': '[]',
'contact_smaz_c1': true,
});
scopesWithoutLegacyMigration.add(_scope);
expect(
await (MessageStore()..setPublicKeyHex = _device).loadMessages('c1'),
isEmpty,
);
expect(
await (ContactSettingsStore()..setPublicKeyHex = _device).loadSmazEnabled(
'c1',
),
isFalse,
);
expect(platform.calls, isEmpty);
});
test('channel migration skips removals of absent old keys', () async {
final psk = Uint8List.fromList(List.filled(16, 1));
final platform = await _init({'channels$_scope': _cachedChannel(psk)});
await ChannelStorageMigration.migrate(_scope);
expect(platform.calls.where((c) => c.$1 == 'remove'), isEmpty);
expect(PrefsManager.instance.getBool('channel_storage_v2_$_scope'), isTrue);
});
test(
'channel migration keeps sources and stays unfinished when a write fails',
() async {
final psk = Uint8List.fromList(List.filled(16, 1));
final id = Channel.storageIdForPsk(psk)!;
final sourceKey = 'channel_messages_${_scope}0';
final platform = await _init({
'channels$_scope': _cachedChannel(psk),
sourceKey: '[]',
});
platform.failedKeys.add('flutter.channel_messages_${_scope}_$id');
await expectLater(
ChannelStorageMigration.migrate(_scope),
throwsStateError,
);
expect((await platform.getAll())['flutter.$sourceKey'], '[]');
expect(
PrefsManager.instance.getBool('channel_storage_v2_$_scope'),
isNull,
);
expect(platform.calls.where((c) => c.$1 == 'remove'), isEmpty);
},
);
test(
'false legacy settings migrate successfully without extra writes',
() async {
final platform = await _init({'contact_smaz_c1': false});
final store = ContactSettingsStore()..setPublicKeyHex = _device;
expect(await store.loadSmazEnabled('c1'), isFalse);
expect(await store.loadSmazEnabled('c1'), isFalse);
expect(platform.calls, [
('set', 'flutter.contact_smaz_${_scope}c1'),
('remove', 'flutter.contact_smaz_c1'),
]);
final persisted = await platform.getAll();
expect(persisted['flutter.contact_smaz_${_scope}c1'], isFalse);
expect(persisted, isNot(contains('flutter.contact_smaz_c1')));
},
);
test(
'channel migration is not marked done before its slot map is durable',
() async {
final psk = Uint8List.fromList(List.filled(16, 1));
final platform = await _init({'channels$_scope': _cachedChannel(psk)});
platform.failedKeys.add('flutter.channel_slot_ids_$_scope');
await expectLater(
ChannelStorageMigration.migrate(_scope),
throwsStateError,
);
expect(
PrefsManager.instance.getBool('channel_storage_v2_$_scope'),
isNull,
);
},
);
}
@@ -0,0 +1,285 @@
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/history_store.dart';
import 'package:meshcore_open/storage/message_store.dart';
const _device = 'abcdef012345';
const _contact = 'contact';
const _channel = 'channel';
class _History extends HistoryStore {
final data = <String, List<String>>{};
int reads = 0;
bool failNextWrite = false;
bool failNextRemove = false;
Completer<void>? nextWriteGate;
Completer<void>? nextWriteStarted;
@override
Future<String?> getString(String key) async {
reads++;
final entries = data[key];
return entries == null ? null : '[${entries.join(',')}]';
}
@override
Future<bool> setString(String key, String value) async {
data[key] = (jsonDecode(value) as List).map(jsonEncode).toList();
return true;
}
@override
Future<bool> remove(String key) async {
if (failNextRemove) {
failNextRemove = false;
return false;
}
data.remove(key);
return true;
}
@override
Future<Set<String>> getKeys() async => data.keys.toSet();
@override
Future<int> entryCount(String key) async => data[key]?.length ?? 0;
@override
Future<List<String>> readEntries(
String key, {
int offset = 0,
int? limit,
}) async {
reads++;
final entries = (data[key] ?? []).skip(offset);
return (limit == null ? entries : entries.take(limit)).toList();
}
@override
Future<int> replaceTail(
String key,
int preservedCount,
List<String> entries, {
int maxEntries = 1000,
}) async {
final gate = nextWriteGate;
nextWriteGate = null;
nextWriteStarted?.complete();
nextWriteStarted = null;
await gate?.future;
if (failNextWrite) {
failNextWrite = false;
throw StateError('Disk unavailable');
}
final prefix = (data[key] ?? []).take(preservedCount).toList();
final all = [...prefix, ...entries];
final dropped = (all.length - maxEntries).clamp(0, all.length);
data[key] = all.skip(dropped).toList();
return (prefix.length - dropped).clamp(0, prefix.length);
}
List<String> texts(String key) => [
for (final entry in data[key] ?? [])
(jsonDecode(entry) as Map)['text'] as String,
];
}
Message _dm(int i, {String? id, String? text}) => Message(
senderKey: Uint8List.fromList([1, 2, 3]),
text: text ?? 'm$i',
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
isOutgoing: false,
messageId: id ?? 'id$i',
);
ChannelMessage _ch(int i) => ChannelMessage(
senderKey: null,
senderName: 'Bob',
text: 'c$i',
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: 0,
messageId: 'cid$i',
);
void main() {
late _History history;
late MessageStore direct;
late ChannelMessageStore channel;
late String directKey;
late String channelKey;
setUp(() {
history = _History();
HistoryStore.use(history);
direct = MessageStore()..setPublicKeyHex = _device;
channel = ChannelMessageStore()..setPublicKeyHex = _device;
directKey = '${direct.keyFor}$_contact';
channelKey = '${channel.keyFor}_$_channel';
});
tearDown(HistoryStore.reset);
test(
'reconciled saves preserve prefixes without reading archived JSON',
() async {
await direct.saveMessages(_contact, [for (var i = 0; i < 8; i++) _dm(i)]);
await channel.saveChannelMessages(_channel, [
for (var i = 0; i < 8; i++) _ch(i),
]);
direct.setArchivedCount(_contact, 6);
channel.setArchivedCount(_channel, 6);
history.reads = 0;
await direct.saveMessages(_contact, [_dm(6), _dm(8)]);
await channel.saveChannelMessages(_channel, [_ch(6), _ch(8)]);
expect(history.reads, 0);
expect(history.texts(directKey), [
for (var i = 0; i <= 6; i++) 'm$i',
'm8',
]);
expect(history.texts(channelKey), [
for (var i = 0; i <= 6; i++) 'c$i',
'c8',
]);
},
);
test('overlapping saves consume each unsaved trim once', () async {
direct.setArchivedCount(_contact, 0);
await direct.saveMessages(_contact, [_dm(0), _dm(1), _dm(2)]);
direct.archive(_contact, [_dm(0)]);
final gate = Completer<void>();
final started = Completer<void>();
history.nextWriteGate = gate;
history.nextWriteStarted = started;
final first = direct.saveMessages(_contact, [_dm(1), _dm(2), _dm(3)]);
await started.future;
direct.archive(_contact, [_dm(1)]);
final second = direct.saveMessages(_contact, [_dm(2), _dm(3), _dm(4)]);
gate.complete();
await Future.wait([first, second]);
expect(history.texts(directKey), [for (var i = 0; i <= 4; i++) 'm$i']);
expect(direct.archivedCount(_contact), 2);
});
test('failed writes retain unsaved trims for retry', () async {
direct.setArchivedCount(_contact, 0);
await direct.saveMessages(_contact, [_dm(0), _dm(1)]);
direct.archive(_contact, [_dm(0)]);
history.failNextWrite = true;
await expectLater(
direct.saveMessages(_contact, [_dm(1), _dm(2)]),
throwsStateError,
);
expect(direct.archivedCount(_contact), 1);
expect(history.texts(directKey), ['m0', 'm1']);
await direct.saveMessages(_contact, [_dm(1), _dm(2)]);
expect(history.texts(directKey), ['m0', 'm1', 'm2']);
expect(direct.archivedCount(_contact), 1);
});
test(
'queued snapshots survive scope switches without restoring old bookkeeping',
() async {
direct.setArchivedCount(_contact, 0);
final messages = [_dm(0)];
final gate = Completer<void>();
final started = Completer<void>();
history.nextWriteGate = gate;
history.nextWriteStarted = started;
final pending = direct.saveMessages(_contact, messages);
await started.future;
messages.clear();
direct.forgetArchive();
direct.setPublicKeyHex = '0123456789abcd';
final newKey = '${direct.keyFor}$_contact';
await direct.saveMessages(_contact, [_dm(1)]);
gate.complete();
await pending;
expect(history.texts(directKey), ['m0']);
expect(history.texts(newKey), ['m1']);
direct.setPublicKeyHex = _device;
expect(direct.archivedCount(_contact), isNull);
},
);
test(
'a clear through another instance is ordered after in-flight saves',
() async {
channel.setArchivedCount(_channel, 0);
final gate = Completer<void>();
final started = Completer<void>();
history.nextWriteGate = gate;
history.nextWriteStarted = started;
final save = channel.saveChannelMessages(_channel, [_ch(0)]);
await started.future;
final clear = (ChannelMessageStore()..setPublicKeyHex = _device)
.clearChannelMessages(_channel);
final laterSave = channel.saveChannelMessages(_channel, [_ch(1)]);
gate.complete();
await Future.wait([save, clear, laterSave]);
expect(history.texts(channelKey), ['c1']);
expect(channel.archivedCount(_channel), 0);
},
);
test('cap reductions remain correct across queued saves', () async {
const cap = MessageStore.maxStoredMessages;
await direct.saveMessages(_contact, [for (var i = 0; i < cap; i++) _dm(i)]);
direct.setArchivedCount(_contact, cap - 2);
final first = direct.saveMessages(_contact, [
_dm(cap - 2),
_dm(cap - 1),
_dm(cap),
]);
final second = direct.saveMessages(_contact, [
_dm(cap - 2),
_dm(cap - 1),
_dm(cap),
_dm(cap + 1),
]);
await Future.wait([first, second]);
expect(history.texts(directKey).first, 'm2');
expect(history.texts(directKey).last, 'm${cap + 1}');
expect(history.data[directKey], hasLength(cap));
expect(direct.archivedCount(_contact), cap - 4);
});
test(
'unreconciled merge preserves distinct duplicates without message IDs',
() async {
final duplicate = _dm(0, id: '', text: 'same');
await direct.saveMessages(_contact, [duplicate, duplicate]);
direct.forgetArchive();
await direct.saveMessages(_contact, [duplicate, _dm(1)]);
expect(history.texts(directKey), ['same', 'same', 'm1']);
},
);
test(
'backend replacement cannot reuse another backend archive counts',
() async {
direct.setArchivedCount(_contact, 100);
final replacement = _History();
HistoryStore.use(replacement);
expect(direct.archivedCount(_contact), isNull);
await direct.saveMessages(_contact, [_dm(0)]);
expect(replacement.texts(directKey), ['m0']);
},
);
}
+27 -10
View File
@@ -55,7 +55,7 @@ void main() {
final loaded = await store.loadMessages(_contact);
final window = loaded.sublist(6);
store.setArchived(_contact, loaded.sublist(0, 6));
store.setArchivedCount(_contact, 6);
await store.saveMessages(_contact, [...window, _dm(10)]);
final reloaded = await store.loadMessages(_contact);
@@ -67,7 +67,7 @@ void main() {
test('trimmed messages are archived, deletes stay deleted', () async {
await _init();
final store = _messageStore();
store.setArchived(_contact, const []);
store.setArchivedCount(_contact, 0);
final window = [for (var i = 0; i < 4; i++) _dm(i)];
await store.saveMessages(_contact, window);
@@ -79,9 +79,23 @@ void main() {
final reloaded = await store.loadMessages(_contact);
expect(reloaded.map((m) => m.text), ['m0', 'm1', 'm3', 'm4']);
expect(store.archivedCount(_contact), 2);
});
store.unarchiveNewest(_contact, 1);
expect(store.archivedCount(_contact), 1);
test('an unreadable stored history does not block later saves', () async {
await _init();
final store = _messageStore();
final key = '${store.keyFor}$_contact';
await PrefsManager.instance.setString(key, '{broken');
// Unreconciled: nothing was loaded before the first save.
await store.saveMessages(_contact, [_dm(0)]);
expect((await store.loadMessages(_contact)).map((m) => m.text), ['m0']);
// Reconciled to zero by a load that found nothing readable.
await PrefsManager.instance.setString(key, '{broken');
store.setArchivedCount(_contact, 0);
await store.saveMessages(_contact, [_dm(1)]);
expect((await store.loadMessages(_contact)).map((m) => m.text), ['m1']);
});
test('an unreconciled save merges with what is stored', () async {
@@ -100,8 +114,8 @@ void main() {
test('clearMessages wipes archived history too', () async {
await _init();
final store = _messageStore();
store.setArchived(_contact, [_dm(0), _dm(1)]);
await store.saveMessages(_contact, [_dm(2)]);
await store.saveMessages(_contact, [_dm(0), _dm(1), _dm(2)]);
store.setArchivedCount(_contact, 2);
await store.clearMessages(_contact);
await store.saveMessages(_contact, [_dm(3)]);
@@ -114,7 +128,10 @@ void main() {
await _init();
final store = _messageStore();
const cap = MessageStore.maxStoredMessages;
store.setArchived(_contact, [for (var i = 0; i < cap; i++) _dm(i)]);
await store.saveMessages(_contact, [
for (var i = 0; i < cap; i++) _dm(i),
]);
store.setArchivedCount(_contact, cap);
await store.saveMessages(_contact, [_dm(cap), _dm(cap + 1)]);
final reloaded = await store.loadMessages(_contact);
@@ -184,7 +201,7 @@ void main() {
await store.saveChannelMessages(_channelId, all);
final loaded = await store.loadChannelMessages(_channelId);
store.setArchived(_channelId, loaded.sublist(0, 5));
store.setArchivedCount(_channelId, 5);
await store.saveChannelMessages(_channelId, [
...loaded.sublist(5),
_ch(8),
@@ -197,8 +214,8 @@ void main() {
test('clearing through another instance resets the archive', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
store.setArchived(_channelId, [_ch(0), _ch(1)]);
await store.saveChannelMessages(_channelId, [_ch(2)]);
await store.saveChannelMessages(_channelId, [_ch(0), _ch(1), _ch(2)]);
store.setArchivedCount(_channelId, 2);
await (ChannelMessageStore()..setPublicKeyHex = _device)
.clearChannelMessages(_channelId);