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
@@ -0,0 +1,264 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_repository_io.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_repository_stub.dart'
|
||||
as web;
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
|
||||
void main() {
|
||||
late Directory directory;
|
||||
late SqliteMapTileCacheRepository repository;
|
||||
final factory = databaseFactoryFfiNoIsolate;
|
||||
|
||||
SqliteMapTileCacheRepository createRepository() =>
|
||||
SqliteMapTileCacheRepository(
|
||||
databaseName: 'map_tile_cache',
|
||||
directory: () async => directory,
|
||||
factory: factory,
|
||||
);
|
||||
|
||||
CacheObject tile(String key, {int daysOld = 0, int? id}) => CacheObject(
|
||||
'https://tile.openstreetmap.org/$key.png',
|
||||
key: key,
|
||||
id: id,
|
||||
relativePath: '$key.png',
|
||||
validTill: DateTime(2030),
|
||||
touched: DateTime.now().subtract(Duration(days: daysOld)),
|
||||
length: 123,
|
||||
eTag: 'etag-$key',
|
||||
);
|
||||
|
||||
setUpAll(sqfliteFfiInit);
|
||||
setUp(() async {
|
||||
directory = await Directory.systemTemp.createTemp('meshcore-map-metadata-');
|
||||
repository = createRepository();
|
||||
});
|
||||
tearDown(() async {
|
||||
await repository.close();
|
||||
await directory.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('desktop selects SQLite and web keeps its platform default', () {
|
||||
expect(
|
||||
createMapTileCacheRepository('map_tile_cache'),
|
||||
Platform.isLinux || Platform.isWindows
|
||||
? isA<SqliteMapTileCacheRepository>()
|
||||
: isNot(isA<SqliteMapTileCacheRepository>()),
|
||||
);
|
||||
expect(
|
||||
web.createMapTileCacheRepository('map_tile_cache'),
|
||||
isA<NonStoringObjectProvider>(),
|
||||
);
|
||||
});
|
||||
|
||||
test('metadata survives reopen and supports updates and deletes', () async {
|
||||
await repository.open();
|
||||
final inserted = await repository.insert(tile('a'));
|
||||
expect(inserted.id, isNotNull);
|
||||
expect(inserted.touched, isNotNull);
|
||||
await repository.update(inserted.copyWith(length: 456));
|
||||
expect((await repository.get('a'))!.length, 456);
|
||||
await repository.close();
|
||||
|
||||
repository = createRepository();
|
||||
await repository.open();
|
||||
final restored = (await repository.get('a'))!;
|
||||
expect(restored.relativePath, 'a.png');
|
||||
expect(restored.eTag, 'etag-a');
|
||||
expect(restored.length, 456);
|
||||
expect(await repository.deleteAll([]), 0);
|
||||
expect(await repository.deleteAll([restored.id!, restored.id!]), 1);
|
||||
expect(await repository.get('a'), isNull);
|
||||
});
|
||||
|
||||
test('age and capacity queries select oldest metadata in SQLite', () async {
|
||||
await repository.open();
|
||||
for (var days = 2; days <= 5; days++) {
|
||||
await repository.insert(
|
||||
tile('tile-$days', daysOld: days),
|
||||
setTouchedToNow: false,
|
||||
);
|
||||
}
|
||||
expect(
|
||||
(await repository.getObjectsOverCapacity(2)).map((entry) => entry.key),
|
||||
['tile-4', 'tile-5'],
|
||||
);
|
||||
expect(
|
||||
(await repository.getOldObjects(
|
||||
const Duration(days: 3),
|
||||
)).map((entry) => entry.key),
|
||||
['tile-5', 'tile-4', 'tile-3'],
|
||||
);
|
||||
});
|
||||
|
||||
test('legacy JSON migrates without altering downloaded tile files', () async {
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
final oldTile = tile('10/1/2', daysOld: 2, id: 88);
|
||||
final downloaded = File('${directory.path}/tile-bytes.png');
|
||||
await downloaded.writeAsBytes([1, 2, 3]);
|
||||
await legacy.writeAsString(
|
||||
jsonEncode([oldTile.toMap(setTouchedToNow: false)]),
|
||||
);
|
||||
|
||||
await repository.open();
|
||||
final imported = (await repository.get(oldTile.key))!;
|
||||
expect(imported.url, oldTile.url);
|
||||
expect(imported.relativePath, oldTile.relativePath);
|
||||
expect(
|
||||
imported.touched!.millisecondsSinceEpoch,
|
||||
oldTile.touched!.millisecondsSinceEpoch,
|
||||
);
|
||||
expect(imported.length, oldTile.length);
|
||||
expect(imported.eTag, oldTile.eTag);
|
||||
expect(await downloaded.readAsBytes(), [1, 2, 3]);
|
||||
expect(await legacy.exists(), isFalse);
|
||||
await repository.close();
|
||||
|
||||
// A crash after commit but before cleanup must not replay stale metadata.
|
||||
await legacy.writeAsString(
|
||||
jsonEncode([tile('stale', id: 99).toMap(setTouchedToNow: false)]),
|
||||
);
|
||||
repository = createRepository();
|
||||
await repository.open();
|
||||
expect(await repository.get('stale'), isNull);
|
||||
expect((await repository.getAllObjects()).length, 1);
|
||||
expect(await legacy.exists(), isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'malformed migration imports readable records and sets the file aside',
|
||||
() async {
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
final aside = File('${legacy.path}.unreadable');
|
||||
final content = jsonEncode([
|
||||
{'invalid': true},
|
||||
tile('readable', id: 1).toMap(setTouchedToNow: false),
|
||||
]);
|
||||
await legacy.writeAsString(content);
|
||||
await repository.open();
|
||||
expect((await repository.getAllObjects()).single.key, 'readable');
|
||||
expect(await legacy.exists(), isFalse);
|
||||
expect(await aside.readAsString(), content);
|
||||
await repository.close();
|
||||
|
||||
// The file that was set aside is not imported again.
|
||||
repository = createRepository();
|
||||
await repository.open();
|
||||
expect((await repository.getAllObjects()).length, 1);
|
||||
await repository.close();
|
||||
await repository.deleteDataFile();
|
||||
expect(await aside.exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('a legacy file that is not JSON does not block opening', () async {
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
await legacy.writeAsString('{broken');
|
||||
await repository.open();
|
||||
expect(await repository.getAllObjects(), isEmpty);
|
||||
expect(await legacy.exists(), isFalse);
|
||||
expect(await File('${legacy.path}.unreadable').readAsString(), '{broken');
|
||||
});
|
||||
|
||||
test(
|
||||
'failed SQL import rolls back rows and preserves original JSON',
|
||||
() async {
|
||||
await repository.open();
|
||||
await repository.close();
|
||||
final db = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
);
|
||||
await db.delete('cacheMigration');
|
||||
await db.execute('''
|
||||
CREATE TRIGGER fail_import BEFORE INSERT ON cacheObject
|
||||
WHEN NEW.key = 'bad' BEGIN SELECT RAISE(ABORT, 'test failure'); END
|
||||
''');
|
||||
await db.close();
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
await legacy.writeAsString(
|
||||
jsonEncode([
|
||||
tile('good', id: 1).toMap(setTouchedToNow: false),
|
||||
tile('bad', id: 2).toMap(setTouchedToNow: false),
|
||||
]),
|
||||
);
|
||||
await expectLater(repository.open(), throwsA(isA<DatabaseException>()));
|
||||
expect(await legacy.exists(), isTrue);
|
||||
|
||||
final failed = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
);
|
||||
expect(await failed.query('cacheObject'), isEmpty);
|
||||
expect(await failed.query('cacheMigration'), isEmpty);
|
||||
await failed.execute('DROP TRIGGER fail_import');
|
||||
await failed.close();
|
||||
await repository.open();
|
||||
expect((await repository.getAllObjects()).length, 2);
|
||||
expect(await legacy.exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'newer database versions are rejected without deleting legacy data',
|
||||
() async {
|
||||
final db = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
options: OpenDatabaseOptions(
|
||||
version: SqliteMapTileCacheRepository.schemaVersion + 1,
|
||||
),
|
||||
);
|
||||
await db.close();
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
await legacy.writeAsString('[]');
|
||||
await expectLater(repository.open(), throwsA(isA<DatabaseException>()));
|
||||
expect(await legacy.exists(), isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
test('newer import markers are not overwritten or replayed', () async {
|
||||
await repository.open();
|
||||
await repository.insert(tile('current'));
|
||||
await repository.close();
|
||||
final db = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
);
|
||||
await db.update('cacheMigration', {
|
||||
'version': SqliteMapTileCacheRepository.legacyImportVersion + 1,
|
||||
});
|
||||
await db.close();
|
||||
final legacy = File('${directory.path}/map_tile_cache.json');
|
||||
await legacy.writeAsString(
|
||||
jsonEncode([tile('legacy', id: 1).toMap(setTouchedToNow: false)]),
|
||||
);
|
||||
await repository.open();
|
||||
expect((await repository.getAllObjects()).map((entry) => entry.key), [
|
||||
'current',
|
||||
]);
|
||||
expect(await legacy.exists(), isTrue);
|
||||
await repository.close();
|
||||
final reopened = await factory.openDatabase(
|
||||
'${directory.path}/map_tile_cache.db',
|
||||
);
|
||||
expect(
|
||||
(await reopened.query('cacheMigration')).single['version'],
|
||||
SqliteMapTileCacheRepository.legacyImportVersion + 1,
|
||||
);
|
||||
await reopened.close();
|
||||
});
|
||||
|
||||
test(
|
||||
'inventory connections do not close the cache-manager connection',
|
||||
() async {
|
||||
await repository.open();
|
||||
await repository.open();
|
||||
expect(await repository.close(), isFalse);
|
||||
final inserted = await repository.insert(tile('a'));
|
||||
expect((await repository.get('a'))!.id, inserted.id);
|
||||
expect(await repository.close(), isTrue);
|
||||
await repository.deleteDataFile();
|
||||
expect(await repository.exists(), isFalse);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/path_history.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
|
||||
class _Load {
|
||||
_Load(this.scope, this.contact);
|
||||
final String scope;
|
||||
final String contact;
|
||||
final result = Completer<ContactPathHistory?>();
|
||||
}
|
||||
|
||||
class _Storage extends StorageService {
|
||||
String scope = 'a';
|
||||
bool delayLoads = true;
|
||||
Completer<void>? saveGate;
|
||||
bool failClears = false;
|
||||
final loads = <_Load>[];
|
||||
final saved = <String, ContactPathHistory>{};
|
||||
|
||||
@override
|
||||
set setPublicKeyHex(String value) => scope = value;
|
||||
|
||||
@override
|
||||
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
|
||||
final load = _Load(scope, contactPubKeyHex);
|
||||
loads.add(load);
|
||||
if (delayLoads) return load.result.future;
|
||||
return saved['${load.scope}:$contactPubKeyHex'];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> savePathHistory(
|
||||
String contactPubKeyHex,
|
||||
ContactPathHistory history,
|
||||
) async {
|
||||
final key = '$scope:$contactPubKeyHex';
|
||||
await saveGate?.future;
|
||||
saved[key] = history;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearPathHistory(String contactPubKeyHex) async {
|
||||
if (failClears) throw StateError('clear failed');
|
||||
saved.remove('$scope:$contactPubKeyHex');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearAllPathHistories() async {
|
||||
if (failClears) throw StateError('clear failed');
|
||||
saved.removeWhere((key, value) => key.startsWith('$scope:'));
|
||||
}
|
||||
}
|
||||
|
||||
ContactPathHistory _history(String key, int hop) => ContactPathHistory(
|
||||
contactPubKeyHex: key,
|
||||
recentPaths: [
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 1,
|
||||
timestamp: DateTime(2026),
|
||||
wasFloodDiscovery: true,
|
||||
pathBytes: [hop],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Contact _contact(int hop) => Contact(
|
||||
publicKey: Uint8List(32),
|
||||
name: 'Test',
|
||||
type: 1,
|
||||
pathLength: 1,
|
||||
path: Uint8List.fromList([hop]),
|
||||
lastSeen: DateTime(2026),
|
||||
);
|
||||
|
||||
Future<void> _settle() => Future<void>.delayed(Duration.zero);
|
||||
|
||||
void main() {
|
||||
late _Storage storage;
|
||||
late PathHistoryService service;
|
||||
setUp(() {
|
||||
storage = _Storage();
|
||||
service = PathHistoryService(storage);
|
||||
});
|
||||
tearDown(() => service.dispose());
|
||||
|
||||
test(
|
||||
'an old load cannot populate the next radio or remove its pending load',
|
||||
() async {
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
service.setDevicePublicKey('b');
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
expect(storage.loads.map((load) => load.scope), ['a', 'b']);
|
||||
storage.loads[0].result.complete(_history('contact', 1));
|
||||
await _settle();
|
||||
expect(service.isCached('contact'), isFalse);
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
expect(storage.loads, hasLength(2));
|
||||
storage.loads[1].result.complete(_history('contact', 2));
|
||||
await _settle();
|
||||
expect(service.peekRecentPaths('contact').single.pathBytes, [2]);
|
||||
},
|
||||
);
|
||||
|
||||
test('an old pending path event cannot be added to the next radio', () async {
|
||||
final contact = _contact(1);
|
||||
service.handlePathUpdated(contact);
|
||||
await _settle();
|
||||
service.setDevicePublicKey('b');
|
||||
service.getRecentPaths(contact.publicKeyHex);
|
||||
await _settle();
|
||||
storage.loads[1].result.complete(_history(contact.publicKeyHex, 2));
|
||||
await _settle();
|
||||
storage.loads[0].result.complete(null);
|
||||
await _settle();
|
||||
expect(service.peekRecentPaths(contact.publicKeyHex).single.pathBytes, [2]);
|
||||
});
|
||||
|
||||
test('clearing a contact invalidates an outstanding read', () async {
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
await service.clearPathHistory('contact');
|
||||
storage.loads.single.result.complete(_history('contact', 1));
|
||||
await _settle();
|
||||
expect(service.isCached('contact'), isFalse);
|
||||
});
|
||||
|
||||
for (final dispose in [false, true]) {
|
||||
test(
|
||||
'${dispose ? 'disposing' : 'clearing all'} prevents delayed load notifications',
|
||||
() async {
|
||||
var notifications = 0;
|
||||
service.addListener(() => notifications++);
|
||||
service.getRecentPaths('contact');
|
||||
await _settle();
|
||||
if (dispose) {
|
||||
service.dispose();
|
||||
} else {
|
||||
service.clearAllHistories();
|
||||
}
|
||||
final before = notifications;
|
||||
storage.loads.single.result.complete(_history('contact', 1));
|
||||
await _settle();
|
||||
expect(service.isCached('contact'), isFalse);
|
||||
expect(notifications, before);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test('reads wait for an already-started history save', () async {
|
||||
storage.delayLoads = false;
|
||||
service.handlePathUpdated(_contact(1));
|
||||
await _settle();
|
||||
storage.saveGate = Completer<void>();
|
||||
final save = service.flushPendingWrites();
|
||||
await _settle();
|
||||
final read = service.readStoredPaths('other');
|
||||
await _settle();
|
||||
expect(storage.loads.where((load) => load.contact == 'other'), isEmpty);
|
||||
storage.saveGate!.complete();
|
||||
await save;
|
||||
expect(await read, isEmpty);
|
||||
expect(
|
||||
storage.loads.where((load) => load.contact == 'other'),
|
||||
hasLength(1),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'clearing all waits for in-flight saves before allowing a new read',
|
||||
() async {
|
||||
storage.delayLoads = false;
|
||||
final contact = _contact(1);
|
||||
service.handlePathUpdated(contact);
|
||||
await _settle();
|
||||
storage.saveGate = Completer<void>();
|
||||
final save = service.flushPendingWrites();
|
||||
await _settle();
|
||||
service.clearAllHistories();
|
||||
final read = service.readStoredPaths(contact.publicKeyHex);
|
||||
storage.saveGate!.complete();
|
||||
await save;
|
||||
expect(await read, isEmpty);
|
||||
expect(storage.saved, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test('a scope switch while waiting for saves skips the old read', () async {
|
||||
storage.delayLoads = false;
|
||||
service.handlePathUpdated(_contact(1));
|
||||
await _settle();
|
||||
storage.saveGate = Completer<void>();
|
||||
final save = service.flushPendingWrites();
|
||||
final read = service.readStoredPaths('other');
|
||||
service.setDevicePublicKey('b');
|
||||
storage.saveGate!.complete();
|
||||
await save;
|
||||
expect(await read, isEmpty);
|
||||
expect(storage.loads.where((load) => load.contact == 'other'), isEmpty);
|
||||
expect(storage.saved.keys.single, startsWith('a:'));
|
||||
});
|
||||
|
||||
test(
|
||||
'a failed clear does not break later loads, clears or flushes',
|
||||
() async {
|
||||
storage.delayLoads = false;
|
||||
storage.failClears = true;
|
||||
await expectLater(service.clearPathHistory('contact'), throwsStateError);
|
||||
service.clearAllHistories();
|
||||
await _settle();
|
||||
|
||||
storage.failClears = false;
|
||||
storage.saved['a:contact'] = _history('contact', 3);
|
||||
await service.flushPendingWrites();
|
||||
expect((await service.readStoredPaths('contact')).single.pathBytes, [3]);
|
||||
await service.clearPathHistory('contact');
|
||||
expect(storage.saved, isEmpty);
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user