Batch per-frame persistence so busy meshes don't stall the UI isolate

Every received packet copy re-saved its channel's whole history, every
unread change re-saved the channel list, and adverts/path records re-saved
full contact and path-history blobs. Under load the SharedPreferences
backlog starved the Dart event loop (frames and timers stopped), the radio's
offline queue overflowed, and CPU stayed pinned after traffic ended.

- Add CoalescedWrites: keeps the latest write per key and runs them once
  per window (750 ms; 5 s for path history). Writes start synchronously so
  stores still read the current scoped key.
- Flush before the app is backgrounded, on disconnect, before switching
  radios, before the channel slot map changes, before channel history
  reloads, before deleteChannel drops a list, and before path history
  reloads an evicted contact.
- Cap in-memory channel history at ChannelMessageStore.maxStoredMessages;
  storage already kept only that many, but the list grew unbounded during a
  session and every save grew with it.
- Cache Contact.publicKeyHex and build pubKeyToHex from a hex-digit lookup; it was
  rebuilt on every equality/hash and per-advert contact scan.

Load test (fake TCP radio, 350 contacts, 17 channels, 10-150 packets/s,
Linux profile build): CPU at 10 packets/s 104% -> 45%, recovers to idle
after traffic instead of staying at 160%, and queued messages drained went
from 555 to 3237 over the same run.
This commit is contained in:
zjs81 committed 2026-10-24 23:38:28 -07:00
1 parent eab1ad2964
commit 603172b3ec
10 files changed
+365 -29

No files matched your search

+31 -1
View File
@@ -1,7 +1,10 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/contact.dart';
import '../models/path_history.dart';
import '../models/path_selection.dart';
import '../utils/coalesced_writes.dart';
import 'storage_service.dart';
class PathHistoryService extends ChangeNotifier {
@@ -10,6 +13,10 @@ class PathHistoryService extends ChangeNotifier {
final Map<String, int> _autoRotationIndex = {};
final Map<String, _FloodStats> _floodStats = {};
final Map<String, Future<void>> _pendingLoads = {};
// A path record lands for most received messages, so saves are batched.
final CoalescedWrites _writes = CoalescedWrites(
delay: const Duration(seconds: 5),
);
// LRU cache eviction tracking
static const int _maxCachedContacts = 50;
@@ -23,6 +30,9 @@ class PathHistoryService extends ChangeNotifier {
PathHistoryService(this._storage);
void setDevicePublicKey(String publicKeyHex) {
// Queued saves use the storage key on entry, so they still land under
// the previous radio's key.
unawaited(_writes.flush());
_storage.setPublicKeyHex = publicKeyHex;
_cache.clear();
_cacheAccessOrder.clear();
@@ -361,7 +371,12 @@ class PathHistoryService extends ChangeNotifier {
_cache[contactPubKeyHex] = updatedHistory;
_trackAccess(contactPubKeyHex);
_evictIfNeeded();
_storage.savePathHistory(contactPubKeyHex, updatedHistory);
// The snapshot is written, not the cache entry: the LRU may evict it
// before the batch runs.
_writes.schedule(
contactPubKeyHex,
() => _storage.savePathHistory(contactPubKeyHex, updatedHistory),
);
notifyListeners();
}
@@ -404,6 +419,9 @@ 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);
}
@@ -445,6 +463,7 @@ class PathHistoryService extends ChangeNotifier {
_cacheAccessOrder.remove(contactPubKeyHex);
_autoRotationIndex.remove(contactPubKeyHex);
_floodStats.remove(contactPubKeyHex);
_writes.cancel(contactPubKeyHex);
await _storage.clearPathHistory(contactPubKeyHex);
_version++;
notifyListeners();
@@ -465,6 +484,7 @@ class PathHistoryService extends ChangeNotifier {
recentPaths: updatedPaths,
);
_writes.cancel(contactPubKeyHex);
await _storage.savePathHistory(contactPubKeyHex, _cache[contactPubKeyHex]!);
_version++;
notifyListeners();
@@ -588,11 +608,21 @@ class PathHistoryService extends ChangeNotifier {
}
}
/// Runs queued saves now, e.g. before the app is backgrounded.
Future<void> flushPendingWrites() => _writes.flush();
@override
void dispose() {
unawaited(_writes.flush());
super.dispose();
}
void clearAllHistories() {
_cache.clear();
_cacheAccessOrder.clear();
_autoRotationIndex.clear();
_floodStats.clear();
_writes.dispose();
_storage.clearAllPathHistories();
_version = 0;
notifyListeners();