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
@@ -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) &&
|
||||
|
||||
Reference in new issue
Block a user